blob: b98f501884b75a4e7d14ca124ad672938a99e541 [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 locale
50import os
51import re
Victor Stinnerd6debb22017-03-27 16:05:26 +020052import sys
Barry Warsaw95be23d2000-08-25 19:13:37 +000053
Martin v. Löwisd8996052002-11-21 21:45:32 +000054
Barry Warsawa1ce93f2003-04-11 18:36:43 +000055__all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
56 'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
Andrew Kuchling770b08e2015-04-13 09:58:36 -040057 'bind_textdomain_codeset',
58 'dgettext', 'dngettext', 'gettext', 'lgettext', 'ldgettext',
59 'ldngettext', 'lngettext', 'ngettext',
Cheryl Sabella637a33b2018-11-07 09:12:20 -050060 'pgettext', 'dpgettext', 'npgettext', 'dnpgettext',
Barry Warsawa1ce93f2003-04-11 18:36:43 +000061 ]
Skip Montanaro2dd42762001-01-23 15:35:05 +000062
Vinay Sajip7ded1f02012-05-26 03:45:29 +010063_default_localedir = os.path.join(sys.base_prefix, 'share', 'locale')
Barry Warsaw95be23d2000-08-25 19:13:37 +000064
Serhiy Storchaka07bcf052016-11-08 21:17:46 +020065# Expression parsing for plural form selection.
66#
67# The gettext library supports a small subset of C syntax. The only
68# incompatible difference is that integer literals starting with zero are
69# decimal.
70#
71# https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms
72# http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y
73
74_token_pattern = re.compile(r"""
75 (?P<WHITESPACES>[ \t]+) | # spaces and horizontal tabs
76 (?P<NUMBER>[0-9]+\b) | # decimal integer
77 (?P<NAME>n\b) | # only n is allowed
78 (?P<PARENTHESIS>[()]) |
79 (?P<OPERATOR>[-*/%+?:]|[><!]=?|==|&&|\|\|) | # !, *, /, %, +, -, <, >,
80 # <=, >=, ==, !=, &&, ||,
81 # ? :
82 # unary and bitwise ops
83 # not allowed
84 (?P<INVALID>\w+|.) # invalid token
85 """, re.VERBOSE|re.DOTALL)
86
87def _tokenize(plural):
88 for mo in re.finditer(_token_pattern, plural):
89 kind = mo.lastgroup
90 if kind == 'WHITESPACES':
91 continue
92 value = mo.group(kind)
93 if kind == 'INVALID':
94 raise ValueError('invalid token in plural form: %s' % value)
95 yield value
96 yield ''
97
98def _error(value):
99 if value:
100 return ValueError('unexpected token in plural form: %s' % value)
101 else:
102 return ValueError('unexpected end of plural form')
103
104_binary_ops = (
105 ('||',),
106 ('&&',),
107 ('==', '!='),
108 ('<', '>', '<=', '>='),
109 ('+', '-'),
110 ('*', '/', '%'),
111)
112_binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops}
113_c2py_ops = {'||': 'or', '&&': 'and', '/': '//'}
114
115def _parse(tokens, priority=-1):
116 result = ''
117 nexttok = next(tokens)
118 while nexttok == '!':
119 result += 'not '
120 nexttok = next(tokens)
121
122 if nexttok == '(':
123 sub, nexttok = _parse(tokens)
124 result = '%s(%s)' % (result, sub)
125 if nexttok != ')':
126 raise ValueError('unbalanced parenthesis in plural form')
127 elif nexttok == 'n':
128 result = '%s%s' % (result, nexttok)
129 else:
130 try:
131 value = int(nexttok, 10)
132 except ValueError:
133 raise _error(nexttok) from None
134 result = '%s%d' % (result, value)
135 nexttok = next(tokens)
136
137 j = 100
138 while nexttok in _binary_ops:
139 i = _binary_ops[nexttok]
140 if i < priority:
141 break
142 # Break chained comparisons
143 if i in (3, 4) and j in (3, 4): # '==', '!=', '<', '>', '<=', '>='
144 result = '(%s)' % result
145 # Replace some C operators by their Python equivalents
146 op = _c2py_ops.get(nexttok, nexttok)
147 right, nexttok = _parse(tokens, i + 1)
148 result = '%s %s %s' % (result, op, right)
149 j = i
150 if j == priority == 4: # '<', '>', '<=', '>='
151 result = '(%s)' % result
152
153 if nexttok == '?' and priority <= 0:
154 if_true, nexttok = _parse(tokens, 0)
155 if nexttok != ':':
156 raise _error(nexttok)
157 if_false, nexttok = _parse(tokens)
158 result = '%s if %s else %s' % (if_true, result, if_false)
159 if priority == 0:
160 result = '(%s)' % result
161
162 return result, nexttok
Barry Warsaw95be23d2000-08-25 19:13:37 +0000163
Serhiy Storchaka60ac9892016-11-14 19:22:12 +0200164def _as_int(n):
165 try:
166 i = round(n)
167 except TypeError:
168 raise TypeError('Plural value must be an integer, got %s' %
169 (n.__class__.__name__,)) from None
Serhiy Storchakaf6595982017-03-12 13:15:01 +0200170 import warnings
171 warnings.warn('Plural value must be an integer, got %s' %
172 (n.__class__.__name__,),
173 DeprecationWarning, 4)
Serhiy Storchaka60ac9892016-11-14 19:22:12 +0200174 return n
175
Martin v. Löwisd8996052002-11-21 21:45:32 +0000176def c2py(plural):
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000177 """Gets a C expression as used in PO files for plural forms and returns a
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200178 Python function that implements an equivalent expression.
Martin v. Löwisd8996052002-11-21 21:45:32 +0000179 """
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200180
181 if len(plural) > 1000:
182 raise ValueError('plural form expression is too long')
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000183 try:
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200184 result, nexttok = _parse(_tokenize(plural))
185 if nexttok:
186 raise _error(nexttok)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000187
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200188 depth = 0
189 for c in result:
190 if c == '(':
191 depth += 1
192 if depth > 20:
193 # Python compiler limit is about 90.
194 # The most complex example has 2.
195 raise ValueError('plural form expression is too complex')
196 elif c == ')':
197 depth -= 1
Martin v. Löwisd8996052002-11-21 21:45:32 +0000198
Serhiy Storchaka60ac9892016-11-14 19:22:12 +0200199 ns = {'_as_int': _as_int}
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200200 exec('''if True:
201 def func(n):
202 if not isinstance(n, int):
Serhiy Storchaka60ac9892016-11-14 19:22:12 +0200203 n = _as_int(n)
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200204 return int(%s)
205 ''' % result, ns)
206 return ns['func']
Serhiy Storchakaeb20fca2016-11-08 21:26:14 +0200207 except RecursionError:
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200208 # Recursion error can be raised in _parse() or exec().
209 raise ValueError('plural form expression is too complex')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000210
Tim Peters07e99cb2001-01-14 23:47:14 +0000211
Benjamin Peterson31e87202010-12-23 22:53:42 +0000212def _expand_lang(loc):
213 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)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000281 if self._fallback:
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300282 with warnings.catch_warnings():
283 warnings.filterwarnings('ignore', r'.*\blgettext\b.*',
284 DeprecationWarning)
285 return self._fallback.lgettext(message)
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300286 if self._output_charset:
287 return message.encode(self._output_charset)
288 return message.encode(locale.getpreferredencoding())
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000289
Martin v. Löwisd8996052002-11-21 21:45:32 +0000290 def ngettext(self, msgid1, msgid2, n):
291 if self._fallback:
292 return self._fallback.ngettext(msgid1, msgid2, n)
293 if n == 1:
294 return msgid1
295 else:
296 return msgid2
297
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000298 def lngettext(self, msgid1, msgid2, n):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300299 import warnings
300 warnings.warn('lngettext() is deprecated, use ngettext() instead',
301 DeprecationWarning, 2)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000302 if self._fallback:
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300303 with warnings.catch_warnings():
304 warnings.filterwarnings('ignore', r'.*\blngettext\b.*',
305 DeprecationWarning)
306 return self._fallback.lngettext(msgid1, msgid2, n)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000307 if n == 1:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300308 tmsg = msgid1
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000309 else:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300310 tmsg = msgid2
311 if self._output_charset:
312 return tmsg.encode(self._output_charset)
313 return tmsg.encode(locale.getpreferredencoding())
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000314
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500315 def pgettext(self, context, message):
316 if self._fallback:
317 return self._fallback.pgettext(context, message)
318 return message
319
320 def npgettext(self, context, msgid1, msgid2, n):
321 if self._fallback:
322 return self._fallback.npgettext(context, msgid1, msgid2, n)
323 if n == 1:
324 return msgid1
325 else:
326 return msgid2
327
Barry Warsaw33d8d702000-08-30 03:29:58 +0000328 def info(self):
329 return self._info
330
331 def charset(self):
332 return self._charset
333
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000334 def output_charset(self):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300335 import warnings
336 warnings.warn('output_charset() is deprecated',
337 DeprecationWarning, 2)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000338 return self._output_charset
339
340 def set_output_charset(self, charset):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300341 import warnings
342 warnings.warn('set_output_charset() is deprecated',
343 DeprecationWarning, 2)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000344 self._output_charset = charset
345
Benjamin Peterson801844d2008-07-14 14:32:15 +0000346 def install(self, names=None):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000347 import builtins
Benjamin Peterson801844d2008-07-14 14:32:15 +0000348 builtins.__dict__['_'] = self.gettext
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500349 if names is not None:
350 allowed = {'gettext', 'lgettext', 'lngettext',
351 'ngettext', 'npgettext', 'pgettext'}
352 for name in allowed & set(names):
353 builtins.__dict__[name] = getattr(self, name)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000354
355
356class GNUTranslations(NullTranslations):
357 # Magic number of .mo files
Guido van Rossume2a383d2007-01-15 16:59:06 +0000358 LE_MAGIC = 0x950412de
359 BE_MAGIC = 0xde120495
Barry Warsaw95be23d2000-08-25 19:13:37 +0000360
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500361 # The encoding of a msgctxt and a msgid in a .mo file is
362 # msgctxt + "\x04" + msgid (gettext version >= 0.15)
363 CONTEXT = "%s\x04%s"
364
Antoine Pitroube8d06f2014-10-28 20:17:51 +0100365 # Acceptable .mo versions
366 VERSIONS = (0, 1)
367
368 def _get_versions(self, version):
369 """Returns a tuple of major version, minor version"""
370 return (version >> 16, version & 0xffff)
371
Barry Warsaw95be23d2000-08-25 19:13:37 +0000372 def _parse(self, fp):
373 """Override this method to support alternative .mo formats."""
Serhiy Storchaka81108372017-09-26 00:55:55 +0300374 # Delay struct import for speeding up gettext import when .mo files
375 # are not used.
376 from struct import unpack
Barry Warsaw95be23d2000-08-25 19:13:37 +0000377 filename = getattr(fp, 'name', '')
378 # Parse the .mo file header, which consists of 5 little endian 32
379 # bit words.
Barry Warsaw33d8d702000-08-30 03:29:58 +0000380 self._catalog = catalog = {}
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000381 self.plural = lambda n: int(n != 1) # germanic plural by default
Barry Warsaw95be23d2000-08-25 19:13:37 +0000382 buf = fp.read()
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000383 buflen = len(buf)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000384 # Are we big endian or little endian?
Barry Warsaw09707e32002-08-14 15:09:12 +0000385 magic = unpack('<I', buf[:4])[0]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000386 if magic == self.LE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000387 version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
388 ii = '<II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000389 elif magic == self.BE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000390 version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
391 ii = '>II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000392 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200393 raise OSError(0, 'Bad magic number', filename)
Antoine Pitroube8d06f2014-10-28 20:17:51 +0100394
395 major_version, minor_version = self._get_versions(version)
396
397 if major_version not in self.VERSIONS:
398 raise OSError(0, 'Bad version number ' + str(major_version), filename)
399
Barry Warsaw95be23d2000-08-25 19:13:37 +0000400 # Now put all messages from the .mo file buffer into the catalog
401 # dictionary.
Guido van Rossum805365e2007-05-07 22:24:25 +0000402 for i in range(0, msgcount):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000403 mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000404 mend = moff + mlen
Barry Warsaw33d8d702000-08-30 03:29:58 +0000405 tlen, toff = unpack(ii, buf[transidx:transidx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000406 tend = toff + tlen
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000407 if mend < buflen and tend < buflen:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000408 msg = buf[moff:mend]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000409 tmsg = buf[toff:tend]
Barry Warsaw95be23d2000-08-25 19:13:37 +0000410 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200411 raise OSError(0, 'File is corrupt', filename)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000412 # See if we're looking at GNU .mo conventions for metadata
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000413 if mlen == 0:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000414 # Catalog description
Andrew Kuchling8b963c52015-04-13 10:38:56 -0400415 lastk = None
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300416 for b_item in tmsg.split(b'\n'):
Guido van Rossum98297ee2007-11-06 21:34:58 +0000417 item = b_item.decode().strip()
Barry Warsaw33d8d702000-08-30 03:29:58 +0000418 if not item:
419 continue
Julien Palardafd1e6d2019-05-09 16:22:15 +0200420 # Skip over comment lines:
421 if item.startswith('#-#-#-#-#') and item.endswith('#-#-#-#-#'):
422 continue
Andrew Kuchling8b963c52015-04-13 10:38:56 -0400423 k = v = None
Barry Warsaw7de63f52003-05-20 17:26:48 +0000424 if ':' in item:
425 k, v = item.split(':', 1)
426 k = k.strip().lower()
427 v = v.strip()
428 self._info[k] = v
429 lastk = k
430 elif lastk:
431 self._info[lastk] += '\n' + item
Barry Warsaw33d8d702000-08-30 03:29:58 +0000432 if k == 'content-type':
433 self._charset = v.split('charset=')[1]
Martin v. Löwisd8996052002-11-21 21:45:32 +0000434 elif k == 'plural-forms':
435 v = v.split(';')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000436 plural = v[1].split('plural=')[1]
437 self.plural = c2py(plural)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000438 # Note: we unconditionally convert both msgids and msgstrs to
439 # Unicode using the character encoding specified in the charset
440 # parameter of the Content-Type header. The gettext documentation
Ezio Melotti42da6632011-03-15 05:18:48 +0200441 # strongly encourages msgids to be us-ascii, but some applications
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000442 # require alternative encodings (e.g. Zope's ZCML and ZPT). For
443 # traditional gettext applications, the msgid conversion will
444 # cause no problems since us-ascii should always be a subset of
445 # the charset encoding. We may want to fall back to 8-bit msgids
446 # if the Unicode conversion fails.
Georg Brandlbded4d32008-07-17 18:15:35 +0000447 charset = self._charset or 'ascii'
Guido van Rossum652f4462007-07-12 08:04:06 +0000448 if b'\x00' in msg:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000449 # Plural forms
Guido van Rossum9600f932007-08-29 03:08:55 +0000450 msgid1, msgid2 = msg.split(b'\x00')
451 tmsg = tmsg.split(b'\x00')
Georg Brandlbded4d32008-07-17 18:15:35 +0000452 msgid1 = str(msgid1, charset)
453 for i, x in enumerate(tmsg):
454 catalog[(msgid1, i)] = str(x, charset)
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000455 else:
Georg Brandlbded4d32008-07-17 18:15:35 +0000456 catalog[str(msg, charset)] = str(tmsg, charset)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000457 # advance to next entry in the seek tables
Barry Warsawfa488ec2000-08-25 20:26:43 +0000458 masteridx += 8
459 transidx += 8
Barry Warsaw33d8d702000-08-30 03:29:58 +0000460
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000461 def lgettext(self, message):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300462 import warnings
463 warnings.warn('lgettext() is deprecated, use gettext() instead',
464 DeprecationWarning, 2)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000465 missing = object()
466 tmsg = self._catalog.get(message, missing)
467 if tmsg is missing:
468 if self._fallback:
469 return self._fallback.lgettext(message)
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300470 tmsg = message
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000471 if self._output_charset:
472 return tmsg.encode(self._output_charset)
473 return tmsg.encode(locale.getpreferredencoding())
474
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000475 def lngettext(self, msgid1, msgid2, n):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300476 import warnings
477 warnings.warn('lngettext() is deprecated, use ngettext() instead',
478 DeprecationWarning, 2)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000479 try:
480 tmsg = self._catalog[(msgid1, self.plural(n))]
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000481 except KeyError:
482 if self._fallback:
483 return self._fallback.lngettext(msgid1, msgid2, n)
484 if n == 1:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300485 tmsg = msgid1
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000486 else:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300487 tmsg = msgid2
488 if self._output_charset:
489 return tmsg.encode(self._output_charset)
490 return tmsg.encode(locale.getpreferredencoding())
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000491
Benjamin Peterson801844d2008-07-14 14:32:15 +0000492 def gettext(self, message):
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000493 missing = object()
494 tmsg = self._catalog.get(message, missing)
495 if tmsg is missing:
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000496 if self._fallback:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000497 return self._fallback.gettext(message)
Georg Brandlbded4d32008-07-17 18:15:35 +0000498 return message
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000499 return tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000500
Benjamin Peterson801844d2008-07-14 14:32:15 +0000501 def ngettext(self, msgid1, msgid2, n):
Martin v. Löwisd8996052002-11-21 21:45:32 +0000502 try:
503 tmsg = self._catalog[(msgid1, self.plural(n))]
504 except KeyError:
505 if self._fallback:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000506 return self._fallback.ngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000507 if n == 1:
Georg Brandlbded4d32008-07-17 18:15:35 +0000508 tmsg = msgid1
Martin v. Löwisd8996052002-11-21 21:45:32 +0000509 else:
Georg Brandlbded4d32008-07-17 18:15:35 +0000510 tmsg = msgid2
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000511 return tmsg
Martin v. Löwisd8996052002-11-21 21:45:32 +0000512
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500513 def pgettext(self, context, message):
514 ctxt_msg_id = self.CONTEXT % (context, message)
515 missing = object()
516 tmsg = self._catalog.get(ctxt_msg_id, missing)
517 if tmsg is missing:
518 if self._fallback:
519 return self._fallback.pgettext(context, message)
520 return message
521 return tmsg
522
523 def npgettext(self, context, msgid1, msgid2, n):
524 ctxt_msg_id = self.CONTEXT % (context, msgid1)
525 try:
526 tmsg = self._catalog[ctxt_msg_id, self.plural(n)]
527 except KeyError:
528 if self._fallback:
529 return self._fallback.npgettext(context, msgid1, msgid2, n)
530 if n == 1:
531 tmsg = msgid1
532 else:
533 tmsg = msgid2
534 return tmsg
535
Tim Peters07e99cb2001-01-14 23:47:14 +0000536
Barry Warsaw95be23d2000-08-25 19:13:37 +0000537# Locate a .mo file using the gettext strategy
Georg Brandlcd869252009-05-17 12:50:58 +0000538def find(domain, localedir=None, languages=None, all=False):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000539 # Get some reasonable defaults for arguments that were not supplied
Barry Warsaw95be23d2000-08-25 19:13:37 +0000540 if localedir is None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000541 localedir = _default_localedir
Barry Warsaw95be23d2000-08-25 19:13:37 +0000542 if languages is None:
543 languages = []
544 for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
545 val = os.environ.get(envar)
546 if val:
547 languages = val.split(':')
548 break
549 if 'C' not in languages:
550 languages.append('C')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000551 # now normalize and expand the languages
Barry Warsaw75f81012000-10-16 15:47:50 +0000552 nelangs = []
Barry Warsawfa488ec2000-08-25 20:26:43 +0000553 for lang in languages:
554 for nelang in _expand_lang(lang):
Barry Warsaw75f81012000-10-16 15:47:50 +0000555 if nelang not in nelangs:
556 nelangs.append(nelang)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000557 # select a language
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000558 if all:
559 result = []
560 else:
561 result = None
Barry Warsaw75f81012000-10-16 15:47:50 +0000562 for lang in nelangs:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000563 if lang == 'C':
564 break
Barry Warsaw84314b72000-08-25 19:53:17 +0000565 mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000566 if os.path.exists(mofile):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000567 if all:
568 result.append(mofile)
569 else:
570 return mofile
571 return result
Barry Warsaw95be23d2000-08-25 19:13:37 +0000572
573
Tim Peters07e99cb2001-01-14 23:47:14 +0000574
Barry Warsaw33d8d702000-08-30 03:29:58 +0000575# a mapping between absolute .mo file path and Translation object
576_translations = {}
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300577_unspecified = ['unspecified']
Barry Warsaw33d8d702000-08-30 03:29:58 +0000578
Martin v. Löwis1be64192002-01-11 06:33:28 +0000579def translation(domain, localedir=None, languages=None,
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300580 class_=None, fallback=False, codeset=_unspecified):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000581 if class_ is None:
582 class_ = GNUTranslations
Georg Brandlcd869252009-05-17 12:50:58 +0000583 mofiles = find(domain, localedir, languages, all=True)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000584 if not mofiles:
Martin v. Löwis1be64192002-01-11 06:33:28 +0000585 if fallback:
586 return NullTranslations()
Serhiy Storchaka81108372017-09-26 00:55:55 +0300587 from errno import ENOENT
588 raise FileNotFoundError(ENOENT,
589 'No translation file found for domain', domain)
Barry Warsaw293b03f2000-10-05 18:48:12 +0000590 # Avoid opening, reading, and parsing the .mo file after it's been done
591 # once.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000592 result = None
593 for mofile in mofiles:
Éric Araujo6108bf52010-10-04 23:52:37 +0000594 key = (class_, os.path.abspath(mofile))
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000595 t = _translations.get(key)
596 if t is None:
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000597 with open(mofile, 'rb') as fp:
598 t = _translations.setdefault(key, class_(fp))
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000599 # Copy the translation object to allow setting fallbacks and
600 # output charset. All other instance data is shared with the
601 # cached object.
Serhiy Storchaka81108372017-09-26 00:55:55 +0300602 # Delay copy import for speeding up gettext import when .mo files
603 # are not used.
604 import copy
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000605 t = copy.copy(t)
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300606 if codeset is not _unspecified:
607 import warnings
608 warnings.warn('parameter codeset is deprecated',
609 DeprecationWarning, 2)
610 if codeset:
611 with warnings.catch_warnings():
612 warnings.filterwarnings('ignore', r'.*\bset_output_charset\b.*',
613 DeprecationWarning)
614 t.set_output_charset(codeset)
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000615 if result is None:
616 result = t
617 else:
618 result.add_fallback(t)
619 return result
Barry Warsaw33d8d702000-08-30 03:29:58 +0000620
Tim Peters07e99cb2001-01-14 23:47:14 +0000621
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300622def install(domain, localedir=None, codeset=_unspecified, names=None):
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000623 t = translation(domain, localedir, fallback=True, codeset=codeset)
Benjamin Peterson801844d2008-07-14 14:32:15 +0000624 t.install(names)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000625
626
Tim Peters07e99cb2001-01-14 23:47:14 +0000627
Barry Warsaw33d8d702000-08-30 03:29:58 +0000628# a mapping b/w domains and locale directories
629_localedirs = {}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000630# a mapping b/w domains and codesets
631_localecodesets = {}
Barry Warsaw33d8d702000-08-30 03:29:58 +0000632# current global domain, `messages' used for compatibility w/ GNU gettext
633_current_domain = 'messages'
Barry Warsaw95be23d2000-08-25 19:13:37 +0000634
635
636def textdomain(domain=None):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000637 global _current_domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000638 if domain is not None:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000639 _current_domain = domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000640 return _current_domain
Barry Warsaw95be23d2000-08-25 19:13:37 +0000641
642
Barry Warsaw33d8d702000-08-30 03:29:58 +0000643def bindtextdomain(domain, localedir=None):
644 global _localedirs
645 if localedir is not None:
646 _localedirs[domain] = localedir
647 return _localedirs.get(domain, _default_localedir)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000648
649
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000650def bind_textdomain_codeset(domain, codeset=None):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300651 import warnings
652 warnings.warn('bind_textdomain_codeset() is deprecated',
653 DeprecationWarning, 2)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000654 global _localecodesets
655 if codeset is not None:
656 _localecodesets[domain] = codeset
657 return _localecodesets.get(domain)
658
659
Barry Warsaw95be23d2000-08-25 19:13:37 +0000660def dgettext(domain, message):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000661 try:
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300662 t = translation(domain, _localedirs.get(domain, None))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200663 except OSError:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000664 return message
665 return t.gettext(message)
Tim Peters07e99cb2001-01-14 23:47:14 +0000666
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000667def ldgettext(domain, message):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300668 import warnings
669 warnings.warn('ldgettext() is deprecated, use dgettext() instead',
670 DeprecationWarning, 2)
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300671 codeset = _localecodesets.get(domain)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000672 try:
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300673 with warnings.catch_warnings():
674 warnings.filterwarnings('ignore', r'.*\bparameter codeset\b.*',
675 DeprecationWarning)
676 t = translation(domain, _localedirs.get(domain, None), codeset=codeset)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200677 except OSError:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300678 return message.encode(codeset or locale.getpreferredencoding())
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300679 with warnings.catch_warnings():
680 warnings.filterwarnings('ignore', r'.*\blgettext\b.*',
681 DeprecationWarning)
682 return t.lgettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000683
Martin v. Löwisd8996052002-11-21 21:45:32 +0000684def dngettext(domain, msgid1, msgid2, n):
685 try:
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300686 t = translation(domain, _localedirs.get(domain, None))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200687 except OSError:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000688 if n == 1:
689 return msgid1
690 else:
691 return msgid2
692 return t.ngettext(msgid1, msgid2, n)
693
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000694def ldngettext(domain, msgid1, msgid2, n):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300695 import warnings
696 warnings.warn('ldngettext() is deprecated, use dngettext() instead',
697 DeprecationWarning, 2)
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300698 codeset = _localecodesets.get(domain)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000699 try:
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300700 with warnings.catch_warnings():
701 warnings.filterwarnings('ignore', r'.*\bparameter codeset\b.*',
702 DeprecationWarning)
703 t = translation(domain, _localedirs.get(domain, None), codeset=codeset)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200704 except OSError:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000705 if n == 1:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300706 tmsg = msgid1
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000707 else:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300708 tmsg = msgid2
709 return tmsg.encode(codeset or locale.getpreferredencoding())
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300710 with warnings.catch_warnings():
711 warnings.filterwarnings('ignore', r'.*\blngettext\b.*',
712 DeprecationWarning)
713 return t.lngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000714
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500715
716def dpgettext(domain, context, message):
717 try:
718 t = translation(domain, _localedirs.get(domain, None))
719 except OSError:
720 return message
721 return t.pgettext(context, message)
722
723
724def dnpgettext(domain, context, msgid1, msgid2, n):
725 try:
726 t = translation(domain, _localedirs.get(domain, None))
727 except OSError:
728 if n == 1:
729 return msgid1
730 else:
731 return msgid2
732 return t.npgettext(context, msgid1, msgid2, n)
733
734
Barry Warsaw33d8d702000-08-30 03:29:58 +0000735def gettext(message):
736 return dgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000737
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000738def lgettext(message):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300739 import warnings
740 warnings.warn('lgettext() is deprecated, use gettext() instead',
741 DeprecationWarning, 2)
742 with warnings.catch_warnings():
743 warnings.filterwarnings('ignore', r'.*\bldgettext\b.*',
744 DeprecationWarning)
745 return ldgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000746
Martin v. Löwisd8996052002-11-21 21:45:32 +0000747def ngettext(msgid1, msgid2, n):
748 return dngettext(_current_domain, msgid1, msgid2, n)
749
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000750def lngettext(msgid1, msgid2, n):
Serhiy Storchakafec35c92018-10-27 08:00:41 +0300751 import warnings
752 warnings.warn('lngettext() is deprecated, use ngettext() instead',
753 DeprecationWarning, 2)
754 with warnings.catch_warnings():
755 warnings.filterwarnings('ignore', r'.*\bldngettext\b.*',
756 DeprecationWarning)
757 return ldngettext(_current_domain, msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000758
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500759
760def pgettext(context, message):
761 return dpgettext(_current_domain, context, message)
762
763
764def npgettext(context, msgid1, msgid2, n):
765 return dnpgettext(_current_domain, context, msgid1, msgid2, n)
766
767
Barry Warsaw33d8d702000-08-30 03:29:58 +0000768# dcgettext() has been deemed unnecessary and is not implemented.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000769
Barry Warsaw33d8d702000-08-30 03:29:58 +0000770# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
771# was:
772#
773# import gettext
774# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
775# _ = cat.gettext
776# print _('Hello World')
Barry Warsaw95be23d2000-08-25 19:13:37 +0000777
Barry Warsaw33d8d702000-08-30 03:29:58 +0000778# The resulting catalog object currently don't support access through a
779# dictionary API, which was supported (but apparently unused) in GNOME
780# gettext.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000781
Barry Warsaw33d8d702000-08-30 03:29:58 +0000782Catalog = translation