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*$', re.IGNORECASE)
84 # match LabelString, EndLabelString, LabelStringAppendix and maybe others but no comments
85 LabelString = re.compile(r'^[^#]*LabelString\S*\s+(.*)\s*$', re.IGNORECASE)
86 MenuString = re.compile(r'^[^#]*MenuString\S*\s+(.*)\s*$', re.IGNORECASE)
87 Tooltip = re.compile(r'^[^#]*Tooltip\S*\s+(.*)\s*$', re.IGNORECASE)
88 GuiName = re.compile(r'^\s*GuiName\s+(.*)\s*$', re.IGNORECASE)
89 ListName = re.compile(r'^\s*ListName\s+(.*)\s*$', re.IGNORECASE)
90 CategoryName = re.compile(r'^\s*Category\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 DescBegin = re.compile(r'^\s*#DescriptionBegin\s*$', re.IGNORECASE)
95 DescEnd = re.compile(r'^\s*#\s*DescriptionEnd\s*$', re.IGNORECASE)
96 Category = re.compile(r'^\s*#\s*Category:\s+(.*)\s*$', re.IGNORECASE)
97 I18nPreamble = re.compile(r'^\s*((Lang)|(Babel))Preamble\s*$', re.IGNORECASE)
98 EndI18nPreamble = re.compile(r'^\s*End((Lang)|(Babel))Preamble\s*$', re.IGNORECASE)
99 I18nString = re.compile(r'_\(([^\)]+)\)')
100 CounterFormat = re.compile(r'^\s*PrettyFormat\s+"?(.*)"?\s*$', re.IGNORECASE)
101 CiteFormat = re.compile(r'^\s*CiteFormat', re.IGNORECASE)
102 KeyVal = re.compile(r'^\s*_\w+\s+(.*)\s*$')
103 Float = re.compile(r'^\s*Float\s*$', re.IGNORECASE)
104 UsesFloatPkg = re.compile(r'^\s*UsesFloatPkg\s+(.*)\s*$', re.IGNORECASE)
105 IsPredefined = re.compile(r'^\s*IsPredefined\s+(.*)\s*$', re.IGNORECASE)
106 End = re.compile(r'^\s*End', re.IGNORECASE)
107 Comment = re.compile(r'^(.*)#')
108 Translation = re.compile(r'^\s*Translation\s+(.*)\s*$', re.IGNORECASE)
109 KeyValPair = re.compile(r'\s*"(.*)"\s+"(.*)"')
115 if layouttranslations:
116 linguas_file = os.path.join(base, 'po/LINGUAS')
117 for line in open(linguas_file).readlines():
118 res = Comment.search(line)
121 if line.strip() != '':
122 languages.extend(line.split())
124 # read old translations if available
128 for line in input.readlines():
129 res = Comment.search(line)
132 if line.strip() == '':
134 res = Translation.search(line)
137 if lang not in languages:
138 oldlanguages.append(lang)
139 languages.append(lang)
140 oldtrans[lang] = dict()
142 res = End.search(line)
146 res = KeyValPair.search(line)
147 if res and lang != '':
148 key = res.group(1).decode('utf-8')
149 val = res.group(2).decode('utf-8')
150 key = key.replace('\\"', '"').replace('\\\\', '\\')
151 val = val.replace('\\"', '"').replace('\\\\', '\\')
152 oldtrans[lang][key] = val
155 print "Error: Unable to handle line:"
158 print "Warning: Unable to open %s for reading." % output
159 print " Old translations will be lost."
161 # walon is not a known document language
162 # FIXME: Do not hardcode, read from lib/languages!
163 if 'wa' in languages:
164 languages.remove('wa')
166 out = open(output, 'w')
167 for src in input_files:
168 readingDescription = False
169 readingI18nPreamble = False
171 readingCiteFormats = False
179 for line in open(src).readlines():
181 res = ClassDescription.search(line)
183 string = res.group(2)
184 if not layouttranslations:
185 writeString(out, src, base, lineno + 1, string)
187 res = ClassCategory.search(line)
189 string = res.group(1)
190 if not layouttranslations:
191 writeString(out, src, base, lineno + 1, string)
193 if readingDescription:
194 res = DescEnd.search(line)
196 readingDescription = False
197 desc = " ".join(descLines)
198 if not layouttranslations:
199 writeString(out, src, base, lineno + 1, desc)
201 descLines.append(line[1:].strip())
203 res = DescBegin.search(line)
205 readingDescription = True
206 descStartLine = lineno
208 if readingI18nPreamble:
209 res = EndI18nPreamble.search(line)
211 readingI18nPreamble = False
213 res = I18nString.search(line)
215 string = res.group(1)
216 if layouttranslations:
219 writeString(out, src, base, lineno, string)
221 res = I18nPreamble.search(line)
223 readingI18nPreamble = True
225 res = NameRE.search(line)
227 string = res.group(1)
228 if not layouttranslations:
229 writeString(out, src, base, lineno + 1, string)
231 res = Style.search(line)
233 string = res.group(1)
234 string = string.replace('_', ' ')
235 # Style means something else inside a float definition
237 if not layouttranslations:
238 writeString(out, src, base, lineno, string)
240 res = LabelString.search(line)
242 string = res.group(1)
243 if not layouttranslations:
244 writeString(out, src, base, lineno, string)
246 res = MenuString.search(line)
248 string = res.group(1)
249 if not layouttranslations:
250 writeString(out, src, base, lineno, string)
252 res = Tooltip.search(line)
254 string = res.group(1)
255 if not layouttranslations:
256 writeString(out, src, base, lineno, string)
258 res = GuiName.search(line)
260 string = res.group(1)
261 if layouttranslations:
262 # gui name must only be added for floats
266 writeString(out, src, base, lineno, string)
268 res = CategoryName.search(line)
270 string = res.group(1)
271 if not layouttranslations:
272 writeString(out, src, base, lineno, string)
274 res = ListName.search(line)
276 string = res.group(1)
277 if layouttranslations:
278 listname = string.strip('"')
280 writeString(out, src, base, lineno, string)
282 res = InsetLayout.search(line)
284 string = res.group(1)
285 string = string.replace('_', ' ')
286 #Flex:xxx is not used in translation
287 #if not layouttranslations:
288 # writeString(out, src, base, lineno, string)
289 m = FlexCheck.search(string)
291 if not layouttranslations:
292 writeString(out, src, base, lineno, m.group(1))
294 res = Category.search(line)
296 string = res.group(1)
297 if not layouttranslations:
298 writeString(out, src, base, lineno, string)
300 res = CounterFormat.search(line)
302 string = res.group(1)
303 if not layouttranslations:
304 writeString(out, src, base, lineno, string)
306 res = Float.search(line)
310 res = IsPredefined.search(line)
312 string = res.group(1).lower()
318 res = UsesFloatPkg.search(line)
320 string = res.group(1).lower()
326 res = CiteFormat.search(line)
328 readingCiteFormats = True
330 res = End.search(line)
332 # If a float is predefined by the package and it does not need
333 # the float package then it uses the standard babel translations.
334 # This is even true for MarginFigure, MarginTable (both from
335 # tufte-book.layout) and Planotable, Plate (both from aguplus.inc).
336 if layouttranslations and readingFloat and usesFloatPkg and not isPredefined:
338 keyset.add(floatname)
345 readingCiteFormats = False
348 if readingCiteFormats:
349 res = KeyVal.search(line)
352 if not layouttranslations:
353 writeString(out, src, base, lineno, val)
355 if layouttranslations:
356 # Extract translations of layout files
359 # Sort languages and key to minimize the diff between different runs
360 # with changed translations
367 ContextRe = re.compile(r'(.*)(\[\[.*\]\])')
369 print >> out, '''# This file has been automatically generated by po/lyx_pot.py.
370 # PLEASE MODIFY ONLY THE LAGUAGES HAVING NO .po FILE! If you want to regenerate
371 # this file from the translations, run `make ../lib/layouttranslations' in po.
372 # Python polib library is needed for building the output file.
374 # This file should remain fixed during minor LyX releases.
375 # For more comments see README.localization file.'''
376 for lang in languages:
377 print >> out, '\nTranslation %s' % lang
378 if lang in oldtrans.keys():
379 trans = oldtrans[lang]
382 if not lang in oldlanguages:
383 poname = os.path.join(base, 'po/' + lang + '.po')
384 po = polib.pofile(poname)
385 # Iterate through po entries and not keys for speed reasons.
386 # FIXME: The code is still too slow
388 if not entry.translated():
390 if entry.msgid in keys:
393 # some translators keep untranslated entries
397 if key in trans.keys():
398 val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
399 key = key.replace('\\', '\\\\').replace('"', '\\"')
400 print >> out, '\t"%s" "%s"' % \
401 (key.encode('utf-8'), val.encode('utf-8'))
402 # also print untranslated entries to help translators
403 elif not lang in oldlanguages:
404 key = key.replace('\\', '\\\\').replace('"', '\\"')
405 res = ContextRe.search(key)
410 print >> out, '\t"%s" "%s"' % \
411 (key.encode('utf-8'), val.encode('utf-8'))
417 def qt4_l10n(input_files, output, base):
418 '''Generate pot file from src/frontends/qt4/ui/*.ui'''
419 output = open(output, 'w')
420 pat = re.compile(r'\s*<string>(.*)</string>')
421 prop = re.compile(r'\s*<property.*name.*=.*shortcut')
422 for src in input_files:
425 for lineno, line in enumerate(input.readlines()):
426 # skip the line after <property name=shortcut>
433 # get lines that match <string>...</string>
435 (string,) = pat.match(line).groups()
436 string = string.replace('&', '&').replace('"', '"')
437 string = string.replace('<', '<').replace('>', '>')
438 string = string.replace('\\', '\\\\').replace('"', r'\"')
439 string = string.replace('
', r'\n')
440 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
441 (relativePath(src, base), lineno+1, string)
446 def languages_l10n(input_files, output, base):
447 '''Generate pot file from lib/languages'''
448 out = open(output, 'w')
449 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
451 for src in input_files:
455 for line in open(src).readlines():
457 res = GuiName.search(line)
459 string = res.group(1)
460 writeString(out, src, base, lineno, string)
466 def latexfonts_l10n(input_files, output, base):
467 '''Generate pot file from lib/latexfonts'''
468 out = open(output, 'w')
469 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
471 for src in input_files:
475 for line in open(src).readlines():
477 res = GuiName.search(line)
479 string = res.group(1)
480 writeString(out, src, base, lineno, string)
486 def external_l10n(input_files, output, base):
487 '''Generate pot file from lib/external_templates'''
488 output = open(output, 'w')
489 Template = re.compile(r'^Template\s+(.*)', re.IGNORECASE)
490 GuiName = re.compile(r'\s*GuiName\s+(.*)', re.IGNORECASE)
491 HelpTextStart = re.compile(r'\s*HelpText\s', re.IGNORECASE)
492 HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
493 HelpTextEnd = re.compile(r'\s*HelpTextEnd\s', re.IGNORECASE)
495 for src in input_files:
499 prev_help_string = ''
500 for lineno, line in enumerate(input.readlines()):
501 if Template.match(line):
502 (string,) = Template.match(line).groups()
503 elif GuiName.match(line):
504 (string,) = GuiName.match(line).groups()
506 if HelpTextEnd.match(line):
508 print >> output, '\nmsgstr ""\n'
511 prev_help_string = ''
512 elif HelpTextSection.match(line):
513 (help_string,) = HelpTextSection.match(line).groups()
514 help_string = help_string.replace('"', '')
515 if help_string != "" and prev_help_string == '':
516 print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
517 (relativePath(src, base), lineno+1, help_string)
519 elif help_string != "":
520 print >> output, '"%s\\n"' % help_string
521 prev_help_string = help_string
522 elif HelpTextStart.match(line):
524 prev_help_string = ''
527 string = string.replace('"', '')
528 if string != "" and not inHelp:
529 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
530 (relativePath(src, base), lineno+1, string)
535 def formats_l10n(input_files, output, base):
536 '''Generate pot file from configure.py'''
537 output = open(output, 'w')
538 GuiName = re.compile(r'.*\\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*', re.IGNORECASE)
539 GuiName2 = re.compile(r'.*\\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*', re.IGNORECASE)
540 input = open(input_files[0])
541 for lineno, line in enumerate(input.readlines()):
544 if GuiName.match(line):
545 label = GuiName.match(line).group(1)
546 shortcut = GuiName.match(line).group(2).replace('"', '')
547 elif GuiName2.match(line):
548 label = GuiName2.match(line).group(1)
549 shortcut = GuiName2.match(line).group(2).replace('"', '')
552 label = label.replace('\\', '\\\\').replace('"', '')
554 labelsc = label + "|" + shortcut
556 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
557 (relativePath(input_files[0], base), lineno+1, label)
559 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
560 (relativePath(input_files[0], base), lineno+1, labelsc)
565 def encodings_l10n(input_files, output, base):
566 '''Generate pot file from lib/encodings'''
567 output = open(output, 'w')
568 # assuming only one encodings file
569 # Encoding utf8 utf8 "Unicode (utf8)" UTF-8 variable inputenc
570 reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
571 input = open(input_files[0])
572 for lineno, line in enumerate(input.readlines()):
573 if not line.startswith('Encoding'):
576 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
577 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
579 print "Error: Unable to handle line:"
581 # No need to abort if the parsing fails
589 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
593 path to the top source directory. default to '.'
595 output pot file, default to './lyx.pot'
597 filename that contains a list of input files in each line
600 layouts: lib/layouts/*
601 layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
603 languages: file lib/languages
604 latexfonts: file lib/latexfonts
605 encodings: file lib/encodings
606 external: external templates file
607 formats: formats predefined in lib/configure.py
610 if __name__ == '__main__':
616 optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
617 ['help', 'type=', 'output=', 'base=', 'src_file='])
618 for (opt, value) in optlist:
619 if opt in ['-h', '--help']:
622 elif opt in ['-o', '--output']:
624 elif opt in ['-b', '--base']:
626 elif opt in ['-t', '--type']:
628 elif opt in ['-s', '--src_file']:
629 input_files = [f.strip() for f in open(value)]
631 if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'latexfonts', 'encodings', 'external', 'formats'] or output is None:
632 print 'Wrong input type or output filename.'
637 if input_type == 'ui':
638 ui_l10n(input_files, output, base)
639 elif input_type == 'latexfonts':
640 latexfonts_l10n(input_files, output, base)
641 elif input_type == 'layouts':
642 layouts_l10n(input_files, output, base, False)
643 elif input_type == 'layouttranslations':
644 layouts_l10n(input_files, output, base, True)
645 elif input_type == 'qt4':
646 qt4_l10n(input_files, output, base)
647 elif input_type == 'external':
648 external_l10n(input_files, output, base)
649 elif input_type == 'formats':
650 formats_l10n(input_files, output, base)
651 elif input_type == 'encodings':
652 encodings_l10n(input_files, output, base)
654 languages_l10n(input_files, output, base)