Search code examples
vim

Remap `gc` for vim-commentary not working


I am trying to write a mapping to use vim Commentary. Right now my .vimrc has the following line:

vnoremap gg <PLUG>Commentary

However, when I open a document to edit pressing gg only makes the terminal flash. Using the default mapping gc works as expected.

I can see that the mapping is loaded by vim by running :map gg which returns

v  gg          * <Plug>Commentary

Solution

    • The terminal flashes because gg puts the cursor on the first line of the buffer and you are already there.

    • <Plug>Commentary is a "plug mapping", a special kind of mapping used by plugin developers as an alternative to exposing the guts of the plugin. Since they are mappings, they can only be consumed in recursive mappings (nmap, xmap, etc.). They can't be used in non-recursive mappings (nnoremap, xnoremap, etc.) at all.

      Therefore, your mapping should look like this:

      xmap gg <Plug>Commentary
      

      Note that I have used xmap, here, which restricts the mapping to visual mode. You don't really want to trigger it while typing egg in select mode.

    • But that's one part of the problem. Your mapping is a visual mode mapping so you can't expect it to work in normal mode.

      For gg to do what you want in normal mode, you would need another mapping:

      nmap gg <Plug>Commentary
      
    • Note that the plugin provides gc in one additional mode: operator-pending mode, so you will have to do it as well for the sake of completeness:

      omap gg <Plug>Commentary
      
    • That said, overriding default commands is not exactly a good idea, especially common ones like gg. That is, unless you are an advanced user who uses some other command to do the same but that seems unlikely, here.