如何在Quarto与RStudio中创建可引用的类定理Hypothesis?
实现Quarto中可引用的Hypothesis元素
问题分析
你当前的Lua脚本仅修改了Hypothesis的显示格式,但未对接Quarto的交叉引用系统,因此无法实现原生定理那样的可引用性。要解决这个问题,需要让Quarto将Hypothesis识别为可引用的交叉引用类型,同时正确渲染格式并关联计数器。
解决方案
步骤1:配置自定义交叉引用类型
在Quarto文档(或全局_quarto.yml配置文件)中添加自定义交叉引用规则,让Quarto识别hypothesis类型:
crossref: custom: hypothesis: label: "Hypothesis" prefix: "H" # 可选,引用时的前缀,例如H1、H2 counter: theorem # 可选,与定理共用计数器,独立计数则删除此行
步骤2:替换为正确的Lua过滤器
替换你现有的Lua脚本为以下版本,它会处理hypothesis类的Div,添加Quarto交叉引用所需的属性,并规范渲染格式:
function Div(div) if div.classes:includes("hypothesis") then -- 获取自定义标签(无则用默认值) local label = div.attributes.label or "Hypothesis" -- 生成引用ID(手动指定ID则优先使用) local ref_id = div.attributes.id or "hyp-" .. pandoc.utils.stringify(div.content[1]):lower():gsub("%s+", "-") -- 构建标题部分:标签 + 自动计数器 + 标题文本 local title_block = pandoc.Para({ pandoc.Strong(label .. " "), pandoc.Span({ pandoc.Str("") }, { class = "quarto-xref-counter" }), pandoc.Str(": "), div.content[1] }) -- 提取描述内容(移除标题后的剩余部分) local desc_content = div.content:slice(2) -- 重构Div结构 div.content = { title_block, pandoc.Div(desc_content, { class = "hypothesis-description" }) } -- 添加Quarto交叉引用识别属性 div.attributes["data-reference-type"] = "hypothesis" div.attributes["data-reference-id"] = ref_id div.classes:insert("quarto-xref-target") return div end return div end
步骤3:在文档中使用Hypothesis
在Quarto文档中按以下格式编写可引用的Hypothesis:
:::{hypothesis} 用户行为假设 用户在完成引导流程后,留存率会提升至少30%。此结论基于过往3次产品迭代的用户数据统计。 ::: 可以像引用定理一样调用:@hyp-用户行为假设
关键说明
- 配置自定义交叉引用后,Quarto会自动管理计数器,无需手动维护
hypothesis_counter变量。 - Lua过滤器添加的
quarto-xref-target类和data-*属性,是让Quarto识别为可引用元素的核心。 - 引用ID支持手动指定,例如
:::{hypothesis} 用户行为假设 id="retention-hyp",之后用@retention-hyp引用即可。
内容的提问来源于stack exchange,提问作者Irfan Malick
相关产品推荐
相关产品推荐

