blob: 43202c46f49d86fb4b8c38defcad60bd297ccd9d [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',
Andrew Kuchling2ca7bb02015-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
Barry Warsaw33d8d702000-08-30 03:29:58 +000060_default_localedir = os.path.join(sys.prefix, 'share', 'locale')
Barry Warsaw95be23d2000-08-25 19:13:37 +000061
62
Martin v. Löwisd8996052002-11-21 21:45:32 +000063def test(condition, true, false):
64 """
65 Implements the C expression:
66
67 condition ? true : false
68
69 Required to correctly interpret plural forms.
70 """
71 if condition:
72 return true
73 else:
74 return false
75
76
77def c2py(plural):
Barry Warsawc4acc2b2003-04-24 18:13:39 +000078 """Gets a C expression as used in PO files for plural forms and returns a
79 Python lambda function that implements an equivalent expression.
Martin v. Löwisd8996052002-11-21 21:45:32 +000080 """
81 # Security check, allow only the "n" identifier
Raymond Hettingera6172712004-12-31 19:15:26 +000082 try:
83 from cStringIO import StringIO
84 except ImportError:
85 from StringIO import StringIO
Martin v. Löwisd8996052002-11-21 21:45:32 +000086 import token, tokenize
87 tokens = tokenize.generate_tokens(StringIO(plural).readline)
Martin v. Löwisa57dccd2003-03-10 16:01:43 +000088 try:
Barry Warsawc4acc2b2003-04-24 18:13:39 +000089 danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
Martin v. Löwisa57dccd2003-03-10 16:01:43 +000090 except tokenize.TokenError:
91 raise ValueError, \
92 'plural forms expression error, maybe unbalanced parenthesis'
93 else:
94 if danger:
95 raise ValueError, 'plural forms expression could be dangerous'
Martin v. Löwisd8996052002-11-21 21:45:32 +000096
97 # Replace some C operators by their Python equivalents
98 plural = plural.replace('&&', ' and ')
99 plural = plural.replace('||', ' or ')
100
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000101 expr = re.compile(r'\!([^=])')
102 plural = expr.sub(' not \\1', plural)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000103
104 # Regular expression and replacement function used to transform
105 # "a?b:c" to "test(a,b,c)".
106 expr = re.compile(r'(.*?)\?(.*?):(.*)')
107 def repl(x):
108 return "test(%s, %s, %s)" % (x.group(1), x.group(2),
109 expr.sub(repl, x.group(3)))
110
111 # Code to transform the plural expression, taking care of parentheses
112 stack = ['']
113 for c in plural:
114 if c == '(':
115 stack.append('')
116 elif c == ')':
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000117 if len(stack) == 1:
118 # Actually, we never reach this code, because unbalanced
119 # parentheses get caught in the security check at the
120 # beginning.
Martin v. Löwisd8996052002-11-21 21:45:32 +0000121 raise ValueError, 'unbalanced parenthesis in plural form'
122 s = expr.sub(repl, stack.pop())
123 stack[-1] += '(%s)' % s
124 else:
125 stack[-1] += c
126 plural = expr.sub(repl, stack.pop())
127
128 return eval('lambda n: int(%s)' % plural)
129
130
Tim Peters07e99cb2001-01-14 23:47:14 +0000131
Barry Warsawfa488ec2000-08-25 20:26:43 +0000132def _expand_lang(locale):
133 from locale import normalize
134 locale = normalize(locale)
135 COMPONENT_CODESET = 1 << 0
136 COMPONENT_TERRITORY = 1 << 1
137 COMPONENT_MODIFIER = 1 << 2
138 # split up the locale into its base components
139 mask = 0
140 pos = locale.find('@')
141 if pos >= 0:
142 modifier = locale[pos:]
143 locale = locale[:pos]
144 mask |= COMPONENT_MODIFIER
145 else:
146 modifier = ''
147 pos = locale.find('.')
148 if pos >= 0:
149 codeset = locale[pos:]
150 locale = locale[:pos]
151 mask |= COMPONENT_CODESET
152 else:
153 codeset = ''
154 pos = locale.find('_')
155 if pos >= 0:
156 territory = locale[pos:]
157 locale = locale[:pos]
158 mask |= COMPONENT_TERRITORY
159 else:
160 territory = ''
161 language = locale
162 ret = []
163 for i in range(mask+1):
164 if not (i & ~mask): # if all components for this combo exist ...
165 val = language
166 if i & COMPONENT_TERRITORY: val += territory
167 if i & COMPONENT_CODESET: val += codeset
168 if i & COMPONENT_MODIFIER: val += modifier
169 ret.append(val)
170 ret.reverse()
171 return ret
172
173
Tim Peters07e99cb2001-01-14 23:47:14 +0000174
Barry Warsaw33d8d702000-08-30 03:29:58 +0000175class NullTranslations:
176 def __init__(self, fp=None):
177 self._info = {}
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000178 self._charset = None
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000179 self._output_charset = None
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000180 self._fallback = None
Raymond Hettinger094662a2002-06-01 01:29:16 +0000181 if fp is not None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000182 self._parse(fp)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000183
Barry Warsaw33d8d702000-08-30 03:29:58 +0000184 def _parse(self, fp):
185 pass
186
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000187 def add_fallback(self, fallback):
188 if self._fallback:
189 self._fallback.add_fallback(fallback)
190 else:
191 self._fallback = fallback
192
Barry Warsaw33d8d702000-08-30 03:29:58 +0000193 def gettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000194 if self._fallback:
195 return self._fallback.gettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000196 return message
197
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000198 def lgettext(self, message):
199 if self._fallback:
200 return self._fallback.lgettext(message)
201 return message
202
Martin v. Löwisd8996052002-11-21 21:45:32 +0000203 def ngettext(self, msgid1, msgid2, n):
204 if self._fallback:
205 return self._fallback.ngettext(msgid1, msgid2, n)
206 if n == 1:
207 return msgid1
208 else:
209 return msgid2
210
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000211 def lngettext(self, msgid1, msgid2, n):
212 if self._fallback:
213 return self._fallback.lngettext(msgid1, msgid2, n)
214 if n == 1:
215 return msgid1
216 else:
217 return msgid2
218
Barry Warsaw33d8d702000-08-30 03:29:58 +0000219 def ugettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000220 if self._fallback:
221 return self._fallback.ugettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000222 return unicode(message)
223
Martin v. Löwisd8996052002-11-21 21:45:32 +0000224 def ungettext(self, msgid1, msgid2, n):
225 if self._fallback:
226 return self._fallback.ungettext(msgid1, msgid2, n)
227 if n == 1:
228 return unicode(msgid1)
229 else:
230 return unicode(msgid2)
231
Barry Warsaw33d8d702000-08-30 03:29:58 +0000232 def info(self):
233 return self._info
234
235 def charset(self):
236 return self._charset
237
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000238 def output_charset(self):
239 return self._output_charset
240
241 def set_output_charset(self, charset):
242 self._output_charset = charset
243
Georg Brandl602b9ba2006-02-19 13:26:36 +0000244 def install(self, unicode=False, names=None):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000245 import __builtin__
246 __builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000247 if hasattr(names, "__contains__"):
248 if "gettext" in names:
249 __builtin__.__dict__['gettext'] = __builtin__.__dict__['_']
250 if "ngettext" in names:
251 __builtin__.__dict__['ngettext'] = (unicode and self.ungettext
252 or self.ngettext)
253 if "lgettext" in names:
254 __builtin__.__dict__['lgettext'] = self.lgettext
255 if "lngettext" in names:
256 __builtin__.__dict__['lngettext'] = self.lngettext
Barry Warsaw33d8d702000-08-30 03:29:58 +0000257
258
259class GNUTranslations(NullTranslations):
260 # Magic number of .mo files
Barry Warsaw09707e32002-08-14 15:09:12 +0000261 LE_MAGIC = 0x950412deL
262 BE_MAGIC = 0xde120495L
Barry Warsaw95be23d2000-08-25 19:13:37 +0000263
264 def _parse(self, fp):
265 """Override this method to support alternative .mo formats."""
266 unpack = struct.unpack
267 filename = getattr(fp, 'name', '')
268 # Parse the .mo file header, which consists of 5 little endian 32
269 # bit words.
Barry Warsaw33d8d702000-08-30 03:29:58 +0000270 self._catalog = catalog = {}
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000271 self.plural = lambda n: int(n != 1) # germanic plural by default
Barry Warsaw95be23d2000-08-25 19:13:37 +0000272 buf = fp.read()
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000273 buflen = len(buf)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000274 # Are we big endian or little endian?
Barry Warsaw09707e32002-08-14 15:09:12 +0000275 magic = unpack('<I', buf[:4])[0]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000276 if magic == self.LE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000277 version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
278 ii = '<II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000279 elif magic == self.BE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000280 version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
281 ii = '>II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000282 else:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000283 raise IOError(0, 'Bad magic number', filename)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000284 # Now put all messages from the .mo file buffer into the catalog
285 # dictionary.
286 for i in xrange(0, msgcount):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000287 mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000288 mend = moff + mlen
Barry Warsaw33d8d702000-08-30 03:29:58 +0000289 tlen, toff = unpack(ii, buf[transidx:transidx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000290 tend = toff + tlen
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000291 if mend < buflen and tend < buflen:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000292 msg = buf[moff:mend]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000293 tmsg = buf[toff:tend]
Barry Warsaw95be23d2000-08-25 19:13:37 +0000294 else:
295 raise IOError(0, 'File is corrupt', filename)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000296 # See if we're looking at GNU .mo conventions for metadata
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000297 if mlen == 0:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000298 # Catalog description
Andrew Kuchling270b0582015-04-14 10:03:35 -0400299 lastk = None
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000300 for item in tmsg.splitlines():
Barry Warsaw33d8d702000-08-30 03:29:58 +0000301 item = item.strip()
302 if not item:
303 continue
Andrew Kuchling270b0582015-04-14 10:03:35 -0400304 k = v = None
Barry Warsaw7de63f52003-05-20 17:26:48 +0000305 if ':' in item:
306 k, v = item.split(':', 1)
307 k = k.strip().lower()
308 v = v.strip()
309 self._info[k] = v
310 lastk = k
311 elif lastk:
312 self._info[lastk] += '\n' + item
Barry Warsaw33d8d702000-08-30 03:29:58 +0000313 if k == 'content-type':
314 self._charset = v.split('charset=')[1]
Martin v. Löwisd8996052002-11-21 21:45:32 +0000315 elif k == 'plural-forms':
316 v = v.split(';')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000317 plural = v[1].split('plural=')[1]
318 self.plural = c2py(plural)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000319 # Note: we unconditionally convert both msgids and msgstrs to
320 # Unicode using the character encoding specified in the charset
321 # parameter of the Content-Type header. The gettext documentation
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200322 # strongly encourages msgids to be us-ascii, but some applications
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000323 # require alternative encodings (e.g. Zope's ZCML and ZPT). For
324 # traditional gettext applications, the msgid conversion will
325 # cause no problems since us-ascii should always be a subset of
326 # the charset encoding. We may want to fall back to 8-bit msgids
327 # if the Unicode conversion fails.
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000328 if '\x00' in msg:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000329 # Plural forms
330 msgid1, msgid2 = msg.split('\x00')
331 tmsg = tmsg.split('\x00')
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000332 if self._charset:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000333 msgid1 = unicode(msgid1, self._charset)
334 tmsg = [unicode(x, self._charset) for x in tmsg]
335 for i in range(len(tmsg)):
336 catalog[(msgid1, i)] = tmsg[i]
337 else:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000338 if self._charset:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000339 msg = unicode(msg, self._charset)
340 tmsg = unicode(tmsg, self._charset)
341 catalog[msg] = tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000342 # advance to next entry in the seek tables
Barry Warsawfa488ec2000-08-25 20:26:43 +0000343 masteridx += 8
344 transidx += 8
Barry Warsaw33d8d702000-08-30 03:29:58 +0000345
346 def gettext(self, message):
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000347 missing = object()
348 tmsg = self._catalog.get(message, missing)
349 if tmsg is missing:
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000350 if self._fallback:
351 return self._fallback.gettext(message)
352 return message
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000353 # Encode the Unicode tmsg back to an 8-bit string, if possible
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000354 if self._output_charset:
355 return tmsg.encode(self._output_charset)
356 elif self._charset:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000357 return tmsg.encode(self._charset)
358 return tmsg
Barry Warsaw33d8d702000-08-30 03:29:58 +0000359
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000360 def lgettext(self, message):
361 missing = object()
362 tmsg = self._catalog.get(message, missing)
363 if tmsg is missing:
364 if self._fallback:
365 return self._fallback.lgettext(message)
366 return message
367 if self._output_charset:
368 return tmsg.encode(self._output_charset)
369 return tmsg.encode(locale.getpreferredencoding())
370
Martin v. Löwisd8996052002-11-21 21:45:32 +0000371 def ngettext(self, msgid1, msgid2, n):
372 try:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000373 tmsg = self._catalog[(msgid1, self.plural(n))]
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000374 if self._output_charset:
375 return tmsg.encode(self._output_charset)
376 elif self._charset:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000377 return tmsg.encode(self._charset)
378 return tmsg
Martin v. Löwisd8996052002-11-21 21:45:32 +0000379 except KeyError:
380 if self._fallback:
381 return self._fallback.ngettext(msgid1, msgid2, n)
382 if n == 1:
383 return msgid1
384 else:
385 return msgid2
386
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000387 def lngettext(self, msgid1, msgid2, n):
388 try:
389 tmsg = self._catalog[(msgid1, self.plural(n))]
390 if self._output_charset:
391 return tmsg.encode(self._output_charset)
392 return tmsg.encode(locale.getpreferredencoding())
393 except KeyError:
394 if self._fallback:
395 return self._fallback.lngettext(msgid1, msgid2, n)
396 if n == 1:
397 return msgid1
398 else:
399 return msgid2
400
Barry Warsaw33d8d702000-08-30 03:29:58 +0000401 def ugettext(self, message):
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000402 missing = object()
403 tmsg = self._catalog.get(message, missing)
404 if tmsg is missing:
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000405 if self._fallback:
406 return self._fallback.ugettext(message)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000407 return unicode(message)
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000408 return tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000409
Martin v. Löwisd8996052002-11-21 21:45:32 +0000410 def ungettext(self, msgid1, msgid2, n):
411 try:
412 tmsg = self._catalog[(msgid1, self.plural(n))]
413 except KeyError:
414 if self._fallback:
415 return self._fallback.ungettext(msgid1, msgid2, n)
416 if n == 1:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000417 tmsg = unicode(msgid1)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000418 else:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000419 tmsg = unicode(msgid2)
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000420 return tmsg
Martin v. Löwisd8996052002-11-21 21:45:32 +0000421
Tim Peters07e99cb2001-01-14 23:47:14 +0000422
Barry Warsaw95be23d2000-08-25 19:13:37 +0000423# Locate a .mo file using the gettext strategy
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000424def find(domain, localedir=None, languages=None, all=0):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000425 # Get some reasonable defaults for arguments that were not supplied
Barry Warsaw95be23d2000-08-25 19:13:37 +0000426 if localedir is None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000427 localedir = _default_localedir
Barry Warsaw95be23d2000-08-25 19:13:37 +0000428 if languages is None:
429 languages = []
430 for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
431 val = os.environ.get(envar)
432 if val:
433 languages = val.split(':')
434 break
435 if 'C' not in languages:
436 languages.append('C')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000437 # now normalize and expand the languages
Barry Warsaw75f81012000-10-16 15:47:50 +0000438 nelangs = []
Barry Warsawfa488ec2000-08-25 20:26:43 +0000439 for lang in languages:
440 for nelang in _expand_lang(lang):
Barry Warsaw75f81012000-10-16 15:47:50 +0000441 if nelang not in nelangs:
442 nelangs.append(nelang)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000443 # select a language
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000444 if all:
445 result = []
446 else:
447 result = None
Barry Warsaw75f81012000-10-16 15:47:50 +0000448 for lang in nelangs:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000449 if lang == 'C':
450 break
Barry Warsaw84314b72000-08-25 19:53:17 +0000451 mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000452 if os.path.exists(mofile):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000453 if all:
454 result.append(mofile)
455 else:
456 return mofile
457 return result
Barry Warsaw95be23d2000-08-25 19:13:37 +0000458
459
Tim Peters07e99cb2001-01-14 23:47:14 +0000460
Barry Warsaw33d8d702000-08-30 03:29:58 +0000461# a mapping between absolute .mo file path and Translation object
462_translations = {}
463
Martin v. Löwis1be64192002-01-11 06:33:28 +0000464def translation(domain, localedir=None, languages=None,
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000465 class_=None, fallback=False, codeset=None):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000466 if class_ is None:
467 class_ = GNUTranslations
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000468 mofiles = find(domain, localedir, languages, all=1)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000469 if not mofiles:
Martin v. Löwis1be64192002-01-11 06:33:28 +0000470 if fallback:
471 return NullTranslations()
Barry Warsaw33d8d702000-08-30 03:29:58 +0000472 raise IOError(ENOENT, 'No translation file found for domain', domain)
Barry Warsaw293b03f2000-10-05 18:48:12 +0000473 # Avoid opening, reading, and parsing the .mo file after it's been done
474 # once.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000475 result = None
476 for mofile in mofiles:
Éric Araujoc17776f2010-10-04 23:59:35 +0000477 key = (class_, os.path.abspath(mofile))
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000478 t = _translations.get(key)
479 if t is None:
Benjamin Peterson14c7bc22009-05-10 01:38:02 +0000480 with open(mofile, 'rb') as fp:
481 t = _translations.setdefault(key, class_(fp))
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000482 # Copy the translation object to allow setting fallbacks and
483 # output charset. All other instance data is shared with the
484 # cached object.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000485 t = copy.copy(t)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000486 if codeset:
487 t.set_output_charset(codeset)
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000488 if result is None:
489 result = t
490 else:
491 result.add_fallback(t)
492 return result
Barry Warsaw33d8d702000-08-30 03:29:58 +0000493
Tim Peters07e99cb2001-01-14 23:47:14 +0000494
Georg Brandl602b9ba2006-02-19 13:26:36 +0000495def install(domain, localedir=None, unicode=False, codeset=None, names=None):
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000496 t = translation(domain, localedir, fallback=True, codeset=codeset)
Georg Brandl602b9ba2006-02-19 13:26:36 +0000497 t.install(unicode, names)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000498
499
Tim Peters07e99cb2001-01-14 23:47:14 +0000500
Barry Warsaw33d8d702000-08-30 03:29:58 +0000501# a mapping b/w domains and locale directories
502_localedirs = {}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000503# a mapping b/w domains and codesets
504_localecodesets = {}
Barry Warsaw33d8d702000-08-30 03:29:58 +0000505# current global domain, `messages' used for compatibility w/ GNU gettext
506_current_domain = 'messages'
Barry Warsaw95be23d2000-08-25 19:13:37 +0000507
508
509def textdomain(domain=None):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000510 global _current_domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000511 if domain is not None:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000512 _current_domain = domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000513 return _current_domain
Barry Warsaw95be23d2000-08-25 19:13:37 +0000514
515
Barry Warsaw33d8d702000-08-30 03:29:58 +0000516def bindtextdomain(domain, localedir=None):
517 global _localedirs
518 if localedir is not None:
519 _localedirs[domain] = localedir
520 return _localedirs.get(domain, _default_localedir)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000521
522
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000523def bind_textdomain_codeset(domain, codeset=None):
524 global _localecodesets
525 if codeset is not None:
526 _localecodesets[domain] = codeset
527 return _localecodesets.get(domain)
528
529
Barry Warsaw95be23d2000-08-25 19:13:37 +0000530def dgettext(domain, message):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000531 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000532 t = translation(domain, _localedirs.get(domain, None),
533 codeset=_localecodesets.get(domain))
Barry Warsaw33d8d702000-08-30 03:29:58 +0000534 except IOError:
535 return message
536 return t.gettext(message)
Tim Peters07e99cb2001-01-14 23:47:14 +0000537
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000538def ldgettext(domain, message):
539 try:
540 t = translation(domain, _localedirs.get(domain, None),
541 codeset=_localecodesets.get(domain))
542 except IOError:
543 return message
544 return t.lgettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000545
Martin v. Löwisd8996052002-11-21 21:45:32 +0000546def dngettext(domain, msgid1, msgid2, n):
547 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000548 t = translation(domain, _localedirs.get(domain, None),
549 codeset=_localecodesets.get(domain))
Martin v. Löwisd8996052002-11-21 21:45:32 +0000550 except IOError:
551 if n == 1:
552 return msgid1
553 else:
554 return msgid2
555 return t.ngettext(msgid1, msgid2, n)
556
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000557def ldngettext(domain, msgid1, msgid2, n):
558 try:
559 t = translation(domain, _localedirs.get(domain, None),
560 codeset=_localecodesets.get(domain))
561 except IOError:
562 if n == 1:
563 return msgid1
564 else:
565 return msgid2
566 return t.lngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000567
Barry Warsaw33d8d702000-08-30 03:29:58 +0000568def gettext(message):
569 return dgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000570
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000571def lgettext(message):
572 return ldgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000573
Martin v. Löwisd8996052002-11-21 21:45:32 +0000574def ngettext(msgid1, msgid2, n):
575 return dngettext(_current_domain, msgid1, msgid2, n)
576
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000577def lngettext(msgid1, msgid2, n):
578 return ldngettext(_current_domain, msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000579
Barry Warsaw33d8d702000-08-30 03:29:58 +0000580# dcgettext() has been deemed unnecessary and is not implemented.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000581
Barry Warsaw33d8d702000-08-30 03:29:58 +0000582# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
583# was:
584#
585# import gettext
586# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
587# _ = cat.gettext
588# print _('Hello World')
Barry Warsaw95be23d2000-08-25 19:13:37 +0000589
Barry Warsaw33d8d702000-08-30 03:29:58 +0000590# The resulting catalog object currently don't support access through a
591# dictionary API, which was supported (but apparently unused) in GNOME
592# gettext.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000593
Barry Warsaw33d8d702000-08-30 03:29:58 +0000594Catalog = translation