C-x C-w) variant that deletes the original file, essentially performing a simple rename without having to invoke
diredor 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)))
(not (string-equal old-filename (buffer-file-name)))
defadviceallows 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-fileis 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-wbehaviour, 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.