Unable to set syntax highlighting automatically in Vim


I have the following in my .vimrc

syntax on
filetype plugin indent on       # Thanks to Jeremy

I run

vim ~/.vimrc

I get the right syntax highlighting.

I source many files in my .vimrc. My .vimrc is a like a roadmap for me where I navigate by


The problem occurs when I navigate to a file which I have sourced: no colors.

All my sourced files contain the word Vim in their PATHs.
It may be possible to use this fact in solving the problem.

How can you provide a syntax highlighting automatically for the sourced files?

Best Solution

Do the files in question end in ".vim"? If not, then vim's filetype detection may not be able to determine that these files contain vim-script. You can either rename the files so that they end in .vim, or add an autocommand to set the filetype appropriately.

To do the latter, you can add something like this to your .vimrc:

au! BufNewFile,BufRead PATTERN set filetype=vim

replacing "PATTERN" with a file pattern that will match the files in question.


See :help autocmd-patterns for how the patterns work:

The file pattern {pat} is tested for a match against the file name in one of
two ways:
1. When there is no '/' in the pattern, Vim checks for a match against only
   the tail part of the file name (without its leading directory path).
2. When there is a '/' in the pattern,  Vim checks for a match against the
   both short file name (as you typed it) and the full file name (after
   expanding it to a full path and resolving symbolic links).

In particular, note this example:

Note:  To match part of a path, but not from the root directory, use a '*' as
the first character.  Example: >
    :autocmd BufRead */doc/*.txt    set tw=78
This autocommand will for example be executed for "/tmp/doc/xx.txt" and
"/usr/home/piet/doc/yy.txt".  The number of directories does not matter here.

In your case you probably want something like:

au! BufNewFile,BufRead */Vim/* set filetype=vim