= Adding i18n/l10n to Trac plugins ^(Trac >= 0.12)^ = == Intro and Motivation == Are you a user of Trac and do your work with it, nothing more? Well, you may ignore this page and go on reading another subpage of [wiki:CookBook CookBook]. Professional coders/translators, please skip to the actual cookbook content in '[#Requiredworkflow Required workflow]', since there can't be any news for you before that section. If you want to learn about translation for a plugin, that as you know already provides one/several message catalog/s, the section '[#Dotranslatorswork Do translators work]' and following parts are for you. Ultimately, all plugin maintainers and developers in general, who are facing requests and are willing to take care for growing demand of their plugin to speak same (foreign) language(s) as Trac >= 0.12 should just read on. == i18n, l10n, ... help! == In short '''i18n''' stands for '''`i`'''`nternationalizatio`'''`n`''' (count 18 more chars between i and n) and is defined as software design for programs with translation support. '''`l`'''`ocalisatio`'''`n`''' that is abbreviated as '''l10n''' could be seen as a follow-up process providing data for one or more locales. It is taking care of feature differences between the original/default (that is English is most cases including Trac) and a given locale as well. Such features are i.e. sentence structure including punctuation and formatting of numbers, date/time strings, and currencies. Once you did some ground work at the source (i18n), most remaining is proper translation work (l10n) putting more or less effort in preserving the sense of the original while looking as native locale as possible.^[#a1 1]^ '''NLS''' (National Language Support or Native Language Support) is meant to be the sum of both. And there are more related terms that we could safely skip for now.^[#a1 1], [#a2 2]^ == Background and concept of i18n/l10n support for Trac plugins == It begun with adding Babel to Trac. Some plugin maintainers created their own translation module inside each plugin separately. Growing amount of code redundancy and possibility of error within imperfect copies and variants of a translation module all that was certainly not a desirable situation. And Trac core maintainers took responsibility with adding functions dedicated to i18n/l10n support for Trac plugins. The evolution of this functions has been documented in [comment:11:ticket:7497 ticket 7497]. The final implementation as mentioned there in [comment:12:ticket:7497 comment 12] was introduced to Trac trunk in changeset r7705 and finally done with changeset r7714. Now adding the needed i18n/l10n helper functions is done by importing a set of functions from `trac/util/translation.py` and providing proper configuration for an additional translation layer ('domain') inside the plugin code. On plugin initialization the dedicated translation domain is created as well and corresponding catalog files holding translated messages are loaded into it. Whenever a translatable text is encountered during runtime inside plugin's code, i18n/l10n helper functions will try to get the corresponding translation from the message catalog of plugin's domain and fall back silently to Trac's main message catalog, if needed. The message catalog selection is done according to the locale setting. Valid settings are a combination of language and country code, optionally extended further by the character encoding used, i.e. to read like ‘de_DE.UTF-8’. Trac uses UTF-8 encoding internally, so there is not much to tell about that. 'C' is a special locale code since it disables all translations and programs use English texts as required by POSIX standard.^[#a3 3]^ {{{#!comment Both searches take the locale setting as a second request argument. Valid settings are a combination of language and country code, often extended further by the character encoding used, i.e. to read like ‘de_DE.UTF-8’. The encoding is of special relevance for languages that had an older encoding per default that was not sufficient for all common chars used by native speakers of that language. 'C' is a special locale code since it disables all translations and programs use English texts as required by POSIX standard. Character encoding is highly dependent on the underlying operation system then.^[#a3 3]^ // I'm not sure to what the above refers. Which search? What locale argument? I don't think the character encoding plays any role here (we deal with unicode internally, catalogs themselves are always encoded in UTF-8) - cboos Thanks for the hint on non-relevance for Trac since this has that uniform encoding. So I hope the current text is better. This might be deleted than. }}} First matching translation will replace the default text what by gettext convention is the same as the msgid, that is used, if all attempts fail to find an exact matching translation. == Required workflow == A walk-through... === Prepare plugin code === ==== Import i18n/l10n helper programs ==== Pick a reasonably unique name for the domain, e.g. ** 'foo' ** This will be the basename for the various translation catalog files (e.g. `/locale/fr/LC_MESSAGES/foo.po` for the French catalog). At run-time, the translation functions (typically `_(...)`) have to know in which catalog the translation will be found. Specifying the 'foo' domain in every such call would be tedious, that's why there's a facility for creating partially instantiated domain-aware translation functions, `domain_functions`. This helper function should be called at module load time, like this: {{{#!python from trac.util.translation import domain_functions _, tag_, N_, add_domain = \ domain_functions('foo', ('_', 'tag_', 'N_', 'add_domain')) }}} The translation functions which can be bound to a domain are: - `'_'`: extract and translate - `'ngettext'`: extract and translate (singular, plural, num) - `'tgettext'`, `'tag_'`: same as `'_'` but for Markup - `'tngettext'`, `'tagn_'`: same as `'ngettext'` but for Markup - `'gettext'`: translate only, don't extract - `'N_'`: extract only, don't translate - `'add_domain'`: register the catalog file for the bound domain To inform Trac about where the plugin's message catalogs can be found, you'll have to call the `add_domain` function obtained via `domain_functions` as shown above. One place to do this is in the `__init__` function of your plugin's main component, like this: {{{#!python def __init__(self): import pkg_resources # here or with the other imports # bind the 'foo' catalog to the specified locale directory locale_dir = pkg_resources.resource_filename(__name__, 'locale') add_domain(self.env.path, locale_dir) }}} assuming that folder `locale` will reside in the same folder as the file containing the code above, referred to as `` (as observable inside the Python egg after packaging). The i18n/l10n helper programs are available inside the plugin now, but if the plugin code contains several python script files and you encounter text for translation in one of them too, you need to import the functions from the main script, say its name is `api.py`, there: {{{#!python from api import _, tag_, N_ }}} ==== Preset configuration for i18n/l10n helper programs ==== Add some lines to `setup.cfg` or, if it doesn't exist by now, create it with the following content: {{{#!ini [extract_messages] add_comments = TRANSLATOR: msgid_bugs_address = output_file = /locale/messages.pot # Note: specify as 'keywords' the functions for which the messages # should be extracted. This should match the list of functions # that you've listed in the `domain_functions()` call above. keywords = _ N_ tag_ # Other example: #keywords = _ ngettext:1,2 N_ tag_ width = 72 [init_catalog] input_file = /locale/messages.pot output_dir = /locale domain = foo [compile_catalog] directory = /locale domain = foo [update_catalog] input_file = /locale/messages.pot output_dir = /locale domain = foo }}} Replace `` as appropriate (i.e. the relative path to the folder containing the `locale` directory, for example `mytracplugin`). This will tell the i18n/l10n helper programs where to look for and store message catalog files. In the `extract_messages` section there is just one more lines you may like to change: `msgid_bugs_address`. To allow for direct feedback regarding your i18n work add a valid e-mail address or a mailing list dedicated to translation issues there. The `add_comments` line simply lists the tags in the comments surrounding the calls to the translation functions in the source code that have to be propagated to the catalogs (see [Babel:wiki:Documentation/0.9/setup.html#extract-messages extract_messages] in Babel's documentation). So you will want to leave that one untouched. ==== Mark text for extraction ==== In python scripts you'll have to wrap text with the translation function `_()` to get it handled by translation helper programs. {{{#!diff --- a//api.py +++ b//api.py @@ -1,1 +1,1 @@ - msg = 'This is a msg text.' + msg = _("This is a msg text.") }}} Note, that quoting of (i18n) message texts should really be done in double quotes. Single quotes are reserved for string constants (see commit note for r9751). This is a somewhat time consuming task depending on the size of the plugin's code. If you initially fail to find all desired texts you may notice this by missing them from the message catalog later and come back to this step again. If the plugin maintainer is unaware of your i18n work or unwilling to support it and he adds more message without the translation function call, remember that you have to do the wrapping of these new texts too. ==== Text extraction from Python code and Genshi templates ==== Message extraction for Genshi templates should be done auto-magically. However there is the markup `i18n:msg` available to ensure extraction even from less common tags. For a real-world example have a look at [changeset:9542/trunk/trac/ticket/templates/ Trac SVN changeset r9542] for marking previously undetected text in templates. See Genshi documentation on this topic, [http://genshi.edgewall.org/wiki/Documentation/0.6.x/i18n.html Internationalization and Localization]. ===== Extraction Babel only does extract from Python scripts by default. To extract messages from Genshi templates as well, you'll have to declare the needed extractors in [=#setup `setup.py`]: {{{#!diff diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -34,6 +35,21 @@ from setuptools import find_packages, setup +extra = {} +from trac.util.dist import get_l10n_cmdclass +cmdclass = get_l10n_cmdclass() +if cmdclass: # Yay, Babel is there, we've got something to do! + extra['cmdclass'] = cmdclass + extractors = [ + ('**.py', 'python', None), + ('**/templates/**.html', 'genshi', None), + ('**/templates/**.txt', 'genshi', { + 'template_class': 'genshi.template:TextTemplate' + }), + ] + extra['message_extractors'] = { + 'foo': extractors, + } +except ImportError: + pass + setup( name = 'foo', version = '0.12', @@ -53,6 +69,7 @@ 'templates/*.txt', 'htdocs/*.*', 'htdocs/css/*.*', + 'locale/*/LC_MESSAGES/*.mo', ] }, install_requires = [ @@ -96,4 +113,5 @@ ] }, test_suite = '.tests', + **extra ) }}} ==== Text extraction from Javascript code ==== #Javascript Adding support for translating the marked strings in the Javascript code is a bit more involved, but if you made it to this point, that shouldn't scare you away... We currently support only statically deployed Javascript files, which means they can't be translated like template files on the server, but that the translation has to happen dynamically on the client side. To this end, we want to send an additional `.js` file containing a dictionary of the messages that have to be translated, and only those. In order to clearly identify which strings have to be present in this dictionary, we'll extract the messages marked for translation (the usual `_(...)` ways) from the Javascript code into a dedicated catalog template, and from there, we'll create dedicated catalogs for each locale. In the end, the translations present in each compiled catalog will be extracted and placed into a `.js` file containing the messages dictionary and some setup code. The first change is to use `get_l10n_js_cmdclass` in lieu of `get_l10n_cmdclass`. The former adds a few more setup commands for extracting messages strings from Javascript `.js` files and `