Rename the current buffer and the corresponding file in Emacs

I want to rename the file associated with the current buffer in Emacs.

I found the following elisp from this article: How to rename an open file in 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 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 name new-name 1) (rename-buffer new-name) (set-visited-file-name new-name) (set-buffer-modified-p nil)))))) 

It works fine, but if possible I want to set the current file name as the default. How to write it?

+4
source share
3 answers

Recently there was a post on the Emacs Redux blog on this topic.

It is mainly implemented in Prelude (the same author), which you can install to get this behavior and many other interesting things. Otherwise, you can put in your configuration file only the corresponding fragment (taken from the blog post above):

 (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 tt))))))) (global-set-key (kbd "Cc r") 'rename-file-and-buffer) 
+3
source

Could you tell us more about why you need this? What are the conditions? Because it has never occurred since I started using Emacs.

But here is what I do sometimes when I want to rename something:

  • Say I'm editing spam-spom-spam.cc. And I want to fix that name.
  • Cx d
  • Cs spo
  • Cx cq
  • DEL a
  • Cc cc

It may seem like a lot of teams, but they flow quite naturally. As a bonus, you will get an overview of your directory and the recently renamed file looks there.

+3
source

This does not require an external tool. Cm

http://www.gnu.org/software/emacs/manual/html_node/emacs/Wdired.html

After changing the file name in the dired buffer, the buffer name also changes.

+2
source

Source: https://habr.com/ru/post/1493148/


All Articles