r
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.9KB

  1. #' Generate a function to run prior to knitting
  2. #'
  3. #' @description **redoc** modifies R Markdown documents prior to knitting to
  4. #' capture and store document elements that will need to be restored later. It
  5. #' does this via a function passed to the `pre_knit` argument of
  6. #' [rmarkdown::output_format()]. `make_preknitter` generates this function from
  7. #' a list of [wrapper functions][make_wrapper()].
  8. #'
  9. #' @param wrappers a list of [wrapper functions][make_wrapper()].
  10. #'
  11. #' @details **rmarkdown** does not provide a mechanism to modify the file prior
  12. #' to knitting, so **redoc** accomplishes this by reaching up the call stack and
  13. #' modifying the environment in the [rmarkdown::render()] function. The
  14. #' function generated by `make_preknitter` will do this by generating the
  15. #' pre-processed R Markdown file and associated list of code chunks, adding these
  16. #' the list of intermediates for cleanup, and switching the document input to
  17. #' this pre-processed document.
  18. #'
  19. #' @return A function to be used in `output_format(pre_knit = ...)``
  20. #' @importFrom yaml write_yaml
  21. #' @export
  22. #' @examples
  23. #'
  24. #' make_preknitter(wrappers = list(htmlcommentwrap, latexwrap))
  25. make_preknitter <- function(wrappers = list()) {
  26. pre_knit <- function(input, ...) {
  27. render_env <- get_parent_env_with("knit_input")
  28. pre_knit_input <- get("knit_input", envir = render_env)
  29. intermediates_loc <- get("intermediates_loc", envir = render_env)
  30. rmd_text <- normalize_newlines(readfile(input))
  31. rmd <- wrap_code(rmd_text, wrappers = wrappers)
  32. codefile <- intermediates_loc(
  33. file_with_meta_ext(basename(input), "codelist", "yml")
  34. )
  35. preprocessed_rmd_file <- intermediates_loc(
  36. file_with_meta_ext(pre_knit_input, "preprocessed")
  37. )
  38. write_yaml(rmd$code, codefile)
  39. cat(rmd$text, file = preprocessed_rmd_file)
  40. assign("knit_input", preprocessed_rmd_file, envir = render_env)
  41. add_intermediates(c(codefile, preprocessed_rmd_file))
  42. }
  43. return(pre_knit)
  44. }