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

How do I reuse the last visual selection range in an Ex command after exiting visual mode in Vim?

Answer

:'<,'>

Explanation

Vim automatically sets two special marks whenever you make a visual selection: '< (start) and '> (end). These marks persist after you leave visual mode and are not overwritten until you make a new selection. This means you can reference your last visual range in Ex commands at any time — even several operations later.

How it works

  • '< — the line/column of the start of the last visual selection
  • '> — the line/column of the end of the last visual selection
  • :'<,'>cmd — runs cmd over the last visually selected range
  • These marks are set in normal mode too: you can jump to them with `< and `>

Example

Visually select three lines with V and press <Esc> to deselect. Later, to sort just those lines:

:'<,'>sort

Or to run a macro only on those lines:

:'<,'>normal @q

Or to comment them out:

:'<,'>s/^/# /

Tips

  • Vim auto-inserts '<,'> when you press : from visual mode, but you can type it manually at any time afterward
  • Use gv to re-enter visual mode and re-highlight the same selection before typing :
  • `< and `> (backtick marks) jump to the exact column, while '< and '> (apostrophe marks) jump to the start of the line
  • The marks survive buffer switches: if you come back to a buffer, the last visual selection marks are still there

Next

How do I make the = operator use an external formatter instead of Vim's built-in indentation?