Configure the syntax highlighting in Vim
En Español
When we enable syntax highlighting (by using :syntax enable
), Vim
will take into consideration the extension of the file to determine the appropriate syntax highlighting rules, and if this fails it will search the contents of the file for specific patterns in order to determine the file type. But if we are working in a temporary file that we don't intend to save, or if we opened, e.g., a file with HTML
extension but we find that it contains PHP
code in it, we can change the rules of the syntax highlighting.
To select the syntax highlighting of the current document use :set filetype
, e.g. to highlight the current document as if it were a HTML
document, we use:
:set filetype=html
If you use :set filetype
alone, it will give you the syntax highlighting rules in use.
To define how an extension is to be highlighted every time that Vim
opens it, e.g. to make all html and htm files be highlighted as php files, you need to add this to your .vimrc
file:
au BufRead,BufNewFile *.html,*.htm set filetype=php
What is more, Vim
allow us to alter this behavior based on the location of the files. Say, we have two projects in our home directory, one called project_x
and one called project_y
, project_x
contains files with html
extension that are pure html
files, while project_y
contains files with html
extension that are in fact php
files. In this case we change the rules only for this directory and subdirectories:
au BufRead,BufNewFile ~/project_y/*.html set filetype=php