blob: 79a025f9500e7d19356e26452ce5911ba6f57e99 [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
49import 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
Skip Montanaro2dd42762001-01-23 15:35:05 +000053__all__ = ["bindtextdomain","textdomain","gettext","dgettext",
54 "find","translation","install","Catalog"]
55
Barry Warsaw33d8d702000-08-30 03:29:58 +000056_default_localedir = os.path.join(sys.prefix, 'share', 'locale')
Barry Warsaw95be23d2000-08-25 19:13:37 +000057
58
Martin v. Löwisd8996052002-11-21 21:45:32 +000059def test(condition, true, false):
60 """
61 Implements the C expression:
62
63 condition ? true : false
64
65 Required to correctly interpret plural forms.
66 """
67 if condition:
68 return true
69 else:
70 return false
71
72
73def c2py(plural):
74 """
75 Gets a C expression as used in PO files for plural forms and
76 returns a Python lambda function that implements an equivalent
77 expression.
78 """
79 # Security check, allow only the "n" identifier
80 from StringIO import StringIO
81 import token, tokenize
82 tokens = tokenize.generate_tokens(StringIO(plural).readline)
Martin v. Löwisa57dccd2003-03-10 16:01:43 +000083 try:
84 danger = [ x for x in tokens if x[0] == token.NAME and x[1] != 'n' ]
85 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 = {}
173 self._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
Martin v. Löwisd8996052002-11-21 21:45:32 +0000192 def ngettext(self, msgid1, msgid2, n):
193 if self._fallback:
194 return self._fallback.ngettext(msgid1, msgid2, n)
195 if n == 1:
196 return msgid1
197 else:
198 return msgid2
199
Barry Warsaw33d8d702000-08-30 03:29:58 +0000200 def ugettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000201 if self._fallback:
202 return self._fallback.ugettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000203 return unicode(message)
204
Martin v. Löwisd8996052002-11-21 21:45:32 +0000205 def ungettext(self, msgid1, msgid2, n):
206 if self._fallback:
207 return self._fallback.ungettext(msgid1, msgid2, n)
208 if n == 1:
209 return unicode(msgid1)
210 else:
211 return unicode(msgid2)
212
Barry Warsaw33d8d702000-08-30 03:29:58 +0000213 def info(self):
214 return self._info
215
216 def charset(self):
217 return self._charset
218
219 def install(self, unicode=0):
220 import __builtin__
221 __builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
222
223
224class GNUTranslations(NullTranslations):
225 # Magic number of .mo files
Barry Warsaw09707e32002-08-14 15:09:12 +0000226 LE_MAGIC = 0x950412deL
227 BE_MAGIC = 0xde120495L
Barry Warsaw95be23d2000-08-25 19:13:37 +0000228
229 def _parse(self, fp):
230 """Override this method to support alternative .mo formats."""
231 unpack = struct.unpack
232 filename = getattr(fp, 'name', '')
233 # Parse the .mo file header, which consists of 5 little endian 32
234 # bit words.
Barry Warsaw33d8d702000-08-30 03:29:58 +0000235 self._catalog = catalog = {}
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000236 self.plural = lambda n: int(n != 1) # germanic plural by default
Barry Warsaw95be23d2000-08-25 19:13:37 +0000237 buf = fp.read()
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000238 buflen = len(buf)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000239 # Are we big endian or little endian?
Barry Warsaw09707e32002-08-14 15:09:12 +0000240 magic = unpack('<I', buf[:4])[0]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000241 if magic == self.LE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000242 version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
243 ii = '<II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000244 elif magic == self.BE_MAGIC:
Barry Warsaw09707e32002-08-14 15:09:12 +0000245 version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
246 ii = '>II'
Barry Warsaw33d8d702000-08-30 03:29:58 +0000247 else:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000248 raise IOError(0, 'Bad magic number', filename)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000249 # Now put all messages from the .mo file buffer into the catalog
250 # dictionary.
251 for i in xrange(0, msgcount):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000252 mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000253 mend = moff + mlen
Barry Warsaw33d8d702000-08-30 03:29:58 +0000254 tlen, toff = unpack(ii, buf[transidx:transidx+8])
Barry Warsaw09707e32002-08-14 15:09:12 +0000255 tend = toff + tlen
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000256 if mend < buflen and tend < buflen:
Martin v. Löwisd8996052002-11-21 21:45:32 +0000257 msg = buf[moff:mend]
Barry Warsaw33d8d702000-08-30 03:29:58 +0000258 tmsg = buf[toff:tend]
Martin v. Löwisd8996052002-11-21 21:45:32 +0000259 if msg.find('\x00') >= 0:
260 # Plural forms
261 msgid1, msgid2 = msg.split('\x00')
262 tmsg = tmsg.split('\x00')
263 for i in range(len(tmsg)):
264 catalog[(msgid1, i)] = tmsg[i]
265 else:
266 catalog[msg] = tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000267 else:
268 raise IOError(0, 'File is corrupt', filename)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000269 # See if we're looking at GNU .mo conventions for metadata
Martin v. Löwisa57dccd2003-03-10 16:01:43 +0000270 if mlen == 0:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000271 # Catalog description
272 for item in tmsg.split('\n'):
273 item = item.strip()
274 if not item:
275 continue
276 k, v = item.split(':', 1)
277 k = k.strip().lower()
278 v = v.strip()
279 self._info[k] = v
280 if k == 'content-type':
281 self._charset = v.split('charset=')[1]
Martin v. Löwisd8996052002-11-21 21:45:32 +0000282 elif k == 'plural-forms':
283 v = v.split(';')
284## nplurals = v[0].split('nplurals=')[1]
285## nplurals = int(nplurals.strip())
286 plural = v[1].split('plural=')[1]
287 self.plural = c2py(plural)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000288 # advance to next entry in the seek tables
Barry Warsawfa488ec2000-08-25 20:26:43 +0000289 masteridx += 8
290 transidx += 8
Barry Warsaw33d8d702000-08-30 03:29:58 +0000291
292 def gettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000293 try:
294 return self._catalog[message]
295 except KeyError:
296 if self._fallback:
297 return self._fallback.gettext(message)
298 return message
Barry Warsaw33d8d702000-08-30 03:29:58 +0000299
Martin v. Löwisd8996052002-11-21 21:45:32 +0000300
301 def ngettext(self, msgid1, msgid2, n):
302 try:
303 return self._catalog[(msgid1, self.plural(n))]
304 except KeyError:
305 if self._fallback:
306 return self._fallback.ngettext(msgid1, msgid2, n)
307 if n == 1:
308 return msgid1
309 else:
310 return msgid2
311
312
Barry Warsaw33d8d702000-08-30 03:29:58 +0000313 def ugettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000314 try:
315 tmsg = self._catalog[message]
316 except KeyError:
317 if self._fallback:
318 return self._fallback.ugettext(message)
319 tmsg = message
Barry Warsaw33d8d702000-08-30 03:29:58 +0000320 return unicode(tmsg, self._charset)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000321
322
Martin v. Löwisd8996052002-11-21 21:45:32 +0000323 def ungettext(self, msgid1, msgid2, n):
324 try:
325 tmsg = self._catalog[(msgid1, self.plural(n))]
326 except KeyError:
327 if self._fallback:
328 return self._fallback.ungettext(msgid1, msgid2, n)
329 if n == 1:
330 tmsg = msgid1
331 else:
332 tmsg = msgid2
333 return unicode(tmsg, self._charset)
334
Tim Peters07e99cb2001-01-14 23:47:14 +0000335
Barry Warsaw95be23d2000-08-25 19:13:37 +0000336# Locate a .mo file using the gettext strategy
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000337def find(domain, localedir=None, languages=None, all=0):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000338 # Get some reasonable defaults for arguments that were not supplied
Barry Warsaw95be23d2000-08-25 19:13:37 +0000339 if localedir is None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000340 localedir = _default_localedir
Barry Warsaw95be23d2000-08-25 19:13:37 +0000341 if languages is None:
342 languages = []
343 for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
344 val = os.environ.get(envar)
345 if val:
346 languages = val.split(':')
347 break
348 if 'C' not in languages:
349 languages.append('C')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000350 # now normalize and expand the languages
Barry Warsaw75f81012000-10-16 15:47:50 +0000351 nelangs = []
Barry Warsawfa488ec2000-08-25 20:26:43 +0000352 for lang in languages:
353 for nelang in _expand_lang(lang):
Barry Warsaw75f81012000-10-16 15:47:50 +0000354 if nelang not in nelangs:
355 nelangs.append(nelang)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000356 # select a language
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000357 if all:
358 result = []
359 else:
360 result = None
Barry Warsaw75f81012000-10-16 15:47:50 +0000361 for lang in nelangs:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000362 if lang == 'C':
363 break
Barry Warsaw84314b72000-08-25 19:53:17 +0000364 mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000365 if os.path.exists(mofile):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000366 if all:
367 result.append(mofile)
368 else:
369 return mofile
370 return result
Barry Warsaw95be23d2000-08-25 19:13:37 +0000371
372
Tim Peters07e99cb2001-01-14 23:47:14 +0000373
Barry Warsaw33d8d702000-08-30 03:29:58 +0000374# a mapping between absolute .mo file path and Translation object
375_translations = {}
376
Martin v. Löwis1be64192002-01-11 06:33:28 +0000377def translation(domain, localedir=None, languages=None,
378 class_=None, fallback=0):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000379 if class_ is None:
380 class_ = GNUTranslations
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000381 mofiles = find(domain, localedir, languages, all=1)
382 if len(mofiles)==0:
Martin v. Löwis1be64192002-01-11 06:33:28 +0000383 if fallback:
384 return NullTranslations()
Barry Warsaw33d8d702000-08-30 03:29:58 +0000385 raise IOError(ENOENT, 'No translation file found for domain', domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000386 # TBD: do we need to worry about the file pointer getting collected?
Barry Warsaw293b03f2000-10-05 18:48:12 +0000387 # Avoid opening, reading, and parsing the .mo file after it's been done
388 # once.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000389 result = None
390 for mofile in mofiles:
391 key = os.path.abspath(mofile)
392 t = _translations.get(key)
393 if t is None:
394 t = _translations.setdefault(key, class_(open(mofile, 'rb')))
395 # Copy the translation object to allow setting fallbacks.
396 # All other instance data is shared with the cached object.
397 t = copy.copy(t)
398 if result is None:
399 result = t
400 else:
401 result.add_fallback(t)
402 return result
Barry Warsaw33d8d702000-08-30 03:29:58 +0000403
Tim Peters07e99cb2001-01-14 23:47:14 +0000404
Barry Warsaw33d8d702000-08-30 03:29:58 +0000405def install(domain, localedir=None, unicode=0):
Martin v. Löwis1be64192002-01-11 06:33:28 +0000406 translation(domain, localedir, fallback=1).install(unicode)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000407
408
Tim Peters07e99cb2001-01-14 23:47:14 +0000409
Barry Warsaw33d8d702000-08-30 03:29:58 +0000410# a mapping b/w domains and locale directories
411_localedirs = {}
412# current global domain, `messages' used for compatibility w/ GNU gettext
413_current_domain = 'messages'
Barry Warsaw95be23d2000-08-25 19:13:37 +0000414
415
416def textdomain(domain=None):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000417 global _current_domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000418 if domain is not None:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000419 _current_domain = domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000420 return _current_domain
Barry Warsaw95be23d2000-08-25 19:13:37 +0000421
422
Barry Warsaw33d8d702000-08-30 03:29:58 +0000423def bindtextdomain(domain, localedir=None):
424 global _localedirs
425 if localedir is not None:
426 _localedirs[domain] = localedir
427 return _localedirs.get(domain, _default_localedir)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000428
429
430def dgettext(domain, message):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000431 try:
432 t = translation(domain, _localedirs.get(domain, None))
433 except IOError:
434 return message
435 return t.gettext(message)
Tim Peters07e99cb2001-01-14 23:47:14 +0000436
Barry Warsaw33d8d702000-08-30 03:29:58 +0000437
Martin v. Löwisd8996052002-11-21 21:45:32 +0000438def dngettext(domain, msgid1, msgid2, n):
439 try:
440 t = translation(domain, _localedirs.get(domain, None))
441 except IOError:
442 if n == 1:
443 return msgid1
444 else:
445 return msgid2
446 return t.ngettext(msgid1, msgid2, n)
447
448
Barry Warsaw33d8d702000-08-30 03:29:58 +0000449def gettext(message):
450 return dgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000451
452
Martin v. Löwisd8996052002-11-21 21:45:32 +0000453def ngettext(msgid1, msgid2, n):
454 return dngettext(_current_domain, msgid1, msgid2, n)
455
456
Barry Warsaw33d8d702000-08-30 03:29:58 +0000457# dcgettext() has been deemed unnecessary and is not implemented.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000458
Barry Warsaw33d8d702000-08-30 03:29:58 +0000459# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
460# was:
461#
462# import gettext
463# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
464# _ = cat.gettext
465# print _('Hello World')
Barry Warsaw95be23d2000-08-25 19:13:37 +0000466
Barry Warsaw33d8d702000-08-30 03:29:58 +0000467# The resulting catalog object currently don't support access through a
468# dictionary API, which was supported (but apparently unused) in GNOME
469# gettext.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000470
Barry Warsaw33d8d702000-08-30 03:29:58 +0000471Catalog = translation