blob: 533be3dbac3fa544d4cce009b7a0901911c62ed2 [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
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +000049import locale, copy, 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',
55 'dgettext', 'dngettext', 'gettext', 'ngettext',
56 ]
Skip Montanaro2dd42762001-01-23 15:35:05 +000057
Barry Warsaw33d8d702000-08-30 03:29:58 +000058_default_localedir = os.path.join(sys.prefix, 'share', 'locale')
Barry Warsaw95be23d2000-08-25 19:13:37 +000059
60
Martin v. Löwisd8996052002-11-21 21:45:32 +000061def test(condition, true, false):
62 """
63 Implements the C expression:
64
65 condition ? true : false
66
67 Required to correctly interpret plural forms.
68 """
69 if condition:
70 return true
71 else:
72 return false
73
74
75def c2py(plural):
Barry Warsawc4acc2b2003-04-24 18:13:39 +000076 """Gets a C expression as used in PO files for plural forms and returns a
77 Python lambda function that implements an equivalent expression.
Martin v. Löwisd8996052002-11-21 21:45:32 +000078 """
79 # Security check, allow only the "n" identifier
Guido van Rossum68937b42007-05-18 00:51:22 +000080 from io import StringIO
Martin v. Löwisd8996052002-11-21 21:45:32 +000081 import token, tokenize
82 tokens = tokenize.generate_tokens(StringIO(plural).readline)
Martin v. Löwisa57dccd2003-03-10 16:01:43 +000083 try:
Barry Warsawc4acc2b2003-04-24 18:13:39 +000084 danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
Martin v. Löwisa57dccd2003-03-10 16:01:43 +000085 except tokenize.TokenError:
Collin Winterce36ad82007-08-30 01:19:48 +000086 raise ValueError('plural forms expression error, maybe unbalanced parenthesis')
Martin v. Löwisa57dccd2003-03-10 16:01:43 +000087 else:
88 if danger:
Collin Winterce36ad82007-08-30 01:19:48 +000089 raise ValueError('plural forms expression could be dangerous')
Martin v. Löwisd8996052002-11-21 21:45:32 +000090
91 # Replace some C operators by their Python equivalents
92 plural = plural.replace('&&', ' and ')
93 plural = plural.replace('||', ' or ')
94
Martin v. Löwisa57dccd2003-03-10 16:01:43 +000095 expr = re.compile(r'\!([^=])')
96 plural = expr.sub(' not \\1', plural)
Martin v. Löwisd8996052002-11-21 21:45:32 +000097
98 # Regular expression and replacement function used to transform
99 # "a?b:c" to "test(a,b,c)".
100 expr = re.compile(r'(.*?)\?(.*?):(.*)')
101 def repl(x):
102 return "test(%s, %s, %s)" % (x.group(1), x.group(2),
103 expr.sub(repl, x.group(3)))
104
105 # Code to transform the plural expression, taking care of parentheses
106 stack = ['']
107 for c in plural:
108 if c == '(':
109 stack.append('')
110 elif c == ')':
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000111 if len(stack) == 1:
112 # Actually, we never reach this code, because unbalanced
113 # parentheses get caught in the security check at the
114 # beginning.
Collin Winterce36ad82007-08-30 01:19:48 +0000115 raise ValueError('unbalanced parenthesis in plural form')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000116 s = expr.sub(repl, stack.pop())
117 stack[-1] += '(%s)' % s
118 else:
119 stack[-1] += c
120 plural = expr.sub(repl, stack.pop())
121
122 return eval('lambda n: int(%s)' % plural)
123
124
Tim Peters07e99cb2001-01-14 23:47:14 +0000125
Barry Warsawfa488ec2000-08-25 20:26:43 +0000126def _expand_lang(locale):
127 from locale import normalize
128 locale = normalize(locale)
129 COMPONENT_CODESET = 1 << 0
130 COMPONENT_TERRITORY = 1 << 1
131 COMPONENT_MODIFIER = 1 << 2
132 # split up the locale into its base components
133 mask = 0
134 pos = locale.find('@')
135 if pos >= 0:
136 modifier = locale[pos:]
137 locale = locale[:pos]
138 mask |= COMPONENT_MODIFIER
139 else:
140 modifier = ''
141 pos = locale.find('.')
142 if pos >= 0:
143 codeset = locale[pos:]
144 locale = locale[:pos]
145 mask |= COMPONENT_CODESET
146 else:
147 codeset = ''
148 pos = locale.find('_')
149 if pos >= 0:
150 territory = locale[pos:]
151 locale = locale[:pos]
152 mask |= COMPONENT_TERRITORY
153 else:
154 territory = ''
155 language = locale
156 ret = []
157 for i in range(mask+1):
158 if not (i & ~mask): # if all components for this combo exist ...
159 val = language
160 if i & COMPONENT_TERRITORY: val += territory
161 if i & COMPONENT_CODESET: val += codeset
162 if i & COMPONENT_MODIFIER: val += modifier
163 ret.append(val)
164 ret.reverse()
165 return ret
166
167
Tim Peters07e99cb2001-01-14 23:47:14 +0000168
Barry Warsaw33d8d702000-08-30 03:29:58 +0000169class NullTranslations:
170 def __init__(self, fp=None):
171 self._info = {}
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000172 self._charset = None
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000173 self._output_charset = None
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000174 self._fallback = None
Raymond Hettinger094662a2002-06-01 01:29:16 +0000175 if fp is not None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000176 self._parse(fp)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000177
Barry Warsaw33d8d702000-08-30 03:29:58 +0000178 def _parse(self, fp):
179 pass
180
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000181 def add_fallback(self, fallback):
182 if self._fallback:
183 self._fallback.add_fallback(fallback)
184 else:
185 self._fallback = fallback
186
Barry Warsaw33d8d702000-08-30 03:29:58 +0000187 def gettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000188 if self._fallback:
189 return self._fallback.gettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000190 return message
191
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000192 def lgettext(self, message):
193 if self._fallback:
194 return self._fallback.lgettext(message)
195 return message
196
Martin v. Löwisd8996052002-11-21 21:45:32 +0000197 def ngettext(self, msgid1, msgid2, n):
198 if self._fallback:
199 return self._fallback.ngettext(msgid1, msgid2, n)
200 if n == 1:
201 return msgid1
202 else:
203 return msgid2
204
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000205 def lngettext(self, msgid1, msgid2, n):
206 if self._fallback:
207 return self._fallback.lngettext(msgid1, msgid2, n)
208 if n == 1:
209 return msgid1
210 else:
211 return msgid2
212
Barry Warsaw33d8d702000-08-30 03:29:58 +0000213 def ugettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000214 if self._fallback:
215 return self._fallback.ugettext(message)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000216 return str(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000217
Martin v. Löwisd8996052002-11-21 21:45:32 +0000218 def ungettext(self, msgid1, msgid2, n):
219 if self._fallback:
220 return self._fallback.ungettext(msgid1, msgid2, n)
221 if n == 1:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000222 return str(msgid1)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000223 else:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000224 return str(msgid2)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000225
Barry Warsaw33d8d702000-08-30 03:29:58 +0000226 def info(self):
227 return self._info
228
229 def charset(self):
230 return self._charset
231
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000232 def output_charset(self):
233 return self._output_charset
234
235 def set_output_charset(self, charset):
236 self._output_charset = charset
237
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000238 def install(self, str=False, names=None):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000239 import __builtin__
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000240 __builtin__.__dict__['_'] = str and self.ugettext or self.gettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000241 if hasattr(names, "__contains__"):
242 if "gettext" in names:
243 __builtin__.__dict__['gettext'] = __builtin__.__dict__['_']
244 if "ngettext" in names:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000245 __builtin__.__dict__['ngettext'] = (str and self.ungettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000246 or self.ngettext)
247 if "lgettext" in names:
248 __builtin__.__dict__['lgettext'] = self.lgettext
249 if "lngettext" in names:
250 __builtin__.__dict__['lngettext'] = self.lngettext
Barry Warsaw33d8d702000-08-30 03:29:58 +0000251
252
253class GNUTranslations(NullTranslations):
254 # Magic number of .mo files
Guido van Rossume2a383d2007-01-15 16:59:06 +0000255 LE_MAGIC = 0x950412de
256 BE_MAGIC = 0xde120495
Barry Warsaw95be23d2000-08-25 19:13:37 +0000257
258 def _parse(self, fp):
259 """Override this method to support alternative .mo formats."""
260 unpack = struct.unpack
261 filename = getattr(fp, 'name', '')
262 # Parse the .mo file header, which consists of 5 little endian 32
263 # bit words.
Barry Warsaw33d8d702000-08-30 03:29:58 +0000264 self._catalog = catalog = {}
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000265 self.plural = lambda n: int(n != 1) # germanic plural by default
Barry Warsaw95be23d2000-08-25 19:13:37 +0000266 buf = fp.read()
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000267 buflen = len(buf)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000268 # Are we big endian or little endian?
Barry Warsaw09707e32002-08-14 15:09:12 +0000269 magic = unpack('<I', buf[:4])[0]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000270 if magic == self.LE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000271 version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
272 ii = '<II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000273 elif magic == self.BE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000274 version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
275 ii = '>II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000276 else:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000277 raise IOError(0, 'Bad magic number', filename)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000278 # Now put all messages from the .mo file buffer into the catalog
279 # dictionary.
Guido van Rossum805365e2007-05-07 22:24:25 +0000280 for i in range(0, msgcount):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000281 mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000282 mend = moff + mlen
Barry Warsaw33d8d702000-08-30 03:29:58 +0000283 tlen, toff = unpack(ii, buf[transidx:transidx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000284 tend = toff + tlen
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000285 if mend < buflen and tend < buflen:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000286 msg = buf[moff:mend]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000287 tmsg = buf[toff:tend]
Barry Warsaw95be23d2000-08-25 19:13:37 +0000288 else:
289 raise IOError(0, 'File is corrupt', filename)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000290 # See if we're looking at GNU .mo conventions for metadata
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000291 if mlen == 0:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000292 # Catalog description
Barry Warsawb8c78762003-10-04 02:28:31 +0000293 lastk = k = None
Guido van Rossum9600f932007-08-29 03:08:55 +0000294 for b_item in tmsg.split(os.linesep.encode("ascii")):
Guido van Rossum652f4462007-07-12 08:04:06 +0000295 item = str(b_item).strip()
Barry Warsaw33d8d702000-08-30 03:29:58 +0000296 if not item:
297 continue
Barry Warsaw7de63f52003-05-20 17:26:48 +0000298 if ':' in item:
299 k, v = item.split(':', 1)
300 k = k.strip().lower()
301 v = v.strip()
302 self._info[k] = v
303 lastk = k
304 elif lastk:
305 self._info[lastk] += '\n' + item
Barry Warsaw33d8d702000-08-30 03:29:58 +0000306 if k == 'content-type':
307 self._charset = v.split('charset=')[1]
Martin v. Löwisd8996052002-11-21 21:45:32 +0000308 elif k == 'plural-forms':
309 v = v.split(';')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000310 plural = v[1].split('plural=')[1]
311 self.plural = c2py(plural)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000312 # Note: we unconditionally convert both msgids and msgstrs to
313 # Unicode using the character encoding specified in the charset
314 # parameter of the Content-Type header. The gettext documentation
315 # strongly encourages msgids to be us-ascii, but some appliations
316 # require alternative encodings (e.g. Zope's ZCML and ZPT). For
317 # traditional gettext applications, the msgid conversion will
318 # cause no problems since us-ascii should always be a subset of
319 # the charset encoding. We may want to fall back to 8-bit msgids
320 # if the Unicode conversion fails.
Guido van Rossum652f4462007-07-12 08:04:06 +0000321 if b'\x00' in msg:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000322 # Plural forms
Guido van Rossum9600f932007-08-29 03:08:55 +0000323 msgid1, msgid2 = msg.split(b'\x00')
324 tmsg = tmsg.split(b'\x00')
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000325 if self._charset:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000326 msgid1 = str(msgid1, self._charset)
327 tmsg = [str(x, self._charset) for x in tmsg]
Guido van Rossum652f4462007-07-12 08:04:06 +0000328 else:
329 msgid1 = str(msgid1)
330 tmsg = [str(x) for x in tmsg]
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000331 for i in range(len(tmsg)):
332 catalog[(msgid1, i)] = tmsg[i]
333 else:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000334 if self._charset:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000335 msg = str(msg, self._charset)
336 tmsg = str(tmsg, self._charset)
Guido van Rossum652f4462007-07-12 08:04:06 +0000337 else:
338 msg = str(msg)
339 tmsg = str(tmsg)
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000340 catalog[msg] = tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000341 # advance to next entry in the seek tables
Barry Warsawfa488ec2000-08-25 20:26:43 +0000342 masteridx += 8
343 transidx += 8
Barry Warsaw33d8d702000-08-30 03:29:58 +0000344
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000345 def lgettext(self, message):
346 missing = object()
347 tmsg = self._catalog.get(message, missing)
348 if tmsg is missing:
349 if self._fallback:
350 return self._fallback.lgettext(message)
351 return message
352 if self._output_charset:
353 return tmsg.encode(self._output_charset)
354 return tmsg.encode(locale.getpreferredencoding())
355
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000356 def lngettext(self, msgid1, msgid2, n):
357 try:
358 tmsg = self._catalog[(msgid1, self.plural(n))]
359 if self._output_charset:
360 return tmsg.encode(self._output_charset)
361 return tmsg.encode(locale.getpreferredencoding())
362 except KeyError:
363 if self._fallback:
364 return self._fallback.lngettext(msgid1, msgid2, n)
365 if n == 1:
366 return msgid1
367 else:
368 return msgid2
369
Barry Warsaw33d8d702000-08-30 03:29:58 +0000370 def ugettext(self, message):
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000371 missing = object()
372 tmsg = self._catalog.get(message, missing)
373 if tmsg is missing:
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000374 if self._fallback:
375 return self._fallback.ugettext(message)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000376 return str(message)
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000377 return tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000378
Guido van Rossum652f4462007-07-12 08:04:06 +0000379 gettext = ugettext
380
Martin v. Löwisd8996052002-11-21 21:45:32 +0000381 def ungettext(self, msgid1, msgid2, n):
382 try:
383 tmsg = self._catalog[(msgid1, self.plural(n))]
384 except KeyError:
385 if self._fallback:
386 return self._fallback.ungettext(msgid1, msgid2, n)
387 if n == 1:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000388 tmsg = str(msgid1)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000389 else:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000390 tmsg = str(msgid2)
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000391 return tmsg
Martin v. Löwisd8996052002-11-21 21:45:32 +0000392
Guido van Rossum652f4462007-07-12 08:04:06 +0000393 ngettext = ungettext
394
Tim Peters07e99cb2001-01-14 23:47:14 +0000395
Barry Warsaw95be23d2000-08-25 19:13:37 +0000396# Locate a .mo file using the gettext strategy
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000397def find(domain, localedir=None, languages=None, all=0):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000398 # Get some reasonable defaults for arguments that were not supplied
Barry Warsaw95be23d2000-08-25 19:13:37 +0000399 if localedir is None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000400 localedir = _default_localedir
Barry Warsaw95be23d2000-08-25 19:13:37 +0000401 if languages is None:
402 languages = []
403 for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
404 val = os.environ.get(envar)
405 if val:
406 languages = val.split(':')
407 break
408 if 'C' not in languages:
409 languages.append('C')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000410 # now normalize and expand the languages
Barry Warsaw75f81012000-10-16 15:47:50 +0000411 nelangs = []
Barry Warsawfa488ec2000-08-25 20:26:43 +0000412 for lang in languages:
413 for nelang in _expand_lang(lang):
Barry Warsaw75f81012000-10-16 15:47:50 +0000414 if nelang not in nelangs:
415 nelangs.append(nelang)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000416 # select a language
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000417 if all:
418 result = []
419 else:
420 result = None
Barry Warsaw75f81012000-10-16 15:47:50 +0000421 for lang in nelangs:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000422 if lang == 'C':
423 break
Barry Warsaw84314b72000-08-25 19:53:17 +0000424 mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000425 if os.path.exists(mofile):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000426 if all:
427 result.append(mofile)
428 else:
429 return mofile
430 return result
Barry Warsaw95be23d2000-08-25 19:13:37 +0000431
432
Tim Peters07e99cb2001-01-14 23:47:14 +0000433
Barry Warsaw33d8d702000-08-30 03:29:58 +0000434# a mapping between absolute .mo file path and Translation object
435_translations = {}
436
Martin v. Löwis1be64192002-01-11 06:33:28 +0000437def translation(domain, localedir=None, languages=None,
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000438 class_=None, fallback=False, codeset=None):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000439 if class_ is None:
440 class_ = GNUTranslations
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000441 mofiles = find(domain, localedir, languages, all=1)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000442 if not mofiles:
Martin v. Löwis1be64192002-01-11 06:33:28 +0000443 if fallback:
444 return NullTranslations()
Barry Warsaw33d8d702000-08-30 03:29:58 +0000445 raise IOError(ENOENT, 'No translation file found for domain', domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000446 # TBD: do we need to worry about the file pointer getting collected?
Barry Warsaw293b03f2000-10-05 18:48:12 +0000447 # Avoid opening, reading, and parsing the .mo file after it's been done
448 # once.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000449 result = None
450 for mofile in mofiles:
451 key = os.path.abspath(mofile)
452 t = _translations.get(key)
453 if t is None:
454 t = _translations.setdefault(key, class_(open(mofile, 'rb')))
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000455 # Copy the translation object to allow setting fallbacks and
456 # output charset. All other instance data is shared with the
457 # cached object.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000458 t = copy.copy(t)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000459 if codeset:
460 t.set_output_charset(codeset)
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000461 if result is None:
462 result = t
463 else:
464 result.add_fallback(t)
465 return result
Barry Warsaw33d8d702000-08-30 03:29:58 +0000466
Tim Peters07e99cb2001-01-14 23:47:14 +0000467
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000468def install(domain, localedir=None, str=False, codeset=None, names=None):
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000469 t = translation(domain, localedir, fallback=True, codeset=codeset)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000470 t.install(str, names)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000471
472
Tim Peters07e99cb2001-01-14 23:47:14 +0000473
Barry Warsaw33d8d702000-08-30 03:29:58 +0000474# a mapping b/w domains and locale directories
475_localedirs = {}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000476# a mapping b/w domains and codesets
477_localecodesets = {}
Barry Warsaw33d8d702000-08-30 03:29:58 +0000478# current global domain, `messages' used for compatibility w/ GNU gettext
479_current_domain = 'messages'
Barry Warsaw95be23d2000-08-25 19:13:37 +0000480
481
482def textdomain(domain=None):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000483 global _current_domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000484 if domain is not None:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000485 _current_domain = domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000486 return _current_domain
Barry Warsaw95be23d2000-08-25 19:13:37 +0000487
488
Barry Warsaw33d8d702000-08-30 03:29:58 +0000489def bindtextdomain(domain, localedir=None):
490 global _localedirs
491 if localedir is not None:
492 _localedirs[domain] = localedir
493 return _localedirs.get(domain, _default_localedir)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000494
495
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000496def bind_textdomain_codeset(domain, codeset=None):
497 global _localecodesets
498 if codeset is not None:
499 _localecodesets[domain] = codeset
500 return _localecodesets.get(domain)
501
502
Barry Warsaw95be23d2000-08-25 19:13:37 +0000503def dgettext(domain, message):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000504 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000505 t = translation(domain, _localedirs.get(domain, None),
506 codeset=_localecodesets.get(domain))
Barry Warsaw33d8d702000-08-30 03:29:58 +0000507 except IOError:
508 return message
509 return t.gettext(message)
Tim Peters07e99cb2001-01-14 23:47:14 +0000510
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000511def ldgettext(domain, message):
512 try:
513 t = translation(domain, _localedirs.get(domain, None),
514 codeset=_localecodesets.get(domain))
515 except IOError:
516 return message
517 return t.lgettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000518
Martin v. Löwisd8996052002-11-21 21:45:32 +0000519def dngettext(domain, msgid1, msgid2, n):
520 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000521 t = translation(domain, _localedirs.get(domain, None),
522 codeset=_localecodesets.get(domain))
Martin v. Löwisd8996052002-11-21 21:45:32 +0000523 except IOError:
524 if n == 1:
525 return msgid1
526 else:
527 return msgid2
528 return t.ngettext(msgid1, msgid2, n)
529
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000530def ldngettext(domain, msgid1, msgid2, n):
531 try:
532 t = translation(domain, _localedirs.get(domain, None),
533 codeset=_localecodesets.get(domain))
534 except IOError:
535 if n == 1:
536 return msgid1
537 else:
538 return msgid2
539 return t.lngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000540
Barry Warsaw33d8d702000-08-30 03:29:58 +0000541def gettext(message):
542 return dgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000543
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000544def lgettext(message):
545 return ldgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000546
Martin v. Löwisd8996052002-11-21 21:45:32 +0000547def ngettext(msgid1, msgid2, n):
548 return dngettext(_current_domain, msgid1, msgid2, n)
549
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000550def lngettext(msgid1, msgid2, n):
551 return ldngettext(_current_domain, msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000552
Barry Warsaw33d8d702000-08-30 03:29:58 +0000553# dcgettext() has been deemed unnecessary and is not implemented.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000554
Barry Warsaw33d8d702000-08-30 03:29:58 +0000555# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
556# was:
557#
558# import gettext
559# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
560# _ = cat.gettext
561# print _('Hello World')
Barry Warsaw95be23d2000-08-25 19:13:37 +0000562
Barry Warsaw33d8d702000-08-30 03:29:58 +0000563# The resulting catalog object currently don't support access through a
564# dictionary API, which was supported (but apparently unused) in GNOME
565# gettext.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000566
Barry Warsaw33d8d702000-08-30 03:29:58 +0000567Catalog = translation