I want to rename a file that is bound current buffer in Emacs.
I found following elisp from this article: How do I 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'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 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 current file name as a default value. How would I write this?
There recently was a post on the Emacs Redux blog on this subject.
Basically it is implemented in the Prelude configuration (by the same author) which you can install to get this behaviour and tons of other interesting stuff. Otherwise, you can put in your configuration file only the relevant snippet (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 t t)))))))
(global-set-key (kbd "C-c r") 'rename-file-and-buffer)
Could you elaborate more on why you need to do it? What are the conditions? Because this has never come up since I started using Emacs.
But here's what I do sometimes when I want to rename something:
This may seem like a lot of commands, but they flow quite naturally. As a bonus, you get an overview of your directory and of how the newly renamed file looks there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With