Debian Codegraph @

R/language.R

raw
1 #' Language
2 #'
3 #' Temporarily change the language used for translations.
4 #'
5 #' @param lang A BCP47 language code like "en" (English), "fr" (French),
6 #' "fr_CA" (French Canadian). Formally, this is a lower case two letter
7 #' [ISO 639 country code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes),
8 #' optionally followed by "_" or "-" and an upper case two letter
9 #' [ISO 3166 region code](https://en.wikipedia.org/wiki/ISO_3166-2).
10 #' @inheritParams with_collate
11 #' @export
12 #' @examples
13 #' with_language("en", try(mean[[1]]))
14 #' with_language("fr", try(mean[[1]]))
15 #' with_language("es", try(mean[[1]]))
16 with_language <- function(lang, code) {
17 local_language(lang)
18 code
19 }
20
21 #' @export
22 #' @rdname with_language
23 local_language <- function(lang, .local_envir = parent.frame()) {
24 if (!is.character(lang) || length(lang) != 1) {
25 stop("`lang` must be a string")
26 }
27
28 # Reset a first time in case the cache was populated beforehand
29 reset_gettext_cache()
30
31 # Reset afterwards to clear any translation we might cache
32 defer(reset_gettext_cache(), envir = .local_envir)
33
34 # https://stackoverflow.com/questions/6152321
35 lang <- gsub("-", "_", lang, fixed = TRUE)
36
37 # Only warn if setting `LANGUAGE` to something other than `"C"` (#254)
38 if (lang != "C") {
39 if (!has_nls()) {
40 warning("Changing language has no effect when R installed without NLS")
41 }
42
43 # > Note: The variable LANGUAGE is ignored if the locale is set to ‘C’.
44 # > In other words, you have to first enable localization, by setting LANG
45 # > (or LC_ALL) to a value other than ‘C’, before you can use a language
46 # > priority list through the LANGUAGE variable.
47 # --- https://www.gnu.org/software/gettext/manual/html_node/The-LANGUAGE-variable.html
48
49 # `LC_ALL` has precedence over `LANG`. Check for the latter if the
50 # former is unset, otherwise check for the former.
51 if (Sys.getenv("LC_ALL", "") == "") {
52 # Causes too many failures because testthat sets `LANG` to "C"
53 # check_language_envvar("LANG")
54 } else {
55 check_language_envvar("LC_ALL")
56 }
57 }
58
59 local_envvar(LANGUAGE = lang, .local_envir = .local_envir)
60
61 invisible()
62 }
63
64 # Reset cache to avoid gettext() retrieving cached value from a previous
65 # language (idea from https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=931456)
66 # See https://github.com/r-lib/withr/issues/213.
67 reset_gettext_cache <- function() {
68 bindtextdomain("reset", local_tempdir())
69 }
70
71 check_language_envvar <- function(var) {
72 if (Sys.getenv(var) %in% c("C", "C.UTF-8")) {
73 warning(sprintf(
74 "Changing language has no effect when envvar %s='%s'",
75 var,
76 Sys.getenv(var)
77 ))
78 }
79 }
80
81 has_nls <- function() capabilities("NLS")[[1]]