Debian Codegraph @

R/citation.R

raw
1 #' Generate BibTeX bibliography databases for R packages
2 #'
3 #' Call [utils::citation()] and [utils::toBibtex()] to create bib entries for R
4 #' packages and write them in a file. It can facilitate the auto-generation of
5 #' bibliography databases for R packages, and it is easy to regenerate all the
6 #' citations after updating R packages.
7 #'
8 #' For a package, the keyword `R-pkgname` is used for its bib item, where
9 #' `pkgname` is the name of the package. Citation entries specified in the
10 #' \file{CITATION} file of the package are also included. The main purpose of
11 #' this function is to automate the generation of the package citation
12 #' information because it often changes (e.g., the author, year, package
13 #' version, and so on).
14 #'
15 #' There are at least two different uses for the URL in a reference list. You
16 #' might want to tell users where to go for more information. In that case, use
17 #' the default `packageURL = TRUE`, and the first URL listed in the
18 #' \file{DESCRIPTION} file will be used. Be careful: some authors don't put the
19 #' most relevant URL first. Alternatively, you might want to identify exactly
20 #' which version of the package was used in the document. If it was installed
21 #' from CRAN or some other repositories, the version number identifies it, and
22 #' `packageURL = FALSE` will use the repository URL (as used by
23 #' [utils::citation()]).
24 #' @param x Package names. Packages which are not installed are ignored.
25 #' @param file The (\file{.bib}) file to write. By default, or if `NULL`, output
26 #' is written to the R console.
27 #' @param tweak Whether to fix some known problems in the citations, especially
28 #' non-standard format of author names.
29 #' @param width Width of lines in bibliography entries. If `NULL`, lines will
30 #' not be wrapped.
31 #' @param prefix Prefix string for keys in BibTeX entries; by default, it is
32 #' `R-` unless `option('xfun.bib.prefix')` has been set to another string.
33 #' @param lib.loc A vector of path names of R libraries.
34 #' @param packageURL Use the `URL` field from the \file{DESCRIPTION} file. See
35 #' Details below.
36 #' @param date The way to include a date of the form `(retrieved YYYY-mm-dd)` in
37 #' the `note` field of bib entries. For `date = 'none'`, no date is included.
38 #' For `date = 'package'`, the [packageDate()] of the package is included. For
39 #' `date = 'today'`, [Sys.Date()] is included. Alternatively, you can provide
40 #' a date directly, e.g., `date = '2025-04-01'.`
41 #' @return A list containing the citations. Citations are also written to the
42 #' `file` as a side effect.
43 #' @note Some packages on CRAN do not have standard bib entries, which was once
44 #' reported by Michael Friendly at
45 #' \url{https://stat.ethz.ch/pipermail/r-devel/2010-November/058977.html}. I
46 #' find this a pain, and there are no easy solutions except contacting package
47 #' authors to modify their DESCRIPTION files. The argument `tweak` has
48 #' provided hacks to deal with known packages with non-standard bib entries;
49 #' `tweak = TRUE` is by no means intended to hide or modify the original
50 #' citation information. It is just due to the loose requirements on package
51 #' authors for the DESCRIPTION file. On one hand, I apologize if it really
52 #' mangles the information about certain packages; on the other, I strongly
53 #' recommend package authors to consider the `Authors@@R` field (see the
54 #' manual _Writing R Extensions_) to make it easier for other people to cite R
55 #' packages.
56 #' @export
57 #' @author Yihui Xie and Michael Friendly
58 #' @examples
59 #' pkg_bib(c('base', 'MASS', 'xfun'))
60 #' pkg_bib('cluster', prefix = 'R-pkg-') # a different prefix
61 #' pkg_bib('xfun', date = 'package')
62 pkg_bib = function(
63 x = .packages(), file = '', tweak = TRUE, width = NULL,
64 prefix = getOption('xfun.bib.prefix', 'R-'), lib.loc = NULL,
65 packageURL = TRUE, date = c('none', 'package', 'today')
66 ) {
67 system.file = function(...) base::system.file(..., lib.loc = lib.loc)
68 citation = function(...) utils::citation(..., lib.loc = lib.loc)
69 date = date[1]
70 x = x[nzchar(x)] # remove possible empty string
71 idx = mapply(system.file, package = x) == ''
72 if (any(idx)) {
73 warning('package(s) ', paste(x[idx], collapse = ', '), ' not found')
74 x = x[!idx]
75 }
76 # no need to write bib for packages in base R other than `base` itself
77 x = setdiff(x, setdiff(base_pkgs(), 'base'))
78 x = sort(x)
79 bib = sapply(x, function(pkg) {
80 meta = packageDescription(pkg, lib.loc)
81 # don't use the citation() URL if the package has provided its own URL
82 cite = citation(pkg, auto = if (is.null(meta$URL)) meta else {
83 if (packageURL) meta$Repository = meta$RemoteType = NULL
84 # use the first URL in case the package provided multiple URLs
85 meta$URL = sub('[, \t\n].*', '', meta$URL)
86 meta
87 })
88 if (tweak) {
89 # e.g. gpairs has "gpairs: " in the title
90 cite$title = gsub(sprintf('^(%s: )(\\1)', pkg), '\\1', cite$title)
91 }
92 date = format(switch(
93 date, none = '', package = packageDate(pkg, lib.loc), today = Sys.Date(), date
94 ))
95 if (!is.na(date) && date != '') cite$note = paste0(cite$note, ' (retrieved ', date, ')')
96 entry = toBibtex(cite)
97 entry[1] = sub('\\{,$', sprintf('{%s%s,', prefix, pkg), entry[1])
98 entry
99 }, simplify = FALSE)
100 if (tweak) {
101 # packages with non-standard author fields; use maintainer instead
102 pkgs = c(
103 "ash", "cat", "CircStats", "Fahrmeir", "flashClust", "leaps", "mapproj",
104 "maps", "pbivnorm", "quadprog", "R2WinBUGS", "Sleuth2", "sm"
105 )
106 for (i in intersect(pkgs, x)) {
107 message('tweaking ', i)
108 maintainer = packageDescription(i, lib.loc, fields = 'Maintainer')
109 bib[[i]]['author'] = sprintf(' author = {%s},', gsub('\\s+<.*>\\s*$', '', maintainer))
110 }
111 bib = lapply(bib, function(b) {
112 b['author'] = sub('Duncan Temple Lang', 'Duncan {Temple Lang}', b['author'])
113 # remove the ugly single quotes required by CRAN policy
114 b['title'] = gsub("(^|\\W)'([^']+)'(\\W|$)", '\\1\\2\\3', b['title'])
115 # keep the first URL if multiple are provided
116 if (!is.na(b['note'])) b['note'] = gsub(
117 '(^.*?https?://.*?),\\s+https?://.*?(},\\s*)$', '\\1\\2', b['note']
118 )
119 if (!('year' %in% names(b))) b['year'] = .this.year
120 b
121 })
122 }
123 # also read citation entries from the CITATION file if provided
124 bib2 = lapply(x, function(pkg) {
125 if (pkg == 'base') return()
126 if (system.file('CITATION', package = pkg) == '') return()
127 cites = citation(pkg, auto = FALSE)
128 cites = Filter(x = cites, function(cite) {
129 # exclude entries identical to citation(pkg, auto = TRUE)
130 !isTRUE(grepl('R package version', cite$note))
131 })
132 s = make_unique(unlist(lapply(cites, function(cite) {
133 if (is.null(cite$year)) format(Sys.Date(), '%Y') else cite$year
134 })))
135 mapply(cites, s, FUN = function(cite, suffix) {
136 # the entry is likely to be the same as citation(pkg, auto = TRUE)
137 if (isTRUE(grepl('R package version', cite$note))) return()
138 entry = toBibtex(cite)
139 entry[1] = sub('\\{,$', sprintf('{%s%s,', pkg, suffix), entry[1])
140 entry
141 }, SIMPLIFY = FALSE)
142 })
143 bib = c(bib, unlist(bib2, recursive = FALSE))
144 bib = lapply(bib, function(b) {
145 idx = which(names(b) == '')
146 if (!is.null(width)) b[-idx] = str_wrap(b[-idx], width, 2, 4)
147 lines = c(b[idx[1L]], b[-idx], b[idx[2L]], '')
148 if (tweak) {
149 # e.g. KernSmooth and spam has & in the title and the journal, respectively
150 lines = gsub('(?<!\\\\)&', '\\\\&', lines, perl = TRUE)
151 }
152 structure(lines, class = 'Bibtex')
153 })
154 if (!is.null(file) && length(x)) write_utf8(unlist(bib), file)
155 invisible(bib)
156 }
157
158 .this.year = sprintf(' year = {%s},', format(Sys.Date(), '%Y'))
159
160 # c(1, 1, 1, 2, 3, 3) -> c(1a, 1b, 1c, 2a, 3a, 3b)
161 make_unique = function(x) {
162 if (length(x) == 0) return(x)
163 x2 = make.unique(x)
164 if (all(i <- x2 == x)) return(x)
165 x2[i] = paste0(x2[i], '.0')
166 i = as.numeric(sub('.*[.]([0-9]+)$', '\\1', x2)) + 1
167 s = letters[i]
168 s = ifelse(is.na(s), i, s)
169 paste0(x, s)
170 }