Thursday, 8 April 2010

Simple File Renaming in Emacs

I stumbled across this tip while browsing reddit/emacs. In summary, it allows for the possibility of having a 'write file' (C-x C-w) variant that deletes the original file, essentially performing a simple rename without having to invoke dired or fire up a shell.

Putting on my Emacs cap, I came up with something similar, shorter and (debatably) more 'emacs-y':

(defadvice write-file (around write-file-possibly-rename activate)
(let ((old-filename (buffer-file-name)))
(and current-prefix-arg
(not (string-equal old-filename (buffer-file-name)))
(delete-file old-filename))))

defadvice allows you to hook a new function up to an existing one, to be invoked either before, after or around it (around advice invokes the original function with its original arguments with ad-do-it, and can do that zero or more times). This form of advice is what hits the spot for this task. Subsequently, when write-file is called, this advice intercepts it, captures the current filename and then invokes the old behaviour. After the write has happened, it checks to see whether or not it should delete the old file, and does so if the preconditions are met.

This preserves the existing C-x C-w behaviour, creating a completely new copy of your file if you choose a different name. Invoked as C-u C-x C-w, however, it deletes the old filename, performing the same rename with less code and less duplication of the existing file-writing plumbing.

No comments:

Post a Comment