如何为代码块添加标题并设置含章节号的自动编号样式
解决方案
核心思路
通过Typst的计数器功能结合章节编号,为每个Python代码块生成带章节前缀的自动编号标题,具体实现逻辑如下:
- 定义代码块专用计数器,设置为随章节标题重置
- 在代码块的展示规则中,获取当前章节编号和递增后的代码块编号
- 将生成的标题添加到代码块上方
修改后的完整Typst代码
#set heading(numbering: "A.") #set counter(code-counter, reset: heading) #show raw.where(lang:"python"): it => { let chapter-num = counter(heading).display() let code-num = counter(code-counter).increment() par( justify: false, block( fill: rgb("#f0fef0"), inset: 1.5em, width: 99%, text( [*Program #chapter-num.#code-num*], it ) ) ) } = first section == first.first section #figure( ```python print("hello,world") ```)<program-hello-world> = second section == second.first section #figure( ```python print("another code block") ```)<program-another> In the program (@program-hello-world), a demo program was given. blabla
代码细节说明
#set counter(code-counter, reset: heading):创建code-counter计数器,指定每当章节标题更新时重置,确保每个章节内的代码块从1开始编号counter(heading).display():获取当前章节的格式化编号(如"A"、"B")counter(code-counter).increment():递增代码块计数器并返回当前编号*Program #chapter-num.#code-num*:生成加粗的带章节前缀的代码块标题,匹配预期效果
内容的提问来源于stack exchange,提问作者Jilong Yin
相关产品推荐
相关产品推荐

