I'm trying to setup mappings for <C-]>
that, depending on the buffer's file type, trigger different functions. For example, if I'm in a Javascript buffer, I want <C-]>
to trigger :TernDef
. If I'm in a C buffer, I want it to trigger :YcmCompleter GoTo
. I tried autocmd FileType c nnoremap <C-]> :YcmCompleter GoTo<CR>
but it just seems to ignore that.
2 Answers
That autocmd looks fine; however, you should define buffer-local mappings (with <buffer>
); else, editing one type of file will override the other type's (global) mapping:
autocmd FileType c nnoremap <buffer> <C-]> :YcmCompleter GoTo<CR>
autocmd FileType javascript nnoremap <buffer> <C-]> :TernDef<CR>
Critique of the autocmd approach
You can define mappings for certain filetypes by prepending :autocmd Filetype {filetype} ...
, and put that into your ~/.vimrc
. But that gets unwieldy as you add mappings and other settings for various filetypes. Better put the :map
commands into ~/.vim/ftplugin/{filetype}_mappings.vim
. (This requires that you have :filetype plugin on
.)
-
-
If you want to add a lot of mappings to a single file type you can also wrap them in a function which is called by the autocommand.– smelmApr 23, 2021 at 17:55
-
1Note that in the
~/.vim/ftplugin/{filetype}_mappings.vim
path, themappings
portion is arbitrary; it could be called{filetype}_foo.vim
. Also note that a directory can be used as well (or in addition); vim will execute~/.vim/ftplugin/{filetype}/*.vim
in asciibetical order upon loading that filetype - filenames are arbitrary in this directory. Mar 12, 2022 at 17:11
For me that line does work (using commands that my Vim recognizes and including a colon at the start of the command). You could try to start Vim without plugins and see whether the line is recognized properly then.
Another option would be to put the commands you want to run in the c.vim file in the ftplugin directory. This way they will be run when you open a file of that type. More info can be found in :help ftplugin<cr>
.
<buffer>
in your mapping: In your current command when you open a c file<c-]>
will be remapped for all of your buffer (C or not). with<buffer>
your mapping will exist only on C buffers, see:h :map-<buffer>
.