#' Render Markdown, R Markdown, and R scripts
#'
#' The function `mark()` renders Markdown to an output format via the
#' \pkg{commonmark} package.
#' @param input A character vector to provide the input file path or text. If
#' not provided, the `text` argument must be provided instead. The `input`
#' vector will be treated as a file path if it is a single string, and points
#' to an existing file or has a filename extension. In other cases, the vector
#' will be treated as the `text` argument input. To avoid ambiguity, if a
#' string should be treated as `text` input when it happens to be an existing
#' file path or has an extension, wrap it in [I()], or simply use the `text`
#' argument instead.
#' @param output An output file path or a filename extension (e.g., `.html`,
#' `.tex`, `.xml`, `.man`, `.markdown`, or `.txt`). In the latter case, the
#' output file path will use the extension on the same base filename as the
#' input file if the `input` is a file. If `output` is not character (e.g.,
#' `NA`), the results will be returned as a character vector instead of being
#' written to a file. If `output` is `NULL` or an extension, and the input is
#' a file path, the output file path will have the same base name as the input
#' file, with an extension corresponding to the output format. The output
#' format is retrieved from the first value in the `output` field of the YAML
#' metadata of the `input` (e.g., `html` will generate HTML output). The
#' `output` argument can also take an output format name (possible values are
#' `html`, `latex`, `xml`, `man`, `commonmark`, and `text`). If no output
#' format is detected or provided, the default is HTML.
#' @param text A character vector as the text input. By default, it is read from
#' the `input` file if provided.
#' @param options Options to be passed to the renderer. See [markdown_options()]
#' for details. This argument can take either a character vector of the form
#' `"+option1 option2-option3"` (use `+` or a space to enable an option, and
#' `-` to disable an option), or a list of the form `list(option1 = value1,
#' option2 = value2, ...)`. A string `"+option1"` is equivalent to
#' `list(option1 = TRUE)`, and `"-option2"` means `list(option2 = FALSE)`.
#' Options that do not take logical values must be specified via a list, e.g.,
#' `list(width = 30)`.
#' @param meta A named list of metadata. Elements in the metadata will be used
#' to fill out the template by their names and values, e.g., `list(title =
#' ...)` will replace the `$title$` variable in the template. See the Section
#' \dQuote{YAML metadata} [in the
#' documentation](https://yihui.org/litedown/#sec:yaml-metadata) for supported
#' variables.
#' @return The output file path if output is written to a file, otherwise a
#' character vector of the rendered output (wrapped in [xfun::raw_string()]
#' for clearer printing).
#' @seealso The spec of GitHub Flavored Markdown:
#'
(.+?)\n'
ret = match_replace(ret, r4, function(x) {
lang = gsub(r4, '\\1', x)
code = gsub(r4, '\\2', x)
# restore raw html content from ```{=html}
i1 = lang == 'html'
x[i1] = restore_html(code[i1])
# possible math environments
i2 = (lang %in% c('tex', 'latex')) &
grepl('^\\\\begin\\{[a-zA-Z*]+\\}.+\\\\end\\{[a-zA-Z*]+\\}\n$', code)
if (any(i2)) {
x[i2] = sprintf('\n%s
\n', code[i2]) has_math <<- TRUE } # discard other types of raw content blocks x[!(i1 | i2)] = '' x }, perl = FALSE) # for perl = TRUE, we'd need (?s) before (.+?) # support mermaid r_mmd = '(.*?)'
if (has_mermaid <- length(grep(r_mmd, ret))) {
ret = gsub(r_mmd, '\\1', ret) } r4 = '(
'
# deal with ```{.class1 .class2 attrs}, which is not supported by commonmark
ret = convert_attrs(ret, r4, '\\2', function(r, z, z2) {
z1 = sub(r, '\\1', z)
# make sure `class` is the first attribute
z2 = gsub('^(.+?)( +)(class="[^"]+")(.*)$', '\\3 \\1\\4', z2)
i = grepl('^class="', z2)
z2 = ifelse(i, sub('^class="', '', z2), paste0('"', z2))
paste0(z1, z2, '>')
}, 'html', function(z2) gsub(id4, ' ', restore_html(z2)))
# some code blocks with "attributes" are verbatim ones
ret = match_replace(ret, '```+\\s*\\{.+}', function(x) gsub(id4, ' ', x, fixed = TRUE))
# remove empty table header
ret = gsub('\n\n(]*> \n)+ \n\n', '', ret)
# table caption: a paragraph that starts with 'Table: ' or ': ' after
ret = gsub(
'()(?s)(.+?
)\n(Table)?: (?s)(.+?)
',
'\\1\n\\4 \\2', ret, perl = TRUE
)
# auto identifiers
if (isTRUE(options[['auto_identifiers']])) ret = auto_identifier(ret)
# number sections
if (isTRUE(options[['number_sections']])) ret = number_sections(ret)
# build table of contents
ret = add_toc(ret, options)
# math
if (!has_math) has_math = length(ret) && (
grepl('$$', ret, fixed = TRUE) || grepl('\\)', ret, fixed = TRUE)
) # math may be from pkg_manual()'s HTML
is_katex = TRUE
if (has_math && length(js_math <- js_options(options[['js_math']], 'katex'))) {
is_katex = js_math$package == 'katex'
}
# number figures and tables, etc.
ret = number_refs(ret, r_ref, is_katex)
} else if (format == 'latex') {
if (isTRUE(options[['footnotes']])) ret = fix_footnotes(ret) # fix footnotes
if (has_sup)
ret = gsub(sprintf('!%s(.+?)%s!', id2, id2), '\\\\textsuperscript{\\1}', ret)
if (has_sub)
ret = gsub(sprintf('!%s(.+?)%s!', id3, id3), '\\\\textsubscript{\\1}', ret)
r4 = sprintf(
'(\\\\begin\\{verbatim}\n)%s(.+?)%s\n(.*?\n)(\\\\end\\{verbatim}\n)', id4, id4
)
ret = match_replace(ret, r4, function(x) {
info = gsub(r4, '\\2', x)
info = gsub('^\\{|}$', '', info)
i = info %in% c('=latex', '=tex')
x[i] = gsub(r4, '\\3', x[i]) # restore raw ```{=latex} content
i = !i & grepl('^=', info)
x[i] = '' # discard other raw content
# TODO: support code highlighting for latex (listings or highr::hi_latex)
x = gsub(r4, '\\1\\3\\4', x)
x
}, perl = FALSE)
# for nested verbatim code blocks, the inner blocks may have leftover ```\nid4
ret = gsub(sprintf('(```)\n%s(.*?)%s', id4, id4), '\\1\\2', ret)
# fix horizontal rules from --- (\linethickness doesn't work)
ret = gsub('{\\linethickness}', '{1pt}', ret, fixed = TRUE)
ret = redefine_level(ret, options[['top_level']])
if (isTRUE(options[['toc']])) ret = paste0('\\tableofcontents\n', ret)
}
pkg_cite = yaml_field(yaml, format, 'citation_package')
if (length(pkg_cite) != 1) pkg_cite = 'natbib'
bib = yaml[['bibliography']]
# temporarily save the bib values when previewing a book because bib may only
# be specified in index.Rmd but not other chapters
if (is.character(b <- .env$current_book)) {
if (length(bib)) .env$bib[[b]] = bib else bib = .env$bib[[b]]
}
if (length(bib) == 1 && grepl(',', bib)) bib = strsplit(bib, ',\\s*')[[1]]
# add [@citation] (.bib files are assumed to be under output dir)
if (length(bib)) {
ret = in_dir(out_dir, add_citation(ret, bib, format))
if (format == 'latex') meta = bib_meta(meta, bib, pkg_cite)
}
# convert some meta variables in case they use Markdown syntax
if (is.character(template)) for (i in top_meta) if (meta_len <- length(meta[[i]])) {
# if author is of length > 1, render them individually
m_author = i == 'author' && meta_len > 1
meta[[i]] = if (m_author) uapply(meta[[i]], render) else {
render(meta[[i]], clean = i != 'abstract')
}
# also provide *_ version of top-level meta variables, containing tags/commands
meta[[paste0(i, '_')]] = I(if (format == 'html') {
tag = tag_meta[i]
sprintf(
'