blob: 253b6d8bc771c4622e027e33acc4aa67fe49e079 [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#
35# TODO:
36# - Lazy loading of .mo files. Currently the entire catalog is loaded into
37# memory, but that's probably bad for large translated programs. Instead,
38# the lexical sort of original strings in GNU .mo files should be exploited
39# to do binary searches and lazy initializations. Or you might want to use
40# the undocumented double-hash algorithm for .mo files with hash tables, but
41# you'll need to study the GNU gettext code to do this.
42#
43# - Support Solaris .mo file formats. Unfortunately, we've been unable to
44# find this format documented anywhere.
Barry Warsaw95be23d2000-08-25 19:13:37 +000045
46import os
47import sys
48import struct
Martin v. Löwisa55ffae2002-01-11 06:58:49 +000049import copy
Barry Warsaw33d8d702000-08-30 03:29:58 +000050from errno import ENOENT
Barry Warsaw95be23d2000-08-25 19:13:37 +000051
Skip Montanaro2dd42762001-01-23 15:35:05 +000052__all__ = ["bindtextdomain","textdomain","gettext","dgettext",
53 "find","translation","install","Catalog"]
54
Barry Warsaw33d8d702000-08-30 03:29:58 +000055_default_localedir = os.path.join(sys.prefix, 'share', 'locale')
Barry Warsaw95be23d2000-08-25 19:13:37 +000056
57
Tim Peters07e99cb2001-01-14 23:47:14 +000058
Barry Warsawfa488ec2000-08-25 20:26:43 +000059def _expand_lang(locale):
60 from locale import normalize
61 locale = normalize(locale)
62 COMPONENT_CODESET = 1 << 0
63 COMPONENT_TERRITORY = 1 << 1
64 COMPONENT_MODIFIER = 1 << 2
65 # split up the locale into its base components
66 mask = 0
67 pos = locale.find('@')
68 if pos >= 0:
69 modifier = locale[pos:]
70 locale = locale[:pos]
71 mask |= COMPONENT_MODIFIER
72 else:
73 modifier = ''
74 pos = locale.find('.')
75 if pos >= 0:
76 codeset = locale[pos:]
77 locale = locale[:pos]
78 mask |= COMPONENT_CODESET
79 else:
80 codeset = ''
81 pos = locale.find('_')
82 if pos >= 0:
83 territory = locale[pos:]
84 locale = locale[:pos]
85 mask |= COMPONENT_TERRITORY
86 else:
87 territory = ''
88 language = locale
89 ret = []
90 for i in range(mask+1):
91 if not (i & ~mask): # if all components for this combo exist ...
92 val = language
93 if i & COMPONENT_TERRITORY: val += territory
94 if i & COMPONENT_CODESET: val += codeset
95 if i & COMPONENT_MODIFIER: val += modifier
96 ret.append(val)
97 ret.reverse()
98 return ret
99
100
Tim Peters07e99cb2001-01-14 23:47:14 +0000101
Barry Warsaw33d8d702000-08-30 03:29:58 +0000102class NullTranslations:
103 def __init__(self, fp=None):
104 self._info = {}
105 self._charset = None
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000106 self._fallback = None
Raymond Hettinger094662a2002-06-01 01:29:16 +0000107 if fp is not None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000108 self._parse(fp)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000109
Barry Warsaw33d8d702000-08-30 03:29:58 +0000110 def _parse(self, fp):
111 pass
112
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000113 def add_fallback(self, fallback):
114 if self._fallback:
115 self._fallback.add_fallback(fallback)
116 else:
117 self._fallback = fallback
118
Barry Warsaw33d8d702000-08-30 03:29:58 +0000119 def gettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000120 if self._fallback:
121 return self._fallback.gettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000122 return message
123
124 def ugettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000125 if self._fallback:
126 return self._fallback.ugettext(message)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000127 return unicode(message)
128
129 def info(self):
130 return self._info
131
132 def charset(self):
133 return self._charset
134
135 def install(self, unicode=0):
136 import __builtin__
137 __builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
138
139
140class GNUTranslations(NullTranslations):
141 # Magic number of .mo files
142 LE_MAGIC = 0x950412de
Barry Warsawb76a55c2000-08-31 10:45:54 +0000143 BE_MAGIC = 0xde120495
Barry Warsaw95be23d2000-08-25 19:13:37 +0000144
145 def _parse(self, fp):
146 """Override this method to support alternative .mo formats."""
Tim Petersc6387912000-09-01 02:20:20 +0000147 # We need to & all 32 bit unsigned integers with 0xffffffff for
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000148 # portability to 64 bit machines.
149 MASK = 0xffffffff
Barry Warsaw95be23d2000-08-25 19:13:37 +0000150 unpack = struct.unpack
151 filename = getattr(fp, 'name', '')
152 # Parse the .mo file header, which consists of 5 little endian 32
153 # bit words.
Barry Warsaw33d8d702000-08-30 03:29:58 +0000154 self._catalog = catalog = {}
Barry Warsaw95be23d2000-08-25 19:13:37 +0000155 buf = fp.read()
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000156 buflen = len(buf)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000157 # Are we big endian or little endian?
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000158 magic = unpack('<i', buf[:4])[0] & MASK
Barry Warsaw33d8d702000-08-30 03:29:58 +0000159 if magic == self.LE_MAGIC:
160 version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20])
161 ii = '<ii'
162 elif magic == self.BE_MAGIC:
163 version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20])
164 ii = '>ii'
165 else:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000166 raise IOError(0, 'Bad magic number', filename)
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000167 # more unsigned ints
168 msgcount &= MASK
169 masteridx &= MASK
170 transidx &= MASK
Barry Warsaw95be23d2000-08-25 19:13:37 +0000171 # Now put all messages from the .mo file buffer into the catalog
172 # dictionary.
173 for i in xrange(0, msgcount):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000174 mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000175 moff &= MASK
176 mend = moff + (mlen & MASK)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000177 tlen, toff = unpack(ii, buf[transidx:transidx+8])
Barry Warsaw9a2d9d72000-08-31 23:28:52 +0000178 toff &= MASK
179 tend = toff + (tlen & MASK)
180 if mend < buflen and tend < buflen:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000181 tmsg = buf[toff:tend]
182 catalog[buf[moff:mend]] = tmsg
Barry Warsaw95be23d2000-08-25 19:13:37 +0000183 else:
184 raise IOError(0, 'File is corrupt', filename)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000185 # See if we're looking at GNU .mo conventions for metadata
186 if mlen == 0 and tmsg.lower().startswith('project-id-version:'):
187 # Catalog description
188 for item in tmsg.split('\n'):
189 item = item.strip()
190 if not item:
191 continue
192 k, v = item.split(':', 1)
193 k = k.strip().lower()
194 v = v.strip()
195 self._info[k] = v
196 if k == 'content-type':
197 self._charset = v.split('charset=')[1]
Barry Warsaw95be23d2000-08-25 19:13:37 +0000198 # advance to next entry in the seek tables
Barry Warsawfa488ec2000-08-25 20:26:43 +0000199 masteridx += 8
200 transidx += 8
Barry Warsaw33d8d702000-08-30 03:29:58 +0000201
202 def gettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000203 try:
204 return self._catalog[message]
205 except KeyError:
206 if self._fallback:
207 return self._fallback.gettext(message)
208 return message
Barry Warsaw33d8d702000-08-30 03:29:58 +0000209
210 def ugettext(self, message):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000211 try:
212 tmsg = self._catalog[message]
213 except KeyError:
214 if self._fallback:
215 return self._fallback.ugettext(message)
216 tmsg = message
Barry Warsaw33d8d702000-08-30 03:29:58 +0000217 return unicode(tmsg, self._charset)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000218
219
Tim Peters07e99cb2001-01-14 23:47:14 +0000220
Barry Warsaw95be23d2000-08-25 19:13:37 +0000221# Locate a .mo file using the gettext strategy
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000222def find(domain, localedir=None, languages=None, all=0):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000223 # Get some reasonable defaults for arguments that were not supplied
Barry Warsaw95be23d2000-08-25 19:13:37 +0000224 if localedir is None:
Barry Warsaw33d8d702000-08-30 03:29:58 +0000225 localedir = _default_localedir
Barry Warsaw95be23d2000-08-25 19:13:37 +0000226 if languages is None:
227 languages = []
228 for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
229 val = os.environ.get(envar)
230 if val:
231 languages = val.split(':')
232 break
233 if 'C' not in languages:
234 languages.append('C')
Barry Warsawfa488ec2000-08-25 20:26:43 +0000235 # now normalize and expand the languages
Barry Warsaw75f81012000-10-16 15:47:50 +0000236 nelangs = []
Barry Warsawfa488ec2000-08-25 20:26:43 +0000237 for lang in languages:
238 for nelang in _expand_lang(lang):
Barry Warsaw75f81012000-10-16 15:47:50 +0000239 if nelang not in nelangs:
240 nelangs.append(nelang)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000241 # select a language
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000242 if all:
243 result = []
244 else:
245 result = None
Barry Warsaw75f81012000-10-16 15:47:50 +0000246 for lang in nelangs:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000247 if lang == 'C':
248 break
Barry Warsaw84314b72000-08-25 19:53:17 +0000249 mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000250 if os.path.exists(mofile):
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000251 if all:
252 result.append(mofile)
253 else:
254 return mofile
255 return result
Barry Warsaw95be23d2000-08-25 19:13:37 +0000256
257
Tim Peters07e99cb2001-01-14 23:47:14 +0000258
Barry Warsaw33d8d702000-08-30 03:29:58 +0000259# a mapping between absolute .mo file path and Translation object
260_translations = {}
261
Martin v. Löwis1be64192002-01-11 06:33:28 +0000262def translation(domain, localedir=None, languages=None,
263 class_=None, fallback=0):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000264 if class_ is None:
265 class_ = GNUTranslations
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000266 mofiles = find(domain, localedir, languages, all=1)
267 if len(mofiles)==0:
Martin v. Löwis1be64192002-01-11 06:33:28 +0000268 if fallback:
269 return NullTranslations()
Barry Warsaw33d8d702000-08-30 03:29:58 +0000270 raise IOError(ENOENT, 'No translation file found for domain', domain)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000271 # TBD: do we need to worry about the file pointer getting collected?
Barry Warsaw293b03f2000-10-05 18:48:12 +0000272 # Avoid opening, reading, and parsing the .mo file after it's been done
273 # once.
Martin v. Löwisa55ffae2002-01-11 06:58:49 +0000274 result = None
275 for mofile in mofiles:
276 key = os.path.abspath(mofile)
277 t = _translations.get(key)
278 if t is None:
279 t = _translations.setdefault(key, class_(open(mofile, 'rb')))
280 # Copy the translation object to allow setting fallbacks.
281 # All other instance data is shared with the cached object.
282 t = copy.copy(t)
283 if result is None:
284 result = t
285 else:
286 result.add_fallback(t)
287 return result
Barry Warsaw33d8d702000-08-30 03:29:58 +0000288
Tim Peters07e99cb2001-01-14 23:47:14 +0000289
Barry Warsaw33d8d702000-08-30 03:29:58 +0000290def install(domain, localedir=None, unicode=0):
Martin v. Löwis1be64192002-01-11 06:33:28 +0000291 translation(domain, localedir, fallback=1).install(unicode)
Barry Warsaw33d8d702000-08-30 03:29:58 +0000292
293
Tim Peters07e99cb2001-01-14 23:47:14 +0000294
Barry Warsaw33d8d702000-08-30 03:29:58 +0000295# a mapping b/w domains and locale directories
296_localedirs = {}
297# current global domain, `messages' used for compatibility w/ GNU gettext
298_current_domain = 'messages'
Barry Warsaw95be23d2000-08-25 19:13:37 +0000299
300
301def textdomain(domain=None):
Barry Warsaw95be23d2000-08-25 19:13:37 +0000302 global _current_domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000303 if domain is not None:
Barry Warsaw95be23d2000-08-25 19:13:37 +0000304 _current_domain = domain
Barry Warsaw33d8d702000-08-30 03:29:58 +0000305 return _current_domain
Barry Warsaw95be23d2000-08-25 19:13:37 +0000306
307
Barry Warsaw33d8d702000-08-30 03:29:58 +0000308def bindtextdomain(domain, localedir=None):
309 global _localedirs
310 if localedir is not None:
311 _localedirs[domain] = localedir
312 return _localedirs.get(domain, _default_localedir)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000313
314
315def dgettext(domain, message):
Barry Warsaw33d8d702000-08-30 03:29:58 +0000316 try:
317 t = translation(domain, _localedirs.get(domain, None))
318 except IOError:
319 return message
320 return t.gettext(message)
Tim Peters07e99cb2001-01-14 23:47:14 +0000321
Barry Warsaw33d8d702000-08-30 03:29:58 +0000322
323def gettext(message):
324 return dgettext(_current_domain, message)
Barry Warsaw95be23d2000-08-25 19:13:37 +0000325
326
Barry Warsaw33d8d702000-08-30 03:29:58 +0000327# dcgettext() has been deemed unnecessary and is not implemented.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000328
Barry Warsaw33d8d702000-08-30 03:29:58 +0000329# James Henstridge's Catalog constructor from GNOME gettext. Documented usage
330# was:
331#
332# import gettext
333# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
334# _ = cat.gettext
335# print _('Hello World')
Barry Warsaw95be23d2000-08-25 19:13:37 +0000336
Barry Warsaw33d8d702000-08-30 03:29:58 +0000337# The resulting catalog object currently don't support access through a
338# dictionary API, which was supported (but apparently unused) in GNOME
339# gettext.
Barry Warsaw95be23d2000-08-25 19:13:37 +0000340
Barry Warsaw33d8d702000-08-30 03:29:58 +0000341Catalog = translation