Rust in Everything
基于 typst 0.15.1

context 表达式、计数器 counter 与状态 state

主线位置:内核自省第一站 —— 理解「求值期(Eval)不知道自己将来排在第几页,只有进入布局期(Realize/Layout)才有 context」。

1. 为什么直接调 #counter(page).get() 会报错?

很多刚接触 Typst 的开发者想在正文里读取当前页码或当前字号 text.size,直接写 #text.size 或 #counter(page).get(),结果编译器立刻报错:

error: can only be used when context is known
  ┌─ test.typ:1:2
  │
1 │ #counter(page).get()
  │  ^^^^^^^^^^^^^^^^^^^
  │
  = hint: try wrapping this in a `context` expression
  = hint: the `context` expression should wrap everything that depends on the function's result

为什么要强制包一层 #context counter(page).get()?回顾我们在 01-overview/why-typst 读过的 crates/typst/src/lib.rs:123:

  1. 在 typst_eval::eval() 阶段,你的脚本只会被从上到下求值一次。此时你定义的一段内容 #let my-box = [当前页码:...] 甚至可能被同时放到第 1 页和第 10 页!在还没有开始排版分页之前,哪来的「当前页码」和「当前生效的 StyleChain 字号」?
  2. 加了 context 关键字后,context expr 在求值阶段不会立即执行 expr,而是把 expr 打包成一个惰性的 ContextElem 节点放进内容树。直到 typst-realize 和 typst-layout 把这个节点真正摆放上某一个具体页面、确定了它的物理坐标 Location 和当前样式链 StyleChain 时,才会注入 Context 触发求值!
sequenceDiagram
  participant Eval as 1. typst_eval::eval()
  participant Tree as Content 树
  participant Realize as 2. typst_realize / layout
  Eval->>Tree: 遇到 `context counter(page).get()`<br/>不执行内部代码,生成惰性 ContextElem 闭包节点
  Tree->>Realize: 节点被排入第 3 页 (Location 确定) 和当前 StyleChain
  Realize->>Realize: 注入 Context(location, styles) 触发闭包求值 -> 得到 (3,)
📝NOTE
冷知识:context 是如何在 Typst 0.11 取代回调地狱 locate(loc => ...) 的?

在 Typst 0.10 及更早版本中,要读位置必须写 locate(loc => ...),要读样式必须写 style(styles => ...),如果既要读页码又要读当前字号,就得写成两层嵌套回调 locate(loc => style(styles => ...))。在 2024 年发布的 Typst 0.11(PR #3605)中,核心团队引入了统一的 context 关键字,将 here()(当前位置)与元素属性读取(如 text.size、page.width)全部合并进隐式上下文环境,一举消除了回调嵌套!

2. 计数器 counter:内置元素计数与自定义定理编号

在 crates/typst-library/src/introspection/counter.rs 中,counter 可以绑定到三类键(CounterKey):

  1. 页面计数器:counter(page);
  2. 任意内置元素计数器:counter(heading)、counter(math.equation)、counter(figure.where(kind: image));
  3. 自定义字符串键计数器:counter("theorem")(对标 LaTeX 的 \newcounter{theorem})。
操作Typst 写法说明
步进 +1#counter("theorem").step()在文档当前位置插入一个 CounterUpdateElem 步进标记(支持 level: 2 多级编号)
直接渲染当前值#context counter("theorem").display("1.1")读取当前位置的值并按模式格式化输出
读取原始数字数组#context counter(heading).get()返回数组,如在第 2 章第 3 节返回 (2, 3)
读取全文最终值#context counter(page).final().first()返回文档末尾的最终页码整数
重置或修改计数#counter(page).update(1) 或 .update(n => n + 2)从当前位置起重置或按函数更新计数器

看一个**定理编号自动跟随一级章节号重置(如「定理 1.1」「定理 1.2」,到了第 2 章自动变成「定理 2.1」)**的经典实现:

#set heading(numbering: "1.1")
#let thm-counter = counter("theorem")

// 每当遇到一级标题时,把定理计数器重置为 0
#show heading.where(level: 1): it => {
  thm-counter.update(0)
  it
}

#let theorem(title: none, body) = {
  thm-counter.step()
  block(width: 100%, fill: luma(246), inset: 8pt, radius: 4pt)[
    *定理 #context {
      let chap = counter(heading).get().first()
      let num = thm-counter.get().first()
      [#chap.#num]
    }#if title != none [(#title)]:* #body
  ]
}

= 代数结构
#theorem(title: "Lagrange")[有限群 $G$ 的子群阶数整除 $|G|$。]

3. 状态 state:跨章节传递任意类型的数据

counter 只能存非负整数数组(SmallVec<[u64; 3]>);如果你想在文档各处累积一个浮点数(比如试卷各道大题的分值总和)、一个字符串列表或一个字典,就用 state("key", initial_value)(见 crates/typst-library/src/introspection/state.rs):

#let total-score = state("score", 0)
#let problem(pts, body) = {
  total-score.update(s => s + pts)
  [*【#pts 分】* #body]
}

// 在卷首直接读取卷末累加出的总分(得益于多遍自省收敛)!
本试卷满分:*#context total-score.final() 分*。

#problem(10)[简述 Typst 的三种语法模式。]

#problem(15)[推导高斯积分公式。]

小结

  • 凡是依赖「我排在哪一页(here() / counter / state / query)」或「当前外层设置了什么样式(text.size)」的代码,一律包在 context { ... } 或 #context ... 中。
  • 计数用 counter,存任意结构化数据用 state。

💬 关联讨论

加载中...