1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
23 from datetime import datetime
25 from os.path import join
28 from lxml import etree
29 import osv, tools, pooler
32 from tools.misc import UpdateableStr
40 'af_ZA': 'Afrikaans_South Africa',
41 'sq_AL': 'Albanian_Albania',
42 'ar_SA': 'Arabic_Saudi Arabia',
43 'eu_ES': 'Basque_Spain',
44 'be_BY': 'Belarusian_Belarus',
45 'bs_BA': 'Serbian (Latin)',
46 'bg_BG': 'Bulgarian_Bulgaria',
47 'ca_ES': 'Catalan_Spain',
48 'hr_HR': 'Croatian_Croatia',
49 'zh_CN': 'Chinese_China',
50 'zh_TW': 'Chinese_Taiwan',
51 'cs_CZ': 'Czech_Czech Republic',
52 'da_DK': 'Danish_Denmark',
53 'nl_NL': 'Dutch_Netherlands',
54 'et_EE': 'Estonian_Estonia',
55 'fa_IR': 'Farsi_Iran',
56 'ph_PH': 'Filipino_Philippines',
57 'fi_FI': 'Finnish_Finland',
58 'fr_FR': 'French_France',
59 'fr_BE': 'French_France',
60 'fr_CH': 'French_France',
61 'fr_CA': 'French_France',
62 'ga': 'Scottish Gaelic',
63 'gl_ES': 'Galician_Spain',
64 'ka_GE': 'Georgian_Georgia',
65 'de_DE': 'German_Germany',
66 'el_GR': 'Greek_Greece',
67 'gu': 'Gujarati_India',
68 'he_IL': 'Hebrew_Israel',
70 'hu': 'Hungarian_Hungary',
71 'is_IS': 'Icelandic_Iceland',
72 'id_ID': 'Indonesian_indonesia',
73 'it_IT': 'Italian_Italy',
74 'ja_JP': 'Japanese_Japan',
77 'ko_KR': 'Korean_Korea',
79 'lt_LT': 'Lithuanian_Lithuania',
80 'lat': 'Latvian_Latvia',
81 'ml_IN': 'Malayalam_India',
82 'id_ID': 'Indonesian_indonesia',
84 'mn': 'Cyrillic_Mongolian',
85 'no_NO': 'Norwegian_Norway',
86 'nn_NO': 'Norwegian-Nynorsk_Norway',
87 'pl': 'Polish_Poland',
88 'pt_PT': 'Portuguese_Portugal',
89 'pt_BR': 'Portuguese_Brazil',
90 'ro_RO': 'Romanian_Romania',
91 'ru_RU': 'Russian_Russia',
93 'sr_CS': 'Serbian (Cyrillic)_Serbia and Montenegro',
94 'sk_SK': 'Slovak_Slovakia',
95 'sl_SI': 'Slovenian_Slovenia',
96 'es_ES': 'Spanish_Spain',
97 'sv_SE': 'Swedish_Sweden',
98 'ta_IN': 'English_Australia',
99 'th_TH': 'Thai_Thailand',
101 'tr_TR': 'Turkish_Turkey',
102 'uk_UA': 'Ukrainian_Ukraine',
103 'vi_VN': 'Vietnamese_Viet Nam',
104 'tlh_TLH': 'Klingon',
109 class UNIX_LINE_TERMINATOR(csv.excel):
110 lineterminator = '\n'
112 csv.register_dialect("UNIX", UNIX_LINE_TERMINATOR)
115 # Warning: better use self.pool.get('ir.translation')._get_source if you can
117 def translate(cr, name, source_type, lang, source=None):
119 cr.execute('select value from ir_translation where lang=%s and type=%s and name=%s and src=%s', (lang, source_type, str(name), source))
121 cr.execute('select value from ir_translation where lang=%s and type=%s and name=%s', (lang, source_type, str(name)))
123 cr.execute('select value from ir_translation where lang=%s and type=%s and src=%s', (lang, source_type, source))
124 res_trans = cr.fetchone()
125 res = res_trans and res_trans[0] or False
128 class GettextAlias(object):
129 def __call__(self, source):
131 frame = inspect.stack()[1][0]
135 cr = frame.f_locals.get('cr')
137 lang = (frame.f_locals.get('context') or {}).get('lang', False)
138 if not (cr and lang):
139 args = frame.f_locals.get('args',False)
141 lang = args[-1].get('lang',False)
142 if frame.f_globals.get('pooler',False):
143 cr = pooler.get_db(frame.f_globals['pooler'].pool_dic.keys()[0]).cursor()
144 if not (lang and cr):
149 cr.execute('select value from ir_translation where lang=%s and type in (%s,%s) and src=%s', (lang, 'code','sql_constraint', source))
150 res_trans = cr.fetchone()
151 return res_trans and res_trans[0] or source
155 # class to handle po files
156 class TinyPoFile(object):
157 def __init__(self, buffer):
162 self.lines = self._get_lines()
163 self.lines_count = len(self.lines);
169 def _get_lines(self):
170 lines = self.buffer.readlines()
171 # remove the BOM (Byte Order Mark):
173 lines[0] = unicode(lines[0], 'utf8').lstrip(unicode( codecs.BOM_UTF8, "utf8"))
175 lines.append('') # ensure that the file ends with at least an empty line
179 return (self.lines_count - len(self.lines))
183 return str[1:-1].replace("\\n", "\n") \
184 .replace("\\\\ ", "\\ ") \
187 type = name = res_id = source = trad = None
190 type, name, res_id, source, trad = self.tnrs.pop(0)
196 if 0 == len(self.lines):
197 raise StopIteration()
198 line = self.lines.pop(0).strip()
199 while line.startswith('#'):
200 if line.startswith('#~ '):
202 if line.startswith('#:'):
203 if ' ' in line[2:].strip():
204 for lpart in line[2:].strip().split(' '):
205 tmp_tnrs.append(lpart.strip().split(':',2))
207 tmp_tnrs.append( line[2:].strip().split(':',2) )
208 elif line.startswith('#,') and (line[2:].strip() == 'fuzzy'):
210 line = self.lines.pop(0).strip()
212 # allow empty lines between comments and msgid
213 line = self.lines.pop(0).strip()
214 if line.startswith('#~ '):
215 while line.startswith('#~ ') or not line.strip():
216 if 0 == len(self.lines):
217 raise StopIteration()
218 line = self.lines.pop(0)
219 # This has been a deprecated entry, don't return anything
223 if not line.startswith('msgid'):
224 raise Exception("malformed file: bad line: %s" % line)
225 source = unquote(line[6:])
226 line = self.lines.pop(0).strip()
227 if not source and self.first:
228 # if the source is "" and it's the first msgid, it's the special
229 # msgstr with the informations about the traduction and the
230 # traductor; we skip it
233 line = self.lines.pop(0).strip()
236 while not line.startswith('msgstr'):
238 raise Exception('malformed file at %d'% self.cur_line())
239 source += unquote(line)
240 line = self.lines.pop(0).strip()
242 trad = unquote(line[7:])
243 line = self.lines.pop(0).strip()
245 trad += unquote(line)
246 line = self.lines.pop(0).strip()
248 if tmp_tnrs and not fuzzy:
249 type, name, res_id = tmp_tnrs.pop(0)
250 for t, n, r in tmp_tnrs:
251 self.tnrs.append((t, n, r, source, trad))
257 return type, name, res_id, source, trad
259 def write_infos(self, modules):
261 self.buffer.write("# Translation of %(project)s.\n" \
262 "# This file contains the translation of the following modules:\n" \
267 '''"Project-Id-Version: %(project)s %(version)s\\n"\n''' \
268 '''"Report-Msgid-Bugs-To: %(bugmail)s\\n"\n''' \
269 '''"POT-Creation-Date: %(now)s\\n"\n''' \
270 '''"PO-Revision-Date: %(now)s\\n"\n''' \
271 '''"Last-Translator: <>\\n"\n''' \
272 '''"Language-Team: \\n"\n''' \
273 '''"MIME-Version: 1.0\\n"\n''' \
274 '''"Content-Type: text/plain; charset=UTF-8\\n"\n''' \
275 '''"Content-Transfer-Encoding: \\n"\n''' \
276 '''"Plural-Forms: \\n"\n''' \
279 % { 'project': release.description,
280 'version': release.version,
281 'modules': reduce(lambda s, m: s + "#\t* %s\n" % m, modules, ""),
282 'bugmail': release.support_email,
283 'now': datetime.now().isoformat(' ')[0:-7] + '+0000',
287 def write(self, modules, tnrs, source, trad):
289 return '"%s"' % s.replace('"','\\"') \
290 .replace('\n', '\\n"\n"') \
291 .replace(' \\ ',' \\\\ ')
294 plurial = len(modules) > 1 and 's' or ''
295 self.buffer.write("#. module%s: %s\n" % (plurial, ', '.join(modules)))
299 for typy, name, res_id in tnrs:
300 self.buffer.write("#: %s:%s:%s\n" % (typy, name, res_id))
305 # only strings in python code are python formated
306 self.buffer.write("#, python-format\n")
308 if not isinstance(trad, unicode):
309 trad = unicode(trad, 'utf8')
310 if not isinstance(source, unicode):
311 source = unicode(source, 'utf8')
315 % (quote(source), quote(trad))
316 self.buffer.write(msg.encode('utf8'))
319 # Methods to export the translation file
321 def trans_export(lang, modules, buffer, format, dbname=None):
323 def _process(format, modules, rows, buffer, lang, newlang):
325 writer=csv.writer(buffer, 'UNIX')
330 writer = tools.TinyPoFile(buffer)
331 writer.write_infos(modules)
333 # we now group the translations by source. That means one translation per source.
335 for module, type, name, res_id, src, trad in rows:
336 row = grouped_rows.setdefault(src, {})
337 row.setdefault('modules', set()).add(module)
338 if ('translation' not in row) or (not row['translation']):
339 row['translation'] = trad
340 row.setdefault('tnrs', []).append((type, name, res_id))
342 for src, row in grouped_rows.items():
343 writer.write(row['modules'], row['tnrs'], src, row['translation'])
345 elif format == 'tgz':
350 rows_by_module.setdefault(module, []).append(row)
352 tmpdir = tempfile.mkdtemp()
353 for mod, modrows in rows_by_module.items():
354 tmpmoddir = join(tmpdir, mod, 'i18n')
355 os.makedirs(tmpmoddir)
356 pofilename = (newlang and mod or lang) + ".po" + (newlang and 't' or '')
357 buf = file(join(tmpmoddir, pofilename), 'w')
358 _process('po', [mod], modrows, buf, lang, newlang)
361 tar = tarfile.open(fileobj=buffer, mode='w|gz')
366 raise Exception(_('Bad file format'))
368 newlang = not bool(lang)
371 trans = trans_generate(lang, modules, dbname)
372 modules = set([t[0] for t in trans[1:]])
373 _process(format, modules, trans, buffer, lang, newlang)
377 def trans_parse_xsl(de):
381 for m in [j for j in n if j.text]:
382 l = m.text.strip().replace('\n',' ')
384 res.append(l.encode("utf8"))
385 res.extend(trans_parse_xsl(n))
388 def trans_parse_rml(de):
391 for m in [j for j in n if j.text]:
392 string_list = [s.replace('\n', ' ').strip() for s in re.split('\[\[.+?\]\]', m.text)]
393 for s in string_list:
395 res.append(s.encode("utf8"))
396 res.extend(trans_parse_rml(n))
399 def trans_parse_view(de):
402 res.append(de.get('string').encode("utf8"))
404 res.append(de.get('sum').encode("utf8"))
406 res.extend(trans_parse_view(n))
409 # tests whether an object is in a list of modules
410 def in_modules(object_name, modules):
419 module = object_name.split('.')[0]
420 module = module_dict.get(module, module)
421 return module in modules
423 def trans_generate(lang, modules, dbname=None):
424 logger = netsvc.Logger()
426 dbname=tools.config['db_name']
430 pool = pooler.get_pool(dbname)
431 trans_obj = pool.get('ir.translation')
432 model_data_obj = pool.get('ir.model.data')
433 cr = pooler.get_db(dbname).cursor()
435 l = pool.obj_pool.items()
438 query = 'SELECT name, model, res_id, module' \
439 ' FROM ir_model_data'
441 if 'all_installed' in modules:
442 query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') '
443 elif not 'all' in modules:
444 query += ' WHERE module IN (%s)' % ','.join(['%s']*len(modules))
445 query_param = modules
446 query += ' ORDER BY module, model, name'
448 cr.execute(query, query_param)
451 def push_translation(module, type, name, id, source):
452 tuple = (module, source, name, id, type)
453 if source and tuple not in _to_translate:
454 _to_translate.append(tuple)
457 if isinstance(s, unicode):
458 return s.encode('utf8')
461 for (xml_name,model,res_id,module) in cr.fetchall():
462 module = encode(module)
463 model = encode(model)
464 xml_name = "%s.%s" % (module, encode(xml_name))
466 if not pool.get(model):
467 logger.notifyChannel("db", netsvc.LOG_ERROR, "Unable to find object %r" % (model,))
470 exists = pool.get(model).exists(cr, uid, res_id)
472 logger.notifyChannel("db", netsvc.LOG_WARNING, "Unable to find object %r with id %d" % (model, res_id))
474 obj = pool.get(model).browse(cr, uid, res_id)
476 if model=='ir.ui.view':
477 d = etree.XML(encode(obj.arch))
478 for t in trans_parse_view(d):
479 push_translation(module, 'view', encode(obj.model), 0, t)
480 elif model=='ir.actions.wizard':
481 service_name = 'wizard.'+encode(obj.wiz_name)
482 if netsvc.Service._services.get(service_name):
483 obj2 = netsvc.Service._services[service_name]
484 for state_name, state_def in obj2.states.iteritems():
485 if 'result' in state_def:
486 result = state_def['result']
487 if result['type'] != 'form':
489 name = "%s,%s" % (encode(obj.wiz_name), state_name)
492 'string': ('wizard_field', lambda s: [encode(s)]),
493 'selection': ('selection', lambda s: [encode(e[1]) for e in ((not callable(s)) and s or [])]),
494 'help': ('help', lambda s: [encode(s)]),
498 if not result.has_key('fields'):
499 logger.notifyChannel("db",netsvc.LOG_WARNING,"res has no fields: %r" % result)
501 for field_name, field_def in result['fields'].iteritems():
502 res_name = name + ',' + field_name
504 for fn in def_params:
506 transtype, modifier = def_params[fn]
507 for val in modifier(field_def[fn]):
508 push_translation(module, transtype, res_name, 0, val)
511 arch = result['arch']
512 if arch and not isinstance(arch, UpdateableStr):
514 for t in trans_parse_view(d):
515 push_translation(module, 'wizard_view', name, 0, t)
517 # export button labels
518 for but_args in result['state']:
519 button_name = but_args[0]
520 button_label = but_args[1]
521 res_name = name + ',' + button_name
522 push_translation(module, 'wizard_button', res_name, 0, button_label)
524 elif model=='ir.model.fields':
526 field_name = encode(obj.name)
527 except AttributeError, exc:
528 logger.notifyChannel("db", netsvc.LOG_ERROR, "name error in %s: %s" % (xml_name,str(exc)))
530 objmodel = pool.get(obj.model)
531 if not objmodel or not field_name in objmodel._columns:
533 field_def = objmodel._columns[field_name]
535 name = "%s,%s" % (encode(obj.model), field_name)
536 push_translation(module, 'field', name, 0, encode(field_def.string))
539 push_translation(module, 'help', name, 0, encode(field_def.help))
541 if field_def.translate:
542 ids = objmodel.search(cr, uid, [])
543 obj_values = objmodel.read(cr, uid, ids, [field_name])
544 for obj_value in obj_values:
545 res_id = obj_value['id']
546 if obj.name in ('ir.model', 'ir.ui.menu'):
548 model_data_ids = model_data_obj.search(cr, uid, [
549 ('model', '=', model),
550 ('res_id', '=', res_id),
552 if not model_data_ids:
553 push_translation(module, 'model', name, 0, encode(obj_value[field_name]))
555 if hasattr(field_def, 'selection') and isinstance(field_def.selection, (list, tuple)):
556 for key, val in field_def.selection:
557 push_translation(module, 'selection', name, 0, encode(val))
559 elif model=='ir.actions.report.xml':
560 name = encode(obj.report_name)
563 fname = obj.report_rml
564 parse_func = trans_parse_rml
567 fname = obj.report_xsl
568 parse_func = trans_parse_xsl
571 xmlstr = tools.file_open(fname).read()
572 d = etree.XML(xmlstr)
573 for t in parse_func(d):
574 push_translation(module, report_type, name, 0, t)
575 except IOError, etree.XMLSyntaxError:
577 logger.notifyChannel("i18n", netsvc.LOG_ERROR, "couldn't export translation for report %s %s %s" % (name, report_type, fname))
579 for constraint in pool.get(model)._constraints:
581 push_translation(module, 'constraint', model, 0, encode(msg))
583 for field_name,field_def in pool.get(model)._columns.items():
584 if field_def.translate:
585 name = model + "," + field_name
587 trad = getattr(obj, field_name) or ''
590 push_translation(module, 'model', name, xml_name, encode(trad))
592 # parse source code for _() calls
593 def get_module_from_path(path,mod_paths=None):
595 # First, construct a list of possible paths
596 def_path = os.path.abspath(os.path.join(tools.config['root_path'], 'addons')) # default addons path (base)
597 ad_paths= map(lambda m: os.path.abspath(m.strip()),tools.config['addons_path'].split(','))
600 mod_paths.append(adp)
601 if not adp.startswith('/'):
602 mod_paths.append(os.path.join(def_path,adp))
603 elif adp.startswith(def_path):
604 mod_paths.append(adp[len(def_path)+1:])
607 if path.startswith(mp) and (os.path.dirname(path) != mp):
608 path = path[len(mp)+1:]
609 return path.split(os.path.sep)[0]
610 return 'base' # files that are not in a module are considered as being in 'base' module
612 modobj = pool.get('ir.module.module')
613 installed_modids = modobj.search(cr, uid, [('state', '=', 'installed')])
614 installed_modules = map(lambda m: m['name'], modobj.read(cr, uid, installed_modids, ['name']))
616 root_path = os.path.join(tools.config['root_path'], 'addons')
618 if root_path in tools.config['addons_path'] :
619 path_list = [root_path]
621 path_list = [root_path,tools.config['addons_path']]
623 for path in path_list:
624 for root, dirs, files in tools.osutil.walksymlinks(path):
625 for fname in fnmatch.filter(files, '*.py'):
626 fabsolutepath = join(root, fname)
627 frelativepath = fabsolutepath[len(path):]
628 module = get_module_from_path(fabsolutepath)
629 is_mod_installed = module in installed_modules
630 if (('all' in modules) or (module in modules)) and is_mod_installed:
631 code_string = tools.file_open(fabsolutepath, subdir='').read()
632 iter = re.finditer('[^a-zA-Z0-9_]_\([\s]*["\'](.+?)["\'][\s]*\)',
635 if module in installed_modules :
636 frelativepath =str("addons"+frelativepath)
638 push_translation(module, 'code', frelativepath, 0, encode(i.group(1)))
641 out = [["module","type","name","res_id","src","value"]] # header
643 # translate strings marked as to be translated
644 for module, source, name, id, type in _to_translate:
645 trans = trans_obj._get_source(cr, uid, name, type, lang, source)
646 out.append([module, type, name, id, source, encode(trans) or ''])
651 def trans_load(db_name, filename, lang, strict=False, verbose=True):
652 logger = netsvc.Logger()
654 fileobj = open(filename,'r')
655 fileformat = os.path.splitext(filename)[-1][1:].lower()
656 r = trans_load_data(db_name, fileobj, fileformat, lang, strict=strict, verbose=verbose)
661 logger.notifyChannel("i18n", netsvc.LOG_ERROR, "couldn't read translation file %s" % (filename,))
664 def trans_load_data(db_name, fileobj, fileformat, lang, strict=False, lang_name=None, verbose=True):
665 logger = netsvc.Logger()
667 logger.notifyChannel("i18n", netsvc.LOG_INFO, 'loading translation file for language %s' % (lang))
668 pool = pooler.get_pool(db_name)
669 lang_obj = pool.get('res.lang')
670 trans_obj = pool.get('ir.translation')
671 model_data_obj = pool.get('ir.model.data')
672 iso_lang = tools.get_iso_codes(lang)
675 cr = pooler.get_db(db_name).cursor()
676 ids = lang_obj.search(cr, uid, [('code','=', lang)])
679 # lets create the language with locale information
681 for ln in get_locales(lang):
683 locale.setlocale(locale.LC_ALL, str(ln))
689 lc = locale.getdefaultlocale()[0]
690 msg = 'Unable to get information for locale %s. Information from the default locale (%s) have been used.'
691 logger.notifyChannel('i18n', netsvc.LOG_WARNING, msg % (lang, lc))
694 lang_name = tools.get_languages().get(lang, lang)
698 'iso_code': iso_lang,
701 'date_format' : str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y')),
702 'time_format' : str(locale.nl_langinfo(locale.T_FMT)),
703 'decimal_point' : str(locale.localeconv()['decimal_point']).replace('\xa0', '\xc2\xa0'),
704 'thousands_sep' : str(locale.localeconv()['thousands_sep']).replace('\xa0', '\xc2\xa0'),
707 lang_obj.create(cr, uid, lang_info)
712 # now, the serious things: we read the language file
714 if fileformat == 'csv':
715 reader = csv.reader(fileobj, quotechar='"', delimiter=',')
716 # read the first line of the file (it contains columns titles)
720 elif fileformat == 'po':
721 reader = TinyPoFile(fileobj)
722 f = ['type', 'name', 'res_id', 'src', 'value']
724 raise Exception(_('Bad file format'))
726 # read the rest of the file
730 # skip empty rows and rows where the translation field (=last fiefd) is empty
731 #if (not row) or (not row[-1]):
734 # dictionary which holds values for this line of the csv file
735 # {'lang': ..., 'type': ..., 'name': ..., 'res_id': ...,
736 # 'src': ..., 'value': ...}
738 for i in range(len(f)):
739 if f[i] in ('module',):
744 dic['res_id'] = int(dic['res_id'])
746 model_data_ids = model_data_obj.search(cr, uid, [
747 ('model', '=', dic['name'].split(',')[0]),
748 ('module', '=', dic['res_id'].split('.', 1)[0]),
749 ('name', '=', dic['res_id'].split('.', 1)[1]),
752 dic['res_id'] = model_data_obj.browse(cr, uid,
753 model_data_ids[0]).res_id
755 dic['res_id'] = False
757 if dic['type'] == 'model' and not strict:
758 (model, field) = dic['name'].split(',')
760 # get the ids of the resources of this model which share
762 obj = pool.get(model)
764 ids = obj.search(cr, uid, [(field, '=', dic['src'])])
766 # if the resource id (res_id) is in that list, use it,
767 # otherwise use the whole list
770 ids = (dic['res_id'] in ids) and [dic['res_id']] or ids
773 ids = trans_obj.search(cr, uid, [
775 ('type', '=', dic['type']),
776 ('name', '=', dic['name']),
777 ('src', '=', dic['src']),
778 ('res_id', '=', dic['res_id'])
781 trans_obj.write(cr, uid, ids, {'value': dic['value']})
783 trans_obj.create(cr, uid, dic)
785 ids = trans_obj.search(cr, uid, [
787 ('type', '=', dic['type']),
788 ('name', '=', dic['name']),
789 ('src', '=', dic['src'])
792 trans_obj.write(cr, uid, ids, {'value': dic['value']})
794 trans_obj.create(cr, uid, dic)
798 logger.notifyChannel("i18n", netsvc.LOG_INFO,
799 "translation file loaded succesfully")
801 filename = '[lang: %s][format: %s]' % (iso_lang or 'new', fileformat)
802 logger.notifyChannel("i18n", netsvc.LOG_ERROR, "couldn't read translation file %s" % (filename,))
804 def get_locales(lang=None):
806 lang = locale.getdefaultlocale()[0]
809 lang = _LOCALE2WIN32.get(lang, lang)
812 ln = locale._build_localename((lang, enc))
814 nln = locale.normalize(ln)
818 for x in process('utf8'): yield x
820 prefenc = locale.getpreferredencoding()
822 for x in process(prefenc): yield x
826 'iso-8859-1': 'iso8859-15',
828 }.get(prefenc.lower())
830 for x in process(prefenc): yield x
837 # locale.resetlocale is bugged with some locales.
838 for ln in get_locales():
840 return locale.setlocale(locale.LC_ALL, ln)
844 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: