简体   繁体   中英

Use lua filter in Rmarkdown for font color text with citations

I was wondering if it's possible to use/readapt Lua filters in r-markdown to get font colours when using citations with r-markdown syntax. For example, when I try to replicate the code from R Markdown Cookbook and add a citation inside the [...] block, I get the following result:

在此处输入图像描述

The following R code can be used to replicate the same pdf document:

# packages
library(rmarkdown)

# Create a citation file
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)

# Create an Rmd file with a reference
my_Rmd <- file.path(tempdir(), "my-Rmd.Rmd")
text_Rmd <- '
---
title: "Color text with a Lua filter"
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 no color attribute, return unchanged
  if color == nil then return el end
   
  -- transform to <span style="color: red;"></span>
  if FORMAT:match \'html\' then
    -- remove color attributes
    el.attributes[\'color\'] = nil
    -- use style attribute instead
    el.attributes[\'style\'] = \'color: \' .. color .. \';\'
    -- return full span element
    return el
  elseif FORMAT:match \'latex\' then
    -- remove color attributes
    el.attributes[\'color\'] = nil
    -- encapsulate in latex code
    table.insert(
      el.content, 1,
      pandoc.RawInline(\'latex\', \'\\\\textcolor{\'..color..\'}{\')
    )
    table.insert(
      el.content,
      pandoc.RawInline(\'latex\', \'}\')
    )
    -- returns only span content
    return el.content
  else
    -- for other format return unchanged
    return el
  end
end
```

Roses are [red and **bold**]{color="red"}

Citation: ABC in @R

Col + Citation: [ABC in @R]{color="red"}

# Citations

<div id="refs"></div>
'
writeLines(text_Rmd, my_Rmd)

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

This is probably an issue with the Pandoc version used nad I believe it is fixed in recent version.

You should install a newer pandoc version and use https://bookdown.org/yihui/rmarkdown-cookbook/install-pandoc.html

or use the daily version of the RStudio IDE which bundles a recent Pandoc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM