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 from __future__ import print_function
21 import sys, os, re, getopt
24 def relativePath(path, base):
25 '''return relative path from top source dir'''
26 # full pathname of path
27 path1 = os.path.normpath(os.path.realpath(path)).split(os.sep)
28 path2 = os.path.normpath(os.path.realpath(base)).split(os.sep)
29 if path1[:len(path2)] != path2:
30 print("Path %s is not under top source directory" % path)
31 path3 = os.path.join(*path1[len(path2):]);
32 # replace all \ by / such that we get the same comments on Windows and *nix
33 path3 = path3.replace('\\', '/')
37 def writeString(outfile, infile, basefile, lineno, string):
38 string = string.replace('\\', '\\\\').replace('"', '')
41 print(u'#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
42 (relativePath(infile, basefile), lineno, string), file=outfile)
45 def ui_l10n(input_files, output, base):
46 '''Generate pot file from lib/ui/*'''
47 output = io.open(output, 'w', encoding='utf_8', newline='\n')
48 Submenu = re.compile(r'^[^#]*Submenu\s+"([^"]*)"', re.IGNORECASE)
49 Popupmenu = re.compile(r'^[^#]*PopupMenu\s+"[^"]+"\s+"([^"]*)"', re.IGNORECASE)
50 IconPalette = re.compile(r'^[^#]*IconPalette\s+"[^"]+"\s+"([^"]*)"', re.IGNORECASE)
51 Toolbar = re.compile(r'^[^#]*Toolbar\s+"[^"]+"\s+"([^"]*)"', re.IGNORECASE)
52 Item = re.compile(r'[^#]*Item\s+"([^"]*)"', re.IGNORECASE)
53 TableInsert = re.compile(r'[^#]*TableInsert\s+"([^"]*)"', re.IGNORECASE)
54 for src in input_files:
55 input = io.open(src, encoding='utf_8')
56 for lineno, line in enumerate(input.readlines()):
57 if Submenu.match(line):
58 (string,) = Submenu.match(line).groups()
59 string = string.replace('_', ' ')
60 elif Popupmenu.match(line):
61 (string,) = Popupmenu.match(line).groups()
62 elif IconPalette.match(line):
63 (string,) = IconPalette.match(line).groups()
64 elif Toolbar.match(line):
65 (string,) = Toolbar.match(line).groups()
66 elif Item.match(line):
67 (string,) = Item.match(line).groups()
68 elif TableInsert.match(line):
69 (string,) = TableInsert.match(line).groups()
72 string = string.replace('"', '')
74 print(u'#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
75 (relativePath(src, base), lineno+1, string), file=output)
80 def layouts_l10n(input_files, output, base, layouttranslations):
81 '''Generate pot file from lib/layouts/*.{layout,inc,module}'''
82 ClassDescription = re.compile(r'^\s*#\s*\\Declare(LaTeX|DocBook)Class.*\{(.*)\}$', re.IGNORECASE)
83 ClassCategory = re.compile(r'^\s*#\s*\\DeclareCategory\{(.*)\}$', re.IGNORECASE)
84 Style = re.compile(r'^\s*Style\s+(.*\S)\s*$', re.IGNORECASE)
85 # match LabelString, EndLabelString, LabelStringAppendix and maybe others but no comments
86 LabelString = re.compile(r'^[^#]*LabelString\S*\s+(.*\S)\s*$', re.IGNORECASE)
87 MenuString = re.compile(r'^[^#]*MenuString\S*\s+(.*\S)\s*$', re.IGNORECASE)
88 OutlinerName = re.compile(r'^[^#]*OutlinerName\s+(\S+|\"[^\"]*\")\s+(\S+|\"[^\"]*\")\s*$', re.IGNORECASE)
89 Tooltip = re.compile(r'^\s*Tooltip\S*\s+(.*\S)\s*$', re.IGNORECASE)
90 GuiName = re.compile(r'^\s*GuiName\s+(.*\S)\s*$', re.IGNORECASE)
91 ListName = re.compile(r'^\s*ListName\s+(.*\S)\s*$', re.IGNORECASE)
92 CategoryName = re.compile(r'^\s*Category\s+(.*\S)\s*$', re.IGNORECASE)
93 NameRE = re.compile(r'^\s*#\s*\\DeclareLyXModule.*{(.*)}$', re.IGNORECASE)
94 InsetLayout = re.compile(r'^InsetLayout\s+\"?(.*)\"?\s*$', re.IGNORECASE)
95 FlexCheck = re.compile(r'^Flex:(.*)', re.IGNORECASE)
96 CaptionCheck = re.compile(r'^Caption:(.*)', re.IGNORECASE)
97 DescBegin = re.compile(r'^\s*#DescriptionBegin\s*$', re.IGNORECASE)
98 DescEnd = re.compile(r'^\s*#\s*DescriptionEnd\s*$', re.IGNORECASE)
99 Category = re.compile(r'^\s*#\s*Category:\s+(.*\S)\s*$', re.IGNORECASE)
100 I18nPreamble = re.compile(r'^\s*((Lang)|(Babel))Preamble\s*$', re.IGNORECASE)
101 EndI18nPreamble = re.compile(r'^\s*End((Lang)|(Babel))Preamble\s*$', re.IGNORECASE)
102 I18nString = re.compile(r'_\(([^\)]+)\)')
103 CounterFormat = re.compile(r'^\s*PrettyFormat\s+"?(.*)"?\s*$', re.IGNORECASE)
104 CiteFormat = re.compile(r'^\s*CiteFormat', re.IGNORECASE)
105 KeyVal = re.compile(r'^\s*_\w+\s+(.*\S)\s*$')
106 Float = re.compile(r'^\s*Float\s*$', re.IGNORECASE)
107 UsesFloatPkg = re.compile(r'^\s*UsesFloatPkg\s+(.*\S)\s*$', re.IGNORECASE)
108 IsPredefined = re.compile(r'^\s*IsPredefined\s+(.*\S)\s*$', re.IGNORECASE)
109 End = re.compile(r'^\s*End', re.IGNORECASE)
110 Comment = re.compile(r'^(.*)#')
111 Translation = re.compile(r'^\s*Translation\s+(.*\S)\s*$', re.IGNORECASE)
112 KeyValPair = re.compile(r'\s*"(.*)"\s+"(.*)"')
118 if layouttranslations:
119 linguas_file = os.path.join(base, 'po/LINGUAS')
120 for line in open(linguas_file).readlines():
121 res = Comment.search(line)
124 if line.strip() != '':
125 languages.extend(line.split())
127 # read old translations if available
129 input = io.open(output, encoding='utf_8')
131 for line in input.readlines():
132 res = Comment.search(line)
135 if line.strip() == '':
137 res = Translation.search(line)
140 if lang not in languages:
141 oldlanguages.append(lang)
142 languages.append(lang)
143 oldtrans[lang] = dict()
145 res = End.search(line)
149 res = KeyValPair.search(line)
150 if res and lang != '':
153 key = key.replace('\\"', '"').replace('\\\\', '\\')
154 val = val.replace('\\"', '"').replace('\\\\', '\\')
155 oldtrans[lang][key] = val
158 print("Error: Unable to handle line:")
161 print("Warning: Unable to open %s for reading." % output)
162 print(" Old translations will be lost.")
164 # walon is not a known document language
165 # FIXME: Do not hardcode, read from lib/languages!
166 if 'wa' in languages:
167 languages.remove('wa')
169 if layouttranslations:
170 out = io.open(output, 'w', encoding='utf_8')
172 out = io.open(output, 'w', encoding='utf_8', newline='\n')
173 for src in input_files:
174 readingDescription = False
175 readingI18nPreamble = False
177 readingCiteFormats = False
185 for line in io.open(src, encoding='utf_8').readlines():
187 res = ClassDescription.search(line)
189 string = res.group(2)
190 if not layouttranslations:
191 writeString(out, src, base, lineno + 1, string)
193 res = ClassCategory.search(line)
195 string = res.group(1)
196 if not layouttranslations:
197 writeString(out, src, base, lineno + 1, string)
199 if readingDescription:
200 res = DescEnd.search(line)
202 readingDescription = False
203 desc = " ".join(descLines)
204 if not layouttranslations:
205 writeString(out, src, base, lineno + 1, desc)
207 descLines.append(line[1:].strip())
209 res = DescBegin.search(line)
211 readingDescription = True
212 descStartLine = lineno
214 if readingI18nPreamble:
215 res = EndI18nPreamble.search(line)
217 readingI18nPreamble = False
219 res = I18nString.search(line)
221 string = res.group(1)
222 if layouttranslations:
225 writeString(out, src, base, lineno, string)
227 res = I18nPreamble.search(line)
229 readingI18nPreamble = True
231 res = NameRE.search(line)
233 string = res.group(1)
234 if not layouttranslations:
235 writeString(out, src, base, lineno + 1, string)
237 res = Style.search(line)
239 string = res.group(1)
240 string = string.replace('_', ' ')
241 # Style means something else inside a float definition
243 if not layouttranslations:
244 writeString(out, src, base, lineno, string)
246 res = LabelString.search(line)
248 string = res.group(1)
249 if not layouttranslations:
250 writeString(out, src, base, lineno, string)
252 res = MenuString.search(line)
254 string = res.group(1)
255 if not layouttranslations:
256 writeString(out, src, base, lineno, string)
258 res = OutlinerName.search(line)
260 string = res.group(2)
261 if not layouttranslations:
262 writeString(out, src, base, lineno, string)
264 res = Tooltip.search(line)
266 string = res.group(1)
267 if not layouttranslations:
268 writeString(out, src, base, lineno, string)
270 res = GuiName.search(line)
272 string = res.group(1)
273 if layouttranslations:
274 # gui name must only be added for floats
278 writeString(out, src, base, lineno, string)
280 res = CategoryName.search(line)
282 string = res.group(1)
283 if not layouttranslations:
284 writeString(out, src, base, lineno, string)
286 res = ListName.search(line)
288 string = res.group(1)
289 if layouttranslations:
290 listname = string.strip('"')
292 writeString(out, src, base, lineno, string)
294 res = InsetLayout.search(line)
296 string = res.group(1)
297 string = string.replace('_', ' ')
298 #Flex:xxx is not used in translation
299 #if not layouttranslations:
300 # writeString(out, src, base, lineno, string)
301 m = FlexCheck.search(string)
303 if not layouttranslations:
304 writeString(out, src, base, lineno, m.group(1))
305 m = CaptionCheck.search(string)
307 if not layouttranslations:
308 writeString(out, src, base, lineno, m.group(1))
310 res = Category.search(line)
312 string = res.group(1)
313 if not layouttranslations:
314 writeString(out, src, base, lineno, string)
316 res = CounterFormat.search(line)
318 string = res.group(1)
319 if not layouttranslations:
320 writeString(out, src, base, lineno, string)
322 res = Float.search(line)
326 res = IsPredefined.search(line)
328 string = res.group(1).lower()
334 res = UsesFloatPkg.search(line)
336 string = res.group(1).lower()
342 res = CiteFormat.search(line)
344 readingCiteFormats = True
346 res = End.search(line)
348 # We have four combinations of the flags usesFloatPkg and isPredefined:
349 # usesFloatPkg and isPredefined: might use standard babel translations
350 # usesFloatPkg and not isPredefined: does not use standard babel translations
351 # not usesFloatPkg and isPredefined: uses standard babel translations
352 # not usesFloatPkg and not isPredefined: not supported by LyX
353 # The third combination is even true for MarginFigure, MarginTable (both from
354 # tufte-book.layout) and Planotable, Plate (both from aguplus.inc).
355 if layouttranslations and readingFloat and usesFloatPkg:
357 keyset.add(floatname)
364 readingCiteFormats = False
367 if readingCiteFormats:
368 res = KeyVal.search(line)
371 if not layouttranslations:
372 writeString(out, src, base, lineno, val)
374 if layouttranslations:
375 # Extract translations of layout files
378 # Sort languages and key to minimize the diff between different runs
379 # with changed translations
386 ContextRe = re.compile(r'(.*)(\[\[.*\]\])')
388 print(u'''# This file has been automatically generated by po/lyx_pot.py.
389 # PLEASE MODIFY ONLY THE LAGUAGES HAVING NO .po FILE! If you want to regenerate
390 # this file from the translations, run `make ../lib/layouttranslations' in po.
391 # Python polib library is needed for building the output file.
393 # This file should remain fixed during minor LyX releases.
394 # For more comments see README.localization file.''', file=out)
395 for lang in languages:
396 print(u'\nTranslation %s' % lang, file=out)
397 if lang in list(oldtrans.keys()):
398 trans = oldtrans[lang]
401 if not lang in oldlanguages:
402 poname = os.path.join(base, 'po/' + lang + '.po')
403 po = polib.pofile(poname)
404 # Iterate through po entries and not keys for speed reasons.
405 # FIXME: The code is still too slow
407 if not entry.translated():
409 if entry.msgid in keys:
412 # some translators keep untranslated entries
416 if key in list(trans.keys()):
417 val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
418 res = ContextRe.search(val)
421 key = key.replace('\\', '\\\\').replace('"', '\\"')
422 print(u'\t"%s" "%s"' % (key, val), file=out)
423 # also print untranslated entries to help translators
424 elif not lang in oldlanguages:
425 key = key.replace('\\', '\\\\').replace('"', '\\"')
426 res = ContextRe.search(key)
431 print(u'\t"%s" "%s"' % (key, val), file=out)
432 print(u'End', file=out)
437 def qt4_l10n(input_files, output, base):
438 '''Generate pot file from src/frontends/qt4/ui/*.ui'''
439 output = io.open(output, 'w', encoding='utf_8', newline='\n')
440 pat = re.compile(r'\s*<string>(.*)</string>')
441 prop = re.compile(r'\s*<property.*name.*=.*shortcut')
442 for src in input_files:
443 input = io.open(src, encoding='utf_8')
445 for lineno, line in enumerate(input.readlines()):
446 # skip the line after <property name=shortcut>
453 # get lines that match <string>...</string>
455 (string,) = pat.match(line).groups()
456 string = string.replace('&', '&').replace('"', '"')
457 string = string.replace('<', '<').replace('>', '>')
458 string = string.replace('\\', '\\\\').replace('"', r'\"')
459 string = string.replace('
', r'\n')
460 print(u'#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
461 (relativePath(src, base), lineno+1, string), file=output)
466 def languages_l10n(input_files, output, base):
467 '''Generate pot file from lib/languages'''
468 out = io.open(output, 'w', encoding='utf_8', newline='\n')
469 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
471 for src in input_files:
475 for line in io.open(src, encoding='utf_8').readlines():
477 res = GuiName.search(line)
479 string = res.group(1)
480 writeString(out, src, base, lineno, string)
486 def latexfonts_l10n(input_files, output, base):
487 '''Generate pot file from lib/latexfonts'''
488 out = io.open(output, 'w', encoding='utf_8', newline='\n')
489 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
491 for src in input_files:
495 for line in io.open(src, encoding='utf_8').readlines():
497 res = GuiName.search(line)
499 string = res.group(1)
500 writeString(out, src, base, lineno, string)
506 def external_l10n(input_files, output, base):
507 '''Generate pot file from lib/external_templates'''
508 output = io.open(output, 'w', encoding='utf_8', newline='\n')
509 Template = re.compile(r'^Template\s+(.*)', re.IGNORECASE)
510 GuiName = re.compile(r'\s*GuiName\s+(.*)', re.IGNORECASE)
511 HelpTextStart = re.compile(r'\s*HelpText\s', re.IGNORECASE)
512 HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
513 HelpTextEnd = re.compile(r'\s*HelpTextEnd\s', re.IGNORECASE)
515 for src in input_files:
516 input = io.open(src, encoding='utf_8')
519 prev_help_string = ''
520 for lineno, line in enumerate(input.readlines()):
521 if Template.match(line):
522 (string,) = Template.match(line).groups()
523 elif GuiName.match(line):
524 (string,) = GuiName.match(line).groups()
526 if HelpTextEnd.match(line):
528 print(u'\nmsgstr ""\n', file=output)
531 prev_help_string = ''
532 elif HelpTextSection.match(line):
533 (help_string,) = HelpTextSection.match(line).groups()
534 help_string = help_string.replace('"', '')
535 if help_string != "" and prev_help_string == '':
536 print(u'#: %s:%d\nmsgid ""\n"%s\\n"' % \
537 (relativePath(src, base), lineno+1, help_string), file=output)
539 elif help_string != "":
540 print(u'"%s\\n"' % help_string, file=output)
541 prev_help_string = help_string
542 elif HelpTextStart.match(line):
544 prev_help_string = ''
547 string = string.replace('"', '')
548 if string != "" and not inHelp:
549 print(u'#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
550 (relativePath(src, base), lineno+1, string), file=output)
555 def formats_l10n(input_files, output, base):
556 '''Generate pot file from configure.py'''
557 output = io.open(output, 'w', encoding='utf_8', newline='\n')
558 GuiName = re.compile(r'.*\\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*', re.IGNORECASE)
559 GuiName2 = re.compile(r'.*\\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*', re.IGNORECASE)
560 input = io.open(input_files[0], encoding='utf_8')
561 for lineno, line in enumerate(input.readlines()):
564 if GuiName.match(line):
565 label = GuiName.match(line).group(1)
566 shortcut = GuiName.match(line).group(2).replace('"', '')
567 elif GuiName2.match(line):
568 label = GuiName2.match(line).group(1)
569 shortcut = GuiName2.match(line).group(2).replace('"', '')
572 label = label.replace('\\', '\\\\').replace('"', '')
574 labelsc = label + "|" + shortcut
576 print(u'#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
577 (relativePath(input_files[0], base), lineno+1, label), file=output)
579 print(u'#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
580 (relativePath(input_files[0], base), lineno+1, labelsc), file=output)
585 def encodings_l10n(input_files, output, base):
586 '''Generate pot file from lib/encodings'''
587 output = io.open(output, 'w', encoding='utf_8', newline='\n')
588 # assuming only one encodings file
589 # Encoding utf8 utf8 "Unicode (utf8)" UTF-8 variable inputenc
590 reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable|variableunsafe)\s+\w+.*')
591 input = io.open(input_files[0], encoding='utf_8')
592 for lineno, line in enumerate(input.readlines()):
593 if not line.startswith('Encoding'):
596 print(u'#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
597 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0]), file=output)
599 print("Error: Unable to handle line:")
601 # No need to abort if the parsing fails
609 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
613 path to the top source directory. default to '.'
615 output pot file, default to './lyx.pot'
617 filename that contains a list of input files in each line
620 layouts: lib/layouts/*
621 layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
623 languages: file lib/languages
624 latexfonts: file lib/latexfonts
625 encodings: file lib/encodings
626 external: external templates file
627 formats: formats predefined in lib/configure.py
630 if __name__ == '__main__':
636 optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
637 ['help', 'type=', 'output=', 'base=', 'src_file='])
638 for (opt, value) in optlist:
639 if opt in ['-h', '--help']:
642 elif opt in ['-o', '--output']:
644 elif opt in ['-b', '--base']:
646 elif opt in ['-t', '--type']:
648 elif opt in ['-s', '--src_file']:
649 input_files = [f.strip() for f in io.open(value, encoding='utf_8')]
651 if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'latexfonts', 'encodings', 'external', 'formats'] or output is None:
652 print('Wrong input type or output filename.')
657 # Ensure a unique sorting of input files and ignore the order in which they
658 # are given on the command line. This is important to avoid huge
659 # pseudo-diffs in the generated .pot file which would then end up in the
660 # .po files as well. We had this situation for years with people using
661 # different build systems to remerge .po files.
664 if input_type == 'ui':
665 ui_l10n(input_files, output, base)
666 elif input_type == 'latexfonts':
667 latexfonts_l10n(input_files, output, base)
668 elif input_type == 'layouts':
669 layouts_l10n(input_files, output, base, False)
670 elif input_type == 'layouttranslations':
671 layouts_l10n(input_files, output, base, True)
672 elif input_type == 'qt4':
673 qt4_l10n(input_files, output, base)
674 elif input_type == 'external':
675 external_l10n(input_files, output, base)
676 elif input_type == 'formats':
677 formats_l10n(input_files, output, base)
678 elif input_type == 'encodings':
679 encodings_l10n(input_files, output, base)
681 languages_l10n(input_files, output, base)