简体   繁体   English

如何忽略VIM键映射命令系列中的错误?

[英]How to ignore error in VIM key mapping command series?

I'm editing key mappings for line movement as following: 我正在编辑线移动的按键映射,如下所示:

vnoremap <silent> <C-j> :m '>+1<CR>gv
vnoremap <silent> <C-k> :m '<-2<CR>gv

They are supposed to move the line block up and down and work fine in most cases except at the top and bottom of a file. 他们应该上下移动行块,并且在大多数情况下都可以正常工作,除了文件的顶部和底部。

When I select the line 1 2, and input ctrl-k, sure, it cannot move anymore upwards, while the expected behavior is that the line 1 2 are still highlight in visual mode. 当然,当我选择第1 2行并输入ctrl-k时,它不能再向上移动,而预期的行为是第1 2行在可视模式下仍然突出显示。

The current appearance is that, the line 1 2 are not highlight anymore. 当前的外观是,第1 2行不再突出显示。 I know that's because the ":m '<-1" failed, then gv will not be executed. 我知道那是因为“:m'< - 1”失败了,那么gv就不会被执行了。

So my question is how to ignore this error to ensure gv executed anyway? 所以我的问题是如何忽略此错误以确保gv执行? Or some other solutions? 还是其他解决方案?

Please note, I know a solution linemovement.vim. 请注意,我知道一个解决方案linemovement.vim。 It run these in two separated commands and some functions. 它以两个单独的命令和一些功能运行它们。 While I suppose this should be a lightweight code. 虽然我认为这应该是轻量级的代码。

You need :silent! 你需要:silent! to suppress the output and skip errors: 抑制输出并跳过错误:

vnoremap <C-j> :<C-u>silent! '<,'>m '>+1<CR>gv
vnoremap <C-k> :<C-u>silent! '<,'>m '<-2<CR>gv
  • <Cu> removes the "selection range" inserted automatically by Vim because :silent doesn't accept a range. <Cu>删除Vim自动插入的“选择范围”,因为:silent不接受范围。
  • we add '<,'> before :move so that it still works on the visual selection. 我们之前添加'<,'> :move以便它仍然适用于视觉选择。

Here is that fix applied to my enhanced (adds autoindenting) version of those mappings: 以下是应用于我的增强(添加自动延迟)版本的映射的修复:

nnoremap ,<Up>   :<C-u>silent! move-2<CR>==
nnoremap ,<Down> :<C-u>silent! move+<CR>==
xnoremap ,<Up>   :<C-u>silent! '<,'>move-2<CR>gv=gv
xnoremap ,<Down> :<C-u>silent! '<,'>move'>+<CR>gv=gv

Thanks for the idea. 谢谢你的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM