I try to color a word depending on its prior use. For example I have the following text file

a : Type1

b : Type2

And now I will take about a and b

So Ideally I would like to define Type1 within the syntax file so that a gets highlighted whenever used afterwards in the text. Is this possible?


To accomplish this you'll need to write an expression that matches your var: TypeN situation.

let type1Match = '\(.*\): Type1'

You can find all matches and store them in a list by using vimgrep and getqflist().

function FindMatches(regex)
    silent execute "vimgrep /" . a:regex . "/j %"
  catch /^Vim\%((\a\+)\)\=:E480/
    return []
  return split(join(map(copy(getqflist()), 'matchlist(v:val.text, a:regex)[1]')))

This function returns a list containing all match cases or and empty list if none are found. To find all cases of var: Type1 use

:echo FindMatches(type1Match)

The last step is to execute syntax match on this list.

execute "syntax match type1Keyword \"\\<\\(" . join(FindMatches(type1Match), '\|') . "\\)\\>\""

You can add this into your syntax file and when the file is saved and loaded it will execute.

One thing to note. This will highlight all cases of the match value. In your example the a in a: Type1 and in And now I will talk about a and b will both be highlighted. You can make your syntax highlighter smarter by highlighting the specific a: Type1 situation differently but requires a match case of .*:\s*Type[0-9].

  • 1
    Thank you so much, this helps me a lot to quickly scan trough my files. – magu_ Apr 30 '15 at 16:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.