Sublime Forum

Syntax highlighting only up to specific characters

#1

Hi, I maintain https://github.com/jonschlinkert/sublime-monokai-extended and https://github.com/jonschlinkert/sublime-markdown-extended, and I’m trying to figure out how to highlight yaml front matter, which is delimited by --- (open and close).

This currently works, but the problem is that when another --- is used anywhere in the document, ST thinks that another front-matter block is being created.

How do I stop after the closing delimiter?

0 Likes

#2

Have a main and main-after-frontmatter context; main checks for front matter and sets (not pushes) something like [main-after-frontmatter, front-matter] after encountering ---. In front-matter you pop when you encounter another ---. Then main-after-frontmatter does the same as main except it doesn’t check for front matter.

2 Likes

#3

thanks, that’s great. I think I get the idea in principle.

Any chance you know of a reference somewhere that explains how that works in the language syntax files (pushing/popping, etc)? I’m familiar with these things as programming concepts, but I’m struggling to see how that works in a declarative syntax file. Is the syntax file just linearly evaluated from top to bottom?

0 Likes

#4

Check out this toy syntax:

%YAML 1.2
---
scope: source.toy
contexts:
  main:
    - match: -{3}
      scope: keyword.control.frontmatter.toy
      set: [main-after-frontmatter, frontmatter]
    - include: main-after-frontmatter
  frontmatter:
    - match: -{3}
      pop: true
      scope: keyword.control.frontmatter.toy
  main-after-frontmatter:
    - match: -{3,}
      scope: support.function.toy

Example:

Hope this helps!

EDIT: Think of there being an imaginary context stack. You push and pop contexts with this imaginary context stack with push, pop and set, where set just means “first pop then push”. We start out in the main context. We then match three dashes, so we “set”, that is, “pop and then push”, two new contexts on the stack, namely main-after-frontmatter and frontmatter. Imagine then that frontmatter is at the top of the stack. This means the match rules from the frontmatter context will take place for the characters ahead. When it encounters three dashes it’ll pop the frontmatter context off the context stack, and we are left with only one context, namely main-after-frontmatter.

3 Likes

#5

Think of there being an imaginary context stack. You push and pop contexts with this imaginary context stack with push, pop and set, where set just means “first pop then push”

Perfect! That’s just what I needed, thank you!

1 Like