|
| 1 | +#' Extract R code from Quarto document |
| 2 | +#' |
| 3 | +#' Extracts R code cells from a Quarto document and writes them to an R script |
| 4 | +#' file that can be rendered with the same options. The Markdown text is not |
| 5 | +#' preserved, but R chunk options are kept as comment headers using Quarto's |
| 6 | +#' `#|` syntax. |
| 7 | +#' |
| 8 | +#' @param qmd Character. Path to the input Quarto document (.qmd file). |
| 9 | +#' @param script Character. Path to the output R script file. If `NULL` |
| 10 | +#' (default), the script file will have the same name as the input file |
| 11 | +#' but with `.R` extension. |
| 12 | +#' |
| 13 | +#' @details |
| 14 | +#' This function processes a Quarto document by: |
| 15 | +#' - Extracting only R code cells (markdown and cell in other languages are ignored) |
| 16 | +#' - Preserving chunk options as `#|` comment headers |
| 17 | +#' - Adding the document's YAML metadata as a spin-style header |
| 18 | +#' - Creating an R script that can be rendered with the same options |
| 19 | +#' |
| 20 | +#' ## File handling: |
| 21 | +#' - If the output R script already exists, the function will abort with an error |
| 22 | +#' - Non-R code cells (e.g., Python, Julia, Observable JS) are ignored |
| 23 | +#' - If no R code cells are found, the function does nothing and returns `NULL` |
| 24 | +#' |
| 25 | +#' ## Compatibility: |
| 26 | +#' The resulting R script is compatible with Quarto's script rendering via |
| 27 | +#' `knitr::spin()` and can be rendered directly with `quarto render script.R`. |
| 28 | +#' See <https://quarto.org/docs/computations/render-scripts.html#knitr> for |
| 29 | +#' more details on rendering R scripts with Quarto. |
| 30 | +#' |
| 31 | +#' The resulting R script uses Quarto's executable cell format with `#|` |
| 32 | +#' comments to preserve chunk options like `echo`, `eval`, `output`, etc. |
| 33 | +#' |
| 34 | +#' @return Invisibly returns the path to the created R script file, or |
| 35 | +#' `NULL` if no R code cells were found. |
| 36 | +#' |
| 37 | +#' @examples |
| 38 | +#' \dontrun{ |
| 39 | +#' # Extract R code from a Quarto document |
| 40 | +#' extract_r_code("my-document.qmd") |
| 41 | +#' # Creates "my-document.R" |
| 42 | +#' |
| 43 | +#' # Specify custom output file |
| 44 | +#' extract_r_code("my-document.qmd", script = "extracted-code.R") |
| 45 | +#' } |
| 46 | +#' |
| 47 | +#' @export |
1 | 48 | extract_r_code <- function(qmd, script = NULL) { |
2 | 49 | if (!file.exists(qmd)) { |
3 | 50 | cli::cli_abort( |
|
0 commit comments