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+"([^"]*)"', re.IGNORECASE)
48 Popupmenu = re.compile(r'^[^#]*PopupMenu\s+"[^"]+"\s+"([^"]*)"', re.IGNORECASE)
49 IconPalette = re.compile(r'^[^#]*IconPalette\s+"[^"]+"\s+"([^"]*)"', re.IGNORECASE)
50 Toolbar = re.compile(r'^[^#]*Toolbar\s+"[^"]+"\s+"([^"]*)"', re.IGNORECASE)
51 Item = re.compile(r'[^#]*Item\s+"([^"]*)"', re.IGNORECASE)
52 TableInsert = re.compile(r'[^#]*TableInsert\s+"([^"]*)"', re.IGNORECASE)
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 ClassDescription = re.compile(r'^\s*#\s*\\Declare(LaTeX|DocBook)Class.*\{(.*)\}$', re.IGNORECASE)
82 ClassCategory = re.compile(r'^\s*#\s*\\DeclareCategory\{(.*)\}$', re.IGNORECASE)
83 Style = re.compile(r'^\s*Style\s+(.*\S)\s*$', re.IGNORECASE)
84 # match LabelString, EndLabelString, LabelStringAppendix and maybe others but no comments
85 LabelString = re.compile(r'^[^#]*LabelString\S*\s+(.*\S)\s*$', re.IGNORECASE)
86 MenuString = re.compile(r'^[^#]*MenuString\S*\s+(.*\S)\s*$', re.IGNORECASE)
87 Tooltip = re.compile(r'^[^#]*Tooltip\S*\s+(.*\S)\s*$', re.IGNORECASE)
88 GuiName = re.compile(r'^\s*GuiName\s+(.*\S)\s*$', re.IGNORECASE)
89 ListName = re.compile(r'^\s*ListName\s+(.*\S)\s*$', re.IGNORECASE)
90 CategoryName = re.compile(r'^\s*Category\s+(.*\S)\s*$', re.IGNORECASE)
91 NameRE = re.compile(r'^\s*#\s*\\DeclareLyXModule.*{(.*)}$', re.IGNORECASE)
92 InsetLayout = re.compile(r'^InsetLayout\s+\"?(.*)\"?\s*$', re.IGNORECASE)
93 FlexCheck = re.compile(r'^Flex:(.*)', re.IGNORECASE)
94 CaptionCheck = re.compile(r'^Caption:(.*)', re.IGNORECASE)
95 DescBegin = re.compile(r'^\s*#DescriptionBegin\s*$', re.IGNORECASE)
96 DescEnd = re.compile(r'^\s*#\s*DescriptionEnd\s*$', re.IGNORECASE)
97 Category = re.compile(r'^\s*#\s*Category:\s+(.*\S)\s*$', re.IGNORECASE)
98 I18nPreamble = re.compile(r'^\s*((Lang)|(Babel))Preamble\s*$', re.IGNORECASE)
99 EndI18nPreamble = re.compile(r'^\s*End((Lang)|(Babel))Preamble\s*$', re.IGNORECASE)
100 I18nString = re.compile(r'_\(([^\)]+)\)')
101 CounterFormat = re.compile(r'^\s*PrettyFormat\s+"?(.*)"?\s*$', re.IGNORECASE)
102 CiteFormat = re.compile(r'^\s*CiteFormat', re.IGNORECASE)
103 KeyVal = re.compile(r'^\s*_\w+\s+(.*\S)\s*$')
104 Float = re.compile(r'^\s*Float\s*$', re.IGNORECASE)
105 UsesFloatPkg = re.compile(r'^\s*UsesFloatPkg\s+(.*\S)\s*$', re.IGNORECASE)
106 IsPredefined = re.compile(r'^\s*IsPredefined\s+(.*\S)\s*$', re.IGNORECASE)
107 End = re.compile(r'^\s*End', re.IGNORECASE)
108 Comment = re.compile(r'^(.*)#')
109 Translation = re.compile(r'^\s*Translation\s+(.*\S)\s*$', re.IGNORECASE)
110 KeyValPair = re.compile(r'\s*"(.*)"\s+"(.*)"')
116 if layouttranslations:
117 linguas_file = os.path.join(base, 'po/LINGUAS')
118 for line in open(linguas_file).readlines():
119 res = Comment.search(line)
122 if line.strip() != '':
123 languages.extend(line.split())
125 # read old translations if available
129 for line in input.readlines():
130 res = Comment.search(line)
133 if line.strip() == '':
135 res = Translation.search(line)
138 if lang not in languages:
139 oldlanguages.append(lang)
140 languages.append(lang)
141 oldtrans[lang] = dict()
143 res = End.search(line)
147 res = KeyValPair.search(line)
148 if res and lang != '':
149 key = res.group(1).decode('utf-8')
150 val = res.group(2).decode('utf-8')
151 key = key.replace('\\"', '"').replace('\\\\', '\\')
152 val = val.replace('\\"', '"').replace('\\\\', '\\')
153 oldtrans[lang][key] = val
156 print "Error: Unable to handle line:"
159 print "Warning: Unable to open %s for reading." % output
160 print " Old translations will be lost."
162 # walon is not a known document language
163 # FIXME: Do not hardcode, read from lib/languages!
164 if 'wa' in languages:
165 languages.remove('wa')
167 out = open(output, 'w')
168 for src in input_files:
169 readingDescription = False
170 readingI18nPreamble = False
172 readingCiteFormats = False
180 for line in open(src).readlines():
182 res = ClassDescription.search(line)
184 string = res.group(2)
185 if not layouttranslations:
186 writeString(out, src, base, lineno + 1, string)
188 res = ClassCategory.search(line)
190 string = res.group(1)
191 if not layouttranslations:
192 writeString(out, src, base, lineno + 1, string)
194 if readingDescription:
195 res = DescEnd.search(line)
197 readingDescription = False
198 desc = " ".join(descLines)
199 if not layouttranslations:
200 writeString(out, src, base, lineno + 1, desc)
202 descLines.append(line[1:].strip())
204 res = DescBegin.search(line)
206 readingDescription = True
207 descStartLine = lineno
209 if readingI18nPreamble:
210 res = EndI18nPreamble.search(line)
212 readingI18nPreamble = False
214 res = I18nString.search(line)
216 string = res.group(1)
217 if layouttranslations:
220 writeString(out, src, base, lineno, string)
222 res = I18nPreamble.search(line)
224 readingI18nPreamble = True
226 res = NameRE.search(line)
228 string = res.group(1)
229 if not layouttranslations:
230 writeString(out, src, base, lineno + 1, string)
232 res = Style.search(line)
234 string = res.group(1)
235 string = string.replace('_', ' ')
236 # Style means something else inside a float definition
238 if not layouttranslations:
239 writeString(out, src, base, lineno, string)
241 res = LabelString.search(line)
243 string = res.group(1)
244 if not layouttranslations:
245 writeString(out, src, base, lineno, string)
247 res = MenuString.search(line)
249 string = res.group(1)
250 if not layouttranslations:
251 writeString(out, src, base, lineno, string)
253 res = Tooltip.search(line)
255 string = res.group(1)
256 if not layouttranslations:
257 writeString(out, src, base, lineno, string)
259 res = GuiName.search(line)
261 string = res.group(1)
262 if layouttranslations:
263 # gui name must only be added for floats
267 writeString(out, src, base, lineno, string)
269 res = CategoryName.search(line)
271 string = res.group(1)
272 if not layouttranslations:
273 writeString(out, src, base, lineno, string)
275 res = ListName.search(line)
277 string = res.group(1)
278 if layouttranslations:
279 listname = string.strip('"')
281 writeString(out, src, base, lineno, string)
283 res = InsetLayout.search(line)
285 string = res.group(1)
286 string = string.replace('_', ' ')
287 #Flex:xxx is not used in translation
288 #if not layouttranslations:
289 # writeString(out, src, base, lineno, string)
290 m = FlexCheck.search(string)
292 if not layouttranslations:
293 writeString(out, src, base, lineno, m.group(1))
294 m = CaptionCheck.search(string)
296 if not layouttranslations:
297 writeString(out, src, base, lineno, m.group(1))
299 res = Category.search(line)
301 string = res.group(1)
302 if not layouttranslations:
303 writeString(out, src, base, lineno, string)
305 res = CounterFormat.search(line)
307 string = res.group(1)
308 if not layouttranslations:
309 writeString(out, src, base, lineno, string)
311 res = Float.search(line)
315 res = IsPredefined.search(line)
317 string = res.group(1).lower()
323 res = UsesFloatPkg.search(line)
325 string = res.group(1).lower()
331 res = CiteFormat.search(line)
333 readingCiteFormats = True
335 res = End.search(line)
337 # If a float is predefined by the package and it does not need
338 # the float package then it uses the standard babel translations.
339 # This is even true for MarginFigure, MarginTable (both from
340 # tufte-book.layout) and Planotable, Plate (both from aguplus.inc).
341 if layouttranslations and readingFloat and usesFloatPkg and not isPredefined:
343 keyset.add(floatname)
350 readingCiteFormats = False
353 if readingCiteFormats:
354 res = KeyVal.search(line)
357 if not layouttranslations:
358 writeString(out, src, base, lineno, val)
360 if layouttranslations:
361 # Extract translations of layout files
364 # Sort languages and key to minimize the diff between different runs
365 # with changed translations
372 ContextRe = re.compile(r'(.*)(\[\[.*\]\])')
374 print >> out, '''# This file has been automatically generated by po/lyx_pot.py.
375 # PLEASE MODIFY ONLY THE LAGUAGES HAVING NO .po FILE! If you want to regenerate
376 # this file from the translations, run `make ../lib/layouttranslations' in po.
377 # Python polib library is needed for building the output file.
379 # This file should remain fixed during minor LyX releases.
380 # For more comments see README.localization file.'''
381 for lang in languages:
382 print >> out, '\nTranslation %s' % lang
383 if lang in oldtrans.keys():
384 trans = oldtrans[lang]
387 if not lang in oldlanguages:
388 poname = os.path.join(base, 'po/' + lang + '.po')
389 po = polib.pofile(poname)
390 # Iterate through po entries and not keys for speed reasons.
391 # FIXME: The code is still too slow
393 if not entry.translated():
395 if entry.msgid in keys:
398 # some translators keep untranslated entries
402 if key in trans.keys():
403 val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
404 key = key.replace('\\', '\\\\').replace('"', '\\"')
405 print >> out, '\t"%s" "%s"' % \
406 (key.encode('utf-8'), val.encode('utf-8'))
407 # also print untranslated entries to help translators
408 elif not lang in oldlanguages:
409 key = key.replace('\\', '\\\\').replace('"', '\\"')
410 res = ContextRe.search(key)
415 print >> out, '\t"%s" "%s"' % \
416 (key.encode('utf-8'), val.encode('utf-8'))
422 def qt4_l10n(input_files, output, base):
423 '''Generate pot file from src/frontends/qt4/ui/*.ui'''
424 output = open(output, 'w')
425 pat = re.compile(r'\s*<string>(.*)</string>')
426 prop = re.compile(r'\s*<property.*name.*=.*shortcut')
427 for src in input_files:
430 for lineno, line in enumerate(input.readlines()):
431 # skip the line after <property name=shortcut>
438 # get lines that match <string>...</string>
440 (string,) = pat.match(line).groups()
441 string = string.replace('&', '&').replace('"', '"')
442 string = string.replace('<', '<').replace('>', '>')
443 string = string.replace('\\', '\\\\').replace('"', r'\"')
444 string = string.replace('
', r'\n')
445 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
446 (relativePath(src, base), lineno+1, string)
451 def languages_l10n(input_files, output, base):
452 '''Generate pot file from lib/languages'''
453 out = open(output, 'w')
454 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
456 for src in input_files:
460 for line in open(src).readlines():
462 res = GuiName.search(line)
464 string = res.group(1)
465 writeString(out, src, base, lineno, string)
471 def latexfonts_l10n(input_files, output, base):
472 '''Generate pot file from lib/latexfonts'''
473 out = open(output, 'w')
474 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
476 for src in input_files:
480 for line in open(src).readlines():
482 res = GuiName.search(line)
484 string = res.group(1)
485 writeString(out, src, base, lineno, string)
491 def external_l10n(input_files, output, base):
492 '''Generate pot file from lib/external_templates'''
493 output = open(output, 'w')
494 Template = re.compile(r'^Template\s+(.*)', re.IGNORECASE)
495 GuiName = re.compile(r'\s*GuiName\s+(.*)', re.IGNORECASE)
496 HelpTextStart = re.compile(r'\s*HelpText\s', re.IGNORECASE)
497 HelpTextSection = re.compile(r'\s*(\S.*\S)\s*$')
498 HelpTextEnd = re.compile(r'\s*HelpTextEnd\s', re.IGNORECASE)
500 for src in input_files:
504 prev_help_string = ''
505 for lineno, line in enumerate(input.readlines()):
506 if Template.match(line):
507 (string,) = Template.match(line).groups()
508 elif GuiName.match(line):
509 (string,) = GuiName.match(line).groups()
511 if HelpTextEnd.match(line):
513 print >> output, '\nmsgstr ""\n'
516 prev_help_string = ''
517 elif HelpTextSection.match(line):
518 (help_string,) = HelpTextSection.match(line).groups()
519 help_string = help_string.replace('"', '')
520 if help_string != "" and prev_help_string == '':
521 print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
522 (relativePath(src, base), lineno+1, help_string)
524 elif help_string != "":
525 print >> output, '"%s\\n"' % help_string
526 prev_help_string = help_string
527 elif HelpTextStart.match(line):
529 prev_help_string = ''
532 string = string.replace('"', '')
533 if string != "" and not inHelp:
534 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
535 (relativePath(src, base), lineno+1, string)
540 def formats_l10n(input_files, output, base):
541 '''Generate pot file from configure.py'''
542 output = open(output, 'w')
543 GuiName = re.compile(r'.*\\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*', re.IGNORECASE)
544 GuiName2 = re.compile(r'.*\\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*', re.IGNORECASE)
545 input = open(input_files[0])
546 for lineno, line in enumerate(input.readlines()):
549 if GuiName.match(line):
550 label = GuiName.match(line).group(1)
551 shortcut = GuiName.match(line).group(2).replace('"', '')
552 elif GuiName2.match(line):
553 label = GuiName2.match(line).group(1)
554 shortcut = GuiName2.match(line).group(2).replace('"', '')
557 label = label.replace('\\', '\\\\').replace('"', '')
559 labelsc = label + "|" + shortcut
561 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
562 (relativePath(input_files[0], base), lineno+1, label)
564 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
565 (relativePath(input_files[0], base), lineno+1, labelsc)
570 def encodings_l10n(input_files, output, base):
571 '''Generate pot file from lib/encodings'''
572 output = open(output, 'w')
573 # assuming only one encodings file
574 # Encoding utf8 utf8 "Unicode (utf8)" UTF-8 variable inputenc
575 reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
576 input = open(input_files[0])
577 for lineno, line in enumerate(input.readlines()):
578 if not line.startswith('Encoding'):
581 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
582 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
584 print "Error: Unable to handle line:"
586 # No need to abort if the parsing fails
594 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
598 path to the top source directory. default to '.'
600 output pot file, default to './lyx.pot'
602 filename that contains a list of input files in each line
605 layouts: lib/layouts/*
606 layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
608 languages: file lib/languages
609 latexfonts: file lib/latexfonts
610 encodings: file lib/encodings
611 external: external templates file
612 formats: formats predefined in lib/configure.py
615 if __name__ == '__main__':
621 optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
622 ['help', 'type=', 'output=', 'base=', 'src_file='])
623 for (opt, value) in optlist:
624 if opt in ['-h', '--help']:
627 elif opt in ['-o', '--output']:
629 elif opt in ['-b', '--base']:
631 elif opt in ['-t', '--type']:
633 elif opt in ['-s', '--src_file']:
634 input_files = [f.strip() for f in open(value)]
636 if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'latexfonts', 'encodings', 'external', 'formats'] or output is None:
637 print 'Wrong input type or output filename.'
642 if input_type == 'ui':
643 ui_l10n(input_files, output, base)
644 elif input_type == 'latexfonts':
645 latexfonts_l10n(input_files, output, base)
646 elif input_type == 'layouts':
647 layouts_l10n(input_files, output, base, False)
648 elif input_type == 'layouttranslations':
649 layouts_l10n(input_files, output, base, True)
650 elif input_type == 'qt4':
651 qt4_l10n(input_files, output, base)
652 elif input_type == 'external':
653 external_l10n(input_files, output, base)
654 elif input_type == 'formats':
655 formats_l10n(input_files, output, base)
656 elif input_type == 'encodings':
657 encodings_l10n(input_files, output, base)
659 languages_l10n(input_files, output, base)