2

在 VSCode 中,您可以使用 Alt+Shift + Up 或 Down 向上或向下复制和粘贴选定的文本行。

几个月前我切换到vim,我真的很怀念这个功能。我发现您可以使用这些可视模式绑定在可视模式下向上或向下移动选定的行,

vnoremap J :m '>+1<CR>gv=gv
vnoremap K :m '<-2<CR>gv=gv

但是如果您可以在不使用 yy 和 p 的情况下也可以上下复制和粘贴,那就太好了,因为当您完成拉动时,光标将放置在初始位置,退出可视模式并降低工作效率。

4

1 回答 1

4

Well, that, here, is the problem with copying and pasting random snippets from the internet without understanding what they do: they are little black boxes that one can't modify or extend at will by lack of knowledge.

Let's deconstruct the first mapping:

vnoremap J :m '>+1<CR>gv=gv
  • :[range]m {address} moves the lines covered by [range] to below line {address}. Here, the range is automatically injected by Vim: '<,'> which means "from the first line of the latest visual selection to its last line", and the address is '>+1, meaning "the last line of the latest visual selection + 1 line". So :'<,'>m '>+1<CR> effectively moves the selected lines below themselves,
  • gv reselects the latest visual selection,
  • = indents it,
  • gv reselects it again for further Js or Ks.

Now, we want a similar mapping but for copying the given lines. Maybe we can start with :help :m and scroll around?

Sure enough we find :help :copy right above :help :move, which we can try right away:

xnoremap <key> :co '>+1<CR>gv=gv

Hmm, it doesn't really work the way we want but that was rather predictable:

  • the address is one line below the last line of the selection,
  • the selection is reselected and indented, which is pointless.

We can fix the first issue by removing the +1:

xnoremap <key> :co '><CR>gv=gv

and fix the second one by selecting the copied lines instead of reselecting the latest selection:

xnoremap <key> :co '><CR>V'[=gv

See :help :copy and :help '[.

于 2021-09-21T08:02:24.050 回答