3

I should know this, but my mind is blank right now ... long night ...

How to define a mapping that is active only when a certain filetype is active (say, markdown and I wish to define a mapping/abbrev for inserting brackets ][ since I don't have them on my keyboard in my language layout)?

3 Answers 3

5

To define a mapping effective only in the buffers having certain filetype value, one can use the combination of a filetype autocommand (see :help autocmd, :help FileType) and a local mapping (see :help map-local).

:autocmd FileType markdown inoremap <buffer> (( [
:autocmd FileType markdown inoremap <buffer> )) ]
1
  • Figures it had to be something dead-simple ;) Thanks ib.!
    – Rook
    Oct 15, 2011 at 14:22
2

The first, mandatory, step is indeed to define buffer local mappings with :h :map-<buffer> as ib said.

Then you have the choice. You can :

  • either clutter your .vimrc with autocommands
  • or use ftplugins, which is the solution that scales, that can be easily redistributed, and so on.

The first approach is fine when we only use vim for a couple of languages/filetypes and when we have very few mappings/commands/abbreviations/... It's fine the first couple of years in Vim. Past a certain amount of ft-specific settings, the second solution is the one to be preferred.

(BTW, this subject is a duplicate, but I too lazy right now to search for the other posts)

0

Add where appropriate (e.g. ~/.vimrc):

au FileType markdown inoremap <C-b> [
2
  • The command does not work as you probably expect. Once a buffer with markdown filetype is open, it defines the global mapping that works for any buffer even after that Markdown file is closed!
    – ib.
    Oct 15, 2011 at 4:46
  • @ib Thank you, forgot about that. (I make this mistake fairly regurlarly in my own ~/.vimrc).
    – Owen
    Oct 15, 2011 at 5:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.