5

Take markdown file as an example. I often found that some downloaded files suffixed with .md (rather than .markdown) can be recognized as markdown file, and syntax-highlighted as such. However, it won't work if I plainly create a file suffixed with .md and open it. I have to :set syntax=markdown so that Vim can highlight the file properly.

Also, I noticed that the syntax in some system files with strange suffix such as .list can be magically highlighted. For example, on my Ubuntu system there is a file /etc/apt/sources.list. Upon opening it, Vim can correctly recognize the syntax in the file is debsources. But it won't be so if I copy the file to ~/Desktop and open again.

Another example, in the same directory /etc/apt/apt.conf.d, there are files with no extension at all, and they can all be recognized having aptconf syntax.

So how does Vim determine which syntax to use for highlighting when encountering strange extensions or no extension at all?

9

In the file recognition procedure used to detect what syntax highlighting to use, there can be a few kinds of checks. The most known one is checking the the file extension. This is done by a command of the following structure:

au BufRead,BufNewFile *.my             setfiletype my-type

Another way, used for makefiles for example, is assigning the auto-cmd too the file name.

The methods that confused you are checking the file path, and checking the file contents in order to detect the file type.

In order to check file contents you can write code similar to this:

if did_filetype()       " filetype already set..
   finish                " ..don't do these checks
endif
if getline(1) =~ '^#!.*\<mine\>'
  setfiletype mine
elseif getline(1) =~? '\<drawing\>'
  setfiletype drawing
endif

More info can be fond in :help new-filetype

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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