---
title: 理解 Sublime Syntax 工作原理
date: 2026-12-05
---

<iframe src="/i/sublime-syntax.html" width="100%" height="240px"></iframe>

一句话解释：Sublime Syntax 是基于维护 Context / Scope 双栈数据结构，基于正则匹配实现的文本打标签（俗称高亮）程序的语法。

经常使用 Sublime Text 的人会知道，这些标签顺便就能拿来做符号索引、特殊折叠规则（如 Markdown 标题）、快捷键生效条件、补全生效条件等编辑器核心功能，只说高亮绝对是小瞧了这玩意儿。可以说整个 Sublime Text 的核心爽点就来自于用户只要写好高亮语法和少数几个复制粘贴的小配置，就能立刻对新编程语言获得极佳的支持。

整个高亮引擎可以看作是在对源码进行**逐行、逐字节**的匹配尝试和打标。

来看下面这个简化的语法：

```yaml
contexts:
  main:
    - include: string
  string:
    - match: '"'
      scope: punctuation.definition.string.begin.json
      push: string-content
  string-content:
    - meta_scope: string.quoted.double.json
    - match: '\\\\(?:["\\\\/bfnrt]|u[0-9a-fA-F]{4})'
      scope: constant.character.escape.json
    - match: '"'
      scope: punctuation.definition.string.end.json
      pop: true
```

这里显然存在 3 个 context: `main` `string` `string-content` 和一堆 scope 通过不同的姿势声明到不同位置。我们用上面的语法去跑下面这个示例代码，看看会发生什么：

```json
{ "key": "value" }
```

结果符合预期：`"key"` 和 `"value"` 都正确被加上了高亮，我们可以想象：

1. context = `[main]`，rules = `match { /"/ }`，注意这一步我们已经把 include 展开了，代码光标来到第一行第一格
2. 对这一行逐个运行 rules，发现匹配到了一个 `"`，吃掉这个字，并执行
   - 给这个字加 scope
   - 修改 context 栈变为 `[main, string-content]`
3. context = `[main, string-content]`, rules = `match { /一串escape正则/, /"/ }`
4. 继续按 rules 顺序运行匹配，中间如果匹配到 escape 就打 scope，如果匹配到 `"` 就打 scope 并 pop context 栈，如果没匹配到就直接跳下一个字，过程中所有字都要打上 `meta_scope`

还有一个细节，行尾算一个独立的匹配目标，这样才能让那些空匹配直接 pop 的规则生效：

```yaml
- match: (?=$) # 匹配到行尾就退出，不继续污染下一行
  pop: true
```

用伪代码描述：

```py
def tokenize(syntax, lines):
  context_stack = [syntax.root_context] # 默认是 main
  scope_stack = [*syntax.root_scopes] # source.json 之类的

  for line in lines:
    cursor = 0
    while cursor <= len(line):
      top = context_stack[-1]
      # 找最先（左）匹配到的 match
      pattern, match = None, None
      for p in get_active_patterns(top):
        m = regex_search(p.regex, line, start_pos=cursor)
        if m and (not match or m.start < match.start):
          pattern, match = p, m
          if m.start == cursor: break # 正好是当前光标位置匹配到了，直接贪心
      if not match: break # 啥也没匹配到，去下一行

      # 准备执行这个 match 的 scope / context 操作
      start, end = match.start, match.end
      action = pattern.action
      # 匹配到空集，跳过这一个字防止死循环
      if start == end and not action:
        cursor = start + 1
        continue
      # 开始画画
      update_stacks(context_stack, scope_stack, start, action, top)
      draw(scope_stack, pattern, match) # 输出 (start, end) 区域的 scope

      cursor = end # 吃掉这个 token，进入下一轮匹配
```

注意到实际 sublime 还支持 `clear_scopes` `embed` `branch` 等特性，需要在全局增加几个栈来实现，这里就不赘述了。

### 参考资料

- [Go.sublime-syntax](https://github.com/sublimehq/Packages/blob/master/Go/Go.sublime-syntax)
- [`vscode-textmate`](https://github.com/microsoft/vscode-textmate)
- [`sublimate`](https://github.com/defuz/sublimate/blob/master/src/core/syntax/parser.rs)、[`syntect`](https://github.com/trishume/syntect)
