I'm trying to define mappings for "cpp" filetype:
autocmd! FileType cpp map <leader>c echo "test c"
autocmd! FileType cpp m开发者_开发技巧ap <leader>r echo "test r"
autocmd! FileType cpp map <leader>t echo "test t"
My leader key is redefined:
let mapleader = ","
When I open *.cpp file only one of the mappings works as expected: the ",t" sequence makes the "echo" happen, but the other two behaves as if there were no any mappings defined: ",r" makes Vim to switch to replace mode and ",c" brings Vim to insert mode.
What am I doing wrong?
I don't know how your example (including ,c
one) could work: you forgot to prepend echo with a colon. But there is another mistake: according to the help:
:au[tocmd]! [group] {event} {pat} [nested] {cmd}
Remove all autocommands associated with {event} and {pat}, and add the command {cmd}.
So, the last one (,t
) should replace all previous ones.
There are also another things you should to consider:
- Don't use
map
, usenoremap
instead: it may once save you from doing a debug job after you add some mapping. - If you define filetype mapping you should normally add
<buffer>
as an argument to:noremap
in a position before{lhs}
: it will make this mapping local to the current buffer. In case you want to re-source vimrc you should put all command into augroup:
augroup VimrcCpp autocmd! autocmd FileType cpp nnoremap <buffer> <leader>c :echo "c"<CR> autocmd FileType cpp nnoremap <buffer> <leader>r :echo "r"<CR> autocmd FileType cpp nnoremap <buffer> <leader>t :echo "t"<CR> augroup END
- I would have removed it from vimrc and added to ~/.vim/ftplugin/cpp.vim (
after
directory is to be used only to override options that you don't like if they are unconditionally defined by a plugin. If there are no mapping conflicts, don't useafter
).
I suggest you put those mapping in a file called cpp.vim
placed in your ~/.vim/after/ftplugin/
(or any equivalent based on OS) directory.
Vim automatically loads it as long as you have
filetype plugin on
in your .vimrc
.
This saves you writing autocommands and keeps your configuration well organized.
精彩评论