tags:

views:

59

answers:

3

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 example:

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!

A: 

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.

Jay
+2  A: 
Pestilence
A: 

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.

Luc Hermitte