blob: a20c6f15224d565b964b3f0c451eb0c928f9d154 [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
Raymond Hettingera6172712004-12-31 19:15:26 +000080 try:
81 from cStringIO import StringIO
82 except ImportError:
83 from StringIO import StringIO
Martin v. Löwisd8996052002-11-21 21:45:32 +000084 import token, tokenize
85 tokens = tokenize.generate_tokens(StringIO(plural).readline)
Martin v. Löwisa57dccd2003-03-10 16:01:43 +000086 try:
Barry Warsawc4acc2b2003-04-24 18:13:39 +000087 danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
Martin v. Löwisa57dccd2003-03-10 16:01:43 +000088 except tokenize.TokenError:
89 raise ValueError, \
90 'plural forms expression error, maybe unbalanced parenthesis'
91 else:
92 if danger:
93 raise ValueError, 'plural forms expression could be dangerous'
Martin v. Löwisd8996052002-11-21 21:45:32 +000094
95 # Replace some C operators by their Python equivalents
96 plural = plural.replace('&&', ' and ')
97 plural = plural.replace('||', ' or ')
98
Martin v. Löwisa57dccd2003-03-10 16:01:43 +000099 expr = re.compile(r'\!([^=])')
100 plural = expr.sub(' not \\1', plural)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000101
102 # Regular expression and replacement function used to transform
103 # "a?b:c" to "test(a,b,c)".
104 expr = re.compile(r'(.*?)\?(.*?):(.*)')
105 def repl(x):
106 return "test(%s, %s, %s)" % (x.group(1), x.group(2),
107 expr.sub(repl, x.group(3)))
108
109 # Code to transform the plural expression, taking care of parentheses
110 stack = ['']
111 for c in plural:
112 if c == '(':
113 stack.append('')
114 elif c == ')':
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000115 if len(stack) == 1:
116 # Actually, we never reach this code, because unbalanced
117 # parentheses get caught in the security check at the
118 # beginning.
Martin v. Löwisd8996052002-11-21 21:45:32 +0000119 raise ValueError, 'unbalanced parenthesis in plural form'
120 s = expr.sub(repl, stack.pop())
121 stack[-1] += '(%s)' % s
122 else:
123 stack[-1] += c
124 plural = expr.sub(repl, stack.pop())
125
126 return eval('lambda n: int(%s)' % plural)
127
128
Tim Peters07e99cb2001-01-14 23:47:14 +0000129
Barry Warsawfa488ec2000-08-25 20:26:43 +0000130def _expand_lang(locale):
131 from locale import normalize
132 locale = normalize(locale)
133 COMPONENT_CODESET = 1 << 0
134 COMPONENT_TERRITORY = 1 << 1
135 COMPONENT_MODIFIER = 1 << 2
136 # split up the locale into its base components
137 mask = 0
138 pos = locale.find('@')
139 if pos >= 0:
140 modifier = locale[pos:]
141 locale = locale[:pos]
142 mask |= COMPONENT_MODIFIER
143 else:
144 modifier = ''
145 pos = locale.find('.')
146 if pos >= 0:
147 codeset = locale[pos:]
148 locale = locale[:pos]
149 mask |= COMPONENT_CODESET
150 else:
151 codeset = ''
152 pos = locale.find('_')
153 if pos >= 0:
154 territory = locale[pos:]
155 locale = locale[:pos]
156 mask |= COMPONENT_TERRITORY
157 else:
158 territory = ''
159 language = locale
160 ret = []
161 for i in range(mask+1):
162 if not (i & ~mask): # if all components for this combo exist ...
163 val = language
164 if i & COMPONENT_TERRITORY: val += territory
165 if i & COMPONENT_CODESET: val += codeset
166 if i & COMPONENT_MODIFIER: val += modifier
167 ret.append(val)
168 ret.reverse()
169 return ret
170
171
Tim Peters07e99cb2001-01-14 23:47:14 +0000172
Barry Warsaw33d8d702000-08-30 03:29:58 +0000173class NullTranslations:
174 def __init__(self, fp=None):
175 self._info = {}
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000176 self._charset = None
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000177 self._output_charset = None
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000178 self._fallback = None
Raymond Hettinger094662a2002-06-01 01:29:16 +0000179 if fp is not None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000180 self._parse(fp)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000181
Barry Warsaw33d8d702000-08-30 03:29:58 +0000182 def _parse(self, fp):
183 pass
184
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000185 def add_fallback(self, fallback):
186 if self._fallback:
187 self._fallback.add_fallback(fallback)
188 else:
189 self._fallback = fallback
190
Barry Warsaw33d8d702000-08-30 03:29:58 +0000191 def gettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000192 if self._fallback:
193 return self._fallback.gettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000194 return message
195
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000196 def lgettext(self, message):
197 if self._fallback:
198 return self._fallback.lgettext(message)
199 return message
200
Martin v. Löwisd8996052002-11-21 21:45:32 +0000201 def ngettext(self, msgid1, msgid2, n):
202 if self._fallback:
203 return self._fallback.ngettext(msgid1, msgid2, n)
204 if n == 1:
205 return msgid1
206 else:
207 return msgid2
208
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000209 def lngettext(self, msgid1, msgid2, n):
210 if self._fallback:
211 return self._fallback.lngettext(msgid1, msgid2, n)
212 if n == 1:
213 return msgid1
214 else:
215 return msgid2
216
Barry Warsaw33d8d702000-08-30 03:29:58 +0000217 def ugettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000218 if self._fallback:
219 return self._fallback.ugettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000220 return unicode(message)
221
Martin v. Löwisd8996052002-11-21 21:45:32 +0000222 def ungettext(self, msgid1, msgid2, n):
223 if self._fallback:
224 return self._fallback.ungettext(msgid1, msgid2, n)
225 if n == 1:
226 return unicode(msgid1)
227 else:
228 return unicode(msgid2)
229
Barry Warsaw33d8d702000-08-30 03:29:58 +0000230 def info(self):
231 return self._info
232
233 def charset(self):
234 return self._charset
235
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000236 def output_charset(self):
237 return self._output_charset
238
239 def set_output_charset(self, charset):
240 self._output_charset = charset
241
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000242 def install(self, unicode=False):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000243 import __builtin__
244 __builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
245
246
247class GNUTranslations(NullTranslations):
248 # Magic number of .mo files
Barry Warsaw09707e32002-08-14 15:09:12 +0000249 LE_MAGIC = 0x950412deL
250 BE_MAGIC = 0xde120495L
Barry Warsaw95be23d2000-08-25 19:13:37 +0000251
252 def _parse(self, fp):
253 """Override this method to support alternative .mo formats."""
254 unpack = struct.unpack
255 filename = getattr(fp, 'name', '')
256 # Parse the .mo file header, which consists of 5 little endian 32
257 # bit words.
Barry Warsaw33d8d702000-08-30 03:29:58 +0000258 self._catalog = catalog = {}
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000259 self.plural = lambda n: int(n != 1) # germanic plural by default
Barry Warsaw95be23d2000-08-25 19:13:37 +0000260 buf = fp.read()
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000261 buflen = len(buf)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000262 # Are we big endian or little endian?
Barry Warsaw09707e32002-08-14 15:09:12 +0000263 magic = unpack('<I', buf[:4])[0]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000264 if magic == self.LE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000265 version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
266 ii = '<II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000267 elif magic == self.BE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000268 version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
269 ii = '>II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000270 else:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000271 raise IOError(0, 'Bad magic number', filename)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000272 # Now put all messages from the .mo file buffer into the catalog
273 # dictionary.
274 for i in xrange(0, msgcount):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000275 mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000276 mend = moff + mlen
Barry Warsaw33d8d702000-08-30 03:29:58 +0000277 tlen, toff = unpack(ii, buf[transidx:transidx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000278 tend = toff + tlen
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000279 if mend < buflen and tend < buflen:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000280 msg = buf[moff:mend]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000281 tmsg = buf[toff:tend]
Barry Warsaw95be23d2000-08-25 19:13:37 +0000282 else:
283 raise IOError(0, 'File is corrupt', filename)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000284 # See if we're looking at GNU .mo conventions for metadata
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000285 if mlen == 0:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000286 # Catalog description
Barry Warsawb8c78762003-10-04 02:28:31 +0000287 lastk = k = None
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000288 for item in tmsg.splitlines():
Barry Warsaw33d8d702000-08-30 03:29:58 +0000289 item = item.strip()
290 if not item:
291 continue
Barry Warsaw7de63f52003-05-20 17:26:48 +0000292 if ':' in item:
293 k, v = item.split(':', 1)
294 k = k.strip().lower()
295 v = v.strip()
296 self._info[k] = v
297 lastk = k
298 elif lastk:
299 self._info[lastk] += '\n' + item
Barry Warsaw33d8d702000-08-30 03:29:58 +0000300 if k == 'content-type':
301 self._charset = v.split('charset=')[1]
Martin v. Löwisd8996052002-11-21 21:45:32 +0000302 elif k == 'plural-forms':
303 v = v.split(';')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000304 plural = v[1].split('plural=')[1]
305 self.plural = c2py(plural)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000306 # Note: we unconditionally convert both msgids and msgstrs to
307 # Unicode using the character encoding specified in the charset
308 # parameter of the Content-Type header. The gettext documentation
309 # strongly encourages msgids to be us-ascii, but some appliations
310 # require alternative encodings (e.g. Zope's ZCML and ZPT). For
311 # traditional gettext applications, the msgid conversion will
312 # cause no problems since us-ascii should always be a subset of
313 # the charset encoding. We may want to fall back to 8-bit msgids
314 # if the Unicode conversion fails.
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000315 if '\x00' in msg:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000316 # Plural forms
317 msgid1, msgid2 = msg.split('\x00')
318 tmsg = tmsg.split('\x00')
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000319 if self._charset:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000320 msgid1 = unicode(msgid1, self._charset)
321 tmsg = [unicode(x, self._charset) for x in tmsg]
322 for i in range(len(tmsg)):
323 catalog[(msgid1, i)] = tmsg[i]
324 else:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000325 if self._charset:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000326 msg = unicode(msg, self._charset)
327 tmsg = unicode(tmsg, self._charset)
328 catalog[msg] = tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000329 # advance to next entry in the seek tables
Barry Warsawfa488ec2000-08-25 20:26:43 +0000330 masteridx += 8
331 transidx += 8
Barry Warsaw33d8d702000-08-30 03:29:58 +0000332
333 def gettext(self, message):
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000334 missing = object()
335 tmsg = self._catalog.get(message, missing)
336 if tmsg is missing:
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000337 if self._fallback:
338 return self._fallback.gettext(message)
339 return message
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000340 # Encode the Unicode tmsg back to an 8-bit string, if possible
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000341 if self._output_charset:
342 return tmsg.encode(self._output_charset)
343 elif self._charset:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000344 return tmsg.encode(self._charset)
345 return tmsg
Barry Warsaw33d8d702000-08-30 03:29:58 +0000346
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000347 def lgettext(self, message):
348 missing = object()
349 tmsg = self._catalog.get(message, missing)
350 if tmsg is missing:
351 if self._fallback:
352 return self._fallback.lgettext(message)
353 return message
354 if self._output_charset:
355 return tmsg.encode(self._output_charset)
356 return tmsg.encode(locale.getpreferredencoding())
357
Martin v. Löwisd8996052002-11-21 21:45:32 +0000358 def ngettext(self, msgid1, msgid2, n):
359 try:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000360 tmsg = self._catalog[(msgid1, self.plural(n))]
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000361 if self._output_charset:
362 return tmsg.encode(self._output_charset)
363 elif self._charset:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000364 return tmsg.encode(self._charset)
365 return tmsg
Martin v. Löwisd8996052002-11-21 21:45:32 +0000366 except KeyError:
367 if self._fallback:
368 return self._fallback.ngettext(msgid1, msgid2, n)
369 if n == 1:
370 return msgid1
371 else:
372 return msgid2
373
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000374 def lngettext(self, msgid1, msgid2, n):
375 try:
376 tmsg = self._catalog[(msgid1, self.plural(n))]
377 if self._output_charset:
378 return tmsg.encode(self._output_charset)
379 return tmsg.encode(locale.getpreferredencoding())
380 except KeyError:
381 if self._fallback:
382 return self._fallback.lngettext(msgid1, msgid2, n)
383 if n == 1:
384 return msgid1
385 else:
386 return msgid2
387
Barry Warsaw33d8d702000-08-30 03:29:58 +0000388 def ugettext(self, message):
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000389 missing = object()
390 tmsg = self._catalog.get(message, missing)
391 if tmsg is missing:
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000392 if self._fallback:
393 return self._fallback.ugettext(message)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000394 return unicode(message)
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000395 return tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000396
Martin v. Löwisd8996052002-11-21 21:45:32 +0000397 def ungettext(self, msgid1, msgid2, n):
398 try:
399 tmsg = self._catalog[(msgid1, self.plural(n))]
400 except KeyError:
401 if self._fallback:
402 return self._fallback.ungettext(msgid1, msgid2, n)
403 if n == 1:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000404 tmsg = unicode(msgid1)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000405 else:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000406 tmsg = unicode(msgid2)
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000407 return tmsg
Martin v. Löwisd8996052002-11-21 21:45:32 +0000408
Tim Peters07e99cb2001-01-14 23:47:14 +0000409
Barry Warsaw95be23d2000-08-25 19:13:37 +0000410# Locate a .mo file using the gettext strategy
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000411def find(domain, localedir=None, languages=None, all=0):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000412 # Get some reasonable defaults for arguments that were not supplied
Barry Warsaw95be23d2000-08-25 19:13:37 +0000413 if localedir is None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000414 localedir = _default_localedir
Barry Warsaw95be23d2000-08-25 19:13:37 +0000415 if languages is None:
416 languages = []
417 for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
418 val = os.environ.get(envar)
419 if val:
420 languages = val.split(':')
421 break
422 if 'C' not in languages:
423 languages.append('C')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000424 # now normalize and expand the languages
Barry Warsaw75f81012000-10-16 15:47:50 +0000425 nelangs = []
Barry Warsawfa488ec2000-08-25 20:26:43 +0000426 for lang in languages:
427 for nelang in _expand_lang(lang):
Barry Warsaw75f81012000-10-16 15:47:50 +0000428 if nelang not in nelangs:
429 nelangs.append(nelang)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000430 # select a language
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000431 if all:
432 result = []
433 else:
434 result = None
Barry Warsaw75f81012000-10-16 15:47:50 +0000435 for lang in nelangs:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000436 if lang == 'C':
437 break
Barry Warsaw84314b72000-08-25 19:53:17 +0000438 mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000439 if os.path.exists(mofile):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000440 if all:
441 result.append(mofile)
442 else:
443 return mofile
444 return result
Barry Warsaw95be23d2000-08-25 19:13:37 +0000445
446
Tim Peters07e99cb2001-01-14 23:47:14 +0000447
Barry Warsaw33d8d702000-08-30 03:29:58 +0000448# a mapping between absolute .mo file path and Translation object
449_translations = {}
450
Martin v. Löwis1be64192002-01-11 06:33:28 +0000451def translation(domain, localedir=None, languages=None,
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000452 class_=None, fallback=False, codeset=None):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000453 if class_ is None:
454 class_ = GNUTranslations
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000455 mofiles = find(domain, localedir, languages, all=1)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000456 if not mofiles:
Martin v. Löwis1be64192002-01-11 06:33:28 +0000457 if fallback:
458 return NullTranslations()
Barry Warsaw33d8d702000-08-30 03:29:58 +0000459 raise IOError(ENOENT, 'No translation file found for domain', domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000460 # TBD: do we need to worry about the file pointer getting collected?
Barry Warsaw293b03f2000-10-05 18:48:12 +0000461 # Avoid opening, reading, and parsing the .mo file after it's been done
462 # once.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000463 result = None
464 for mofile in mofiles:
465 key = os.path.abspath(mofile)
466 t = _translations.get(key)
467 if t is None:
468 t = _translations.setdefault(key, class_(open(mofile, 'rb')))
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000469 # Copy the translation object to allow setting fallbacks and
470 # output charset. All other instance data is shared with the
471 # cached object.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000472 t = copy.copy(t)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000473 if codeset:
474 t.set_output_charset(codeset)
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000475 if result is None:
476 result = t
477 else:
478 result.add_fallback(t)
479 return result
Barry Warsaw33d8d702000-08-30 03:29:58 +0000480
Tim Peters07e99cb2001-01-14 23:47:14 +0000481
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000482def install(domain, localedir=None, unicode=False, codeset=None):
483 t = translation(domain, localedir, fallback=True, codeset=codeset)
484 t.install(unicode)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000485
486
Tim Peters07e99cb2001-01-14 23:47:14 +0000487
Barry Warsaw33d8d702000-08-30 03:29:58 +0000488# a mapping b/w domains and locale directories
489_localedirs = {}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000490# a mapping b/w domains and codesets
491_localecodesets = {}
Barry Warsaw33d8d702000-08-30 03:29:58 +0000492# current global domain, `messages' used for compatibility w/ GNU gettext
493_current_domain = 'messages'
Barry Warsaw95be23d2000-08-25 19:13:37 +0000494
495
496def textdomain(domain=None):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000497 global _current_domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000498 if domain is not None:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000499 _current_domain = domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000500 return _current_domain
Barry Warsaw95be23d2000-08-25 19:13:37 +0000501
502
Barry Warsaw33d8d702000-08-30 03:29:58 +0000503def bindtextdomain(domain, localedir=None):
504 global _localedirs
505 if localedir is not None:
506 _localedirs[domain] = localedir
507 return _localedirs.get(domain, _default_localedir)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000508
509
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000510def bind_textdomain_codeset(domain, codeset=None):
511 global _localecodesets
512 if codeset is not None:
513 _localecodesets[domain] = codeset
514 return _localecodesets.get(domain)
515
516
Barry Warsaw95be23d2000-08-25 19:13:37 +0000517def dgettext(domain, message):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000518 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000519 t = translation(domain, _localedirs.get(domain, None),
520 codeset=_localecodesets.get(domain))
Barry Warsaw33d8d702000-08-30 03:29:58 +0000521 except IOError:
522 return message
523 return t.gettext(message)
Tim Peters07e99cb2001-01-14 23:47:14 +0000524
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000525def ldgettext(domain, message):
526 try:
527 t = translation(domain, _localedirs.get(domain, None),
528 codeset=_localecodesets.get(domain))
529 except IOError:
530 return message
531 return t.lgettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000532
Martin v. Löwisd8996052002-11-21 21:45:32 +0000533def dngettext(domain, msgid1, msgid2, n):
534 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000535 t = translation(domain, _localedirs.get(domain, None),
536 codeset=_localecodesets.get(domain))
Martin v. Löwisd8996052002-11-21 21:45:32 +0000537 except IOError:
538 if n == 1:
539 return msgid1
540 else:
541 return msgid2
542 return t.ngettext(msgid1, msgid2, n)
543
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000544def ldngettext(domain, msgid1, msgid2, n):
545 try:
546 t = translation(domain, _localedirs.get(domain, None),
547 codeset=_localecodesets.get(domain))
548 except IOError:
549 if n == 1:
550 return msgid1
551 else:
552 return msgid2
553 return t.lngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000554
Barry Warsaw33d8d702000-08-30 03:29:58 +0000555def gettext(message):
556 return dgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000557
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000558def lgettext(message):
559 return ldgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000560
Martin v. Löwisd8996052002-11-21 21:45:32 +0000561def ngettext(msgid1, msgid2, n):
562 return dngettext(_current_domain, msgid1, msgid2, n)
563
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000564def lngettext(msgid1, msgid2, n):
565 return ldngettext(_current_domain, msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000566
Barry Warsaw33d8d702000-08-30 03:29:58 +0000567# dcgettext() has been deemed unnecessary and is not implemented.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000568
Barry Warsaw33d8d702000-08-30 03:29:58 +0000569# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
570# was:
571#
572# import gettext
573# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
574# _ = cat.gettext
575# print _('Hello World')
Barry Warsaw95be23d2000-08-25 19:13:37 +0000576
Barry Warsaw33d8d702000-08-30 03:29:58 +0000577# The resulting catalog object currently don't support access through a
578# dictionary API, which was supported (but apparently unused) in GNOME
579# gettext.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000580
Barry Warsaw33d8d702000-08-30 03:29:58 +0000581Catalog = translation