Vim Tips Wiki
Advertisement
Tip 646 Printable Monobook Previous Next

created 2004 · complexity basic · author Frank Butler · version 6.0


The following mappings in your vimrc provide a quick way to move lines of text up or down. The mappings work in normal, insert and visual modes, allowing you to move the current line or a selected block of lines.

nnoremap <M-j> mz:m+<CR>`z==
nnoremap <M-k> mz:m-2<CR>`z==
inoremap <M-j> <Esc>:m+<CR>==gi
inoremap <M-k> <Esc>:m-2<CR>==gi
vnoremap <M-j> :m'>+<CR>gv=`<my`>mzgv`yo`z
vnoremap <M-k> :m'<-2<CR>gv=`>my`<mzgv`yo`z

Press Alt-j to move the current line down, or press Alt-k to move the current line up. The == re-indents the line to suit its new position.

Explanation

The command :m 5 moves the current line to below line 5. If the number starts with + or -, it is relative to the current line, so :m +5 moves the current line down by 5 lines (+5 is interpreted as .+5 where . means the current line). The space after :m is not required, and the +1 can be written as + (the 1 is assumed).

See also

Comments

 TO DO 

  • A quick test shows that this is very nice, and if polished, it could be a featured tip.
  • Why does it use a mark? I only tried the normal-mode mapping, but it seemed to work fine with the mz and `z removed.
  • Need to improve my above explanation.

Comments welcome. JohnBeckett 11:58, September 3, 2009 (UTC)

I think the visual commands can be made simpler

vnoremap <M-j> :m'>+<cr>gv=gv
vnoremap <M-k> :m-2<CR>gv=gv

John, the z mark in the normal mode mapping is intended to return the cursor to its original position in the line. Unfortunately, the re-indenting clobbers this. Also, if the line is re-indented the z mark will be out by the same amount that the line is re-indented.

Another version of this feature can be found in the Transposing tip. If memory serves correctly, it doesn't suffer the indenting bug I described above and the mappings can also take a count. Its a lot more complex though. BenArmston 21:53, November 3, 2009 (UTC)

Advertisement