Is it possible to have per file type key mapping in Vim

Is it possible to have per file type key mapping in Vim

I just discovered lately that when you enter a non breaking space(nbsp) in an HTML document
and set the encoding to utf-8, you wont' have to enter nbsp; repeatedly to format text. I at first
thought, hey, why don't I map this to the space bar like so :imap <SPACE> <C-R>=nr2char(160)<CR>.
I later edited my .vimrc and when I restarted Vim, I got dozen errors about some function needing a
name even though I had given it. I realised that the nbsp is not treated as a space(duh) even though it
looks like one. So, I thought a better way would be to have a per file type mapping, so that I when I am editing a html document, the space inserts an nbsp and a normal space chr(32) when editing any other file.
How do I do this?

Antwort1

The au[tocommand] command takes a FileType event that runs when filetype has been set (e.g. on startup with a filename). E.g. in ~/.vimrc:

au Filetype python source ~/.vim/scripts/python.vim

Antwort2

You can use filetype plugins which only get sourced when the file is of a certain filetype. To set this up create the file ~/.vim/ftplugin/html.vim and put your commands in this file. If there is already a file you could create a directory called html and then every file in the directory will be sourced. Take a look at :h ftplugin-name for other naming options. (If the directories do not exist create them)

All that you need to have in your vimrc is filetype plugin indent on (indent really isn't necessary for this but normally useful).

It might also be important to make the mapping local to the buffer only by using

map <buffer>

It might also be useful to look over :h ftplugin and :h filetype

verwandte Informationen