Debian Codegraph @

R/mark.R

raw
1 #' Render Markdown, R Markdown, and R scripts
2 #'
3 #' The function `mark()` renders Markdown to an output format via the
4 #' \pkg{commonmark} package.
5 #' @param input A character vector to provide the input file path or text. If
6 #' not provided, the `text` argument must be provided instead. The `input`
7 #' vector will be treated as a file path if it is a single string, and points
8 #' to an existing file or has a filename extension. In other cases, the vector
9 #' will be treated as the `text` argument input. To avoid ambiguity, if a
10 #' string should be treated as `text` input when it happens to be an existing
11 #' file path or has an extension, wrap it in [I()], or simply use the `text`
12 #' argument instead.
13 #' @param output An output file path or a filename extension (e.g., `.html`,
14 #' `.tex`, `.xml`, `.man`, `.markdown`, or `.txt`). In the latter case, the
15 #' output file path will use the extension on the same base filename as the
16 #' input file if the `input` is a file. If `output` is not character (e.g.,
17 #' `NA`), the results will be returned as a character vector instead of being
18 #' written to a file. If `output` is `NULL` or an extension, and the input is
19 #' a file path, the output file path will have the same base name as the input
20 #' file, with an extension corresponding to the output format. The output
21 #' format is retrieved from the first value in the `output` field of the YAML
22 #' metadata of the `input` (e.g., `html` will generate HTML output). The
23 #' `output` argument can also take an output format name (possible values are
24 #' `html`, `latex`, `xml`, `man`, `commonmark`, and `text`). If no output
25 #' format is detected or provided, the default is HTML.
26 #' @param text A character vector as the text input. By default, it is read from
27 #' the `input` file if provided.
28 #' @param options Options to be passed to the renderer. See [markdown_options()]
29 #' for details. This argument can take either a character vector of the form
30 #' `"+option1 option2-option3"` (use `+` or a space to enable an option, and
31 #' `-` to disable an option), or a list of the form `list(option1 = value1,
32 #' option2 = value2, ...)`. A string `"+option1"` is equivalent to
33 #' `list(option1 = TRUE)`, and `"-option2"` means `list(option2 = FALSE)`.
34 #' Options that do not take logical values must be specified via a list, e.g.,
35 #' `list(width = 30)`.
36 #' @param meta A named list of metadata. Elements in the metadata will be used
37 #' to fill out the template by their names and values, e.g., `list(title =
38 #' ...)` will replace the `$title$` variable in the template. See the Section
39 #' \dQuote{YAML metadata} [in the
40 #' documentation](https://yihui.org/litedown/#sec:yaml-metadata) for supported
41 #' variables.
42 #' @return The output file path if output is written to a file, otherwise a
43 #' character vector of the rendered output (wrapped in [xfun::raw_string()]
44 #' for clearer printing).
45 #' @seealso The spec of GitHub Flavored Markdown:
46 #' <https://github.github.com/gfm/>
47 #' @import utils
48 #' @export
49 #' @examples
50 #'
51 #' mark(c('Hello _World_!', '', 'Welcome to **litedown**.'))
52 #' # if input appears to be a file path but should be treated as text, use I()
53 #' mark(I('This is *not* a file.md'))
54 #' # that's equivalent to
55 #' mark(text = 'This is *not* a file.md')
56 #'
57 #' # output to a file
58 #' (mark('_Hello_, **World**!', output = tempfile()))
59 #'
60 #' # convert to other formats
61 #' mark('Hello _World_!', '.tex')
62 #' mark('Hello _**`World`**_!', 'xml')
63 #' mark('Hello _**`World`**_!', 'text')
64 mark = function(input, output = NULL, text = NULL, options = NULL, meta = list()) {
65 text = read_input(input, text); input = attr(text, 'input')
66 part = yaml_body(text)
67 yaml = part$yaml; yaml2 = yaml_text(part, text) # unparsed YAML
68 text = part$body
69
70 full = is_output_full(output)
71 format = detect_format(output, yaml)
72 output = auto_output(input, output, format)
73 out_dir = dirname(output_path(input, output) %||% '.')
74
75 # title/author/date can be provided as top-level YAML options
76 meta = merge_list(
77 get_option('meta', format),
78 yaml[intersect(names(yaml), top_meta)],
79 yaml_field(yaml, format),
80 list(generator = I(paste('litedown', packageVersion('litedown')))),
81 meta
82 )
83 meta = normalize_meta(meta)
84
85 render_fun = tryCatch(
86 getFromNamespace(paste0('markdown_', tolower(format)), 'commonmark'),
87 error = function(e) {
88 stop("Output format '", format, "' is not supported in commonmark.")
89 }
90 )
91
92 options = merge_list(yaml_field(yaml, format, 'options'), option2list(options))
93 options = normalize_options(options, format)
94 options$extensions = intersect(
95 names(Filter(isTRUE, options)), commonmark::list_extensions()
96 )
97
98 # whether to write YAML metadata to output
99 keep_yaml = isTRUE(options[['keep_yaml']])
100
101 # if keep_yaml or format is not html/latex, don't use template; otherwise
102 # check the `template` value in litedown::(html|latex)_format in YAML
103 template = if (keep_yaml || !format %in% c('html', 'latex')) FALSE else
104 yaml_field(yaml, format, 'template')
105 # if not set there, check global option; if not set, disable template if no
106 # YAML was provided (i.e., generate a fragment)
107 if (is.null(template))
108 template = get_option('template', format, full || 'yaml' %in% names(part))
109 # template = FALSE means no template; other values mean the default template
110 if (!is.character(template)) template = if (!isFALSE(template))
111 pkg_file('resources', sprintf('litedown.%s', format))
112
113 render_args = options[intersect(names(formals(render_fun)), names(options))]
114 render = function(x, clean = FALSE) {
115 if (length(x) == 0) return(x)
116 res = do.call(render_fun, c(list(text = x), render_args))
117 if (clean) res = sans_p(res)
118 I(res)
119 }
120
121 if (isTRUE(options[['smartypants']])) text = smartypants(text)
122
123 # test if a feature needs to be enabled
124 test_feature = function(name, pattern) {
125 isTRUE(options[[name]]) && format %in% c('html', 'latex') &&
126 length(grep(pattern, text, perl = TRUE))
127 }
128
129 # protect $ $ and $$ $$ math expressions for html/latex output
130 if (has_math <- test_feature('latex_math', '[$]')) {
131 id = id_string(text); maths = NULL
132 text = xfun::protect_math(text, id)
133 if (has_math <- any(grepl(paste0('`', id), text, fixed = TRUE))) {
134 # temporarily replace math expressions with tokens so render() won't seem
135 # them (to avoid issues like #33) and restore them later
136 text = one_string(text)
137 text = match_replace(text, sprintf('`%s(?s).{3,}?%s`', id, id), function(x) {
138 # replace math with !id-n-id! where n is the index of the math
139 tokens = sprintf('!%s-%d-%s!', id, length(maths) + seq_along(x), id)
140 math = gsub(sprintf('`%s|%s`', id, id), '', x)
141 maths <<- c(maths, set_names(math, tokens))
142 tokens
143 })
144 if (format == 'html') maths = html_escape(maths)
145 text = split_lines(text)
146 }
147 }
148
149 p = NULL # indices of prose
150 find_prose = local({
151 t = NULL
152 function() {
153 # return early if text has not changed
154 if (!is.null(p) && identical(text, t)) return(p)
155 t <<- text
156 p <<- prose_index(text)
157 }
158 })
159 # superscript and subscript; for now, we allow only characters alnum|*|(|) for
160 # script text but can consider changing this rule upon users' request
161 r2 = '(?<!`)\\^([[:alnum:]*(),.]+?)\\^(?!`)'
162 if (has_sup <- test_feature('superscript', r2)) {
163 id2 = id_string(text)
164 find_prose()
165 text[p] = match_replace(text[p], r2, function(x) {
166 # place superscripts inside !id...id!
167 x = gsub('^\\^|\\^$', id2, x)
168 sprintf('!%s!', x)
169 })
170 }
171 r3 = '(?<![~`[:space:]])~([[:alnum:]*(),.]+?)~(?!`)'
172 if (has_sub <- test_feature('subscript', r3)) {
173 id3 = id_string(text)
174 find_prose()
175 text[p]= match_replace(text[p], r3, function(x) {
176 # place subscripts inside !id...id!
177 x = gsub('^~|~$', id3, x)
178 sprintf('!%s!', x)
179 })
180 }
181 find_prose()
182 # add line breaks before/after fenced Div's to wrap ::: tokens into separate
183 # paragraphs or code blocks
184 text[p] = sub('^([ >]*:::+ )([^ {]+)$', '\\1{.\\2}', text[p]) # ::: foo -> ::: {.foo}
185 text[p] = sub(
186 '^([ >]*)((:::+)( \\{.*\\})?)$',
187 if (format == 'latex') '\\1\n\\1```\n\\1\\2 \\3\n\\1```\n\\1' else '\\1\n\\1\\2\n\\1',
188 text[p]
189 )
190
191 id4 = id_string(text)
192 if (format == 'latex') {
193 # put info string inside code blocks so the info won't be lost, e.g., ```r -> ```\nr
194 text = gsub(
195 '^([> ]*)(```+)([^`].*)$', sprintf('\\1\\2\n\\1%s\\3%s', id4, id4), text
196 )
197 } else if (format == 'html' && length(p) < length(text)) {
198 # hide spaces so that attributes won't be dropped: {.lang foo} -> {.lang!id!foo}
199 r4 = '^([> ]*```+\\s*)(\\{.+})\\s*$'
200 text = match_replace(text, r4, function(x) {
201 x1 = sub(r4, '\\1', x)
202 x2 = sub(r4, '\\2', x)
203 x2 = gsub(' ', id4, x2, fixed = TRUE)
204 paste0(x1, x2)
205 })
206 }
207
208 # turn @ref into [@ref](#ref) and resolve cross-references later in JS; for
209 # latex output, turn @ref to \ref{}
210 r_ref = '(([a-z]+)[-:][-_[:alnum:]]+)' # must start with letters followed by - or :
211 r5 = paste0('(^|(?<=\\s|\\())@', r_ref, '(?!\\])')
212 if (test_feature('cross_refs', r5)) {
213 text[p] = match_replace(text[p], r5, function(x) {
214 sprintf('[%s](%s)', x, sub('^@', '#', x))
215 })
216 }
217
218 ret = render(text)
219 ret = move_attrs(ret, format) # apply attributes of the form {attr="value"}
220
221 if (has_math) ret = match_replace(ret, sprintf('!%s-\\d+-%s!', id, id), function(x) {
222 if (length(maths) != length(x)) warning(
223 'LaTeX math expressions cannot be restored correctly (expected ',
224 length(maths), ' expression(s) but found ', length(x), ' in the output).'
225 )
226 maths[x]
227 })
228
229 has_mermaid = FALSE
230
231 if (format == 'html') {
232 # don't disable check boxes
233 ret = gsub('(<li><input type="checkbox" [^>]*?)disabled="" (/>)', '\\1\\2', ret)
234 # replace <a> with <span> if href is empty but other attrs exist, so we have
235 # a way to create SPANs with attributes, e.g., [text](){.foo} -> <span
236 # class="foo"></span>
237 ret = gsub('<a href="" ([^>]+>.*?</)a>', '<span \\1span>', ret)
238 if (has_sup)
239 ret = gsub(sprintf('!%s(.+?)%s!', id2, id2), '<sup>\\1</sup>', ret)
240 if (has_sub)
241 ret = gsub(sprintf('!%s(.+?)%s!', id3, id3), '<sub>\\1</sub>', ret)
242 r4 = '<pre><code class="language-\\{=([^}]+)}">(.+?)</code></pre>\n'
243 ret = match_replace(ret, r4, function(x) {
244 lang = gsub(r4, '\\1', x)
245 code = gsub(r4, '\\2', x)
246 # restore raw html content from ```{=html}
247 i1 = lang == 'html'
248 x[i1] = restore_html(code[i1])
249 # possible math environments
250 i2 = (lang %in% c('tex', 'latex')) &
251 grepl('^\\\\begin\\{[a-zA-Z*]+\\}.+\\\\end\\{[a-zA-Z*]+\\}\n$', code)
252 if (any(i2)) {
253 x[i2] = sprintf('<p>\n%s</p>\n', code[i2])
254 has_math <<- TRUE
255 }
256 # discard other types of raw content blocks
257 x[!(i1 | i2)] = ''
258 x
259 }, perl = FALSE) # for perl = TRUE, we'd need (?s) before (.+?)
260 # support mermaid
261 r_mmd = '<pre><code class="language-mermaid">(.*?)</code></pre>'
262 if (has_mermaid <- length(grep(r_mmd, ret))) {
263 ret = gsub(r_mmd, '<pre class="mermaid">\\1</pre>', ret)
264 }
265 r4 = '(<pre><code class="language-)\\{([^"]+)}">'
266 # deal with ```{.class1 .class2 attrs}, which is not supported by commonmark
267 ret = convert_attrs(ret, r4, '\\2', function(r, z, z2) {
268 z1 = sub(r, '\\1', z)
269 # make sure `class` is the first attribute
270 z2 = gsub('^(.+?)( +)(class="[^"]+")(.*)$', '\\3 \\1\\4', z2)
271 i = grepl('^class="', z2)
272 z2 = ifelse(i, sub('^class="', '', z2), paste0('"', z2))
273 paste0(z1, z2, '>')
274 }, 'html', function(z2) gsub(id4, ' ', restore_html(z2)))
275 # some code blocks with "attributes" are verbatim ones
276 ret = match_replace(ret, '```+\\s*\\{.+}', function(x) gsub(id4, ' ', x, fixed = TRUE))
277 # remove empty table header
278 ret = gsub('<thead>\n<tr>\n(<th[^>]*></th>\n)+</tr>\n</thead>\n', '', ret)
279 # table caption: a paragraph that starts with 'Table: ' or ': ' after </table>
280 ret = gsub(
281 '(<table>)(?s)(.+?</table>)\n<p>(Table)?: (?s)(.+?)</p>',
282 '\\1\n<caption>\\4</caption>\\2', ret, perl = TRUE
283 )
284 # auto identifiers
285 if (isTRUE(options[['auto_identifiers']])) ret = auto_identifier(ret)
286 # number sections
287 if (isTRUE(options[['number_sections']])) ret = number_sections(ret)
288 # build table of contents
289 ret = add_toc(ret, options)
290 # math
291 if (!has_math) has_math = length(ret) && (
292 grepl('$$</p>', ret, fixed = TRUE) || grepl('\\)</span>', ret, fixed = TRUE)
293 ) # math may be from pkg_manual()'s HTML
294 is_katex = TRUE
295 if (has_math && length(js_math <- js_options(options[['js_math']], 'katex'))) {
296 is_katex = js_math$package == 'katex'
297 }
298 # number figures and tables, etc.
299 ret = number_refs(ret, r_ref, is_katex)
300 } else if (format == 'latex') {
301 if (isTRUE(options[['footnotes']])) ret = fix_footnotes(ret) # fix footnotes
302 if (has_sup)
303 ret = gsub(sprintf('!%s(.+?)%s!', id2, id2), '\\\\textsuperscript{\\1}', ret)
304 if (has_sub)
305 ret = gsub(sprintf('!%s(.+?)%s!', id3, id3), '\\\\textsubscript{\\1}', ret)
306 r4 = sprintf(
307 '(\\\\begin\\{verbatim}\n)%s(.+?)%s\n(.*?\n)(\\\\end\\{verbatim}\n)', id4, id4
308 )
309 ret = match_replace(ret, r4, function(x) {
310 info = gsub(r4, '\\2', x)
311 info = gsub('^\\{|}$', '', info)
312 i = info %in% c('=latex', '=tex')
313 x[i] = gsub(r4, '\\3', x[i]) # restore raw ```{=latex} content
314 i = !i & grepl('^=', info)
315 x[i] = '' # discard other raw content
316 # TODO: support code highlighting for latex (listings or highr::hi_latex)
317 x = gsub(r4, '\\1\\3\\4', x)
318 x
319 }, perl = FALSE)
320 # for nested verbatim code blocks, the inner blocks may have leftover ```\nid4
321 ret = gsub(sprintf('(```)\n%s(.*?)%s', id4, id4), '\\1\\2', ret)
322 # fix horizontal rules from --- (\linethickness doesn't work)
323 ret = gsub('{\\linethickness}', '{1pt}', ret, fixed = TRUE)
324 ret = redefine_level(ret, options[['top_level']])
325 if (isTRUE(options[['toc']])) ret = paste0('\\tableofcontents\n', ret)
326 }
327
328 pkg_cite = yaml_field(yaml, format, 'citation_package')
329 if (length(pkg_cite) != 1) pkg_cite = 'natbib'
330 bib = yaml[['bibliography']]
331 # temporarily save the bib values when previewing a book because bib may only
332 # be specified in index.Rmd but not other chapters
333 if (is.character(b <- .env$current_book)) {
334 if (length(bib)) .env$bib[[b]] = bib else bib = .env$bib[[b]]
335 }
336 if (length(bib) == 1 && grepl(',', bib)) bib = strsplit(bib, ',\\s*')[[1]]
337 # add [@citation] (.bib files are assumed to be under output dir)
338 if (length(bib)) {
339 ret = in_dir(out_dir, add_citation(ret, bib, format))
340 if (format == 'latex') meta = bib_meta(meta, bib, pkg_cite)
341 }
342
343 # convert some meta variables in case they use Markdown syntax
344 if (is.character(template)) for (i in top_meta) if (meta_len <- length(meta[[i]])) {
345 # if author is of length > 1, render them individually
346 m_author = i == 'author' && meta_len > 1
347 meta[[i]] = if (m_author) uapply(meta[[i]], render) else {
348 render(meta[[i]], clean = i != 'abstract')
349 }
350 # also provide *_ version of top-level meta variables, containing tags/commands
351 meta[[paste0(i, '_')]] = I(if (format == 'html') {
352 tag = tag_meta[i]
353 sprintf(
354 '<div class="%s">%s</div>', i, if (tag == '') meta[[i]] else {
355 one_string(sprintf('<%s>%s</%s>', tag, meta[[i]], tag))
356 }
357 )
358 } else if (format == 'latex') {
359 sprintf(cmd_meta[i], if (m_author) one_string(meta[[i]], ' \\and ') else meta[[i]])
360 })
361 }
362
363 # cross references (\ref or clever \cref)
364 clever = isTRUE(options[['cleveref']])
365 if (format == 'latex') ret = latex_refs(ret, r_ref, clever) else clever = FALSE
366
367 # use the template (if provided) to create a standalone document
368 if (is.character(template)) {
369 meta$body = I(ret)
370 if (format == 'html') {
371 # reset the internal js/css stored in acc_var() on exit
372 on.exit(acc_var(), add = TRUE)
373 # add js/css for math
374 if (has_math) set_math(js_math, is_katex)
375 # add js/css for syntax highlighting
376 set_highlight(options, ret)
377 # add js for mermaid
378 if (has_mermaid && length(grep('mermaid', meta[['js']])) == 0)
379 acc_var(js = '@npm/mermaid/dist/mermaid.min.js')
380 }
381 ret = build_output(
382 format, options, template, meta, test = c(if (length(input)) dirname(input), '.')
383 )
384 # load the cleveref package if not loaded
385 if (clever && !any(grepl('\\\\usepackage.*\\{cleveref\\}', ret, perl = TRUE)))
386 ret = sub('(?=\\\\begin\\{document\\})', '\\\\usepackage{cleveref}\n', ret, perl = TRUE)
387 }
388
389 if (format == 'html') {
390 ret = in_dir(out_dir, embed_resources(ret, options))
391 ret = clean_html(ret)
392 } else if (format == 'latex') {
393 # remove \maketitle if \title is absent
394 if (!grepl('\n\\title{', ret, fixed = TRUE))
395 ret = gsub('\n\\maketitle\n', '\n', ret, fixed = TRUE)
396 }
397
398 if (keep_yaml) ret = one_string(c(yaml2, '', ret))
399
400 ret = sub('\n$', '', ret)
401 if (is_output_file(output)) {
402 # build PDF for LaTeX output when the output file is .pdf
403 is_pdf = FALSE
404 if (format == 'latex') {
405 latex_engine = yaml_field(yaml, format, 'latex_engine')
406 if (is.character(latex_engine) || file_ext(output) == 'pdf') {
407 is_pdf = TRUE
408 tex = with_ext(output, '.tex')
409 if (!isTRUE(yaml_field(yaml, format, 'keep_tex')))
410 on.exit(file.remove(tex), add = TRUE)
411 write_utf8(ret, tex)
412 output = tinytex::latexmk(
413 tex, latex_engine %||% 'xelatex',
414 if (pkg_cite == 'biblatex') 'biber' else 'bibtex'
415 )
416 }
417 }
418 # for RStudio to capture the output path when previewing the output
419 if (is_rmd_preview()) message('\nOutput created: ', output)
420 if (is_pdf) invisible(output) else write_utf8(ret, output)
421 } else raw_string(ret, lang = paste0('.', format))
422 }
423
424 # insert body and meta variables into a template
425 build_output = function(format, options, template, meta, ...) {
426 tpl = one_string(template, ...)
427 if (format == 'html') {
428 defaults = list(
429 'css' = 'default',
430 'plain-title' = I(str_trim(commonmark::markdown_text(meta[['title']])))
431 )
432 for (i in setdiff(names(defaults), names(meta))) meta[[i]] = defaults[[i]]
433 # special handling for css/js "files" that have no extensions
434 for (i in c('css', 'js')) {
435 i2 = paste0(i, '2') # treat css2/js2 as global base (e.g. for sites)
436 meta[[i]] = resolve_files(c(meta[[i2]], meta[[i]], acc_var(i)), i)
437 }
438 }
439 sub_vars(tpl, meta, ...)
440 }
441
442 # substitute all variables in template with their values
443 sub_vars = function(tpl, meta, ...) {
444 # find all variables in the template
445 vars = unlist(match_full(tpl, '[$][-_[:alnum:]]+[$]'))
446 # insert $body$ at last in case the body contain any $variables$ accidentally
447 if (!is.na(i <- match('$body$', vars))) vars = c(vars[-i], vars[i])
448 for (v in vars) {
449 tpl = sub_var(tpl, v, meta[[gsub('[$]', '', v)]], ...)
450 }
451 tpl
452 }
453
454 top_meta = c('title', 'subtitle', 'author', 'date', 'abstract')
455 tag_meta = c('h1', 'h2', 'h2', 'h3', '')
456 names(tag_meta) = top_meta
457 cmd_meta = c(sprintf('\\%s{%%s}', top_meta[-5]), '\\begin{abstract}\n%s\\end{abstract}')
458 names(cmd_meta) = top_meta
459
460 yaml_text = function(part, text) if (length(l <- part$lines) == 2) text[l[1]:l[2]]
461
462 #' Markdown rendering options
463 #'
464 #' A list of all options to control Markdown rendering. Options that are enabled
465 #' by default are marked by a `+` prefix, and those disabled by default are
466 #' marked by `-`.
467 #'
468 #' See <https://yihui.org/litedown/#sec:markdown-options> for the full list of
469 #' options and their documentation.
470 #' @return A character vector of all available options.
471 #' @export
472 #' @examples
473 #' # all available options
474 #' litedown::markdown_options()
475 markdown_options = function() {
476 # options enabled by default
477 x1 = c(
478 'smart', 'embed_resources', 'embed_cleanup', 'js_math', 'js_highlight', 'footnotes',
479 'superscript', 'subscript', 'latex_math', 'auto_identifiers', 'cross_refs',
480 setdiff(commonmark::list_extensions(), 'tagfilter')
481 )
482 # options disabled by default
483 x2 = c(
484 'toc', 'hardbreaks', 'tagfilter', 'number_sections', 'cleveref', 'offline',
485 'smartypants'
486 )
487 sort(c(paste0('+', x1), paste0('-', x2)))
488 }