Search code examples
vimsyntaxtypedefhighlighting

vim syntax highlighting - flexible recognition of custom keywords/types (typedef)


In my C++ code, I use customized types a lot like

typedef double type_scalar
typedef std::complex<type_scalar> type_complex
etc.

where I follow the convention that i always put type_* in front of my type names. I use (G)VIM editor and would like it to syntax-highlight my custom types just like the built-in ones (without explicitly listing them all in the syntax file).

I searched the web for possible solutions and tried putting everything from regex expressions like

syn keyword cppType \<type_.*/

and

syn keyword cppType type_[^\ ]*\

to

syn match typedefSuffix     '\a\+'
syn keyword cppType     type_ nextgroup=typedefSuffix

in my ~/.vim/syntax/cpp.vim file, but I wasn't able to get the desired result, i.e. to get every instance of the form type_whatever highlighted.

Can anyone help?


Solution

  • syn keyword cppType \<type_.*/
    

    That one looks promising, except for:

    • :syn keyword does not take a regular expression, only literal keywords; you need :syn match (and enclose the regular expression in delimiters)
    • The .*/ will match everything up to the last / in the line; you rather need \w\+ to restrict the match to the remainder of the identifier, and \> to enforce the end of the keyword. Ergo:
    syn match cppType "\<type_\w\+\>"
    

    Put that into ~/.vim/after/syntax/cpp.vim, and you should be good to go.

    Your problems could have been resolved via the excellent documentation. Learn how to look up commands and navigate the built-in :help; it is comprehensive and offers many tips. You won't learn Vim as fast as other editors, but if you commit to continuous learning, it'll prove a very powerful and efficient editor.