blob: 77b67aef4204c909931d6eb1f75854324ef796a9 [file] [log] [blame]
Barry Warsaw95be23d2000-08-25 19:13:37 +00001"""Internationalization and localization support.
2
3This module provides internationalization (I18N) and localization (L10N)
4support for your Python programs by providing an interface to the GNU gettext
5message catalog library.
6
7I18N refers to the operation by which a program is made aware of multiple
8languages. L10N refers to the adaptation of your program, once
Barry Warsaw33d8d702000-08-30 03:29:58 +00009internationalized, to the local language and cultural habits.
Barry Warsaw95be23d2000-08-25 19:13:37 +000010
11"""
12
Barry Warsawfa488ec2000-08-25 20:26:43 +000013# This module represents the integration of work, contributions, feedback, and
14# suggestions from the following people:
Barry Warsaw95be23d2000-08-25 19:13:37 +000015#
16# Martin von Loewis, who wrote the initial implementation of the underlying
17# C-based libintlmodule (later renamed _gettext), along with a skeletal
18# gettext.py implementation.
19#
20# Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule,
21# which also included a pure-Python implementation to read .mo files if
22# intlmodule wasn't available.
23#
24# James Henstridge, who also wrote a gettext.py module, which has some
25# interesting, but currently unsupported experimental features: the notion of
26# a Catalog class and instances, and the ability to add to a catalog file via
27# a Python API.
28#
29# Barry Warsaw integrated these modules, wrote the .install() API and code,
30# and conformed all C and Python code to Python's coding standards.
Barry Warsaw33d8d702000-08-30 03:29:58 +000031#
32# Francois Pinard and Marc-Andre Lemburg also contributed valuably to this
33# module.
34#
Martin v. Löwisa57dccd2003-03-10 16:01:43 +000035# J. David Ibanez implemented plural forms. Bruno Haible fixed some bugs.
Martin v. Löwisd8996052002-11-21 21:45:32 +000036#
Barry Warsaw33d8d702000-08-30 03:29:58 +000037# TODO:
38# - Lazy loading of .mo files. Currently the entire catalog is loaded into
39# memory, but that's probably bad for large translated programs. Instead,
40# the lexical sort of original strings in GNU .mo files should be exploited
41# to do binary searches and lazy initializations. Or you might want to use
42# the undocumented double-hash algorithm for .mo files with hash tables, but
43# you'll need to study the GNU gettext code to do this.
44#
45# - Support Solaris .mo file formats. Unfortunately, we've been unable to
46# find this format documented anywhere.
Barry Warsaw95be23d2000-08-25 19:13:37 +000047
Martin v. Löwisd8996052002-11-21 21:45:32 +000048
Victor Stinnerd6debb22017-03-27 16:05:26 +020049import os
50import re
Victor Stinnerd6debb22017-03-27 16:05:26 +020051import sys
Barry Warsaw95be23d2000-08-25 19:13:37 +000052
Martin v. Löwisd8996052002-11-21 21:45:32 +000053
Barry Warsawa1ce93f2003-04-11 18:36:43 +000054__all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
55 'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
Andrew Kuchling770b08e2015-04-13 09:58:36 -040056 'bind_textdomain_codeset',
57 'dgettext', 'dngettext', 'gettext', 'lgettext', 'ldgettext',
58 'ldngettext', 'lngettext', 'ngettext',
Cheryl Sabella637a33b2018-11-07 09:12:20 -050059 'pgettext', 'dpgettext', 'npgettext', 'dnpgettext',
Barry Warsawa1ce93f2003-04-11 18:36:43 +000060 ]
Skip Montanaro2dd42762001-01-23 15:35:05 +000061
Vinay Sajip7ded1f02012-05-26 03:45:29 +010062_default_localedir = os.path.join(sys.base_prefix, 'share', 'locale')
Barry Warsaw95be23d2000-08-25 19:13:37 +000063
Serhiy Storchaka07bcf052016-11-08 21:17:46 +020064# Expression parsing for plural form selection.
65#
66# The gettext library supports a small subset of C syntax. The only
67# incompatible difference is that integer literals starting with zero are
68# decimal.
69#
70# https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms
71# http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y
72
73_token_pattern = re.compile(r"""
74 (?P<WHITESPACES>[ \t]+) | # spaces and horizontal tabs
75 (?P<NUMBER>[0-9]+\b) | # decimal integer
76 (?P<NAME>n\b) | # only n is allowed
77 (?P<PARENTHESIS>[()]) |
78 (?P<OPERATOR>[-*/%+?:]|[><!]=?|==|&&|\|\|) | # !, *, /, %, +, -, <, >,
79 # <=, >=, ==, !=, &&, ||,
80 # ? :
81 # unary and bitwise ops
82 # not allowed
83 (?P<INVALID>\w+|.) # invalid token
84 """, re.VERBOSE|re.DOTALL)
85
86def _tokenize(plural):
87 for mo in re.finditer(_token_pattern, plural):
88 kind = mo.lastgroup
89 if kind == 'WHITESPACES':
90 continue
91 value = mo.group(kind)
92 if kind == 'INVALID':
93 raise ValueError('invalid token in plural form: %s' % value)
94 yield value
95 yield ''
96
97def _error(value):
98 if value:
99 return ValueError('unexpected token in plural form: %s' % value)
100 else:
101 return ValueError('unexpected end of plural form')
102
103_binary_ops = (
104 ('||',),
105 ('&&',),
106 ('==', '!='),
107 ('<', '>', '<=', '>='),
108 ('+', '-'),
109 ('*', '/', '%'),
110)
111_binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops}
112_c2py_ops = {'||': 'or', '&&': 'and', '/': '//'}
113
114def _parse(tokens, priority=-1):
115 result = ''
116 nexttok = next(tokens)
117 while nexttok == '!':
118 result += 'not '
119 nexttok = next(tokens)
120
121 if nexttok == '(':
122 sub, nexttok = _parse(tokens)
123 result = '%s(%s)' % (result, sub)
124 if nexttok != ')':
125 raise ValueError('unbalanced parenthesis in plural form')
126 elif nexttok == 'n':
127 result = '%s%s' % (result, nexttok)
128 else:
129 try:
130 value = int(nexttok, 10)
131 except ValueError:
132 raise _error(nexttok) from None
133 result = '%s%d' % (result, value)
134 nexttok = next(tokens)
135
136 j = 100
137 while nexttok in _binary_ops:
138 i = _binary_ops[nexttok]
139 if i < priority:
140 break
141 # Break chained comparisons
142 if i in (3, 4) and j in (3, 4): # '==', '!=', '<', '>', '<=', '>='
143 result = '(%s)' % result
144 # Replace some C operators by their Python equivalents
145 op = _c2py_ops.get(nexttok, nexttok)
146 right, nexttok = _parse(tokens, i + 1)
147 result = '%s %s %s' % (result, op, right)
148 j = i
149 if j == priority == 4: # '<', '>', '<=', '>='
150 result = '(%s)' % result
151
152 if nexttok == '?' and priority <= 0:
153 if_true, nexttok = _parse(tokens, 0)
154 if nexttok != ':':
155 raise _error(nexttok)
156 if_false, nexttok = _parse(tokens)
157 result = '%s if %s else %s' % (if_true, result, if_false)
158 if priority == 0:
159 result = '(%s)' % result
160
161 return result, nexttok
Barry Warsaw95be23d2000-08-25 19:13:37 +0000162
Serhiy Storchaka60ac9892016-11-14 19:22:12 +0200163def _as_int(n):
164 try:
165 i = round(n)
166 except TypeError:
167 raise TypeError('Plural value must be an integer, got %s' %
168 (n.__class__.__name__,)) from None
Serhiy Storchakaf6595982017-03-12 13:15:01 +0200169 import warnings
170 warnings.warn('Plural value must be an integer, got %s' %
171 (n.__class__.__name__,),
172 DeprecationWarning, 4)
Serhiy Storchaka60ac9892016-11-14 19:22:12 +0200173 return n
174
Martin v. Löwisd8996052002-11-21 21:45:32 +0000175def c2py(plural):
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000176 """Gets a C expression as used in PO files for plural forms and returns a
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200177 Python function that implements an equivalent expression.
Martin v. Löwisd8996052002-11-21 21:45:32 +0000178 """
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200179
180 if len(plural) > 1000:
181 raise ValueError('plural form expression is too long')
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000182 try:
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200183 result, nexttok = _parse(_tokenize(plural))
184 if nexttok:
185 raise _error(nexttok)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000186
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200187 depth = 0
188 for c in result:
189 if c == '(':
190 depth += 1
191 if depth > 20:
192 # Python compiler limit is about 90.
193 # The most complex example has 2.
194 raise ValueError('plural form expression is too complex')
195 elif c == ')':
196 depth -= 1
Martin v. Löwisd8996052002-11-21 21:45:32 +0000197
Serhiy Storchaka60ac9892016-11-14 19:22:12 +0200198 ns = {'_as_int': _as_int}
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200199 exec('''if True:
200 def func(n):
201 if not isinstance(n, int):
Serhiy Storchaka60ac9892016-11-14 19:22:12 +0200202 n = _as_int(n)
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200203 return int(%s)
204 ''' % result, ns)
205 return ns['func']
Serhiy Storchakaeb20fca2016-11-08 21:26:14 +0200206 except RecursionError:
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200207 # Recursion error can be raised in _parse() or exec().
208 raise ValueError('plural form expression is too complex')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000209
Tim Peters07e99cb2001-01-14 23:47:14 +0000210
Benjamin Peterson31e87202010-12-23 22:53:42 +0000211def _expand_lang(loc):
Hai Shi7443d422020-05-14 09:22:30 +0800212 import locale
Benjamin Peterson31e87202010-12-23 22:53:42 +0000213 loc = locale.normalize(loc)
Barry Warsawfa488ec2000-08-25 20:26:43 +0000214 COMPONENT_CODESET = 1 << 0
215 COMPONENT_TERRITORY = 1 << 1
216 COMPONENT_MODIFIER = 1 << 2
217 # split up the locale into its base components
218 mask = 0
Benjamin Peterson31e87202010-12-23 22:53:42 +0000219 pos = loc.find('@')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000220 if pos >= 0:
Benjamin Peterson31e87202010-12-23 22:53:42 +0000221 modifier = loc[pos:]
222 loc = loc[:pos]
Barry Warsawfa488ec2000-08-25 20:26:43 +0000223 mask |= COMPONENT_MODIFIER
224 else:
225 modifier = ''
Benjamin Peterson31e87202010-12-23 22:53:42 +0000226 pos = loc.find('.')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000227 if pos >= 0:
Benjamin Peterson31e87202010-12-23 22:53:42 +0000228 codeset = loc[pos:]
229 loc = loc[:pos]
Barry Warsawfa488ec2000-08-25 20:26:43 +0000230 mask |= COMPONENT_CODESET
231 else:
232 codeset = ''
Benjamin Peterson31e87202010-12-23 22:53:42 +0000233 pos = loc.find('_')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000234 if pos >= 0:
Benjamin Peterson31e87202010-12-23 22:53:42 +0000235 territory = loc[pos:]
236 loc = loc[:pos]
Barry Warsawfa488ec2000-08-25 20:26:43 +0000237 mask |= COMPONENT_TERRITORY
238 else:
239 territory = ''
Benjamin Peterson31e87202010-12-23 22:53:42 +0000240 language = loc
Barry Warsawfa488ec2000-08-25 20:26:43 +0000241 ret = []
242 for i in range(mask+1):
243 if not (i & ~mask): # if all components for this combo exist ...
244 val = language
245 if i & COMPONENT_TERRITORY: val += territory
246 if i & COMPONENT_CODESET: val += codeset
247 if i & COMPONENT_MODIFIER: val += modifier
248 ret.append(val)
249 ret.reverse()
250 return ret
251
252
Tim Peters07e99cb2001-01-14 23:47:14 +0000253
Barry Warsaw33d8d702000-08-30 03:29:58 +0000254class NullTranslations:
255 def __init__(self, fp=None):
256 self._info = {}
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000257 self._charset = None
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000258 self._output_charset = None
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000259 self._fallback = None
Raymond Hettinger094662a2002-06-01 01:29:16 +0000260 if fp is not None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000261 self._parse(fp)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000262
Barry Warsaw33d8d702000-08-30 03:29:58 +0000263 def _parse(self, fp):
264 pass
265
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000266 def add_fallback(self, fallback):
267 if self._fallback:
268 self._fallback.add_fallback(fallback)
269 else:
270 self._fallback = fallback
271
Barry Warsaw33d8d702000-08-30 03:29:58 +0000272 def gettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000273 if self._fallback:
274 return self._fallback.gettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000275 return message
276
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000277 def lgettext(self, message):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300278 import warnings
279 warnings.warn('lgettext() is deprecated, use gettext() instead',
280 DeprecationWarning, 2)
Hai Shi7443d422020-05-14 09:22:30 +0800281 import locale
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000282 if self._fallback:
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300283 with warnings.catch_warnings():
284 warnings.filterwarnings('ignore', r'.*\blgettext\b.*',
285 DeprecationWarning)
286 return self._fallback.lgettext(message)
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300287 if self._output_charset:
288 return message.encode(self._output_charset)
289 return message.encode(locale.getpreferredencoding())
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000290
Martin v. Löwisd8996052002-11-21 21:45:32 +0000291 def ngettext(self, msgid1, msgid2, n):
292 if self._fallback:
293 return self._fallback.ngettext(msgid1, msgid2, n)
294 if n == 1:
295 return msgid1
296 else:
297 return msgid2
298
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000299 def lngettext(self, msgid1, msgid2, n):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300300 import warnings
301 warnings.warn('lngettext() is deprecated, use ngettext() instead',
302 DeprecationWarning, 2)
Hai Shi7443d422020-05-14 09:22:30 +0800303 import locale
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000304 if self._fallback:
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300305 with warnings.catch_warnings():
306 warnings.filterwarnings('ignore', r'.*\blngettext\b.*',
307 DeprecationWarning)
308 return self._fallback.lngettext(msgid1, msgid2, n)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000309 if n == 1:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300310 tmsg = msgid1
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000311 else:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300312 tmsg = msgid2
313 if self._output_charset:
314 return tmsg.encode(self._output_charset)
315 return tmsg.encode(locale.getpreferredencoding())
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000316
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500317 def pgettext(self, context, message):
318 if self._fallback:
319 return self._fallback.pgettext(context, message)
320 return message
321
322 def npgettext(self, context, msgid1, msgid2, n):
323 if self._fallback:
324 return self._fallback.npgettext(context, msgid1, msgid2, n)
325 if n == 1:
326 return msgid1
327 else:
328 return msgid2
329
Barry Warsaw33d8d702000-08-30 03:29:58 +0000330 def info(self):
331 return self._info
332
333 def charset(self):
334 return self._charset
335
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000336 def output_charset(self):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300337 import warnings
338 warnings.warn('output_charset() is deprecated',
339 DeprecationWarning, 2)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000340 return self._output_charset
341
342 def set_output_charset(self, charset):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300343 import warnings
344 warnings.warn('set_output_charset() is deprecated',
345 DeprecationWarning, 2)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000346 self._output_charset = charset
347
Benjamin Peterson801844d2008-07-14 14:32:15 +0000348 def install(self, names=None):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000349 import builtins
Benjamin Peterson801844d2008-07-14 14:32:15 +0000350 builtins.__dict__['_'] = self.gettext
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500351 if names is not None:
352 allowed = {'gettext', 'lgettext', 'lngettext',
353 'ngettext', 'npgettext', 'pgettext'}
354 for name in allowed & set(names):
355 builtins.__dict__[name] = getattr(self, name)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000356
357
358class GNUTranslations(NullTranslations):
359 # Magic number of .mo files
Guido van Rossume2a383d2007-01-15 16:59:06 +0000360 LE_MAGIC = 0x950412de
361 BE_MAGIC = 0xde120495
Barry Warsaw95be23d2000-08-25 19:13:37 +0000362
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500363 # The encoding of a msgctxt and a msgid in a .mo file is
364 # msgctxt + "\x04" + msgid (gettext version >= 0.15)
365 CONTEXT = "%s\x04%s"
366
Antoine Pitroube8d06f2014-10-28 20:17:51 +0100367 # Acceptable .mo versions
368 VERSIONS = (0, 1)
369
370 def _get_versions(self, version):
371 """Returns a tuple of major version, minor version"""
372 return (version >> 16, version & 0xffff)
373
Barry Warsaw95be23d2000-08-25 19:13:37 +0000374 def _parse(self, fp):
375 """Override this method to support alternative .mo formats."""
Serhiy Storchaka81108372017-09-26 00:55:55 +0300376 # Delay struct import for speeding up gettext import when .mo files
377 # are not used.
378 from struct import unpack
Barry Warsaw95be23d2000-08-25 19:13:37 +0000379 filename = getattr(fp, 'name', '')
380 # Parse the .mo file header, which consists of 5 little endian 32
381 # bit words.
Barry Warsaw33d8d702000-08-30 03:29:58 +0000382 self._catalog = catalog = {}
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000383 self.plural = lambda n: int(n != 1) # germanic plural by default
Barry Warsaw95be23d2000-08-25 19:13:37 +0000384 buf = fp.read()
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000385 buflen = len(buf)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000386 # Are we big endian or little endian?
Barry Warsaw09707e32002-08-14 15:09:12 +0000387 magic = unpack('<I', buf[:4])[0]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000388 if magic == self.LE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000389 version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
390 ii = '<II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000391 elif magic == self.BE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000392 version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
393 ii = '>II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000394 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200395 raise OSError(0, 'Bad magic number', filename)
Antoine Pitroube8d06f2014-10-28 20:17:51 +0100396
397 major_version, minor_version = self._get_versions(version)
398
399 if major_version not in self.VERSIONS:
400 raise OSError(0, 'Bad version number ' + str(major_version), filename)
401
Barry Warsaw95be23d2000-08-25 19:13:37 +0000402 # Now put all messages from the .mo file buffer into the catalog
403 # dictionary.
Guido van Rossum805365e2007-05-07 22:24:25 +0000404 for i in range(0, msgcount):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000405 mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000406 mend = moff + mlen
Barry Warsaw33d8d702000-08-30 03:29:58 +0000407 tlen, toff = unpack(ii, buf[transidx:transidx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000408 tend = toff + tlen
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000409 if mend < buflen and tend < buflen:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000410 msg = buf[moff:mend]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000411 tmsg = buf[toff:tend]
Barry Warsaw95be23d2000-08-25 19:13:37 +0000412 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200413 raise OSError(0, 'File is corrupt', filename)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000414 # See if we're looking at GNU .mo conventions for metadata
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000415 if mlen == 0:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000416 # Catalog description
Andrew Kuchling8b963c52015-04-13 10:38:56 -0400417 lastk = None
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300418 for b_item in tmsg.split(b'\n'):
Guido van Rossum98297ee2007-11-06 21:34:58 +0000419 item = b_item.decode().strip()
Barry Warsaw33d8d702000-08-30 03:29:58 +0000420 if not item:
421 continue
Julien Palardafd1e6d2019-05-09 16:22:15 +0200422 # Skip over comment lines:
423 if item.startswith('#-#-#-#-#') and item.endswith('#-#-#-#-#'):
424 continue
Andrew Kuchling8b963c52015-04-13 10:38:56 -0400425 k = v = None
Barry Warsaw7de63f52003-05-20 17:26:48 +0000426 if ':' in item:
427 k, v = item.split(':', 1)
428 k = k.strip().lower()
429 v = v.strip()
430 self._info[k] = v
431 lastk = k
432 elif lastk:
433 self._info[lastk] += '\n' + item
Barry Warsaw33d8d702000-08-30 03:29:58 +0000434 if k == 'content-type':
435 self._charset = v.split('charset=')[1]
Martin v. Löwisd8996052002-11-21 21:45:32 +0000436 elif k == 'plural-forms':
437 v = v.split(';')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000438 plural = v[1].split('plural=')[1]
439 self.plural = c2py(plural)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000440 # Note: we unconditionally convert both msgids and msgstrs to
441 # Unicode using the character encoding specified in the charset
442 # parameter of the Content-Type header. The gettext documentation
Ezio Melotti42da6632011-03-15 05:18:48 +0200443 # strongly encourages msgids to be us-ascii, but some applications
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000444 # require alternative encodings (e.g. Zope's ZCML and ZPT). For
445 # traditional gettext applications, the msgid conversion will
446 # cause no problems since us-ascii should always be a subset of
447 # the charset encoding. We may want to fall back to 8-bit msgids
448 # if the Unicode conversion fails.
Georg Brandlbded4d32008-07-17 18:15:35 +0000449 charset = self._charset or 'ascii'
Guido van Rossum652f4462007-07-12 08:04:06 +0000450 if b'\x00' in msg:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000451 # Plural forms
Guido van Rossum9600f932007-08-29 03:08:55 +0000452 msgid1, msgid2 = msg.split(b'\x00')
453 tmsg = tmsg.split(b'\x00')
Georg Brandlbded4d32008-07-17 18:15:35 +0000454 msgid1 = str(msgid1, charset)
455 for i, x in enumerate(tmsg):
456 catalog[(msgid1, i)] = str(x, charset)
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000457 else:
Georg Brandlbded4d32008-07-17 18:15:35 +0000458 catalog[str(msg, charset)] = str(tmsg, charset)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000459 # advance to next entry in the seek tables
Barry Warsawfa488ec2000-08-25 20:26:43 +0000460 masteridx += 8
461 transidx += 8
Barry Warsaw33d8d702000-08-30 03:29:58 +0000462
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000463 def lgettext(self, message):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300464 import warnings
465 warnings.warn('lgettext() is deprecated, use gettext() instead',
466 DeprecationWarning, 2)
Hai Shi7443d422020-05-14 09:22:30 +0800467 import locale
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000468 missing = object()
469 tmsg = self._catalog.get(message, missing)
470 if tmsg is missing:
471 if self._fallback:
472 return self._fallback.lgettext(message)
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300473 tmsg = message
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000474 if self._output_charset:
475 return tmsg.encode(self._output_charset)
476 return tmsg.encode(locale.getpreferredencoding())
477
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000478 def lngettext(self, msgid1, msgid2, n):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300479 import warnings
480 warnings.warn('lngettext() is deprecated, use ngettext() instead',
481 DeprecationWarning, 2)
Hai Shi7443d422020-05-14 09:22:30 +0800482 import locale
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000483 try:
484 tmsg = self._catalog[(msgid1, self.plural(n))]
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000485 except KeyError:
486 if self._fallback:
487 return self._fallback.lngettext(msgid1, msgid2, n)
488 if n == 1:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300489 tmsg = msgid1
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000490 else:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300491 tmsg = msgid2
492 if self._output_charset:
493 return tmsg.encode(self._output_charset)
494 return tmsg.encode(locale.getpreferredencoding())
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000495
Benjamin Peterson801844d2008-07-14 14:32:15 +0000496 def gettext(self, message):
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000497 missing = object()
498 tmsg = self._catalog.get(message, missing)
499 if tmsg is missing:
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000500 if self._fallback:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000501 return self._fallback.gettext(message)
Georg Brandlbded4d32008-07-17 18:15:35 +0000502 return message
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000503 return tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000504
Benjamin Peterson801844d2008-07-14 14:32:15 +0000505 def ngettext(self, msgid1, msgid2, n):
Martin v. Löwisd8996052002-11-21 21:45:32 +0000506 try:
507 tmsg = self._catalog[(msgid1, self.plural(n))]
508 except KeyError:
509 if self._fallback:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000510 return self._fallback.ngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000511 if n == 1:
Georg Brandlbded4d32008-07-17 18:15:35 +0000512 tmsg = msgid1
Martin v. Löwisd8996052002-11-21 21:45:32 +0000513 else:
Georg Brandlbded4d32008-07-17 18:15:35 +0000514 tmsg = msgid2
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000515 return tmsg
Martin v. Löwisd8996052002-11-21 21:45:32 +0000516
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500517 def pgettext(self, context, message):
518 ctxt_msg_id = self.CONTEXT % (context, message)
519 missing = object()
520 tmsg = self._catalog.get(ctxt_msg_id, missing)
521 if tmsg is missing:
522 if self._fallback:
523 return self._fallback.pgettext(context, message)
524 return message
525 return tmsg
526
527 def npgettext(self, context, msgid1, msgid2, n):
528 ctxt_msg_id = self.CONTEXT % (context, msgid1)
529 try:
530 tmsg = self._catalog[ctxt_msg_id, self.plural(n)]
531 except KeyError:
532 if self._fallback:
533 return self._fallback.npgettext(context, msgid1, msgid2, n)
534 if n == 1:
535 tmsg = msgid1
536 else:
537 tmsg = msgid2
538 return tmsg
539
Tim Peters07e99cb2001-01-14 23:47:14 +0000540
Barry Warsaw95be23d2000-08-25 19:13:37 +0000541# Locate a .mo file using the gettext strategy
Georg Brandlcd869252009-05-17 12:50:58 +0000542def find(domain, localedir=None, languages=None, all=False):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000543 # Get some reasonable defaults for arguments that were not supplied
Barry Warsaw95be23d2000-08-25 19:13:37 +0000544 if localedir is None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000545 localedir = _default_localedir
Barry Warsaw95be23d2000-08-25 19:13:37 +0000546 if languages is None:
547 languages = []
548 for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
549 val = os.environ.get(envar)
550 if val:
551 languages = val.split(':')
552 break
553 if 'C' not in languages:
554 languages.append('C')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000555 # now normalize and expand the languages
Barry Warsaw75f81012000-10-16 15:47:50 +0000556 nelangs = []
Barry Warsawfa488ec2000-08-25 20:26:43 +0000557 for lang in languages:
558 for nelang in _expand_lang(lang):
Barry Warsaw75f81012000-10-16 15:47:50 +0000559 if nelang not in nelangs:
560 nelangs.append(nelang)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000561 # select a language
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000562 if all:
563 result = []
564 else:
565 result = None
Barry Warsaw75f81012000-10-16 15:47:50 +0000566 for lang in nelangs:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000567 if lang == 'C':
568 break
Barry Warsaw84314b72000-08-25 19:53:17 +0000569 mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000570 if os.path.exists(mofile):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000571 if all:
572 result.append(mofile)
573 else:
574 return mofile
575 return result
Barry Warsaw95be23d2000-08-25 19:13:37 +0000576
577
Tim Peters07e99cb2001-01-14 23:47:14 +0000578
Barry Warsaw33d8d702000-08-30 03:29:58 +0000579# a mapping between absolute .mo file path and Translation object
580_translations = {}
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300581_unspecified = ['unspecified']
Barry Warsaw33d8d702000-08-30 03:29:58 +0000582
Martin v. Löwis1be64192002-01-11 06:33:28 +0000583def translation(domain, localedir=None, languages=None,
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300584 class_=None, fallback=False, codeset=_unspecified):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000585 if class_ is None:
586 class_ = GNUTranslations
Georg Brandlcd869252009-05-17 12:50:58 +0000587 mofiles = find(domain, localedir, languages, all=True)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000588 if not mofiles:
Martin v. Löwis1be64192002-01-11 06:33:28 +0000589 if fallback:
590 return NullTranslations()
Serhiy Storchaka81108372017-09-26 00:55:55 +0300591 from errno import ENOENT
592 raise FileNotFoundError(ENOENT,
593 'No translation file found for domain', domain)
Barry Warsaw293b03f2000-10-05 18:48:12 +0000594 # Avoid opening, reading, and parsing the .mo file after it's been done
595 # once.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000596 result = None
597 for mofile in mofiles:
Éric Araujo6108bf52010-10-04 23:52:37 +0000598 key = (class_, os.path.abspath(mofile))
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000599 t = _translations.get(key)
600 if t is None:
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000601 with open(mofile, 'rb') as fp:
602 t = _translations.setdefault(key, class_(fp))
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000603 # Copy the translation object to allow setting fallbacks and
604 # output charset. All other instance data is shared with the
605 # cached object.
Serhiy Storchaka81108372017-09-26 00:55:55 +0300606 # Delay copy import for speeding up gettext import when .mo files
607 # are not used.
608 import copy
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000609 t = copy.copy(t)
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300610 if codeset is not _unspecified:
611 import warnings
612 warnings.warn('parameter codeset is deprecated',
613 DeprecationWarning, 2)
614 if codeset:
615 with warnings.catch_warnings():
616 warnings.filterwarnings('ignore', r'.*\bset_output_charset\b.*',
617 DeprecationWarning)
618 t.set_output_charset(codeset)
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000619 if result is None:
620 result = t
621 else:
622 result.add_fallback(t)
623 return result
Barry Warsaw33d8d702000-08-30 03:29:58 +0000624
Tim Peters07e99cb2001-01-14 23:47:14 +0000625
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300626def install(domain, localedir=None, codeset=_unspecified, names=None):
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000627 t = translation(domain, localedir, fallback=True, codeset=codeset)
Benjamin Peterson801844d2008-07-14 14:32:15 +0000628 t.install(names)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000629
630
Tim Peters07e99cb2001-01-14 23:47:14 +0000631
Barry Warsaw33d8d702000-08-30 03:29:58 +0000632# a mapping b/w domains and locale directories
633_localedirs = {}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000634# a mapping b/w domains and codesets
635_localecodesets = {}
Barry Warsaw33d8d702000-08-30 03:29:58 +0000636# current global domain, `messages' used for compatibility w/ GNU gettext
637_current_domain = 'messages'
Barry Warsaw95be23d2000-08-25 19:13:37 +0000638
639
640def textdomain(domain=None):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000641 global _current_domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000642 if domain is not None:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000643 _current_domain = domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000644 return _current_domain
Barry Warsaw95be23d2000-08-25 19:13:37 +0000645
646
Barry Warsaw33d8d702000-08-30 03:29:58 +0000647def bindtextdomain(domain, localedir=None):
648 global _localedirs
649 if localedir is not None:
650 _localedirs[domain] = localedir
651 return _localedirs.get(domain, _default_localedir)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000652
653
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000654def bind_textdomain_codeset(domain, codeset=None):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300655 import warnings
656 warnings.warn('bind_textdomain_codeset() is deprecated',
657 DeprecationWarning, 2)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000658 global _localecodesets
659 if codeset is not None:
660 _localecodesets[domain] = codeset
661 return _localecodesets.get(domain)
662
663
Barry Warsaw95be23d2000-08-25 19:13:37 +0000664def dgettext(domain, message):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000665 try:
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300666 t = translation(domain, _localedirs.get(domain, None))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200667 except OSError:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000668 return message
669 return t.gettext(message)
Tim Peters07e99cb2001-01-14 23:47:14 +0000670
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000671def ldgettext(domain, message):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300672 import warnings
673 warnings.warn('ldgettext() is deprecated, use dgettext() instead',
674 DeprecationWarning, 2)
Hai Shi7443d422020-05-14 09:22:30 +0800675 import locale
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300676 codeset = _localecodesets.get(domain)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000677 try:
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300678 with warnings.catch_warnings():
679 warnings.filterwarnings('ignore', r'.*\bparameter codeset\b.*',
680 DeprecationWarning)
681 t = translation(domain, _localedirs.get(domain, None), codeset=codeset)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200682 except OSError:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300683 return message.encode(codeset or locale.getpreferredencoding())
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300684 with warnings.catch_warnings():
685 warnings.filterwarnings('ignore', r'.*\blgettext\b.*',
686 DeprecationWarning)
687 return t.lgettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000688
Martin v. Löwisd8996052002-11-21 21:45:32 +0000689def dngettext(domain, msgid1, msgid2, n):
690 try:
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300691 t = translation(domain, _localedirs.get(domain, None))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200692 except OSError:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000693 if n == 1:
694 return msgid1
695 else:
696 return msgid2
697 return t.ngettext(msgid1, msgid2, n)
698
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000699def ldngettext(domain, msgid1, msgid2, n):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300700 import warnings
701 warnings.warn('ldngettext() is deprecated, use dngettext() instead',
702 DeprecationWarning, 2)
Hai Shi7443d422020-05-14 09:22:30 +0800703 import locale
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300704 codeset = _localecodesets.get(domain)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000705 try:
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300706 with warnings.catch_warnings():
707 warnings.filterwarnings('ignore', r'.*\bparameter codeset\b.*',
708 DeprecationWarning)
709 t = translation(domain, _localedirs.get(domain, None), codeset=codeset)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200710 except OSError:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000711 if n == 1:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300712 tmsg = msgid1
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000713 else:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300714 tmsg = msgid2
715 return tmsg.encode(codeset or locale.getpreferredencoding())
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300716 with warnings.catch_warnings():
717 warnings.filterwarnings('ignore', r'.*\blngettext\b.*',
718 DeprecationWarning)
719 return t.lngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000720
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500721
722def dpgettext(domain, context, message):
723 try:
724 t = translation(domain, _localedirs.get(domain, None))
725 except OSError:
726 return message
727 return t.pgettext(context, message)
728
729
730def dnpgettext(domain, context, msgid1, msgid2, n):
731 try:
732 t = translation(domain, _localedirs.get(domain, None))
733 except OSError:
734 if n == 1:
735 return msgid1
736 else:
737 return msgid2
738 return t.npgettext(context, msgid1, msgid2, n)
739
740
Barry Warsaw33d8d702000-08-30 03:29:58 +0000741def gettext(message):
742 return dgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000743
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000744def lgettext(message):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300745 import warnings
746 warnings.warn('lgettext() is deprecated, use gettext() instead',
747 DeprecationWarning, 2)
748 with warnings.catch_warnings():
749 warnings.filterwarnings('ignore', r'.*\bldgettext\b.*',
750 DeprecationWarning)
751 return ldgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000752
Martin v. Löwisd8996052002-11-21 21:45:32 +0000753def ngettext(msgid1, msgid2, n):
754 return dngettext(_current_domain, msgid1, msgid2, n)
755
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000756def lngettext(msgid1, msgid2, n):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300757 import warnings
758 warnings.warn('lngettext() is deprecated, use ngettext() instead',
759 DeprecationWarning, 2)
760 with warnings.catch_warnings():
761 warnings.filterwarnings('ignore', r'.*\bldngettext\b.*',
762 DeprecationWarning)
763 return ldngettext(_current_domain, msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000764
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500765
766def pgettext(context, message):
767 return dpgettext(_current_domain, context, message)
768
769
770def npgettext(context, msgid1, msgid2, n):
771 return dnpgettext(_current_domain, context, msgid1, msgid2, n)
772
773
Barry Warsaw33d8d702000-08-30 03:29:58 +0000774# dcgettext() has been deemed unnecessary and is not implemented.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000775
Barry Warsaw33d8d702000-08-30 03:29:58 +0000776# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
777# was:
778#
779# import gettext
780# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
781# _ = cat.gettext
782# print _('Hello World')
Barry Warsaw95be23d2000-08-25 19:13:37 +0000783
Barry Warsaw33d8d702000-08-30 03:29:58 +0000784# The resulting catalog object currently don't support access through a
785# dictionary API, which was supported (but apparently unused) in GNOME
786# gettext.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000787
Barry Warsaw33d8d702000-08-30 03:29:58 +0000788Catalog = translation