3

Suppose I want to make a syntax highlighting script to work with files with the following hypothetical format:

blah # blahA1B2 bla
asdf A11B453 # qwert
aaa A0B0 bbb @

That is, lines with arbitrary text, but somewhere in the line I have a string with the format A\d\+B\d\+ (A immediately followed by a number, immediately followed by B, and then another number).

Furthermore, suppose that I highlight the whole line based on another pattern (in the example I'll make it clear).

What I want is to highlight only the numbers within the pattern A[0-9]\+B[0-9]\+, without removing the current highlight from the A and B.

The following script almost solves my problem:

syn match Type '.*#.*'
syn match Macro '.*@.*'
syn match Number '[AB]\zs\d\+\ze'

What it does:

  • Highlight with green lines that have a # (this part is ok).
  • Highlight with purple lines that have a @ (this part also is ok).
  • Highlight the number following A or B (this need improvement).

The problem with my script is that it also highlights A2 and B3, but they should be together to be highlighted.

I've also worked a bit with the contains and containedin, but with no success.

3
  • Work harder at understanding containedin. Add a pattern for A11B453, then make the [AB]\zs\d\+\ze contained in it. Nov 13, 2015 at 18:34
  • I did that also, this violates the condition of not removing the previous highlighting from A and B.
    – Kira
    Nov 13, 2015 at 18:36
  • ... Which is why you make the pattern transparent. Nov 13, 2015 at 19:32

1 Answer 1

3

Apparently transparent was the missing piece of the puzzle, as @Sato points out.

The final script would be something of this sort:

syn match Type '.*#.*'
syn match Macro '.*@.*'
syn match pattern 'A\d\+B\d\+' transparent contains=num
syn match num '[AB]\zs\d\+\ze' contained
hi def link num Number

Without the transparent, A and B would lack highlighting.

For some reason adding a containedin=pattern in num's line won't work, but I didn't bother finding out why.

3
  • Nope, this still highlights all A=number and B=number. You have to use contained, not just contains. And you can safely forget about containedin. Nov 13, 2015 at 20:05
  • Right, I've added the contained part.
    – Kira
    Nov 13, 2015 at 20:21
  • Yes: without contained the num pattern is also matched at top level. Nov 13, 2015 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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