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

How to correctly indent text when using `put` in Vim

我在 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. Select/* Comment */,命中斩.
  2. 将光标移动到第一行代码的末尾并点击 return。
  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. 手动修复错误缩进的代码。

Vim 当我用 o 开始一个新行时自动缩进很好,所以它似乎也应该处理 putting 到一个新行....有吗一个能让我 put 新代码行正确缩进的命令?

:nnoremap p p`[v`]=

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

您可以使用 ]p[p 在当前行的缩进级别粘贴。请注意,这仅在寄存器的内容是逐行的时才有效。参见 :h ]p

如果你想使用 ]p 和朋友,但总是希望它是线性的,那么我建议你看看 Tim Pope 的 unimpaired.vim 插件。它还提供 >p/<p 映射,粘贴一个缩进级别 deeper/shallower,以及 =p/=P 粘贴然后重新缩进,类似于p='].

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