Avoid printing console control chars when knitting via RStudio

39 Views Asked by At

When you run the following code in Rstudio you will see that in the final output the ANSI control chars are included in the output. If you run the same code from the R console, this is not the case.

I found 2 workarounds:

  • A partial workaround is to set pillar.subtle to FALSE which gets rid of the control chars responsible for gray text (but not the ones for italic text)
  • The other option is to use crayon::strip_style.

However, since the control chars are only visible from within RStudio, my guess it has something to do with the capability of RStudio to display ANSI control chars in the first place.

Hence, my question: is there an R option which I could pass to R.options which deactivates these extended capabilities such that I do not need to fall back to strip_style. In some old issues I found the option crayon.enabled but this is obviously not supported any more.

library(shiny)
library(knitr)
library(tibble)
library(glue)

ui <- fluidPage(checkboxInput("use_subtle", "pilar.subtle", value = TRUE), 
                checkboxInput("strip", "Use strip_style", value = FALSE),
                uiOutput("content"))

server <- function(input, output) {
   n <- new.env()
   output$content <- renderUI({
      subtle <- input$use_subtle
      chunk <- glue("```{{r, R.options = list(pillar.subtle = {subtle})}}
                        as_tibble(mtcars)
                     ```")
      res <- HTML(knit2html(text = chunk, fragment.only = TRUE, quiet = TRUE, envir = n))
      if (input$strip) {
         res <- crayon::strip_style(res)
      }
      res
   })
}

shinyApp(ui, server)

Output from Rstudio

ANSI Control Chars

Output from R Console

No ANSI Control Chars

0

There are 0 best solutions below