Dynamic Abbreviation in Emacs

January 29, 2009

Dynamic abbreviation, available by calling dabbrev-expand or pressing M-/, is a generalization of the standard abbreviation system in Emacs and is one of it’s most productivity-enhancing features. Regular abbreviations, or abbrevs, are shortcuts for words and blocks of text that you type frequently. For example, if you write a lot of C programs with similar comment blocks at the top of the file you could define an abbreviation, say “chead”. Typing “chead” would then automatically insert the desired header. Abbrevs can also be used as a method of auto-correction for misspelled words: just set “recieve” as an abbrev for “receive”. Some modes also define a few abbrevs for you automatically. For example, AUCTeX has a LaTeX-Math minor mode (C-c ~ or LaTeX-math-mode) that defines shortcuts for many common mathematical symbols and Greek letters.

Dynamic abbreviations are different in that you do not have to define them explicitly and you must call dabbrev-expand to use them. dabbrev-expand is essentially a form of completion where you first type a couple of letters of a word and press M-/. Emacs tries to complete the word by first looking at all the words in the current buffer, then in all other open buffers. Pressing M-/ multiple times will cycle through all possible completions.

First and foremost, dabbrev-expand is useful for typing long or difficult words that appear many times in a single document. For example, I’m typing da M-/ instead of dabbrev-expand as I write this. You might need to refer several times to an author with a name that’s difficult to remember or spell. After you type it once, you can begin using M-/ to complete it after the first few letters. In a programming context, you might need to call a function with a long name that’s defined or used elsewhere in the file.

More advanced usage of dabbrev-expand involves completion of symbols from other buffers. For example, I use BibTeX to manage my references. All of the books and articles that I might need to cite in my research are stored in a single BibTeX database which I usually have open in Emacs while I’m writing a paper. When I need to cite a paper a the LaTeX document I’m writing, I simply type \cite{ and the first few letters of the corresponding BibTeX key–in my case this starts with the first author’s surname–and press M-/. If I’ve cited the paper before it’s key is completed from the current buffer. Otherwise, Emacs looks at the other open buffers, namely my BibTeX database.

Although I’ve only covered a couple of cases, they are suggestive of other situations where dabbrev-expand might be helpful. There are many more productive uses for this hidden Emacs gem. See EmacsWiki:DynamicAbbreviations for more discussion, some useful bindings, and a few enhancements.