vimtricks.wiki Concise Vim tricks, one at a time.

How do I create text shortcuts that auto-expand while typing in Vim?

Answer

iabbrev

Explanation

:iabbrev defines insert-mode abbreviations that expand automatically when you type a non-keyword character (space, punctuation, <CR>) after the abbreviation. This is Vim's built-in snippet mechanism — no plugin required — and it's useful for fixing habitual typos, expanding personal shortcodes, or reducing boilerplate.

How it works

  • :iabbrev {lhs} {rhs} registers the abbreviation
  • While typing in insert mode, Vim watches for {lhs} followed by a non-word character (the trigger)
  • When triggered, Vim silently replaces {lhs} with {rhs} and then inserts the trigger character
  • Only full words are matched — typing email won't trigger an abbreviation for em

Example

Define a typo correction in your vimrc:

iabbrev teh the
iabbrev recieve receive

Define a personal shortcode:

iabbrev @em finn@example.com

After :iabbrev @em [email protected], typing @em in insert mode produces:

[email protected] 

Tips

  • Press <C-]> in insert mode to force-expand an abbreviation without inserting a trigger character — useful at the end of a line
  • Use <C-v>{trigger} to insert the trigger character literally and prevent expansion
  • :iabbrev to list all active insert abbreviations; :iunabbrev {lhs} to remove one
  • For dynamic expansions (e.g., inserting today's date), use <expr>: iabbrev <expr> dts strftime('%Y-%m-%d')
  • :abbreviate defines abbreviations for both insert and command modes; :cabbrev for command mode only

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?