3

This was written by Steve Yegge (at least I found it on his blog). It lets you change the name of the currently open file in emacs. Would it be possible to make the current name of the file the default name in the new name dialog? I often have one little typo in the filename and would rather just edit it than writing the entire name over again.

;; Never understood why Emacs doesn't have this function.
(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)
       (rename-file name new-name 1) 
       (rename-buffer new-name)
       (set-visited-file-name new-name)
       (set-buffer-modified-p nil))))))
sds
  • 58,617
  • 29
  • 161
  • 278
  • possible duplicate of [Rename current buffer and related file in Emacs](http://stackoverflow.com/questions/17829619/rename-current-buffer-and-related-file-in-emacs) – phils Apr 14 '14 at 04:04
  • Also see [How do I rename an open file in Emacs?](http://stackoverflow.com/q/384284/324105); and if you want it to be VCS-aware, see [Bozhidar Batsov's answer](http://stackoverflow.com/a/16838442/324105) to that question. – phils Apr 14 '14 at 04:08

2 Answers2

2

You need to use read-from-minibuffer:

(interactive (list (read-from-minibuffer "New name: " (buffer-name))))

I also recommend error instead of message for reporting errors.

PS. If you want completion based on existing files, you might prefer

(interactive (list (read-file-name "New name: " nil nil nil (buffer-name))))

PPS. The reason why this function is not present in the core is that most people prefer to manipulate files from specialized buffers, specifically, dired for "directory editing" and vc-dir for version control, where you can rename files and the corresponding buffers are treated appropriately.

sds
  • 58,617
  • 29
  • 161
  • 278
  • thank you so much! it's amazing what you can do with emacs :) –  Apr 13 '14 at 17:07
  • I think `read-file-name` is more appropriate here than `read-from-minibuffer`. See the duplicate Q&As for examples. – phils Apr 14 '14 at 04:09
1

This robust renaming is already handled by dired.

To facilitate jumping to the current buffer's file directly, add this to your init:

(autoload 'dired-jump "dired-x" nil t)
(define-key ctl-x-map [(control j)] 'dired-jump)

Now C-x C-j R renames the current buffer. You're also on your way to discovering all the other useful things that dired can do.

EDIT: From there M-n fills in the old name.

event_jr
  • 17,467
  • 4
  • 47
  • 62