Skip to content

Function for printing color formatted Stan code in Quarto #1149

@avehtari

Description

@avehtari

How about adding a helper function to make it easier to have color formatted Stan code in Quarto files?

I've been recently been using something like the following

print_stan_file <- function(file, fold = FALSE, summary = "Stan model code") {
  code <- readLines(file)
  if (isTRUE(getOption("knitr.in.progress")) &
        identical(knitr::opts_current$get("results"), "asis")) {
    if (fold) {
      cat("<details><summary>", summary, "</summary>\n\n", sep = "")
    }
    cat("```stan\n")
    cat(code, sep = "\n")
    cat("\n```\n")
    if (fold) {
      cat("\n</details>\n")
    }
  } else {
    writeLines(code)
  }
}

Which is used in Quarto as

#| output: asis
print_stan_file(stan_model_file_path)

If the function is called outside of rendering or without output: asis, it will write the plain code. If the function is called when rendering and Quarto block option output: asis is used, the output will be color formatted.

Additional argument fold makes the code to be folded with title provided by argument summary

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions