Stata syntax highlighting in Rmarkdown - r

I am using Bookdown and Rmarkdown to compose a technical book for Stata users. I would like to include Stata highlighting syntax in the chunks of code, but I am not interested in actually executing Stata from Rstudio. I just want the syntax highlighting.
I learned here that it is possible to use highlightjs but I have no idea how to include it in my .Rmd files.
I would like to be able to include something like the following and get it syntax highlighted.
```stata
sysuse auto, clear
reg mpg length
```
I highly appreciate your help.
Thanks.

Now you can highlight your stata code, by using the latest R packages related to knitting.
rmarkdown Ver. 2.10
knitr: Ver. 1.33
bookdown: Ver. 0.22
You may also have to [u]se a Pandoc version not bundled with the RStudio IDE. I use a Pandoc Ver. 2.14.0.3.
---
title: "Untitled"
author: "author"
output:
bookdown::pdf_document2: default
---
- `rmarkdown`: Ver. `r packageVersion("rmarkdown")`
- `knitr`: Ver. `r packageVersion("knitr")`
- `bookdown`: Ver. `r packageVersion("bookdown")`
- (`pandoc`: Ver. `r rmarkdown::pandoc_version()`)
```stata
sysuse auto, clear
reg mpg length
```

Related

R Markdown equation preview for \newcommand

I have an R markdown file with several custom latex commands, defined via \newcommand. I really like the preview in RStudio, but it doesn't seem to be able to render these commands or those imported from packages. In the following example, neither the custom command \expect nor the package command \bm is shown in the preview. Instead, they are shown in red letters in the preview.
Is there any way to have them rendered in the preview?
---
header-includes:
- \usepackage{bm}
output:
pdf_document
---
\newcommand{\expect}[1]{\mathbb{E}\left[ #1 \right]}
$$
\expect{\bm{X}} = \lambda
$$

R markdown not recognizing loaded LaTeX packages

I'm trying to use the LaTeX package gensymb in my R markdown document (PDF output), but it seems to not work. These two examples work:
IN LaTeX as a .tex file compiled with PDFLaTeX:
\documentclass{article}[12pt]
\usepackage{gensymb}
\begin{document}
It is 90 \degree F outside.
\end{document}
As well as this one In RStudio as a .rmd file using knitr and pdfLaTeX:
header-includes:
output:
pdf_document:
fontsize: 12pt
geometry: margin=1in
---
It is 90 $^{\circ}$ F outside.
But the following does not compile in a .rmd file.
header-includes:
- \usepackage{gensymb}
output:
pdf_document:
fontsize: 12pt
geometry: margin=1in
---
It is 90 \degree F outside.
The error from R reports
tlmgr.pl: Local TeX Live (2019) is older than remote repository (2020).
Cross release updates are only supported with
update-tlmgr-latest(.sh/.exe) --update
See https://tug.org/texlive/upgrade.html for details.
! LaTeX Error: File `gensymb.sty' not found.
Any help is greatly appreciated!
The errors suggest that there are two distributions of TeX installed. One of them is not updated to the same version as the repository from which it is trying to get gensymb and therefore fails to download the package.
It is wise to only have one distribution installed to prevent errors or confusion like that.

Font issue in rmarkdown slides with Metropolis theme

I am using the rmarkdown package to produce PDF slides with the Metropolis theme. Recently, I noticed that the equations started to appear differently - they use a different font.
Minimal example of *.Rmd file:
---
output:
beamer_presentation:
theme: "metropolis"
latex_engine: xelatex
keep_tex: true
---
## Problem with font
$$f(x_i\mid\mu,\sigma^2) = \exp\left\{-\frac{(x_i-\mu)^2}{2\sigma^2}\right\}$$
which, when knitted in RStudio, produces:
This looks different from what is obtained when compiling the same slide directly in LaTeX with xelatex:
\documentclass{beamer}
\usetheme{metropolis}
\begin{document}
\begin{frame}{Problem with font}
\[f(x_i\mid\mu,\sigma^2) = \exp\left\{-\frac{(x_i-\mu)^2}{2\sigma^2}\right\}\]
\end{frame}
\end{document}
which produces:
This does not look like a big difference, but in other equations some special characters are missing, and the font size is slightly different, affecting the whole layout of my slides.
After some investigation, it turns out that commenting out those two lines in the tex file produced by rmarkdown makes it better:
%\usepackage{unicode-math}
%\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
Is the unicode-math package the (only) culprit here? How to solve this problem and make sure that Metropolis uses the right fonts without manually changing the tex files?
Thanks in advance for your help!
System configuration:
RStudio 1.2.1335
rmarkdown 1.15
pandoc 2.3.1 (through RStudio)
Metropolis theme 1.2
Fira Sans font 4.3
XeTeX 3.14159265-2.6-0.999991 (TeX Live 2019)
What you are seeing is, indeed, the effect of the unicode-math package. There is a simple way to work around this by forcing pandoc to use the mathspec package instead. This can be done by setting mathspec: true in your metadata
---
mathspec: true
output: …
---
or by setting the respective variable when calling pandoc
---
output:
beamer_presentation:
theme: "metropolis"
latex_engine: xelatex
pandoc_args: ["--variable=mathspec"]
---
There is only a minor, very subtle, and mostly inconsequential difference between the two. I'd suggest to use the first version, as it is simpler.
See TeX StackExchange for a discussion of the differences between unicode-math and mathspec.

Is $$ deprecated in R Markdown LaTeX?

I was reading here that $$ is deprecated in LaTeX and replaced with \[ and \]. It seems the opposite when I use R Markdown in R Studio though.
If I wrap an equation in $$ it will display block style, live preview, in my R Markdown (in R Studio). If I use \[ and \] it will still knitr fine, but it won't showup R Studio live preview. See below.
---
title: "Untitled"
author: "March 2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
\[x = R + F\]
$$x = R + E$$
The linked Q&A is correct. $$ is deprecated for LaTeX. However, you are not writing LaTeX but Rmarkdown, which is processed by pandoc. In the pandoc manual we find:
TeX math will be printed in all output formats. How it is rendered depends on the output format:
LaTeX
It will appear verbatim surrounded by \(...\) (for inline math) or \[...\] (for display math).
So you can use $$...$$ in Rmarkdown documents and still have the correct output when converting to PDF via LaTeX. The other form works due to another pandoc extension. If you need cross-references for equations, you should use bookdown, though.

Rstudio pdf knit fails with "Environment Shaded undefined" error

When trying to knit a PDF using a template from package rticles output: rticles::acm_article I get the following error:
! LaTeX Error: Environment Shaded undefined.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.76 \begin{Shaded}
This appears to only happen when I include code chunks within the output document.
Reproducible example:
You will need to start a new R Markdown document using the New Document -> From Template -> Association for Computing Machinery. Here is the R Markdown file:
---
title: Short Paper
author:
- name: I Am Me
email: me#email.com
affiliation: Fictional University
abstract: |
This is the abstract.
It consists of two paragraphs.
output:
rticles::acm_article:
keep_tex: true
---
## Simple test
Code chuck follows:
```{r}
plot(rnorm(10))
```
This above example, however, works if I set echo=FALSE in the header. You won't get code in the output, but for an academic paper you probably don't need it anyway, an if you do you can display it in a different manner.
Notes:
R version 3.3.1 (2016-06-21)
Platform: x86_64-pc-linux-gnu (64-bit),
running Ubuntu 16:10
I made sure I have the texlive-latex-base, texlive-latex-recommended, and texlive-latex-extra package installed, but still no luck
I also tried generating a pdf from the intermediate .tex file, as suggested here, but I get the same error.
I considered this approach, but it didn't work, I still got an error (maybe I need to tweak to work in my context, but not sure how)
So, the issue here is the rticles templates sometimes omit a means for pandoc to inject code highlighting environments, e.g. Shaded. To get around this, you would have to insert into the template.tex preamble:
$if(highlighting-macros)$
$highlighting-macros$
$endif$
I struggled with fixing the error and actually raised another question which I was able to answer after quite some experimentation and searching for other related questions/answers.
In short the solution presented above by coatless works perfect given you know the location of the template.tex file. Obviously, I played around with the wrong files before I came across a related question on rticles and how to embed (missing) LATEX.
The longer answer can be found in my "another question". For reference here are the key steps:
locate the template.tex file in your R package rticles library. If you do not know where you have your package library use .libPaths() in your RStudio console. Then work your way to the resources subfolder of your rticle template. In my case:
R-3.5.0/library/rticles/rmarkdown/templates/ieee_article/resources.
add the fix proposed by coatless above in the preamble of the template.tex. The preamble is anything before the line \begin{document}:
$if(highlighting-macros)$
$highlighting-macros$
$endif$
save template.tex and go back to R/RStudio and hit the knit button. R code chunks are now nicely displayed, if you do not suppress their printing with echo = FALSE.
I know the post is old, but I'll put this here for reference for others who have the same problem.
The reason is that in the latex template the environment Shaded is trying to be redefined. However the environment only exists if you are using R chunks in your pdf. So if you don't have any r chunks in the pdf, it tries to redefine something which was never defined - causing the error.
The solution is to modify the \renewenvironment{Shaded} command in the latex template.
https://github.com/yihui/bookdown-chinese/commit/a3e392593b464ba31a7eceb0cd60f7e0bd112798
I found a work around. If I hide the code with chunk option echo = FALSE, a PDF is generated with no issues.
Reproducible example 1:
title: Short Paper
author:
- name: I Am Me
email: me#email.com
affiliation: Fictional University
abstract: |
This is the abstract.
It consists of two paragraphs.
bibliography: sigproc.bib
output:
rticles::acm_article:
keep_tex: true
---
## Simple test
Code chuck follows:
```{r}
plot(rnorm(10))
```
Knit to PDF fails with ! LaTeX Error: Environment Shaded undefined.
Example 2:
---
title: Short Paper
author:
- name: I Am Me
email: me#email.com
affiliation: Fictional University
abstract: |
This is the abstract.
It consists of two paragraphs.
bibliography: sigproc.bib
output:
rticles::acm_article:
keep_tex: true
---
## Simple test
Code chuck follows:
```{r echo=FALSE}
plot(rnorm(10))
```
Knit to PDF works!.
The only difference between the two examples is adding echo=FALSE to the code chunk header. You won't get code in the output, but for an academic paper you probably don't need it anyway, an if you do you can display it in a different manner.
The rticles templates typically do not directly allow shading of code. As a result,
the required $highlighting-macros$ which is used to control the shading is not included.
If for any reason, you cannot (or do not) want to directly edit the template.tex file as suggested by #coatless, you can alternatively consider include the code directly in the acm_proc_article-sp.cls file:
\usepackage{color}
\usepackage{fancyvrb}
\newcommand{\VerbBar}{|}
\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\usepackage{framed}
\definecolor{shadecolor}{RGB}{248,248,248}
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\ImportTok}[1]{#1}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.81,0.36,0.00}{\textbf{#1}}}
\newcommand{\BuiltInTok}[1]{#1}
\newcommand{\ExtensionTok}[1]{#1}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.77,0.63,0.00}{#1}}
\newcommand{\RegionMarkerTok}[1]{#1}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{0.94,0.16,0.16}{#1}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.64,0.00,0.00}{\textbf{#1}}}
\newcommand{\NormalTok}[1]{#1}
You may also wish to see my answer to a similar question, whereby the same code is put into a header.tex file in the same directory as your project.

Resources