blob: 7032efae7ffa876f182358f1fb2b49ceec0def26 [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
Benjamin Peterson31e87202010-12-23 22:53:42 +000049import locale, copy, io, os, re, struct, sys
Barry Warsaw33d8d702000-08-30 03:29:58 +000050from errno import ENOENT
Barry Warsaw95be23d2000-08-25 19:13:37 +000051
Martin v. Löwisd8996052002-11-21 21:45:32 +000052
Barry Warsawa1ce93f2003-04-11 18:36:43 +000053__all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
54 'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
Andrew Kuchling770b08e2015-04-13 09:58:36 -040055 'bind_textdomain_codeset',
56 'dgettext', 'dngettext', 'gettext', 'lgettext', 'ldgettext',
57 'ldngettext', 'lngettext', 'ngettext',
Barry Warsawa1ce93f2003-04-11 18:36:43 +000058 ]
Skip Montanaro2dd42762001-01-23 15:35:05 +000059
Vinay Sajip7ded1f02012-05-26 03:45:29 +010060_default_localedir = os.path.join(sys.base_prefix, 'share', 'locale')
Barry Warsaw95be23d2000-08-25 19:13:37 +000061
Serhiy Storchaka07bcf052016-11-08 21:17:46 +020062# Expression parsing for plural form selection.
63#
64# The gettext library supports a small subset of C syntax. The only
65# incompatible difference is that integer literals starting with zero are
66# decimal.
67#
68# https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms
69# http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y
70
71_token_pattern = re.compile(r"""
72 (?P<WHITESPACES>[ \t]+) | # spaces and horizontal tabs
73 (?P<NUMBER>[0-9]+\b) | # decimal integer
74 (?P<NAME>n\b) | # only n is allowed
75 (?P<PARENTHESIS>[()]) |
76 (?P<OPERATOR>[-*/%+?:]|[><!]=?|==|&&|\|\|) | # !, *, /, %, +, -, <, >,
77 # <=, >=, ==, !=, &&, ||,
78 # ? :
79 # unary and bitwise ops
80 # not allowed
81 (?P<INVALID>\w+|.) # invalid token
82 """, re.VERBOSE|re.DOTALL)
83
84def _tokenize(plural):
85 for mo in re.finditer(_token_pattern, plural):
86 kind = mo.lastgroup
87 if kind == 'WHITESPACES':
88 continue
89 value = mo.group(kind)
90 if kind == 'INVALID':
91 raise ValueError('invalid token in plural form: %s' % value)
92 yield value
93 yield ''
94
95def _error(value):
96 if value:
97 return ValueError('unexpected token in plural form: %s' % value)
98 else:
99 return ValueError('unexpected end of plural form')
100
101_binary_ops = (
102 ('||',),
103 ('&&',),
104 ('==', '!='),
105 ('<', '>', '<=', '>='),
106 ('+', '-'),
107 ('*', '/', '%'),
108)
109_binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops}
110_c2py_ops = {'||': 'or', '&&': 'and', '/': '//'}
111
112def _parse(tokens, priority=-1):
113 result = ''
114 nexttok = next(tokens)
115 while nexttok == '!':
116 result += 'not '
117 nexttok = next(tokens)
118
119 if nexttok == '(':
120 sub, nexttok = _parse(tokens)
121 result = '%s(%s)' % (result, sub)
122 if nexttok != ')':
123 raise ValueError('unbalanced parenthesis in plural form')
124 elif nexttok == 'n':
125 result = '%s%s' % (result, nexttok)
126 else:
127 try:
128 value = int(nexttok, 10)
129 except ValueError:
130 raise _error(nexttok) from None
131 result = '%s%d' % (result, value)
132 nexttok = next(tokens)
133
134 j = 100
135 while nexttok in _binary_ops:
136 i = _binary_ops[nexttok]
137 if i < priority:
138 break
139 # Break chained comparisons
140 if i in (3, 4) and j in (3, 4): # '==', '!=', '<', '>', '<=', '>='
141 result = '(%s)' % result
142 # Replace some C operators by their Python equivalents
143 op = _c2py_ops.get(nexttok, nexttok)
144 right, nexttok = _parse(tokens, i + 1)
145 result = '%s %s %s' % (result, op, right)
146 j = i
147 if j == priority == 4: # '<', '>', '<=', '>='
148 result = '(%s)' % result
149
150 if nexttok == '?' and priority <= 0:
151 if_true, nexttok = _parse(tokens, 0)
152 if nexttok != ':':
153 raise _error(nexttok)
154 if_false, nexttok = _parse(tokens)
155 result = '%s if %s else %s' % (if_true, result, if_false)
156 if priority == 0:
157 result = '(%s)' % result
158
159 return result, nexttok
Barry Warsaw95be23d2000-08-25 19:13:37 +0000160
Martin v. Löwisd8996052002-11-21 21:45:32 +0000161def c2py(plural):
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000162 """Gets a C expression as used in PO files for plural forms and returns a
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200163 Python function that implements an equivalent expression.
Martin v. Löwisd8996052002-11-21 21:45:32 +0000164 """
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200165
166 if len(plural) > 1000:
167 raise ValueError('plural form expression is too long')
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000168 try:
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200169 result, nexttok = _parse(_tokenize(plural))
170 if nexttok:
171 raise _error(nexttok)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000172
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200173 depth = 0
174 for c in result:
175 if c == '(':
176 depth += 1
177 if depth > 20:
178 # Python compiler limit is about 90.
179 # The most complex example has 2.
180 raise ValueError('plural form expression is too complex')
181 elif c == ')':
182 depth -= 1
Martin v. Löwisd8996052002-11-21 21:45:32 +0000183
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200184 ns = {}
185 exec('''if True:
186 def func(n):
187 if not isinstance(n, int):
188 raise ValueError('Plural value must be an integer.')
189 return int(%s)
190 ''' % result, ns)
191 return ns['func']
Serhiy Storchakaeb20fca2016-11-08 21:26:14 +0200192 except RecursionError:
Serhiy Storchaka07bcf052016-11-08 21:17:46 +0200193 # Recursion error can be raised in _parse() or exec().
194 raise ValueError('plural form expression is too complex')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000195
Tim Peters07e99cb2001-01-14 23:47:14 +0000196
Benjamin Peterson31e87202010-12-23 22:53:42 +0000197def _expand_lang(loc):
198 loc = locale.normalize(loc)
Barry Warsawfa488ec2000-08-25 20:26:43 +0000199 COMPONENT_CODESET = 1 << 0
200 COMPONENT_TERRITORY = 1 << 1
201 COMPONENT_MODIFIER = 1 << 2
202 # split up the locale into its base components
203 mask = 0
Benjamin Peterson31e87202010-12-23 22:53:42 +0000204 pos = loc.find('@')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000205 if pos >= 0:
Benjamin Peterson31e87202010-12-23 22:53:42 +0000206 modifier = loc[pos:]
207 loc = loc[:pos]
Barry Warsawfa488ec2000-08-25 20:26:43 +0000208 mask |= COMPONENT_MODIFIER
209 else:
210 modifier = ''
Benjamin Peterson31e87202010-12-23 22:53:42 +0000211 pos = loc.find('.')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000212 if pos >= 0:
Benjamin Peterson31e87202010-12-23 22:53:42 +0000213 codeset = loc[pos:]
214 loc = loc[:pos]
Barry Warsawfa488ec2000-08-25 20:26:43 +0000215 mask |= COMPONENT_CODESET
216 else:
217 codeset = ''
Benjamin Peterson31e87202010-12-23 22:53:42 +0000218 pos = loc.find('_')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000219 if pos >= 0:
Benjamin Peterson31e87202010-12-23 22:53:42 +0000220 territory = loc[pos:]
221 loc = loc[:pos]
Barry Warsawfa488ec2000-08-25 20:26:43 +0000222 mask |= COMPONENT_TERRITORY
223 else:
224 territory = ''
Benjamin Peterson31e87202010-12-23 22:53:42 +0000225 language = loc
Barry Warsawfa488ec2000-08-25 20:26:43 +0000226 ret = []
227 for i in range(mask+1):
228 if not (i & ~mask): # if all components for this combo exist ...
229 val = language
230 if i & COMPONENT_TERRITORY: val += territory
231 if i & COMPONENT_CODESET: val += codeset
232 if i & COMPONENT_MODIFIER: val += modifier
233 ret.append(val)
234 ret.reverse()
235 return ret
236
237
Tim Peters07e99cb2001-01-14 23:47:14 +0000238
Barry Warsaw33d8d702000-08-30 03:29:58 +0000239class NullTranslations:
240 def __init__(self, fp=None):
241 self._info = {}
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000242 self._charset = None
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000243 self._output_charset = None
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000244 self._fallback = None
Raymond Hettinger094662a2002-06-01 01:29:16 +0000245 if fp is not None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000246 self._parse(fp)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000247
Barry Warsaw33d8d702000-08-30 03:29:58 +0000248 def _parse(self, fp):
249 pass
250
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000251 def add_fallback(self, fallback):
252 if self._fallback:
253 self._fallback.add_fallback(fallback)
254 else:
255 self._fallback = fallback
256
Barry Warsaw33d8d702000-08-30 03:29:58 +0000257 def gettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000258 if self._fallback:
259 return self._fallback.gettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000260 return message
261
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000262 def lgettext(self, message):
263 if self._fallback:
264 return self._fallback.lgettext(message)
265 return message
266
Martin v. Löwisd8996052002-11-21 21:45:32 +0000267 def ngettext(self, msgid1, msgid2, n):
268 if self._fallback:
269 return self._fallback.ngettext(msgid1, msgid2, n)
270 if n == 1:
271 return msgid1
272 else:
273 return msgid2
274
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000275 def lngettext(self, msgid1, msgid2, n):
276 if self._fallback:
277 return self._fallback.lngettext(msgid1, msgid2, n)
278 if n == 1:
279 return msgid1
280 else:
281 return msgid2
282
Barry Warsaw33d8d702000-08-30 03:29:58 +0000283 def info(self):
284 return self._info
285
286 def charset(self):
287 return self._charset
288
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000289 def output_charset(self):
290 return self._output_charset
291
292 def set_output_charset(self, charset):
293 self._output_charset = charset
294
Benjamin Peterson801844d2008-07-14 14:32:15 +0000295 def install(self, names=None):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000296 import builtins
Benjamin Peterson801844d2008-07-14 14:32:15 +0000297 builtins.__dict__['_'] = self.gettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000298 if hasattr(names, "__contains__"):
299 if "gettext" in names:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000300 builtins.__dict__['gettext'] = builtins.__dict__['_']
Georg Brandl602b9ba2006-02-19 13:26:36 +0000301 if "ngettext" in names:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000302 builtins.__dict__['ngettext'] = self.ngettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000303 if "lgettext" in names:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000304 builtins.__dict__['lgettext'] = self.lgettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000305 if "lngettext" in names:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000306 builtins.__dict__['lngettext'] = self.lngettext
Barry Warsaw33d8d702000-08-30 03:29:58 +0000307
308
309class GNUTranslations(NullTranslations):
310 # Magic number of .mo files
Guido van Rossume2a383d2007-01-15 16:59:06 +0000311 LE_MAGIC = 0x950412de
312 BE_MAGIC = 0xde120495
Barry Warsaw95be23d2000-08-25 19:13:37 +0000313
Antoine Pitroube8d06f2014-10-28 20:17:51 +0100314 # Acceptable .mo versions
315 VERSIONS = (0, 1)
316
317 def _get_versions(self, version):
318 """Returns a tuple of major version, minor version"""
319 return (version >> 16, version & 0xffff)
320
Barry Warsaw95be23d2000-08-25 19:13:37 +0000321 def _parse(self, fp):
322 """Override this method to support alternative .mo formats."""
323 unpack = struct.unpack
324 filename = getattr(fp, 'name', '')
325 # Parse the .mo file header, which consists of 5 little endian 32
326 # bit words.
Barry Warsaw33d8d702000-08-30 03:29:58 +0000327 self._catalog = catalog = {}
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000328 self.plural = lambda n: int(n != 1) # germanic plural by default
Barry Warsaw95be23d2000-08-25 19:13:37 +0000329 buf = fp.read()
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000330 buflen = len(buf)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000331 # Are we big endian or little endian?
Barry Warsaw09707e32002-08-14 15:09:12 +0000332 magic = unpack('<I', buf[:4])[0]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000333 if magic == self.LE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000334 version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
335 ii = '<II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000336 elif magic == self.BE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000337 version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
338 ii = '>II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000339 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200340 raise OSError(0, 'Bad magic number', filename)
Antoine Pitroube8d06f2014-10-28 20:17:51 +0100341
342 major_version, minor_version = self._get_versions(version)
343
344 if major_version not in self.VERSIONS:
345 raise OSError(0, 'Bad version number ' + str(major_version), filename)
346
Barry Warsaw95be23d2000-08-25 19:13:37 +0000347 # Now put all messages from the .mo file buffer into the catalog
348 # dictionary.
Guido van Rossum805365e2007-05-07 22:24:25 +0000349 for i in range(0, msgcount):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000350 mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000351 mend = moff + mlen
Barry Warsaw33d8d702000-08-30 03:29:58 +0000352 tlen, toff = unpack(ii, buf[transidx:transidx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000353 tend = toff + tlen
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000354 if mend < buflen and tend < buflen:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000355 msg = buf[moff:mend]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000356 tmsg = buf[toff:tend]
Barry Warsaw95be23d2000-08-25 19:13:37 +0000357 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200358 raise OSError(0, 'File is corrupt', filename)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000359 # See if we're looking at GNU .mo conventions for metadata
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000360 if mlen == 0:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000361 # Catalog description
Andrew Kuchling8b963c52015-04-13 10:38:56 -0400362 lastk = None
Christian Heimes6ae5d7f2007-10-31 18:53:44 +0000363 for b_item in tmsg.split('\n'.encode("ascii")):
Guido van Rossum98297ee2007-11-06 21:34:58 +0000364 item = b_item.decode().strip()
Barry Warsaw33d8d702000-08-30 03:29:58 +0000365 if not item:
366 continue
Andrew Kuchling8b963c52015-04-13 10:38:56 -0400367 k = v = None
Barry Warsaw7de63f52003-05-20 17:26:48 +0000368 if ':' in item:
369 k, v = item.split(':', 1)
370 k = k.strip().lower()
371 v = v.strip()
372 self._info[k] = v
373 lastk = k
374 elif lastk:
375 self._info[lastk] += '\n' + item
Barry Warsaw33d8d702000-08-30 03:29:58 +0000376 if k == 'content-type':
377 self._charset = v.split('charset=')[1]
Martin v. Löwisd8996052002-11-21 21:45:32 +0000378 elif k == 'plural-forms':
379 v = v.split(';')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000380 plural = v[1].split('plural=')[1]
381 self.plural = c2py(plural)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000382 # Note: we unconditionally convert both msgids and msgstrs to
383 # Unicode using the character encoding specified in the charset
384 # parameter of the Content-Type header. The gettext documentation
Ezio Melotti42da6632011-03-15 05:18:48 +0200385 # strongly encourages msgids to be us-ascii, but some applications
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000386 # require alternative encodings (e.g. Zope's ZCML and ZPT). For
387 # traditional gettext applications, the msgid conversion will
388 # cause no problems since us-ascii should always be a subset of
389 # the charset encoding. We may want to fall back to 8-bit msgids
390 # if the Unicode conversion fails.
Georg Brandlbded4d32008-07-17 18:15:35 +0000391 charset = self._charset or 'ascii'
Guido van Rossum652f4462007-07-12 08:04:06 +0000392 if b'\x00' in msg:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000393 # Plural forms
Guido van Rossum9600f932007-08-29 03:08:55 +0000394 msgid1, msgid2 = msg.split(b'\x00')
395 tmsg = tmsg.split(b'\x00')
Georg Brandlbded4d32008-07-17 18:15:35 +0000396 msgid1 = str(msgid1, charset)
397 for i, x in enumerate(tmsg):
398 catalog[(msgid1, i)] = str(x, charset)
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000399 else:
Georg Brandlbded4d32008-07-17 18:15:35 +0000400 catalog[str(msg, charset)] = str(tmsg, charset)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000401 # advance to next entry in the seek tables
Barry Warsawfa488ec2000-08-25 20:26:43 +0000402 masteridx += 8
403 transidx += 8
Barry Warsaw33d8d702000-08-30 03:29:58 +0000404
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000405 def lgettext(self, message):
406 missing = object()
407 tmsg = self._catalog.get(message, missing)
408 if tmsg is missing:
409 if self._fallback:
410 return self._fallback.lgettext(message)
411 return message
412 if self._output_charset:
413 return tmsg.encode(self._output_charset)
414 return tmsg.encode(locale.getpreferredencoding())
415
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000416 def lngettext(self, msgid1, msgid2, n):
417 try:
418 tmsg = self._catalog[(msgid1, self.plural(n))]
419 if self._output_charset:
420 return tmsg.encode(self._output_charset)
421 return tmsg.encode(locale.getpreferredencoding())
422 except KeyError:
423 if self._fallback:
424 return self._fallback.lngettext(msgid1, msgid2, n)
425 if n == 1:
426 return msgid1
427 else:
428 return msgid2
429
Benjamin Peterson801844d2008-07-14 14:32:15 +0000430 def gettext(self, message):
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000431 missing = object()
432 tmsg = self._catalog.get(message, missing)
433 if tmsg is missing:
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000434 if self._fallback:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000435 return self._fallback.gettext(message)
Georg Brandlbded4d32008-07-17 18:15:35 +0000436 return message
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000437 return tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000438
Benjamin Peterson801844d2008-07-14 14:32:15 +0000439 def ngettext(self, msgid1, msgid2, n):
Martin v. Löwisd8996052002-11-21 21:45:32 +0000440 try:
441 tmsg = self._catalog[(msgid1, self.plural(n))]
442 except KeyError:
443 if self._fallback:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000444 return self._fallback.ngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000445 if n == 1:
Georg Brandlbded4d32008-07-17 18:15:35 +0000446 tmsg = msgid1
Martin v. Löwisd8996052002-11-21 21:45:32 +0000447 else:
Georg Brandlbded4d32008-07-17 18:15:35 +0000448 tmsg = msgid2
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000449 return tmsg
Martin v. Löwisd8996052002-11-21 21:45:32 +0000450
Tim Peters07e99cb2001-01-14 23:47:14 +0000451
Barry Warsaw95be23d2000-08-25 19:13:37 +0000452# Locate a .mo file using the gettext strategy
Georg Brandlcd869252009-05-17 12:50:58 +0000453def find(domain, localedir=None, languages=None, all=False):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000454 # Get some reasonable defaults for arguments that were not supplied
Barry Warsaw95be23d2000-08-25 19:13:37 +0000455 if localedir is None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000456 localedir = _default_localedir
Barry Warsaw95be23d2000-08-25 19:13:37 +0000457 if languages is None:
458 languages = []
459 for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
460 val = os.environ.get(envar)
461 if val:
462 languages = val.split(':')
463 break
464 if 'C' not in languages:
465 languages.append('C')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000466 # now normalize and expand the languages
Barry Warsaw75f81012000-10-16 15:47:50 +0000467 nelangs = []
Barry Warsawfa488ec2000-08-25 20:26:43 +0000468 for lang in languages:
469 for nelang in _expand_lang(lang):
Barry Warsaw75f81012000-10-16 15:47:50 +0000470 if nelang not in nelangs:
471 nelangs.append(nelang)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000472 # select a language
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000473 if all:
474 result = []
475 else:
476 result = None
Barry Warsaw75f81012000-10-16 15:47:50 +0000477 for lang in nelangs:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000478 if lang == 'C':
479 break
Barry Warsaw84314b72000-08-25 19:53:17 +0000480 mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000481 if os.path.exists(mofile):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000482 if all:
483 result.append(mofile)
484 else:
485 return mofile
486 return result
Barry Warsaw95be23d2000-08-25 19:13:37 +0000487
488
Tim Peters07e99cb2001-01-14 23:47:14 +0000489
Barry Warsaw33d8d702000-08-30 03:29:58 +0000490# a mapping between absolute .mo file path and Translation object
491_translations = {}
492
Martin v. Löwis1be64192002-01-11 06:33:28 +0000493def translation(domain, localedir=None, languages=None,
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000494 class_=None, fallback=False, codeset=None):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000495 if class_ is None:
496 class_ = GNUTranslations
Georg Brandlcd869252009-05-17 12:50:58 +0000497 mofiles = find(domain, localedir, languages, all=True)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000498 if not mofiles:
Martin v. Löwis1be64192002-01-11 06:33:28 +0000499 if fallback:
500 return NullTranslations()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200501 raise OSError(ENOENT, 'No translation file found for domain', domain)
Barry Warsaw293b03f2000-10-05 18:48:12 +0000502 # Avoid opening, reading, and parsing the .mo file after it's been done
503 # once.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000504 result = None
505 for mofile in mofiles:
Éric Araujo6108bf52010-10-04 23:52:37 +0000506 key = (class_, os.path.abspath(mofile))
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000507 t = _translations.get(key)
508 if t is None:
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000509 with open(mofile, 'rb') as fp:
510 t = _translations.setdefault(key, class_(fp))
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000511 # Copy the translation object to allow setting fallbacks and
512 # output charset. All other instance data is shared with the
513 # cached object.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000514 t = copy.copy(t)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000515 if codeset:
516 t.set_output_charset(codeset)
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000517 if result is None:
518 result = t
519 else:
520 result.add_fallback(t)
521 return result
Barry Warsaw33d8d702000-08-30 03:29:58 +0000522
Tim Peters07e99cb2001-01-14 23:47:14 +0000523
Benjamin Peterson801844d2008-07-14 14:32:15 +0000524def install(domain, localedir=None, codeset=None, names=None):
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000525 t = translation(domain, localedir, fallback=True, codeset=codeset)
Benjamin Peterson801844d2008-07-14 14:32:15 +0000526 t.install(names)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000527
528
Tim Peters07e99cb2001-01-14 23:47:14 +0000529
Barry Warsaw33d8d702000-08-30 03:29:58 +0000530# a mapping b/w domains and locale directories
531_localedirs = {}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000532# a mapping b/w domains and codesets
533_localecodesets = {}
Barry Warsaw33d8d702000-08-30 03:29:58 +0000534# current global domain, `messages' used for compatibility w/ GNU gettext
535_current_domain = 'messages'
Barry Warsaw95be23d2000-08-25 19:13:37 +0000536
537
538def textdomain(domain=None):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000539 global _current_domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000540 if domain is not None:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000541 _current_domain = domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000542 return _current_domain
Barry Warsaw95be23d2000-08-25 19:13:37 +0000543
544
Barry Warsaw33d8d702000-08-30 03:29:58 +0000545def bindtextdomain(domain, localedir=None):
546 global _localedirs
547 if localedir is not None:
548 _localedirs[domain] = localedir
549 return _localedirs.get(domain, _default_localedir)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000550
551
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000552def bind_textdomain_codeset(domain, codeset=None):
553 global _localecodesets
554 if codeset is not None:
555 _localecodesets[domain] = codeset
556 return _localecodesets.get(domain)
557
558
Barry Warsaw95be23d2000-08-25 19:13:37 +0000559def dgettext(domain, message):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000560 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000561 t = translation(domain, _localedirs.get(domain, None),
562 codeset=_localecodesets.get(domain))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200563 except OSError:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000564 return message
565 return t.gettext(message)
Tim Peters07e99cb2001-01-14 23:47:14 +0000566
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000567def ldgettext(domain, message):
568 try:
569 t = translation(domain, _localedirs.get(domain, None),
570 codeset=_localecodesets.get(domain))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200571 except OSError:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000572 return message
573 return t.lgettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000574
Martin v. Löwisd8996052002-11-21 21:45:32 +0000575def dngettext(domain, msgid1, msgid2, n):
576 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000577 t = translation(domain, _localedirs.get(domain, None),
578 codeset=_localecodesets.get(domain))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200579 except OSError:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000580 if n == 1:
581 return msgid1
582 else:
583 return msgid2
584 return t.ngettext(msgid1, msgid2, n)
585
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000586def ldngettext(domain, msgid1, msgid2, n):
587 try:
588 t = translation(domain, _localedirs.get(domain, None),
589 codeset=_localecodesets.get(domain))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200590 except OSError:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000591 if n == 1:
592 return msgid1
593 else:
594 return msgid2
595 return t.lngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000596
Barry Warsaw33d8d702000-08-30 03:29:58 +0000597def gettext(message):
598 return dgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000599
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000600def lgettext(message):
601 return ldgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000602
Martin v. Löwisd8996052002-11-21 21:45:32 +0000603def ngettext(msgid1, msgid2, n):
604 return dngettext(_current_domain, msgid1, msgid2, n)
605
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000606def lngettext(msgid1, msgid2, n):
607 return ldngettext(_current_domain, msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000608
Barry Warsaw33d8d702000-08-30 03:29:58 +0000609# dcgettext() has been deemed unnecessary and is not implemented.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000610
Barry Warsaw33d8d702000-08-30 03:29:58 +0000611# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
612# was:
613#
614# import gettext
615# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
616# _ = cat.gettext
617# print _('Hello World')
Barry Warsaw95be23d2000-08-25 19:13:37 +0000618
Barry Warsaw33d8d702000-08-30 03:29:58 +0000619# The resulting catalog object currently don't support access through a
620# dictionary API, which was supported (but apparently unused) in GNOME
621# gettext.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000622
Barry Warsaw33d8d702000-08-30 03:29:58 +0000623Catalog = translation