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

How do I search for a pattern that spans multiple lines in Vim?

Answer

/pattern\_s\+next

Explanation

Vim's regular expressions support multi-line matching through underscore-prefixed atoms. The \_ prefix modifies character classes to include newlines, enabling searches that cross line boundaries. This is essential for finding patterns split across lines.

How it works

  • \_s — matches any whitespace character INCLUDING newline
  • \_^ — matches the start of a line (anywhere in pattern)
  • \_. — matches any character INCLUDING newline
  • \_[] — character class that includes newline

Example

Find return followed by a value on the next line:

/return\_s\+\w\+
Before:
return
  value

The pattern matches across the line break, highlighting 'return\n  value'

Tips

  • \_.* matches everything including newlines (like [\s\S]* in other regex)
  • Useful with :s for multi-line substitutions: :%s/foo\_s\+bar/combined/g
  • Be careful with \_.\+ as it can match very large spans — use \_.\{-} for non-greedy

Next

How do I return to normal mode from absolutely any mode in Vim?