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?

  • 1
    If you're having to use that many non-breaking spaces, something else is probably wrong. What's your ultimate goal here? What are you trying to accomplish? – Aaron Miller Aug 9 '13 at 22:02
  • If you found a way that makes life simpler, wouldn't go for it. I just want to not have to see nbsps plus I won't have to be forced to use <pre> tags whenever I'm entering code. If it's not possible then fine, I can live without it. – Segfault Aug 9 '13 at 22:12

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
| improve this answer | |
  • Thanks man. I've figured it out. au BufRead *.html so C:\mine\.vim\map_space.vim. – Segfault Aug 9 '13 at 22:33

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

| improve this answer | |
  • 1
    Thanks @FDinoff for pointing out the buffer part. The mapping kept affecting even non html files. – Segfault Aug 9 '13 at 23:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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