clinuxvimvirc

vi/vim - custom formatting depending on presence of special file or tag inside code


Question

Is there a simple/reliable way to have VIM, on a project/directory specific base, either detect a special file (ie: custom .vimrc with a couple settings), or to change run-time settings based on the presence of a special tag/string/hash in a comment at the beginning of a source (.c) or header (.h) file? The string/hash must map to a function/setting in the .vimrc file, and must not contain the actual settings themselves.


Background

I have a mutli-developer project where we all have a common set of code style settings for our various editors ( and , primarily), and we all adhere strictly to these settings, such as newline style (CR versus CR+LF), indentation (length, hard-tabs versus expanded-as-spaces), and so on.


Problem

I'm creating a few new projects that, for reasons beyond our control (ie: static code analysis tool we have to use), will require different style settings than ours. There are ways to bypass this in the static code analysis tool, but there's a non-technical/legal requirement that we avoid disabling "features" of this tool.

For each of these new projects, I would like to somehow make / aware of some special flag, either by the presence of a special file in the root of the project's directory structure, or by a special keyword/tag/hash/etc I could put inside a /* C-style block comment */. When / is aware of the presence of this "trigger", I would want it to invoke a function to override the style settings for newlines, indentation, etc. If this is possible, is it also possible to have several, mutually exclusive such "triggers" so that everyone has a common .vimrc and the project determines which style to utilize?


Question - redux

Is there a straightforward way to accomplish this?


Solution

  • ... to change run-time settings based on the presence of a special tag/string/hash in a comment at the beginning of a c source (.c) or header (.h) file?

    Yes, they're called modelines. http://vim.wikia.com/wiki/Modeline_magic

    They can appear at the start or end of files.

    An example from some C sources of mine:

    /* vim:ft=c:expandtab:sw=4:ts=4:sts=4:
     */
    

    See :help modeline in vim for more info.