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.
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.'<,'>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With