7

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.

David
  • 9,216
  • 4
  • 45
  • 78

1 Answers1

17

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

David
  • 9,216
  • 4
  • 45
  • 78