blob: 5ad7ff6bfcee3b0712a5c91e9a449bb2dff3e612 [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 copy
50import locale
51import os
52import re
53import struct
54import sys
Barry Warsaw33d8d702000-08-30 03:29:58 +000055from errno import ENOENT
Barry Warsaw95be23d2000-08-25 19:13:37 +000056
Martin v. Löwisd8996052002-11-21 21:45:32 +000057
Barry Warsawa1ce93f2003-04-11 18:36:43 +000058__all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
59 'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
Andrew Kuchling770b08e2015-04-13 09:58:36 -040060 'bind_textdomain_codeset',
61 'dgettext', 'dngettext', 'gettext', 'lgettext', 'ldgettext',
62 'ldngettext', 'lngettext', 'ngettext',
Barry Warsawa1ce93f2003-04-11 18:36:43 +000063 ]
Skip Montanaro2dd42762001-01-23 15:35:05 +000064
Vinay Sajip7ded1f02012-05-26 03:45:29 +010065_default_localedir = os.path.join(sys.base_prefix, 'share', 'locale')
Barry Warsaw95be23d2000-08-25 19:13:37 +000066
Serhiy Storchaka07bcf052016-11-08 21:17:46 +020067# Expression parsing for plural form selection.
68#
69# The gettext library supports a small subset of C syntax. The only
70# incompatible difference is that integer literals starting with zero are
71# decimal.
72#
73# https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms
74# http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y
75
76_token_pattern = re.compile(r"""
77 (?P<WHITESPACES>[ \t]+) | # spaces and horizontal tabs
78 (?P<NUMBER>[0-9]+\b) | # decimal integer
79 (?P<NAME>n\b) | # only n is allowed
80 (?P<PARENTHESIS>[()]) |
81 (?P<OPERATOR>[-*/%+?:]|[><!]=?|==|&&|\|\|) | # !, *, /, %, +, -, <, >,
82 # <=, >=, ==, !=, &&, ||,
83 # ? :
84 # unary and bitwise ops
85 # not allowed
86 (?P<INVALID>\w+|.) # invalid token
87 """, re.VERBOSE|re.DOTALL)
88
89def _tokenize(plural):
90 for mo in re.finditer(_token_pattern, plural):
91 kind = mo.lastgroup
92 if kind == 'WHITESPACES':
93 continue
94 value = mo.group(kind)
95 if kind == 'INVALID':
96 raise ValueError('invalid token in plural form: %s' % value)
97 yield value
98 yield ''
99
100def _error(value):
101 if value:
102 return ValueError('unexpected token in plural form: %s' % value)
103 else:
104 return ValueError('unexpected end of plural form')
105
106_binary_ops = (
107 ('||',),
108 ('&&',),
109 ('==', '!='),
110 ('<', '>', '<=', '>='),
111 ('+', '-'),
112 ('*', '/', '%'),
113)
114_binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops}
115_c2py_ops = {'||': 'or', '&&': 'and', '/': '//'}
116
117def _parse(tokens, priority=-1):
118 result = ''
119 nexttok = next(tokens)
120 while nexttok == '!':
121 result += 'not '
122 nexttok = next(tokens)
123
124 if nexttok == '(':
125 sub, nexttok = _parse(tokens)
126 result = '%s(%s)' % (result, sub)
127 if nexttok != ')':
128 raise ValueError('unbalanced parenthesis in plural form')
129 elif nexttok == 'n':
130 result = '%s%s' % (result, nexttok)
131 else:
132 try:
133 value = int(nexttok, 10)
134 except ValueError:
135 raise _error(nexttok) from None
136 result = '%s%d' % (result, value)
137 nexttok = next(tokens)
138
139 j = 100
140 while nexttok in _binary_ops:
141 i = _binary_ops[nexttok]
142 if i < priority:
143 break
144 # Break chained comparisons
145 if i in (3, 4) and j in (3, 4): # '==', '!=', '<', '>', '<=', '>='
146 result = '(%s)' % result
147 # Replace some C operators by their Python equivalents
148 op = _c2py_ops.get(nexttok, nexttok)
149 right, nexttok = _parse(tokens, i + 1)
150 result = '%s %s %s' % (result, op, right)
151 j = i
152 if j == priority == 4: # '<', '>', '<=', '>='
153 result = '(%s)' % result
154
155 if nexttok == '?' and priority <= 0:
156 if_true, nexttok = _parse(tokens, 0)
157 if nexttok != ':':
158 raise _error(nexttok)
159 if_false, nexttok = _parse(tokens)
160 result = '%s if %s else %s' % (if_true, result, if_false)
161 if priority == 0:
162 result = '(%s)' % result
163
164 return result, nexttok
Barry Warsaw95be23d2000-08-25 19:13:37 +0000165
Serhiy Storchaka60ac9892016-11-14 19:22:12 +0200166def _as_int(n):
167 try:
168 i = round(n)
169 except TypeError:
170 raise TypeError('Plural value must be an integer, got %s' %
171 (n.__class__.__name__,)) from None
Serhiy Storchakaf6595982017-03-12 13:15:01 +0200172 import warnings
173 warnings.warn('Plural value must be an integer, got %s' %
174 (n.__class__.__name__,),
175 DeprecationWarning, 4)
Serhiy Storchaka60ac9892016-11-14 19:22:12 +0200176 return n
177
Martin v. Löwisd8996052002-11-21 21:45:32 +0000178def c2py(plural):
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000179 """Gets a C expression as used in PO files for plural forms and returns a
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200180 Python function that implements an equivalent expression.
Martin v. Löwisd8996052002-11-21 21:45:32 +0000181 """
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200182
183 if len(plural) > 1000:
184 raise ValueError('plural form expression is too long')
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000185 try:
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200186 result, nexttok = _parse(_tokenize(plural))
187 if nexttok:
188 raise _error(nexttok)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000189
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200190 depth = 0
191 for c in result:
192 if c == '(':
193 depth += 1
194 if depth > 20:
195 # Python compiler limit is about 90.
196 # The most complex example has 2.
197 raise ValueError('plural form expression is too complex')
198 elif c == ')':
199 depth -= 1
Martin v. Löwisd8996052002-11-21 21:45:32 +0000200
Serhiy Storchaka60ac9892016-11-14 19:22:12 +0200201 ns = {'_as_int': _as_int}
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200202 exec('''if True:
203 def func(n):
204 if not isinstance(n, int):
Serhiy Storchaka60ac9892016-11-14 19:22:12 +0200205 n = _as_int(n)
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200206 return int(%s)
207 ''' % result, ns)
208 return ns['func']
Serhiy Storchakaeb20fca2016-11-08 21:26:14 +0200209 except RecursionError:
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200210 # Recursion error can be raised in _parse() or exec().
211 raise ValueError('plural form expression is too complex')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000212
Tim Peters07e99cb2001-01-14 23:47:14 +0000213
Benjamin Peterson31e87202010-12-23 22:53:42 +0000214def _expand_lang(loc):
215 loc = locale.normalize(loc)
Barry Warsawfa488ec2000-08-25 20:26:43 +0000216 COMPONENT_CODESET = 1 << 0
217 COMPONENT_TERRITORY = 1 << 1
218 COMPONENT_MODIFIER = 1 << 2
219 # split up the locale into its base components
220 mask = 0
Benjamin Peterson31e87202010-12-23 22:53:42 +0000221 pos = loc.find('@')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000222 if pos >= 0:
Benjamin Peterson31e87202010-12-23 22:53:42 +0000223 modifier = loc[pos:]
224 loc = loc[:pos]
Barry Warsawfa488ec2000-08-25 20:26:43 +0000225 mask |= COMPONENT_MODIFIER
226 else:
227 modifier = ''
Benjamin Peterson31e87202010-12-23 22:53:42 +0000228 pos = loc.find('.')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000229 if pos >= 0:
Benjamin Peterson31e87202010-12-23 22:53:42 +0000230 codeset = loc[pos:]
231 loc = loc[:pos]
Barry Warsawfa488ec2000-08-25 20:26:43 +0000232 mask |= COMPONENT_CODESET
233 else:
234 codeset = ''
Benjamin Peterson31e87202010-12-23 22:53:42 +0000235 pos = loc.find('_')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000236 if pos >= 0:
Benjamin Peterson31e87202010-12-23 22:53:42 +0000237 territory = loc[pos:]
238 loc = loc[:pos]
Barry Warsawfa488ec2000-08-25 20:26:43 +0000239 mask |= COMPONENT_TERRITORY
240 else:
241 territory = ''
Benjamin Peterson31e87202010-12-23 22:53:42 +0000242 language = loc
Barry Warsawfa488ec2000-08-25 20:26:43 +0000243 ret = []
244 for i in range(mask+1):
245 if not (i & ~mask): # if all components for this combo exist ...
246 val = language
247 if i & COMPONENT_TERRITORY: val += territory
248 if i & COMPONENT_CODESET: val += codeset
249 if i & COMPONENT_MODIFIER: val += modifier
250 ret.append(val)
251 ret.reverse()
252 return ret
253
254
Tim Peters07e99cb2001-01-14 23:47:14 +0000255
Barry Warsaw33d8d702000-08-30 03:29:58 +0000256class NullTranslations:
257 def __init__(self, fp=None):
258 self._info = {}
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000259 self._charset = None
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000260 self._output_charset = None
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000261 self._fallback = None
Raymond Hettinger094662a2002-06-01 01:29:16 +0000262 if fp is not None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000263 self._parse(fp)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000264
Barry Warsaw33d8d702000-08-30 03:29:58 +0000265 def _parse(self, fp):
266 pass
267
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000268 def add_fallback(self, fallback):
269 if self._fallback:
270 self._fallback.add_fallback(fallback)
271 else:
272 self._fallback = fallback
273
Barry Warsaw33d8d702000-08-30 03:29:58 +0000274 def gettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000275 if self._fallback:
276 return self._fallback.gettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000277 return message
278
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000279 def lgettext(self, message):
280 if self._fallback:
281 return self._fallback.lgettext(message)
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300282 if self._output_charset:
283 return message.encode(self._output_charset)
284 return message.encode(locale.getpreferredencoding())
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000285
Martin v. Löwisd8996052002-11-21 21:45:32 +0000286 def ngettext(self, msgid1, msgid2, n):
287 if self._fallback:
288 return self._fallback.ngettext(msgid1, msgid2, n)
289 if n == 1:
290 return msgid1
291 else:
292 return msgid2
293
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000294 def lngettext(self, msgid1, msgid2, n):
295 if self._fallback:
296 return self._fallback.lngettext(msgid1, msgid2, n)
297 if n == 1:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300298 tmsg = msgid1
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000299 else:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300300 tmsg = msgid2
301 if self._output_charset:
302 return tmsg.encode(self._output_charset)
303 return tmsg.encode(locale.getpreferredencoding())
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000304
Barry Warsaw33d8d702000-08-30 03:29:58 +0000305 def info(self):
306 return self._info
307
308 def charset(self):
309 return self._charset
310
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000311 def output_charset(self):
312 return self._output_charset
313
314 def set_output_charset(self, charset):
315 self._output_charset = charset
316
Benjamin Peterson801844d2008-07-14 14:32:15 +0000317 def install(self, names=None):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000318 import builtins
Benjamin Peterson801844d2008-07-14 14:32:15 +0000319 builtins.__dict__['_'] = self.gettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000320 if hasattr(names, "__contains__"):
321 if "gettext" in names:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000322 builtins.__dict__['gettext'] = builtins.__dict__['_']
Georg Brandl602b9ba2006-02-19 13:26:36 +0000323 if "ngettext" in names:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000324 builtins.__dict__['ngettext'] = self.ngettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000325 if "lgettext" in names:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000326 builtins.__dict__['lgettext'] = self.lgettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000327 if "lngettext" in names:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000328 builtins.__dict__['lngettext'] = self.lngettext
Barry Warsaw33d8d702000-08-30 03:29:58 +0000329
330
331class GNUTranslations(NullTranslations):
332 # Magic number of .mo files
Guido van Rossume2a383d2007-01-15 16:59:06 +0000333 LE_MAGIC = 0x950412de
334 BE_MAGIC = 0xde120495
Barry Warsaw95be23d2000-08-25 19:13:37 +0000335
Antoine Pitroube8d06f2014-10-28 20:17:51 +0100336 # Acceptable .mo versions
337 VERSIONS = (0, 1)
338
339 def _get_versions(self, version):
340 """Returns a tuple of major version, minor version"""
341 return (version >> 16, version & 0xffff)
342
Barry Warsaw95be23d2000-08-25 19:13:37 +0000343 def _parse(self, fp):
344 """Override this method to support alternative .mo formats."""
345 unpack = struct.unpack
346 filename = getattr(fp, 'name', '')
347 # Parse the .mo file header, which consists of 5 little endian 32
348 # bit words.
Barry Warsaw33d8d702000-08-30 03:29:58 +0000349 self._catalog = catalog = {}
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000350 self.plural = lambda n: int(n != 1) # germanic plural by default
Barry Warsaw95be23d2000-08-25 19:13:37 +0000351 buf = fp.read()
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000352 buflen = len(buf)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000353 # Are we big endian or little endian?
Barry Warsaw09707e32002-08-14 15:09:12 +0000354 magic = unpack('<I', buf[:4])[0]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000355 if magic == self.LE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000356 version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
357 ii = '<II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000358 elif magic == self.BE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000359 version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
360 ii = '>II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000361 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200362 raise OSError(0, 'Bad magic number', filename)
Antoine Pitroube8d06f2014-10-28 20:17:51 +0100363
364 major_version, minor_version = self._get_versions(version)
365
366 if major_version not in self.VERSIONS:
367 raise OSError(0, 'Bad version number ' + str(major_version), filename)
368
Barry Warsaw95be23d2000-08-25 19:13:37 +0000369 # Now put all messages from the .mo file buffer into the catalog
370 # dictionary.
Guido van Rossum805365e2007-05-07 22:24:25 +0000371 for i in range(0, msgcount):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000372 mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000373 mend = moff + mlen
Barry Warsaw33d8d702000-08-30 03:29:58 +0000374 tlen, toff = unpack(ii, buf[transidx:transidx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000375 tend = toff + tlen
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000376 if mend < buflen and tend < buflen:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000377 msg = buf[moff:mend]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000378 tmsg = buf[toff:tend]
Barry Warsaw95be23d2000-08-25 19:13:37 +0000379 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200380 raise OSError(0, 'File is corrupt', filename)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000381 # See if we're looking at GNU .mo conventions for metadata
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000382 if mlen == 0:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000383 # Catalog description
Andrew Kuchling8b963c52015-04-13 10:38:56 -0400384 lastk = None
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300385 for b_item in tmsg.split(b'\n'):
Guido van Rossum98297ee2007-11-06 21:34:58 +0000386 item = b_item.decode().strip()
Barry Warsaw33d8d702000-08-30 03:29:58 +0000387 if not item:
388 continue
Andrew Kuchling8b963c52015-04-13 10:38:56 -0400389 k = v = None
Barry Warsaw7de63f52003-05-20 17:26:48 +0000390 if ':' in item:
391 k, v = item.split(':', 1)
392 k = k.strip().lower()
393 v = v.strip()
394 self._info[k] = v
395 lastk = k
396 elif lastk:
397 self._info[lastk] += '\n' + item
Barry Warsaw33d8d702000-08-30 03:29:58 +0000398 if k == 'content-type':
399 self._charset = v.split('charset=')[1]
Martin v. Löwisd8996052002-11-21 21:45:32 +0000400 elif k == 'plural-forms':
401 v = v.split(';')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000402 plural = v[1].split('plural=')[1]
403 self.plural = c2py(plural)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000404 # Note: we unconditionally convert both msgids and msgstrs to
405 # Unicode using the character encoding specified in the charset
406 # parameter of the Content-Type header. The gettext documentation
Ezio Melotti42da6632011-03-15 05:18:48 +0200407 # strongly encourages msgids to be us-ascii, but some applications
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000408 # require alternative encodings (e.g. Zope's ZCML and ZPT). For
409 # traditional gettext applications, the msgid conversion will
410 # cause no problems since us-ascii should always be a subset of
411 # the charset encoding. We may want to fall back to 8-bit msgids
412 # if the Unicode conversion fails.
Georg Brandlbded4d32008-07-17 18:15:35 +0000413 charset = self._charset or 'ascii'
Guido van Rossum652f4462007-07-12 08:04:06 +0000414 if b'\x00' in msg:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000415 # Plural forms
Guido van Rossum9600f932007-08-29 03:08:55 +0000416 msgid1, msgid2 = msg.split(b'\x00')
417 tmsg = tmsg.split(b'\x00')
Georg Brandlbded4d32008-07-17 18:15:35 +0000418 msgid1 = str(msgid1, charset)
419 for i, x in enumerate(tmsg):
420 catalog[(msgid1, i)] = str(x, charset)
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000421 else:
Georg Brandlbded4d32008-07-17 18:15:35 +0000422 catalog[str(msg, charset)] = str(tmsg, charset)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000423 # advance to next entry in the seek tables
Barry Warsawfa488ec2000-08-25 20:26:43 +0000424 masteridx += 8
425 transidx += 8
Barry Warsaw33d8d702000-08-30 03:29:58 +0000426
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000427 def lgettext(self, message):
428 missing = object()
429 tmsg = self._catalog.get(message, missing)
430 if tmsg is missing:
431 if self._fallback:
432 return self._fallback.lgettext(message)
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300433 tmsg = message
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000434 if self._output_charset:
435 return tmsg.encode(self._output_charset)
436 return tmsg.encode(locale.getpreferredencoding())
437
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000438 def lngettext(self, msgid1, msgid2, n):
439 try:
440 tmsg = self._catalog[(msgid1, self.plural(n))]
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000441 except KeyError:
442 if self._fallback:
443 return self._fallback.lngettext(msgid1, msgid2, n)
444 if n == 1:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300445 tmsg = msgid1
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000446 else:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300447 tmsg = msgid2
448 if self._output_charset:
449 return tmsg.encode(self._output_charset)
450 return tmsg.encode(locale.getpreferredencoding())
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000451
Benjamin Peterson801844d2008-07-14 14:32:15 +0000452 def gettext(self, message):
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000453 missing = object()
454 tmsg = self._catalog.get(message, missing)
455 if tmsg is missing:
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000456 if self._fallback:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000457 return self._fallback.gettext(message)
Georg Brandlbded4d32008-07-17 18:15:35 +0000458 return message
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000459 return tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000460
Benjamin Peterson801844d2008-07-14 14:32:15 +0000461 def ngettext(self, msgid1, msgid2, n):
Martin v. Löwisd8996052002-11-21 21:45:32 +0000462 try:
463 tmsg = self._catalog[(msgid1, self.plural(n))]
464 except KeyError:
465 if self._fallback:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000466 return self._fallback.ngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000467 if n == 1:
Georg Brandlbded4d32008-07-17 18:15:35 +0000468 tmsg = msgid1
Martin v. Löwisd8996052002-11-21 21:45:32 +0000469 else:
Georg Brandlbded4d32008-07-17 18:15:35 +0000470 tmsg = msgid2
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000471 return tmsg
Martin v. Löwisd8996052002-11-21 21:45:32 +0000472
Tim Peters07e99cb2001-01-14 23:47:14 +0000473
Barry Warsaw95be23d2000-08-25 19:13:37 +0000474# Locate a .mo file using the gettext strategy
Georg Brandlcd869252009-05-17 12:50:58 +0000475def find(domain, localedir=None, languages=None, all=False):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000476 # Get some reasonable defaults for arguments that were not supplied
Barry Warsaw95be23d2000-08-25 19:13:37 +0000477 if localedir is None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000478 localedir = _default_localedir
Barry Warsaw95be23d2000-08-25 19:13:37 +0000479 if languages is None:
480 languages = []
481 for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
482 val = os.environ.get(envar)
483 if val:
484 languages = val.split(':')
485 break
486 if 'C' not in languages:
487 languages.append('C')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000488 # now normalize and expand the languages
Barry Warsaw75f81012000-10-16 15:47:50 +0000489 nelangs = []
Barry Warsawfa488ec2000-08-25 20:26:43 +0000490 for lang in languages:
491 for nelang in _expand_lang(lang):
Barry Warsaw75f81012000-10-16 15:47:50 +0000492 if nelang not in nelangs:
493 nelangs.append(nelang)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000494 # select a language
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000495 if all:
496 result = []
497 else:
498 result = None
Barry Warsaw75f81012000-10-16 15:47:50 +0000499 for lang in nelangs:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000500 if lang == 'C':
501 break
Barry Warsaw84314b72000-08-25 19:53:17 +0000502 mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000503 if os.path.exists(mofile):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000504 if all:
505 result.append(mofile)
506 else:
507 return mofile
508 return result
Barry Warsaw95be23d2000-08-25 19:13:37 +0000509
510
Tim Peters07e99cb2001-01-14 23:47:14 +0000511
Barry Warsaw33d8d702000-08-30 03:29:58 +0000512# a mapping between absolute .mo file path and Translation object
513_translations = {}
514
Martin v. Löwis1be64192002-01-11 06:33:28 +0000515def translation(domain, localedir=None, languages=None,
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000516 class_=None, fallback=False, codeset=None):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000517 if class_ is None:
518 class_ = GNUTranslations
Georg Brandlcd869252009-05-17 12:50:58 +0000519 mofiles = find(domain, localedir, languages, all=True)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000520 if not mofiles:
Martin v. Löwis1be64192002-01-11 06:33:28 +0000521 if fallback:
522 return NullTranslations()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200523 raise OSError(ENOENT, 'No translation file found for domain', domain)
Barry Warsaw293b03f2000-10-05 18:48:12 +0000524 # Avoid opening, reading, and parsing the .mo file after it's been done
525 # once.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000526 result = None
527 for mofile in mofiles:
Éric Araujo6108bf52010-10-04 23:52:37 +0000528 key = (class_, os.path.abspath(mofile))
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000529 t = _translations.get(key)
530 if t is None:
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000531 with open(mofile, 'rb') as fp:
532 t = _translations.setdefault(key, class_(fp))
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000533 # Copy the translation object to allow setting fallbacks and
534 # output charset. All other instance data is shared with the
535 # cached object.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000536 t = copy.copy(t)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000537 if codeset:
538 t.set_output_charset(codeset)
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000539 if result is None:
540 result = t
541 else:
542 result.add_fallback(t)
543 return result
Barry Warsaw33d8d702000-08-30 03:29:58 +0000544
Tim Peters07e99cb2001-01-14 23:47:14 +0000545
Benjamin Peterson801844d2008-07-14 14:32:15 +0000546def install(domain, localedir=None, codeset=None, names=None):
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000547 t = translation(domain, localedir, fallback=True, codeset=codeset)
Benjamin Peterson801844d2008-07-14 14:32:15 +0000548 t.install(names)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000549
550
Tim Peters07e99cb2001-01-14 23:47:14 +0000551
Barry Warsaw33d8d702000-08-30 03:29:58 +0000552# a mapping b/w domains and locale directories
553_localedirs = {}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000554# a mapping b/w domains and codesets
555_localecodesets = {}
Barry Warsaw33d8d702000-08-30 03:29:58 +0000556# current global domain, `messages' used for compatibility w/ GNU gettext
557_current_domain = 'messages'
Barry Warsaw95be23d2000-08-25 19:13:37 +0000558
559
560def textdomain(domain=None):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000561 global _current_domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000562 if domain is not None:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000563 _current_domain = domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000564 return _current_domain
Barry Warsaw95be23d2000-08-25 19:13:37 +0000565
566
Barry Warsaw33d8d702000-08-30 03:29:58 +0000567def bindtextdomain(domain, localedir=None):
568 global _localedirs
569 if localedir is not None:
570 _localedirs[domain] = localedir
571 return _localedirs.get(domain, _default_localedir)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000572
573
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000574def bind_textdomain_codeset(domain, codeset=None):
575 global _localecodesets
576 if codeset is not None:
577 _localecodesets[domain] = codeset
578 return _localecodesets.get(domain)
579
580
Barry Warsaw95be23d2000-08-25 19:13:37 +0000581def dgettext(domain, message):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000582 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000583 t = translation(domain, _localedirs.get(domain, None),
584 codeset=_localecodesets.get(domain))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200585 except OSError:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000586 return message
587 return t.gettext(message)
Tim Peters07e99cb2001-01-14 23:47:14 +0000588
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000589def ldgettext(domain, message):
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300590 codeset = _localecodesets.get(domain)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000591 try:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300592 t = translation(domain, _localedirs.get(domain, None), codeset=codeset)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200593 except OSError:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300594 return message.encode(codeset or locale.getpreferredencoding())
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000595 return t.lgettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000596
Martin v. Löwisd8996052002-11-21 21:45:32 +0000597def dngettext(domain, msgid1, msgid2, n):
598 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000599 t = translation(domain, _localedirs.get(domain, None),
600 codeset=_localecodesets.get(domain))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200601 except OSError:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000602 if n == 1:
603 return msgid1
604 else:
605 return msgid2
606 return t.ngettext(msgid1, msgid2, n)
607
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000608def ldngettext(domain, msgid1, msgid2, n):
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300609 codeset = _localecodesets.get(domain)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000610 try:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300611 t = translation(domain, _localedirs.get(domain, None), codeset=codeset)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200612 except OSError:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000613 if n == 1:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300614 tmsg = msgid1
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000615 else:
Serhiy Storchaka26cb4652017-06-20 17:13:29 +0300616 tmsg = msgid2
617 return tmsg.encode(codeset or locale.getpreferredencoding())
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000618 return t.lngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000619
Barry Warsaw33d8d702000-08-30 03:29:58 +0000620def gettext(message):
621 return dgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000622
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000623def lgettext(message):
624 return ldgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000625
Martin v. Löwisd8996052002-11-21 21:45:32 +0000626def ngettext(msgid1, msgid2, n):
627 return dngettext(_current_domain, msgid1, msgid2, n)
628
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000629def lngettext(msgid1, msgid2, n):
630 return ldngettext(_current_domain, msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000631
Barry Warsaw33d8d702000-08-30 03:29:58 +0000632# dcgettext() has been deemed unnecessary and is not implemented.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000633
Barry Warsaw33d8d702000-08-30 03:29:58 +0000634# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
635# was:
636#
637# import gettext
638# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
639# _ = cat.gettext
640# print _('Hello World')
Barry Warsaw95be23d2000-08-25 19:13:37 +0000641
Barry Warsaw33d8d702000-08-30 03:29:58 +0000642# The resulting catalog object currently don't support access through a
643# dictionary API, which was supported (but apparently unused) in GNOME
644# gettext.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000645
Barry Warsaw33d8d702000-08-30 03:29:58 +0000646Catalog = translation