Applying defadvice to Several Functions at Once

One of the distinguishing—and most useful—features of Lisp is the macro. Sadly, we don’t often see them discussed in the Emacs blogosphere so I was happy to see Bozhidar Batsov over at Emacs Redux give a beautiful example of macro use. The problem he addresses is to save the current buffer whenever you switch to a different window1. You can switch windows in a number of ways, of course, so several functions need to be advised to first save the current buffer.

The result is that six statements of the form

(defadvice switch-to-buffer (before switch-to-buffer-auto-save activate)
  (prelude-auto-save))

are replaced with the single statement

(advise-commands "auto-save"
                 (switch-to-buffer other-window windmove-up windmove-down windmove-left windmove-right)
                 (prelude-auto-save))

using the advise-commands macro that Batsov wrote.

This neatly illustrates one of the main uses of macros: rather than writing almost identical code over and over, you abstract the common code into a macro. Be sure to read Batsov’s post to see the concept in action.

Update: Inserted missing “of.”

Footnotes:

1 It’s another question as to why you’d want to do this. As long-time Irreal readers know I was a Vi(m) user for many years before seeing the light and switching to Emacs. One of the things I really hated was that I couldn’t switch to another file without first saving the current file (I think this was fixed with the Vim multiple window commands). Still, as I’ve said before, Emacs lets you have it your own way.

This entry was posted in Programming and tagged , . Bookmark the permalink.