PageRenderTime 27ms CodeModel.GetById 21ms RepoModel.GetById 6ms app.codeStats 0ms

/python/lib/Lib/gettext.py

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