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

How do I write a Vim search pattern that matches any character including newlines for multi-line searches?

Answer

\_.{-}

Explanation

The \_ modifier in Vim extends any character class or atom to also match newlines. The most common use is \_. — any character including newline — which enables powerful multi-line search and substitution patterns.

How it works

In Vim, the ordinary . atom matches any character except newline. Prefixing \_ enables newline matching:

  • \_. — any character including newline
  • \_s — whitespace including newlines
  • \_a — letters including newlines

For multi-line matches, pair with a quantifier:

  • \_.{-} — zero or more chars, non-greedy (recommended)
  • \_.+ — one or more chars, greedy

The \{-} (non-greedy) quantifier is almost always preferable over * here, to avoid matching too broadly.

Example

Given this text:

func(
  arg1,
  arg2
)

The search /func(\_.{-}) matches the entire multi-line call including the parentheses and content across line breaks. Use with substitution:

:%s/func(\_.{-})/func(REPLACED)/

Tips

  • Always prefer \_.{-} (non-greedy) over \_.* (greedy) to prevent overly wide matches that consume far more than intended
  • The \_ prefix works with many atoms: \_d (digits + newline), \_u (uppercase + newline)
  • Combine with \zs and \ze to precisely delimit the matched portion of a multi-line pattern
  • Use :set incsearch to see matches update as you type, making multi-line patterns easier to refine

Next

How do I encode and decode JSON data in Vimscript for configuration and plugin development?