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 GuiName = re.compile(r'^\s*GuiName\s+(.*)\s*$', re.IGNORECASE)
87 ListName = re.compile(r'^\s*ListName\s+(.*)\s*$', re.IGNORECASE)
88 CategoryName = re.compile(r'^\s*Category\s+(.*)\s*$', re.IGNORECASE)
89 NameRE = re.compile(r'^\s*#\s*\\DeclareLyXModule.*{(.*)}$', re.IGNORECASE)
90 InsetLayout = re.compile(r'^InsetLayout\s+\"?(.*)\"?\s*$', re.IGNORECASE)
91 FlexCheck = re.compile(r'^Flex:(.*)', re.IGNORECASE)
92 DescBegin = re.compile(r'^\s*#DescriptionBegin\s*$', re.IGNORECASE)
93 DescEnd = re.compile(r'^\s*#\s*DescriptionEnd\s*$', re.IGNORECASE)
94 Category = re.compile(r'^\s*#\s*Category:\s+(.*)\s*$', re.IGNORECASE)
95 I18nPreamble = re.compile(r'^\s*((Lang)|(Babel))Preamble\s*$', re.IGNORECASE)
96 EndI18nPreamble = re.compile(r'^\s*End((Lang)|(Babel))Preamble\s*$', re.IGNORECASE)
97 I18nString = re.compile(r'_\(([^\)]+)\)')
98 CounterFormat = re.compile(r'^\s*PrettyFormat\s+"?(.*)"?\s*$', re.IGNORECASE)
99 CiteFormat = re.compile(r'^\s*CiteFormat', re.IGNORECASE)
100 KeyVal = re.compile(r'^\s*_\w+\s+(.*)\s*$')
101 Float = re.compile(r'^\s*Float\s*$', re.IGNORECASE)
102 UsesFloatPkg = re.compile(r'^\s*UsesFloatPkg\s+(.*)\s*$', re.IGNORECASE)
103 IsPredefined = re.compile(r'^\s*IsPredefined\s+(.*)\s*$', re.IGNORECASE)
104 End = re.compile(r'^\s*End', re.IGNORECASE)
105 Comment = re.compile(r'^(.*)#')
106 Translation = re.compile(r'^\s*Translation\s+(.*)\s*$', re.IGNORECASE)
107 KeyValPair = re.compile(r'\s*"(.*)"\s+"(.*)"')
113 if layouttranslations:
114 linguas_file = os.path.join(base, 'po/LINGUAS')
115 for line in open(linguas_file).readlines():
116 res = Comment.search(line)
119 if line.strip() != '':
120 languages.extend(line.split())
122 # read old translations if available
126 for line in input.readlines():
127 res = Comment.search(line)
130 if line.strip() == '':
132 res = Translation.search(line)
135 if lang not in languages:
136 oldlanguages.append(lang)
137 languages.append(lang)
138 oldtrans[lang] = dict()
140 res = End.search(line)
144 res = KeyValPair.search(line)
145 if res and lang != '':
146 key = res.group(1).decode('utf-8')
147 val = res.group(2).decode('utf-8')
148 key = key.replace('\\"', '"').replace('\\\\', '\\')
149 val = val.replace('\\"', '"').replace('\\\\', '\\')
150 oldtrans[lang][key] = val
153 print "Error: Unable to handle line:"
156 print "Warning: Unable to open %s for reading." % output
157 print " Old translations will be lost."
159 # walon is not a known document language
160 # FIXME: Do not hardcode, read from lib/languages!
161 if 'wa' in languages:
162 languages.remove('wa')
164 out = open(output, 'w')
165 for src in input_files:
166 readingDescription = False
167 readingI18nPreamble = False
169 readingCiteFormats = False
177 for line in open(src).readlines():
179 res = ClassDescription.search(line)
181 string = res.group(2)
182 if not layouttranslations:
183 writeString(out, src, base, lineno + 1, string)
185 res = ClassCategory.search(line)
187 string = res.group(1)
188 if not layouttranslations:
189 writeString(out, src, base, lineno + 1, string)
191 if readingDescription:
192 res = DescEnd.search(line)
194 readingDescription = False
195 desc = " ".join(descLines)
196 if not layouttranslations:
197 writeString(out, src, base, lineno + 1, desc)
199 descLines.append(line[1:].strip())
201 res = DescBegin.search(line)
203 readingDescription = True
204 descStartLine = lineno
206 if readingI18nPreamble:
207 res = EndI18nPreamble.search(line)
209 readingI18nPreamble = False
211 res = I18nString.search(line)
213 string = res.group(1)
214 if layouttranslations:
217 writeString(out, src, base, lineno, string)
219 res = I18nPreamble.search(line)
221 readingI18nPreamble = True
223 res = NameRE.search(line)
225 string = res.group(1)
226 if not layouttranslations:
227 writeString(out, src, base, lineno + 1, string)
229 res = Style.search(line)
231 string = res.group(1)
232 string = string.replace('_', ' ')
233 # Style means something else inside a float definition
235 if not layouttranslations:
236 writeString(out, src, base, lineno, string)
238 res = LabelString.search(line)
240 string = res.group(1)
241 if not layouttranslations:
242 writeString(out, src, base, lineno, string)
244 res = GuiName.search(line)
246 string = res.group(1)
247 if layouttranslations:
248 # gui name must only be added for floats
252 writeString(out, src, base, lineno, string)
254 res = CategoryName.search(line)
256 string = res.group(1)
257 if not layouttranslations:
258 writeString(out, src, base, lineno, string)
260 res = ListName.search(line)
262 string = res.group(1)
263 if layouttranslations:
264 listname = string.strip('"')
266 writeString(out, src, base, lineno, string)
268 res = InsetLayout.search(line)
270 string = res.group(1)
271 string = string.replace('_', ' ')
272 #Flex:xxx is not used in translation
273 #if not layouttranslations:
274 # writeString(out, src, base, lineno, string)
275 m = FlexCheck.search(string)
277 if not layouttranslations:
278 writeString(out, src, base, lineno, m.group(1))
280 res = Category.search(line)
282 string = res.group(1)
283 if not layouttranslations:
284 writeString(out, src, base, lineno, string)
286 res = CounterFormat.search(line)
288 string = res.group(1)
289 if not layouttranslations:
290 writeString(out, src, base, lineno, string)
292 res = Float.search(line)
296 res = IsPredefined.search(line)
298 string = res.group(1).lower()
304 res = UsesFloatPkg.search(line)
306 string = res.group(1).lower()
312 res = CiteFormat.search(line)
314 readingCiteFormats = True
316 res = End.search(line)
318 # If a float is predefined by the package and it does not need
319 # the float package then it uses the standard babel translations.
320 # This is even true for MarginFigure, MarginTable (both from
321 # tufte-book.layout) and Planotable, Plate (both from aguplus.inc).
322 if layouttranslations and readingFloat and usesFloatPkg and not isPredefined:
324 keyset.add(floatname)
331 readingCiteFormats = False
334 if readingCiteFormats:
335 res = KeyVal.search(line)
338 if not layouttranslations:
339 writeString(out, src, base, lineno, val)
341 if layouttranslations:
342 # Extract translations of layout files
345 # Sort languages and key to minimize the diff between different runs
346 # with changed translations
353 ContextRe = re.compile(r'(.*)(\[\[.*\]\])')
355 print >> out, '''# This file has been automatically generated by po/lyx_pot.py.
356 # PLEASE MODIFY ONLY THE LAGUAGES HAVING NO .po FILE! If you want to regenerate
357 # this file from the translations, run `make ../lib/layouttranslations' in po.
358 # Python polib library is needed for building the output file.
360 # This file should remain fixed during minor LyX releases.
361 # For more comments see README.localization file.'''
362 for lang in languages:
363 print >> out, '\nTranslation %s' % lang
364 if lang in oldtrans.keys():
365 trans = oldtrans[lang]
368 if not lang in oldlanguages:
369 poname = os.path.join(base, 'po/' + lang + '.po')
370 po = polib.pofile(poname)
371 # Iterate through po entries and not keys for speed reasons.
372 # FIXME: The code is still too slow
374 if not entry.translated():
376 if entry.msgid in keys:
379 # some translators keep untranslated entries
383 if key in trans.keys():
384 val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
385 key = key.replace('\\', '\\\\').replace('"', '\\"')
386 print >> out, '\t"%s" "%s"' % \
387 (key.encode('utf-8'), val.encode('utf-8'))
388 # also print untranslated entries to help translators
389 elif not lang in oldlanguages:
390 key = key.replace('\\', '\\\\').replace('"', '\\"')
391 res = ContextRe.search(key)
396 print >> out, '\t"%s" "%s"' % \
397 (key.encode('utf-8'), val.encode('utf-8'))
403 def qt4_l10n(input_files, output, base):
404 '''Generate pot file from src/frontends/qt4/ui/*.ui'''
405 output = open(output, 'w')
406 pat = re.compile(r'\s*<string>(.*)</string>')
407 prop = re.compile(r'\s*<property.*name.*=.*shortcut')
408 for src in input_files:
411 for lineno, line in enumerate(input.readlines()):
412 # skip the line after <property name=shortcut>
419 # get lines that match <string>...</string>
421 (string,) = pat.match(line).groups()
422 string = string.replace('&', '&').replace('"', '"')
423 string = string.replace('<', '<').replace('>', '>')
424 string = string.replace('\\', '\\\\').replace('"', r'\"')
425 string = string.replace('
', r'\n')
426 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
427 (relativePath(src, base), lineno+1, string)
432 def languages_l10n(input_files, output, base):
433 '''Generate pot file from lib/languages'''
434 out = open(output, 'w')
435 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
437 for src in input_files:
441 for line in open(src).readlines():
443 res = GuiName.search(line)
445 string = res.group(1)
446 writeString(out, src, base, lineno, string)
452 def latexfonts_l10n(input_files, output, base):
453 '''Generate pot file from lib/latexfonts'''
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 external_l10n(input_files, output, base):
473 '''Generate pot file from lib/external_templates'''
474 output = open(output, 'w')
475 Template = re.compile(r'^Template\s+(.*)', re.IGNORECASE)
476 GuiName = re.compile(r'\s*GuiName\s+(.*)', re.IGNORECASE)
477 HelpTextStart = re.compile(r'\s*HelpText\s', re.IGNORECASE)
478 HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
479 HelpTextEnd = re.compile(r'\s*HelpTextEnd\s', re.IGNORECASE)
481 for src in input_files:
485 prev_help_string = ''
486 for lineno, line in enumerate(input.readlines()):
487 if Template.match(line):
488 (string,) = Template.match(line).groups()
489 elif GuiName.match(line):
490 (string,) = GuiName.match(line).groups()
492 if HelpTextEnd.match(line):
494 print >> output, '\nmsgstr ""\n'
497 prev_help_string = ''
498 elif HelpTextSection.match(line):
499 (help_string,) = HelpTextSection.match(line).groups()
500 help_string = help_string.replace('"', '')
501 if help_string != "" and prev_help_string == '':
502 print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
503 (relativePath(src, base), lineno+1, help_string)
505 elif help_string != "":
506 print >> output, '"%s\\n"' % help_string
507 prev_help_string = help_string
508 elif HelpTextStart.match(line):
510 prev_help_string = ''
513 string = string.replace('"', '')
514 if string != "" and not inHelp:
515 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
516 (relativePath(src, base), lineno+1, string)
521 def formats_l10n(input_files, output, base):
522 '''Generate pot file from configure.py'''
523 output = open(output, 'w')
524 GuiName = re.compile(r'.*\\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*', re.IGNORECASE)
525 GuiName2 = re.compile(r'.*\\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*', re.IGNORECASE)
526 input = open(input_files[0])
527 for lineno, line in enumerate(input.readlines()):
530 if GuiName.match(line):
531 label = GuiName.match(line).group(1)
532 shortcut = GuiName.match(line).group(2).replace('"', '')
533 elif GuiName2.match(line):
534 label = GuiName2.match(line).group(1)
535 shortcut = GuiName2.match(line).group(2).replace('"', '')
538 label = label.replace('\\', '\\\\').replace('"', '')
540 labelsc = label + "|" + shortcut
542 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
543 (relativePath(input_files[0], base), lineno+1, label)
545 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
546 (relativePath(input_files[0], base), lineno+1, labelsc)
551 def encodings_l10n(input_files, output, base):
552 '''Generate pot file from lib/encodings'''
553 output = open(output, 'w')
554 # assuming only one encodings file
555 # Encoding utf8 utf8 "Unicode (utf8)" UTF-8 variable inputenc
556 reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
557 input = open(input_files[0])
558 for lineno, line in enumerate(input.readlines()):
559 if not line.startswith('Encoding'):
562 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
563 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
565 print "Error: Unable to handle line:"
567 # No need to abort if the parsing fails
575 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
579 path to the top source directory. default to '.'
581 output pot file, default to './lyx.pot'
583 filename that contains a list of input files in each line
586 layouts: lib/layouts/*
587 layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
589 languages: file lib/languages
590 latexfonts: file lib/latexfonts
591 encodings: file lib/encodings
592 external: external templates file
593 formats: formats predefined in lib/configure.py
596 if __name__ == '__main__':
602 optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
603 ['help', 'type=', 'output=', 'base=', 'src_file='])
604 for (opt, value) in optlist:
605 if opt in ['-h', '--help']:
608 elif opt in ['-o', '--output']:
610 elif opt in ['-b', '--base']:
612 elif opt in ['-t', '--type']:
614 elif opt in ['-s', '--src_file']:
615 input_files = [f.strip() for f in open(value)]
617 if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'latexfonts', 'encodings', 'external', 'formats'] or output is None:
618 print 'Wrong input type or output filename.'
623 if input_type == 'ui':
624 ui_l10n(input_files, output, base)
625 elif input_type == 'latexfonts':
626 latexfonts_l10n(input_files, output, base)
627 elif input_type == 'layouts':
628 layouts_l10n(input_files, output, base, False)
629 elif input_type == 'layouttranslations':
630 layouts_l10n(input_files, output, base, True)
631 elif input_type == 'qt4':
632 qt4_l10n(input_files, output, base)
633 elif input_type == 'external':
634 external_l10n(input_files, output, base)
635 elif input_type == 'formats':
636 formats_l10n(input_files, output, base)
637 elif input_type == 'encodings':
638 encodings_l10n(input_files, output, base)
640 languages_l10n(input_files, output, base)