Advised Buffer Switching
Let's conclude this chapter with an example that introduces a very useful Lisp tool called advice.
It frequently happens that I'm editing many similarly named files at the same time; for instance, foobar.c and foobar.h. When I want to switch from one buffer to the other, I use C-x b, switch-to-buffer, which prompts me for a buffer name. Since I like to keep my keystrokes to a minimum, I depend on TAB completion of the buffer name. I'll type
C-x b fo TAB
expecting that the TAB will complete "fo" to "foobar.c", then I'll press RET to accept the completed input. Ninety percent of the time, this works great. Other times, such as in this example, pressing fo TAB will only expand as far as "foobar.", requiring me to disambiguate between "foobar.c" and "foobar.h". Out of habit, though, I often press RET and accept the buffer name "foobar.".
At this point, Emacs creates a brand-new empty buffer named foobar., which of course isn't what I wanted at all. Now I've got to kill the brand-new buffer (with C-x k, kill-buffer) and start all over again. Though I do occasionally need the ability to switch to a nonexistent buffer, that need is very rare compared with the number of times I commit this error. What I'd like is for Emacs to catch my error before letting me commit it, by only accepting the names of existing buffers when it prompts me for one.
To achieve this, we'll use advice. A piece of advice attached to a Lisp function is code that gets executed before or after the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access