Pandoc fails to render valid LaTeX macro definitions from markdown (and R markdown)

荒凉一梦 提交于 2020-03-23 09:36:34

问题


In R, I have character objects that contain LaTeX macro definitions. The challenge is to use these objects in R Markdown documents, so that the macro definitions are rendered correctly when the .Rmd files are converted to LaTeX (and then to PDF). It is a challenge because Pandoc (v2.9.1 and 2.9.2) fails to render some macro-generating code correctly, even when that code is valid LaTeX.

Here is a minimal example. First, consider this Rmd file:

---
title: "Rendering LaTeX Macros from R Objects"
output: 
  pdf_document:
    keep_md: true
    keep_tex: true
---

```{r}
withoutBraces <- "\\newcommand\\withoutBraces{This is a sentence.}"
withBraces    <- "\\newcommand{withBraces}{This is a sentence.}"
```

```{r, results = "asis"}
writeLines(withoutBraces)
writeLines(withBraces)
```

Knitting this .Rmd file from RStudio produces a .tex file that includes the following output:

\newcommand\withoutBraces{This is a sentence.}

but

\textbackslash newcommand\{withBraces\}\{This is a sentence.\}

In other words, the \withoutBraces command is rendered correctly in the .tex document, but the \withBraces command is not. Inspection reveals that the rmarkdown::render() part of the knitting process is fine, in the sense that it produces an unproblematic .md file. The problem lies with pandoc: when it converts the .md file to a .tex file, the \withBraces command doesn't render correctly.

If I were writing .md files instead of .Rmd files, I could use "generic raw attributes" in my code chunks to get the \withoutBraces macro definition to render correctly, as in this example from @mb21. But I don't see a way to do that when working with R Markdown files. Is there anything that I can do to get the \withoutBraces definition to render correctly when I am knitting an .Rmd file to LaTeX and PDF?


回答1:


The problem lay with a LaTeX formatting error on my part, not in any problem with pandoc. I had written

withBraces    <- "\\newcommand{withBraces}{This is a sentence.}"

when I should have written

withBraces    <- "\\newcommand{\\withBraces}{This is a sentence.}"

When I use the second string instead of the first, there is no problem with the conversion to LaTeX.



来源:https://stackoverflow.com/questions/60640002/pandoc-fails-to-render-valid-latex-macro-definitions-from-markdown-and-r-markdo

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