How do I target a substitution at the cursor position using \%#?
Answer
:s/\%#\k\+/REPL/
Explanation
Most substitutions operate on broad ranges, but sometimes you want a precise edit anchored to where your cursor is right now. Vim's \%# atom matches the current cursor position inside a pattern, so you can build a targeted :s command that edits only the token at that location. This is useful in scripts, mappings, and repeatable refactors where motion-based text objects are awkward.
How it works
:s/.../.../runs substitute on the current line\%#is a zero-width atom that matches exactly at the cursor position\k\+matches one or more keyword characters (the rest of the word)- Combined as
\%#\k\+, Vim replaces the keyword starting at your cursor
Example
Given the line with cursor at the start of alpha:
alpha beta gamma
Run:
:s/\%#\k\+/REPL/
Result:
REPL beta gamma
Tips
- Use different character classes if your tokens include punctuation
- Pair with
:keeppatternswhen you do not want to overwrite/history - This pattern is great inside custom commands that depend on current cursor context