I need to (visual) select a range of lines from command line.

For example the following command :?^\s*for?+,/^\s*end/- p prints all lines contained between a for and end (exclusive way). Instead of performing the printing operation I would like to switch to visual mode with those lines highlighted. I searched in the manual but I couldn't find such an ex-command.

  • Do you mean "exclusive"?
    – Rich
    Feb 1, 2017 at 11:48
  • you're right! I edited the question
    – nicmus
    Feb 1, 2017 at 14:14

1 Answer 1


The boundaries of a visual mode selection are defined by the < and > marks.

Thus, the following command will enter visual mode with lines 5 through 10 (inclusive) selected:

 :5mark < | 10mark > | normal gvV
  • :5mark < sets the start of the selection to line 5,
  • :10mark > sets the end of the selection to line 10,
  • gv enters visual mode with the area defined above selected,
  • V makes the selection linewise.

You can pass any Vim range into the :mark command: the following will enter visual mode using the regular expressions foo and bar to define the boundaries of the selection area:

:execute search("foo") . "mark <" | execute search("bar") . "mark >" | normal gvV

The following command is a simpler version of the above, but is dependent on cursor position:

/foo/mark < | /bar/mark > | normal gvV

For more explanation, see:

  • 1
    Thanks! I solved with: ?^\s*for?+ mark < | /^\s*end/- mark > | norm gv
    – nicmus
    Feb 1, 2017 at 11:41
  • @nicmus Ah yes, that's simpler for your specific use. I've updated my answer.
    – Rich
    Feb 1, 2017 at 11:59
  • Just for the sake of any future readers that might be wondering, the + and - in @nicmus's comment are adjusting the ranges in order to make the selection not include the lines that match the regular expressions. (See :help range)
    – Rich
    Feb 2, 2017 at 9:25
  • The . concatenation operator really threw me off so here's an example if someone feels the same: :execute "l" . "s" will produce the same output as :ls.
    – toraritte
    Dec 31, 2019 at 15:56
  • To visually select the entire buffer: :execute "1mark < | " line('$')"mark > | normal gvV". (With help from the Execute chapter of Learn Vimscript the Hard Way.)
    – toraritte
    Jul 5, 2020 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.