在 Vim 中上下移动整行 [英] Move entire line up and down in Vim

查看:231
本文介绍了在 Vim 中上下移动整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Notepad++ 中,我可以使用 Ctrl + Shift + Up/Down 向上移动当前行和下来.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?

Mykola 的答案适用于所有行,除了缓冲区开头和结尾的行.向上移动第一行或向下移动底线会删除该行,当向上移动底线时,它最初会跳两个空格,就像一个棋子!任何人都可以提供任何改进吗?

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?

推荐答案

将以下内容放入您的 .vimrc 以完成工作

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

该行的消失看起来像是 Vim 的错误.我放了一个黑客来避免它.可能有一些更准确的解决方案.

Disappearing of the line looks like a Vim bug. I put a hack to avoid it. Probably there is some more accurate solution.

更新

仅仅使用 Vim 组合就有很多无法解释的困难.这些是缺行和额外的跳行.

There are a lot of unexplained difficulties with just using Vim combinations. These are line missing and extra line jumping.

这里是脚本解决方案,它可以放在 .vimrc 或 ~/.vim/plugin/swap_lines.vim 中

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>

这篇关于在 Vim 中上下移动整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆