r-for-educators / flair

decorate your R code
https://r-for-educators.github.io/flair/index.html
Other
209 stars 22 forks source link

Could flair add instead of replace highlighting? #5

Open maelle opened 4 years ago

maelle commented 4 years ago

At the moment in e.g. https://kbodwin.github.io/flair/index.html#re-referencing-a-chunk the code chunk

decorate("how_to_pipe") %>% 
  flair_funs()

has R syntax highlighting (different color for the argument for instance) whereas the following chunk has the yellow highlight but all the rest of the text is black.

Would it be possible and make sense for flair to add formatting to the existing syntax highlighting? I'm guessing it might be hard.

kbodwin commented 4 years ago

It's definitely something we would like, too.

The challenge is that syntax highlighting happens post-knit, via JavaScript, so this would have to be done "manually"; we can't take advantage of the natural syntax highlighting process.

So - it's on our to-do list, but it might be a little while, unfortunately.

machow commented 3 years ago

Hey--I think flair might be able to make these feature work with a small change! The crux is that highlight.js can do highlighting, even of code blocks that have span elements (like flair uses to mark pieces of code). It looks like in most cases, if flair puts the name of the engine back as a class on the code output, then highlightjs will work with it.

maelle commented 2 years ago

Coming back to this as I was having fun blurring code. A possible strategy would be to use downlit and then xml2 to tweak stuff, the results would be HTML (hljs would need to be turned off). The CSS to go with downlit added classes (like in pkgdown) would need to be added.

Example, not a nice interface yet :sweat_smile:

---
title: "Untitled"
output: 
  html_document:
    highlight: NULL
    theme: 
      version: 4
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(magrittr)
code <- "iris %>%
  group_by(Species) %>%
  summarize(mean(Sepal.Length))"

html <- downlit::highlight(code) %>%
  xml2::read_html()

ops <- xml2::xml_find_all(html, "//span[@class='o']")
pipes <- ops[xml2::xml_text(ops)== "%>%"]
purrr::walk(
  pipes,
  function(x) xml2::xml_attr(x, "style") <- "background-color: yellow;"
)

text <- xml2::xml_contents(xml2::xml_find_first(html, "body")) |>
  paste0(collapse = "")

cat(sprintf("<pre><code>%s</code></pre>", text))
maelle commented 2 years ago

what I particularly like with downlit is the autolinking.