gettext.py 19 KB

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