有没有办法在Emacs中重命名打开的文件?在我看的时候?类似于另存为,但原始文件应该删除。


当前回答

为了完整起见,由于有些人访问此页面时可能认为他们将得到Emacs的“另存为”特性的答案,对于打开的文件,这是C-x C-w。

其他回答

优秀的crux包具有crux-rename-file-and-buffer(以及许多其他有用的函数)。

它可以通过复制来实现。在文件上按Shift +c, emacs将要求您为路径指定一个名称,其中包括文件名,因此只需提供新名称,然后输入…当然,你必须删除前一个。

下面是一个改编自史蒂夫的更健壮的版本。

;; Originally from stevey, adapted to support moving to a new directory.
(defun rename-file-and-buffer (new-name)
  "Renames both current buffer and file it's visiting to NEW-NAME."
  (interactive
   (progn
     (if (not (buffer-file-name))
         (error "Buffer '%s' is not visiting a file!" (buffer-name)))
     ;; Disable ido auto merge since it too frequently jumps back to the original
     ;; file name if you pause while typing. Reenable with C-z C-z in the prompt.
     (let ((ido-auto-merge-work-directories-length -1))
       (list (read-file-name (format "Rename %s to: " (file-name-nondirectory
                                                       (buffer-file-name))))))))
  (if (equal new-name "")
      (error "Aborted rename"))
  (setq new-name (if (file-directory-p new-name)
                     (expand-file-name (file-name-nondirectory
                                        (buffer-file-name))
                                       new-name)
                   (expand-file-name new-name)))
  ;; Only rename if the file was saved before. Update the
  ;; buffer name and visited file in all cases.
  (if (file-exists-p (buffer-file-name))
      (rename-file (buffer-file-name) new-name 1))
  (let ((was-modified (buffer-modified-p)))
    ;; This also renames the buffer, and works with uniquify
    (set-visited-file-name new-name)
    (if was-modified
        (save-buffer)
      ;; Clear buffer-modified flag caused by set-visited-file-name
      (set-buffer-modified-p nil)))

  (setq default-directory (file-name-directory new-name))

  (message "Renamed to %s." new-name))

是的,使用dired模式,你可以:

c - xd打开干燥 RET选择当前文件的目录 C-x C-j (Dired -跳转到当前文件的名称,在Dired中) R来重命名文件(或dired-do-rename)。 Q返回(重命名的)文件缓冲区

重命名相当于shell mv,但它也会更新任何打开的缓冲区,与mv不同的是,它不会改变文件系统中文件的访问和修改时间。

如果您正在使用Spacemacs,那么您可以免费获得这种行为,因为它附带了一个重命名-current-buffer-file的实现(基于magnars),默认情况下绑定到src -f- r。

https://github.com/syl20bnr/spacemacs/blob/bd7ef98e4c35fd87538dd2a81356cc83f5fd02f3/layers/%2Bdistributions/spacemacs-base/funcs.el#L294