Move entire line up and down in Vim
In Notepad++, I can use Ctrl + Shift + Up / Down to move the current line up and down. Is there a similar command to this in Vim? I have looked through endless guides, but have found nothing.
If there isn't, how could I bind the action to that key combination?
Edit: Mykola's answer works for all lines, apart from those at the beginning and end of the buffer. Moving the first line up or the bottom line down deletes the line, and when moving the bottom line up it jumps two spaces initially, like a pawn! Can anyone offer any refinements?
Put the following to your .vimrc to do the job
noremap <c-s-up> :call feedkeys( line('.')==1 ? '' : 'ddkP' )<CR>
noremap <c-s-down> ddp
Disappearing of the line looks like a Vim bug. I put a hack to avoid it. Probably there is some more accurate solution.
Update
There are a lot of unexplained difficulties with just using Vim combinations. These are line missing and extra line jumping.
So here is the scripting solution which can be placed either inside .vimrc or ~/.vim/plugin/swap_lines.vim
function! s:swap_lines(n1, n2)
let line1 = getline(a:n1)
let line2 = getline(a:n2)
call setline(a:n1, line2)
call setline(a:n2, line1)
endfunction
function! s:swap_up()
let n = line('.')
if n == 1
return
endif
call s:swap_lines(n, n - 1)
exec n - 1
endfunction
function! s:swap_down()
let n = line('.')
if n == line('$')
return
endif
call s:swap_lines(n, n + 1)
exec n + 1
endfunction
noremap <silent> <c-s-up> :call <SID>swap_up()<CR>
noremap <silent> <c-s-down> :call <SID>swap_down()<CR>
If I want to swap one line with the line above I usually do the following
ddkP
Explanation
Assuming the cursor is on the line you like to move.
Moving up and down: :m
for move
:m +1
- moves down 1 line
:m -2
- move up 1 lines
(Note you can replace +1 with any numbers depending on how many lines you want to move it up or down, ie +2 would move it down 2 lines, -3 would move it up 2 lines)
To move to specific line
:set number
- display number lines (easier to see where you are moving it to)
:m 3
- move the line after 3rd line (replace 3 to any line you'd like)
Moving multiple lines:
V
(ie Shift-V) and move courser up and down to select multiple lines in VIM
once selected hit : and run the commands above, m +1
etc
上一篇: 在vim中,我如何回到搜索前的位置?
下一篇: 在Vim中上下移动整行