Sublime Text 4: custom syntax highlight for specific YAML property names

176 views Asked by At

I am writing a lot of OPEN API specifications in YAML, which contain some custom properties. Those properties are used by a script generating documentation from the specifications. Anyways, I would like to have a specific color for those properties, to make it easier to spot them in the code.

This is what I want to achieve:

Results preview

I tried to extend the Sublime Text YAML syntax highlighting to include those property names, but so far I did not succeed: no color change. See below what I have done so far, hopefully someone can spot my mistake(s).

Custom YAML .sublime-syntax file:

%YAML 1.2
---
name: YAML custom
scope: source.yaml
version: 2.1

file_extensions:
  - yaml
  - yml

extends: Packages/YAML/YAML.sublime-syntax

contexts:
  custom-xtra:
    - match: '(\@xtra(\w)*)'
      scope: custom.extra.yaml
    - match: '(\@template_(\w)*)'
      scope: custom.extra.yaml

Color setting in the .sublime-color-scheme file:

{
    "name": "YAML custom",
    "scope": "custom.extra.yaml",
    "foreground": "Turquoise"
},
1

There are 1 answers

1
Keith Hall On BEST ANSWER

The reason why this doesn't work, is because you have introduced a new context, custom-xtra, which isn't referenced anywhere, so it never gets used.

Generally the way to extend a syntax definition with custom scoping is to open your file and have it highlighted with the original syntax definition, and to put the text caret on some token you want to highlight differently. In your case, somewhere in the '@template_resp' text.

Then, from the Tools menu -> Developer -> Show Scope Name. You will see a popup showing the current scope by the caret and below that, a Context Backtrace. This tells you the scope stack at that point in the file.

Here, we can see that the rules highlighting that piece of text come from a context called flow-scalar-single-quoted-body in the Packages/YAML/YAML.sublime-syntax file.

Therefore, including your custom-xtra context from flow-scalar-single-quoted-body will help ensure your match patterns take effect.

%YAML 1.2
---
name: YAML custom
scope: source.yaml.custom
version: 2

file_extensions:
  - yaml
  - yml

extends: Packages/YAML/YAML.sublime-syntax

contexts:
  custom-xtra:
    - match: '\@xtra\w*'
      scope: custom.extra.yaml
    - match: '\@template_\w*'
      scope: custom.extra.yaml

  flow-scalar-single-quoted-body:
    - meta_prepend: true
    - include: custom-xtra