Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename current buffer and related file in Emacs

Tags:

emacs

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?

like image 821
ironsand Avatar asked Jul 24 '13 09:07

ironsand


2 Answers

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)
like image 97
François Févotte Avatar answered Oct 28 '22 17:10

François Févotte


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:

  1. Say I'm editing spam-spom-spam.cc. And I want to fix the name.
  2. C-x d
  3. C-s spo
  4. C-x C-q
  5. DEL a
  6. C-c C-c

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.

like image 33
abo-abo Avatar answered Oct 28 '22 18:10

abo-abo