blob: a23c2acf007a722e3592a22131c9966bc808e8d2 [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:
86 raise ValueError, \
87 'plural forms expression error, maybe unbalanced parenthesis'
88 else:
89 if danger:
90 raise ValueError, 'plural forms expression could be dangerous'
Martin v. Löwisd8996052002-11-21 21:45:32 +000091
92 # Replace some C operators by their Python equivalents
93 plural = plural.replace('&&', ' and ')
94 plural = plural.replace('||', ' or ')
95
Martin v. Löwisa57dccd2003-03-10 16:01:43 +000096 expr = re.compile(r'\!([^=])')
97 plural = expr.sub(' not \\1', plural)
Martin v. Löwisd8996052002-11-21 21:45:32 +000098
99 # Regular expression and replacement function used to transform
100 # "a?b:c" to "test(a,b,c)".
101 expr = re.compile(r'(.*?)\?(.*?):(.*)')
102 def repl(x):
103 return "test(%s, %s, %s)" % (x.group(1), x.group(2),
104 expr.sub(repl, x.group(3)))
105
106 # Code to transform the plural expression, taking care of parentheses
107 stack = ['']
108 for c in plural:
109 if c == '(':
110 stack.append('')
111 elif c == ')':
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000112 if len(stack) == 1:
113 # Actually, we never reach this code, because unbalanced
114 # parentheses get caught in the security check at the
115 # beginning.
Martin v. Löwisd8996052002-11-21 21:45:32 +0000116 raise ValueError, 'unbalanced parenthesis in plural form'
117 s = expr.sub(repl, stack.pop())
118 stack[-1] += '(%s)' % s
119 else:
120 stack[-1] += c
121 plural = expr.sub(repl, stack.pop())
122
123 return eval('lambda n: int(%s)' % plural)
124
125
Tim Peters07e99cb2001-01-14 23:47:14 +0000126
Barry Warsawfa488ec2000-08-25 20:26:43 +0000127def _expand_lang(locale):
128 from locale import normalize
129 locale = normalize(locale)
130 COMPONENT_CODESET = 1 << 0
131 COMPONENT_TERRITORY = 1 << 1
132 COMPONENT_MODIFIER = 1 << 2
133 # split up the locale into its base components
134 mask = 0
135 pos = locale.find('@')
136 if pos >= 0:
137 modifier = locale[pos:]
138 locale = locale[:pos]
139 mask |= COMPONENT_MODIFIER
140 else:
141 modifier = ''
142 pos = locale.find('.')
143 if pos >= 0:
144 codeset = locale[pos:]
145 locale = locale[:pos]
146 mask |= COMPONENT_CODESET
147 else:
148 codeset = ''
149 pos = locale.find('_')
150 if pos >= 0:
151 territory = locale[pos:]
152 locale = locale[:pos]
153 mask |= COMPONENT_TERRITORY
154 else:
155 territory = ''
156 language = locale
157 ret = []
158 for i in range(mask+1):
159 if not (i & ~mask): # if all components for this combo exist ...
160 val = language
161 if i & COMPONENT_TERRITORY: val += territory
162 if i & COMPONENT_CODESET: val += codeset
163 if i & COMPONENT_MODIFIER: val += modifier
164 ret.append(val)
165 ret.reverse()
166 return ret
167
168
Tim Peters07e99cb2001-01-14 23:47:14 +0000169
Barry Warsaw33d8d702000-08-30 03:29:58 +0000170class NullTranslations:
171 def __init__(self, fp=None):
172 self._info = {}
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000173 self._charset = None
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000174 self._output_charset = None
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000175 self._fallback = None
Raymond Hettinger094662a2002-06-01 01:29:16 +0000176 if fp is not None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000177 self._parse(fp)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000178
Barry Warsaw33d8d702000-08-30 03:29:58 +0000179 def _parse(self, fp):
180 pass
181
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000182 def add_fallback(self, fallback):
183 if self._fallback:
184 self._fallback.add_fallback(fallback)
185 else:
186 self._fallback = fallback
187
Barry Warsaw33d8d702000-08-30 03:29:58 +0000188 def gettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000189 if self._fallback:
190 return self._fallback.gettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000191 return message
192
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000193 def lgettext(self, message):
194 if self._fallback:
195 return self._fallback.lgettext(message)
196 return message
197
Martin v. Löwisd8996052002-11-21 21:45:32 +0000198 def ngettext(self, msgid1, msgid2, n):
199 if self._fallback:
200 return self._fallback.ngettext(msgid1, msgid2, n)
201 if n == 1:
202 return msgid1
203 else:
204 return msgid2
205
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000206 def lngettext(self, msgid1, msgid2, n):
207 if self._fallback:
208 return self._fallback.lngettext(msgid1, msgid2, n)
209 if n == 1:
210 return msgid1
211 else:
212 return msgid2
213
Barry Warsaw33d8d702000-08-30 03:29:58 +0000214 def ugettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000215 if self._fallback:
216 return self._fallback.ugettext(message)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000217 return str(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000218
Martin v. Löwisd8996052002-11-21 21:45:32 +0000219 def ungettext(self, msgid1, msgid2, n):
220 if self._fallback:
221 return self._fallback.ungettext(msgid1, msgid2, n)
222 if n == 1:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000223 return str(msgid1)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000224 else:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000225 return str(msgid2)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000226
Barry Warsaw33d8d702000-08-30 03:29:58 +0000227 def info(self):
228 return self._info
229
230 def charset(self):
231 return self._charset
232
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000233 def output_charset(self):
234 return self._output_charset
235
236 def set_output_charset(self, charset):
237 self._output_charset = charset
238
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000239 def install(self, str=False, names=None):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000240 import __builtin__
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000241 __builtin__.__dict__['_'] = str and self.ugettext or self.gettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000242 if hasattr(names, "__contains__"):
243 if "gettext" in names:
244 __builtin__.__dict__['gettext'] = __builtin__.__dict__['_']
245 if "ngettext" in names:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000246 __builtin__.__dict__['ngettext'] = (str and self.ungettext
Georg Brandl602b9ba2006-02-19 13:26:36 +0000247 or self.ngettext)
248 if "lgettext" in names:
249 __builtin__.__dict__['lgettext'] = self.lgettext
250 if "lngettext" in names:
251 __builtin__.__dict__['lngettext'] = self.lngettext
Barry Warsaw33d8d702000-08-30 03:29:58 +0000252
253
254class GNUTranslations(NullTranslations):
255 # Magic number of .mo files
Guido van Rossume2a383d2007-01-15 16:59:06 +0000256 LE_MAGIC = 0x950412de
257 BE_MAGIC = 0xde120495
Barry Warsaw95be23d2000-08-25 19:13:37 +0000258
259 def _parse(self, fp):
260 """Override this method to support alternative .mo formats."""
261 unpack = struct.unpack
262 filename = getattr(fp, 'name', '')
263 # Parse the .mo file header, which consists of 5 little endian 32
264 # bit words.
Barry Warsaw33d8d702000-08-30 03:29:58 +0000265 self._catalog = catalog = {}
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000266 self.plural = lambda n: int(n != 1) # germanic plural by default
Barry Warsaw95be23d2000-08-25 19:13:37 +0000267 buf = fp.read()
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000268 buflen = len(buf)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000269 # Are we big endian or little endian?
Barry Warsaw09707e32002-08-14 15:09:12 +0000270 magic = unpack('<I', buf[:4])[0]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000271 if magic == self.LE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000272 version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
273 ii = '<II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000274 elif magic == self.BE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000275 version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
276 ii = '>II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000277 else:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000278 raise IOError(0, 'Bad magic number', filename)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000279 # Now put all messages from the .mo file buffer into the catalog
280 # dictionary.
Guido van Rossum805365e2007-05-07 22:24:25 +0000281 for i in range(0, msgcount):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000282 mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000283 mend = moff + mlen
Barry Warsaw33d8d702000-08-30 03:29:58 +0000284 tlen, toff = unpack(ii, buf[transidx:transidx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000285 tend = toff + tlen
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000286 if mend < buflen and tend < buflen:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000287 msg = buf[moff:mend]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000288 tmsg = buf[toff:tend]
Barry Warsaw95be23d2000-08-25 19:13:37 +0000289 else:
290 raise IOError(0, 'File is corrupt', filename)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000291 # See if we're looking at GNU .mo conventions for metadata
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000292 if mlen == 0:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000293 # Catalog description
Barry Warsawb8c78762003-10-04 02:28:31 +0000294 lastk = k = None
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000295 for item in tmsg.splitlines():
Barry Warsaw33d8d702000-08-30 03:29:58 +0000296 item = item.strip()
297 if not item:
298 continue
Barry Warsaw7de63f52003-05-20 17:26:48 +0000299 if ':' in item:
300 k, v = item.split(':', 1)
301 k = k.strip().lower()
302 v = v.strip()
303 self._info[k] = v
304 lastk = k
305 elif lastk:
306 self._info[lastk] += '\n' + item
Barry Warsaw33d8d702000-08-30 03:29:58 +0000307 if k == 'content-type':
308 self._charset = v.split('charset=')[1]
Martin v. Löwisd8996052002-11-21 21:45:32 +0000309 elif k == 'plural-forms':
310 v = v.split(';')
Martin v. Löwisd8996052002-11-21 21:45:32 +0000311 plural = v[1].split('plural=')[1]
312 self.plural = c2py(plural)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000313 # Note: we unconditionally convert both msgids and msgstrs to
314 # Unicode using the character encoding specified in the charset
315 # parameter of the Content-Type header. The gettext documentation
316 # strongly encourages msgids to be us-ascii, but some appliations
317 # require alternative encodings (e.g. Zope's ZCML and ZPT). For
318 # traditional gettext applications, the msgid conversion will
319 # cause no problems since us-ascii should always be a subset of
320 # the charset encoding. We may want to fall back to 8-bit msgids
321 # if the Unicode conversion fails.
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000322 if '\x00' in msg:
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000323 # Plural forms
324 msgid1, msgid2 = msg.split('\x00')
325 tmsg = tmsg.split('\x00')
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000326 if self._charset:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000327 msgid1 = str(msgid1, self._charset)
328 tmsg = [str(x, self._charset) for x in tmsg]
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000329 for i in range(len(tmsg)):
330 catalog[(msgid1, i)] = tmsg[i]
331 else:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000332 if self._charset:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000333 msg = str(msg, self._charset)
334 tmsg = str(tmsg, self._charset)
Barry Warsaw6008cbd2003-04-11 20:26:47 +0000335 catalog[msg] = tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000336 # advance to next entry in the seek tables
Barry Warsawfa488ec2000-08-25 20:26:43 +0000337 masteridx += 8
338 transidx += 8
Barry Warsaw33d8d702000-08-30 03:29:58 +0000339
340 def gettext(self, message):
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000341 missing = object()
342 tmsg = self._catalog.get(message, missing)
343 if tmsg is missing:
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000344 if self._fallback:
345 return self._fallback.gettext(message)
346 return message
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000347 # Encode the Unicode tmsg back to an 8-bit string, if possible
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000348 if self._output_charset:
349 return tmsg.encode(self._output_charset)
350 elif self._charset:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000351 return tmsg.encode(self._charset)
352 return tmsg
Barry Warsaw33d8d702000-08-30 03:29:58 +0000353
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000354 def lgettext(self, message):
355 missing = object()
356 tmsg = self._catalog.get(message, missing)
357 if tmsg is missing:
358 if self._fallback:
359 return self._fallback.lgettext(message)
360 return message
361 if self._output_charset:
362 return tmsg.encode(self._output_charset)
363 return tmsg.encode(locale.getpreferredencoding())
364
Martin v. Löwisd8996052002-11-21 21:45:32 +0000365 def ngettext(self, msgid1, msgid2, n):
366 try:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000367 tmsg = self._catalog[(msgid1, self.plural(n))]
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000368 if self._output_charset:
369 return tmsg.encode(self._output_charset)
370 elif self._charset:
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000371 return tmsg.encode(self._charset)
372 return tmsg
Martin v. Löwisd8996052002-11-21 21:45:32 +0000373 except KeyError:
374 if self._fallback:
375 return self._fallback.ngettext(msgid1, msgid2, n)
376 if n == 1:
377 return msgid1
378 else:
379 return msgid2
380
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000381 def lngettext(self, msgid1, msgid2, n):
382 try:
383 tmsg = self._catalog[(msgid1, self.plural(n))]
384 if self._output_charset:
385 return tmsg.encode(self._output_charset)
386 return tmsg.encode(locale.getpreferredencoding())
387 except KeyError:
388 if self._fallback:
389 return self._fallback.lngettext(msgid1, msgid2, n)
390 if n == 1:
391 return msgid1
392 else:
393 return msgid2
394
Barry Warsaw33d8d702000-08-30 03:29:58 +0000395 def ugettext(self, message):
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000396 missing = object()
397 tmsg = self._catalog.get(message, missing)
398 if tmsg is missing:
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000399 if self._fallback:
400 return self._fallback.ugettext(message)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000401 return str(message)
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000402 return tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000403
Martin v. Löwisd8996052002-11-21 21:45:32 +0000404 def ungettext(self, msgid1, msgid2, n):
405 try:
406 tmsg = self._catalog[(msgid1, self.plural(n))]
407 except KeyError:
408 if self._fallback:
409 return self._fallback.ungettext(msgid1, msgid2, n)
410 if n == 1:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000411 tmsg = str(msgid1)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000412 else:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000413 tmsg = str(msgid2)
Barry Warsawa1ce93f2003-04-11 18:36:43 +0000414 return tmsg
Martin v. Löwisd8996052002-11-21 21:45:32 +0000415
Tim Peters07e99cb2001-01-14 23:47:14 +0000416
Barry Warsaw95be23d2000-08-25 19:13:37 +0000417# Locate a .mo file using the gettext strategy
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000418def find(domain, localedir=None, languages=None, all=0):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000419 # Get some reasonable defaults for arguments that were not supplied
Barry Warsaw95be23d2000-08-25 19:13:37 +0000420 if localedir is None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000421 localedir = _default_localedir
Barry Warsaw95be23d2000-08-25 19:13:37 +0000422 if languages is None:
423 languages = []
424 for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
425 val = os.environ.get(envar)
426 if val:
427 languages = val.split(':')
428 break
429 if 'C' not in languages:
430 languages.append('C')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000431 # now normalize and expand the languages
Barry Warsaw75f81012000-10-16 15:47:50 +0000432 nelangs = []
Barry Warsawfa488ec2000-08-25 20:26:43 +0000433 for lang in languages:
434 for nelang in _expand_lang(lang):
Barry Warsaw75f81012000-10-16 15:47:50 +0000435 if nelang not in nelangs:
436 nelangs.append(nelang)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000437 # select a language
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000438 if all:
439 result = []
440 else:
441 result = None
Barry Warsaw75f81012000-10-16 15:47:50 +0000442 for lang in nelangs:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000443 if lang == 'C':
444 break
Barry Warsaw84314b72000-08-25 19:53:17 +0000445 mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000446 if os.path.exists(mofile):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000447 if all:
448 result.append(mofile)
449 else:
450 return mofile
451 return result
Barry Warsaw95be23d2000-08-25 19:13:37 +0000452
453
Tim Peters07e99cb2001-01-14 23:47:14 +0000454
Barry Warsaw33d8d702000-08-30 03:29:58 +0000455# a mapping between absolute .mo file path and Translation object
456_translations = {}
457
Martin v. Löwis1be64192002-01-11 06:33:28 +0000458def translation(domain, localedir=None, languages=None,
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000459 class_=None, fallback=False, codeset=None):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000460 if class_ is None:
461 class_ = GNUTranslations
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000462 mofiles = find(domain, localedir, languages, all=1)
Barry Warsawc4acc2b2003-04-24 18:13:39 +0000463 if not mofiles:
Martin v. Löwis1be64192002-01-11 06:33:28 +0000464 if fallback:
465 return NullTranslations()
Barry Warsaw33d8d702000-08-30 03:29:58 +0000466 raise IOError(ENOENT, 'No translation file found for domain', domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000467 # TBD: do we need to worry about the file pointer getting collected?
Barry Warsaw293b03f2000-10-05 18:48:12 +0000468 # Avoid opening, reading, and parsing the .mo file after it's been done
469 # once.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000470 result = None
471 for mofile in mofiles:
472 key = os.path.abspath(mofile)
473 t = _translations.get(key)
474 if t is None:
475 t = _translations.setdefault(key, class_(open(mofile, 'rb')))
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000476 # Copy the translation object to allow setting fallbacks and
477 # output charset. All other instance data is shared with the
478 # cached object.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000479 t = copy.copy(t)
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000480 if codeset:
481 t.set_output_charset(codeset)
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000482 if result is None:
483 result = t
484 else:
485 result.add_fallback(t)
486 return result
Barry Warsaw33d8d702000-08-30 03:29:58 +0000487
Tim Peters07e99cb2001-01-14 23:47:14 +0000488
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000489def install(domain, localedir=None, str=False, codeset=None, names=None):
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000490 t = translation(domain, localedir, fallback=True, codeset=codeset)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000491 t.install(str, names)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000492
493
Tim Peters07e99cb2001-01-14 23:47:14 +0000494
Barry Warsaw33d8d702000-08-30 03:29:58 +0000495# a mapping b/w domains and locale directories
496_localedirs = {}
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000497# a mapping b/w domains and codesets
498_localecodesets = {}
Barry Warsaw33d8d702000-08-30 03:29:58 +0000499# current global domain, `messages' used for compatibility w/ GNU gettext
500_current_domain = 'messages'
Barry Warsaw95be23d2000-08-25 19:13:37 +0000501
502
503def textdomain(domain=None):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000504 global _current_domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000505 if domain is not None:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000506 _current_domain = domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000507 return _current_domain
Barry Warsaw95be23d2000-08-25 19:13:37 +0000508
509
Barry Warsaw33d8d702000-08-30 03:29:58 +0000510def bindtextdomain(domain, localedir=None):
511 global _localedirs
512 if localedir is not None:
513 _localedirs[domain] = localedir
514 return _localedirs.get(domain, _default_localedir)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000515
516
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000517def bind_textdomain_codeset(domain, codeset=None):
518 global _localecodesets
519 if codeset is not None:
520 _localecodesets[domain] = codeset
521 return _localecodesets.get(domain)
522
523
Barry Warsaw95be23d2000-08-25 19:13:37 +0000524def dgettext(domain, message):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000525 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000526 t = translation(domain, _localedirs.get(domain, None),
527 codeset=_localecodesets.get(domain))
Barry Warsaw33d8d702000-08-30 03:29:58 +0000528 except IOError:
529 return message
530 return t.gettext(message)
Tim Peters07e99cb2001-01-14 23:47:14 +0000531
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000532def ldgettext(domain, message):
533 try:
534 t = translation(domain, _localedirs.get(domain, None),
535 codeset=_localecodesets.get(domain))
536 except IOError:
537 return message
538 return t.lgettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000539
Martin v. Löwisd8996052002-11-21 21:45:32 +0000540def dngettext(domain, msgid1, msgid2, n):
541 try:
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000542 t = translation(domain, _localedirs.get(domain, None),
543 codeset=_localecodesets.get(domain))
Martin v. Löwisd8996052002-11-21 21:45:32 +0000544 except IOError:
545 if n == 1:
546 return msgid1
547 else:
548 return msgid2
549 return t.ngettext(msgid1, msgid2, n)
550
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000551def ldngettext(domain, msgid1, msgid2, n):
552 try:
553 t = translation(domain, _localedirs.get(domain, None),
554 codeset=_localecodesets.get(domain))
555 except IOError:
556 if n == 1:
557 return msgid1
558 else:
559 return msgid2
560 return t.lngettext(msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000561
Barry Warsaw33d8d702000-08-30 03:29:58 +0000562def gettext(message):
563 return dgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000564
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000565def lgettext(message):
566 return ldgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000567
Martin v. Löwisd8996052002-11-21 21:45:32 +0000568def ngettext(msgid1, msgid2, n):
569 return dngettext(_current_domain, msgid1, msgid2, n)
570
Gustavo Niemeyer7bd33c52004-07-22 18:44:01 +0000571def lngettext(msgid1, msgid2, n):
572 return ldngettext(_current_domain, msgid1, msgid2, n)
Martin v. Löwisd8996052002-11-21 21:45:32 +0000573
Barry Warsaw33d8d702000-08-30 03:29:58 +0000574# dcgettext() has been deemed unnecessary and is not implemented.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000575
Barry Warsaw33d8d702000-08-30 03:29:58 +0000576# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
577# was:
578#
579# import gettext
580# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
581# _ = cat.gettext
582# print _('Hello World')
Barry Warsaw95be23d2000-08-25 19:13:37 +0000583
Barry Warsaw33d8d702000-08-30 03:29:58 +0000584# The resulting catalog object currently don't support access through a
585# dictionary API, which was supported (but apparently unused) in GNOME
586# gettext.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000587
Barry Warsaw33d8d702000-08-30 03:29:58 +0000588Catalog = translation