25

I can enable syntax highlighting for a file that has an extension that is unknown to vim by doing the following

set syntax=c

Every time I switch tabs however, I have to renter the command. Is there any way to let vim know that a file with an extension .xyz should be coloured with C syntax?

Samaursa
  • 16,527
  • 21
  • 89
  • 160

4 Answers4

26

Put this at the end of your .vimrc (I'm assuming you have autocommands enabled).

autocmd BufRead,BufNewFile *.xmlx set filetype=xml
Dan Loewenherz
  • 10,879
  • 7
  • 50
  • 81
  • 4
    Hmm... how is this answer answered on December 8, 2009 when the question was asked March 25, 2011? +1 nonetheless... – Samaursa May 10 '12 at 17:00
  • Whoa, very weird... I think this must be an SO bug. This answer must have been for another question, otherwise I wouldn't have mentioned XML. – Dan Loewenherz May 10 '12 at 17:20
  • 2
    @Samaursa This question was merged from http://stackoverflow.com/q/1869777/427545 – Lekensteyn Oct 05 '12 at 21:55
  • I don't recommend using BufEnter. That's triggered whenever focus enters the buffer. As a result, Vim will re-parse the file every time you switch to it. For some syntaxes and files, this can be quite slow. – Justin L. Feb 28 '13 at 02:38
  • @JustinL. thanks for the tip--BufRead seems to be a better idea. – Dan Loewenherz Feb 28 '13 at 03:05
20

In your home directory, create the .vim/ftdetect/xyz.vim:

au BufRead,BufNewFile *.xyz set filetype=c    " to overrule an existing filetype
au BufRead,BufNewFile *.xyz setfiletype c     " to set it only if no filetype has been detected for this extension
zarkdav
  • 679
  • 5
  • 11
19

With autocommand. E.g.

au BufNewFile,BufRead *.xyz setf c
Lars Noschinski
  • 3,667
  • 16
  • 29
3

You can set it in the vim config file:

http://beerpla.net/2008/04/02/how-to-add-a-vim-file-extension-to-syntax-highlighting/

Robert Martin
  • 73
  • 1
  • 6
  • http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers – Marco Apr 07 '15 at 09:30