Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore error in VIM key mapping command series?

Tags:

vim

keymapping

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.

The current appearance is that, the line 1 2 are not highlight anymore. I know that's because the ":m '<-1" failed, then gv will not be executed.

So my question is how to ignore this error to ensure gv executed anyway? Or some other solutions?

Please note, I know a solution linemovement.vim. It run these in two separated commands and some functions. While I suppose this should be a lightweight code.

like image 575
Qiu Yangfan Avatar asked Dec 20 '22 10:12

Qiu Yangfan


1 Answers

You need :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
  • <C-u> removes the "selection range" inserted automatically by Vim because :silent doesn't accept a range.
  • we add '<,'> before :move so that it still works on the visual selection.

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.

like image 56
romainl Avatar answered Jan 15 '23 06:01

romainl