rmd_modify: Modify nodes of an Rmd ast

View source: R/rmd_modify.R

rmd_modifyR Documentation

Modify nodes of an Rmd ast

Description

This function applies a function to selected nodes of an rmd_ast or rmd_tibble. The selection is implemented using the same approach as rmd_select() which enables a variety of useful syntax for selecting nodes from the ast.

The function .f must return a valid rmd node object (e.g., rmd_chunk, rmd_heading, etc.). The results are validated to ensure they maintain the proper structure and class.

Usage

rmd_modify(x, .f, ...)

Arguments

x

Rmd object, e.g. rmd_ast or rmd_tibble.

.f

A function to apply to the selected nodes. Must return a valid rmd node object.

...

Selection arguments (unnamed) and function arguments (named). Unnamed arguments are used for node selection using tidyselect syntax. Named arguments are passed to the function .f.

Value

Returns the modified Rmd object (either rmd_ast or rmd_tibble depending on input). Only the selected nodes are modified by applying .f, while unselected nodes remain unchanged.

Examples

rmd = parse_rmd(system.file("examples/hw01.Rmd", package = "parsermd"))

# Modify specific chunks by label
f = function(node) { # Add a comment to the chunk
  node@code = c("# Modified chunk", node@code)
  node
}
rmd_modify(rmd, .f = f, "plot-dino") |>
  rmd_select("plot-dino") |>
  as_document() |>
  cat(sep="\n")

# Modify all chunks with named arguments passed to function
f = function(node, prefix = "## ") {
  node@code = paste0(prefix, node@code)
  node
}
rmd_modify(rmd, f, has_type("rmd_chunk"), prefix = "# ") |>
 rmd_select(has_type("rmd_chunk")) |>
 as_document() |>
 cat(sep="\n")


parsermd documentation built on Aug. 21, 2025, 5:27 p.m.