You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R Markdown中使用Lua过滤器实现带引文文本的字体颜色设置

我想知道是否可以在r-markdown中使用或适配Lua过滤器,实现对采用r-markdown语法书写的包含引文的内容设置字体颜色。例如我尝试复现R Markdown Cookbook中的代码,在[...]块内添加引文后得到了如下结果:

运行结果示意图

可使用以下R代码复现相同的PDF文档问题:

# 加载依赖包
library(rmarkdown)

# 创建参考文献文件
my_bib <- file.path(tempdir(), "my-bib.bib")
cit_R <- "
@Manual{R,
  title = {R: A Language and Environment for Statistical Computing},
  author = {{R Core Team}},
  organization = {R Foundation for Statistical Computing},
  address = {Vienna, Austria},
  year = {2021},
  url = {https://www.R-project.org/},
}
"
writeLines(cit_R, my_bib)

# 创建带引用的Rmd文件
my_Rmd <- file.path(tempdir(), "my-Rmd.Rmd")
text_Rmd <- '
---
title: "用Lua过滤器设置文字颜色"
output: 
  pdf_document: 
    pandoc_args: ["--lua-filter=color-text.lua"]
bibliography: my-bib.bib
---

```{cat, engine.opts = list(file = "color-text.lua")}
Span = function(el)
  color = el.attributes["color"]
  -- 如果没有颜色属性则直接返回原内容
  if color == nil then return el end
   
  -- 适配HTML格式:转成<span style="color: red;"></span>
  if FORMAT:match "html" then
    el.attributes["color"] = nil
    el.attributes["style"] = "color: " .. color .. ";"
    return el
  -- 适配LaTeX格式
  elseif FORMAT:match "latex" then
    el.attributes["color"] = nil
    -- 用LaTeX原生颜色命令包裹内容
    table.insert(
      el.content, 1,
      pandoc.RawInline("latex", "\\textcolor{"..color.."}{")
    )
    table.insert(
      el.content,
      pandoc.RawInline("latex", "}")
    )
    return el.content
  -- 其他格式直接返回原内容
  else
    return el
  end
end

玫瑰是[红色加粗]{color="red"}的

普通引用:ABC 在 @R 中提到

带颜色的引用:[ABC 在 @R 中提到]{color="red"}

参考文献
' writeLines(text_Rmd, my_Rmd)
渲染文档

render(
input = my_Rmd,
output_file = file.path(tempdir(), "test1.pdf")
)
browseURL(file.path(tempdir(), "test1.pdf"))

内容的提问来源于stack exchange,提问作者agila
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 06:54:03