Debian Codegraph @

docs/messages.rst

raw
1 .. -*- mode: rst; encoding: utf-8 -*-
2
3 .. _messages:
4
5 =============================
6 Working with Message Catalogs
7 =============================
8
9
10 Introduction
11 ============
12
13 The ``gettext`` translation system enables you to mark any strings used in your
14 application as subject to localization, by wrapping them in functions such as
15 ``gettext(str)`` and ``ngettext(singular, plural, num)``. For brevity, the
16 ``gettext`` function is often aliased to ``_(str)``, so you can write:
17
18 .. code-block:: python
19
20 print(_("Hello"))
21
22 instead of just:
23
24 .. code-block:: python
25
26 print("Hello")
27
28 to make the string "Hello" localizable.
29
30 Message catalogs are collections of translations for such localizable messages
31 used in an application. They are commonly stored in PO (Portable Object) and MO
32 (Machine Object) files, the formats of which are defined by the GNU `gettext`_
33 tools and the GNU `translation project`_.
34
35 .. _`gettext`: https://www.gnu.org/software/gettext/
36 .. _`translation project`: https://sourceforge.net/projects/translation/
37
38 The general procedure for building message catalogs looks something like this:
39
40 * use a tool (such as ``xgettext``) to extract localizable strings from the
41 code base and write them to a POT (PO Template) file.
42 * make a copy of the POT file for a specific locale (for example, "en_US")
43 and start translating the messages
44 * use a tool such as ``msgfmt`` to compile the locale PO file into a binary
45 MO file
46 * later, when code changes make it necessary to update the translations, you
47 regenerate the POT file and merge the changes into the various
48 locale-specific PO files, for example using ``msgmerge``
49
50 Python provides the :mod:`gettext` module as part of the standard library,
51 which enables applications to work with appropriately generated MO files.
52
53 As ``gettext`` provides a solid and well supported foundation for translating
54 application messages, Babel does not reinvent the wheel, but rather reuses this
55 infrastructure, and makes it easier to build message catalogs for Python
56 applications.
57
58
59 Message Extraction
60 ==================
61
62 Babel provides functionality similar to that of the ``xgettext`` program,
63 except that only extraction from Python source files is built-in, while support
64 for other file formats can be added using a simple extension mechanism.
65
66 Unlike ``xgettext``, which is usually invoked once for every file, the routines
67 for message extraction in Babel operate on directories. While the per-file
68 approach of ``xgettext`` works nicely with projects using a ``Makefile``,
69 Python projects rarely use ``make``, and thus a different mechanism is needed
70 for extracting messages from the heterogeneous collection of source files that
71 many Python projects are composed of.
72
73 When message extraction is based on directories instead of individual files,
74 there needs to be a way to configure which files should be treated in which
75 manner. For example, while many projects may contain ``.html`` files, some of
76 those files may be static HTML files that don't contain localizable message,
77 while others may be `Jinja2`_ templates, and still others may contain `Genshi`_
78 markup templates. Some projects may even mix HTML files for different templates
79 languages (for whatever reason). Therefore the way in which messages are
80 extracted from source files can not only depend on the file extension, but
81 needs to be controllable in a precise manner.
82
83 .. _`Jinja2`: https://jinja.pocoo.org/
84 .. _`Genshi`: https://genshi.edgewall.org/
85
86 Babel accepts a configuration file to specify this mapping of files to
87 extraction methods, which is described below.
88
89
90 .. _`frontends`:
91
92 ----------
93 Front-Ends
94 ----------
95
96 Babel provides two different front-ends to access its functionality for working
97 with message catalogs:
98
99 * A :ref:`cmdline`, and
100 * :ref:`setup-integration`
101
102 Which one you choose depends on the nature of your project. For most modern
103 Python projects, the distutils/setuptools integration is probably more
104 convenient.
105
106
107 .. _`mapping`:
108
109 -------------------------------------------
110 Extraction Method Mapping and Configuration
111 -------------------------------------------
112
113 The mapping of extraction methods to files in Babel is done via a configuration
114 file. This file maps extended glob patterns to the names of the extraction
115 methods, and can also set various options for each pattern (which options are
116 available depends on the specific extraction method).
117
118 For example, the following configuration adds extraction of messages from both
119 Genshi markup templates and text templates:
120
121 .. code-block:: ini
122
123 # Extraction from Python source files
124
125 [python: **.py]
126
127 # Extraction from Genshi HTML and text templates
128
129 [genshi: **/templates/**.html]
130 ignore_tags = script,style
131 include_attrs = alt title summary
132
133 [genshi: **/templates/**.txt]
134 template_class = genshi.template:TextTemplate
135 encoding = ISO-8819-15
136
137 # Extraction from JavaScript files
138
139 [javascript: **.js]
140 extract_messages = $._, jQuery._
141
142 The extended glob patterns used in this configuration are similar to the glob
143 patterns provided by most shells. A single asterisk (``*``) is a wildcard for
144 any number of characters (except for the pathname component separator "/"),
145 while a question mark (``?``) only matches a single character. In addition,
146 two subsequent asterisk characters (``**``) can be used to make the wildcard
147 match any directory level, so the pattern ``**.txt`` matches any file with the
148 extension ``.txt`` in any directory.
149
150 Babel supports two configuration file formats: INI and TOML.
151
152 INI Configuration Format
153 ^^^^^^^^^^^^^^^^^^^^^^^^
154
155 The INI configuration file syntax is based on the format commonly found in ``.INI``
156 files on Windows systems, and as supported by the ``ConfigParser`` module in
157 the Python standard library. Section names (the strings enclosed in square
158 brackets) specify both the name of the extraction method, and the extended glob
159 pattern to specify the files that this extraction method should be used for,
160 separated by a colon. The options in the sections are passed to the extraction
161 method. Which options are available is specific to the extraction method used.
162
163 Lines that start with a ``#`` or ``;`` character are ignored and can be used
164 for comments. Empty lines are ignored, too.
165
166 TOML Configuration Format
167 ^^^^^^^^^^^^^^^^^^^^^^^^^^
168
169 Babel also supports TOML format for configuration files, when the ``tomllib``
170 module is available (Python 3.11+), or when the ``tomli`` package is installed
171 (for Python versions prior to 3.11).
172
173 TOML provides a more structured format and is particularly useful when combined
174 with ``pyproject.toml``.
175
176 The same configuration examples shown above can be written in TOML format:
177
178 .. code-block:: toml
179
180 # Extraction from Python source files
181 [[mappings]]
182 method = "python"
183 pattern = "**.py"
184
185 # Extraction from Genshi HTML and text templates
186 [[mappings]]
187 method = "genshi"
188 pattern = "**/templates/**.html"
189 ignore_tags = "script,style"
190 include_attrs = "alt title summary"
191
192 [[mappings]]
193 method = "genshi"
194 pattern = "**/templates/**.txt"
195 template_class = "genshi.template:TextTemplate"
196 encoding = "ISO-8819-15"
197
198 # Extraction from JavaScript files
199 [[mappings]]
200 method = "javascript"
201 pattern = "**.js"
202 extract_messages = "$._, jQuery._"
203
204 In TOML format, each ``[[mappings]]`` section defines a mapping. The ``method``
205 and ``pattern`` fields are required. The ``pattern`` field can be a string or
206 an array of strings to match multiple patterns with the same configuration.
207
208 If you're using ``pyproject.toml``, nest the configuration under ``[tool.babel]``:
209
210 .. code-block:: toml
211
212 [tool.babel]
213 [[tool.babel.mappings]]
214 method = "python"
215 pattern = "**.py"
216
217 You can reference custom extractors in both formats. In TOML:
218
219 .. code-block:: toml
220
221 [extractors]
222 custom = "mypackage.module:extract_custom"
223
224 [[mappings]]
225 method = "custom"
226 pattern = "**.ctm"
227 some_option = "foo"
228
229 Common Options
230 ^^^^^^^^^^^^^^
231
232 In addition to extractor-specific options, the following options can be specified
233 in any mapping section and will be merged with global settings:
234
235 ``keywords``
236 A list of keywords (function names) to extract messages from.
237 This uses the same syntax as the ``--keyword`` command-line option.
238 Keywords specified here are added to (not replacing) the default keywords or
239 those specified via command-line.
240
241 In INI format, whitespace-separated: ``keywords = _ gettext ngettext:1,2 pgettext:1c,2``
242
243 In TOML format, use either a whitespace-separated string or an array:
244 ``keywords = "_ gettext ngettext:1,2"`` or
245 ``keywords = ["_", "gettext", "ngettext:1,2"]``
246
247 ``add_comments``
248 A list of comment tag prefixes to extract and include in the
249 output. This uses the same syntax as the ``--add-comments`` command-line option.
250 Comment tags specified here are added to those specified via command-line.
251
252 In INI format, whitespace-separated: ``add_comments = TRANSLATOR: NOTE:``
253
254 In TOML format, use either a string or an array:
255 ``add_comments = "TRANSLATOR NOTE:"`` (parsed as a single string!) or
256 ``add_comments = ["TRANSLATOR:", "NOTE:"]``
257
258 **Example in INI format:**
259
260 .. code-block:: ini
261
262 [python: **.py]
263 keywords = _ _l _n:1,2
264 add_comments = TRANSLATOR:
265
266 **Example in TOML format:**
267
268 .. code-block:: toml
269
270 [[mappings]]
271 method = "python"
272 pattern = "**.py"
273 keywords = ["_", "_l", "_n:1,2"]
274 add_comments = ["TRANSLATOR:"]
275
276 .. note:: if you're performing message extraction using the command Babel
277 provides for integration into ``setup.py`` scripts, you can also
278 provide this configuration in a different way, namely as a keyword
279 argument to the ``setup()`` function. See
280 :ref:`setup-integration` for more information.
281
282
283 Default Extraction Methods
284 --------------------------
285
286 Babel comes with a few builtin extractors: ``python`` (which extracts
287 messages from Python source files), ``javascript``, and ``ignore`` (which
288 extracts nothing).
289
290 The ``python`` extractor is by default mapped to the glob pattern ``**.py``,
291 meaning it'll be applied to all files with the ``.py`` extension in any
292 directory. If you specify your own mapping configuration, this default mapping
293 is discarded, so you need to explicitly add it to your mapping (as shown in the
294 example above.)
295
296
297 .. _`referencing extraction methods`:
298
299 Referencing Extraction Methods
300 ------------------------------
301
302 Generally, packages publish Babel extractors as Python entry points,
303 and so you can use a short name such as “genshi” to refer to them.
304
305 If the package implementing an extraction method has not been installed in a
306 way that has kept its entry point mapping intact, you need to map the short
307 names to fully qualified function names in an extract section in the mapping
308 configuration. For example:
309
310 .. code-block:: ini
311
312 # Some custom extraction method
313
314 [extractors]
315 custom = mypackage.module:extract_custom
316
317 [custom: **.ctm]
318 some_option = foo
319
320 Note that the builtin extraction methods ``python`` and ``ignore`` are always
321 available, and you should never need to explicitly define them in the
322 ``[extractors]`` section.
323
324
325 --------------------------
326 Writing Extraction Methods
327 --------------------------
328
329 Adding new methods for extracting localizable methods is easy. First, you'll
330 need to implement a function that complies with the following interface:
331
332 .. code-block:: python
333
334 def extract_xxx(fileobj, keywords, comment_tags, options):
335 """Extract messages from XXX files.
336
337 :param fileobj: the file-like object the messages should be extracted
338 from
339 :param keywords: a list of keywords (i.e. function names) that should
340 be recognized as translation functions
341 :param comment_tags: a list of translator tags to search for and
342 include in the results
343 :param options: a dictionary of additional options (optional)
344 :return: an iterator over ``(lineno, funcname, message, comments)``
345 tuples
346 :rtype: ``iterator``
347 """
348
349 .. note:: Any strings in the tuples produced by this function must be either
350 ``unicode`` objects, or ``str`` objects using plain ASCII characters.
351 That means that if sources contain strings using other encodings, it
352 is the job of the extractor implementation to do the decoding to
353 ``unicode`` objects.
354
355 Next, you should register that function as an `entry point`_.
356 If using ``setup.py``, add something like the following to your ``setup.py``
357 script:
358
359 .. code-block:: python
360
361 def setup(...
362
363 entry_points = """
364 [babel.extractors]
365 xxx = your.package:extract_xxx
366 """,
367
368 If using a ``pyproject.toml`` file, add something like the following:
369
370 .. code-block:: toml
371
372 [project.entry-points."babel.extractors"]
373 xxx = "your.package:extract_xxx"
374
375 That is, add your extraction method to the entry point group
376 ``babel.extractors``, where the name of the entry point is the name that people
377 will use to reference the extraction method, and the value being the module and
378 the name of the function (separated by a colon) implementing the actual
379 extraction.
380
381 .. note:: As shown in `Referencing Extraction Methods`_, declaring an entry
382 point is not strictly required, as users can still reference the
383 extraction function directly. But whenever possible, the entry point
384 should be declared to make configuration more convenient.
385
386 .. _`setuptools`: https://setuptools.pypa.io/en/latest/setuptools.html
387
388
389 -------------------
390 Translator Comments
391 -------------------
392
393 First of all what are comments tags. Comments tags are excerpts of text to
394 search for in comments, only comments, right before the python :mod:`gettext`
395 calls, as shown on the following example:
396
397 .. code-block:: python
398
399 # NOTE: This is a comment about `Foo Bar`
400 _('Foo Bar')
401
402 The comments tag for the above example would be ``NOTE:``, and the translator
403 comment for that tag would be ``This is a comment about `Foo Bar```.
404
405 The resulting output in the catalog template would be something like::
406
407 #. This is a comment about `Foo Bar`
408 #: main.py:2
409 msgid "Foo Bar"
410 msgstr ""
411
412 Now, you might ask, why would I need that?
413
414 Consider this simple case; you have a menu item called “manual”. You know what
415 it means, but when the translator sees this they will wonder did you mean:
416
417 1. a document or help manual, or
418 2. a manual process?
419
420 This is the simplest case where a translation comment such as
421 “The installation manual” helps to clarify the situation and makes a translator
422 more productive.
423
424 .. note:: Whether translator comments can be extracted depends on the extraction
425 method in use. The Python extractor provided by Babel does implement
426 this feature, but others may not.