gettext.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. """Internationalization and localization support.
  2. This module provides internationalization (I18N) and localization (L10N)
  3. support for your Python programs by providing an interface to the GNU gettext
  4. message catalog library.
  5. I18N refers to the operation by which a program is made aware of multiple
  6. languages. L10N refers to the adaptation of your program, once
  7. internationalized, to the local language and cultural habits.
  8. """
  9. # This module represents the integration of work, contributions, feedback, and
  10. # suggestions from the following people:
  11. #
  12. # Martin von Loewis, who wrote the initial implementation of the underlying
  13. # C-based libintlmodule (later renamed _gettext), along with a skeletal
  14. # gettext.py implementation.
  15. #
  16. # Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule,
  17. # which also included a pure-Python implementation to read .mo files if
  18. # intlmodule wasn't available.
  19. #
  20. # James Henstridge, who also wrote a gettext.py module, which has some
  21. # interesting, but currently unsupported experimental features: the notion of
  22. # a Catalog class and instances, and the ability to add to a catalog file via
  23. # a Python API.
  24. #
  25. # Barry Warsaw integrated these modules, wrote the .install() API and code,
  26. # and conformed all C and Python code to Python's coding standards.
  27. #
  28. # Francois Pinard and Marc-Andre Lemburg also contributed valuably to this
  29. # module.
  30. #
  31. # J. David Ibanez implemented plural forms. Bruno Haible fixed some bugs.
  32. #
  33. # TODO:
  34. # - Lazy loading of .mo files. Currently the entire catalog is loaded into
  35. # memory, but that's probably bad for large translated programs. Instead,
  36. # the lexical sort of original strings in GNU .mo files should be exploited
  37. # to do binary searches and lazy initializations. Or you might want to use
  38. # the undocumented double-hash algorithm for .mo files with hash tables, but
  39. # you'll need to study the GNU gettext code to do this.
  40. #
  41. # - Support Solaris .mo file formats. Unfortunately, we've been unable to
  42. # find this format documented anywhere.
  43. import locale, copy, os, re, struct, sys
  44. from errno import ENOENT
  45. __all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
  46. 'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
  47. 'bind_textdomain_codeset',
  48. 'dgettext', 'dngettext', 'gettext', 'lgettext', 'ldgettext',
  49. 'ldngettext', 'lngettext', 'ngettext',
  50. ]
  51. _default_localedir = os.path.join(sys.prefix, 'share', 'locale')
  52. def test(condition, true, false):
  53. """
  54. Implements the C expression:
  55. condition ? true : false
  56. Required to correctly interpret plural forms.
  57. """
  58. if condition:
  59. return true
  60. else:
  61. return false
  62. def c2py(plural):
  63. """Gets a C expression as used in PO files for plural forms and returns a
  64. Python lambda function that implements an equivalent expression.
  65. """
  66. # Security check, allow only the "n" identifier
  67. try:
  68. from cStringIO import StringIO
  69. except ImportError:
  70. from StringIO import StringIO
  71. import token, tokenize
  72. tokens = tokenize.generate_tokens(StringIO(plural).readline)
  73. try:
  74. danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
  75. except tokenize.TokenError:
  76. raise ValueError, \
  77. 'plural forms expression error, maybe unbalanced parenthesis'
  78. else:
  79. if danger:
  80. raise ValueError, 'plural forms expression could be dangerous'
  81. # Replace some C operators by their Python equivalents
  82. plural = plural.replace('&&', ' and ')
  83. plural = plural.replace('||', ' or ')
  84. expr = re.compile(r'\!([^=])')
  85. plural = expr.sub(' not \\1', plural)
  86. # Regular expression and replacement function used to transform
  87. # "a?b:c" to "test(a,b,c)".
  88. expr = re.compile(r'(.*?)\?(.*?):(.*)')
  89. def repl(x):
  90. return "test(%s, %s, %s)" % (x.group(1), x.group(2),
  91. expr.sub(repl, x.group(3)))
  92. # Code to transform the plural expression, taking care of parentheses
  93. stack = ['']
  94. for c in plural:
  95. if c == '(':
  96. stack.append('')
  97. elif c == ')':
  98. if len(stack) == 1:
  99. # Actually, we never reach this code, because unbalanced
  100. # parentheses get caught in the security check at the
  101. # beginning.
  102. raise ValueError, 'unbalanced parenthesis in plural form'
  103. s = expr.sub(repl, stack.pop())
  104. stack[-1] += '(%s)' % s
  105. else:
  106. stack[-1] += c
  107. plural = expr.sub(repl, stack.pop())
  108. return eval('lambda n: int(%s)' % plural)
  109. def _expand_lang(locale):
  110. from locale import normalize
  111. locale = normalize(locale)
  112. COMPONENT_CODESET = 1 << 0
  113. COMPONENT_TERRITORY = 1 << 1
  114. COMPONENT_MODIFIER = 1 << 2
  115. # split up the locale into its base components
  116. mask = 0
  117. pos = locale.find('@')
  118. if pos >= 0:
  119. modifier = locale[pos:]
  120. locale = locale[:pos]
  121. mask |= COMPONENT_MODIFIER
  122. else:
  123. modifier = ''
  124. pos = locale.find('.')
  125. if pos >= 0:
  126. codeset = locale[pos:]
  127. locale = locale[:pos]
  128. mask |= COMPONENT_CODESET
  129. else:
  130. codeset = ''
  131. pos = locale.find('_')
  132. if pos >= 0:
  133. territory = locale[pos:]
  134. locale = locale[:pos]
  135. mask |= COMPONENT_TERRITORY
  136. else:
  137. territory = ''
  138. language = locale
  139. ret = []
  140. for i in range(mask+1):
  141. if not (i & ~mask): # if all components for this combo exist ...
  142. val = language
  143. if i & COMPONENT_TERRITORY: val += territory
  144. if i & COMPONENT_CODESET: val += codeset
  145. if i & COMPONENT_MODIFIER: val += modifier
  146. ret.append(val)
  147. ret.reverse()
  148. return ret
  149. class NullTranslations:
  150. def __init__(self, fp=None):
  151. self._info = {}
  152. self._charset = None
  153. self._output_charset = None
  154. self._fallback = None
  155. if fp is not None:
  156. self._parse(fp)
  157. def _parse(self, fp):
  158. pass
  159. def add_fallback(self, fallback):
  160. if self._fallback:
  161. self._fallback.add_fallback(fallback)
  162. else:
  163. self._fallback = fallback
  164. def gettext(self, message):
  165. if self._fallback:
  166. return self._fallback.gettext(message)
  167. return message
  168. def lgettext(self, message):
  169. if self._fallback:
  170. return self._fallback.lgettext(message)
  171. return message
  172. def ngettext(self, msgid1, msgid2, n):
  173. if self._fallback:
  174. return self._fallback.ngettext(msgid1, msgid2, n)
  175. if n == 1:
  176. return msgid1
  177. else:
  178. return msgid2
  179. def lngettext(self, msgid1, msgid2, n):
  180. if self._fallback:
  181. return self._fallback.lngettext(msgid1, msgid2, n)
  182. if n == 1:
  183. return msgid1
  184. else:
  185. return msgid2
  186. def ugettext(self, message):
  187. if self._fallback:
  188. return self._fallback.ugettext(message)
  189. return unicode(message)
  190. def ungettext(self, msgid1, msgid2, n):
  191. if self._fallback:
  192. return self._fallback.ungettext(msgid1, msgid2, n)
  193. if n == 1:
  194. return unicode(msgid1)
  195. else:
  196. return unicode(msgid2)
  197. def info(self):
  198. return self._info
  199. def charset(self):
  200. return self._charset
  201. def output_charset(self):
  202. return self._output_charset
  203. def set_output_charset(self, charset):
  204. self._output_charset = charset
  205. def install(self, unicode=False, names=None):
  206. import __builtin__
  207. __builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
  208. if hasattr(names, "__contains__"):
  209. if "gettext" in names:
  210. __builtin__.__dict__['gettext'] = __builtin__.__dict__['_']
  211. if "ngettext" in names:
  212. __builtin__.__dict__['ngettext'] = (unicode and self.ungettext
  213. or self.ngettext)
  214. if "lgettext" in names:
  215. __builtin__.__dict__['lgettext'] = self.lgettext
  216. if "lngettext" in names:
  217. __builtin__.__dict__['lngettext'] = self.lngettext
  218. class GNUTranslations(NullTranslations):
  219. # Magic number of .mo files
  220. LE_MAGIC = 0x950412deL
  221. BE_MAGIC = 0xde120495L
  222. def _parse(self, fp):
  223. """Override this method to support alternative .mo formats."""
  224. unpack = struct.unpack
  225. filename = getattr(fp, 'name', '')
  226. # Parse the .mo file header, which consists of 5 little endian 32
  227. # bit words.
  228. self._catalog = catalog = {}
  229. self.plural = lambda n: int(n != 1) # germanic plural by default
  230. buf = fp.read()
  231. buflen = len(buf)
  232. # Are we big endian or little endian?
  233. magic = unpack('<I', buf[:4])[0]
  234. if magic == self.LE_MAGIC:
  235. version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
  236. ii = '<II'
  237. elif magic == self.BE_MAGIC:
  238. version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
  239. ii = '>II'
  240. else:
  241. raise IOError(0, 'Bad magic number', filename)
  242. # Now put all messages from the .mo file buffer into the catalog
  243. # dictionary.
  244. for i in xrange(0, msgcount):
  245. mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
  246. mend = moff + mlen
  247. tlen, toff = unpack(ii, buf[transidx:transidx+8])
  248. tend = toff + tlen
  249. if mend < buflen and tend < buflen:
  250. msg = buf[moff:mend]
  251. tmsg = buf[toff:tend]
  252. else:
  253. raise IOError(0, 'File is corrupt', filename)
  254. # See if we're looking at GNU .mo conventions for metadata
  255. if mlen == 0:
  256. # Catalog description
  257. lastk = None
  258. for item in tmsg.splitlines():
  259. item = item.strip()
  260. if not item:
  261. continue
  262. k = v = None
  263. if ':' in item:
  264. k, v = item.split(':', 1)
  265. k = k.strip().lower()
  266. v = v.strip()
  267. self._info[k] = v
  268. lastk = k
  269. elif lastk:
  270. self._info[lastk] += '\n' + item
  271. if k == 'content-type':
  272. self._charset = v.split('charset=')[1]
  273. elif k == 'plural-forms':
  274. v = v.split(';')
  275. plural = v[1].split('plural=')[1]
  276. self.plural = c2py(plural)
  277. # Note: we unconditionally convert both msgids and msgstrs to
  278. # Unicode using the character encoding specified in the charset
  279. # parameter of the Content-Type header. The gettext documentation
  280. # strongly encourages msgids to be us-ascii, but some applications
  281. # require alternative encodings (e.g. Zope's ZCML and ZPT). For
  282. # traditional gettext applications, the msgid conversion will
  283. # cause no problems since us-ascii should always be a subset of
  284. # the charset encoding. We may want to fall back to 8-bit msgids
  285. # if the Unicode conversion fails.
  286. if '\x00' in msg:
  287. # Plural forms
  288. msgid1, msgid2 = msg.split('\x00')
  289. tmsg = tmsg.split('\x00')
  290. if self._charset:
  291. msgid1 = unicode(msgid1, self._charset)
  292. tmsg = [unicode(x, self._charset) for x in tmsg]
  293. for i in range(len(tmsg)):
  294. catalog[(msgid1, i)] = tmsg[i]
  295. else:
  296. if self._charset:
  297. msg = unicode(msg, self._charset)
  298. tmsg = unicode(tmsg, self._charset)
  299. catalog[msg] = tmsg
  300. # advance to next entry in the seek tables
  301. masteridx += 8
  302. transidx += 8
  303. def gettext(self, message):
  304. missing = object()
  305. tmsg = self._catalog.get(message, missing)
  306. if tmsg is missing:
  307. if self._fallback:
  308. return self._fallback.gettext(message)
  309. return message
  310. # Encode the Unicode tmsg back to an 8-bit string, if possible
  311. if self._output_charset:
  312. return tmsg.encode(self._output_charset)
  313. elif self._charset:
  314. return tmsg.encode(self._charset)
  315. return tmsg
  316. def lgettext(self, message):
  317. missing = object()
  318. tmsg = self._catalog.get(message, missing)
  319. if tmsg is missing:
  320. if self._fallback:
  321. return self._fallback.lgettext(message)
  322. return message
  323. if self._output_charset:
  324. return tmsg.encode(self._output_charset)
  325. return tmsg.encode(locale.getpreferredencoding())
  326. def ngettext(self, msgid1, msgid2, n):
  327. try:
  328. tmsg = self._catalog[(msgid1, self.plural(n))]
  329. if self._output_charset:
  330. return tmsg.encode(self._output_charset)
  331. elif self._charset:
  332. return tmsg.encode(self._charset)
  333. return tmsg
  334. except KeyError:
  335. if self._fallback:
  336. return self._fallback.ngettext(msgid1, msgid2, n)
  337. if n == 1:
  338. return msgid1
  339. else:
  340. return msgid2
  341. def lngettext(self, msgid1, msgid2, n):
  342. try:
  343. tmsg = self._catalog[(msgid1, self.plural(n))]
  344. if self._output_charset:
  345. return tmsg.encode(self._output_charset)
  346. return tmsg.encode(locale.getpreferredencoding())
  347. except KeyError:
  348. if self._fallback:
  349. return self._fallback.lngettext(msgid1, msgid2, n)
  350. if n == 1:
  351. return msgid1
  352. else:
  353. return msgid2
  354. def ugettext(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.ugettext(message)
  360. return unicode(message)
  361. return tmsg
  362. def ungettext(self, msgid1, msgid2, n):
  363. try:
  364. tmsg = self._catalog[(msgid1, self.plural(n))]
  365. except KeyError:
  366. if self._fallback:
  367. return self._fallback.ungettext(msgid1, msgid2, n)
  368. if n == 1:
  369. tmsg = unicode(msgid1)
  370. else:
  371. tmsg = unicode(msgid2)
  372. return tmsg
  373. # Locate a .mo file using the gettext strategy
  374. def find(domain, localedir=None, languages=None, all=0):
  375. # Get some reasonable defaults for arguments that were not supplied
  376. if localedir is None:
  377. localedir = _default_localedir
  378. if languages is None:
  379. languages = []
  380. for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
  381. val = os.environ.get(envar)
  382. if val:
  383. languages = val.split(':')
  384. break
  385. if 'C' not in languages:
  386. languages.append('C')
  387. # now normalize and expand the languages
  388. nelangs = []
  389. for lang in languages:
  390. for nelang in _expand_lang(lang):
  391. if nelang not in nelangs:
  392. nelangs.append(nelang)
  393. # select a language
  394. if all:
  395. result = []
  396. else:
  397. result = None
  398. for lang in nelangs:
  399. if lang == 'C':
  400. break
  401. mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
  402. if os.path.exists(mofile):
  403. if all:
  404. result.append(mofile)
  405. else:
  406. return mofile
  407. return result
  408. # a mapping between absolute .mo file path and Translation object
  409. _translations = {}
  410. def translation(domain, localedir=None, languages=None,
  411. class_=None, fallback=False, codeset=None):
  412. if class_ is None:
  413. class_ = GNUTranslations
  414. mofiles = find(domain, localedir, languages, all=1)
  415. if not mofiles:
  416. if fallback:
  417. return NullTranslations()
  418. raise IOError(ENOENT, 'No translation file found for domain', domain)
  419. # Avoid opening, reading, and parsing the .mo file after it's been done
  420. # once.
  421. result = None
  422. for mofile in mofiles:
  423. key = (class_, os.path.abspath(mofile))
  424. t = _translations.get(key)
  425. if t is None:
  426. with open(mofile, 'rb') as fp:
  427. t = _translations.setdefault(key, class_(fp))
  428. # Copy the translation object to allow setting fallbacks and
  429. # output charset. All other instance data is shared with the
  430. # cached object.
  431. t = copy.copy(t)
  432. if codeset:
  433. t.set_output_charset(codeset)
  434. if result is None:
  435. result = t
  436. else:
  437. result.add_fallback(t)
  438. return result
  439. def install(domain, localedir=None, unicode=False, codeset=None, names=None):
  440. t = translation(domain, localedir, fallback=True, codeset=codeset)
  441. t.install(unicode, names)
  442. # a mapping b/w domains and locale directories
  443. _localedirs = {}
  444. # a mapping b/w domains and codesets
  445. _localecodesets = {}
  446. # current global domain, `messages' used for compatibility w/ GNU gettext
  447. _current_domain = 'messages'
  448. def textdomain(domain=None):
  449. global _current_domain
  450. if domain is not None:
  451. _current_domain = domain
  452. return _current_domain
  453. def bindtextdomain(domain, localedir=None):
  454. global _localedirs
  455. if localedir is not None:
  456. _localedirs[domain] = localedir
  457. return _localedirs.get(domain, _default_localedir)
  458. def bind_textdomain_codeset(domain, codeset=None):
  459. global _localecodesets
  460. if codeset is not None:
  461. _localecodesets[domain] = codeset
  462. return _localecodesets.get(domain)
  463. def dgettext(domain, message):
  464. try:
  465. t = translation(domain, _localedirs.get(domain, None),
  466. codeset=_localecodesets.get(domain))
  467. except IOError:
  468. return message
  469. return t.gettext(message)
  470. def ldgettext(domain, message):
  471. try:
  472. t = translation(domain, _localedirs.get(domain, None),
  473. codeset=_localecodesets.get(domain))
  474. except IOError:
  475. return message
  476. return t.lgettext(message)
  477. def dngettext(domain, msgid1, msgid2, n):
  478. try:
  479. t = translation(domain, _localedirs.get(domain, None),
  480. codeset=_localecodesets.get(domain))
  481. except IOError:
  482. if n == 1:
  483. return msgid1
  484. else:
  485. return msgid2
  486. return t.ngettext(msgid1, msgid2, n)
  487. def ldngettext(domain, msgid1, msgid2, n):
  488. try:
  489. t = translation(domain, _localedirs.get(domain, None),
  490. codeset=_localecodesets.get(domain))
  491. except IOError:
  492. if n == 1:
  493. return msgid1
  494. else:
  495. return msgid2
  496. return t.lngettext(msgid1, msgid2, n)
  497. def gettext(message):
  498. return dgettext(_current_domain, message)
  499. def lgettext(message):
  500. return ldgettext(_current_domain, message)
  501. def ngettext(msgid1, msgid2, n):
  502. return dngettext(_current_domain, msgid1, msgid2, n)
  503. def lngettext(msgid1, msgid2, n):
  504. return ldngettext(_current_domain, msgid1, msgid2, n)
  505. # dcgettext() has been deemed unnecessary and is not implemented.
  506. # James Henstridge's Catalog constructor from GNOME gettext. Documented usage
  507. # was:
  508. #
  509. # import gettext
  510. # cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
  511. # _ = cat.gettext
  512. # print _('Hello World')
  513. # The resulting catalog object currently don't support access through a
  514. # dictionary API, which was supported (but apparently unused) in GNOME
  515. # gettext.
  516. Catalog = translation