How do I search for a pattern that spans multiple lines in Vim?
Answer
\_.pattern
Explanation
Vim's regex engine normally treats . as matching any character except a newline. By prefixing a character class with \_, you tell Vim to include newlines in the match. The most common form is \_. — which matches any single character including a newline — letting you build patterns that cross line boundaries.
How it works
.in Vim regex: matches any character except\n\_.: matches any character including\n\_s: matches any whitespace including newlines (equivalent to[ \t\n])\_[ ]: matches any character in the set, plus newlines
You can combine \_ with other atoms:
/start\_.\{-}end— non-greedy match fromstarttoendacross lines/foo\_sbar— matchesfooandbarseparated by any whitespace or newline
Example
Given a buffer:
error: disk
full
The pattern /error:\_.*full matches across the newline, finding the whole span from error: to full. Without \_, the . would stop at the end of the first line and the pattern would not match.
Tips
- Use
\{-}(non-greedy) with\_.to avoid accidentally consuming too much:/start\_.\{-}end - Pair with
:s/start\_.\{-}end/replacement/to collapse multi-line constructs into a single replacement \_^and\_$match start/end of line anywhere in the pattern, not just at the edges- Check
:help /\_for the full list of multi-line atoms