Detect filetype from within VIM plugin?
I have a vim plugin that defines a bunch of key mappings.
I'm trying to figure out how I can change the defininition of the key mapping based on the filetype.
For exa开发者_运维问答mple:
If the file is a *.py: then map the key to X If the file is a *.php: then map the key to Y
Thanks!
Yes. One way would be to use autocmd to call a custom function that sets your maps. It would look roughly like the following (could have mangled the syntax, so this isn't really copy & pastable):
augroup foo
autocmd!
autocmd FileType python call MyPythonSettings()
augroup end
function !MyPythonSettings() set noai " set mappings... endfunction
When specific commands/abbreviation/mappings needs to be defined, I always split my plugin into several files:
- the core functions that go into autoload plugin(s)
- the global mappings/commands/abbreviations that go into a "plain" plugin
- the filetype specific stuff that go into ftplugins.
Useless example:
The autoload plugin
" autoload/lh/ThePlugin.vim
let g:multby = 42
function lh#ThePlugin#fn(arg)
return a:arg * g:multby
endfunction
function lh#ThePlugin#inc_mult()
let g:multby += 1
endfunction
The "plain" plugin
" plugin/ThePlugin.vim
if exist('g:ThePlugin_loaded') | finish | endif
let g:ThePlugin_loaded = '1.0.0'
nnoremap £ :call lh#ThePlugin#inc_mult()
One ftplugin
" ftplugin/cpp/cpp_ThePlugin.vim
if exist('b:ThePlugin_loaded') | finish | endif
let b:ThePlugin_loaded = '1.0.0'
inoremap <buffer> µ <c-r>=lh#ThePlugin#fn(12)<cr>
PS: note the use of <buffer>
in order to not pollute other filetypes with mappings that make no sense, nor override previously defined (and specific) mappings that do make sense.
The FileType
event gets fired when the user opens a file to edit. This, however requires that the user has enabled :filetype on
in her vimrc
(or manually), whether for those specific extensions or globally.
If the user is editing a new file, you won't get that until they first save the buffer or do :setf autohotkey
:setf sql
etc.
精彩评论