如何在Quarto中为习题、示例等环境设置共享计数器?
解决Quarto多自定义环境共享章节连续计数器的问题
完全可以实现!通过Quarto的自定义交叉引用配置,把示例、习题、备注、定理、定义这五个环境绑定到同一个共享计数器即可,具体步骤如下:
1. 在_quarto.yml中配置共享计数器
在项目根目录的_quarto.yml文件里添加自定义交叉引用规则,给五个环境指定同一个计数器名称(比如shared):
crossref: custom: - type: example prefix: "Example" counter: shared ref-type: exm label: "Example" - type: exercise prefix: "Exercise" counter: shared ref-type: exr label: "Exercise" - type: remark prefix: "Remark" counter: shared ref-type: rmk label: "Remark" - type: theorem prefix: "Theorem" counter: shared ref-type: thm label: "Theorem" - type: definition prefix: "Definition" counter: shared ref-type: def label: "Definition"
这里的核心是counter: shared——所有设置了这个字段的类型,都会共用同一个计数器,且默认会在每个章节开头重置计数,刚好匹配你要的章节内连续编号需求。
2. 在文档中使用自定义环境
配置完成后,在qmd文档里用对应的类名定义环境,并设置id用于交叉引用:
The first example is @exm-1. ::: {#exm-1 .example} This should be Example 1.1. ::: It is followed by the first exercise, @exr-1 ::: {#exr-1 .exercise} This should be Exercise 1.2. ::: Next is a theorem, @thm-1 ::: {#thm-1 .theorem} This is Theorem 1.3. :::
3. 渲染效果
这样渲染后,五个环境会按出现顺序在章节内连续编号:
- Example 1.1
- Exercise 1.2
- Theorem 1.3
以此类推,完全符合你要复刻的书籍编号规则。
如果你之前用提示框尝试过,这种自定义交叉引用的方式更原生、更稳定,不需要额外的hack就能实现共享计数的需求。
内容的提问来源于stack exchange,提问作者Achim Zeileis
相关产品推荐
相关产品推荐

