2 # -*- coding: utf-8 -*-
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
10 # Full author contact details are available in file CREDITS
14 # to get usage message
16 # This script will extract translatable strings from input files and write
17 # to output in gettext .pot format.
19 import sys, os, re, getopt
20 if sys.version_info < (2, 4, 0):
21 from sets import Set as set
23 def relativePath(path, base):
24 '''return relative path from top source dir'''
25 # full pathname of path
26 path1 = os.path.normpath(os.path.realpath(path)).split(os.sep)
27 path2 = os.path.normpath(os.path.realpath(base)).split(os.sep)
28 if path1[:len(path2)] != path2:
29 print "Path %s is not under top source directory" % path
30 path3 = os.path.join(*path1[len(path2):]);
31 # replace all \ by / such that we get the same comments on Windows and *nix
32 path3 = path3.replace('\\', '/')
36 def writeString(outfile, infile, basefile, lineno, string):
37 string = string.replace('\\', '\\\\').replace('"', '')
40 print >> outfile, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
41 (relativePath(infile, basefile), lineno, string)
44 def ui_l10n(input_files, output, base):
45 '''Generate pot file from lib/ui/*'''
46 output = open(output, 'w')
47 Submenu = re.compile(r'^[^#]*Submenu\s+"([^"]*)"')
48 Popupmenu = re.compile(r'^[^#]*PopupMenu\s+"[^"]+"\s+"([^"]*)"')
49 IconPalette = re.compile(r'^[^#]*IconPalette\s+"[^"]+"\s+"([^"]*)"')
50 Toolbar = re.compile(r'^[^#]*Toolbar\s+"[^"]+"\s+"([^"]*)"')
51 Item = re.compile(r'[^#]*Item\s+"([^"]*)"')
52 TableInsert = re.compile(r'[^#]*TableInsert\s+"([^"]*)"')
53 for src in input_files:
55 for lineno, line in enumerate(input.readlines()):
56 if Submenu.match(line):
57 (string,) = Submenu.match(line).groups()
58 string = string.replace('_', ' ')
59 elif Popupmenu.match(line):
60 (string,) = Popupmenu.match(line).groups()
61 elif IconPalette.match(line):
62 (string,) = IconPalette.match(line).groups()
63 elif Toolbar.match(line):
64 (string,) = Toolbar.match(line).groups()
65 elif Item.match(line):
66 (string,) = Item.match(line).groups()
67 elif TableInsert.match(line):
68 (string,) = TableInsert.match(line).groups()
71 string = string.replace('"', '')
73 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
74 (relativePath(src, base), lineno+1, string)
79 def layouts_l10n(input_files, output, base, layouttranslations):
80 '''Generate pot file from lib/layouts/*.{layout,inc,module}'''
81 Style = re.compile(r'^Style\s+(.*)', re.IGNORECASE)
82 # include ???LabelString???, but exclude comment lines
83 LabelString = re.compile(r'^[^#]*LabelString\S*\s+(.*)')
84 GuiName = re.compile(r'\s*GuiName\s+(.*)')
85 ListName = re.compile(r'\s*ListName\s+(.*)')
86 CategoryName = re.compile(r'\s*Category\s+(.*)')
87 NameRE = re.compile(r'DeclareLyXModule.*{(.*)}')
88 InsetLayout = re.compile(r'^InsetLayout\s+\"?(.*)\"?')
89 FlexCheck = re.compile(r'^Flex:(.*)')
90 DescBegin = re.compile(r'#+\s*DescriptionBegin\s*$')
91 DescEnd = re.compile(r'#+\s*DescriptionEnd\s*$')
92 Category = re.compile(r'#Category: (.*)$')
93 I18nPreamble = re.compile(r'\s*(Lang)|(Babel)Preamble\s*$')
94 EndI18nPreamble = re.compile(r'\s*End(Lang)|(Babel)Preamble\s*$')
95 I18nString = re.compile(r'_\(([^\)]+)\)')
96 CounterFormat = re.compile(r'\s*PrettyFormat\s+"?(.*)"?')
97 CiteFormat = re.compile(r'\s*CiteFormat')
98 KeyVal = re.compile(r'^\s*_\w+\s+(.*)$')
99 Float = re.compile(r'\s*Float')
100 End = re.compile(r'\s*End')
101 Comment = re.compile(r'\s*#')
102 Translation = re.compile(r'\s*Translation\s+(.*)\s*$')
103 KeyValPair = re.compile(r'\s*"(.*)"\s+"(.*)"')
109 if layouttranslations:
110 linguas_file = os.path.join(base, 'po/LINGUAS')
111 for line in open(linguas_file).readlines():
112 if Comment.search(line) == None:
113 languages.extend(line.split())
115 # read old translations if available
119 for line in input.readlines():
120 res = Comment.search(line)
123 if line.strip() == '':
125 res = Translation.search(line)
128 if lang not in languages:
129 oldlanguages.append(lang)
130 languages.append(lang)
131 oldtrans[lang] = dict()
133 res = End.search(line)
137 res = KeyValPair.search(line)
138 if res and lang != '':
139 key = res.group(1).decode('utf-8')
140 val = res.group(2).decode('utf-8')
141 key = key.replace('\\"', '"').replace('\\\\', '\\')
142 val = val.replace('\\"', '"').replace('\\\\', '\\')
143 oldtrans[lang][key] = val
146 print "Error: Unable to handle line:"
149 print "Warning: Unable to open %s for reading." % output
150 print " Old translations will be lost."
152 # walon is not a known document language
153 # FIXME: Do not hardcode, read from lib/languages!
154 if 'wa' in languages:
155 languages.remove('wa')
157 out = open(output, 'w')
158 for src in input_files:
159 readingDescription = False
160 readingI18nPreamble = False
162 readingCiteFormats = False
166 for line in open(src).readlines():
168 if readingDescription:
169 res = DescEnd.search(line)
171 readingDescription = False
172 desc = " ".join(descLines)
173 if not layouttranslations:
174 writeString(out, src, base, lineno + 1, desc)
176 descLines.append(line[1:].strip())
178 res = DescBegin.search(line)
180 readingDescription = True
181 descStartLine = lineno
183 if readingI18nPreamble:
184 res = EndI18nPreamble.search(line)
186 readingI18nPreamble = False
188 res = I18nString.search(line)
190 string = res.group(1)
191 if layouttranslations:
194 writeString(out, src, base, lineno, string)
196 res = I18nPreamble.search(line)
198 readingI18nPreamble = True
200 res = NameRE.search(line)
202 string = res.group(1)
203 if not layouttranslations:
204 writeString(out, src, base, lineno + 1, string)
206 res = Style.search(line)
208 string = res.group(1)
209 string = string.replace('_', ' ')
210 if not layouttranslations:
211 writeString(out, src, base, lineno, string)
213 res = LabelString.search(line)
215 string = res.group(1)
216 if not layouttranslations:
217 writeString(out, src, base, lineno, string)
219 res = GuiName.search(line)
221 string = res.group(1)
222 if layouttranslations:
223 # gui name must only be added for floats
227 writeString(out, src, base, lineno, string)
229 res = CategoryName.search(line)
231 string = res.group(1)
232 if not layouttranslations:
233 writeString(out, src, base, lineno, string)
235 res = ListName.search(line)
237 string = res.group(1)
238 if layouttranslations:
239 keyset.add(string.strip('"'))
241 writeString(out, src, base, lineno, string)
243 res = InsetLayout.search(line)
245 string = res.group(1)
246 string = string.replace('_', ' ')
247 #Flex:xxx is not used in translation
248 #if not layouttranslations:
249 # writeString(out, src, base, lineno, string)
250 m = FlexCheck.search(string)
252 if not layouttranslations:
253 writeString(out, src, base, lineno, m.group(1))
255 res = Category.search(line)
257 string = res.group(1)
258 if not layouttranslations:
259 writeString(out, src, base, lineno, string)
261 res = CounterFormat.search(line)
263 string = res.group(1)
264 if not layouttranslations:
265 writeString(out, src, base, lineno, string)
267 res = Float.search(line)
271 res = CiteFormat.search(line)
273 readingCiteFormats = True
274 res = End.search(line)
276 readingCiteFormats = False
278 if readingCiteFormats:
279 res = KeyVal.search(line)
282 if not layouttranslations:
283 writeString(out, src, base, lineno, val)
285 if layouttranslations:
286 # Extract translations of layout files
289 # Sort languages and key to minimize the diff between different runs
290 # with changed translations
297 print >> out, '''# This file has been automatically generated by po/lyx_pot.py.
298 # PLEASE MODIFY ONLY THE LAGUAGES HAVING NO .po FILE! If you want to regenerate
299 # this file from the translations, run `make ../lib/layouttranslations' in po.
300 # Python polib library is needed for building the output file.
302 # This file should remain fixed during minor LyX releases.'''
303 for lang in languages:
304 print >> out, '\nTranslation %s' % lang
305 if lang in oldtrans.keys():
306 trans = oldtrans[lang]
309 if not lang in oldlanguages:
310 poname = os.path.join(base, 'po/' + lang + '.po')
311 po = polib.pofile(poname)
312 # Iterate through po entries and not keys for speed reasons.
313 # FIXME: The code is still too slow
315 if not entry.translated():
317 if entry.msgid in keys:
320 # some translators keep untranslated entries
324 if key in trans.keys():
325 val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
326 key = key.replace('\\', '\\\\').replace('"', '\\"')
327 print >> out, '\t"%s" "%s"' % \
328 (key.encode('utf-8'), val.encode('utf-8'))
329 # also print untranslated entries to help translators
330 elif not lang in oldlanguages:
331 key = key.replace('\\', '\\\\').replace('"', '\\"')
332 print >> out, '\t"%s" "%s"' % \
333 (key.encode('utf-8'), key.encode('utf-8'))
339 def qt4_l10n(input_files, output, base):
340 '''Generate pot file from src/frontends/qt4/ui/*.ui'''
341 output = open(output, 'w')
342 pat = re.compile(r'\s*<string>(.*)</string>')
343 prop = re.compile(r'\s*<property.*name.*=.*shortcut')
344 for src in input_files:
347 for lineno, line in enumerate(input.readlines()):
348 # skip the line after <property name=shortcut>
355 # get lines that match <string>...</string>
357 (string,) = pat.match(line).groups()
358 string = string.replace('&', '&').replace('"', '"')
359 string = string.replace('<', '<').replace('>', '>')
360 string = string.replace('\\', '\\\\').replace('"', r'\"')
361 string = string.replace('
', r'\n')
362 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
363 (relativePath(src, base), lineno+1, string)
368 def languages_l10n(input_files, output, base):
369 '''Generate pot file from lib/languages'''
370 out = open(output, 'w')
371 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)')
373 for src in input_files:
377 for line in open(src).readlines():
379 res = GuiName.search(line)
381 string = res.group(1)
382 writeString(out, src, base, lineno, string)
388 def external_l10n(input_files, output, base):
389 '''Generate pot file from lib/external_templates'''
390 output = open(output, 'w')
391 Template = re.compile(r'^Template\s+(.*)')
392 GuiName = re.compile(r'\s*GuiName\s+(.*)')
393 HelpTextStart = re.compile(r'\s*HelpText\s')
394 HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
395 HelpTextEnd = re.compile(r'\s*HelpTextEnd\s')
397 for src in input_files:
401 prev_help_string = ''
402 for lineno, line in enumerate(input.readlines()):
403 if Template.match(line):
404 (string,) = Template.match(line).groups()
405 elif GuiName.match(line):
406 (string,) = GuiName.match(line).groups()
408 if HelpTextEnd.match(line):
410 print >> output, '\nmsgstr ""\n'
413 prev_help_string = ''
414 elif HelpTextSection.match(line):
415 (help_string,) = HelpTextSection.match(line).groups()
416 help_string = help_string.replace('"', '')
417 if help_string != "" and prev_help_string == '':
418 print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
419 (relativePath(src, base), lineno+1, help_string)
421 elif help_string != "":
422 print >> output, '"%s\\n"' % help_string
423 prev_help_string = help_string
424 elif HelpTextStart.match(line):
426 prev_help_string = ''
429 string = string.replace('"', '')
430 if string != "" and not inHelp:
431 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
432 (relativePath(src, base), lineno+1, string)
437 def formats_l10n(input_files, output, base):
438 '''Generate pot file from configure.py'''
439 output = open(output, 'w')
440 GuiName = re.compile(r'.*\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*')
441 GuiName2 = re.compile(r'.*\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*')
442 input = open(input_files[0])
443 for lineno, line in enumerate(input.readlines()):
446 if GuiName.match(line):
447 label = GuiName.match(line).group(1)
448 shortcut = GuiName.match(line).group(2).replace('"', '')
449 elif GuiName2.match(line):
450 label = GuiName2.match(line).group(1)
451 shortcut = GuiName2.match(line).group(2).replace('"', '')
454 label = label.replace('\\', '\\\\').replace('"', '')
456 labelsc = label + "|" + shortcut
458 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
459 (relativePath(input_files[0], base), lineno+1, label)
461 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
462 (relativePath(input_files[0], base), lineno+1, labelsc)
467 def encodings_l10n(input_files, output, base):
468 '''Generate pot file from lib/encodings'''
469 output = open(output, 'w')
470 # assuming only one encodings file
471 # Encoding utf8 utf8 "Unicode (utf8)" UTF-8 variable inputenc
472 reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
473 input = open(input_files[0])
474 for lineno, line in enumerate(input.readlines()):
475 if not line.startswith('Encoding'):
478 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
479 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
481 print "Error: Unable to handle line:"
483 # No need to abort if the parsing fails
491 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
495 path to the top source directory. default to '.'
497 output pot file, default to './lyx.pot'
499 filename that contains a list of input files in each line
502 layouts: lib/layouts/*
503 layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
505 languages: file lib/languages
506 encodings: file lib/encodings
507 external: external templates file
508 formats: formats predefined in lib/configure.py
511 if __name__ == '__main__':
517 optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
518 ['help', 'type=', 'output=', 'base=', 'src_file='])
519 for (opt, value) in optlist:
520 if opt in ['-h', '--help']:
523 elif opt in ['-o', '--output']:
525 elif opt in ['-b', '--base']:
527 elif opt in ['-t', '--type']:
529 elif opt in ['-s', '--src_file']:
530 input_files = [f.strip() for f in open(value)]
532 if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'encodings', 'external', 'formats'] or output is None:
533 print 'Wrong input type or output filename.'
538 if input_type == 'ui':
539 ui_l10n(input_files, output, base)
540 elif input_type == 'layouts':
541 layouts_l10n(input_files, output, base, False)
542 elif input_type == 'layouttranslations':
543 layouts_l10n(input_files, output, base, True)
544 elif input_type == 'qt4':
545 qt4_l10n(input_files, output, base)
546 elif input_type == 'external':
547 external_l10n(input_files, output, base)
548 elif input_type == 'formats':
549 formats_l10n(input_files, output, base)
550 elif input_type == 'encodings':
551 encodings_l10n(input_files, output, base)
553 languages_l10n(input_files, output, base)