程式扎記: [Linux 常見問題] How To Add A File Extension To vim Syntax Highlighting

標籤

2016年6月21日 星期二

[Linux 常見問題] How To Add A File Extension To vim Syntax Highlighting

Source From Here
Question
Today I was asked a question about defining custom extensions for vim syntax highlighting such that, for example, vim would know that example.lmx is actually of type xml and apply xml syntax highlighting to it. I know vim already automatically does it not just based on extension but by looking for certain strings inside the text, like  but what if my file doesn't have such strings?

How-To
After digging around I found the solution. Take file extension .scala for example. Originally, vim can't recognize it and no syntax highlight:

# vim Account.scala



Below action will let vim to handle file extension .scala with Java syntax high-light. Add the following to
 ~/.vimrc (the vim configuration file):
  1. syntax on  
  2. filetype on  
  3. au BufNewFile,BufRead *.scala set filetype=java  
After applying it, try to edit Account.scala again:


But why and how does it work, you ask?
  1. :help au    :au[tocmd] [group] {event} {pat} [nested] {cmd}  
  2.         Add {cmd} to the list of commands that Vim will execute automatically on {event} for a file matching {pat}.  
  3. :help BufNewFile    When starting to edit a file that doesn't exist.  
  4. :help BufRead   When starting to edit a new buffer, after reading the file into the buffer.  
  5. :help filetype  will actually tell this whole story in part B.  


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!