Use highlighter in a Shiny App

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

You can execute the following code to launch the sample Shiny app included with this package and experience it in action.

shiny::shinyAppFile(system.file("examples/shiny_app.R", package = "highlighter"))

The code for the application mentioned above is as follows:

library(shiny)
library(highlighter)
library(stringr)

ui <- fluidPage(
  h1("Highlighter example"),
  hr(),
  div(
    style = "padding: 1rem;",
    selectizeInput(
      inputId = "file",
      label = "Select a file",
      choices = list.files(
        path.package(package = "highlighter"),
        recursive = TRUE
      ) |>
        str_subset(pattern = "docs", negate = TRUE) |>
        str_subset(pattern = ".css", negate = TRUE)
    ),
    checkboxInput(
      inputId = "autoguess",
      label = "Auto guess language?",
      value = TRUE
    ),
    selectizeInput(
      inputId = "language",
      label = "Select language",
      choices = highlighter::get_available_languages(),
      selected = "r"
    ),
    highlighterOutput("code")
  )
)

server <- function(input, output, session) {

  output$code <- renderHighlighter({
    shiny::req(shiny::isTruthy(input$language))
    highlight_file(
      file_path = file.path(
        path.package(package = "highlighter"),
        input$file
      ),
      language = if (input$autoguess) NULL else input$language,
      theme = "solarized_light",
      plugins = list(
        line_number(
          use_line_number = TRUE,
          start_from = 3
        ),
        highlight(
          range = "7-10,13"
        )
      )
    )
  })
}

shinyApp(ui, server)


Try the highlighter package in your browser

Any scripts or data that you put into this service are public.

highlighter documentation built on Sept. 25, 2023, 5:08 p.m.