Move entire line up and down in Vim

后端 未结 19 1171
无人及你
无人及你 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:08

    :m.+1 or :m.-2 would do if you're moving a single line. Here's my script to move multiple lines. In visual mode, Alt-up/Alt-down will move the lines containing the visual selection up/down by one line. In insert mode or normal mode, Alt-up/Alt-down will move the current line if no count prefix is given. If there's a count prefix, Alt-up/Alt-down will move that many lines beginning from the current line up/down by one line.

    function! MoveLines(offset) range
        let l:col = virtcol('.')
        let l:offset = str2nr(a:offset)
        exe 'silent! :' . a:firstline . ',' . a:lastline . 'm'
            \ . (l:offset > 0 ? a:lastline + l:offset : a:firstline + l:offset)
        exe 'normal ' . l:col . '|'
    endf
    
    imap   :call MoveLines('-2')
    imap   :call MoveLines('+1')
    nmap   :call MoveLines('-2')
    nmap   :call MoveLines('+1')
    vmap   :call MoveLines('-2')gv
    vmap   :call MoveLines('+1')gv
    

提交回复
热议问题