Debian Codegraph @

R/string.R

raw
1 #' Test if a character vector consists of blank strings
2 #'
3 #' Return a logical vector indicating if elements of a character vector are
4 #' blank (white spaces or empty strings).
5 #' @param x A character vector.
6 #' @return `TRUE` for blank elements, or `FALSE` otherwise.
7 #' @export
8 #' @examples
9 #' xfun::is_blank('')
10 #' xfun::is_blank('abc')
11 #' xfun::is_blank(c('', ' ', '\n\t'))
12 #' xfun::is_blank(c('', ' ', 'abc'))
13 is_blank = function(x) grepl('^\\s*$', x)
14
15 # remote blank elements from both ends
16 strip_blank = function(x) {
17 if (!(N <- length(x))) return(x)
18 r = rle(is_blank(x))
19 l = r$lengths; v = r$values; n = length(v)
20 i = c(if (v[1]) seq_len(l[1]), if (n > 1 && v[n]) N - seq_len(l[n]) + 1)
21 if (length(i)) x[-i] else x
22 }
23
24 #' Convert numbers to English words
25 #'
26 #' This can be helpful when writing reports with \pkg{knitr}/\pkg{rmarkdown} if
27 #' we want to print numbers as English words in the output. The function `n2w()`
28 #' is an alias of `numbers_to_words()`.
29 #' @param x A numeric vector. The absolute values should be less than `1e15`.
30 #' @param cap Whether to capitalize the first letter of the word. This can be
31 #' useful when the word is at the beginning of a sentence. Default is `FALSE`.
32 #' @param hyphen Whether to insert hyphen (-) when the number is between 21 and
33 #' 99 (except 30, 40, etc.).
34 #' @param and Whether to insert `and` between hundreds and tens, e.g., write 110
35 #' as \dQuote{one hundred and ten} if `TRUE` instead of \dQuote{one hundred
36 #' ten}.
37 #' @return A character vector.
38 #' @author Daijiang Li
39 #' @export
40 #' @examples library(xfun)
41 #' n2w(0, cap = TRUE)
42 #' n2w(0:121, and = TRUE)
43 #' n2w(1e6)
44 #' n2w(1e11+12345678)
45 #' n2w(-987654321)
46 #' n2w(1e15-1)
47 #' n2w(123.456)
48 #' n2w(123.45678901)
49 #' n2w(123.456789098765)
50 numbers_to_words = function(x, cap = FALSE, hyphen = TRUE, and = FALSE) {
51 if (!is.numeric(x)) stop('The input is not numeric.')
52 if (any(abs(x) >= 1e15)) stop('The absolute value must be less than 1e15.')
53 opts = options(scipen = 15, OutDec = '.') # avoid scientific notation
54 on.exit(options(opts), add = TRUE)
55
56 zero_to_19 = c(
57 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
58 'eleven', 'twelve', paste0(c('thir', 'four', 'fif', 'six', 'seven', 'eigh', 'nine'), 'teen')
59 )
60 names(zero_to_19) = as.character(0:19)
61 tens = c('twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety')
62 names(tens) = as.character(seq(20, 90, 10))
63 marks = c('', 'thousand,', 'million,', 'billion,', 'trillion,')
64
65 convert_1 = function(x_c) zero_to_19[x_c] # 0 - 9
66
67 # 10 - 99
68 convert_2 = function(x_c) {
69 x_cs = strsplit(x_c, split = '')[[1]]
70 if (x_cs[1] == 1) return(zero_to_19[x_c]) # 10 - 19
71 if (x_cs[2] == 0) return(tens[x_c]) # 20, 30, 40, ...
72 # 21, 22, etc.
73 paste(tens[as.integer(x_cs[1]) - 1], convert_1(x_cs[2]), sep = if (hyphen) '-' else ' ')
74 }
75
76 # 100 - 999
77 convert_3 = function(x_c) {
78 x_cs = strsplit(x_c, split = '')[[1]]
79 n_hundreds = paste(convert_1(x_cs[1]), 'hundred', sep = ' ')
80 out = if (x_cs[2] == '0') {
81 if (x_cs[3] == '0') return(n_hundreds) # x00
82 convert_1(x_cs[3]) # x0x
83 } else {
84 convert_2(paste(x_cs[2:3], collapse = '')) # xxx
85 }
86 paste(n_hundreds, out, sep = if (and) ' and ' else ' ')
87 }
88
89 convert_le3 = function(x_c) {
90 x_c = gsub('^0+', '', x_c) # avoid something like 000, 001, 010; but also remove 0
91 n = nchar(x_c)
92 if (n == 0) return('')
93 if (n == 1) return(convert_1(x_c))
94 if (n == 2) return(convert_2(x_c))
95 if (n == 3) return(convert_3(x_c))
96 }
97
98 convert_one = function(x) {
99 minus = if (x >= 0) '' else {
100 x = abs(x); 'minus '
101 }
102 if (x == 0) {
103 out = 'zero' # because convert_le3 removed all 0s
104 } else {
105 x_marks = strsplit(format(floor(x), big.mark = ','), split = ',')[[1]] # e.g. 123,456,789
106 out = vapply(x_marks, convert_le3, character(1)) # group by 3 digits
107 x_marks2 = marks[length(x_marks):1] # units?
108 x_marks2[which(out == '')] = '' # e.g. 4,000,123, 000, remove millions
109 out = paste(out, x_marks2, sep = ' ', collapse = ' ') # zip together
110 }
111 out = paste0(minus, out)
112 out = gsub('^ *|,? *$', '', out) # trim heading/trailing space
113 out = gsub(' {2,}', ' ', out) # remove multiple spaces
114 if (cap) out = sub('^([a-z])', '\\U\\1', out, perl = TRUE)
115 if (x - floor(x) > 0) {
116 frac = sub('^[0-9]+[.]', '', as.character(x))
117 frac = convert_1(strsplit(frac, '')[[1]])
118 out = paste(c(out, 'point', frac), collapse = ' ')
119 }
120 out
121 }
122
123 if (length(x) > 1) vapply(x, convert_one, character(1)) else convert_one(x)
124 }
125
126 #' @export
127 #' @rdname numbers_to_words
128 n2w = numbers_to_words
129
130 #' Join multiple words into a single string
131 #'
132 #' If `words` is of length 2, the first word and second word are joined by the
133 #' `and` string; if `and` is blank, `sep` is used. When the length is greater
134 #' than 2, `sep` is used to separate all words, and the `and` string is
135 #' prepended to the last word.
136 #' @param words A character vector.
137 #' @param sep Separator to be inserted between words.
138 #' @param and Character string to be prepended to the last word.
139 #' @param before,after A character string to be added before/after each word.
140 #' @param oxford_comma Whether to insert the separator between the last two
141 #' elements in the list.
142 #' @return A character string marked by [raw_string()].
143 #' @export
144 #' @examples join_words('a'); join_words(c('a', 'b'))
145 #' join_words(c('a', 'b', 'c'))
146 #' join_words(c('a', 'b', 'c'), sep = ' / ', and = '')
147 #' join_words(c('a', 'b', 'c'), and = '')
148 #' join_words(c('a', 'b', 'c'), before = '"', after = '"')
149 #' join_words(c('a', 'b', 'c'), before = '"', after = '"', oxford_comma = FALSE)
150 join_words = function(
151 words, sep = ', ', and = ' and ', before = '', after = before, oxford_comma = TRUE
152 ) {
153 n = length(words)
154 if (n > 0) {
155 words = paste0(before, words, after)
156 if (n == 2) {
157 words = paste(words, collapse = if (is_blank(and)) sep else and)
158 } else if (n > 2) {
159 if (oxford_comma && grepl('^ ', and) && grepl(' $', sep)) and = gsub('^ ', '', and)
160 words[n] = paste0(and, words[n])
161 # combine the last two words directly without the comma
162 if (!oxford_comma) {
163 words[n - 1] = paste0(words[n - 1:0], collapse = '')
164 words = words[-n]
165 }
166 words = paste(words, collapse = sep)
167 }
168 }
169 raw_string(words)
170 }
171
172 #' Evaluate an expression after forcing the decimal point to be a dot
173 #'
174 #' Sometimes it is necessary to use the dot character as the decimal separator.
175 #' In R, this could be affected by two settings: the global option
176 #' `options(OutDec)` and the `LC_NUMERIC` locale. This function sets the former
177 #' to `.` and the latter to `C` before evaluating an expression, such as
178 #' coercing a number to character.
179 #' @param x An expression.
180 #' @export
181 #' @return The value of `x`.
182 #' @examples
183 #' opts = options(OutDec = ',')
184 #' as.character(1.234) # using ',' as the decimal separator
185 #' print(1.234) # same
186 #' xfun::decimal_dot(as.character(1.234)) # using dot
187 #' xfun::decimal_dot(print(1.234)) # using dot
188 #' options(opts)
189 decimal_dot = function(x) {
190 opts = options(OutDec = '.'); on.exit(options(opts), add = TRUE)
191 lcn = Sys.getlocale('LC_NUMERIC')
192 if (lcn != 'C') {
193 Sys.setlocale('LC_NUMERIC', 'C')
194 on.exit(suppressWarnings(Sys.setlocale('LC_NUMERIC', lcn)), add = TRUE)
195 }
196 x
197 }
198
199 # create a URL query string from named parameters
200 query_params = function(..., .list = list()) {
201 x = if (missing(.list)) list(...) else .list
202 x = paste(names(x), x, sep = '=', collapse = '&')
203 if (x != '') paste0('?', x) else x
204 }
205
206 #' Wrap character vectors
207 #'
208 #' A wrapper function to make [strwrap()] return a character vector of the same
209 #' length as the input vector; each element of the output vector is a string
210 #' formed by concatenating wrapped strings by `\n`.
211 #' @param ... Arguments passed to [strwrap()].
212 #' @return A character vector.
213 #' @export
214 #' @examples
215 #' x = sample(c(letters, ' '), 200, TRUE, c(rep(.5/26, 26), .5))
216 #' x = rep(paste(x, collapse = ''), 2)
217 #' strwrap(x, width = 30)
218 #' xfun::str_wrap(x, width = 30) # same length as x
219 str_wrap = function(...) {
220 res = strwrap(..., simplify = FALSE)
221 unlist(lapply(res, one_string))
222 }
223
224 #' Split a character vector by line breaks
225 #'
226 #' Call `unlist(strsplit(x, '\n'))` on the character vector `x` and
227 #' make sure it works in a few edge cases: `split_lines('')` returns
228 #' `''` instead of `character(0)` (which is the returned value of
229 #' `strsplit('', '\n')`); `split_lines('a\n')` returns `c('a',
230 #' '')` instead of `c('a')` (which is the returned value of
231 #' `strsplit('a\n', '\n')`.
232 #' @param x A character vector.
233 #' @return All elements of the character vector are split by `'\n'` into
234 #' lines.
235 #' @export
236 #' @examples xfun::split_lines(c('a', 'b\nc'))
237 split_lines = function(x) {
238 if (length(grep('\n', x)) == 0L) return(x)
239 x = gsub('\n$', '\n\n', x)
240 x[x == ''] = '\n'
241 unlist(strsplit(x, '\r?\n'))
242 }
243
244 #' Split source lines into complete expressions
245 #'
246 #' Parse the lines of code one by one to find complete expressions in the code,
247 #' and put them in a list.
248 #' @param x A character vector of R source code.
249 #' @param merge_comments Whether to merge consecutive lines of comments as a
250 #' single expression to be combined with the next non-comment expression (if
251 #' any).
252 #' @param line_number Whether to store the line numbers of each expression in
253 #' the returned value.
254 #' @return A list of character vectors, and each vector contains a complete R
255 #' expression, with an attribute `lines` indicating the starting and ending
256 #' line numbers of the expression if the argument `line_number = TRUE`.
257 #' @export
258 #' @examples
259 #' code = c('# comment 1', '# comment 2', 'if (TRUE) {', '1 + 1', '}', 'print(1:5)')
260 #' xfun::split_source(code)
261 #' xfun::split_source(code, merge_comments = TRUE)
262 split_source = function(x, merge_comments = FALSE, line_number = FALSE) {
263 if ((n <- length(x)) < 1) return(list(x))
264 i1 = i2 = 1L
265 res = list()
266 add_source = function(x) {
267 res[[length(res) + 1]] <<- if (line_number) structure(x, lines = c(i1, i2)) else x
268 }
269 while (i2 <= n) {
270 piece = x[i1:i2]
271 if ((!merge_comments || (!all(grepl('^#', piece)) || i2 == n)) && valid_syntax(piece)) {
272 add_source(piece)
273 i1 = i2 + 1L # start from the next line
274 }
275 i2 = i2 + 1L
276 }
277 if (i1 <= n) parse(text = piece) # must be an error there
278 res
279 }
280
281 #' Check if the syntax of the code is valid
282 #'
283 #' Try to [parse()] the code and see if an error occurs.
284 #' @param code A character vector of R source code.
285 #' @param silent Whether to suppress the error message when the code is not
286 #' valid.
287 #' @return `TRUE` if the code could be parsed, otherwise `FALSE`.
288 #' @export
289 #' @examples xfun::valid_syntax('1+1')
290 #' xfun::valid_syntax('1+')
291 #' xfun::valid_syntax(c('if(T){1+1}', 'else {2+2}'), silent = FALSE)
292 valid_syntax = function(code, silent = TRUE) {
293 !inherits(suppressWarnings(try(parse_only(code), silent = silent)), 'try-error')
294 }
295
296 #' Bump version numbers
297 #'
298 #' Increase the last digit of version numbers, e.g., from `0.1` to
299 #' `0.2`, or `7.23.9` to `7.23.10`.
300 #' @param x A vector of version numbers (of the class `"numeric_version"`),
301 #' or values that can be coerced to version numbers via
302 #' `as.numeric_version()`.
303 #' @return A vector of new version numbers.
304 #' @export
305 #' @examples xfun::bump_version(c('0.1', '91.2.14'))
306 bump_version = function(x) {
307 x = as.numeric_version(x)
308 for (i in seq_along(x)) {
309 v = x[i]
310 n = length(unclass(v)[[1]])
311 v[[1, n]] = v[[1, n]] + 1 # bump the last digit
312 x[i] = v
313 }
314 x
315 }
316
317 # Given a CRAN release version (X.Y or X.Y.0), return list(next_ver, patch)
318 # where next_ver is the next NEWS header version and patch is the new dev version.
319 release_versions = function(ver) {
320 if (!grepl(r <- '^(\\d+\\.\\d+)(\\.0)?$', ver)) stop(
321 'Cannot parse version ', ver, ' from DESCRIPTION (expected X.Y or X.Y.0 format)'
322 )
323 v = as.numeric_version(ver)
324 v[[1, 2]] = v[[1, 2]] + 1
325 list(next_ver = as.character(v), patch = sub(r, '\\1.1', ver))
326 }
327
328 #' Fix pairs of characters in a file
329 #'
330 #' For example, the curly braces may be wrong (the opening and closing braces
331 #' are swapped for some reason).
332 #' @param x A character vector (by default, read from `file`).
333 #' @param file Path to a text file.
334 #' @param chars A vector of characters of length 2. By default, it is a pair of
335 #' curly double quotes.
336 #' @references <https://d.cosx.org/d/420794/5>
337 #' @noRd
338 #' @examples
339 #' files = list.files('.', '[.]R?md$', recursive = TRUE, full.names = TRUE)
340 #' for (f in files) {
341 #' pair_chars(file = f)
342 #' # curly single quotes
343 #' pair_chars(file = f, chars = c('\U2018', '\U2019'))
344 #' }
345 pair_chars = function(x = read_utf8(file), file, chars = c('\U201c', '\U201d')) {
346 if (length(chars) != 2) stop("'chars' must be of length 2 (i.e., a pair of characters)")
347 is_file = !missing(file)
348 r = paste(c('[', chars, ']'), collapse = '')
349 k = gregexpr(r, x)
350 m = regmatches(x, k)
351 for (i in seq_along(m)) {
352 n = length(m[[i]])
353 if (n %% 2 != 0) {
354 warning(
355 'The characters do not appear in pairs in the text (',
356 'line: ', i, if (is_file) c('; file: ', file), '):\n', x[i], '\n'
357 )
358 next
359 }
360 m[[i]] = rep(chars, length.out = n)
361 }
362 x2 = x
363 regmatches(x, k) = m
364 if (is_file) {
365 if (!identical(x, x2)) write_utf8(x, file)
366 invisible(x)
367 } else x
368 }
369
370 #' Generate ID strings
371 #'
372 #' Substitute certain (by default, non-alphanumeric) characters with dashes and
373 #' remove extra dashes at both ends to generate ID strings. This function is
374 #' intended for generating IDs for HTML elements, so HTML tags in the input text
375 #' will be removed first.
376 #' @param x A character vector.
377 #' @param exclude A (Perl) regular expression to detect characters to be
378 #' replaced by dashes. By default, non-alphanumeric characters are replaced.
379 #' @return A character vector of IDs.
380 #' @export
381 #' @examples
382 #' x = c('Hello world 123!', 'a &b*^##c 456')
383 #' xfun::alnum_id(x)
384 #' xfun::alnum_id(x, '[^[:alpha:]]+') # only keep alphabetical chars
385 #' # when text contains HTML tags
386 #' xfun::alnum_id('<h1>Hello <strong>world</strong>!')
387 alnum_id = function(x, exclude = '[^[:alnum:]]+') {
388 x = strip_html(x)
389 tolower(gsub('^-+|-+$', '', gsub(exclude, '-', x, perl = TRUE)))
390 }
391
392 #' Strip HTML tags
393 #'
394 #' Remove HTML tags and comments from text.
395 #' @param x A character vector.
396 #' @return A character vector with HTML tags and comments stripped off.
397 #' @export
398 #' @examples
399 #' xfun::strip_html('<a href="#">Hello <!-- comment -->world!</a>')
400 strip_html = function(x) {
401 x = gsub('<!--.*?-->', '', x)
402 x = gsub('<[^>]+>', '', x)
403 x
404 }
405
406 # no need to close these tags
407 .void_tags = c(
408 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input',
409 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'
410 )
411
412 .html_class2 = c(.html_class <- c('xfun_html', 'html'), 'xfun_raw_string')
413
414 #' Tools for HTML tags
415 #'
416 #' Given a tag name, generate an HTML tag with optional attributes and content.
417 #' [html_tag()] can be viewed as a simplified version of `htmltools::tags`,
418 #' [html_value()] adds classes on the value so that it will be treated as raw
419 #' HTML (not escaped by `html_tag()`), [html_escape()] escapes special
420 #' characters in HTML, and `html_view()` launches a browser or viewer to view
421 #' the HTML content.
422 #' @param .name The tag name.
423 #' @param .content The content between opening and closing tags. Ignored for
424 #' void tags such as `<img>`. Special characters such as `&`, `<`, and `>`
425 #' will be escaped unless the value was generated from [html_value()]. The
426 #' content can be either a character vector or a list. If it is a list, it may
427 #' contain both normal text and HTML content.
428 #' @param .attrs A named list of attributes.
429 #' @param ... For `html_tag()`, named arguments as an alternative way to provide
430 #' attributes. For `html_view()`, other arguments to be passed to [new_app()].
431 #' @return A character string.
432 #' @export
433 #' @examples
434 #' xfun::html_tag('a', '<R Project>', href = 'https://www.r-project.org', target = '_blank')
435 #' xfun::html_tag('br')
436 #' xfun::html_tag('a', xfun::html_tag('strong', 'R Project'), href = '#')
437 #' xfun::html_tag('a', list('<text>', xfun::html_tag('b', 'R Project')), href = '#')
438 html_tag = function(.name, .content = NULL, .attrs = NULL, ...) {
439 if (is.null(.attrs)) .attrs = list(...)
440 if (length(.attrs) && (is.null(nm <- names(.attrs)) || any(nm == '')))
441 stop('Tag attributes must be named values')
442 x1 = c('<', .name)
443 x2 = if (length(.attrs)) .mapply(function(a, v) {
444 if (is.null(v)) a else sprintf('%s="%s"', a, html_escape(v, TRUE))
445 }, list(nm, .attrs), NULL)
446 x2 = paste(unlist(x2), collapse = ' ')
447 x3 = if (.name %in% .void_tags) ' />' else {
448 c('>', one_string(html_content(.content)), '</', .name, '>')
449 }
450 x = c(x1, if (x2 != '') c(' ', x2), x3)
451 x = paste(x, collapse = '')
452 html_value(x)
453 }
454
455 # recursively resolve HTML content if it's a list containing both HTML and regular text
456 html_content = function(x) {
457 if (is.list(x)) unlist(lapply(x, html_content)) else {
458 if (length(x) && !inherits(x, .html_class)) x = html_escape(x)
459 x
460 }
461 }
462
463 #' @param x A character vector to be treated as raw HTML content for
464 #' `html_value()`, escaped for `html_escape()`, and viewed for `html_view()`.
465 #' @rdname html_tag
466 #' @export
467 html_value = function(x) structure(x, class = .html_class2, lang = '.html')
468
469 #' @param attr Whether to escape `"`, `\r`, and `\n` (which should be escaped
470 #' for tag attributes).
471 #' @param name The app name passed to [new_app()].
472 #' @rdname html_tag
473 #' @export
474 #' @examples
475 #' xfun::html_escape('" quotes " & brackets < >')
476 #' xfun::html_escape('" & < > \r \n', attr = TRUE)
477 html_escape = function(x, attr = FALSE) {
478 x = gsubf('&', '&amp;', x)
479 x = gsubf('<', '&lt;', x)
480 x = gsubf('>', '&gt;', x)
481 # for attributes, we still need to escape more characters
482 if (attr) {
483 x = gsubf('"', '&quot;', x)
484 x = gsubf('\r', '&#13;', x)
485 x = gsubf('\n', '&#10;', x)
486 }
487 x
488 }
489
490 #' @rdname html_tag
491 #' @export
492 html_view = function(x, name = 'xfun-html', ...) {
493 new_app(name, function(path, ...) {
494 if (dir_exists(path)) list(payload = if (path == '.') one_string(x) else path) else {
495 list(file = normalizePath(path), `content-type` = mime_type(path))
496 }
497 }, ...)
498 }
499
500 one_string = function(x, ...) paste(x, ..., collapse = '\n')
501
502 # en/decrypt a string via a character map (old and new must be 16 unique hex chars)
503 .crypt = function(x, old, new) {
504 x2 = chartr(old, new, as.character(charToRaw(x)))
505 rawToChar(as.raw(strtoi(x2, 16L)))
506 }
507 encrypt = function(x, key) .crypt(x, '0123456789abcdef', key)
508 decrypt = function(x, key) .crypt(x, key, '0123456789abcdef')