What is the command (or shortcut) to move a line up or down in vim? My current workflow is to yank (copy) the line and than delete that line and than to put (paste) that line.
First, you do not need to yank and delete; the latter will also put the deleted contents into the (default or specified) register. Therefore,
ddkP are common commands to move a line one down / up.
Alternatively, you can use the
:move command, i.e.
:move +1 /
:move -2; this doesn't clobber the register, and you can also move entire ranges. You can easily define key mappings to shorten this.
If you don't mind plugins (and the additional comfort that often comes with them), both Tim Pope's unimpaired plugin and my LineJuggler plugin provide
[e mappings to move lines (and several more; Tim's for a variety of uses, mine focused on handling line(s)).
The easiest is:
:m-2 which is abbreviation for
:move as Ingo suggested.
Or using visual mode (V) by cutting the line (d/x) then paste it (p - below cursor, P above cursor) after you moved your cursor to the right place before pasting (so in summary it's Vxp/Vdp).
When moving multiple lines in visual mode, then you've to use
:m '>+1 (to move one line down) or
:m '<-2 (to move one line up).
Here is sample useful mapping (Shift+ ↑/Shift+↓):
nnoremap <S-Up> :m-2<CR> nnoremap <S-Down> :m+<CR> inoremap <S-Up> <Esc>:m-2<CR> inoremap <S-Down> <Esc>:m+<CR>
Here are some suggested at vim wikia:
nnoremap <A-j> :m .+1<CR>== nnoremap <A-k> :m .-2<CR>== inoremap <A-j> <Esc>:m .+1<CR>==gi inoremap <A-k> <Esc>:m .-2<CR>==gi vnoremap <A-j> :m '>+1<CR>gv=gv vnoremap <A-k> :m '<-2<CR>gv=gv
In normal mode or in insert mode, press Alt-j to move the current line down, or press Alt-k to move the current line up.
After visually selecting a block of lines (for example, by pressing V then moving the cursor down), press Alt-j to move the whole block down, or press Alt-k to move the block up.
FWIW, here is what I've used for years. It moves the current line up and down in normal mode or the selection in visual mode, while adjusting the indentation automatically.
nnoremap ,<Up> :<C-u>silent! move-2<CR>== nnoremap ,<Down> :<C-u>silent! move+<CR>== xnoremap ,<Up> :<C-u>silent! '<,'>move-2<CR>gv=gv xnoremap ,<Down> :<C-u>silent! '<,'>move'>+<CR>gv=gv