1 """Internationalization and localization support.
3 This module provides internationalization (I18N) and localization (L10N)
4 support for your Python programs by providing an interface to the GNU gettext
5 message catalog library.
7 I18N refers to the operation by which a program is made aware of multiple
8 languages. L10N refers to the adaptation of your program, once
9 internationalized, to the local language and cultural habits.
13 # This module represents the integration of work, contributions, feedback, and
14 # suggestions from the following people:
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.
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.
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
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.
32 # Francois Pinard and Marc-Andre Lemburg also contributed valuably to this
35 # J. David Ibanez implemented plural forms.
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.
45 # - Support Solaris .mo file formats. Unfortunately, we've been unable to
46 # find this format documented anywhere.
49 import copy
, os
, re
, struct
, sys
50 from errno
import ENOENT
53 __all__
= ["bindtextdomain","textdomain","gettext","dgettext",
54 "find","translation","install","Catalog"]
56 _default_localedir
= os
.path
.join(sys
.prefix
, 'share', 'locale')
59 def test(condition
, true
, false
):
61 Implements the C expression:
63 condition ? true : false
65 Required to correctly interpret plural forms.
75 Gets a C expression as used in PO files for plural forms and
76 returns a Python lambda function that implements an equivalent
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
)
83 danger
= [ x
for x
in tokens
if x
[0] == token
.NAME
and x
[1] != 'n' ]
85 raise ValueError, 'dangerous expression'
87 # Replace some C operators by their Python equivalents
88 plural
= plural
.replace('&&', ' and ')
89 plural
= plural
.replace('||', ' or ')
91 expr
= re
.compile(r
'\![^=]')
92 plural
= expr
.sub(' not ', plural
)
94 # Regular expression and replacement function used to transform
95 # "a?b:c" to "test(a,b,c)".
96 expr
= re
.compile(r
'(.*?)\?(.*?):(.*)')
98 return "test(%s, %s, %s)" % (x
.group(1), x
.group(2),
99 expr
.sub(repl
, x
.group(3)))
101 # Code to transform the plural expression, taking care of parentheses
108 raise ValueError, 'unbalanced parenthesis in plural form'
109 s
= expr
.sub(repl
, stack
.pop())
110 stack
[-1] += '(%s)' % s
113 plural
= expr
.sub(repl
, stack
.pop())
115 return eval('lambda n: int(%s)' % plural
)
119 def _expand_lang(locale
):
120 from locale
import normalize
121 locale
= normalize(locale
)
122 COMPONENT_CODESET
= 1 << 0
123 COMPONENT_TERRITORY
= 1 << 1
124 COMPONENT_MODIFIER
= 1 << 2
125 # split up the locale into its base components
127 pos
= locale
.find('@')
129 modifier
= locale
[pos
:]
130 locale
= locale
[:pos
]
131 mask |
= COMPONENT_MODIFIER
134 pos
= locale
.find('.')
136 codeset
= locale
[pos
:]
137 locale
= locale
[:pos
]
138 mask |
= COMPONENT_CODESET
141 pos
= locale
.find('_')
143 territory
= locale
[pos
:]
144 locale
= locale
[:pos
]
145 mask |
= COMPONENT_TERRITORY
150 for i
in range(mask
+1):
151 if not (i
& ~mask
): # if all components for this combo exist ...
153 if i
& COMPONENT_TERRITORY
: val
+= territory
154 if i
& COMPONENT_CODESET
: val
+= codeset
155 if i
& COMPONENT_MODIFIER
: val
+= modifier
162 class NullTranslations
:
163 def __init__(self
, fp
=None):
166 self
._fallback
= None
170 def _parse(self
, fp
):
173 def add_fallback(self
, fallback
):
175 self
._fallback
.add_fallback(fallback
)
177 self
._fallback
= fallback
179 def gettext(self
, message
):
181 return self
._fallback
.gettext(message
)
184 def ngettext(self
, msgid1
, msgid2
, n
):
186 return self
._fallback
.ngettext(msgid1
, msgid2
, n
)
192 def ugettext(self
, message
):
194 return self
._fallback
.ugettext(message
)
195 return unicode(message
)
197 def ungettext(self
, msgid1
, msgid2
, n
):
199 return self
._fallback
.ungettext(msgid1
, msgid2
, n
)
201 return unicode(msgid1
)
203 return unicode(msgid2
)
211 def install(self
, unicode=0):
213 __builtin__
.__dict
__['_'] = unicode and self
.ugettext
or self
.gettext
216 class GNUTranslations(NullTranslations
):
217 # Magic number of .mo files
218 LE_MAGIC
= 0x950412deL
219 BE_MAGIC
= 0xde120495L
221 def _parse(self
, fp
):
222 """Override this method to support alternative .mo formats."""
223 unpack
= struct
.unpack
224 filename
= getattr(fp
, 'name', '')
225 # Parse the .mo file header, which consists of 5 little endian 32
227 self
._catalog
= catalog
= {}
230 # Are we big endian or little endian?
231 magic
= unpack('<I', buf
[:4])[0]
232 if magic
== self
.LE_MAGIC
:
233 version
, msgcount
, masteridx
, transidx
= unpack('<4I', buf
[4:20])
235 elif magic
== self
.BE_MAGIC
:
236 version
, msgcount
, masteridx
, transidx
= unpack('>4I', buf
[4:20])
239 raise IOError(0, 'Bad magic number', filename
)
240 # Now put all messages from the .mo file buffer into the catalog
242 for i
in xrange(0, msgcount
):
243 mlen
, moff
= unpack(ii
, buf
[masteridx
:masteridx
+8])
245 tlen
, toff
= unpack(ii
, buf
[transidx
:transidx
+8])
247 if mend
< buflen
and tend
< buflen
:
249 tmsg
= buf
[toff
:tend
]
250 if msg
.find('\x00') >= 0:
252 msgid1
, msgid2
= msg
.split('\x00')
253 tmsg
= tmsg
.split('\x00')
254 for i
in range(len(tmsg
)):
255 catalog
[(msgid1
, i
)] = tmsg
[i
]
259 raise IOError(0, 'File is corrupt', filename
)
260 # See if we're looking at GNU .mo conventions for metadata
261 if mlen
== 0 and tmsg
.lower().startswith('project-id-version:'):
262 # Catalog description
263 for item
in tmsg
.split('\n'):
267 k
, v
= item
.split(':', 1)
268 k
= k
.strip().lower()
271 if k
== 'content-type':
272 self
._charset
= v
.split('charset=')[1]
273 elif k
== 'plural-forms':
275 ## nplurals = v[0].split('nplurals=')[1]
276 ## nplurals = int(nplurals.strip())
277 plural
= v
[1].split('plural=')[1]
278 self
.plural
= c2py(plural
)
279 # advance to next entry in the seek tables
283 def gettext(self
, message
):
285 return self
._catalog
[message
]
288 return self
._fallback
.gettext(message
)
292 def ngettext(self
, msgid1
, msgid2
, n
):
294 return self
._catalog
[(msgid1
, self
.plural(n
))]
297 return self
._fallback
.ngettext(msgid1
, msgid2
, n
)
304 def ugettext(self
, message
):
306 tmsg
= self
._catalog
[message
]
309 return self
._fallback
.ugettext(message
)
311 return unicode(tmsg
, self
._charset
)
314 def ungettext(self
, msgid1
, msgid2
, n
):
316 tmsg
= self
._catalog
[(msgid1
, self
.plural(n
))]
319 return self
._fallback
.ungettext(msgid1
, msgid2
, n
)
324 return unicode(tmsg
, self
._charset
)
327 # Locate a .mo file using the gettext strategy
328 def find(domain
, localedir
=None, languages
=None, all
=0):
329 # Get some reasonable defaults for arguments that were not supplied
330 if localedir
is None:
331 localedir
= _default_localedir
332 if languages
is None:
334 for envar
in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
335 val
= os
.environ
.get(envar
)
337 languages
= val
.split(':')
339 if 'C' not in languages
:
340 languages
.append('C')
341 # now normalize and expand the languages
343 for lang
in languages
:
344 for nelang
in _expand_lang(lang
):
345 if nelang
not in nelangs
:
346 nelangs
.append(nelang
)
355 mofile
= os
.path
.join(localedir
, lang
, 'LC_MESSAGES', '%s.mo' % domain
)
356 if os
.path
.exists(mofile
):
358 result
.append(mofile
)
365 # a mapping between absolute .mo file path and Translation object
368 def translation(domain
, localedir
=None, languages
=None,
369 class_
=None, fallback
=0):
371 class_
= GNUTranslations
372 mofiles
= find(domain
, localedir
, languages
, all
=1)
375 return NullTranslations()
376 raise IOError(ENOENT
, 'No translation file found for domain', domain
)
377 # TBD: do we need to worry about the file pointer getting collected?
378 # Avoid opening, reading, and parsing the .mo file after it's been done
381 for mofile
in mofiles
:
382 key
= os
.path
.abspath(mofile
)
383 t
= _translations
.get(key
)
385 t
= _translations
.setdefault(key
, class_(open(mofile
, 'rb')))
386 # Copy the translation object to allow setting fallbacks.
387 # All other instance data is shared with the cached object.
392 result
.add_fallback(t
)
396 def install(domain
, localedir
=None, unicode=0):
397 translation(domain
, localedir
, fallback
=1).install(unicode)
401 # a mapping b/w domains and locale directories
403 # current global domain, `messages' used for compatibility w/ GNU gettext
404 _current_domain
= 'messages'
407 def textdomain(domain
=None):
408 global _current_domain
409 if domain
is not None:
410 _current_domain
= domain
411 return _current_domain
414 def bindtextdomain(domain
, localedir
=None):
416 if localedir
is not None:
417 _localedirs
[domain
] = localedir
418 return _localedirs
.get(domain
, _default_localedir
)
421 def dgettext(domain
, message
):
423 t
= translation(domain
, _localedirs
.get(domain
, None))
426 return t
.gettext(message
)
429 def dngettext(domain
, msgid1
, msgid2
, n
):
431 t
= translation(domain
, _localedirs
.get(domain
, None))
437 return t
.ngettext(msgid1
, msgid2
, n
)
440 def gettext(message
):
441 return dgettext(_current_domain
, message
)
444 def ngettext(msgid1
, msgid2
, n
):
445 return dngettext(_current_domain
, msgid1
, msgid2
, n
)
448 # dcgettext() has been deemed unnecessary and is not implemented.
450 # James Henstridge's Catalog constructor from GNOME gettext. Documented usage
454 # cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
456 # print _('Hello World')
458 # The resulting catalog object currently don't support access through a
459 # dictionary API, which was supported (but apparently unused) in GNOME
462 Catalog
= translation