Quarto
R
Best practices
Foundations series · part 15

Companion code: show it, link it, test it

Publishing runnable scripts alongside Quarto articles with automated checks and no R needed at render time

How to ship runnable companion scripts in Quarto docs: the include shortcode pattern, path rules, and CI checks that catch unlinked files.
Published

2026-09-27

Modified

2026-11-13

Technical articles and engineering handbooks often need runnable code that is too long or too self-contained to show inline. An article might walk through an architecture, a testing strategy, or a migration pattern, but a reader wanting to adapt it needs the complete script: imports, helper functions, execution guards, and command-line arguments.

Shipping companion files alongside Quarto articles looks deceptively simple. You add a folder of scripts, declare them as site resources, and link them in prose. But without strict patterns and automated verification, documentation and companion code quickly drift apart.

The problem: drift between prose and files

On my blog, I accumulated fifteen companion R scripts and a collection of configuration templates, including git hooks, issue forms, and CI workflows. Hosting the files was never an issue: my site configuration published them directly using resource patterns in _quarto.yml:

resources:
  - "templates/**"
  - "posts/*/scripts/**"

Quarto’s resource declarations instruct the generator to copy drop-in templates and each post’s companion script folder into the rendered site directory verbatim without evaluating them. Most companion scripts were linked, but inconsistently across posts. However, discoverability, consistency, and structural integrity degraded over time:

  1. Inconsistent presentation: Companion scripts were linked across articles under varying headings (“Trying it yourself”, “Executable demo script”, “Runnable walkthrough”) and placed at arbitrary locations within posts.
  2. Missing links: One script existed on disk but was mentioned in the post only as plain text, leaving readers with no link or download button.
  3. Path ambiguity: Readers could not distinguish between downloadable companion files and local paths inside their own project. A code example reading a configuration template looked like a file the reader was expected to have locally, while execution commands mixed internal repository paths with reader commands.
  4. Orphaned templates: Ten configuration templates in the repository were never referenced or linked from any article. A multi-file agent skill folder had only its primary markdown document linked, leaving its supporting scripts invisible.
  5. Ghost references: An article referred to a template file name that did not exist on disk.

When companion code is treated as a passive file drop rather than a verified interface, broken links and orphaned assets slip past manual review.

The web-repo way: transclusion and build gates

Modern static documentation engines in software engineering address this problem with transclusion: embedding external source files directly into rendered pages at build time.

  • Material for MkDocs: The pymdownx.snippets Markdown extension allows documentation pages to pull code from external files using a snippet directive such as --8<-- "path/to/file.py". The source file remains a normal script that can be tested, linted, and versioned independently, while the documentation pulls in the exact file contents during site generation.

  • Docusaurus: Using Webpack’s raw-loader within MDX pages, authors import scripts directly into code block components:

    import CodeBlock from '@theme/CodeBlock';
    import DemoSource from '!!raw-loader!./demo.js';
    
    <CodeBlock language="javascript">{DemoSource}</CodeBlock>
  • Sphinx: Python’s documentation framework provides the .. literalinclude:: filename.py directive to embed files directly into pages with syntax highlighting and line numbers.

In all three ecosystems, the rendered page and the underlying file share a single source of truth. Software repositories pair this with automated CI gates: offline link checkers like lychee scan the rendered HTML output for dead links, and build assertions confirm that every tracked asset exists in the final release directory.

Which option when

Teams building technical documentation in Quarto have several options for sharing code. Selecting the right mechanism depends on execution requirements and project scope:

Mechanism How it works Best suited for Trade-offs
Include in callout (Recommended) Quarto include shortcode inside a collapsed callout Standalone scripts, utilities, and configuration templates Static display only; code is not executed in the reader’s browser
Quarto Code Tools (code-tools: true) HTML header dropdown with “View Source” Showing the article’s own .qmd source document Default button shows page source; source: <url> is restricted to one URL per page
code-fold Folds computational code cells Collapsing long executed blocks within an analysis Only works on executed Knitr/Jupyter cells; does not fold static markdown code blocks
Executed code + freeze Runs R code at render time; caches outputs in _freeze/ Articles where tables or figures must be generated dynamically Requires full R runtime in CI or manual commitment and synchronization of _freeze/
Quarto Live (webR) WebAssembly in the browser (r-wasm/quarto-live) Interactive workshops, exercises, and small educational snippets Needs a render engine (knitr or Jupyter) at build time; downloads WebAssembly binaries from external CDNs; not every package works in webR; test the ones you need
Separate examples repo External GitHub repository Multi-file R packages, full Shiny apps, and large pipelines A second repository to keep in step with the posts

For standalone R scripts, tests, and configuration templates, the static include pattern requires no R at render time, one test in testthat, and one CI step.

Companion code

View companion-check.R · Download

Scans Quarto posts and templates to verify that every companion file is linked, included, and published without broken references or unlinked paths in prose. Base R only.

# Companion code checker for Quarto sites and blogs
# Scans posts and templates to verify companion assets are linked, included,
# and published without broken references or unlinked paths in prose.
#
# Usage:
#   Rscript companion-check.R
#   Or from R:
#   source("companion-check.R")
#   problems <- check_companions(
#     root = ".",
#     allow = c('- "templates/**"', '- "posts/*/scripts/**"')
#   )

extract_markdown_links <- function(lines) {
  matches <- gregexpr("\\[[^\\]]*\\]\\(([^)]+)\\)", lines, perl = TRUE)
  reg_matches <- regmatches(lines, matches)
  results <- list()

  for (i in seq_along(lines)) {
    hits <- reg_matches[[i]]
    if (length(hits) > 0L) {
      raw_targets <- sub(".*\\]\\(([^)]+)\\).*", "\\1", hits)
      clean_targets <- vapply(
        raw_targets,
        function(tgt) {
          # Strip optional trailing attributes like {download="x.R"} or quotes
          clean <- sub("\\{.*$", "", tgt)
          trimws(clean)
        },
        character(1),
        USE.NAMES = FALSE
      )

      results[[length(results) + 1L]] <- data.frame(
        line = rep(i, length(clean_targets)),
        target = clean_targets,
        stringsAsFactors = FALSE
      )
    }
  }

  if (length(results) == 0L) {
    return(data.frame(
      line = integer(0),
      target = character(0),
      stringsAsFactors = FALSE
    ))
  }
  do.call(rbind, results)
}

extract_includes <- function(lines) {
  # Match {{< include ... >}} only when not preceded by { (ignoring escaped {{< ... >}})
  matches <- gregexpr(
    "(?<!\\{)\\{\\{<\\s*include\\s+([^ >]+)\\s*>\\}\\}",
    lines,
    perl = TRUE
  )
  reg_matches <- regmatches(lines, matches)
  results <- list()

  for (i in seq_along(lines)) {
    hits <- reg_matches[[i]]
    if (length(hits) > 0L) {
      targets <- sub(".*include\\s+([^ >]+).*", "\\1", hits)
      results[[length(results) + 1L]] <- data.frame(
        line = rep(i, length(targets)),
        target = trimws(targets),
        stringsAsFactors = FALSE
      )
    }
  }

  if (length(results) == 0L) {
    return(data.frame(
      line = integer(0),
      target = character(0),
      stringsAsFactors = FALSE
    ))
  }
  do.call(rbind, results)
}

check_companions <- function(root = ".", allow = character()) {
  root <- normalizePath(root, mustWork = TRUE)
  posts_dir <- file.path(root, "posts")
  templates_dir <- file.path(root, "templates")

  problems <- list()
  add_problem <- function(file, line, rule, message) {
    norm_file <- normalizePath(file, mustWork = FALSE)
    rel_file <- if (startsWith(norm_file, paste0(root, "/"))) {
      substring(norm_file, nchar(root) + 2L)
    } else {
      norm_file
    }
    problems[[length(problems) + 1L]] <<- data.frame(
      file = rel_file,
      line = as.integer(line),
      rule = rule,
      message = message,
      stringsAsFactors = FALSE
    )
  }

  # 1. Discover all posts
  post_qmds <- character(0)
  if (dir.exists(posts_dir)) {
    candidate_dirs <- list.dirs(posts_dir, recursive = FALSE)
    candidate_indices <- file.path(candidate_dirs, "index.qmd")
    post_qmds <- candidate_indices[file.exists(candidate_indices)]
  }

  # 2. Discover all companion scripts
  all_scripts <- character(0)
  if (dir.exists(posts_dir)) {
    all_post_files <- list.files(posts_dir, recursive = TRUE, full.names = TRUE)
    all_scripts <- all_post_files[grepl("/scripts/[^/]+$", all_post_files)]
  }

  # 3. Discover all templates
  all_templates <- character(0)
  if (dir.exists(templates_dir)) {
    all_templates <- list.files(
      templates_dir,
      recursive = TRUE,
      full.names = TRUE
    )
  }

  # Track linked templates across all posts
  linked_template_paths <- character(0)

  # Check each post
  for (qmd in post_qmds) {
    lines <- readLines(qmd, warn = FALSE)
    checked_lines <- lines
    checked_lines[trimws(lines) %in% allow] <- ""
    link_info <- extract_markdown_links(checked_lines)
    include_info <- extract_includes(checked_lines)

    # Validate Markdown links pointing to scripts or templates
    companion_links <- link_info[
      grepl(
        "^(scripts/|templates/|\\.\\./\\.\\./templates/)",
        link_info$target
      ),
    ]
    for (j in seq_len(nrow(companion_links))) {
      tgt <- companion_links$target[j]
      line_num <- companion_links$line[j]
      full_path <- normalizePath(file.path(dirname(qmd), tgt), mustWork = FALSE)

      if (!file.exists(full_path)) {
        add_problem(
          qmd,
          line_num,
          "broken_link",
          sprintf("Markdown link target '%s' does not exist on disk", tgt)
        )
      } else if (
        startsWith(
          full_path,
          paste0(normalizePath(templates_dir, mustWork = FALSE), "/")
        )
      ) {
        linked_template_paths <- c(linked_template_paths, full_path)
      }
    }

    # Validate include shortcodes
    for (j in seq_len(nrow(include_info))) {
      inc <- include_info$target[j]
      line_num <- include_info$line[j]
      full_inc <- normalizePath(file.path(dirname(qmd), inc), mustWork = FALSE)

      if (!file.exists(full_inc)) {
        add_problem(
          qmd,
          line_num,
          "missing_include_target",
          sprintf("Include target '%s' does not exist on disk", inc)
        )
      }
    }

    # Verify script linkage and companion code sections for this post's scripts
    post_scripts <- all_scripts[dirname(dirname(all_scripts)) == dirname(qmd)]
    has_companion_section <- any(lines == "## Companion code")

    if (length(post_scripts) > 0L && !has_companion_section) {
      add_problem(
        qmd,
        1L,
        "missing_section",
        "Post contains companion scripts but has no '## Companion code' section"
      )
    }

    for (s in post_scripts) {
      script_file <- basename(s)
      rel_script_link <- file.path("scripts", script_file)

      # Check script is linked
      if (!rel_script_link %in% link_info$target) {
        add_problem(
          qmd,
          1L,
          "unlinked_script",
          sprintf(
            "Companion script '%s' is not linked in %s",
            rel_script_link,
            basename(qmd)
          )
        )
      }

      # Check script is included
      expected_include <- file.path("scripts", script_file)
      if (!expected_include %in% include_info$target) {
        add_problem(
          qmd,
          1L,
          "missing_include",
          sprintf(
            "Companion script '%s' is not embedded with {{< include %s >}}",
            rel_script_link,
            rel_script_link
          )
        )
      }
    }

    # Check for unlinked prose paths
    path_pattern <- "(?:^|[^a-zA-Z0-9_.-])(?:scripts/|templates/|\\.\\./\\.\\./templates/)"
    # A fence closes only on a bare run of at least as many backticks as
    # opened it, so a ```` fence can show a ``` example inside it.
    fence_len <- 0L

    for (i in seq_along(lines)) {
      line <- lines[i]
      ticks <- nchar(sub("^(`*).*$", "\\1", line))
      if (ticks >= 3L) {
        if (fence_len == 0L) {
          fence_len <- ticks
          next
        }
        if (ticks >= fence_len && grepl("^`+\\s*$", line)) {
          fence_len <- 0L
          next
        }
      }
      in_fence <- fence_len > 0L

      if (trimws(line) %in% allow) {
        next
      }

      # Full URLs in hosting examples are not repository-relative paths.
      path_text <- gsub("https?://[^[:space:]`\"<>]+", "", line, perl = TRUE)

      if (in_fence) {
        if (grepl(path_pattern, path_text, perl = TRUE)) {
          if (!grepl("^\\s*\\{\\{<\\s*include\\s+\\S+\\s*>\\}\\}\\s*$", line)) {
            add_problem(
              qmd,
              i,
              "forbidden_code_path",
              sprintf(
                "Forbidden companion path inside code block: %s",
                trimws(line)
              )
            )
          }
        }
      } else {
        stripped <- gsub("\\[[^\\]]*\\]\\([^)]+\\)", "", path_text, perl = TRUE)
        if (grepl(path_pattern, stripped, perl = TRUE)) {
          add_problem(
            qmd,
            i,
            "unlinked_prose",
            sprintf("Unlinked companion path in prose: %s", trimws(line))
          )
        }
      }
    }
  }

  # Check for orphaned template files
  for (tmpl in all_templates) {
    tmpl_norm <- normalizePath(tmpl, mustWork = FALSE)
    if (!tmpl_norm %in% linked_template_paths) {
      rel_tmpl <- if (startsWith(tmpl_norm, paste0(root, "/"))) {
        substring(tmpl_norm, nchar(root) + 2L)
      } else {
        tmpl_norm
      }
      add_problem(
        tmpl,
        1L,
        "unlinked_template",
        sprintf("Template file '%s' is not linked from any post", rel_tmpl)
      )
    }
  }

  if (length(problems) == 0L) {
    return(data.frame(
      file = character(0),
      line = integer(0),
      rule = character(0),
      message = character(0),
      stringsAsFactors = FALSE
    ))
  }

  do.call(rbind, problems)
}

# Standalone demo: builds a mock site in tempdir(), seeds issues, and prints report
if (sys.nframe() == 0L) {
  demo_root <- file.path(tempdir(), paste0("companion-demo-", Sys.getpid()))
  dir.create(
    file.path(demo_root, "posts", "analysis-demo", "scripts"),
    recursive = TRUE
  )
  dir.create(file.path(demo_root, "templates"), recursive = TRUE)

  # Create mock template
  tmpl_file <- file.path(demo_root, "templates", "pipeline.yml")
  writeLines("name: pipeline", tmpl_file)

  # Create mock script
  script_file <- file.path(
    demo_root,
    "posts",
    "analysis-demo",
    "scripts",
    "demo.R"
  )
  writeLines(c("# Demo script", "message('Hello from demo!')"), script_file)

  # Create mock post with deliberate defects:
  # 1. Unlinked script (script exists, but never linked or included)
  # 2. Broken link to non-existent script
  # 3. Unlinked prose path
  # 4. Missing ## Companion code section
  post_file <- file.path(demo_root, "posts", "analysis-demo", "index.qmd")
  writeLines(
    c(
      "---",
      "title: 'Mock Analysis'",
      "---",
      "",
      "This post discusses scripts/demo.R in prose without linking it.",
      "",
      "Check out [broken file](scripts/missing.R).",
      ""
    ),
    post_file
  )

  cat("Running companion check on mock Quarto site with planted defects...\n")
  report <- check_companions(demo_root)

  if (nrow(report) > 0L) {
    cat(sprintf("Identified %d companion code issues:\n\n", nrow(report)))
    for (k in seq_len(nrow(report))) {
      cat(sprintf(
        "- [%s] %s:%d - %s\n",
        report$rule[k],
        report$file[k],
        report$line[k],
        report$message[k]
      ))
    }
  } else {
    cat("All companion checks passed cleanly.\n")
  }

  unlink(demo_root, recursive = TRUE)
}

Sources

Quarto documentation

Web documentation platforms

Interactive R environments

R packages

NoteUpdates
  • 2026-11-13: The site’s test files now carry a site- or post- prefix, so the test named here is tests/testthat/test-site-companions.R.