In Bookdown, `\textcolor` is not recognized when I attempt to compile an epub book using Pandoc

北城余情 提交于 2020-05-01 03:37:58

问题


In bookdown, it appears that \textcolor in latex is not recognized when I try to compile using

bookdown::render_book('bookdown::epub_book')

even though I have added \usepackage{xcolor} into the preamble.tex file.

Is there a reason for this?


回答1:


Let's have a look at the way the document is processed. I will leave out processing by the knitr and R Markdown packages and focus on pandoc, which is the final step when converting from Markdown to any other format.

Pandoc first parses the document into an internal, intermediate format. We can inspect that format by choosing native as the target format. So when we feed \textcolor{red}{Mars} to pandoc, it will show us the native representation:

$ printf '\\textcolor{red}{Mars}' | pandoc --from=markdown --to=native
[Para [RawInline (Format "tex") "\\textcolor{red}{Mars}"]]

What this means is that, without going into too much detail, pandoc recognizes \textcolor... as a raw LaTeX command embedded into Markdown. It does not try to parse the LaTeX any further, as it was told to read Markdown, not LaTeX. This raw LaTeX snippet will be included in the output when producing output of a format which supports inclusion of LaTeX. The snippet is left out by pandoc when generating HTML/EPUB, as including it would not have the intended effect.

So can we convince pandoc to continue parsing, and does pandoc know how to translate \textcolor from LaTeX to HTML?

The second question is easy to answer by converting the LaTeX to HTML via pandoc:

$ printf '\\textcolor{red}{Mars}' | pandoc --from=latex --to=html
<p><span style="color: red">Mars</span></p>

That looks good, so let's make pandoc parse the raw LaTeX snippets as the next step. Pandoc has a feature called Lua filters which allow us to modify the internal document representation programmatically. Here is such a filter which will parse the raw LaTeX commands:

function RawInline (el)
  if el.format == 'tex' then
    local blocks = pandoc.read(el.text, 'latex').blocks
    return blocks[1] and blocks[1].content or el
  end
end

Save this code to a file parse-latex.lua and make your document processing pipeline use this file:

---
output:
  bookdown::epub_book:
    pandoc_args: ['--lua-filter=/path/to/your/parse-latex.lua']
---

The colored text should now show up in your epub book.



来源:https://stackoverflow.com/questions/57548218/in-bookdown-textcolor-is-not-recognized-when-i-attempt-to-compile-an-epub-bo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!