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

How do I use a Vimscript expression to compute the replacement text in a substitution?

Answer

:s/pattern/\=expr/

Explanation

Prefixing the replacement field of :s with \= makes Vim evaluate the rest as a Vimscript expression and use the result as the replacement string. This turns every substitution into a mini-program: you can call built-in functions, apply arithmetic, access captured groups via submatch(), and compose complex transformations that are impossible with static replacement text.

How it works

  • \= at the start of the replacement means "this is an expression, not a literal string"
  • submatch(0) — the entire match; submatch(1) — the first capture group \(\), and so on
  • The return value of the expression becomes the replacement text

Example

Convert every hex colour code in a CSS file to uppercase:

:%s/#\([0-9a-fA-F]\{6\}\)/\='#' . toupper(submatch(1))/g

Before:

color: #ff6600;
background: #abc123;

After:

color: #FF6600;
background: #ABC123;

Or increment every integer on a line by 1:

:%s/\d\+/\=submatch(0)+1/g

Tips

  • Chain functions: \=strpart(submatch(0), 0, 3) to truncate each match to 3 characters
  • Use printf() for formatted output: \=printf('%04d', submatch(0)) to zero-pad numbers
  • Call system() to invoke external tools per match (use sparingly; it is slow)
  • Works in any range: :'<,'>s/pattern/\=expr/ applies only to the visual selection

Next

How do I split a complex Vim macro into reusable subroutines?