Debian Codegraph @

R/package.R

raw
1 #' A lightweight version of R Markdown
2 #'
3 #' Markdown is a plain-text format that can be converted to HTML and other
4 #' formats. This package can render R Markdown to Markdown, and then to an
5 #' output document format. The main differences between this package and
6 #' \pkg{rmarkdown} are that it does not use Pandoc or \pkg{knitr} (i.e., fewer
7 #' dependencies), and it also has fewer Markdown features.
8 #' @importFrom xfun alnum_id base64_uri csv_options del_empty_dir dir_create
9 #' divide_chunk download_cache exit_call fenced_block fenced_div file_exists
10 #' file_ext grep_sub html_escape html_tag html_value in_dir is_abs_path
11 #' is_blank is_rel_path loadable mime_type new_app new_record normalize_path
12 #' parse_only prose_index raw_string read_all read_utf8 record_print
13 #' relative_path Rscript_call same_path sans_ext set_envvar split_lines
14 #' try_error try_silent with_ext write_utf8
15 '_PACKAGE'
16
17 # an internal environment to store some intermediate objects
18 .env = new_env()
19
20 #' The `fuse()` environment
21 #'
22 #' Get the environment passed to the `envir` argument of [fuse()], i.e., the
23 #' environment in which code chunks and inline code are evaluated.
24 #' @return When called during `fuse()`, it returns the `envir` argument value of
25 #' `fuse()`. When called outside `fuse()`, it returns the global environment.
26 #' @export
27 fuse_env = function() .env$global %||% globalenv()
28
29 #' @export
30 record_print.data.frame = function(x, ...) {
31 asis = inherits(x, 'AsIs')
32 if (is.null(getOption('xfun.md_table.limit')) && !'limit' %in% names(list(...))) {
33 opts = options(xfun.md_table.limit = if (!asis) 10)
34 on.exit(options(opts), add = TRUE)
35 }
36 if (asis) class(x) = setdiff(class(x), 'AsIs')
37 if (inherits(x, 'tbl_df')) x = as.data.frame(x)
38 tab = xfun::md_table(x, ...)
39 opt = reactor()
40 tab = add_cap(tab, opt$tab.cap, opt$label, opt$cap.pos %||% 'top', opt$tab.env, 'tab')
41 new_record(c(tab, ''), 'asis')
42 }
43
44 #' @export
45 record_print.matrix = record_print.data.frame
46
47 #' @export
48 record_print.tbl_df = record_print.data.frame
49
50 #' @export
51 record_print.knitr_kable = function(x, ...) {
52 if ((fmt <- attr(x, 'format')) %in% c('html', 'latex'))
53 x = fenced_block(x, paste0('=', fmt))
54 new_record(c(x, ''), 'asis')
55 }
56
57 # register vignette engines
58 .onLoad = function(lib, pkg) {
59 vig_add('vignette', vig_fun(TRUE), vig_fun(FALSE))
60 vig_add('book', vig_fun(TRUE, TRUE), vig_fun(FALSE, TRUE))
61 }
62
63 vig_add = function(name, weave, tangle) {
64 tools::vignetteEngine(
65 name, weave, tangle, '[.]R?md$', aspell = list(filter = vig_filter)
66 )
67 }
68
69 # weave or tangle?
70 vig_fun = function(weave = TRUE, book = FALSE) {
71 function(file, quiet = FALSE, ...) {
72 empty_file = function() write_utf8(character(), with_ext(file, '.R'))
73
74 # call fuse_book() to build multiple input files into a book
75 if (book) return(if (weave) {
76 if (quiet) {
77 opt = options(litedown.progress.delay = Inf); on.exit(options(opt))
78 }
79 fuse_book(dirname(file), envir = globalenv())
80 } else empty_file())
81
82 # fuse() .Rmd and mark() .md
83 if (grepl('[.]Rmd$', file)) {
84 if (weave) fuse(file, quiet = quiet, envir = globalenv()) else {
85 if (getRversion() <= '3.2.5') empty_file() else fiss(file)
86 }
87 } else {
88 if (weave) mark(file) else empty_file()
89 }
90 }
91 }
92
93 # filter out code from document so aspell() won't spell check code
94 vig_filter = function(ifile, encoding) {
95 res = crack(ifile)
96 res = lapply(res, function(x) {
97 if (x$type == 'code_chunk') return(rep('', length(x$source)))
98 if (is.character(x$source)) x$source else {
99 one_string(uapply(x$source, function(s) {
100 if (is.character(s)) s else ''
101 }), '')
102 }
103 })
104 structure(split_lines(unlist(res)), control = '-H -t')
105 }
106
107 #' Print the package description, news, citation, manual pages, and source code
108 #'
109 #' Helper functions to retrieve various types of package information that can be
110 #' put together as the full package documentation like a \pkg{pkgdown} website.
111 #' These functions can be called inside any R Markdown document.
112 #' @param name The package name (by default, it is automatically detected from
113 #' the `DESCRIPTION` file if it exists in the current working directory or
114 #' upper-level directories).
115 #' @param type The HTML tag for the description: `table` (`<table>` with `<tr>`
116 #' and `<td>`) or `dl` (definition list `<dl>` with `<dt>` and `<dd>`).
117 #' @return A character vector (HTML or Markdown) that will be printed as is
118 #' inside a code chunk of an R Markdown document.
119 #'
120 #' `pkg_desc()` returns an HTML table containing the package metadata.
121 #' @export
122 #' @examples
123 #' \dontrun{
124 #' litedown::pkg_desc()
125 #' litedown::pkg_news()
126 #' litedown::pkg_citation()
127 #' }
128 pkg_desc = function(name = detect_pkg(), type = c('table', 'dl')) {
129 fields = c(
130 'Title', 'Version', 'Description', 'Depends', 'Imports', 'Suggests',
131 'License', 'URL', 'BugReports', 'VignetteBuilder', 'Authors@R', 'Author'
132 )
133 # read the DESCRIPTION file if pkg root is found, otherwise use installed info
134 d = if (is.character(p <- attr(name, 'path'))) {
135 as.list(read.dcf(file.path(p, 'DESCRIPTION'))[1, ][fields])
136 } else {
137 packageDescription(name, fields = fields)
138 }
139 names(d) = fields
140 # remove single quotes on words (which are unnecessary IMO)
141 for (i in c('Title', 'Description')) d[[i]] = sans_sq(d[[i]])
142 d[['Author']] = one_string(pkg_authors(d), ', ')
143 d[['Authors@R']] = NULL
144 # convert URLs to <a>, and escape HTML in other fields
145 for (i in names(d)) d[[i]] = if (!is.na(d[[i]])) {
146 if (i %in% c('Description', 'URL', 'BugReports', 'Author')) {
147 sans_p(commonmark::markdown_html(d[[i]], extensions = 'autolink'))
148 } else html_escape(d[[i]])
149 }
150 d = unlist(d)
151 res = one_string(switch(
152 type[1],
153 table = c(
154 '<table class="table-full"><tbody>',
155 sprintf('<tr>\n<td>%s</td>\n<td>%s</td>\n</tr>', names(d), d),
156 '</tbody></table>'
157 ),
158 dl = c('<dl class="pkg-desc">', sprintf('<dt>%s</dt>\n<dd>%s</dd>', names(d), d), '</dl>')
159 ))
160
161 new_asis(c(res, vest(css = '@manual')))
162 }
163
164 # format authors, adding URL and ORCID links as appropriate
165 pkg_authors = function(desc, role = NULL, extra = TRUE) {
166 if (is.null(a <- desc[['Authors@R']])) return(desc[['Author']])
167 a = eval(parse_only(a))
168 a = uapply(a, function(x) {
169 if (length(role) && !any(role %in% x$role)) return()
170 role = if (extra && length(x$role)) paste0('[', one_string(x$role, ', '), ']')
171 name = paste(x$given, x$family)
172 comment = as.list(x$comment)
173 orcid = if (extra) sprintf(
174 '[![ORCID iD](https://cloud.r-project.org/web/orcid.svg){.orcid}](https://orcid.org/%s)',
175 comment[["ORCID"]]
176 )
177 link = comment[['URL']]
178 if (length(link)) name = sprintf('[%s](%s)', name, link)
179 one_string(c(name, orcid, role), ' ')
180 })
181 a
182 }
183
184 #' @param path For [pkg_news()], path to the `NEWS.md` file. If empty, [news()]
185 #' will be called to retrieve the news entries. For [pkg_code()], path to the
186 #' package root directory that contains `R/` and/or `src/` subdirectories.
187 #' @param recent The number of recent versions to show. By default, only the
188 #' latest version's news entries are retrieved. To show the full news, set
189 #' `recent = 0`.
190 #' @param toc Whether to add section headings to the document TOC (when TOC has
191 #' been enabled for the document).
192 #' @param number_sections Whether to number section headings (when sections are
193 #' numbered in the document).
194 #' @param ... Other arguments to be passed to [news()].
195 #' @return `pkg_news()` returns the news entries.
196 #' @rdname pkg_desc
197 #' @export
198 pkg_news = function(
199 name = detect_pkg(), path = detect_news(name), recent = 1, toc = TRUE,
200 number_sections = TRUE, ...
201 ) {
202 a = header_class(toc, number_sections)
203 if (length(path) != 1 || path == '') {
204 db = news(package = name, ...)
205 if (recent > 0) db = head(db, recent)
206 res = NULL
207 for (v in unique(db$Version)) {
208 df = db[db$Version == v, ]
209 res = c(
210 res, paste('##', name, v, a), '',
211 if (all(df$Category == '')) paste0(df$HTML, '\n') else paste0(
212 '### ', df$Category, a, '\n\n', df$HTML, '\n\n'
213 ), ''
214 )
215 }
216 } else {
217 res = read_utf8(path)
218 if (recent > 0 && length(h <- grep('^# ', res)) >= 2)
219 res = res[h[1]:(h[1 + recent] - 1)]
220 # lower heading levels: # -> ##, ## -> ###, etc, and add attributes
221 for (i in 2:1) res = sub(sprintf('^(#{%d} .+)', i), paste0('#\\1', a), res)
222 # shorten headings
223 res = gsub('^## CHANGES IN ([^ ]+) VERSION( .+)', '## \\1\\2', res)
224 # link Github @username and #issue
225 if (length(u <- github_link(dirname(path)))) {
226 r1 = '([[:alnum:]-]+)'; r2 = '([0-9]+)'
227 res = gsub(paste0(' @', r1), ' [@\\1](https://github.com/\\1)', res)
228 res = gsub(paste0(' #', r2), sprintf(' [#\\1](%sissues/\\1)', u), res)
229 res = gsub(
230 sprintf(' %s/%s#%s', r1, r1, r2),
231 ' [\\1/\\2#\\3](https://github.com/\\1/\\2/issues/\\3)', res
232 )
233 }
234 }
235 new_asis(res)
236 }
237
238 # classes for section headings in news, code, and manual
239 header_class = function(toc, number_sections, md = TRUE) {
240 a = c(if (!toc) 'unlisted', if (!number_sections) 'unnumbered')
241 if (md && length(a)) a = paste0('.', a)
242 a = one_string(a, ' ')
243 if (a != '') a = if (md) paste0(' {', a, '}') else paste0(' class="', a, '"')
244 a
245 }
246
247 #' @param pattern A regular expression to match filenames that should be treated
248 #' as source code.
249 #' @param link Whether to add links on the file paths of source code. By
250 #' default, if a GitHub repo link is detected from the `BugReports` field of
251 #' the package `DESCRIPTION`, GitHub links will be added to file paths. You
252 #' can also provide a string template containing the placeholder `%s` (which
253 #' will be filled out with the file paths via `sprintf()`), e.g.,
254 #' `https://github.com/yihui/litedown/blob/main/%s`.
255 #' @return `pkg_code()` returns the package source code under the `R/` and
256 #' `src/` directories.
257 #' @rdname pkg_desc
258 #' @export
259 pkg_code = function(
260 path = attr(detect_pkg(), 'path'), pattern = '[.](R|c|h|f|cpp)$', toc = TRUE,
261 number_sections = TRUE, link = TRUE
262 ) {
263 if (!isTRUE(dir.exists(path))) {
264 if (missing(path)) message('Please run this function in the package source directory.')
265 return()
266 }
267 a = header_class(toc, number_sections)
268 if (isTRUE(link) && length(u <- github_link(path))) link = paste0(u, 'blob/HEAD/%s')
269 ds = c('R', 'src')
270 ds = ds[ds %in% list.dirs(path, FALSE, FALSE)]
271 flat = length(ds) == 1 # if only one dir exists, list files in a flat structure
272 code = in_dir(path, lapply(ds, function(d) {
273 fs = list.files(d, pattern, full.names = TRUE, recursive = TRUE)
274 if (length(fs) == 0) return()
275 x = uapply(fs, function(f) c(
276 sprintf('##%s %s%s', if (flat) '' else '#', if (is.character(link)) {
277 sprintf('[`%s`](%s)', f, sprintf(link, f))
278 } else sprintf('`%s`', f), a), '',
279 fenced_block(read_utf8(f), lineno_attr(file_ext(f), auto = FALSE)), ''
280 ))
281 e = unique(file_ext(fs))
282 c(if (!flat) paste0('## ', paste0('`*.', e, '`', collapse = ' / '), a), '', x)
283 }))
284 new_asis(unlist(code))
285 }
286
287 # retrieve Github repo link from DESCRIPTION
288 github_link = function(path) {
289 u = read.dcf(file.path(path, 'DESCRIPTION'), 'BugReports')[1, 1]
290 grep_sub('^(https://github.com/[^/]+/[^/]+/).*', '\\1', u)
291 }
292
293 #' @return `pkg_citation()` returns the package citation in both the plain-text
294 #' and BibTeX formats.
295 #' @rdname pkg_desc
296 #' @export
297 pkg_citation = function(name = detect_pkg()) {
298 res = uapply(citation(name), function(x) {
299 x = tweak_citation(x)
300 unname(c(format(x, style = 'text'), fenced_block(toBibtex(x), 'latex')))
301 })
302 new_asis(res)
303 }
304
305 # dirty hack to add year if missing
306 tweak_citation = function(x) {
307 cls = class(x)
308 x = unclass(x)
309 if (is.null(x[[1]]$year)) x[[1]]$year = format(Sys.Date(), '%Y')
310 class(x) = cls
311 x
312 }
313
314 #' @param overview Whether to include the package overview page, i.e., the
315 #' `{name}-package.Rd` page.
316 #' @param examples A list of arguments to be passed to [xfun::record()] to run
317 #' examples each help page, e.g., `list(dev = 'svg', dev.args = list(height =
318 #' 6))`. If not a list (e.g., `FALSE`), examples will not be run.
319 #' @return `pkg_manual()` returns all manual pages of the package in HTML.
320 #' @rdname pkg_desc
321 #' @export
322 pkg_manual = function(
323 name = detect_pkg(), toc = TRUE, number_sections = TRUE, overview = TRUE,
324 examples = list()
325 ) {
326 links = tools::findHTMLlinks('')
327 # resolve internal links (will assign IDs of the form sec:man-ID to all h2)
328 r = sprintf('^[.][.]/[.][.]/(%s)/html/(.+)[.]html$', name)
329 i = grep(r, links)
330 links[i] = paste0('#sec:man-', alnum_id(sub(r, '\\2', links[i])))
331 # resolve external links to specific man pages on https://rdrr.io
332 r = sprintf('^[.][.]/[.][.]/(%s)/html/', paste(xfun::base_pkgs(), collapse = '|'))
333 links = sub(r, 'https://rdrr.io/r/\\1/', links)
334
335 db = tools::Rd_db(name) # all Rd pages
336 intro = paste0(name, '-package.Rd') # the name-package entry (package overview)
337 entries = setdiff(names(db), intro)
338 entries = entries[!vapply(entries, function(i) {
339 kwd = uapply(db[[i]], function(x) if (attr(x, 'Rd_tag') == '\\keyword') x)
340 'internal' %in% kwd
341 }, logical(1))]
342 db = db[c(if (overview && intro %in% names(db)) intro, entries)]
343 al = lapply(db, Rd_aliases)
344
345 cl = header_class(toc, number_sections, FALSE)
346 r1 = '<code class="reqn">\\s*([^<]+?)\\s*</code>' # inline math
347 r2 = sprintf('<p[^>]*>\\s*%s\\s*</p>', r1) # display math
348 res = uapply(names(db), function(i) {
349 txt = ''
350 con = textConnection('txt', 'w', local = TRUE, encoding = 'UTF-8')
351 tryCatch(
352 tools::Rd2HTML(db[[i]], Links = links, out = con), error = function(e) {
353 warning("The Rd file '", i, "' appears to be malformed.", call. = FALSE)
354 stop(e)
355 }, finally = close(con))
356 # extract body, which may end at </main> (R 4.4.x) or </div></body> (R 4.3.x)
357 txt = gsub('(?s).*?(?=<h2)', '', one_string(txt), perl = TRUE)
358 txt = gsub('(</main>|</div>\\s*</body>).*', '', txt)
359 # free math from <code>
360 txt = gsub(r2, '<p>$$\\1$$</p>', txt)
361 txt = gsub(r1, '<span>\\\\(\\1\\\\)</span>', txt)
362 # run examples
363 if (is.list(examples)) {
364 xfun::pkg_attach(name)
365 default = list(print = function(x, ...) {
366 if (inherits(x, 'xfun_raw_string')) record_print(x) else
367 xfun:::record_print.default(x)
368 }, dev.path = 'manual/', dev.args = list(width = 9, height = 7))
369 txt = run_examples(txt, merge_list(default, examples), sans_ext(i))
370 }
371 # remove existing ID and class
372 for (a in c('id', 'class')) txt = gsub(sprintf('(<h2[^>]*?) %s="[^"]+"', a), '\\1', txt)
373 if (cl != '') txt = sub('<h2', paste0('<h2', cl), txt, fixed = TRUE)
374 sub('<h2', sprintf('<h2 id="sec:man-%s"', sans_ext(i)), txt, fixed = TRUE)
375 })
376
377 # extract all aliases and put them in the beginning (like a TOC)
378 env = asNamespace(name)
379 toc = unlist(.mapply(function(topics, target) {
380 fn = uapply(topics, function(x) {
381 if (is.function(env[[x]])) paste0(x, '()') else x # add () after function names
382 })
383 sprintf('<a href="#sec:man-%s"><code>%s</code></a>', target, fn)
384 }, al, sans_ext(names(al))))
385
386 g = toupper(substr(unlist(al), 1, 1))
387 g[!g %in% LETTERS] = 'misc'
388 g = factor(g, intersect(c(LETTERS, 'misc'), g))
389 toc = split(toc, g) # group by first character
390 toc = unlist(mapply(function(x, g) {
391 c('<p>', sprintf('<b>-- <kbd>%s</kbd> --</b>', g), x, '</p>')
392 }, toc, names(toc)))
393
394 r = '(<a href=")[.][.]/[.][.]/([^/]+)/help/'
395 res = gsub(r, '\\1https://rdrr.io/cran/\\2/man/', res)
396 res = gsub(" (id|class)='([^']+)'", ' \\1="\\2"', res) # ' -> "
397 res = gsub('<h3>', '<h3 class="unnumbered unlisted">', res, fixed = TRUE)
398 res = match_replace(res, '<(h[1-6])[^>]*>(?s).+?</\\1>', function(x) {
399 gsub('\n', ' ', x) # remove \n in headings so build_toc() can be correctly build TOC
400 })
401 res = gsub('<code style="[^"]+">', '<code>', res)
402 res = gsub('<code id="[^"]+">', '<code>', res)
403 res = gsub('(<code[^>]*>)\\s+', '\\1', res)
404 res = gsub('\\s+(</code>)', '\\1', res)
405 res = gsub('<div class="sourceCode"><pre>(.+?)</pre></div>', '<pre><code>\\1</code></pre>', res)
406 res = gsub('<div class="sourceCode ([^"]+)"><pre>(.+?)</pre></div>', '<pre><code class="language-\\1">\\2</code></pre>', res)
407 res = gsub('<code class="language-R"', '<code class="language-r"', res, fixed = TRUE)
408 res = gsub('&#8288;', '', res, fixed = TRUE)
409 res = gsub('<img src="../help/figures/', '<img src="man/figures/', res, fixed = TRUE)
410 new_asis(c(toc, res, vest(css = '@manual')))
411 }
412
413 run_examples = function(html, config, path) {
414 config$dev.path = path = paste0(config$dev.path, path)
415 on.exit(del_empty_dir(dirname(path)), add = TRUE)
416 r = '(?s).*?<pre><code[^>]*>(?s)(.+?)</code></pre>'
417 match_replace(html, paste0('(?<=<h3>Examples</h3>)', r), function(x) {
418 code = gsub(r, '\\1', x, perl = TRUE)
419 code = restore_html(str_trim(code))
420 nr1 = 'if (FALSE) { ## Not run'
421 nr2 = '} ## Not run'
422 code = gsub('\n?## Not run:\\s*?\n', paste0('\n', nr1, '\n'), code)
423 code = gsub('\n+## End[(]Not run[)]\n*', paste0('\n', nr2, '\n'), code)
424 res = do.call(xfun::record, merge_list(config, list(code = code, envir = globalenv())))
425 idx = seq_along(res); cls = class(res)
426 for (i in idx) {
427 ri = res[[i]]; ci = class(ri)
428 # disable asis output since it may contain raw HTML
429 if ('record_asis' %in% ci) class(res[[i]]) = 'record_output'
430 # split the dontrun block
431 if ('record_source' %in% ci && !any(is.na(nr <- match(c(nr1, nr2), ri)))) {
432 i1 = nr[1]; i2 = nr[2]
433 new_block = function(i, ...) {
434 b = trim_blank(one_string(ri[i]))
435 if (is_blank(b)) b = character()
436 list(structure(b, class = c(ci, ...)))
437 }
438 if (i1 > 1) {
439 res = c(res, new_block((i1 + 1):(i2 - 1), 'fade'))
440 idx = c(idx, i)
441 }
442 n = length(ri)
443 if (i2 < n) {
444 res = c(res, new_block((i2 + 1):n))
445 idx = c(idx, i)
446 }
447 res[i] = if (i1 > 1) new_block(1:(i1 - 1)) else
448 new_block((i1 + 1):(i2 - 1), 'fade')
449 }
450 }
451 res = res[order(idx)]
452 class(res) = cls
453 res = one_string(c('', format(res, 'markdown')))
454 res
455 })
456 }
457
458 # detect package name and root path from current and upper dirs
459 detect_pkg = local({
460 res = NULL # cache the detection
461 function(...) {
462 if (is.null(res) || !same_path('.', attr(res, 'wd'))) res <<- .detect_pkg(...)
463 res
464 }
465 })
466
467 .detect_pkg = function(error = TRUE) {
468 ds = if (xfun::is_R_CMD_check()) {
469 # R CMD check's working directory is PKG_NAME.Rcheck by default
470 name = grep_sub('[.]Rcheck$', '', basename(getwd()))
471 # when running R CMD check, DESCRIPTION won't be under working directory but
472 # ../PKG_NAME/ (on CRAN's *nix) or ./00_pkg_src/
473 c(file.path('..', name), if (dir.exists('00_pkg_src'))
474 dirname(list.files('.', '^DESCRIPTION$', recursive = TRUE)))
475 } else name = NULL
476 for (d in c(ds, './')) {
477 if (!is.null(root <- xfun::proj_root(d, head(xfun::root_rules, 1)))) break
478 }
479 if (is.null(root)) {
480 root = if (length(name)) system.file(package = name)
481 if (identical(root, '')) root = NULL
482 }
483 if (is.null(root)) {
484 if (error) stop(
485 "Cannot automatically detect the package root directory from '", getwd(), "'. ",
486 "You must provide the package name explicitly."
487 ) else return()
488 } else if (is.null(name)) {
489 desc = read_utf8(file.path(root, 'DESCRIPTION'))
490 name = grep_sub('^Package: (.+?)\\s*$', '\\1', desc)[1]
491 }
492 structure(name, path = root, wd = getwd())
493 }
494
495 detect_news = function(name) {
496 if (isTRUE(file_exists(path <- file.path(attr(name, 'path'), 'NEWS.md'))))
497 path else system.file('NEWS.md', package = name)
498 }
499
500 # get \alias{} names in an Rd object
501 Rd_aliases = function(x) {
502 uapply(x, function(x) if (attr(x, 'Rd_tag') == '\\alias') as.character(x))
503 }