vimtricks.wiki Concise Vim tricks, one at a time.

How do I run commands without disturbing my marks?

Answer

:lockmarks

Explanation

Many Ex commands silently adjust or delete marks as a side effect of modifying buffer content. If you have carefully placed marks throughout a file and need to run a bulk operation (like a global substitution or a filter command), :lockmarks prevents those marks from being moved or destroyed.

How it works

  • :lockmarks {command} executes {command} while keeping all marks (a-z, A-Z, and numbered marks) at their current positions
  • Without :lockmarks, inserting or deleting lines shifts marks below the change, and marks on deleted lines are lost
  • The marks stay pinned to their original line numbers regardless of what the command does to surrounding text

Example

Suppose you have marks a, b, and c set on lines 10, 50, and 100. You want to delete all blank lines:

" Without lockmarks — marks shift as lines are removed
:g/^$/d

" With lockmarks — marks stay on their original lines
:lockmarks g/^$/d

After the second command, 'a, 'b, and 'c still point to the content you originally marked, even though line numbers changed.

Tips

  • Essential in Vimscript functions that modify buffers but should not disturb the user's marks
  • Combine with :keeppattern for a fully non-destructive batch operation: :keeppattern lockmarks %s/foo/bar/g
  • Also preserves the '[ and '] marks from the last change, which is useful in scripts that chain operations

Next

How do I return to normal mode from absolutely any mode in Vim?