How do I run a substitute or filter command without Vim automatically repositioning my marks?
Answer
:keepmarks
Explanation
When Vim executes commands that move or reorder lines — such as :sort, :%!sort, or :s/// across ranges — it automatically adjusts named marks to follow the text. Sometimes you want marks to stay exactly where they are even after the buffer changes. The :keepmarks modifier tells Vim not to reposition marks during the subsequent command.
How it works
- Prefix any Ex command with
:keepmarksto prevent marks from being moved - Specifically, it suppresses adjustments to the visual selection marks
'<and'>, the change marks'[and'], and other auto-set marks - The marks you set manually (
'a,'b, etc.) are also preserved - Without
:keepmarks, a:sortor filter command would move'<and'>to the new positions of the sorted lines
Example
" Select lines 5-20 in visual mode, exit visual, then sort without moving marks
:keepmarks 5,20!sort
After this command, '< still points to line 5 and '> to line 20, even though the lines were reordered by sort.
Tips
- Combine with
:keepjumpsto also preserve the jump list::keepjumps keepmarks %s/old/new/g - Especially useful in Vimscript functions that manipulate buffers and need stable mark positions for subsequent operations
:lockmarksis a related but different modifier — it prevents marks from being updated at all, even from their normal adjustments during insertions