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

How do I use a Vim expression to dynamically compute substitution replacement text?

Answer

:s/pattern/\=expression/

Explanation

The \= prefix in the replacement field of :s/// tells Vim to evaluate the right-hand side as a Vim script expression and use the result as the replacement text. This unlocks dynamic substitutions that go beyond simple string replacement — you can perform arithmetic, call functions, or transform matches programmatically.

How it works

  • \= signals that the replacement is a Vim expression, not a literal string
  • submatch(0) — returns the full matched text as a string
  • submatch(1), submatch(2), etc. — return text captured by parenthesised groups
  • The expression result is converted to a string and substituted in place of each match

Example

Double every number in a line:

items: 10, price: 5

Run :s/\d\+/\=submatch(0)*2/g:

items: 20, price: 10

Vim matches each sequence of digits, evaluates submatch(0)*2 as an integer expression, and replaces the match with the result.

Tips

  • Use str2nr(submatch(0)) for explicit string-to-number conversion on ambiguous inputs
  • toupper(submatch(0)) and tolower(submatch(0)) transform case via expression
  • Combine with :g/pattern/ to target only specific lines first, then substitute within them
  • The global flag /g applies the expression to every match on the line, re-evaluating for each
  • Try :s/\(\w\+\)/\=len(submatch(1))/g to replace each word with its character count

Next

How do I programmatically set a register's content in Vimscript to pre-load a macro?