Search code examples
vimvim-syntax-highlighting

Vim: load syntax file from local directory


I would like to be able to create a vim syntax file for a specific project, to highlight identifiers unique to that project. I could, of course, install a syntax file in $HOME/.vim/after/syntax/*.vim but I want to set this up as a per-folder configuration. The project syntax file should add on to the existing syntax file, not replace it. I also want a general solution that automatically loads a local file it if exists, and doens't need to be configured for specific directories in .vimrc or in a plugin.

Edit: This is similar to the question Vim: apply settings on files in directory but that deals with settings in .vimrc, which is loaded before syntax files. Syntax files conventionally wipe out predefined syntax information, so it is not useful to set this infomration in .vimrc, and the techniques to load alternate .vimrc files are therefore not helpful. I don't know of a way to trigger additional "after" files to be loaded. I have seen this question asked before but no answers except those pertaining to .vimrc.

I have configured local .vimrc files using :set exrc and have verified that these files get loaded, but syntax definitions in .vimrc get overwritten by syntax files that are loaded later on. (And I want project syntax to add to standard syntax, not replace it.)

Is a similar functionality, whether a vim feature or a plugin, that can be used for local "after" syntax files?


Solution

  • I adapted a solution based on this answer: https://stackoverflow.com/a/13192721/2150289. While I'd still like to explore other options if they exist, this works. Leaving this as a separate question and answer, since .vimrc answers don't apply, and it is not obvious that this is possible for a syntax file.

    In my project directory I have a local .vimrc that sets tabs and so forth. This is loaded by set exrc or any other method that loads a local .vimrc.

    To load "after" files, you can daisy-chain them to an "after" file that gets loaded in your .vim/after directory. For example, I have a .vim_syntax_cpp.vim with C++ syntax specific to the project. I place this is the project directory:

    PROJECT/
      .vimrc           # gets loaded by set exrc
      .vim_syntax_cpp  # daisy chained from .vim/after/syntax/cpp.vim
      Makefile
      foo.cpp
      bar.cpp
    

    In ~/.vim/after/syntax/cpp.vim, I place this code:

    " load syntax file if it exists in the
    " current directory or parent directory
    if filereadable(".vim_syntax_cpp.vim")
        source .vim_syntax_cpp.vim
    elseif filereadable("../.vim_syntax_cpp.vim")
        source ../.vim_syntax_cpp.vim
    endif
    

    I have verified that this loads the local syntax file and adds them to existing syntax definitions.

    This method has limitations; see the comments in the linked answer.