16

Recently I learned from Practical Vim a way to copy or move block of lines without having to move the cursor from the current position. This is done in command line mode. e.g.

:123,133m.  # moves lines from 123 to 133 below the cursor position.

While I like it, it is a pain to type the long line numbers, especially when the file has too many lines.

At times, the lines to move are relatively near the cursor (but I don't want to move my cursor, yank, come back where I was, paste!). It would be great if I could use relative numbers, similar to how we do in normal mode. It is like saying

move 5 lines which are 10 lines above the current line to here

In short, how to use relative numbers in command line mode (similar to normal mode)?

22

Assuming your lines span from 15 to 10 lines above the current one, you can achieve what you requested using relative line numbers:

:-10,-15m.

Unfortunately when specifying a backwards range, Vim asks you to confirm if that is what you really wanted. To avoid the confirmation step, you can type silent before your command, or just specify a forwards range:

:-15,-10m.

As you might expect + can be used to refer to lines below the current one.

Detailed help can be found with:

:help cmdline-ranges
  • But I have never once used this feature. I do 15k d5j 10j P. – joeytwiddle Oct 30 '15 at 9:24
11

You can use hard numbers in your range:

:200,300command

Or relative numbers:

:-27,+46command

Or manual marks:

:'a,'bcommand

Or automatic marks:

:'[,'>command

Or searches:

:?foo?,/bar/command

Or line shortcuts:

:.,$command

Or any combination of the tricks above:

:?foo?,+46command
:'a,$command
...
3

You can use relative addressing (e.g. .-10,.+3) with any Ex command, cp. :help :range.

Alternatively, have a look at my LineJuggler plugin; it provides several short mappings to move lines around or duplicate them, and all those mappings take a relative line offset as [count].

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.