Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight selection of code in xaringan

How can I highlight a single word or a selection of code in xaringan instead of the whole line?

In the following example I want to highlight only the pipe operator %>% and not the whole line.

---
output:
  xaringan::moon_reader:
    css: [default]
    lib_dir: libs
    nature:
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
---

```{r setup, include=F}
library(magrittr)
```

Highlight Whole Line (not what I need)
```{r, eval=F}
iris %>% #<<
  summary()
```

Highlight Whole Line 2 (also not what I need)
```{r, eval=F}
{{ iris %>% }}
  summary()
```

Highlight Pipe only (What I would need, doesnt work)
```{r, eval=F}
iris {{ %>% }}
  summary()
```

Highlight Pipe only html-mark (doesnt work, as expected)
```{r, eval=F}
iris <mark>%>%</mark>
  summary()
```

Which results in this enter image description here

Any help is appreciated.

like image 949
David Avatar asked Aug 25 '18 11:08

David


1 Answers

One solution I found: using highlightSpans: true and then use backticks inside the code. I.e.,

---
output:
  xaringan::moon_reader:
    css: [default]
    lib_dir: libs
    nature:
      highlightStyle: github
      highlightLines: true
      highlightSpans: true
      countIncrementalSlides: false
---

```{r, eval=F}
iris `%>%`
  summary()
```

produces

enter image description here

The only caveat to that method is that it only runs if R itself does not evaluate the code. (eval=TRUE would return an error)

The source of this was: https://github.com/gnab/remark/wiki/Configuration

like image 175
David Avatar answered Nov 03 '22 00:11

David