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))
295 m = CaptionCheck.search(string)
297 if not layouttranslations:
298 writeString(out, src, base, lineno, m.group(1))
300 res = Category.search(line)
302 string = res.group(1)
303 if not layouttranslations:
304 writeString(out, src, base, lineno, string)
306 res = CounterFormat.search(line)
308 string = res.group(1)
309 if not layouttranslations:
310 writeString(out, src, base, lineno, string)
312 res = Float.search(line)
316 res = IsPredefined.search(line)
318 string = res.group(1).lower()
324 res = UsesFloatPkg.search(line)
326 string = res.group(1).lower()
332 res = CiteFormat.search(line)
334 readingCiteFormats = True
336 res = End.search(line)
338 # If a float is predefined by the package and it does not need
339 # the float package then it uses the standard babel translations.
340 # This is even true for MarginFigure, MarginTable (both from
341 # tufte-book.layout) and Planotable, Plate (both from aguplus.inc).
342 if layouttranslations and readingFloat and usesFloatPkg and not isPredefined:
344 keyset.add(floatname)
351 readingCiteFormats = False
354 if readingCiteFormats:
355 res = KeyVal.search(line)
358 if not layouttranslations:
359 writeString(out, src, base, lineno, val)
361 if layouttranslations:
362 # Extract translations of layout files
365 # Sort languages and key to minimize the diff between different runs
366 # with changed translations
373 ContextRe = re.compile(r'(.*)(\[\[.*\]\])')
375 print >> out, '''# This file has been automatically generated by po/lyx_pot.py.
376 # PLEASE MODIFY ONLY THE LAGUAGES HAVING NO .po FILE! If you want to regenerate
377 # this file from the translations, run `make ../lib/layouttranslations' in po.
378 # Python polib library is needed for building the output file.
380 # This file should remain fixed during minor LyX releases.
381 # For more comments see README.localization file.'''
382 for lang in languages:
383 print >> out, '\nTranslation %s' % lang
384 if lang in oldtrans.keys():
385 trans = oldtrans[lang]
388 if not lang in oldlanguages:
389 poname = os.path.join(base, 'po/' + lang + '.po')
390 po = polib.pofile(poname)
391 # Iterate through po entries and not keys for speed reasons.
392 # FIXME: The code is still too slow
394 if not entry.translated():
396 if entry.msgid in keys:
399 # some translators keep untranslated entries
403 if key in trans.keys():
404 val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
405 key = key.replace('\\', '\\\\').replace('"', '\\"')
406 print >> out, '\t"%s" "%s"' % \
407 (key.encode('utf-8'), val.encode('utf-8'))
408 # also print untranslated entries to help translators
409 elif not lang in oldlanguages:
410 key = key.replace('\\', '\\\\').replace('"', '\\"')
411 res = ContextRe.search(key)
416 print >> out, '\t"%s" "%s"' % \
417 (key.encode('utf-8'), val.encode('utf-8'))
423 def qt4_l10n(input_files, output, base):
424 '''Generate pot file from src/frontends/qt4/ui/*.ui'''
425 output = open(output, 'w')
426 pat = re.compile(r'\s*<string>(.*)</string>')
427 prop = re.compile(r'\s*<property.*name.*=.*shortcut')
428 for src in input_files:
431 for lineno, line in enumerate(input.readlines()):
432 # skip the line after <property name=shortcut>
439 # get lines that match <string>...</string>
441 (string,) = pat.match(line).groups()
442 string = string.replace('&', '&').replace('"', '"')
443 string = string.replace('<', '<').replace('>', '>')
444 string = string.replace('\\', '\\\\').replace('"', r'\"')
445 string = string.replace('
', r'\n')
446 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
447 (relativePath(src, base), lineno+1, string)
452 def languages_l10n(input_files, output, base):
453 '''Generate pot file from lib/languages'''
454 out = open(output, 'w')
455 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
457 for src in input_files:
461 for line in open(src).readlines():
463 res = GuiName.search(line)
465 string = res.group(1)
466 writeString(out, src, base, lineno, string)
472 def latexfonts_l10n(input_files, output, base):
473 '''Generate pot file from lib/latexfonts'''
474 out = open(output, 'w')
475 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
477 for src in input_files:
481 for line in open(src).readlines():
483 res = GuiName.search(line)
485 string = res.group(1)
486 writeString(out, src, base, lineno, string)
492 def external_l10n(input_files, output, base):
493 '''Generate pot file from lib/external_templates'''
494 output = open(output, 'w')
495 Template = re.compile(r'^Template\s+(.*)', re.IGNORECASE)
496 GuiName = re.compile(r'\s*GuiName\s+(.*)', re.IGNORECASE)
497 HelpTextStart = re.compile(r'\s*HelpText\s', re.IGNORECASE)
498 HelpTextSection = re.compile(r'\s*(\S.*\S)\s*$')
499 HelpTextEnd = re.compile(r'\s*HelpTextEnd\s', re.IGNORECASE)
501 for src in input_files:
505 prev_help_string = ''
506 for lineno, line in enumerate(input.readlines()):
507 if Template.match(line):
508 (string,) = Template.match(line).groups()
509 elif GuiName.match(line):
510 (string,) = GuiName.match(line).groups()
512 if HelpTextEnd.match(line):
514 print >> output, '\nmsgstr ""\n'
517 prev_help_string = ''
518 elif HelpTextSection.match(line):
519 (help_string,) = HelpTextSection.match(line).groups()
520 help_string = help_string.replace('"', '')
521 if help_string != "" and prev_help_string == '':
522 print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
523 (relativePath(src, base), lineno+1, help_string)
525 elif help_string != "":
526 print >> output, '"%s\\n"' % help_string
527 prev_help_string = help_string
528 elif HelpTextStart.match(line):
530 prev_help_string = ''
533 string = string.replace('"', '')
534 if string != "" and not inHelp:
535 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
536 (relativePath(src, base), lineno+1, string)
541 def formats_l10n(input_files, output, base):
542 '''Generate pot file from configure.py'''
543 output = open(output, 'w')
544 GuiName = re.compile(r'.*\\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*', re.IGNORECASE)
545 GuiName2 = re.compile(r'.*\\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*', re.IGNORECASE)
546 input = open(input_files[0])
547 for lineno, line in enumerate(input.readlines()):
550 if GuiName.match(line):
551 label = GuiName.match(line).group(1)
552 shortcut = GuiName.match(line).group(2).replace('"', '')
553 elif GuiName2.match(line):
554 label = GuiName2.match(line).group(1)
555 shortcut = GuiName2.match(line).group(2).replace('"', '')
558 label = label.replace('\\', '\\\\').replace('"', '')
560 labelsc = label + "|" + shortcut
562 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
563 (relativePath(input_files[0], base), lineno+1, label)
565 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
566 (relativePath(input_files[0], base), lineno+1, labelsc)
571 def encodings_l10n(input_files, output, base):
572 '''Generate pot file from lib/encodings'''
573 output = open(output, 'w')
574 # assuming only one encodings file
575 # Encoding utf8 utf8 "Unicode (utf8)" UTF-8 variable inputenc
576 reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
577 input = open(input_files[0])
578 for lineno, line in enumerate(input.readlines()):
579 if not line.startswith('Encoding'):
582 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
583 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
585 print "Error: Unable to handle line:"
587 # No need to abort if the parsing fails
595 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
599 path to the top source directory. default to '.'
601 output pot file, default to './lyx.pot'
603 filename that contains a list of input files in each line
606 layouts: lib/layouts/*
607 layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
609 languages: file lib/languages
610 latexfonts: file lib/latexfonts
611 encodings: file lib/encodings
612 external: external templates file
613 formats: formats predefined in lib/configure.py
616 if __name__ == '__main__':
622 optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
623 ['help', 'type=', 'output=', 'base=', 'src_file='])
624 for (opt, value) in optlist:
625 if opt in ['-h', '--help']:
628 elif opt in ['-o', '--output']:
630 elif opt in ['-b', '--base']:
632 elif opt in ['-t', '--type']:
634 elif opt in ['-s', '--src_file']:
635 input_files = [f.strip() for f in open(value)]
637 if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'latexfonts', 'encodings', 'external', 'formats'] or output is None:
638 print 'Wrong input type or output filename.'
643 if input_type == 'ui':
644 ui_l10n(input_files, output, base)
645 elif input_type == 'latexfonts':
646 latexfonts_l10n(input_files, output, base)
647 elif input_type == 'layouts':
648 layouts_l10n(input_files, output, base, False)
649 elif input_type == 'layouttranslations':
650 layouts_l10n(input_files, output, base, True)
651 elif input_type == 'qt4':
652 qt4_l10n(input_files, output, base)
653 elif input_type == 'external':
654 external_l10n(input_files, output, base)
655 elif input_type == 'formats':
656 formats_l10n(input_files, output, base)
657 elif input_type == 'encodings':
658 encodings_l10n(input_files, output, base)
660 languages_l10n(input_files, output, base)