在 Vim 中使用 `put` 时如何正确缩进文本

问题描述 投票:0回答:4

我在 Vim 中

putting
发短信时遇到问题。

假设我想将
/* Comment */
行粘贴到
$('table').append
行下方...

/* Comment */

for (var i=1; i<=lineLength ; i++) {
    $('table').append('<tr></tr>');
    for (var j=1; j<=lineLength; j++) {
    $('table tr:nth-last-child(1)').append('<td></td>');
    }
}

在大多数文本编辑器中,我的工作流程是

  1. 选择
    /* Comment */
    ,点击剪切。
  2. 将光标移至第一行代码末尾并按回车键。
  3. 文本编辑器自动缩进,我只需点击粘贴即可。

/* Comment */

for (var i=1; i<=lineLength ; i++) {
    $('table').append('<tr></tr>');
    | <==Pipe is position of cursor before paste; pasted lines are inserted here.
    for (var j=1; j<=lineLength; j++) {
    $('table tr:nth-last-child(1)').append('<td></td>');
    }
}

但是使用 vim,似乎我必须这样做:

  1. 移至
    /* Comment */
    线,点击
    dd
  2. 移至
    $('table').append
    线,点击
    p

新代码:

for (var i=1; i<=lineLength ; i++) {
        $('table').append('<tr></tr>');
/* Comment */. <== Comment is not correctly indented.
        for (var j=1; j<=lineLength; j++) {
        $('table tr:nth-last-child(1)').append('<td></td>');
        }
    }
  1. 手动修复错误缩进的代码。

当我用

o
开始新行时,Vim 自动缩进很好,所以看起来它也应该将
putting
处理到新行......是否有一个命令可以让我
put
新行具有正确缩进的代码?

vim indentation copy-paste paste auto-indent
4个回答
5
投票

您可以使用

]p
[p
在当前行的缩进级别进行粘贴。请注意,这仅在寄存器的内容是逐行的情况下才有效。参见
:h ]p

如果你想使用

]p
和朋友,但总是希望它是逐行的,那么我建议你看看 Tim Pope 的 unimpaired.vim 插件。它还提供
>p
/
<p
映射,将一层缩进更深/更浅地粘贴,以及
=p
/
=P
粘贴然后重新缩进,类似于
p=']


2
投票
:nnoremap p p`[v`]=

取自 https://github.com/sickill/vim-pasta


0
投票

:nnoremap p p=']
与其他答案相同,但击键次数更少。无需目视选择。


0
投票

我认为最优雅的解决方案是在插入模式下使用

Ctrl-R"
。它将寄存器
"
(存储最近删除的文本)的内容放在光标的位置。

© www.soinside.com 2019 - 2024. All rights reserved.