Debian Codegraph @

R/locale.R

raw
1 #' Locale settings
2 #'
3 #' Temporarily change locale settings.
4 #'
5 #' Setting the `LC_ALL` category is currently not implemented.
6 #'
7 #' @template with
8 #' @param new,.new `[named character]`\cr New locale settings
9 #' @param ... Additional arguments with locale settings.
10 #' @inheritParams with_collate
11 #' @seealso [Sys.setlocale()]
12 #' @examples
13 #'
14 #' ## Change locale for time:
15 #' df <- data.frame(
16 #' stringsAsFactors = FALSE,
17 #' date = as.Date(c("2019-01-01", "2019-02-01")),
18 #' value = c(1, 2)
19 #' )
20 #' with_locale(new = c("LC_TIME" = "es_ES"), code = plot(df$date, df$value))
21 #' ## Compare with:
22 #' # plot(df$date, df$value)
23 #'
24 #' ## Month names:
25 #' with_locale(new = c("LC_TIME" = "en_GB"), format(ISOdate(2000, 1:12, 1), "%B"))
26 #' with_locale(new = c("LC_TIME" = "es_ES"), format(ISOdate(2000, 1:12, 1), "%B"))
27 #'
28 #' ## Change locale for currencies:
29 #' with_locale(new = c("LC_MONETARY" = "it_IT"), Sys.localeconv())
30 #' with_locale(new = c("LC_MONETARY" = "en_US"), Sys.localeconv())
31 #'
32 #' ## Ordering:
33 #' x <- c("bernard", "bérénice", "béatrice", "boris")
34 #' with_locale(c(LC_COLLATE = "fr_FR"), sort(x))
35 #' with_locale(c(LC_COLLATE = "C"), sort(x))
36 #'
37 #' @export
38 with_locale <- function(new, code) {
39 local_locale(new)
40 code
41 }
42
43 #' @rdname with_locale
44 #' @export
45 local_locale <- function(.new = list(), ..., .local_envir = parent.frame()) {
46 new <- list_combine(as.list(.new), list(...))
47 cats <- as_locale_cats(new)
48
49 # <https://github.com/r-lib/withr/issues/179>
50 # R supports setting LC_COLLATE to C via envvar. When that is the
51 # case, it takes precedence over the currently set locale. We need
52 # to set both the envvar and the locale for collate to fully take
53 # effect.
54 if ("LC_COLLATE" %in% names(cats)) {
55 collate <- cats["LC_COLLATE"]
56 local_envvar(collate, .local_envir = .local_envir)
57 }
58
59 old <- get_locale(cats)
60 defer(set_locale(old), envir = .local_envir)
61 set_locale(cats)
62
63 invisible(old)
64 }
65
66 set_locale <- function(cats) {
67 mapply(Sys.setlocale, names(cats), cats)
68 }
69 get_locale <- function(cats) {
70 vapply(names(cats), Sys.getlocale, character(1))
71 }
72
73 as_locale_cats <- function(cats) {
74 cats <- as_character(cats)
75 stopifnot(is.named(cats))
76
77 if ("LC_ALL" %in% names(cats)) {
78 stop("Setting LC_ALL category not implemented.", call. = FALSE)
79 }
80
81 cats
82 }