R/plugin-markdown.R

Defines functions markdown

Documented in markdown

#' Convert markdown to html
#'
#' Use the \pkg{markdown} package. Markdown inputs are converted to html
#' and their extension changed to \code{.html}. Binary files are ignored.
#'
#' @param pattern Regular expression used to identify markdown files.
#' @export
#' @examples
#' static_site <- rsmith_demo("static-site")
#' static_site %>% preview()
#' static_site %>% use(markdown()) %>% preview()
markdown <- function(pattern = "\\.md$") {
  if (!is_installed("markdown")) {
    stop("Please install the markdown package", call. = FALSE)
  }

  plugin("markdown", function(file) {
    if (!grepl(pattern, path(file)) || is_binary(file)) return(file)

    if (nzchar(file$contents)) {
      html <- markdown::markdownToHTML(text = file$contents, fragment.only = TRUE)
      file$contents <- html
    }

    path <- tools::file_path_sans_ext(file$metadata$.path)
    file$metadata$.path <- paste0(path, ".html")

    file
  })
}
hadley/rsmith documentation built on May 17, 2019, 12:16 p.m.