Debian Codegraph @

R/markdown.R

raw
1 #' Find the indices of lines in Markdown that are prose (not code blocks)
2 #'
3 #' Filter out the indices of lines between code block fences such as \verb{```}
4 #' (could be three or four or more backticks).
5 #' @param x A character vector of text in Markdown.
6 #' @param warn Whether to emit a warning when code fences are not balanced.
7 #' @note If the code fences are not balanced (e.g., a starting fence without an
8 #' ending fence), this function will treat all lines as prose.
9 #' @return An integer vector of indices of lines that are prose in Markdown.
10 #' @export
11 #' @examples library(xfun)
12 #' prose_index(c('a', '```', 'b', '```', 'c'))
13 #' prose_index(c('a', '````', '```r', '1+1', '```', '````', 'c'))
14 prose_index = function(x, warn = TRUE) {
15 xi = seq_along(x); n = length(idx <- code_lines_regex(x))
16 if (n == 0) return(xi)
17 if (n %% 2 != 0) {
18 if (warn) warning('Code fences are not balanced')
19 # treat all lines as prose
20 return(xi)
21 }
22 idx2 = matrix(idx, nrow = 2)
23 idx2 = unlist(mapply(seq, idx2[1, ], idx2[2, ], SIMPLIFY = FALSE))
24 xi[-idx2]
25 }
26
27 # find starting and ending lines of code blocks via regex (may not be accurate)
28 code_lines_regex = function(x) {
29 idx = NULL
30 # if raw HTML <pre></pre> exists, it should be treated as code block
31 inside_pre = if (length(p1 <- grep('<pre>', x))) {
32 p2 = grep('</pre>', x)
33 if (length(p1) == length(p2)) {
34 idx = rbind(p1, p2)
35 function(i) any(i > p1 & i < p2)
36 }
37 }
38 r = '^(\\s*```+).*'; s = ''
39 # shouldn't match ``` ``text``` ```, which is inline code, not code block
40 i1 = grepl(r, x); i2 = !grepl('^\\s*```+\\s+`', x); i3 = !grepl('-->\\s*$', x)
41 for (i in which(i1 & i2 & i3)) {
42 if (is.function(inside_pre) && inside_pre(i)) next
43 if (s == '') {
44 s = gsub(r, '\\1', x[i]); idx = c(idx, i); next
45 }
46 # look for the next line with the same amount of backticks (end of block)
47 if (grepl(paste0('^', s), x[i])) {
48 idx = c(idx, i); s = ''
49 }
50 }
51 idx
52 }
53
54 # find lines via commonmark (accurate but gregexpr()/substring() are slow)
55 code_lines_cmark = function(x) {
56 xml = commonmark::markdown_xml(x, sourcepos = TRUE)
57 r = '(?<=<code_block sourcepos=")(\\d+):\\d+-(\\d+):\\d+(?=")'
58 m = gregexpr(r, xml, perl = TRUE)[[1]]
59 if (all(m < 0)) return()
60 s = attr2(m, 'capture.start'); l = attr2(m, 'capture.length')
61 as.integer(substring(xml, s, s + l - 1))
62 }
63
64 #' Protect math expressions in pairs of backticks in Markdown
65 #'
66 #' For Markdown renderers that do not support LaTeX math, we need to protect
67 #' math expressions as verbatim code (in a pair of backticks), because some
68 #' characters in the math expressions may be interpreted as Markdown syntax
69 #' (e.g., a pair of underscores may make text italic). This function detects
70 #' math expressions in Markdown (by heuristics), and wrap them in backticks.
71 #'
72 #' Expressions in pairs of dollar signs or double dollar signs are treated as
73 #' math, if there are no spaces after the starting dollar sign, or before the
74 #' ending dollar sign. There should be a space or `(` before the starting dollar
75 #' sign, unless the math expression starts from the very beginning of a line.
76 #' For a pair of single dollar signs, the ending dollar sign should not be
77 #' followed by a number, and the inner math expression should not be wrapped in
78 #' backticks. With these assumptions, there should not be too many false
79 #' positives when detecing math expressions.
80 #'
81 #' Besides, LaTeX environments (\verb{\begin{*}} and \verb{\end{*}}) are also
82 #' protected in backticks.
83 #' @param x A character vector of text in Markdown.
84 #' @param token A character string to wrap math expressions at both ends. This
85 #' can be a unique token so that math expressions can be reliably identified
86 #' and restored after the Markdown text is converted.
87 #' @param use_block Whether to use code blocks (```` ```md-math ````) to protect
88 #' `$$ $$` expressions that span across multiple lines. This is necessary when
89 #' a certain line in the math expression starts with a special character that
90 #' can accidentally start a new element (e.g., a leading `+` may start a
91 #' bullet list). Only code blocks can prevent this case.
92 #' @return A character vector with math expressions in backticks.
93 #' @note If you are using Pandoc or the \pkg{rmarkdown} package, there is no
94 #' need to use this function, because Pandoc's Markdown can recognize math
95 #' expressions.
96 #' @export
97 #' @examples library(xfun)
98 #' protect_math(c('hi $a+b$', 'hello $$\\alpha$$', 'no math here: $x is $10 dollars'))
99 #' protect_math(c('hi $$', '\\begin{equation}', 'x + y = z', '\\end{equation}'))
100 #' protect_math('$a+b$', '===')
101 protect_math = function(x, token = '', use_block = FALSE) {
102 i = prose_index(x)
103 if (length(i)) x[i] = escape_math(x[i], token, use_block)
104 x
105 }
106
107 escape_math = function(x, token = '', use_block = FALSE) {
108 # replace $x$ with `\(x\)` (protect inline math in <code></code>)
109 m = gregexpr('(?<=^|[\\s(])[$](?![ `])[^$]+?(?<![ `])[$](?![$0123456789])', x, perl = TRUE)
110 regmatches(x, m) = lapply(regmatches(x, m), function(z) {
111 if (length(z) == 0) return(z)
112 z = sub('^[$]', paste0('`', token, '\\\\('), z)
113 z = sub('[$]$', paste0('\\\\)', token, '`'), z)
114 z
115 })
116 # replace $$x$$ with `$$x$$` (protect display math)
117 m = gregexpr('(?<=^|[\\s(])[$][$](?! )[^$]+?(?<! )[$][$]', x, perl = TRUE)
118 regmatches(x, m) = lapply(regmatches(x, m), function(z) {
119 if (length(z) == 0) return(z)
120 paste0('`', token, z, token, '`')
121 })
122 # now, if there are still lines starting and ending with $$, they might be
123 # math expressions of display style spanning multiple lines, e.g.,
124 # $$\alpha +
125 # \beta$$
126 # we assume that $$ can only appear once on one line
127 i = vapply(gregexpr('[$]', x), length, integer(1)) == 2
128 if (any(i)) {
129 r1 = sprintf('\\1%s\\2', if (use_block) {
130 paste(c('```{.md-math', if (token != '') c(' .', token), '}\n\\1'), collapse = '')
131 } else paste0('`', token))
132 x[i] = gsub('^(\\s*)([$][$][^ ]+)', r1, x[i], perl = TRUE)
133 r2 = if (use_block) '\\1\\2\n\\1```' else paste0('\\1\\2', token, '`')
134 x[i] = gsub('^(\\s*)(.*?[^ ][$][$])$', r2, x[i], perl = TRUE)
135 }
136 # equation environments (\begin and \end must match); only protect outermost
137 # environments in case of nesting (e.g., \begin{cases} inside \begin{equation})
138 i1 = grep('^\\\\begin\\{[^}]+\\}$', x)
139 i2 = grep('^\\\\end\\{[^}]+\\}$', x)
140 if (length(i1) == length(i2)) {
141 events = sort(c(i1, i2))
142 depth = 0; opens = closes = integer()
143 for (j in events) {
144 if (j %in% i1) {
145 if (depth == 0) opens = c(opens, j)
146 depth = depth + 1
147 } else {
148 depth = depth - 1
149 if (depth == 0) closes = c(closes, j)
150 }
151 }
152 x[opens] = paste0('`', token, x[opens])
153 x[closes] = paste0(x[closes], token, '`')
154 }
155 x
156 }
157
158 #' Create a fenced block in Markdown
159 #'
160 #' Wrap content with fence delimiters such as backticks (code blocks) or colons
161 #' (fenced Div). Optionally the fenced block can have attributes. The function
162 #' `fenced_div()` is a shorthand of `fenced_block(char = ':')`.
163 #' @param x A character vector of the block content.
164 #' @param attrs A vector of block attributes.
165 #' @param fence The fence string, e.g., `:::` or ```` ``` ````. This will be
166 #' generated from the `char` argument by default.
167 #' @param char The fence character to be used to generate the fence string by
168 #' default.
169 #' @return `fenced_block()` returns a character vector that contains both the
170 #' fences and content.
171 #' @export
172 #' @examples
173 #' # code block with class 'r' and ID 'foo'
174 #' xfun::fenced_block('1+1', c('.r', '#foo'))
175 #' # fenced Div
176 #' xfun::fenced_block('This is a **Div**.', char = ':')
177 fenced_block = function(x, attrs = NULL, fence = make_fence(x, char), char = '`') {
178 a = block_attr(attrs)
179 c('', paste0(fence, a), x, fence)
180 }
181
182 #' @param ... Arguments to be passed to `fenced_block()`.
183 #' @rdname fenced_block
184 #' @export
185 fenced_div = function(...) fenced_block(..., char = ':')
186
187 #' @param start The number of characters to start searching `x` with. If the
188 #' string of this number of characters is found, add one more character, and
189 #' repeat the search.
190 #' @return `make_fence()` returns a character string. If the block content
191 #' contains `N` fence characters (e.g., backticks), use `N + 1` characters as
192 #' the fence.
193 #' @rdname fenced_block
194 #' @export
195 #' @examples
196 #' # three backticks by default
197 #' xfun::make_fence('1+1')
198 #' # needs five backticks for the fences because content has four
199 #' xfun::make_fence(c('````r', '1+1', '````'))
200 make_fence = function(x, char = '`', start = 3) {
201 f = strrep(char, start)
202 while (any(grepl(f, x, fixed = TRUE))) f = paste0(f, char)
203 f
204 }
205
206 # concatenate block attributes for fenced blocks
207 block_attr = function(attrs) {
208 a = paste(attrs, collapse = ' ')
209 if (grepl('[ .=#]', a)) a = paste0('{', a, '}')
210 if (a == '') a else paste0(' ', a)
211 }
212
213 #' Embed a file, multiple files, or directory on an HTML page
214 #'
215 #' For a file, first encode it into base64 data (a character string). Then
216 #' generate a hyperlink of the form \samp{<a href="base64 data"
217 #' download="filename">Download filename</a>}. The file can be downloaded when
218 #' the link is clicked in modern web browsers. For a directory, it will be
219 #' compressed as a zip archive first, and the zip file is passed to
220 #' `embed_file()`. For multiple files, they are also compressed to a zip file
221 #' first.
222 #'
223 #' These functions can be called in R code chunks in R Markdown documents with
224 #' HTML output formats. You may embed an arbitrary file or directory in the HTML
225 #' output file, so that readers of the HTML page can download it from the
226 #' browser. A common use case is to embed data files for readers to download.
227 #' @param path Path to the file(s) or directory.
228 #' @param name The default filename to use when downloading the file. Note that
229 #' for `embed_dir()`, only the base name (of the zip filename) will be used.
230 #' @param text The text for the hyperlink.
231 #' @param ... For `embed_file()`, additional arguments to be passed to
232 #' [html_tag()] (e.g., `class = 'foo'`). For `embed_dir()` and
233 #' `embed_files()`, arguments passed to `embed_file()`.
234 #' @note Windows users may need to install Rtools to obtain the \command{zip}
235 #' command to use `embed_dir()` and `embed_files()`.
236 #' @return An HTML tag \samp{<a>} with the appropriate attributes.
237 #' @export
238 #' @examples
239 #' logo = xfun:::R_logo()
240 #' link = xfun::embed_file(logo, text = 'Download R logo')
241 #' link
242 #' if (interactive()) xfun::html_view(link)
243 embed_file = function(path, name = basename(path), text = paste('Download', name), ...) {
244 h = base64_uri(path)
245 html_tag('a', text, href = h, download = name, ...)
246 }
247
248 #' @rdname embed_file
249 #' @export
250 embed_dir = function(path, name = paste0(normalize_path(path), '.zip'), ...) {
251 name = gsub('/', '', basename(name))
252 in_dir(path, {
253 name = file.path(tempdir(), name); on.exit(file.remove(name), add = TRUE)
254 zip(name, '.'); embed_file(name, ...)
255 })
256 }
257
258 #' @rdname embed_file
259 #' @export
260 embed_files = function(path, name = with_ext(basename(path[1]), '.zip'), ...) {
261 name = file.path(tempdir(), basename(name))
262 on.exit(file.remove(name), add = TRUE)
263 zip(name, path)
264 embed_file(name, ...)
265 }
266
267 zip = function(name, ...) {
268 if (utils::zip(name, ...) != 0) stop('Failed to create the zip archive ', name)
269 invisible(0)
270 }
271
272 #' Generate a simple Markdown pipe table
273 #'
274 #' A minimal Markdown table generator using the pipe `|` as column separators.
275 #'
276 #' The default argument values can be set via global options with the prefix
277 #' `xfun.md_table.`, e.g., `options(xfun.md_table.digits 2, xfun.md_table.na =
278 #' 'n/a')`.
279 #' @param x A 2-dimensional object (e.g., a matrix or data frame).
280 #' @param digits The number of decimal places to be passed to [round()]. It can
281 #' be a integer vector of the same length as the number of columns in `x` to
282 #' round columns separately. The default is `3`.
283 #' @param na A character string to represent `NA` values. The default is an
284 #' empty string.
285 #' @param newline A character string to substitute `\n` in `x` (because pipe
286 #' tables do not support line breaks in cells). The default is a space.
287 #' @param limit The maximum number of rows to show in the table. If it is
288 #' smaller than the number of rows, the data in the middle will be omitted. If
289 #' it is of length 2, the second number will be used to limit the number of
290 #' columns. Zero and negative values are ignored.
291 #' @param escape Whether to backslash-escape special Markdown characters
292 #' (\verb{\\`, *, _, [, ], <, >, ~, \\}) in table cells. This prevents cell
293 #' content from being interpreted as Markdown (e.g., `<foo:bar>` being treated
294 #' as a link). It can take a logical value (`TRUE` means all columns and
295 #' `FALSE` means none), or a vector of column indices or names to escape
296 #' selectively. The default is `FALSE`.
297 #' @return A character vector.
298 #' @seealso [knitr::kable()] (which supports more features)
299 #' @export
300 #' @examples
301 #' xfun::md_table(head(iris))
302 #' xfun::md_table(mtcars, limit = c(10, 6))
303 #' xfun::md_table(data.frame(x = 'Hello <world>', y = 1), escape = TRUE)
304 #' xfun::md_table(data.frame(x = 'Hello <world>', y = 1), escape = 'x')
305 md_table = function(x, digits = NULL, na = NULL, newline = NULL, limit = NULL, escape = NULL) {
306 if (length(d <- dim(x)) != 2)
307 stop('xfun::md_table() only supports 2-dimensional objects.')
308 if (d[2] == 0) return(character())
309 if (is.null(digits))
310 digits = getOption('xfun.md_table.digits', min(getOption('digits'), 3))
311 digits = rep(digits, d[2]) # recycle for all columns
312 num = logical(d[2]) # numeric columns
313 for (j in seq_len(d[2])) if (is.numeric(x[, j])) {
314 num[j] = TRUE
315 x[, j] = round(x[, j], digits[j])
316 }
317 is_na = is.na(x)
318 x = as.matrix(format(x))
319 if (any(is_na)) x[is_na] = na %||% getOption('xfun.md_table.na', '')
320 rn = rownames(x)
321 # ignore empty and automatic row names (integers)
322 if (!all(grepl('^[0-9]*$', rn))) {
323 x = cbind(' ' = rn, x)
324 num = c(FALSE, num)
325 }
326 # get first and last limit/2 rows/cols in N rows/cols
327 if (length(limit <- limit %||% getOption('xfun.md_table.limit'))) {
328 # subset rows
329 l1 = limit[1]
330 if (l1 > 0 && l1 < d[1]) {
331 n1 = round(l1/2); n2 = l1 - n1
332 x = rbind(head(x, n1), '&vellip;', tail(x, n2))
333 }
334 # subset columns
335 if (length(limit) >= 2 && (l2 <- limit[2]) > 0 && l2 < d[2]) {
336 n1 = round(l2/2); n2 = l2 - n1
337 x = cbind(
338 x[, seq_len(n1), drop = FALSE],
339 `...` = '...',
340 x[, d[2] - seq_len(n2) + 1, drop = FALSE]
341 )
342 num = c(head(num, n1), FALSE, tail(num, n2))
343 }
344 d = dim(x)
345 if (d[2] == 0) return(character())
346 }
347 escape = escape %||% getOption('xfun.md_table.escape', FALSE)
348 if (!isFALSE(escape)) {
349 cols = if (isTRUE(escape)) seq_len(ncol(x)) else {
350 if (is.character(escape)) match(escape, colnames(x)) else escape
351 }
352 cols = cols[!is.na(cols)]
353 for (j in cols) x[, j] = gsub('([][\\\\`*_<>~])', '\\\\\\1', x[, j])
354 }
355 cn = colnames(x) %||% rep(' ', d[2]) # table header
356 a = ifelse(num, '--:', '---') # alignment
357 a[cn == '...'] = ':-:'
358 x = rbind(cn, a, x)
359 d = dim(x)
360 x = gsub('|', '\\|', x, fixed = TRUE)
361 dim(x) = d
362 res = do.call(function(...) paste(..., sep = '|'), as.data.frame(x))
363 res = gsub('\n', newline %||% getOption('xfun.md_table.newline', ' '), res, fixed = TRUE)
364 paste0('|', res, '|')
365 }
366
367 #' Represent a (recursive) list with (nested) tabsets
368 #'
369 #' The tab titles are names of list members, and the tab content contains the
370 #' values of list members. If a list member is also a list, it will be
371 #' represented recursively with a child tabset.
372 #' @param x A list for `tabset()`, and a character vector for `tab_content()`.
373 #' @param value A function to print the value of a list member. By default,
374 #' [str()] is used to print the structure of the value. You may also use
375 #' [dput()] to output the full value, but it may be slow when the size of the
376 #' value is too big. If the function prints the value to the console, the
377 #' output will be captured and shown in a code block. If you want construct
378 #' the tab content by yourself instead of capturing console output as a code
379 #' block, you may pass the Markdown content to [tab_content()] and return it
380 #' in this `value()` function.
381 #' @return A character vector of Markdown that can be rendered to HTML with
382 #' [litedown::mark()].
383 #' @export
384 #' @examples
385 #' xfun::tabset(iris)
386 #' xfun::tabset(iris, dput)
387 #' xfun::tabset(iris, print)
388 #'
389 #' # a deeply nested list
390 #' plot(1:10)
391 #' p = recordPlot()
392 #' xfun::tabset(p)
393 #'
394 #' # custom tab content
395 #' xfun::tabset(iris, function(x) {
396 #' if (is.factor(x)) {
397 #' res = c('A factor with levels: ', xfun::join_words(levels(x), before = '`'))
398 #' xfun::tab_content(res)
399 #' } else print(summary(x))
400 #' })
401 tabset = function(x, value = str) {
402 obj = paste(deparse(substitute(x)), collapse = ' ')
403 md_viewable(.tabset(x, value), meta = list(
404 css = '@tabsets', js = '@tabsets', title = paste0('`xfun::tabset(', obj, ')`')
405 ))
406 }
407
408 .tabset = function(x, value) {
409 if (is.list(x)) {
410 idx = seq_along(x)
411 nms = names(x) %||% sprintf('[[%d]]', idx)
412 res = NULL
413 for (i in idx) {
414 con = paste0(' ', .tabset(unclass(x)[[i]], value)) # indent content
415 res = c(res, paste0('- `', nms[i], '`'), '', con)
416 }
417 # attach attributes to the last tab if necessary
418 if (is.list(att <- attributes(x))) {
419 att$names = NULL # names have been displayed
420 if (length(att)) res = c(
421 res, '', '- `attr(*)`', '', paste0(' ', .tabset(att, value))
422 )
423 }
424 c('::: tabset', res, ':::')
425 } else {
426 out = capture.output(val <- value(x))
427 # if the value() function prints something, use a code block to show the
428 # output; otherwise, show the value itself if it is a record_asis object
429 if (length(out)) c('```r', out, '```') else
430 as.character(if (inherits(val, 'record_asis')) val)
431 }
432 }
433
434 #' @rdname tabset
435 #' @export
436 tab_content = function(x) invisible(new_record(x, 'asis'))
437
438 md_viewable = function(x, ...) {
439 structure(x, class = c('xfun_md_viewable', 'record_asis'), ...)
440 }
441
442 #' @export
443 print.xfun_md_viewable = function(x, ...) {
444 if (loadable('litedown')) {
445 html = litedown::mark(text = c('---', '---', '', x), meta = attr2(x, 'meta'), ...)
446 html_view(html)
447 } else {
448 warning("Cannot preview the result since the 'litedown' package is not available.")
449 raw_string(x)
450 }
451 }