在 vim 中剪切和粘贴多行

我在 Mac 10.7.2上运行 vim 7.3,在剪切和粘贴几行代码时遇到了一些麻烦。

在我以前的 Linux 设置(它被偷了,所以我不知道版本) ,我可以输入“ dd”多次,然后“ p”会把它们全部拉回来。例如: type: “ dd dd”,两行将被删除。现在输入“ p”并将 都有行粘贴回缓冲区。

我知道我可以通过输入“2dd”,然后输入“ p”来完成我想要的任务——但是我希望能够输出“ dd”,而不用提前计算行数。

有什么想法吗?

88888 次浏览

Have you considered using visual mode?

You could just go:

  • Press V
  • Select everything you want to cut without counting
  • Press d
  • Go to where you want to paste
  • Press p

This should yield approximately half as many keystrokes as the dd method since you press one key per line rather than two. Bonus points if you use 5j (or similar) to select multiple lines at a time.

Not sure if this is close enough to what you're trying, but one thing you could do is use a specific register, and capitalize your register name. That tells vim to append to the register rather than replace it, so if you have the lines:

one
two
three

you can enter

"qdd
"Qdd
"Qdd

and then subsequently if you enter

"qp

it will paste back the original lines

I agree with @Ben S. that this is the preferred way to accomplish this but if you are just looking to replicate your old behavior you can remap dd to append to a specified register, and then map p to paste from that register and clear it.
This will have the disadvantage of causing p to only work with things deleted using dd (using d} to delete to the end of the paragraph would not put the text in the correct register to be pasted later).

Add the following to your vimrc

noremap dd "Ddd             "Appends the contents of the current line into register d
noremap p "dp:let @d=""<CR> "Pastes from register d and then clears it out

if you don't want pasting to clear out the contents of the register

noremap p "dp               "Paste from register d

but this will cause that register to grow without ever clearing it out

To cut and paste by line numbers (do :set number to see the line numbers), for lines x to y do:

:x,yd

or if your cursor is already on line x, do

:,yd

Then go to where you want to paste and press p

You could type:

d<n>d

where <n> is the number of lines that you want to cut, and then you could paste them with:

p

For example, to cut and paste 3 lines:

d3d
p

To copy and paste 4 lines:

y4y (with the cursor on the starting line you wanna copy)

p (with cursor on the line you wanna paste after)