Debian Codegraph @

R/utils.R

raw
1 # reset an environment using "objects" in a list
2 reset_env = function(x = list(), envir) {
3 rm(list = ls(envir, all.names = TRUE), envir = envir)
4 list2env(x, envir)
5 }
6
7 # counters for elements to be cross-referenced (e.g., fig, tab)
8 counters = local({
9 db = NULL
10 list(
11 get = function() db,
12 inc = function(name) db[[name]] <<- (db[[name]] %||% 0L) + 1L,
13 del = function(name) db <<- NULL
14 )
15 })
16
17 # use PCRE by default (which seems to handle multibyte chars better)
18 gregexpr = function(..., perl = TRUE) base::gregexpr(..., perl = perl)
19 attr = function(...) base::attr(..., exact = TRUE) # exact attr() please
20 `%|%` = function(x, y) if (length(x)) x else y
21 if (getRversion() < '4.4.0') `%||%` = function(x, y) if (is.null(x)) y else x
22 set_names = function(x, nm) {
23 names(x) = nm; x
24 }
25
26 dropNULL = function(x) x[!vapply(x, is.null, logical(1))]
27
28 # remove the <p> tag from HTML
29 sans_p = function(x) gsub('^<p[^>]*>|(</p>)?\n$', '', x)
30
31 # remove ugly single quotes, e.g., 'LaTeX' -> LaTeX
32 sans_sq = function(x) gsub("(^|\\W)'([^']+)'(\\W|$)", '\\1\\2\\3', x)
33
34 # remove YAML header (if title exists, convert it to h1)
35 sans_yaml = function(x) {
36 if (length(x) && grepl('^---\\s*?($|\n)', x[1])) {
37 res = xfun::yaml_body(split_lines(x))
38 x = c(if (is.character(t <- res$yaml$title)) paste('#', t), res$body)
39 }
40 x
41 }
42
43 split_chunk = function(...) xfun::divide_chunk(..., use_yaml = FALSE)
44
45 is_lang = function(x) is.symbol(x) || is.language(x)
46
47 uapply = function(..., recursive = TRUE) unlist(lapply(...), recursive = recursive)
48 .mapply = function(fun, ...) base::.mapply(fun, list(...), NULL)
49
50 #' Convert some ASCII strings to HTML entities
51 #'
52 #' Transform ASCII strings `(c)` (copyright), `(r)` (registered trademark),
53 #' `(tm)` (trademark), and fractions `n/m` into *smart* typographic HTML
54 #' entities.
55 #' @param text A character vector of the Markdown text.
56 #' @return A character vector of the transformed text.
57 #' @keywords internal
58 smartypants = function(text) {
59 text = split_lines(text)
60 i = prose_index(text)
61 r = '(?<!`)\\((c|r|tm)\\)|(\\d+/\\d+)(?!`)'
62 text[i] = match_replace(text[i], r, function(z) {
63 y = pants[z]
64 i = is.na(y)
65 y[i] = z[i]
66 y
67 })
68 text
69 }
70
71 # Represent some fractions with HTML entities
72 fracs = local({
73 n1 = c(
74 '1/2', '1/3', '2/3', '1/4', '3/4', '1/5', '2/5', '3/5', '4/5', '1/6', '5/6',
75 '1/8', '3/8', '5/8', '7/8'
76 )
77 n2 = c('1/7', '1/9', '1/10')
78 x2 = seq_along(n2) + 8527 # &#8528;, 8529, 8530
79 set_names(c(sprintf('&frac%s;', gsub('/', '', n1)), sprintf('&#%d;', x2)), c(n1, n2))
80 })
81
82 pants = c(fracs, c('(c)' = '&copy;', '(r)' = '&reg;', '(tm)' = '&trade;'))
83
84 # merge a later list in arguments into a former one by name
85 merge_list = function(...) {
86 dots = list(...)
87 res = dots[[1]]
88 for (i in seq_along(dots) - 1L) {
89 if (i == 0) next
90 x = dots[[i + 1]]
91 if (!is.list(x)) next
92 res[names(x)] = x
93 }
94 res
95 }
96
97 CHARS = c(letters, LETTERS, 0:9, '!', ',', '/', ':', ';', '=', '@')
98
99 # generate a random string that is not present in provided text
100 id_string = function(text, lens = c(5:10, 20), times = 20) {
101 for (i in lens) {
102 for (j in seq_len(times)) {
103 id = paste(sample(CHARS, i, replace = TRUE), collapse = '')
104 if (length(grep(id, text, fixed = TRUE)) == 0) return(id)
105 }
106 }
107 # failure should be very rare
108 stop('Failed to generate a unique ID string. You may try again.')
109 }
110
111 # a shorthand for gregexpr() and regmatches()
112 match_replace = function(x, r, replace = identity, ...) {
113 m = gregexpr(r, x, ...)
114 regmatches(x, m) = lapply(regmatches(x, m), function(z) {
115 if (length(z)) replace(z) else z
116 })
117 x
118 }
119
120 # gregexec() + regmatches() to greedy-match all substrings in regex groups
121 match_all = function(x, r, ...) {
122 regmatches(x, base::gregexec(r, x, ...))
123 }
124 # for R < 4.1.0
125 if (!exists('gregexec', baseenv(), inherits = TRUE)) match_all = function(x, r, ...) {
126 lapply(match_full(x, r, ...), function(z) {
127 if (length(z)) do.call(cbind, match_one(z, r, ...)) else z
128 })
129 }
130
131 # regexec() + regmatches() to match the regex once and capture substrings
132 match_one = function(x, r, ...) regmatches(x, regexec(r, x, ...))
133
134 # gregexpr() + regmatches() to match full strings but not substrings in regex groups
135 match_full = function(x, r, ...) regmatches(x, gregexpr(r, x, ...))
136
137 # if `text` is NULL and `input` is a file, read it; otherwise use the `text`
138 # argument as input
139 read_input = function(input, text) {
140 if (missing(input)) input = NULL
141 if (is.null(text)) {
142 if (is.null(input)) stop("Either 'input' or 'text' must be provided.")
143 text = if (is_file(input)) read_utf8(input) else input
144 }
145 structure(split_lines(text), input = if (is_file(input)) input)
146 }
147
148 # test if an input is a file path; if shouldn't be treated as file, use I()
149 is_file = function(x) {
150 length(x) == 1 && !inherits(x, 'AsIs') && is.character(x) &&
151 (file_ext(x) != '' || suppressWarnings(file_exists(x)))
152 }
153
154 is_output_file = function(x) {
155 is.character(x) && !(x %in% names(md_formats) || is_ext(x))
156 }
157
158 is_ext = function(x) grepl('^[.]', x) && sans_ext(x) == ''
159
160 # if output has an attribute full = TRUE
161 is_output_full = function(x) isTRUE(attr(x, 'full'))
162
163 # test if input is R code or not (this is based on heuristics and may not be robust)
164 is_R = function(input, text) {
165 if (is_file(input)) grepl('[.][Rrs]$', input) else {
166 # if R code, it must not contain ```{, be syntactically valid, and contain
167 # at least one expression (i.e., not all comments)
168 !length(grep('^\\s*```+\\{', text)) && !try_error(res <- parse_only(text)) && length(res)
169 }
170 }
171
172 # make an output filename with the format and input name
173 auto_output = function(input, output, format = NULL) {
174 # change NULL to a filename extension
175 if (is.null(output) && !is.null(format)) {
176 output = md_formats[format]
177 if (is.na(output)) stop(
178 "The output format '", format, "' is not supported (must be ",
179 xfun::join_words(names(md_formats), and = ' or ', before = "'"), ")."
180 )
181 }
182 # non-character `output` means the output shouldn't be written to a file
183 if (is.character(output)) {
184 if (startsWith(output, 'markdown:')) output = 'markdown'
185 # if `output` is an extension, make a full file path based on input
186 if (is_ext(output)) {
187 if (is_file(input)) output = with_ext(input, output)
188 }
189 if (is_file(input)) check_output(input, output)
190 }
191 output
192 }
193
194 # fall back to input path if output path is not available
195 output_path = function(input, output) {
196 if (is_output_file(output)) output else if (is_file(input)) input
197 }
198
199 # make sure not to overwrite input file inadvertently
200 check_output = function(input, output) {
201 if (file_exists(input) && same_path(input, output))
202 stop('The output file path is the same as input: ', input)
203 output
204 }
205
206 # substitute a variable in template `x` with its value; the variable may have
207 # more than one possible name, in which case we try them one by one
208 sub_var = function(x, name, value, ...) {
209 for (i in name) {
210 if (any(grepl(i, x, fixed = TRUE))) {
211 return(sub(i, one_string(value, ...), x, fixed = TRUE))
212 }
213 }
214 x
215 }
216
217 # unescape HTML code
218 restore_html = function(x) {
219 x = gsub('&quot;', '"', x, fixed = TRUE)
220 x = gsub('&amp;', '&', x, fixed = TRUE)
221 x = gsub('&lt;', '<', x, fixed = TRUE)
222 x = gsub('&gt;', '>', x, fixed = TRUE)
223 x
224 }
225
226 #' Add CSS/JS assets to HTML output
227 #'
228 #' While CSS/JS assets can be set via the `css`/`js` keys under the `meta` field
229 #' of the `html` output format in YAML, this function provides another way to
230 #' add them, which can be called in a code chunk to dynamically add assets.
231 #' @param feature A character vector of features supported by CSS/JS, e.g.,
232 #' `c('article', 'callout')`. See the row names of `litedown:::assets` for all
233 #' available features. Each feature will be mapped to CSS/JS.
234 #' @param css,js Character vectors of CSS/JS assets.
235 #' @return A vector of `<link>` (CSS) or `<script>` (JS) tags.
236 #' @export
237 #' @examples
238 #' litedown:::assets[, -1]
239 #' # add features
240 #' litedown::vest(c('copy-button', 'tabsets'))
241 #' # add css/js directly
242 #' litedown::vest(css = '@tabsets', js = c('@tabsets', '@fold-details'))
243 vest = function(feature = NULL, css = NULL, js = NULL) {
244 if (length(feature)) {
245 a = assets[feature, , drop = FALSE]
246 css = c(a[, 'css'], css); js = c(a[, 'js'], js)
247 }
248 new_asis(c(resolve_files(css, 'css'), resolve_files(js, 'js')), raw = TRUE)
249 }
250
251 assets = t(data.frame(
252 article = c('side notes, floats, and full-width elements for articles', '@article', '@sidenotes, @appendix'),
253 book = c('cover and chapter pages for books', '@book', NA),
254 callout = c('frames with legends', '@callout', '@callout'),
255 'center-img' = c('center images in paragraphs', NA, '@center-img'),
256 'chapter-toc' = c('add TOC to each chapter', NA, '@chapter-toc'),
257 'copy-button' = c('copy buttons', '@copy-button', '@copy-button'),
258 default = c('default CSS', '@default', NA),
259 'external-link' = c('open external links in new windows', NA, '@external-link'),
260 'fold-details' = c('fold elements (e.g., code blocks)', NA, '@fold-details'),
261 'heading-anchor' = c('add anchor links to headings', '@heading-anchor', '@heading-anchor'),
262 'key-buttons' = c('style keyboard shortcuts', '@key-buttons', '@key-buttons'),
263 pages = c('paginate HTML for printing', '@pages', '@pages'),
264 'right-quote' = c('right-align quote footers', NA, '@right-quote'),
265 snap = c('snap slides', '@snap', '@snap'),
266 tabsets = c('create tabsets from bullet lists or sections', '@tabsets', '@tabsets'),
267 'toc-highlight' = c('highlight TOC items on scroll', NA, '@toc-highlight'),
268 row.names = c('description', 'css', 'js'), check.names = FALSE
269 ))
270
271 # an HTML form for creating new files in roam()
272 feature_form = function(path) {
273 nms = rownames(assets)
274 files = list.files(if (dir.exists(path)) path else dirname(path), full.names = TRUE)
275 files = basename(files[file_exists(files)])
276 one_string(c(
277 '<h3>New File</h3>',
278 '<p><label>Filename: <input type="text" id="filename-input" list="file-list" placeholder="enter a new filename (not in the list)" /></label></p>',
279 if (length(files)) c(
280 '<datalist id="file-list">',
281 sprintf('<option value="&#10060; %s">', html_escape(files, TRUE)),
282 '</datalist>'
283 ),
284 '<p><b>Select HTML features</b></p>', '<p style="columns:20em;">',
285 sprintf(
286 '<label><input name="%s" type="checkbox" /> <a href="https://yihui.org/litedown/#sec:%s" target="_blank"><code>%s</code></a>: %s</label>',
287 nms, nms, nms, html_escape(assets[, 'description'])
288 ), '</p>'
289 ))
290 }
291
292 na_omit = function(x) x[!is.na(x)]
293
294 # accumulate variable values
295 acc_var = local({
296 db = list()
297 function(...) {
298 v = list(...)
299 if (is.null(nms <- names(v))) {
300 v = unlist(v)
301 switch(length(v) + 1, db <<- list(), db[[v]], db[v])
302 } else {
303 for (i in nms) db[[i]] <<- c(db[[i]], v[[i]])
304 }
305 }
306 })
307
308 # set js/css variables according to the js_math option
309 set_math = function(o, is_katex) {
310 if (is_katex) o$js = c(o$js, 'dist/contrib/auto-render.min.js')
311 js = js_combine(sprintf('npm/%s%s/%s', o$package, o$version, o$js))
312 js = if (is_katex) c(js, '@render-katex') else c('@mathjax-config', js)
313 css = sprintf('@npm/%s%s/%s', o$package, o$version, o$css)
314 acc_var(js = js, css = css)
315 }
316
317 # use jsdelivr's combine feature
318 js_combine = function(...) {
319 if (length(x <- c(...))) paste0('@', paste(x, collapse = ','))
320 }
321
322 js_options = function(x, default) {
323 d = js_default(x, default)
324 x = if (is.list(x)) merge_list(d, x) else d
325 if (length(x) == 0) return()
326 if (x$version != '') x$version = sub('^@?', '@', x$version)
327 x
328 }
329
330 js_default = function(x, default) {
331 if (is.list(x)) x = x$package
332 if (is.null(x) || isTRUE(x)) x = default
333 if (is.character(x)) merge_list(js_libs[[x]], list(package = x))
334 }
335
336 js_libs = list(
337 highlight = list(
338 version = '11.7.0', style = 'xcode', js = 'build/highlight.min.js'
339 ),
340 katex = list(version = '', css = 'dist/katex.min.css', js = 'dist/katex.min.js'),
341 mathjax = list(version = '3', js = 'es5/tex-mml-chtml.js'),
342 prism = list(
343 version = '1.29.0', js = 'components/prism-core.min.js'
344 )
345 )
346
347 # set js/css variables according to the js_highlight option
348 set_highlight = function(options, html) {
349 # if the class .line-numbers is present, add js/css for line numbers
350 if (any(grepl('<code class="[^"]*line-numbers', html)))
351 acc_var(js = '@code-line-numbers', css = '@code-line-numbers')
352
353 r = '(?<=<code class="language-)([^"]+)(?=")'
354 if (!any(grepl(r, html, perl = TRUE))) return()
355 if (!length(o <- js_options(options[['js_highlight']], 'prism'))) return()
356
357 p = o$package
358 # return jsdelivr subpaths
359 get_path = function(path) {
360 t = switch(
361 p, highlight = 'gh/highlightjs/cdn-release%s/%s', prism = 'npm/prismjs%s/%s'
362 )
363 sprintf(t, o$version, path)
364 }
365 # add the `prism-` prefix if necessary
366 normalize_prism = function(x) {
367 if (length(x) == 1 && x == 'prism') x else sub('^(prism-)?', 'prism-', x)
368 }
369
370 # if resources need to be embedded, we need to work harder to figure out which
371 # js files to embed (this is quite tricky and may not be robust)
372 embed = ('https' %in% options[['embed_resources']]) || is.character(options[['offline']])
373
374 # style -> css
375 css = c(if (is.null(s <- o$style)) {
376 if (p == 'prism') '@prism-xcode' # use prism-xcode.css in the lite.js repo
377 } else if (is.character(s)) js_combine(get_path(switch(
378 p,
379 highlight = sprintf('build/styles/%s.min.css', s),
380 prism = sprintf('themes/%s.min.css', normalize_prism(s))
381 ))))
382
383 # languages -> js
384 get_lang = function(x) switch(
385 p,
386 highlight = sprintf('build/languages/%s.min.js', x),
387 prism = sprintf('components/%s.min.js', normalize_prism(x))
388 )
389 autoloader = 'plugins/autoloader/prism-autoloader.min.js'
390 o$js = c(o$js, if (!is.null(l <- o$languages)) get_lang(l) else {
391 # detect <code> languages in html and load necessary language components
392 lang = unlist(match_full(html, r))
393 lang = gsub(' .*', '', lang) # only use the first class name
394 lang = setdiff(lang, 'plain') # exclude known non-existent names
395 f = switch(p, highlight = js_libs[[c(p, 'js')]], prism = autoloader)
396 if (!embed && p == 'prism') f else {
397 get_lang(lang_files(p, get_path(f), lang))
398 }
399 })
400 js = get_path(o$js)
401 if (p == 'highlight') js = c(js, 'npm/@xiee/utils/js/load-highlight.js')
402 # do not combine js when they are automatically detected (this will make
403 # embedding faster because each js is a separate URL that has been downloaded)
404 js = if (is.null(l)) paste0('@', js) else js_combine(js)
405
406 acc_var(js = js, css = css)
407 }
408
409 # figure out which language support files are needed for highlight.js/prism.js
410 lang_files = function(package, path, langs) {
411 u = jsdelivr(path, '')
412 x = download_cache$get(u, 'text')
413 x = one_string(x)
414
415 warn = function(l1, l2, url) warning(
416 "Unable to recognize code blocks with language(s): ", comma_list(l2),
417 ". They will not be syntax highlighted by ", package, ".js. If you can find ",
418 "the right language files at ", url, ", you may mannually specify their names ",
419 "in the 'languages' field of the 'js_highlight' option.",
420 if (length(l1)) c(" Also remember to add ", comma_list(l1))
421 )
422
423 if (package == 'highlight') {
424 # first figure out all languages bundles in highlight.js (starting with grmr_)
425 x = unlist(strsplit(x, ',\n?grmr_'))
426 r = '^([[:alnum:]_-]+):.+'
427 x = grep(r, x, value = TRUE)
428 l = gsub(r, '\\1', x)
429 # then find their aliases
430 a = lapply(match_full(x, '(?<=aliases:\\[)[^]]+(?=\\])'), function(z) {
431 z = unlist(strsplit(z, '[",]'))
432 z[!is_blank(z)]
433 })
434 l = c(l, unlist(a)) # all possible languages that can be highlighted
435 l = setdiff(langs, l) # languages not supported by default
436 if (length(l) == 0) return()
437 # check if language files exist on CDN
438 d = paste0(dirname(u), '/languages/')
439 l1 = uapply(l, function(z) {
440 if (downloadable(sprintf('%s%s.min.js', d, z))) z
441 })
442 l2 = setdiff(l, l1)
443 if (length(l2)) warn(l1, l2, d)
444 l1
445 } else {
446 # dependencies and aliases (the arrays should be more than 1000 characters)
447 x = unlist(match_full(x, '(?<=\\{)([[:alnum:]_-]+:\\[?"[^}]{1000,})(?=\\})'))
448 if (length(x) < 2) {
449 warning(
450 "Unable to process Prism's autoloader plugin (", u, ") to figure out ",
451 "language components automatically. Please report this message to ",
452 packageDescription('litedown')$BugReports, "."
453 )
454 return()
455 }
456 x = x[1:2]
457 x = lapply(match_full(x, '([[:alnum:]_-]+):(\\["[^]]+\\]|"[^"]+")'), function(z) {
458 z = gsub('[]["]', '', z)
459 uapply(strsplit(z, '[:,]'), function(y) {
460 set_names(list(y[-1]), y[1])
461 }, recursive = FALSE)
462 })
463 # x1 is dependencies; x2 is aliases
464 x1 = x[[1]]; x2 = unlist(x[[2]])
465 # normalize aliases to canonical names
466 i = langs %in% names(x2)
467 langs[i] = x2[langs[i]]
468 # resolve dependencies via recursion
469 resolve_deps = function(lang) {
470 deps = x1[[lang]]
471 c(lapply(deps, resolve_deps), lang)
472 }
473 # all languages required for this page
474 l1 = unique(uapply(langs, resolve_deps))
475 # languages that are officially supported
476 l2 = c(names(x1), unlist(x1), x2)
477 # for unknown languages, check if they exist on CDN
478 d = sub('/plugins/.+', '/components/', u)
479 l3 = uapply(setdiff(l1, l2), function(z) {
480 if (!downloadable(sprintf('%sprism-%s.min.js', d, z))) z
481 })
482 l4 = setdiff(l1, l3)
483 if (length(l3)) warn(l4, l3, d)
484 l4
485 }
486 }
487
488 # test if a URL can be downloaded
489 downloadable = function(u, type = 'text') {
490 !try_error(download_cache$get(u, type))
491 }
492
493 # quote a vector and combine by commas
494 comma_list = function(x) paste0('"', x, '"', collapse = ', ')
495
496 # get an option specific to an output format
497 get_option = function(name, format, ...) {
498 getOption(sprintf('litedown.%s.%s', format, name), ...)
499 }
500
501 # if a string is a file path found under test dirs, read the file; then concatenate elements by \n
502 one_string = function(x, by = '\n', test = NULL) {
503 if (length(test) && is_file(x)) {
504 p = if (is_abs_path(x)) x else xfun::existing_files(file.path(c(test, '.'), x))
505 if (length(p)) x = read_utf8(p[1]) else stop("The file '", x, "' is not found")
506 }
507 paste(x, collapse = by)
508 }
509
510 # find @citation and resolve references
511 add_citation = function(x, bib, format = 'html') {
512 if (!format %in% c('html', 'latex')) return(x)
513 bib = do.call(c, lapply(bib, rbibutils::readBib, direct = TRUE, texChars = 'convert'))
514 if (length(bib) == 0) return(x)
515 cited = NULL
516 is_html = format == 'html'
517 r = if (is_html) '(?<!<code>)(\\[@[-;@ [:alnum:]]+\\]|@[-[:alnum:]]+)' else
518 '(?<!\\{)(\\{\\[\\}@[-;@ [:alnum:]]+\\{\\]\\}|@[-[:alnum:]]+)'
519 # [@key] for citep, and @key for citet
520 x = match_replace(x, r, function(z) {
521 z2 = uapply(strsplit(z, '[;@ {}]+'), function(keys) {
522 bracket = any(grepl('^\\[', keys))
523 if (bracket) keys = gsub('^\\[|\\]$', '', keys)
524 keys = keys[keys != '']
525 if (length(keys) == 0 || !all(keys %in% names(bib))) return(NA)
526 if (is_html) {
527 cited <<- c(cited, keys)
528 cite_html(keys, bib, bracket)
529 } else {
530 sprintf('\\cite%s{%s}', if (bracket) 'p' else 't', one_string(keys, ','))
531 }
532 })
533 ifelse(is.na(z2), z, z2)
534 })
535 if (is_html) {
536 b = bib_html(bib, cited)
537 d = '<div id="refs">'
538 if (any(grepl(d, x, fixed = TRUE))) {
539 x = sub(d, paste0(d, one_string(b)), x, fixed = TRUE)
540 } else {
541 x = one_string(c(x, d, b, '</div>'))
542 }
543 }
544 x
545 }
546
547 # fall back to given name if family name is empty
548 author_name = function(x) {
549 a = paste(x$family %|% x$given, collapse = ' ')
550 a = gsub('\\{\\\\(.)}', '\\1', a) # un-escape special latex chars
551 html_escape(a)
552 }
553
554 # mimic natbib's author-year citation style for HTML output
555 cite_html = function(keys, bib, bracket = TRUE) {
556 x = NULL; N = length(keys)
557 for (i in seq_len(N)) {
558 key = keys[i]; b = bib[[key]]; a = b$author; n = length(a)
559 z = paste0(c(
560 author_name(a[[1]]),
561 if (n == 2) c('<span class="ref-and"></span>', author_name(a[[2]])),
562 if (n > 2) '<span class="ref-et-al"></span>', ' ',
563 if (bracket) b$year else
564 c('<span class="ref-paren-open ref-paren-close">', b$year, '</span>')
565 ), collapse = '')
566 cls = if (bracket) c(
567 if (i == 1) 'ref-paren-open', if (i == N) 'ref-paren-close',
568 if (i < N) 'ref-semicolon'
569 )
570 z = cite_link(key, z, one_string(c('', cls), ' '))
571 x = c(x, z)
572 }
573 one_string(x, '')
574 }
575
576 cite_link = function(key, text, class = '') {
577 sprintf('<a href="#ref-%s" class="citation%s">%s</a>', key, class, text)
578 }
579
580 # html bibliography
581 bib_html = function(bib, keys) {
582 bib = sort(bib[unique(keys)])
583 keys = uapply(bib, function(x) attr(unclass(x)[[1]], 'key'))
584 res = format(bib, 'html')
585 paste0('<p id="ref-', keys, '"', sub('^<p', '', res))
586 }
587
588 # add meta variables bib-preamble and bib-end for LaTeX output
589 bib_meta = function(meta, bib, package) {
590 bib = one_string(bib, ',')
591 if (is.null(meta[['bib-preamble']])) meta[['bib-preamble']] = switch(
592 package,
593 none = '\\bibliographystyle{apalike}\\let\\citep\\cite\\let\\citet\\cite',
594 natbib = '\\usepackage{natbib}\\bibliographystyle{abbrvnat}',
595 biblatex = paste0(
596 '\\usepackage[style=authoryear]{biblatex}\\addbibresource{', bib,
597 '}\\let\\citep\\parencite\\let\\citet\\cite'
598 )
599 )
600 if (is.null(meta[['bib-end']])) meta[['bib-end']] = if (package == 'biblatex')
601 '\\printbibliography' else paste0('\\bibliography{', bib, '}')
602 meta
603 }
604
605 # find headings and build a table of contents as an unordered list
606 build_toc = function(html, n = 3) {
607 if (n <= 0) return()
608 if (n > 6) n = 6
609 r = sprintf('<(h[1-%d])( id="[^"]+")?[^>]*>(.+?)</\\1>', n)
610 items = unlist(match_full(html, r))
611 # ignore headings with class="unlisted"
612 items = items[!has_class(items, 'unlisted')]
613 if (length(items) <= 1) return() # require at least 2 items in TOC
614 x = gsub(r, '<toc\\2>\\3</toc>', items) # use a tag <toc> to protect heading text
615 x = gsub('<a[^>]+>|</a>', '', x) # clean up <a>
616 h = as.integer(gsub('^h', '', gsub(r, '\\1', items))) # heading level
617 s = strrep(' ', seq_len(n) - 1) # indent
618 x = paste0(s[h], '- ', x) # create an unordered list
619 x = commonmark::markdown_html(x)
620 # add anchors on TOC items
621 x = gsub('<toc id="([^"]+)">(.+?)</toc>', '<a href="#\\1">\\2</a>', x)
622 x = gsub('</?toc>', '', x)
623 # add class 'numbered' to the first <ul> if any heading is numbered
624 if (length(grep('<span class="section-number[^"]*">', x)))
625 x = sub('<ul>', '<ul class="numbered">', x)
626 paste0('<div id="TOC">\n', x, '</div>')
627 }
628
629 # add TOC to the html body
630 add_toc = function(html, options) {
631 o = options[['toc']]
632 if (is.null(o) || isFALSE(o)) return(html)
633 if (isTRUE(o)) o = list()
634 if (!is.numeric(o$depth)) o$depth = 3
635 one_string(c(build_toc(html, o$depth), html))
636 }
637
638 sec_levels = c('subsubsection', 'subsection', 'section', 'chapter', 'part')
639 # raise section levels: redefine section to chapter or part, and so on
640 redefine_level = function(x, top) {
641 n = switch(top, chapter = 1, part = 2, 0)
642 if (n == 0) return(x)
643 for (i in 3:1) {
644 x = gsub(sprintf('(^|\n)\\\\%s', sec_levels[i]), sprintf('\\\\%s', sec_levels[i + n]), x)
645 }
646 x
647 }
648
649 # move image attributes like `![](){#id .class width="20%"}`, heading attributes
650 # `# foo {#id .class}`, and fenced Div's `::: {#id .class}` into HTML tags and
651 # LaTeX commands
652 move_attrs = function(x, format = 'html') {
653 if (format == 'html') {
654 # images
655 x = convert_attrs(x, '(<img src="[^>]+ )/>\\{([^}]+)\\}', '\\2', function(r, z, z2) {
656 z1 = sub(r, '\\1', z)
657 paste0(z1, z2, ' />')
658 })
659 # headings
660 x = convert_attrs(x, '(<h[1-6])(>.+?) \\{([^}]+)\\}(</h[1-6]>)', '\\3', function(r, z, z3) {
661 z1 = sub(r, '\\1 ', z)
662 z24 = sub(r, '\\2\\4', z)
663 paste0(z1, z3, z24)
664 })
665 # links
666 x = convert_attrs(x, '(<a[^>]+)(>(?s).*?</a>)(\\{([^}]+)\\})?', '\\4', function(r, z, z3) {
667 z1 = sub(r, '\\1', z, perl = TRUE)
668 z2 = sub(r, '\\2', z, perl = TRUE)
669 paste0(z1, ifelse(z3 == '', '', ' '), z3, z2)
670 })
671 # fenced Div's
672 x = convert_attrs(x, '<p>:::+ \\{(.*?)\\}</p>', '\\1', function(r, z, z1) {
673 # add attributes to the div but remove the data-latex attribute
674 z1 = str_trim(gsub('(^| )data-latex="[^"]*"( |$)', ' ', z1))
675 sprintf('<div%s%s>', ifelse(z1 == '', '', ' '), z1)
676 })
677 x = gsub('<p>:::+</p>', '</div>', x)
678 } else if (format == 'latex') {
679 # only support image width
680 x = convert_attrs(x, '(\\\\includegraphics)(\\{[^}]+\\})\\\\\\{([^}]+)\\\\\\}', '\\3', function(r, z, z3) {
681 r2 = '(^|.* )width="([^"]+)"( .*|$)'
682 j = grepl(r2, z3)
683 w = gsub(r2, '\\2', z3[j])
684 w = gsub('\\\\', '\\', w, fixed = TRUE)
685 k = grep('%$', w)
686 w[k] = paste0(as.numeric(sub('%$', '', w[k])) / 100, '\\linewidth')
687 z3[j] = paste0('[width=', w, ']')
688 z3[!j] = ''
689 z1 = sub(r, '\\1', z)
690 z2 = sub(r, '\\2', z)
691 paste0(z1, z3, z2)
692 }, format)
693 # discard most attributes for headings
694 r = sprintf('(\\\\(%s)\\{.+?) \\\\\\{([^}]+)\\\\\\}(\\})', paste(sec_levels, collapse = '|'))
695 x = convert_attrs(x, r, '\\3', function(r, z, z3) {
696 z = gsub(r, '\\1\\4', z)
697 k = has_class(z3, 'unnumbered')
698 z[k] = sub('{', '*{', z[k], fixed = TRUE)
699 k = has_class(z3, 'appendix')
700 z[k] = '\\appendix'
701 r2 = '(^|.* )id="([^"]+)".*'
702 k = grepl(r2, z3)
703 id = gsub(r2, '\\2', z3[k])
704 z[k] = paste0(z[k], '\\label{', id, '}')
705 z
706 }, format)
707 # fenced Div's: first class name is the environment name; options from data-latex
708 r = '\n\\\\begin\\{verbatim\\}\n(:::+)( \\{([^\n]+?)\\})? \\1\n\\\\end\\{verbatim\\}\n'
709 x = convert_attrs(x, r, '\\3', function(r, z, z3) {
710 r1 = '(^|.*? )class="([^" ]+)[" ].*'
711 r2 = ' data-latex="([^"]*)".*$'
712 r3 = paste0(r1, '?', r2)
713 i3 = grepl(r3, z3)
714 z4 = ifelse(i3, gsub(r3, '{\\2}\\3', z3), ifelse(z3 == '', '', '{@}'))
715 cls = gsub(r1, '\\2', z3)
716 # fig/tab environments don't need the data-latex attribute
717 i4 = !i3 & cls %in% c('figure', 'caption', 'table')
718 z4[i4] = sprintf('{%s}', cls[i4])
719 z3 = latex_envir(gsub('\\\\', '\\', z4, fixed = TRUE))
720 z3[z3 %in% c('\\begin{@}', '\\end{@}')] = ''
721 i = grep('^\\\\begin', z3)
722 z3[i] = paste0('\n', z3[i])
723 i = grep('^\\\\end', z3)
724 z3[i] = paste0(z3[i], '\n')
725 # put fig/tab captions in \caption{}
726 z3 = gsub('\\begin{caption}', '\\caption{', z3, fixed = TRUE)
727 z3 = gsub('\\end{caption}', '}', z3, fixed = TRUE)
728 z3
729 }, format)
730 # remove table env generated from commonmark and use those from fenced Divs
731 x = gsub('\\\\begin\\{table\\}\n(?=\\\\begin\\{tabular\\})', '', x, perl = TRUE)
732 x = gsub('(?<=\\\\end\\{tabular\\}\n)\\\\end\\{table}', '', x, perl = TRUE)
733 } else {
734 # TODO: remove attributes for other formats
735 }
736 x
737 }
738
739 convert_attrs = function(x, r, s, f, format = 'html', f2 = identity) {
740 r2 = '(?<=^| )[.#]([-:[:alnum:]]+)(?= |$)' # should we allow other chars in ID/class?
741 match_replace(x, r, function(y) {
742 z = sub(r, s, y, perl = TRUE)
743 if (format == 'html') {
744 z = gsub('[\U201c\U201d]', '"', z)
745 } else {
746 z = gsub('=``', '="', z, fixed = TRUE)
747 z = gsub("''( |\\\\})", '"\\1', z)
748 z = gsub('\\\\([#%])', '\\1', z)
749 }
750 z2 = f2(z)
751 # {-} is a shorthand of {.unnumbered}
752 z2[z2 == '-'] = '.unnumbered'
753 # convert #id to id="" and .class to class=""
754 z2 = match_replace(z2, r2, function(a) {
755 i = grep('^[.]', a)
756 if ((n <- length(i))) {
757 # merge multiple classes into one class attribute
758 a[i] = sub('^[.]', '', a[i])
759 a[i] = c(sprintf('class="%s"', paste(a[i], collapse = ' ')), rep('', n - 1))
760 a = c(a[i], a[-i])
761 }
762 if (length(i <- grep('^#', a))) {
763 a[i] = gsub(r2, 'id="\\1"', a[i], perl = TRUE)
764 a = c(a[i], a[-i]) # make sure id is the first attribute
765 }
766 a
767 })
768 # remove spaces after class="..." (caused by merging multiple classes)
769 z2 = sub('(^| )(class="[^"]+") +', '\\1\\2 ', z2)
770 f(r, y, str_trim(z2))
771 })
772 }
773
774 str_trim = function(x) gsub('^\\s+|\\s+$', '', x)
775 # trim blank lines from both ends
776 trim_blank = function(x) gsub('^(\\s*\n)+|\n\\s*$', '', x)
777
778 # {A}, '', {B}, {C}, '', '' -> \begin{A}\end{A}\begin{B}\begin{C}\end{C}\end{B}
779 latex_envir = function(x, env = NULL) {
780 n = length(x)
781 if (n == 0) return()
782 x1 = x[1]
783 env2 = tail(env, 1) # the most recent env is in the end
784 env = if (x1 == '') head(env, -1) else c(env, sub('^(\\{[^}]+}).*$', '\\1', x1))
785 c(if (x1 == '') paste0('\\end', env2) else paste0('\\begin', x1), latex_envir(x[-1], env))
786 }
787
788 # fix footnotes for LaTeX output: convert `\footnotemark[1] \footnotetext[1]{*}`
789 # to `\footnote{*}` (see r-lib/commonmark#32)
790 fix_footnotes = function(x) {
791 f1 = f2 = NULL
792 r = '\n\\\\footnotetext\\[(.+?)]\\{(.+?)\n\n}\n'
793 x = match_replace(x, r, function(z) {
794 f1 <<- c(f1, sub(r, '\\1', z))
795 f2 <<- c(f2, sub(r, '\\2', z))
796 ''
797 }, perl = FALSE)
798 f1 = sprintf('\\footnotemark[%s]', f1)
799 f2 = sprintf('\\footnote{%s}', f2)
800 for (i in seq_along(f1)) {
801 x = sub(f1[i], f2[i], x, fixed = TRUE)
802 }
803 x
804 }
805
806 # add auto identifiers to headings
807 auto_identifier = function(x) {
808 r = '<(h[1-6])([^>]*)>(.+?)</\\1>'
809 match_replace(x, r, function(z) {
810 z1 = sub(r, '\\1', z) # tag
811 z2 = sub(r, '\\2', z) # attrs
812 z3 = sub(r, '\\3', z) # content
813 i = !grepl(' id="[^"]*"', z2) # skip headings that already have IDs
814 p = ifelse(z1 == 'h1', 'chp:', 'sec:') # h1 is chapter; h2+ are sections
815 id = unique_id(paste0(p[i], alnum_id(z3[i])), 'section')
816 z[i] = sprintf('<%s id="%s"%s>%s</%s>', z1[i], id, z2[i], z3[i], z1[i])
817 z
818 })
819 }
820
821 # add a number suffix to an id if it is duplicated
822 unique_id = function(x, empty) {
823 x[x == ''] = empty
824 i = duplicated(x)
825 for (d in unique(x[i])) {
826 k = x == d
827 x[k] = paste0(x[k], '_', seq_len(sum(k)))
828 }
829 x
830 }
831
832 # test if a class name exists in attributes
833 has_class = function(x, class) {
834 grepl(sprintf('(^| )class="([^"]+ )?%s( [^"]+)?"', class), x)
835 }
836
837 # number sections in HTML output
838 number_sections = function(x) {
839 h = sub('</h([1-6])>', '\\1', unlist(match_full(x, '</h[1-6]>')))
840 if (length(h) == 0) return(x) # no headings
841 h = min(as.integer(h)) # highest level of headings
842 r = '<h([1-6])([^>]*)>(?!<span class="section-number)'
843 n = rep(0, 6) # counters for all levels of headings
844 # when previewing a book chapter, set the start number if possible
845 is_appendix = FALSE # the start "number" for appendix is A-Z
846 if (length(f <- .env$current_file)) {
847 if (length(n_start <- grep_sub('^([0-9]+|[A-Z])[-_].+', '\\1', basename(f))))
848 if (!(is_appendix <- grepl('^[A-Z]$', n_start))) n[1] = as.integer(n_start) - 1
849 }
850 k0 = 6 # level of last unnumbered heading
851 match_replace(x, r, function(z) {
852 z1 = as.integer(sub(r, '\\1', z, perl = TRUE)) # heading levels
853 z2 = sub(r, '\\2', z, perl = TRUE) # heading attributes
854 num_sections = identity # generate appendix numbers
855 for (i in seq_along(z)) {
856 k = z1[i]
857 if (k < 6) n[(k + 1):6] <<- 0
858 # skip unnumbered sections
859 if (has_class(z2[i], 'unnumbered')) {
860 k0 <<- k; next
861 } else {
862 # don't number headings with level lower than last unnumbered heading
863 if (k > k0) next else k0 <<- 6
864 }
865 if (has_class(z2[i], 'appendix')) {
866 if (k != h) stop(
867 "The 'appendix' attribute must be on the top-level heading (",
868 strrep('#', h), ').'
869 )
870 num_sections = local({
871 a = n[k] # an offset (highest top-level heading number before appendix)
872 # number headings with A-Z or roman numerals
873 num = if (sum(z1[i:length(z)] == h) - 1 > 26) as.roman else {
874 function(i) LETTERS[i]
875 }
876 function(s) {
877 if (s[1] <= a) stop(
878 'An appendix section must start with the top-level heading (',
879 strrep('#', h), ').'
880 )
881 s[1] = num(s[1] - a)
882 s
883 }
884 })
885 next
886 }
887 n[k] <<- n[k] + 1
888 # remove leading 0's
889 s = if (h > 1) n[-(1:(h - 1))] else n
890 if (is_appendix) s[1] = n_start else s = num_sections(s)
891 s = paste(s, collapse = '.')
892 s = gsub('([.]0)+$', '', s) # remove trailing 0's
893 # if section number doesn't contain '.', assign a class 'main-number' to the number
894 z[i] = paste0(z[i], sprintf(
895 '<span class="section-number%s">%s</span> ',
896 ifelse(grepl('[.]', s), '', ' main-number'), s
897 ))
898 }
899 z
900 })
901 }
902
903 # number elements such as headings and figures, etc and resolve cross-references
904 number_refs = function(x, r, katex = TRUE) {
905 if (length(x) == 0) return(x)
906 db = list() # element numbers
907
908 # first, find numbered section headings
909 r2 = '<h[1-6][^>]*? id="([^"]+)"[^>]*><span class="section-number[^"]*">([0-9.]+)</span>'
910 m = match_all(x, r2)[[1]]
911 if (length(m)) {
912 ids = m[2, ]
913 db = as.list(set_names(m[3, ], ids))
914 }
915
916 # retrieve refs from all chapters for fuse_book()
917 if (is.character(b <- .env$current_book)) db = merge_list(.env$refs[[b]], db)
918
919 # then find and number other elements
920 r2 = sprintf('<a href="#@%s"> ?</a>', r)
921 db2 = list()
922 x = match_replace(x, r2, function(z) {
923 type = sub(r2, '\\2', z)
924 id = sub(r2, '\\1', z)
925 ids = split(id, type)
926 db2 <<- unlist(unname(lapply(ids, function(id) set_names(seq_along(id), id))))
927 sprintf('<span class="ref-number-%s">%d</span>', type, db2[id])
928 })
929 db = unlist(if (is.character(b)) merge_list(db, as.list(db2)) else c(db, db2))
930 ids = names(db)
931 if (any(i <- duplicated(ids))) warning('Duplicated IDs: ', one_string(ids[i], ', '))
932
933 # save refs db for fuse_book()
934 if (is.character(b)) .env$refs[[b]] = db
935
936 # finally, resolve cross-references
937 r2 = sprintf('<a href="#(%s)">@\\1</a>', r)
938 match_replace(x, r2, function(z) {
939 type = sub(r2, '\\3', z)
940 id = sub(r2, '\\2', z)
941 # equation numbers will be resolved in JS later
942 i1 = grepl('^eq[-:]', id)
943 z[i1] = sprintf('\\ref{%s}', id[i1])
944 i2 = grepl('^eqn[-:]', id)
945 z[i2] = sprintf('\\eqref{%s}', sub('eqn', 'eq', id[i2]))
946 i3 = i1 | i2
947 # KaTeX requires references to be in math, e.g., \(\ref{ID}\)
948 if (katex) z[i3] = paste0('\\(', z[i3], '\\)')
949 i = id %in% ids
950 # for backward compatibility, if fig-id is not found, also look for fig:id
951 if (any(i4 <- !i & !i3)) {
952 id2 = sub('-', ':', id)
953 j = i4 & (id2 %in% ids)
954 id[j] = id2[j]; i[j] = TRUE; i4[j] = FALSE
955 }
956 if (any(i)) z[i] = sprintf(
957 '<a class="cross-ref-%s" href="#%s">%s</a>', type[i], id[i], db[id[i]]
958 )
959 if (any(i4)) warning('Reference key(s) not found: ', one_string(id[i4], ', '))
960 z
961 })
962 }
963
964 # add a special anchor [](#@id) to text, to be used to resolved cross-references
965 add_ref = function(id, type, x = NULL) {
966 c(sprintf('[](#@%s:%s)', type, id), x)
967 }
968
969 # make cross-refs for LaTeX output, to be resolved by a LaTeX engine
970 latex_refs = function(x, r, clever = FALSE) {
971 ar = paste0('@', r)
972 r0 = function(a, b) sprintf('\\\\protect\\\\hyperlink\\{%s\\}\\{%s\\}', a, b)
973 r1 = r0(ar, '\\s*') # \label{}
974 r2 = r0(r, ar) # \ref{}
975 x = gsub(r1, '\\\\label{\\1}', x)
976 x = gsub(r2, sprintf('\\\\%sref{\\1}', if (clever) 'c' else ''), x)
977 x
978 }
979
980 embed_resources = function(x, options) {
981 if (length(x) == 0) return(x)
982 r = '\n<link[^>]*? rel="stylesheet" [^>]*>|\n<script[^>]*? src="[^"]+"[^>]*>\\s*</script>'
983 x = match_replace(x, r, function(z) {
984 # de-dup assets (e.g., when vest() is called multiple times on the same asset)
985 z[duplicated(z)] = ''
986 z
987 })
988
989 embed = c('https', 'local') %in% options[['embed_resources']]
990 offline = options[['offline']]
991 if (!any(embed, is.character(offline))) return(x)
992 clean = options[['embed_cleanup']]
993
994 # find images in <img> and (for slides only) comments
995 rs = c(
996 '(<img src=")([^"]+)("[^>]*?/>)',
997 '(<!--#[^>]*? style="background-image: url\\("?)([^"]+?)("?\\);)'
998 )
999 for (r in rs) x = match_replace(x, r, function(z) {
1000 z1 = sub(r, '\\1', z)
1001 z2 = sub(r, '\\2', z)
1002 z3 = sub(r, '\\3', z)
1003 # skip images already base64 encoded
1004 for (i in grep('^data:.+;base64,.+', z2, invert = TRUE)) {
1005 is_svg = grepl('[.]svg$', f <- z2[i]) && grepl('^<img', z1[i])
1006 a = if (is_svg) str_trim(gsub('^"|/>$', '', z3[i])) else ''
1007 f = download_url(f, offline)
1008 if (is_https(f)) {
1009 if (embed[1]) z2[i] = if (!is_svg) download_cache$get(f, 'base64') else {
1010 download_cache$get(f, 'text', function(xml) process_svg(xml, a))
1011 }
1012 } else if (embed[2]) {
1013 if (file_exists(f <- URLdecode(f))) {
1014 z2[i] = if (is_svg) process_svg(read_utf8(f), a) else base64_uri(f)
1015 if (clean && normalize_path(f) %in% .env$plot_files) file.remove(f)
1016 } else {
1017 warning("File '", f, "' not found (hence cannot be embedded).")
1018 }
1019 }
1020 }
1021 ifelse(grepl('<svg', z2), z2, paste0(z1, z2, z3))
1022 })
1023
1024 # CSS and JS
1025 r = paste0(
1026 '<link[^>]*? rel="stylesheet" href="([^"]+)"[^>]*>|',
1027 '<script([^>]*?) src="([^"]+)"([^>]*)>\\s*</script>'
1028 )
1029 x2 = NULL # js to be appended before </body>
1030 x = match_replace(x, r, function(z) {
1031 z1 = sub(r, '\\1', z) # css
1032 z2 = sub(r, '\\3', z) # js
1033 js = z2 != ''
1034 z3 = paste0(z1, z2)
1035 at = sub(r, '\\2\\4', z) # attributes for js
1036 # skip resources already base64 encoded
1037 i1 = !grepl('^data:.+;base64,.+', z3)
1038 z3[i1] = gen_tags(
1039 z3[i1], ifelse(js[i1], 'js', 'css'), embed[1], embed[2], offline, at
1040 )
1041 # js with the defer attribute and has been embedded (i.e., no src attribute)
1042 i = grepl(' defer($| )', at) & !grepl('^<script([^>]*?) src="', z3) & i1
1043 x2 <<- c(x2, z3[i])
1044 z3[i] = ''
1045 z3
1046 })
1047 # move deferred scripts to the end of <body>
1048 if (length(x2)) {
1049 x = if (length(grep('</body>', x)) != 1) {
1050 one_string(c(x, x2))
1051 } else {
1052 sub('</body>', one_string(c(x2, '</body>')), x, fixed = TRUE)
1053 }
1054 }
1055 x
1056 }
1057
1058 # remove the xml/doctype declaration in svg, and add attributes
1059 process_svg = function(x, attr) {
1060 while (length(x) > 0 && !grepl('^\\s*<svg .+', x[1])) x = x[-1]
1061 if (length(x) > 0 && !attr %in% c('', 'alt=""')) {
1062 x[1] = if (grepl(r <- '\\s*>\\s*$', x[1])) {
1063 paste0(gsub(r, ' ', x[1]), attr, '>')
1064 } else {
1065 paste(x[1], attr)
1066 }
1067 }
1068 one_string(x)
1069 }
1070
1071 normalize_options = function(x, format = 'html') {
1072 g = get_option('options', format)
1073 x = option2list(x)
1074 n = names(x)
1075 # default options
1076 d = option2list(markdown_options())
1077 g = option2list(g)
1078 d[names(g)] = g # merge global options() into default options
1079 d[n] = x # then merge user-provided options
1080 if (!is.character(d[['top_level']])) d$top_level = 'section'
1081 if (isTRUE(o <- d[['offline']])) o = 'assets'
1082 if (!is.character(o)) o = FALSE
1083 d$offline = o
1084 d = normalize_embed(d)
1085 d
1086 }
1087
1088 normalize_embed = function(x) {
1089 v = x[['embed_resources']]
1090 if (is.logical(v)) {
1091 v = if (v) 'local'
1092 } else {
1093 if (length(v) == 1 && v == 'all') v = c('local', 'https')
1094 }
1095 x[['embed_resources']] = v
1096 x
1097 }
1098
1099 named_bool = function(x, val = TRUE) as.list(set_names(rep(val, length(x)), x))
1100
1101 # normalize metadata variable names: change _ to -
1102 normalize_meta = function(x) {
1103 # make sure some variables are available in metadata
1104 x = merge_list(list(classoption = '', documentclass = 'article', body_class = 'body'), x)
1105 names(x) = gsub('_', '-', names(x))
1106 x
1107 }
1108
1109 # turn '+a-b c' to list(a = TRUE, b = FALSE, c = TRUE)
1110 option2list = function(x) {
1111 if (!is.character(x)) return(as.list(x))
1112 x = unlist(strsplit(x, '\\b(?=[+-])', perl = TRUE))
1113 x = unlist(strsplit(x, '\\s+'))
1114 x = setdiff(x, '')
1115 i = grepl('^-', x)
1116 c(named_bool(sub('^[-]', '', x[i]), FALSE), named_bool(sub('^[+]', '', x[!i])))
1117 }
1118
1119 pkg_file = function(...) {
1120 system.file(..., package = 'litedown', mustWork = TRUE)
1121 }
1122
1123 jsdelivr = function(file, dir = 'npm/@xiee/utils/') {
1124 ifelse(is_https(file), file, sprintf('https://cdn.jsdelivr.net/%s%s', dir, file))
1125 }
1126
1127 # get the latest version of jsdelivr assets
1128 jsd_version = local({
1129 vers = list() # cache versions in current session
1130 # find version from local cache
1131 p_cache = function() {
1132 d = if (getRversion() >= '4.0') tools::R_user_dir('litedown', 'cache') else {
1133 file.path(dirname(tempdir()), 'R', 'cache', 'litedown')
1134 }
1135 file.path(d, 'jsd_versions.rds')
1136 }
1137 # update cache to a specific version
1138 u_cache = function(info, pkg, version, file) {
1139 if (!grepl('^@', version)) version = paste0('@', version)
1140 info[[pkg]] = list(version = version, time = Sys.time())
1141 saveRDS(info, file)
1142 version
1143 }
1144 # cache expires after one week by default
1145 v_cache = function(pkg, force, delta = getOption('litedown.jsdelivr.cache', 604800)) {
1146 if (!isTRUE(force) && file.exists(f <- p_cache())) {
1147 info = readRDS(f)
1148 if (is.character(force)) {
1149 u_cache(info, pkg, force, f)
1150 } else {
1151 info = info[[pkg]]
1152 if (!is.null(t <- info$time) && Sys.time() - t <= delta) info$version
1153 }
1154 }
1155 }
1156 # query version from jsdelivr api
1157 v_api = function(pkg) {
1158 x = tryCatch(
1159 read_utf8(paste0('https://data.jsdelivr.com/v1/packages/', pkg, '/resolved?specifier=latest')),
1160 error = function(e) v_cache(pkg, FALSE, Inf) # fall back to local cache
1161 )
1162 v = grep_sub('.*"version":\\s*"([0-9.]+)".*', '@\\1', x)
1163 if (length(v)) {
1164 if (dir_create(dirname(f <- p_cache()))) {
1165 info = if (file.exists(f)) readRDS(f) else list()
1166 u_cache(info, pkg, v[1], f)
1167 }
1168 v[1]
1169 }
1170 }
1171 # force can be TRUE/FALSE/version number
1172 function(pkg, force = FALSE) {
1173 if (isFALSE(force) && is.character(v <- vers[[pkg]])) return(v)
1174 v = v_cache(pkg, force) %||% v_api(pkg)
1175 (vers[[pkg]] <<- if (length(v)) v[1] else '')
1176 }
1177 })
1178
1179 jsd_versions = function(pkgs) uapply(pkgs, jsd_version)
1180
1181 # resolve the implicit latest version to current latest version
1182 jsd_resolve = function(x) {
1183 if (!getOption('litedown.jsd_resolve', TRUE)) return(x)
1184 rs = paste0(c(
1185 '((?<=https://cdn.jsdelivr.net/combine/)|(?<=,))',
1186 '(?<=https://cdn.jsdelivr.net/)(?!combine/)'
1187 ), '([^/]+/(@[^/]+/)?[^/@]+)((?=/)|(?=@latest$)|$)')
1188 for (r in rs) x = match_replace(x, r, function(z) {
1189 paste0(z, jsd_versions(z))
1190 })
1191 x = sub('@latest$', '', x)
1192 x
1193 }
1194
1195 # if both @foo and foo are present, remove foo
1196 resolve_dups = function(x) {
1197 x = unique(x)
1198 for (i in grep('^@', x, value = TRUE)) {
1199 x = x[x != sub('^@', '', i)]
1200 }
1201 x
1202 }
1203
1204 # add filename extensions to paths without extensions: the path should contain
1205 # no slashes (@xiee/utils assets) or at least 2 slashes when the npm package
1206 # name doesn't start with @ (otherwise the path should contain >= 3 slashes),
1207 # e.g. don't add ext for npm/simple-datatables
1208 add_ext = function(x, ext) {
1209 n = vapply(strsplit(x, ''), function(z) sum(z == '/'), 0)
1210 i = file_ext(x) == '' & (n == 0 | n > grepl('^[^/]+/@', x) + 2)
1211 x[i] = paste0(x[i], ext)
1212 x
1213 }
1214
1215 # resolve CSS/JS shorthand filenames to actual paths (e.g., 'default' to 'default.css')
1216 resolve_files = function(x, ext = 'css') {
1217 x = resolve_dups(x)
1218 if (length(x) == 0) return(x)
1219 min_ext = paste0('.min.', ext)
1220
1221 # @foo -> jsdelivr.net/npm/@xiee/utils/ext/foo.min.ext
1222 i0 = grepl('^@', x)
1223 x[i0] = sub('^@', '', x[i0])
1224 # @foo@version -> @npm/@xiee/utils@version/foo
1225 i = i0 & !grepl('[/,]', x)
1226 x[i] = sub('^(.+?)@(.+)$', sprintf('npm/@xiee/utils@\\2/%s/\\1', ext), x[i])
1227
1228 # if no extension is specified, use .min.ext
1229 x[i0] = add_ext(x[i0], min_ext)
1230 i = i0 & !grepl('[/,]', x)
1231 x[i] = jsdelivr(paste0(ext, '/', x[i]))
1232
1233 # @foo/bar -> jsdelivr.net/foo/bar
1234 i = i0 & !grepl(',', x)
1235 x[i] = jsdelivr(x[i], '')
1236
1237 # @foo/bar,baz -> jsdelivr.net/combine/foo/bar,foo/baz
1238 i = i0 & grepl(',', x)
1239 if (any(i)) x[i] = sapply(strsplit(x[i], ',\\s*'), function(z) {
1240 d = dirname(z[1])
1241 if (d == '.') d = paste0('npm/@xiee/utils/', ext)
1242 for (j in seq_along(z)) {
1243 if (grepl('/', z[j])) {
1244 d = dirname(z[j])
1245 } else {
1246 z[j] = paste(d, z[j], sep = '/')
1247 }
1248 }
1249 z = add_ext(z, min_ext)
1250 paste0('combine/', paste(z, collapse = ','))
1251 })
1252 x[i] = jsdelivr(x[i], '')
1253 x[i0] = jsd_resolve(x[i0])
1254
1255 i = dirname(x) == '.' & file_ext(x) == '' & !file_exists(x)
1256 x[i] = map_assets(x[i], ext)
1257 x = if (ext %in% c('css', 'js')) gen_tags(x, ext) else read_all(x)
1258 I(x)
1259 }
1260
1261 map_assets = function(x, ext) {
1262 if (length(x) == 0) return(x)
1263 x[x == 'slides'] = 'snap' # alias slides.css -> snap.css
1264 # built-in resources in this package
1265 b1 = c(if (ext != 'js') 'default', 'snap')
1266 i1 = x %in% b1
1267 x[i1] = file.path(pkg_file('resources'), sprintf('%s.%s', x[i1], ext))
1268 # in case users forgot to type @ for jsdelivr assets
1269 b2 = sub('@', '', assets[, ext])
1270 i2 = x %in% b2
1271 x[i2] = jsdelivr(sprintf('%s/%s.min.%s', ext, x[i2], ext))
1272 x[i2] = jsd_resolve(x[i2])
1273 if (any(i3 <- !(i1 | i2))) stop(
1274 "Invalid '", ext, "' option: ", paste0("'", x[i3], "'", collapse = ', '),
1275 " (possible values are: ", paste0("'", unique(c(b1, na_omit(b2))), "'", collapse = ', '), ")"
1276 )
1277 x
1278 }
1279
1280 # generate tags for css/js depending on whether they need to be embedded or offline
1281 gen_tag = function(
1282 x, ext = file_ext(x), embed_https = FALSE, embed_local = FALSE,
1283 offline = FALSE, attr = ' defer'
1284 ) {
1285 if (ext == 'css') {
1286 t1 = '<link rel="stylesheet" href="%s">'
1287 t2 = c('<style type="text/css">', '</style>')
1288 } else if (ext == 'js') {
1289 t1 = paste0('<script src="%s"', attr, '></script>')
1290 t2 = c('<script>', '</script>')
1291 } else stop("The file extension '", ext, "' is not supported.")
1292 is_web = is_https(x)
1293 is_rel = !is_web && is_rel_path(x)
1294 if (is_web && embed_https && xfun::url_filename(x) == 'MathJax.js') {
1295 warning('MathJax.js cannot be embedded. Please use MathJax v3 instead.')
1296 embed_https = FALSE
1297 }
1298 # linking for 1) local rel paths that don't need to be embedded, or 2) web
1299 # resources that don't need to be accessed offline
1300 link1 = is_rel && !embed_local
1301 link2 = is_web && !embed_https
1302 if (link1 || link2) {
1303 if (link2) x = download_url(
1304 x, offline, handler = function(code) resolve_url(x, code, ext, FALSE)
1305 )
1306 sprintf(t1, x)
1307 } else {
1308 # embedding for other cases
1309 one_string(c(t2[1], resolve_external(x, is_web, ext), t2[2]))
1310 }
1311 }
1312
1313 # check if path starts with https://, but also tolerate http://
1314 is_https = function(x) grepl('^https?://', x)
1315
1316 # a vectorized version
1317 gen_tags = function(...) mapply(gen_tag, ..., USE.NAMES = FALSE)
1318
1319 # read CSS/JS and embed external fonts/background images, etc.
1320 resolve_external = function(x, web = TRUE, ext = '') {
1321 # download and cache web resources
1322 if (web) download_cache$get(x, 'text', handler = function(code) {
1323 # remove jsdelivr comments
1324 if (grepl('^https://cdn[.]jsdelivr[.]net/', x)) {
1325 code = gsub(
1326 '^/[*][*]\n( [*][^\n]*\n)+ [*]/\n|\n/[*/]# sourceMappingURL=.+[.]map( [*]/)?$',
1327 '', one_string(code)
1328 )
1329 code = resolve_url(x, code, ext)
1330 }
1331 code
1332 }) else {
1333 resolve_url(x, read_utf8(x), ext)
1334 }
1335 }
1336
1337 # find url("path") in JS/CSS and base64 encode or download the resources
1338 resolve_url = function(url, code, ext, encode = TRUE) {
1339 d = dirname(url)
1340 # embed fonts in mathjax's js
1341 if (grepl('^https://cdn[.]jsdelivr[.]net/npm/mathjax.+[.]js$', url)) {
1342 r = '.*?fontURL:[^"]+\\("([^"]+)".*' # output/chtml/fonts/woff-v2
1343 p = grep_sub(r, '\\1', code)
1344 if (length(p) == 1) code = match_replace(
1345 code, '(?<=src:\'url\\(")(%%URL%%/[^"]+)(?="\\))', function(u) {
1346 f = sub('%%URL%%/', '', u, fixed = TRUE)
1347 u2 = paste(d, p, f, sep = '/')
1348 if (encode) {
1349 uapply(u2, download_cache$get, 'base64')
1350 } else {
1351 .mapply(function(u, f) download_url(u, p, f), u2, f)
1352 u
1353 }
1354 }
1355 ) else warning(
1356 'Unable to determine the font path in MathJax. Please report an issue to ',
1357 'https://github.com/yihui/litedown/issues and mention the URL ', url, '.'
1358 )
1359 }
1360 # find `attr: url(resource)` and embed url resources in CSS
1361 if (ext == 'css') {
1362 r = '((: ?| )url\\(["\']?)([^"\')]+)(["\']?\\))'
1363 code = match_replace(code, paste0('(?<!behavior)', r), function(z) {
1364 z1 = gsub(r, '\\1', z)
1365 z2 = gsub(r, '\\3', z)
1366 z3 = gsub(r, '\\4', z)
1367 i = is_https(z2)
1368 u = ifelse(i, z2, sprintf('%s/%s', d, z2))
1369 z2 = unlist(if (encode) {
1370 lapply(u, function(x) {
1371 if (is_https(x)) download_cache$get(x, 'base64') else base64_uri(x)
1372 })
1373 } else {
1374 .mapply(function(u, i, f) download_url(u, '.', if (!i) f), u, i, z2)
1375 })
1376 paste0(z1, z2, z3)
1377 })
1378 } else if (ext == 'js') {
1379 # the literal sequence '</script>' inside <script> tag needs to be escaped;
1380 # to avoid problems in general caused by closing tags, we escape them all
1381 code = gsub('</', '<\\/', code, fixed = TRUE)
1382 }
1383 code
1384 }
1385
1386 # download a file to a local dir if the local file doesn't exist
1387 download_url = function(url, dir = '.', file = NULL, handler = NULL) {
1388 if (!is.character(dir) || !is_https(url) || grepl('^http://127.0.0.1', url))
1389 return(url)
1390 f = file %||% gsub('^https?://|[?#].*$', '', url)
1391 p = URLdecode(f)
1392 # see if a previous version of the jsd asset exists
1393 if (dir.exists(dir) && startsWith(p, 'cdn.jsdelivr.net/')) in_dir(dir, {
1394 p2 = sub('@[0-9.]+/', '@*/', p)
1395 if (n <- length(p2 <- Sys.glob(p2))) p = p2[n]
1396 })
1397 if (dir != '.') p = file.path(dir, p)
1398 if (!file_exists(p)) {
1399 xfun::download_file(url, p)
1400 if (is.function(handler)) xfun::process_file(p, function(x) {
1401 x # force eval before changing wd
1402 in_dir(dirname(p), handler(x))
1403 })
1404 }
1405 URLencode(p)
1406 }
1407
1408 # compact HTML code
1409 clean_html = function(x) {
1410 x = gsub('\n+(\n<[a-z1-6]+[^>]*>|\n</(body|div|head|html)>)', '\\1', x)
1411 # can also merge <style>/<script> tags (<style type="text/css">).+?</style>\\s*\\1
1412 x
1413 }