Companion code: show it, link it, test it
Publishing runnable scripts alongside Quarto articles with automated checks and no R needed at render time
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:
- 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.
- 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.
- 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.
- 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.
- 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.snippetsMarkdown 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-loaderwithin 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.pydirective 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.
The R way: show it, link it, test it
In Quarto, I use shortcodes, collapsed callouts, a path convention, and automated verification tests.
1 · The presentation pattern
Every post that ships a companion script ends with a dedicated ## Companion code section directly before the sources. The section contains a paired View and Download link, a brief explanation, and a collapsed callout displaying the full script:
## Companion code
[View `demo.R`](scripts/demo.R) · [Download](scripts/demo.R){download="demo.R"}
Description of what the script does and required packages.
::: {.callout-note collapse="true"}
## Full script: `demo.R`
```r
{{< include scripts/demo.R >}}
```
:::The example uses triple curly braces to display the shortcode literally without running it (see Quarto shortcode escaping). In a published article, normal double braces transclude the script at render time.
This structure solves several practical problems:
- Single source of truth: Quarto evaluates the
includeshortcode at render time inside the fenced code block. Quarto and Pandoc escape the code and apply syntax highlighting, while Quarto’scode-copyfeature provides the copy-to-clipboard button. The embedded text and the downloadable file come from the exact same file on disk. - No R needed at render time: The shortcode runs during Quarto’s text processing phase. As long as the post contains no executable chunks, it does not invoke Knitr or evaluate R expressions. The site can be built in lightweight CI containers without an R runtime installed.
- Uncluttered layout: Long scripts do not distract from the article’s narrative. Readers who only want the concept see a compact section; readers who want the code can view it in the page or download it with one click.
2 · The path convention
To eliminate ambiguity between published assets and a reader’s internal project layout, I use a path rule across the articles:
- Published assets are always links: Any mention of a companion script path in prose must be a Markdown hyperlink pointing to the real file on disk (for example, scripts/companion-check.R).
- Reader paths use project-relative prefixes: When an article or code example describes a file in the reader’s project, it must use standard project paths such as
R/clean-data.R, never a companion folder prefix. - Reader-facing header comments: The companion script itself is displayed directly on the webpage. Header comments must instruct the reader on how to execute the standalone file (for example,
# Usage: Rscript companion-check.R), avoiding internal repository paths.
3 · Automated verification
Manual vigilance does not prevent broken links or forgotten files. I guard the pattern with three automated layers:
A · The unit test
The site’s own test suite runs tests/testthat/test-site-companions.R, while my companion script (scripts/companion-check.R) packages these checks into a reusable function, check_companions(), that can be called directly in a project’s own tests:
test_that("companion checker validates site structure", {
# Validates that every companion script is linked in prose,
# embedded via an include shortcode, and exists on disk.
report <- check_companions(root = ".")
expect_equal(nrow(report), 0L)
})The test asserts five structural rules:
- Every post companion script is hyperlinked in its post and included within a
## Companion codesection. - Every configuration file in the site template directory is hyperlinked from at least one post.
- Every Markdown link pointing to a companion script or template resolves to an existing file on disk.
- Every shortcode include target exists on disk.
- No unlinked companion path appears in prose, and no companion path appears inside code blocks other than an include shortcode.
When run against the blog before adopting this standard, the test identified one unlinked script, ten unlinked template files, and three command blocks that showed source-repository paths to readers.
B · CI output verification
Unit tests run against source files. To verify that Quarto’s resource configuration actually published every asset, the GitHub Actions workflow includes a post-render shell check before deployment:
missing=0
while IFS= read -r f; do
if [ ! -f "_site/$f" ]; then echo "::error::not published: $f"; missing=1; fi
done < <(git ls-files 'posts/*/scripts/*' 'templates/*')
exit "$missing"The workflow runs this verification across all tracked companion scripts and template files. If an author modifies _quarto.yml and accidentally excludes companion assets, CI fails immediately before preview deployment or static publication. An offline link checker (lychee) then scans the rendered HTML files in _site/ to ensure all relative links resolve.
C · Post checker integration
My repository uses a pre-flight checker (tools/check-post.R) that parses and evaluates code blocks in articles to ensure example code runs without errors. Because include shortcodes are Quarto directives rather than valid R expressions, the checker skips code blocks that contain only include shortcodes (escaped or not), preventing false parse failures while keeping all other R blocks verified.
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-check.R
# 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
- Quarto Includes: quarto.org/docs/authoring/includes.html
- Quarto Shortcode Escaping: quarto.org/docs/extensions/shortcodes.html#escaping
- Quarto HTML Code Tools: quarto.org/docs/output-formats/html-code.html#code-tools
- Quarto Code Folding: quarto.org/docs/output-formats/html-code.html#folding-code
- Quarto Code Execution and Freeze: quarto.org/docs/projects/code-execution.html#freeze
Web documentation platforms
- Material for MkDocs Snippets: squidfunk.github.io/mkdocs-material/reference/code-blocks/
- PyMdown Extensions Snippets: facelessuser.github.io/pymdown-extensions/extensions/snippets/
- Docusaurus Code Blocks: docusaurus.io/docs/markdown-features/react#importing-code-snippets
- Sphinx Literal Include Directive: sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-literalinclude
- Lychee Link Checker: lychee.cli.rs
Interactive R environments
- Quarto Live: r-wasm.github.io/quarto-live
- webR Documentation: docs.r-wasm.org/webr/latest
R packages
- testthat: testthat.r-lib.org
- withr: withr.r-lib.org
- 2026-11-13: The site’s test files now carry a
site-orpost-prefix, so the test named here istests/testthat/test-site-companions.R.