`
#' and ``) or `dl` (definition list `` with `- ` and `
- `).
#' @return A character vector (HTML or Markdown) that will be printed as is
#' inside a code chunk of an R Markdown document.
#'
#' `pkg_desc()` returns an HTML table containing the package metadata.
#' @export
#' @examples
#' \dontrun{
#' litedown::pkg_desc()
#' litedown::pkg_news()
#' litedown::pkg_citation()
#' }
pkg_desc = function(name = detect_pkg(), type = c('table', 'dl')) {
fields = c(
'Title', 'Version', 'Description', 'Depends', 'Imports', 'Suggests',
'License', 'URL', 'BugReports', 'VignetteBuilder', 'Authors@R', 'Author'
)
# read the DESCRIPTION file if pkg root is found, otherwise use installed info
d = if (is.character(p <- attr(name, 'path'))) {
as.list(read.dcf(file.path(p, 'DESCRIPTION'))[1, ][fields])
} else {
packageDescription(name, fields = fields)
}
names(d) = fields
# remove single quotes on words (which are unnecessary IMO)
for (i in c('Title', 'Description')) d[[i]] = sans_sq(d[[i]])
d[['Author']] = one_string(pkg_authors(d), ', ')
d[['Authors@R']] = NULL
# convert URLs to , and escape HTML in other fields
for (i in names(d)) d[[i]] = if (!is.na(d[[i]])) {
if (i %in% c('Description', 'URL', 'BugReports', 'Author')) {
sans_p(commonmark::markdown_html(d[[i]], extensions = 'autolink'))
} else html_escape(d[[i]])
}
d = unlist(d)
res = one_string(switch(
type[1],
table = c(
'
',
sprintf('\n| %s | \n%s | \n ', names(d), d),
' '
),
dl = c('', sprintf('- %s
\n- %s
', names(d), d), ' ')
))
new_asis(c(res, vest(css = '@manual')))
}
# format authors, adding URL and ORCID links as appropriate
pkg_authors = function(desc, role = NULL, extra = TRUE) {
if (is.null(a <- desc[['Authors@R']])) return(desc[['Author']])
a = eval(parse_only(a))
a = uapply(a, function(x) {
if (length(role) && !any(role %in% x$role)) return()
role = if (extra && length(x$role)) paste0('[', one_string(x$role, ', '), ']')
name = paste(x$given, x$family)
comment = as.list(x$comment)
orcid = if (extra) sprintf(
'[{.orcid}](https://orcid.org/%s)',
comment[["ORCID"]]
)
link = comment[['URL']]
if (length(link)) name = sprintf('[%s](%s)', name, link)
one_string(c(name, orcid, role), ' ')
})
a
}
#' @param path For [pkg_news()], path to the `NEWS.md` file. If empty, [news()]
#' will be called to retrieve the news entries. For [pkg_code()], path to the
#' package root directory that contains `R/` and/or `src/` subdirectories.
#' @param recent The number of recent versions to show. By default, only the
#' latest version's news entries are retrieved. To show the full news, set
#' `recent = 0`.
#' @param toc Whether to add section headings to the document TOC (when TOC has
#' been enabled for the document).
#' @param number_sections Whether to number section headings (when sections are
#' numbered in the document).
#' @param ... Other arguments to be passed to [news()].
#' @return `pkg_news()` returns the news entries.
#' @rdname pkg_desc
#' @export
pkg_news = function(
name = detect_pkg(), path = detect_news(name), recent = 1, toc = TRUE,
number_sections = TRUE, ...
) {
a = header_class(toc, number_sections)
if (length(path) != 1 || path == '') {
db = news(package = name, ...)
if (recent > 0) db = head(db, recent)
res = NULL
for (v in unique(db$Version)) {
df = db[db$Version == v, ]
res = c(
res, paste('##', name, v, a), '',
if (all(df$Category == '')) paste0(df$HTML, '\n') else paste0(
'### ', df$Category, a, '\n\n', df$HTML, '\n\n'
), ''
)
}
} else {
res = read_utf8(path)
if (recent > 0 && length(h <- grep('^# ', res)) >= 2)
res = res[h[1]:(h[1 + recent] - 1)]
# lower heading levels: # -> ##, ## -> ###, etc, and add attributes
for (i in 2:1) res = sub(sprintf('^(#{%d} .+)', i), paste0('#\\1', a), res)
# shorten headings
res = gsub('^## CHANGES IN ([^ ]+) VERSION( .+)', '## \\1\\2', res)
# link Github @username and #issue
if (length(u <- github_link(dirname(path)))) {
r1 = '([[:alnum:]-]+)'; r2 = '([0-9]+)'
res = gsub(paste0(' @', r1), ' [@\\1](https://github.com/\\1)', res)
res = gsub(paste0(' #', r2), sprintf(' [#\\1](%sissues/\\1)', u), res)
res = gsub(
sprintf(' %s/%s#%s', r1, r1, r2),
' [\\1/\\2#\\3](https://github.com/\\1/\\2/issues/\\3)', res
)
}
}
new_asis(res)
}
# classes for section headings in news, code, and manual
header_class = function(toc, number_sections, md = TRUE) {
a = c(if (!toc) 'unlisted', if (!number_sections) 'unnumbered')
if (md && length(a)) a = paste0('.', a)
a = one_string(a, ' ')
if (a != '') a = if (md) paste0(' {', a, '}') else paste0(' class="', a, '"')
a
}
#' @param pattern A regular expression to match filenames that should be treated
#' as source code.
#' @param link Whether to add links on the file paths of source code. By
#' default, if a GitHub repo link is detected from the `BugReports` field of
#' the package `DESCRIPTION`, GitHub links will be added to file paths. You
#' can also provide a string template containing the placeholder `%s` (which
#' will be filled out with the file paths via `sprintf()`), e.g.,
#' `https://github.com/yihui/litedown/blob/main/%s`.
#' @return `pkg_code()` returns the package source code under the `R/` and
#' `src/` directories.
#' @rdname pkg_desc
#' @export
pkg_code = function(
path = attr(detect_pkg(), 'path'), pattern = '[.](R|c|h|f|cpp)$', toc = TRUE,
number_sections = TRUE, link = TRUE
) {
if (!isTRUE(dir.exists(path))) {
if (missing(path)) message('Please run this function in the package source directory.')
return()
}
a = header_class(toc, number_sections)
if (isTRUE(link) && length(u <- github_link(path))) link = paste0(u, 'blob/HEAD/%s')
ds = c('R', 'src')
ds = ds[ds %in% list.dirs(path, FALSE, FALSE)]
flat = length(ds) == 1 # if only one dir exists, list files in a flat structure
code = in_dir(path, lapply(ds, function(d) {
fs = list.files(d, pattern, full.names = TRUE, recursive = TRUE)
if (length(fs) == 0) return()
x = uapply(fs, function(f) c(
sprintf('##%s %s%s', if (flat) '' else '#', if (is.character(link)) {
sprintf('[`%s`](%s)', f, sprintf(link, f))
} else sprintf('`%s`', f), a), '',
fenced_block(read_utf8(f), lineno_attr(file_ext(f), auto = FALSE)), ''
))
e = unique(file_ext(fs))
c(if (!flat) paste0('## ', paste0('`*.', e, '`', collapse = ' / '), a), '', x)
}))
new_asis(unlist(code))
}
# retrieve Github repo link from DESCRIPTION
github_link = function(path) {
u = read.dcf(file.path(path, 'DESCRIPTION'), 'BugReports')[1, 1]
grep_sub('^(https://github.com/[^/]+/[^/]+/).*', '\\1', u)
}
#' @return `pkg_citation()` returns the package citation in both the plain-text
#' and BibTeX formats.
#' @rdname pkg_desc
#' @export
pkg_citation = function(name = detect_pkg()) {
res = uapply(citation(name), function(x) {
x = tweak_citation(x)
unname(c(format(x, style = 'text'), fenced_block(toBibtex(x), 'latex')))
})
new_asis(res)
}
# dirty hack to add year if missing
tweak_citation = function(x) {
cls = class(x)
x = unclass(x)
if (is.null(x[[1]]$year)) x[[1]]$year = format(Sys.Date(), '%Y')
class(x) = cls
x
}
#' @param overview Whether to include the package overview page, i.e., the
#' `{name}-package.Rd` page.
#' @param examples A list of arguments to be passed to [xfun::record()] to run
#' examples each help page, e.g., `list(dev = 'svg', dev.args = list(height =
#' 6))`. If not a list (e.g., `FALSE`), examples will not be run.
#' @return `pkg_manual()` returns all manual pages of the package in HTML.
#' @rdname pkg_desc
#' @export
pkg_manual = function(
name = detect_pkg(), toc = TRUE, number_sections = TRUE, overview = TRUE,
examples = list()
) {
links = tools::findHTMLlinks('')
# resolve internal links (will assign IDs of the form sec:man-ID to all h2)
r = sprintf('^[.][.]/[.][.]/(%s)/html/(.+)[.]html$', name)
i = grep(r, links)
links[i] = paste0('#sec:man-', alnum_id(sub(r, '\\2', links[i])))
# resolve external links to specific man pages on https://rdrr.io
r = sprintf('^[.][.]/[.][.]/(%s)/html/', paste(xfun::base_pkgs(), collapse = '|'))
links = sub(r, 'https://rdrr.io/r/\\1/', links)
db = tools::Rd_db(name) # all Rd pages
intro = paste0(name, '-package.Rd') # the name-package entry (package overview)
entries = setdiff(names(db), intro)
entries = entries[!vapply(entries, function(i) {
kwd = uapply(db[[i]], function(x) if (attr(x, 'Rd_tag') == '\\keyword') x)
'internal' %in% kwd
}, logical(1))]
db = db[c(if (overview && intro %in% names(db)) intro, entries)]
al = lapply(db, Rd_aliases)
cl = header_class(toc, number_sections, FALSE)
r1 = '\\s*([^<]+?)\\s*' # inline math
r2 = sprintf(']*>\\s*%s\\s* ', r1) # display math
res = uapply(names(db), function(i) {
txt = ''
con = textConnection('txt', 'w', local = TRUE, encoding = 'UTF-8')
tryCatch(
tools::Rd2HTML(db[[i]], Links = links, out = con), error = function(e) {
warning("The Rd file '", i, "' appears to be malformed.", call. = FALSE)
stop(e)
}, finally = close(con))
# extract body, which may end at (R 4.4.x) or |