vimvi

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?


Solution

  • 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>