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

How do I search for multiple spellings or word endings with a single Vim pattern?

Answer

/colour\%[s]

Explanation

Vim's \%[...] optional atom lets you specify a sequence of characters that are matched as a whole, or not at all. Any prefix of the bracketed string is also valid—making it perfect for handling spelling variants, optional suffixes, and abbreviated words without resorting to \| alternation.

How it works

  • \%[...] matches the enclosed character sequence optionally, accepting any prefix of the content
  • /colour\%[s] matches colour and colours
  • /organiz\%[ation] matches organiz, organiza, organizat, organizati, organizatio, and organization
  • The match is greedy: Vim matches as many characters in \%[...] as possible
  • Unlike \(foo\)\?, this works on a sequence of characters, not just a single atom

Example

/col\%[our]\%[s]

This single pattern matches all of: col, colo, colou, colour, colours—useful when searching a codebase that uses both British and abbreviated spellings.

/func\%[tion]

Matches func and function simultaneously—handy in mixed JavaScript/CoffeeScript files.

Tips

  • Combine with \c for case-insensitive matching: /\ccol\%[our]
  • Use in :s substitutions to normalize spellings: :%s/col\%[our]s\?/color/g
  • Note that \%[...] does not work as an alternation operator—each character inside is optional in sequence from left to right, not a set of alternatives
  • See :help /\%[] for the full specification

Next

How do I scroll the view left and right when lines are wider than the screen?