How do I create an insert-mode abbreviation that expands a short sequence into longer text?
Answer
:iabbrev {lhs} {rhs}
Explanation
The :iabbrev command defines insert-mode abbreviations — short character sequences that automatically expand into longer text when you type a non-keyword character (space, newline, punctuation) immediately after them. This is one of Vim's most underused features for reducing repetitive typing and fixing common typos on the fly.
How it works
:iabbrevregisters an abbreviation active only in Insert mode (unlike:abbreviate, which also applies to Command mode)- When the {lhs} is followed by a non-keyword character, Vim replaces the typed text with {rhs}
- The trigger character is kept, so typing
tehreplacestehwiththeand leaves the space in place - Put abbreviations in your
vimrcfor permanent effect
Example
" Fix common typos
:iabbrev teh the
:iabbrev adn and
:iabbrev dont don't
" Expand code snippets
:iabbrev ifmain if __name__ == '__main__':
:iabbrev pdb import pdb; pdb.set_trace()
In a Python file, typing ifmain<CR> inserts:
if __name__ == '__main__':
Tips
- Use
:iabclearto remove all insert abbreviations, or:iunabbrev {lhs}to remove a specific one - View all active abbreviations with
:iabbrev(no arguments) - For multi-line expansions, use
<CR>in the rhs::iabbrev lorem Lorem ipsum dolor<CR>sit amet - Abbreviations with the same lhs as a word in your text won't expand unless the lhs appears as a standalone sequence
- Use
:iabbrev <expr> {lhs} {expr}for dynamic expansions like inserting the current date