1

Let's think we are going to render html file. We highlight <a> and <img> tags, so a and img will be highlighted as Keywords. We assume <a> accepts attribute href but not src, while <img> accepts attribute src not href. So in <a href="place1" src="place2">, href will be highlighted as, let's say, Identifier, while src will not be highlighted; while in <img href="place1" src="place2">, src will be highlighted but href will not be highlighted. Is there a way of implementing this via syntax region or syntax match?

1

You can do this with the :syntax command's contains, containedin, and contained keywords. See :help syn-contains, :help syn-containedin and :help :syn-contained for the documentation on these, but briefly, the technique is to

  1. Use either contains to allow an outer group to contain an inner group or containedin to allow an inner group to be contained within an outer group,
  2. Use contained to only activate an inner group when it is contained within another.

Here a basic example of one way to achieve what you describe in your question (with extremely simplified regular expressions—the point is to demonstrate the use of the containedin and contained keywords, not the matching of tags. If you need help with that, maybe take a look at Vim's included HTML syntax file: e $VIMRUNTIME/syntax/html.vim).

syntax match myAnchorTag /<a.*a>/
syntax match myImgTag /<img.*img>/

syntax match myHrefAttribute containedin=myAnchorTag contained /href/
syntax match mySrcAttribute containedin=myImgTag contained /src/

highlight link myHrefAttribute Identifier
highlight link mySrcAttribute Identifier

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.