问题
I have a mapping in my vimrc that downwardly comments out regions of c code:
nmap comc :normal! I//<ESC>
Since the 'normal' ex command implicitly converts input such as "Ncomc" to ".,.+N-1 comc", I can range comments downwardly without many keystrokes and without leaving normal mode. This is, however, a very limited subset of what vim ranges can do. If I'm willing to be verbose, I can achieve upward ranging comments like so:
.,.-5 normal comc
While editing text, I would much prefer to type something like "-6comc" or make a mapping of "Comc" that uses upward ranges. I'm haven't been able to do so successfully.
Similarly, range operations support commenting until a search pattern is reached, e.g :
.,/int main/ comc
I would, however, like to do so without all that typing.
回答1:
The behavior you requested is normally done with :h map-operator
mapping. With this commenting 3 lines down will turn into comc2j
though, but 3 lines up is now just as easy: comc2k
.
You can also use visual mode without changing your mapping at all: V2kcomc
. You will have to add xnoremap
with the identical lhs
and rhs
because nnoremap
works only for normal mode. (And do not use nmap.)
Third option is mapping -
to something that moves {count}
lines up and puts count back:
nnoremap <expr> - (v:count ? ":\<C-u>\n" . (v:count-1) . 'k' . v:count : '')
. This assumes you are writing 6-comc
, not -6comc
.
// By the way, I would suggest The NERD Commenter
if it comes to the plugin.
回答2:
While it's commendable to go as far as possible without any plugins, sometimes they're just the best option. What will you do when you start working in a language that has comments with #
or (*
...*)
? Add new mappings for these comment characters?
I recommend commentary.vim which does filetype-aware commenting.
The default commenting operator in commentary.vim is gc
. You can combine it with motions, and use it in Visual mode too.
Your use cases:
Comment downwards N lines (say, 3):
:.,.+3normal gcc
, orgc3j
or4gcc
.Comment upwards 5 lines:
:.,.-5normal gcc
, or simplygc5k
.Comment until
int main
::.,/int main/-1normal gcc
, or simplygc/int main
followed by Enter.
来源:https://stackoverflow.com/questions/17478304/advanced-usage-of-ranges-with-vim-keymappings