Move entire line up and down in Vim

后端 未结 19 1146
无人及你
无人及你 2020-11-29 14:27

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?

19条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 15:15

    Put the following to your .vimrc to do the job

    noremap  :call feedkeys( line('.')==1 ? '' : 'ddkP' )
    noremap  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   :call swap_up()
    noremap   :call swap_down()
    

提交回复
热议问题