8

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 '17 at 11:48
  • you're right! I edited the question – nicmus Feb 1 '17 at 14:14
7

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:

  • Thanks! I solved with: ?^\s*for?+ mark < | /^\s*end/- mark > | norm gv – nicmus Feb 1 '17 at 11:41
  • @nicmus Ah yes, that's simpler for your specific use. I've updated my answer. – Rich Feb 1 '17 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 '17 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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