如何通过Pandoc Lua过滤器将括号引用设为小字体?
output:
html_document:
md_extensions: -ascii_identifiers
pandoc_args:
- small-parencite.lua
references:
- author:
- family: Allaire
given: JJ - family: Xie
given: Yihui - family: McPherson
given: Jonathan - family: Luraschi
given: Javier - family: Ushey
given: Kevin - family: Atkins
given: Aron - family: Wickham
given: Hadley - family: Cheng
given: Joe - family: Chang
given: Winston - family: Iannone
given: Richard
id: R-rmarkdown
issued: 2020
note: R package version 2.3
title: "rmarkdown: Dynamic Documents for R"
title-short: rmarkdown
type: book
url: "https://github.com/rstudio/rmarkdown"
- family: Allaire
- author:
- family: Xie
given: Yihui
edition: 2nd
id: knitr2015
issued: 2015
note: ISBN 978-1498716963
publisher: Chapman; Hall/CRC
publisher-place: Boca Raton, Florida
title: Dynamic Documents with R and knitr
type: book
url: "https://yihui.org/knitr/"
- family: Xie
我希望所有括号引用显示为小字体,示例如下:
This is knitr [@knitr2015].
但我不想手动添加<small>标签,希望直接保留[@citation]写法,比如:
This is knitr [@knitr2015]
注意:我希望叙述引用的字体大小保持正常,示例如下:
This is a markdown variant by @R-rmarkdown.
References
--- ## 问题分析与修正方案 你的过滤器未生效主要有以下几个问题: 1. **引用类型判断错误**:`cite.citations`是包含多个引用的数组,不是字符串,不能直接和`'NormalCitation'`比较。需要遍历数组,检查每个引用的`mode`属性——括号引用的`mode`为`'NormalCitation'`,叙述引用为`'NarrativeCitation'`。 2. **未返回修改后的内容**:代码中生成了`pandoc.Str`对象,但没有将其作为返回值,最终还是返回原始的`cite`对象,等于没有修改。 3. **内容拼接方式错误**:`cite.content`是Pandoc的Inline元素列表,不能直接转换为字符串拼接,需要用Pandoc原生的RawInline元素插入HTML标签。 4. **Pandoc参数错误**:在R Markdown的YAML配置中,指定Lua过滤器需要使用`--lua-filter=`前缀,原配置缺少该前缀,导致Pandoc无法识别过滤器文件。 ### 修正后的`small-parencite.lua` ```lua Cite = function(cite) -- 仅在HTML或revealjs格式下应用修改 if not FORMAT:match 'html' and not FORMAT:match 'revealjs' then return cite end -- 检查当前Cite元素是否全部为括号引用 local is_parencite = true for _, cit in ipairs(cite.citations) do if cit.mode ~= 'NormalCitation' then is_parencite = false break end end if is_parencite then -- 用HTML的small标签包裹整个引用内容 return pandoc.RawInline('html', '<small>') .. cite.content .. pandoc.RawInline('html', '</small>') else -- 叙述引用保持原样 return cite end end
修正后的R Markdown配置
修改test.md的YAML头部,补全Lua过滤器的参数前缀:
output: html_document: md_extensions: -ascii_identifiers pandoc_args: - --lua-filter=small-parencite.lua
直接使用Pandoc编译的命令
如果不用R Markdown,直接用Pandoc命令行编译:
pandoc test.md --lua-filter=small-parencite.lua -o test.html
内容的提问来源于stack exchange,提问作者Carlos Luis Rivera
相关产品推荐
相关产品推荐

