How to Syntax Highlight Inline R Code in R Markdown

How to syntax highlight inline R code in R Markdown?

Here is one solution using the development version of the highr package (devtools::install_github('yihui/highr')). Basically you just define your custom LaTeX commands to highlight the tokens. highr:::cmd_pandoc_latex is a data frame of LaTeX commands that Pandoc uses to do syntax highlighting.

head(highr:::cmd_pandoc_latex)
## cmd1 cmd2
## COMMENT \\CommentTok{ }
## FUNCTION \\NormalTok{ }
## IF \\NormalTok{ }
## ELSE \\NormalTok{ }
## WHILE \\NormalTok{ }
## FOR \\NormalTok{ }

Then you can redefine the inline hook of knitr:

---
output:
pdf_document:
keep_tex: yes
---

```{r include=FALSE}
local({
hi_pandoc = function(code) {
if (knitr:::pandoc_to() != 'latex') return(code)
if (packageVersion('highr') < '0.6.1') stop('highr >= 0.6.1 is required')
res = highr::hi_latex(code, markup = highr:::cmd_pandoc_latex)
sprintf('\\texttt{%s}', res)
}
hook_inline = knitr::knit_hooks$get('inline')
knitr::knit_hooks$set(inline = function(x) {
if (is.character(x) && inherits(x, 'AsIs')) hi_pandoc(x) else hook_inline(x)
})
})
```

Test inline R code: `r I("plot(cars, main = 'A scatterplot.')")`.
Normal inline code `r pi`.

A code block:

```r
plot(cars, main = 'A scatterplot.')
1 + 2 # a comment
```

I used I() as a convenient marker to tell the character strings to be syntax highlighted from normal character strings. It is just an arbitrary choice. PDF output:

syntax highlighted inline code

This is not a perfect solution, though. You will need to tweak it in some cases. For example, most special LaTeX characters are not escaped, such as ~. You may need to process the LaTeX code returned by hi_pandoc() by gsub().

Personally I find multiple colors in inline output distracting, so I would not syntax highlighting it, but this is entirely personal taste.

Differences in R Markdown syntax highlighting for in-line code

We changed the treatment of code in a recent release of rmarkdown (the red was too strong). My guess is that you have two different versions of the rmarkdown package in play. If you update both systems to the most recent version from CRAN (v0.6.1 as of the time of this writing) then you should get consistent behavior.

Inline code in R markdown PDF file is not displayed correctly

Text like `this` is translated into the LaTeX command \texttt{this}. LaTeX commands can be changed, so we can modify the \texttt command to create a color box:

```{=latex}
\definecolor{codegray}{HTML}{cccccc}
\let\textttOrig\texttt
\renewcommand{\texttt}[1]{\textttOrig{\colorbox{codegray}{#1}}}
```

Add the above at the beginning of your Rmd document (right after the YAML header) to get a gray background for you inline code snippets.

How to enable syntax highlighting in code chunks within r markdown ioslides presentations?

If you navigate to your R install library folder, you should be able to go to (note that your version number may vary):

rmarkdown > rmd > ioslides > ioslides-13.5.1 > theme > css

to find the 'default.css' file. In there, you can scroll down to the /*Pretty print */ comment. Underneath, you should see a bunch of arguments that start with .prettyprint. Your best bet may be to copy those into a new custom .css file so you can play around a little until you get the highlighting you're after. For example, I made a file called slides.css and put it in the same folder as my markdown document. Then, I copied in these css arguments and just modified the colors:

/* Pretty print */

/* line 600, ../scss/default.scss */
.prettyprint .com {
/* a comment */
color: green;
font-style: italic;
}

/* line 604, ../scss/default.scss */
.prettyprint .lit {
/* a literal value */
color: black;
}

/* line 609, ../scss/default.scss */
.prettyprint .pun,
.prettyprint .opn,
.prettyprint .clo {
color: red;
}

/* line 618, ../scss/default.scss */
.prettyprint .pln {
color: blue;
}

Then, with my ioslides file:

---
title: "Ioslides check"
output:
ioslides_presentation:
css: slides.css
---

##

```{r}
# cars[,1] as an example for a comment
head(cars)
cars[1:5, 1]
```

My output looks like

Sample Image

If you want to figure out which elements you actually want to modify (for example, if you instead would like to change the look of your code), you can use the inspect function of a browser (CTRL + SHIFT + I in chrome) to highlight the elements of your ioslides output to see to which class they belong. For example, when I highlight the results output, it shows me that that can be modified by playing with the pre (preformatted text) tag. If I therefore add a color argument to pre:

pre {
font-family: 'Source Code Pro', 'Courier New', monospace;
font-size: 20px;
color: pink;
line-height: 28px;
padding: 10px 0 10px 60px;
letter-spacing: -1px;
margin-bottom: 20px;
width: 106%;
left: -60px;
position: relative;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
/*overflow: hidden;*/
}

I can change the results output as well:

Sample Image

but keep in mind that many of the classes above are also contained within the pre tag, so if you make modifications to pre that are not overridden by a child class, you can get some unintended results. For example, if I change the font-size of the pre elements:

/* line 337, ../scss/default.scss */
pre {
font-family: 'Source Code Pro', 'Courier New', monospace;
font-size: 50px;
line-height: 28px;
padding: 10px 0 10px 60px;
letter-spacing: -1px;
margin-bottom: 20px;
width: 106%;
left: -60px;
position: relative;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
/*overflow: hidden;*/
}

but only change the font-size of some of the child elements

/* line 604, ../scss/default.scss */
.prettyprint .lit {
/* a literal value */
color: black;
font-size: 20px;
}

my output will be wonky:

Sample Image

How do I highlight certain words in a text, produced from a code chunkt?

Try

gsub("have","\\\\textcolor{red}{have}", mytext) 

It makes no difference if you use gsub or str_replace_all. The important change is to use 4 backslashes. And you have to change the argument order for textcolor.



Related Topics



Leave a reply



Submit