Skip to content

Instantly share code, notes, and snippets.

@pkkm
Created August 29, 2013 11:41
Show Gist options
  • Save pkkm/6377017 to your computer and use it in GitHub Desktop.
Save pkkm/6377017 to your computer and use it in GitHub Desktop.
Rename the current file and buffer.
(defun rename-this-buffer-and-file ()
"Renames the current buffer and the file it is visiting (after saving it)."
(interactive)
(save-buffer)
(let ((filename (buffer-file-name)))
(unless filename
(error "Not visiting a file"))
(unless (file-exists-p filename)
(error "File \"%s\" doesn't exist" filename))
(let ((new-name
(read-file-name "New name: "
(file-name-directory filename)
nil nil
(file-name-nondirectory filename))))
(when (or (file-exists-p new-name)
(file-symlink-p new-name))
(error "File \"%s\" already exists" new-name))
(rename-file filename new-name)
(rename-buffer new-name t) ; t -- if the name is taken, pick an unique one.
(set-visited-file-name new-name)))
(set-buffer-modified-p nil))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment