How do I rename an open file in Emacs?

后端 未结 11 1786
别跟我提以往
别跟我提以往 2020-12-07 07:03

Is there a way to rename an open file in Emacs? While I\'m viewing it? Something like save-as, but the original one should go away.

相关标签:
11条回答
  • 2020-12-07 07:34

    Try this function from Steve Yegge's .emacs:

    ;; source: http://steve.yegge.googlepages.com/my-dot-emacs-file
    (defun rename-file-and-buffer (new-name)
      "Renames both current buffer and file it's visiting to NEW-NAME."
      (interactive "sNew name: ")
      (let ((name (buffer-name))
            (filename (buffer-file-name)))
        (if (not filename)
            (message "Buffer '%s' is not visiting a file!" name)
          (if (get-buffer new-name)
              (message "A buffer named '%s' already exists!" new-name)
            (progn
              (rename-file filename new-name 1)
              (rename-buffer new-name)
              (set-visited-file-name new-name)
              (set-buffer-modified-p nil))))))
    

    Take a look at that page, there's another really useful related function there, called "move-buffer-file".

    0 讨论(0)
  • 2020-12-07 07:36

    There is a way very easy, you press the command M-x and than type vc-rename-file, after that you just need to select your current file at the directory, and than choose the new name. The buff that has the changed file will be refreshed.

    Source:https://www.gnu.org/software/emacs/manual/html_node/emacs/VC-Delete_002fRename.html

    0 讨论(0)
  • 2020-12-07 07:39

    Here's another version, that's pretty robust and VC aware:

    (defun rename-file-and-buffer ()
      "Rename the current buffer and file it is visiting."
      (interactive)
      (let ((filename (buffer-file-name)))
        (if (not (and filename (file-exists-p filename)))
            (message "Buffer is not visiting a file!")
          (let ((new-name (read-file-name "New name: " filename)))
            (cond
             ((vc-backend filename) (vc-rename-file filename new-name))
             (t
              (rename-file filename new-name t)
              (set-visited-file-name new-name t t)))))))
    

    You can read more about it here.

    0 讨论(0)
  • 2020-12-07 07:41

    Yes, with dired mode, you can:

    • C-x d to open dired
    • RET to select directory of current file
    • C-x C-j (dired-jump to the name of the current file, in Dired)
    • R to rename the file (or dired-do-rename).
    • q to go back to the (renamed) file buffer

    The rename is equivalent to a shell mv, but it will also update any open buffers, and unlike mv it will not change the access and modify times on the file in the filesystem.

    0 讨论(0)
  • 2020-12-07 07:41

    It can be achieved by copy. shift+c on the file and emacs will ask you to denote a name for the path including the file name, so you just provide the new name,and enter...of course, you have to Delete the former one.

    0 讨论(0)
提交回复
热议问题