i am daniel gempesaw

i like ultimate, bikes, snowboarding, music, math, weight lifting, anime, and karen

Emacs multiple file find and replace from dired-mode

I’m trying to start using dired-mode in Emacs more, because it’s really quite handy. I’m decent at bash, I can accomplish some things from there, but there’s a lot of commands I don’t know about (cut?) and I’m pretty bad at remembering syntax. dired-mode to the rescue :D

I had to recursively find and replace in a pretty large directory today, replacing a string literal as a variable. Multiple instances per file, multiple files per directory, a few directories, etc. Luckily, it’s really quite simple, as stackoverflow explains. Start up find-name-dired and choose the parent directory and pick the files you want. t toggles the entire directory as marked, and Q will start a query-replace-regex for the marked files, which is now everything.

Business as usual (input search term RET input replacement RET) and then Emacs goes through and opens each file, highlighting the instances and pausing for your input. ! gets you to the end of the file, replacing all instances, and stops again for the next file. Y replaces all instances without asking, which is my favorite.

Emacs opens each file in a separate buffer, editing them, and then moving on to the next file, but it doesn’t save the file before going on to the next one. But, lucky me, I have a before buffer-change hook that tries to save the open buffer before going on, so in my particular case, all the buffers end up being saved automagically :D

;; automatically save buffers associated with files on buffer switch
;; and on windows switch
(defadvice switch-to-buffer (before save-buffer-now activate)
  (when buffer-file-name (save-buffer)))
(defadvice other-window (before other-window-now activate)
  (when buffer-file-name (save-buffer)))

nifty! and to top it all off, this was all done on a remote box via tramp. go team.