Sublime Forum

Custom syntax: highlight JS with `}` as a pop symbol

#1

Example syntax I’m trying to highlight looks like this:

...

script {
  javascript goes here
}

...

The problem is that javascript inside the script section can (obviously) also contain }. Which means that I can’t simply do:

- match: 'script \{'
  push: "Packages/JavaScript/JavaScript.sublime-syntax"
  with_prototype: 
    - match: '\}'
      pop: true

What I came up with is the following:

  - match: 'script \{'
    push: script

script:
  - match: ''
    set: Packages/JavaScript/JavaScript.sublime-syntax
    with_prototype: 
      - match: \{
        push: script
      - match: \}
        pop: true

This works… to an extent. Since parser consumes { and }, JSON objects are not detected. Even worse - sometimes javascript parser also doesn’t like what I’m doing:

This is probably happening because the text field1: "value" is not a valid javascript.

Am I missing something and there’s an easier way to pass highlighting to the JS highlighter and get back when JS pops out its last context?

0 Likes

#2

You don’t need to push the javascript context, but can just include it. This should work with your example:

    - match: '(script)\s*({)'
      captures:
        1: keyword.control.test
        2: punctuation.section.braces.begin.test
      push:
        - match: '}'
          scope: punctuation.section.braces.end.test
          pop: true
        - include: "Packages/JavaScript/JavaScript.sublime-syntax"
```

You may also use `- include: scope:source.js` to include javascript.

*Edit: Changed match order*
2 Likes

#3

it may be best to have the pop pattern match first, in case the JS syntax has (or will have in future) stray close bracket detection

2 Likes

#4

That seems to work! Thank you so much :thumbsup:

0 Likes