Advanced Usage of Ranges with Vim Keymappings

后端 未结 2 1961
不知归路
不知归路 2021-01-23 11:26

I have a mapping in my vimrc that downwardly comments out regions of c code:

nmap comc :normal! I//

Since the \'normal\' ex command

相关标签:
2条回答
  • 2021-01-23 11:52

    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, or gc3j or 4gcc.

    • Comment upwards 5 lines: :.,.-5normal gcc, or simply gc5k.

    • Comment until int main: :.,/int main/-1normal gcc, or simply gc/int main followed by Enter.

    0 讨论(0)
  • 2021-01-23 11:58

    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.

    0 讨论(0)
提交回复
热议问题