How do I execute a command without changing '[ and '] marks in Vim?
Answer
:keepmarks {command}
Explanation
Many batch edits in Vim update special marks like '[ and '], which can disrupt follow-up motions or tooling that depends on those positions. The :keepmarks modifier lets you run an Ex command while preserving the current mark state. This is especially valuable in advanced editing pipelines where marks are part of your navigation workflow.
How it works
:keepmarksis a command modifier placed before another Ex command{command}is any Ex command you want to run (substitute, global, normal, etc.)- Vim executes the command but does not update marks that would normally be changed by that edit
This helps keep positional context stable during scripted transformations, so your next operation can still rely on previous marks.
Example
Without :keepmarks, running a wide edit changes special marks to the most recent affected text:
:%s/foo/bar/g
With :keepmarks, the same edit preserves prior mark context:
:keepmarks %s/foo/bar/g
In refactor sessions, this means you can apply broad edits while still jumping back to previously meaningful positions.
Tips
- Combine with
:keeppatternswhen you also want to preserve the search register - Useful in mappings/functions that chain multiple Ex commands
- Works well with mark-driven navigation habits in large files