Search code examples
vimnerdcommenter

How do I use ctrl + / as a shortcut in vim using map? (<C-_> doesn't work)


I'm using a plugin for vim called NERDCommenter which allows me to toggle line of code's commented state. The thing is I want to change the shortcut to ctrl + / or command + /. Online (from other posts I read) it says to not use <C-/>, but to instead use <C-_>. This does not work and only maps the toggle comment command to ctrl underscore.

Here is the code I'm using to do this:

nnoremap <C-_> :call NERDComment(0, "toggle")<CR>

Can someone please let me know what I'm doing wrong? Thank you.


Solution

  • As of writing this, in MacOS using the current/built-in Terminal app (without the use of other software), unfortunately it is not possible to map a Vim shortcut using Control+/ or Command ⌘+/.

    This is because neither of these key sequences have control code encodings (more on that here and here).


    Option #1 (recommended)

    Map Option/Alt+/ to toggle NERDCommenter → mac users must use the real character (÷) generated by Option/Alt sequence to do this:

    nmap ÷ <plug>NERDCommenterToggle
    vmap ÷ <plug>NERDCommenterToggle<CR>gv
    

    Only works if Terminal > Preferences > Profiles [settings] > Keyboard > 'Use Option as Meta Key' is toggled OFF. More info here.

    Option #2 - MacVim

    You can use MacVim which allows you to map the Command ⌘ key with <D->. More info here.

    Option #3 - iTerm2

    Use iTerm2 for your terminal app. This way you can map Control+/ to <C-_> and it will work. For Command ⌘+/ to work, you'll have to create a new keyboard shortcut to send as an escape sequence to Vim. More info here and here.


    I wouldn't advise this, but you could also use a program to remap your Command ⌘ or Control modifier keys every time you open a specific app like Terminal. iTerm2 works for this task too, as well as programs like Karabiner -- for older versions of MacOS. According to this post, the newer Karabiner-Elements requires some tweaking for app-specific remapping.

    More Resources: here, here, and here.