Loom
Loom

Reputation: 9986

Move current line (up/down) to one position in Vim

Sometimes I want to swap current line with line up or below in vim. I can do it with commands :m+1 or :m-1. However it is too wordy. Is there shorter way doing the same?

Upvotes: 5

Views: 5885

Answers (4)

oskar
oskar

Reputation: 119

Vim has the :move command that allows you to move one line.

For instance, :m +1 will move the current line down.

I have these mappings in my .vimrc :

" move the lines of visual mode up or down
" JK to move and keep a correct indentation (with =)
" <up><down> to move keeping the correct indentation
vnoremap <silent> J :m '>+1<cr>gv=gv
vnoremap <silent> <down> :m '>+1<cr>gv
vnoremap <silent> K :m '<-2<cr>gv=gv
vnoremap <silent> <up> :m '<-2<cr>gv

With these lines, if you select a bunch of lines in visual mode, and then press <up> or <down> arrows, the lines will be moved up or down (and you will stay in the same visual selection thanks to the gv at the end).

J and K are almost the same, but they keep and autoindentation, using the = operator (gv= autoindents the last visual selection).

For sure, i encourage you to do modify the keys that are mapped to your own preferences. These are just mine. Also, copy-pasting without understanding is probably a bad idea. If you understand that mapping, you could check help pages for :m, gv and =.

Upvotes: 3

Ingo Karkat
Ingo Karkat

Reputation: 172520

Both Tim Pope's unimpaired.vim - Pairs of handy bracket mappings and my own LineJuggler plugin provide (among others; my plugin has a focus on line moves and copies, whereas Tim's has a mixture of useful stuff) [e and ]e mappings to move the current line / selection above or below. These don't clobber the default register, as ddp et al. would do.

Upvotes: 4

romainl
romainl

Reputation: 196476

Give mappings a chance:

nnoremap <leader>k :move-2<CR>==
nnoremap <leader>j :move+<CR>==
xnoremap <leader>k :move-2<CR>gv=gv
xnoremap <leader>j :move'>+<CR>gv=gv

Upvotes: 1

Kent
Kent

Reputation: 195029

give this a try:

ddp and ddkP

if it gives what you want. ;)

Upvotes: 8

Related Questions