Rook
Rook

Reputation: 62538

Define mapping in insert mode that works only with a certain filetype

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)?

Upvotes: 3

Views: 240

Answers (3)

Luc Hermitte
Luc Hermitte

Reputation: 32946

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)

Upvotes: 2

ib.
ib.

Reputation: 28954

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> )) ]

Upvotes: 5

Owen
Owen

Reputation: 39366

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

au FileType markdown inoremap <C-b> [

Upvotes: 0

Related Questions