shiki syntax highlighting

syntax highlighting

Beautiful syntax highlighting with shiki

Emil Hvitfeldt
05-08-2021

The shiki Javascript library provides beautiful syntax highlighting.

To use this highlighter, specify beforeInit: ["https://unpkg.com/shiki", "shiki-addon.js"] in nature and include shiki-addon.js at same folder as your rmd file.

The theme can be changed in shiki-addon.js with avaliable themes are listed here.

Result

Rmd

---
title: "Presentation Ninja"
subtitle: "⚔<br/>with xaringan"
author: "Yihui Xie"
institute: "RStudio, PBC"
date: "2016/12/12 (updated: `r Sys.Date()`)"
output:
  xaringan::moon_reader:
    lib_dir: libs
    seal: false
    nature:
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
      beforeInit: ["https://unpkg.com/shiki", 
                   "shiki-addon.js"]
---

# Title

```{r, eval=FALSE}
install.packages("tidyverse")
# Alternatively, install just ggplot2:
install.packages("ggplot2")

# Or the development version from GitHub:
# install.packages("devtools")
devtools::install_github("tidyverse/ggplot2")

NA_real_
```

---

# Language aware

```{js,  eval=FALSE}
var element = document.getElementById("myCode");
Shiki.highlight(element);
```

shiki-addon.js

remark.highlighter.engine.highlightBlock = (block, temp) => {
   shiki_wrapper(block)
};

function shiki_wrapper (block) {
    shiki
      .getHighlighter({
        theme: 'github-light'
      })
      .then(highlighter => {

        // Add spaces to empty lines to avoid them being removed
        const search = '<div class="remark-code-line"></div>';
        const replaceWith = '<div class="remark-code-line"> </div>';
        block.innerHTML = block.innerHTML.split(search).join(replaceWith);

        codeLanguage = block.className.replace(" remark-code","")
        block.innerHTML = highlighter.codeToHtml(block.innerText, codeLanguage)
      });
};

Reuse

Text and figures are licensed under Creative Commons Attribution CC BY 4.0. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".

Citation

For attribution, please cite this work as

Hvitfeldt (2021, May 8). Xaringan Gallery: shiki syntax highlighting. Retrieved from https://xaringan.gallery/examples/shiki/

BibTeX citation

@misc{hvitfeldt2021shiki,
  author = {Hvitfeldt, Emil},
  title = {Xaringan Gallery: shiki syntax highlighting},
  url = {https://xaringan.gallery/examples/shiki/},
  year = {2021}
}