How do I write a Vim search pattern that matches text at or between mark positions?
Answer
\%'m
Explanation
Vim's \%'m regex atom matches the exact position of mark m in a search pattern. This lets you write searches and substitutions that are anchored to named marks rather than fixed line numbers, which is particularly powerful when combined with visual-mode marks '< and '> or manually set marks.
How it works
\%'a— matches the position of marka(zero-width assertion)\%'<— matches the start of the last visual selection\%'>— matches the end of the last visual selection- These atoms do not consume characters; they assert a position, just like
^or$
Example
Suppose you set mark a at a specific position with ma, then mark b further down with mb. You can substitute only within that span:
:'a,'bs/old/new/g
But with \%'m in the pattern itself, you can do more targeted matches. For instance, highlight text from mark a to mark b on a single line:
/\%'afoo.*\%'b
Or use a substitution that only touches text between the two marks:
:%s/\%'a\_.*\%'b/replacement/
Tips
- Combine
\%'<and\%'>with\%V(in-visual-selection atom) for different scoping strategies \%'monly works when the mark is set in the current buffer- The backtick form
`mjumps to markmprecisely;\%'mmirrors that precision in patterns - Useful for scripted substitutions where a range command is insufficient because you need pattern matching across the boundary