How do you reuse a visual mode selection?

Solution 1:

You may re-select the last selected visual area with gv.

Solution 2:

gv is definitely the fastest method (use last selection), but if you want a stable saved selection region (or several), you can always create macros.

Lets say I want to store a selection of my current method, which goes from lines 25-35. I can create a macro that selects the whole method by typing

q    //start recording
a    //use register a
25G  //Go to line 25
V    //visual-line mode
35G  //Go to line 35
q    // stop recording

I can then get that selection back by typing @a (run macro in register a). Repeat with any register, lines, or sections of lines, that you wish. Obviously if you make changes to the file the selection may change as well, so you may want to consider using marks instead of "hardcoding" line numbers.

Solution 3:

gv works great for recovering the last selection. But one sometimes needs a bit more.

If you ever needed more persistent record, have a look a this plugin we are currently working on on the GitHub.

VisualMarks allows you to save and restore visually selected areas just like you save and mark specific locations in your files with m. After installing, and with the default options, use:

ma

in visual mode to save your current selection to mark a, then

<a

in normal mode to get back to this selection.

Solution 4:

Vim remembers the last selection.

If you enter : in visual mode it will auto-fill :'<,'> for you so you can continue entering command, e.g.

:'<,'>s/old/new/    # (Replace pattern in selected area)

If you want to execute another command on the same visual selection, you can simply bring up the old one from the history and edit it.

:'<,>'s/abc/xyz/    # (This will run the replace command on the same selection area)

Another way to tell the replace command and other commands which support match pattern to use the previous selection is by adding \%V to the pattern, e.g.

:s/\%Vabc/xyz/      # (Same as above)

For more info, please, see :help \%V.

To re-select the previous selection use gv.