10

Is it possible to use something like gettext to translate an R script. If so, how? If not, what other options I have?

evgeniuz
  • 2,599
  • 5
  • 30
  • 36
  • What do you mean by "translate"? – Subs May 26 '12 at 09:24
  • I mean I have strings in it, written in English. I need to mark them somehow, extract to separate file, translate them to Russian. And by running script with one parameter — it would display English messages, and with other — Russian ones. Just as gettext works :) – evgeniuz May 26 '12 at 09:30
  • @Andrie isn't gettext meant for packages only? Isn't the domain suggested in the answer below invalid? Does that really work for any gettext in a script? I mean I do get the .pot file but can't get no link to the .mo file then... – Matt Bannert Oct 18 '12 at 17:58

1 Answers1

12

You can use base::gettext/ngettext, base::bindtextdomain and tools::xgettext2pot functions.
For example:

myFunction <- function()
{  
  bindtextdomain("R-myProgram","/my/translation/dir")
  gettext("Hello",domain="R-myProgram")
}

Then, supposing this function is inside a file whose path is "/my/dir/R/myfile.R" use: tools::xgettext2pot("/my/dir", "/my/translation/dir/pot/R-myProgram.pot") then use msginit, msgfmt, etc. to create a .mo file /my/translation/dir/fr/LC_MESSAGES/R-myProgram.mo. myFunction() should now print "Bonjour" instead of "Hello" if your locale is French.

A couple of other points :

  • It seems like xgettext2pot assumes your project is a standard R package and looks only for *.R files inside the R/ subdirectory.
  • The domain argument seems to be by default the namespace of the function calling gettext()
  • stop(), message(), warning() and packupStartupMessage() are also detected by xgettext2pot. There is also a gettextf() function available as a sprintf-like variant of gettext().
  • Since the standard xgettext utility doesn't seem to support R syntax, and since one has to use tools::xgettext2pot, a couple of things will miss from the standard approach, such as message contexts (pgettext()), flags indicating printf-like strings and the possibility to write in-code comments for the translators (extracted by xgettext -c) without modifying the .pot file by hand.
ehmicky
  • 1,915
  • 4
  • 20
  • 29
  • If I set the my locale with `sys.getlocale("LC_All","fr")` to French I just dont get the translated `msstr` back. still all hello. Why is that? – Matt Bannert Oct 18 '12 at 14:15
  • Looks promising, thanks! I referenced this comment in the following request to support gettext in shiny.18n: https://github.com/Appsilon/shiny.i18n/issues/15 – Motin Sep 02 '18 at 11:28
  • no luck to translate if using Sys.setlocale(category = "LC_ALL", locale = "fr_FR.utf8") before the call to myFunction()7 – cmbarbu Jul 01 '20 at 06:26