3

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?

Sagar Jain
  • 6,909
  • 11
  • 43
  • 75
Loom
  • 9,518
  • 20
  • 52
  • 108
  • possible duplicate of [Move entire line up and down in Vim](http://stackoverflow.com/questions/741814/move-entire-line-up-and-down-in-vim) – glts Apr 11 '14 at 19:00

4 Answers4

5

give this a try:

ddp and ddkP

if it gives what you want. ;)

Kent
  • 181,427
  • 30
  • 222
  • 283
3

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.

Ingo Karkat
  • 161,022
  • 15
  • 231
  • 302
1

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
romainl
  • 172,579
  • 20
  • 259
  • 291
1

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 =.