Can you have file type-specific key bindings in Vim?

In my .vimrc file, I have a key binding for commenting out that inserts double slashes (//) at the start of a line:

" the mappings below are for commenting blocks of text
:map <C-G> :s/^/\/\//<Esc><Esc>
:map <C-T> :s/\/\/// <Esc><Esc>

However, when I’m editing Python scripts, I want to change that to a # sign for comments

I have a Python.vim file in my .vim/ftdetect folder that also has settings for tab widths, etc. What is the code to override the keybindings if possible, so that I have Python use:

" the mappings below are for commenting blocks of text
:map <C-G> :s/^/#/<Esc><Esc>
:map <C-T> :s/#/ <Esc><Esc>

You can use :map <buffer> ... to make a local mapping just for the active buffer. This requires that your Vim was compiled with +localmap.

So you can do something like

autocmd FileType python map <buffer> <C-G> ...

The ftdetect folder is for scripts of filetype detection. Filetype plugins must be inside the ftplugin folder. The filetype must be included in the file name in one of the following three forms:

  • .../ftplugin/<filetype>.vim
  • .../ftplugin/<filetype>_foo.vim
  • .../ftplugin/<filetype>/foo.vim

For instance, you can map comments for the cpp filetype putting the following inside the .../ftplugin/cpp_mine.vim:

:map <buffer> <C-G> :s/^/\/\//<Esc><Esc>
:map <buffer> <C-T> :s/\/\/// <Esc><Esc>