blob: 08d051bf116557e61b9843aa796dedd99c8f02f6 [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)
282 return message
283
Martin v. Löwisd8996052002-11-21 21:45:32 +0000284 def ngettext(self, msgid1, msgid2, n):
285 if self._fallback:
286 return self._fallback.ngettext(msgid1, msgid2, n)
287 if n == 1:
288 return msgid1
289 else:
290 return msgid2
291
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000292 def lngettext(self, msgid1, msgid2, n):
293 if self._fallback:
294 return self._fallback.lngettext(msgid1, msgid2, n)
295 if n == 1:
296 return msgid1
297 else:
298 return msgid2
299
Barry Warsaw33d8d702000-08-30 03:29:58 +0000300 def info(self):
301 return self._info
302
303 def charset(self):
304 return self._charset
305
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000306 def output_charset(self):
307 return self._output_charset
308
309 def set_output_charset(self, charset):
310 self._output_charset = charset
311
Benjamin Peterson801844d2008-07-14 14:32:15 +0000312 def install(self, names=None):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000313 import builtins
Benjamin Peterson801844d2008-07-14 14:32:15 +0000314 builtins.__dict__['_'] = self.gettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000315 if hasattr(names, "__contains__"):
316 if "gettext" in names:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000317 builtins.__dict__['gettext'] = builtins.__dict__['_']
Georg Brandl602b9ba2006-02-19 13:26:36 +0000318 if "ngettext" in names:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000319 builtins.__dict__['ngettext'] = self.ngettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000320 if "lgettext" in names:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000321 builtins.__dict__['lgettext'] = self.lgettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000322 if "lngettext" in names:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000323 builtins.__dict__['lngettext'] = self.lngettext
Barry Warsaw33d8d702000-08-30 03:29:58 +0000324
325
326class GNUTranslations(NullTranslations):
327 # Magic number of .mo files
Guido van Rossume2a383d2007-01-15 16:59:06 +0000328 LE_MAGIC = 0x950412de
329 BE_MAGIC = 0xde120495
Barry Warsaw95be23d2000-08-25 19:13:37 +0000330
Antoine Pitroube8d06f2014-10-28 20:17:51 +0100331 # Acceptable .mo versions
332 VERSIONS = (0, 1)
333
334 def _get_versions(self, version):
335 """Returns a tuple of major version, minor version"""
336 return (version >> 16, version & 0xffff)
337
Barry Warsaw95be23d2000-08-25 19:13:37 +0000338 def _parse(self, fp):
339 """Override this method to support alternative .mo formats."""
340 unpack = struct.unpack
341 filename = getattr(fp, 'name', '')
342 # Parse the .mo file header, which consists of 5 little endian 32
343 # bit words.
Barry Warsaw33d8d702000-08-30 03:29:58 +0000344 self._catalog = catalog = {}
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000345 self.plural = lambda n: int(n != 1) # germanic plural by default
Barry Warsaw95be23d2000-08-25 19:13:37 +0000346 buf = fp.read()
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000347 buflen = len(buf)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000348 # Are we big endian or little endian?
Barry Warsaw09707e32002-08-14 15:09:12 +0000349 magic = unpack('<I', buf[:4])[0]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000350 if magic == self.LE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000351 version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
352 ii = '<II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000353 elif magic == self.BE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000354 version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
355 ii = '>II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000356 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200357 raise OSError(0, 'Bad magic number', filename)
Antoine Pitroube8d06f2014-10-28 20:17:51 +0100358
359 major_version, minor_version = self._get_versions(version)
360
361 if major_version not in self.VERSIONS:
362 raise OSError(0, 'Bad version number ' + str(major_version), filename)
363
Barry Warsaw95be23d2000-08-25 19:13:37 +0000364 # Now put all messages from the .mo file buffer into the catalog
365 # dictionary.
Guido van Rossum805365e2007-05-07 22:24:25 +0000366 for i in range(0, msgcount):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000367 mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000368 mend = moff + mlen
Barry Warsaw33d8d702000-08-30 03:29:58 +0000369 tlen, toff = unpack(ii, buf[transidx:transidx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000370 tend = toff + tlen
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000371 if mend < buflen and tend < buflen:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000372 msg = buf[moff:mend]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000373 tmsg = buf[toff:tend]
Barry Warsaw95be23d2000-08-25 19:13:37 +0000374 else:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200375 raise OSError(0, 'File is corrupt', filename)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000376 # See if we're looking at GNU .mo conventions for metadata
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000377 if mlen == 0:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000378 # Catalog description
Andrew Kuchling8b963c52015-04-13 10:38:56 -0400379 lastk = None
Christian Heimes6ae5d7f2007-10-31 18:53:44 +0000380 for b_item in tmsg.split('\n'.encode("ascii")):
Guido van Rossum98297ee2007-11-06 21:34:58 +0000381 item = b_item.decode().strip()
Barry Warsaw33d8d702000-08-30 03:29:58 +0000382 if not item:
383 continue
Andrew Kuchling8b963c52015-04-13 10:38:56 -0400384 k = v = None
Barry Warsaw7de63f52003-05-20 17:26:48 +0000385 if ':' in item:
386 k, v = item.split(':', 1)
387 k = k.strip().lower()
388 v = v.strip()
389 self._info[k] = v
390 lastk = k
391 elif lastk:
392 self._info[lastk] += '\n' + item
Barry Warsaw33d8d702000-08-30 03:29:58 +0000393 if k == 'content-type':
394 self._charset = v.split('charset=')[1]
Martin v. Löwisd8996052002-11-21 21:45:32 +0000395 elif k == 'plural-forms':
396 v = v.split(';')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000397 plural = v[1].split('plural=')[1]
398 self.plural = c2py(plural)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000399 # Note: we unconditionally convert both msgids and msgstrs to
400 # Unicode using the character encoding specified in the charset
401 # parameter of the Content-Type header. The gettext documentation
Ezio Melotti42da6632011-03-15 05:18:48 +0200402 # strongly encourages msgids to be us-ascii, but some applications
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000403 # require alternative encodings (e.g. Zope's ZCML and ZPT). For
404 # traditional gettext applications, the msgid conversion will
405 # cause no problems since us-ascii should always be a subset of
406 # the charset encoding. We may want to fall back to 8-bit msgids
407 # if the Unicode conversion fails.
Georg Brandlbded4d32008-07-17 18:15:35 +0000408 charset = self._charset or 'ascii'
Guido van Rossum652f4462007-07-12 08:04:06 +0000409 if b'\x00' in msg:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000410 # Plural forms
Guido van Rossum9600f932007-08-29 03:08:55 +0000411 msgid1, msgid2 = msg.split(b'\x00')
412 tmsg = tmsg.split(b'\x00')
Georg Brandlbded4d32008-07-17 18:15:35 +0000413 msgid1 = str(msgid1, charset)
414 for i, x in enumerate(tmsg):
415 catalog[(msgid1, i)] = str(x, charset)
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000416 else:
Georg Brandlbded4d32008-07-17 18:15:35 +0000417 catalog[str(msg, charset)] = str(tmsg, charset)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000418 # advance to next entry in the seek tables
Barry Warsawfa488ec2000-08-25 20:26:43 +0000419 masteridx += 8
420 transidx += 8
Barry Warsaw33d8d702000-08-30 03:29:58 +0000421
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000422 def lgettext(self, message):
423 missing = object()
424 tmsg = self._catalog.get(message, missing)
425 if tmsg is missing:
426 if self._fallback:
427 return self._fallback.lgettext(message)
428 return message
429 if self._output_charset:
430 return tmsg.encode(self._output_charset)
431 return tmsg.encode(locale.getpreferredencoding())
432
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000433 def lngettext(self, msgid1, msgid2, n):
434 try:
435 tmsg = self._catalog[(msgid1, self.plural(n))]
436 if self._output_charset:
437 return tmsg.encode(self._output_charset)
438 return tmsg.encode(locale.getpreferredencoding())
439 except KeyError:
440 if self._fallback:
441 return self._fallback.lngettext(msgid1, msgid2, n)
442 if n == 1:
443 return msgid1
444 else:
445 return msgid2
446
Benjamin Peterson801844d2008-07-14 14:32:15 +0000447 def gettext(self, message):
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000448 missing = object()
449 tmsg = self._catalog.get(message, missing)
450 if tmsg is missing:
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000451 if self._fallback:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000452 return self._fallback.gettext(message)
Georg Brandlbded4d32008-07-17 18:15:35 +0000453 return message
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000454 return tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000455
Benjamin Peterson801844d2008-07-14 14:32:15 +0000456 def ngettext(self, msgid1, msgid2, n):
Martin v. Löwisd8996052002-11-21 21:45:32 +0000457 try:
458 tmsg = self._catalog[(msgid1, self.plural(n))]
459 except KeyError:
460 if self._fallback:
Benjamin Peterson801844d2008-07-14 14:32:15 +0000461 return self._fallback.ngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000462 if n == 1:
Georg Brandlbded4d32008-07-17 18:15:35 +0000463 tmsg = msgid1
Martin v. Löwisd8996052002-11-21 21:45:32 +0000464 else:
Georg Brandlbded4d32008-07-17 18:15:35 +0000465 tmsg = msgid2
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000466 return tmsg
Martin v. Löwisd8996052002-11-21 21:45:32 +0000467
Tim Peters07e99cb2001-01-14 23:47:14 +0000468
Barry Warsaw95be23d2000-08-25 19:13:37 +0000469# Locate a .mo file using the gettext strategy
Georg Brandlcd869252009-05-17 12:50:58 +0000470def find(domain, localedir=None, languages=None, all=False):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000471 # Get some reasonable defaults for arguments that were not supplied
Barry Warsaw95be23d2000-08-25 19:13:37 +0000472 if localedir is None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000473 localedir = _default_localedir
Barry Warsaw95be23d2000-08-25 19:13:37 +0000474 if languages is None:
475 languages = []
476 for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
477 val = os.environ.get(envar)
478 if val:
479 languages = val.split(':')
480 break
481 if 'C' not in languages:
482 languages.append('C')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000483 # now normalize and expand the languages
Barry Warsaw75f81012000-10-16 15:47:50 +0000484 nelangs = []
Barry Warsawfa488ec2000-08-25 20:26:43 +0000485 for lang in languages:
486 for nelang in _expand_lang(lang):
Barry Warsaw75f81012000-10-16 15:47:50 +0000487 if nelang not in nelangs:
488 nelangs.append(nelang)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000489 # select a language
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000490 if all:
491 result = []
492 else:
493 result = None
Barry Warsaw75f81012000-10-16 15:47:50 +0000494 for lang in nelangs:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000495 if lang == 'C':
496 break
Barry Warsaw84314b72000-08-25 19:53:17 +0000497 mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000498 if os.path.exists(mofile):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000499 if all:
500 result.append(mofile)
501 else:
502 return mofile
503 return result
Barry Warsaw95be23d2000-08-25 19:13:37 +0000504
505
Tim Peters07e99cb2001-01-14 23:47:14 +0000506
Barry Warsaw33d8d702000-08-30 03:29:58 +0000507# a mapping between absolute .mo file path and Translation object
508_translations = {}
509
Martin v. Löwis1be64192002-01-11 06:33:28 +0000510def translation(domain, localedir=None, languages=None,
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000511 class_=None, fallback=False, codeset=None):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000512 if class_ is None:
513 class_ = GNUTranslations
Georg Brandlcd869252009-05-17 12:50:58 +0000514 mofiles = find(domain, localedir, languages, all=True)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000515 if not mofiles:
Martin v. Löwis1be64192002-01-11 06:33:28 +0000516 if fallback:
517 return NullTranslations()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200518 raise OSError(ENOENT, 'No translation file found for domain', domain)
Barry Warsaw293b03f2000-10-05 18:48:12 +0000519 # Avoid opening, reading, and parsing the .mo file after it's been done
520 # once.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000521 result = None
522 for mofile in mofiles:
Éric Araujo6108bf52010-10-04 23:52:37 +0000523 key = (class_, os.path.abspath(mofile))
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000524 t = _translations.get(key)
525 if t is None:
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000526 with open(mofile, 'rb') as fp:
527 t = _translations.setdefault(key, class_(fp))
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000528 # Copy the translation object to allow setting fallbacks and
529 # output charset. All other instance data is shared with the
530 # cached object.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000531 t = copy.copy(t)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000532 if codeset:
533 t.set_output_charset(codeset)
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000534 if result is None:
535 result = t
536 else:
537 result.add_fallback(t)
538 return result
Barry Warsaw33d8d702000-08-30 03:29:58 +0000539
Tim Peters07e99cb2001-01-14 23:47:14 +0000540
Benjamin Peterson801844d2008-07-14 14:32:15 +0000541def install(domain, localedir=None, codeset=None, names=None):
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000542 t = translation(domain, localedir, fallback=True, codeset=codeset)
Benjamin Peterson801844d2008-07-14 14:32:15 +0000543 t.install(names)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000544
545
Tim Peters07e99cb2001-01-14 23:47:14 +0000546
Barry Warsaw33d8d702000-08-30 03:29:58 +0000547# a mapping b/w domains and locale directories
548_localedirs = {}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000549# a mapping b/w domains and codesets
550_localecodesets = {}
Barry Warsaw33d8d702000-08-30 03:29:58 +0000551# current global domain, `messages' used for compatibility w/ GNU gettext
552_current_domain = 'messages'
Barry Warsaw95be23d2000-08-25 19:13:37 +0000553
554
555def textdomain(domain=None):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000556 global _current_domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000557 if domain is not None:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000558 _current_domain = domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000559 return _current_domain
Barry Warsaw95be23d2000-08-25 19:13:37 +0000560
561
Barry Warsaw33d8d702000-08-30 03:29:58 +0000562def bindtextdomain(domain, localedir=None):
563 global _localedirs
564 if localedir is not None:
565 _localedirs[domain] = localedir
566 return _localedirs.get(domain, _default_localedir)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000567
568
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000569def bind_textdomain_codeset(domain, codeset=None):
570 global _localecodesets
571 if codeset is not None:
572 _localecodesets[domain] = codeset
573 return _localecodesets.get(domain)
574
575
Barry Warsaw95be23d2000-08-25 19:13:37 +0000576def dgettext(domain, message):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000577 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000578 t = translation(domain, _localedirs.get(domain, None),
579 codeset=_localecodesets.get(domain))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200580 except OSError:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000581 return message
582 return t.gettext(message)
Tim Peters07e99cb2001-01-14 23:47:14 +0000583
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000584def ldgettext(domain, message):
585 try:
586 t = translation(domain, _localedirs.get(domain, None),
587 codeset=_localecodesets.get(domain))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200588 except OSError:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000589 return message
590 return t.lgettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000591
Martin v. Löwisd8996052002-11-21 21:45:32 +0000592def dngettext(domain, msgid1, msgid2, n):
593 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000594 t = translation(domain, _localedirs.get(domain, None),
595 codeset=_localecodesets.get(domain))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200596 except OSError:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000597 if n == 1:
598 return msgid1
599 else:
600 return msgid2
601 return t.ngettext(msgid1, msgid2, n)
602
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000603def ldngettext(domain, msgid1, msgid2, n):
604 try:
605 t = translation(domain, _localedirs.get(domain, None),
606 codeset=_localecodesets.get(domain))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200607 except OSError:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000608 if n == 1:
609 return msgid1
610 else:
611 return msgid2
612 return t.lngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000613
Barry Warsaw33d8d702000-08-30 03:29:58 +0000614def gettext(message):
615 return dgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000616
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000617def lgettext(message):
618 return ldgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000619
Martin v. Löwisd8996052002-11-21 21:45:32 +0000620def ngettext(msgid1, msgid2, n):
621 return dngettext(_current_domain, msgid1, msgid2, n)
622
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000623def lngettext(msgid1, msgid2, n):
624 return ldngettext(_current_domain, msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000625
Barry Warsaw33d8d702000-08-30 03:29:58 +0000626# dcgettext() has been deemed unnecessary and is not implemented.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000627
Barry Warsaw33d8d702000-08-30 03:29:58 +0000628# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
629# was:
630#
631# import gettext
632# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
633# _ = cat.gettext
634# print _('Hello World')
Barry Warsaw95be23d2000-08-25 19:13:37 +0000635
Barry Warsaw33d8d702000-08-30 03:29:58 +0000636# The resulting catalog object currently don't support access through a
637# dictionary API, which was supported (but apparently unused) in GNOME
638# gettext.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000639
Barry Warsaw33d8d702000-08-30 03:29:58 +0000640Catalog = translation