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 Style = re.compile(r'^\s*Style\s+(.*)\s*$', re.IGNORECASE)
82 # match LabelString, EndLabelString, LabelStringAppendix and maybe others but no comments
83 LabelString = re.compile(r'^[^#]*LabelString\S*\s+(.*)\s*$', re.IGNORECASE)
84 GuiName = re.compile(r'^\s*GuiName\s+(.*)\s*$', re.IGNORECASE)
85 ListName = re.compile(r'^\s*ListName\s+(.*)\s*$', re.IGNORECASE)
86 CategoryName = re.compile(r'^\s*Category\s+(.*)\s*$', re.IGNORECASE)
87 NameRE = re.compile(r'^\s*#\s*\\DeclareLyXModule.*{(.*)}$', re.IGNORECASE)
88 InsetLayout = re.compile(r'^InsetLayout\s+\"?(.*)\"?\s*$', re.IGNORECASE)
89 FlexCheck = re.compile(r'^Flex:(.*)', re.IGNORECASE)
90 DescBegin = re.compile(r'^\s*#DescriptionBegin\s*$', re.IGNORECASE)
91 DescEnd = re.compile(r'^\s*#\s*DescriptionEnd\s*$', re.IGNORECASE)
92 Category = re.compile(r'^\s*#\s*Category:\s+(.*)\s*$', re.IGNORECASE)
93 I18nPreamble = re.compile(r'^\s*((Lang)|(Babel))Preamble\s*$', re.IGNORECASE)
94 EndI18nPreamble = re.compile(r'^\s*End((Lang)|(Babel))Preamble\s*$', re.IGNORECASE)
95 I18nString = re.compile(r'_\(([^\)]+)\)')
96 CounterFormat = re.compile(r'^\s*PrettyFormat\s+"?(.*)"?\s*$', re.IGNORECASE)
97 CiteFormat = re.compile(r'^\s*CiteFormat', re.IGNORECASE)
98 KeyVal = re.compile(r'^\s*_\w+\s+(.*)\s*$')
99 Float = re.compile(r'^\s*Float\s*$', re.IGNORECASE)
100 UsesFloatPkg = re.compile(r'^\s*UsesFloatPkg\s+(.*)\s*$', re.IGNORECASE)
101 IsPredefined = re.compile(r'^\s*IsPredefined\s+(.*)\s*$', re.IGNORECASE)
102 End = re.compile(r'^\s*End', re.IGNORECASE)
103 Comment = re.compile(r'^(.*)#')
104 Translation = re.compile(r'^\s*Translation\s+(.*)\s*$', re.IGNORECASE)
105 KeyValPair = re.compile(r'\s*"(.*)"\s+"(.*)"')
111 if layouttranslations:
112 linguas_file = os.path.join(base, 'po/LINGUAS')
113 for line in open(linguas_file).readlines():
114 res = Comment.search(line)
117 if line.strip() != '':
118 languages.extend(line.split())
120 # read old translations if available
124 for line in input.readlines():
125 res = Comment.search(line)
128 if line.strip() == '':
130 res = Translation.search(line)
133 if lang not in languages:
134 oldlanguages.append(lang)
135 languages.append(lang)
136 oldtrans[lang] = dict()
138 res = End.search(line)
142 res = KeyValPair.search(line)
143 if res and lang != '':
144 key = res.group(1).decode('utf-8')
145 val = res.group(2).decode('utf-8')
146 key = key.replace('\\"', '"').replace('\\\\', '\\')
147 val = val.replace('\\"', '"').replace('\\\\', '\\')
148 oldtrans[lang][key] = val
151 print "Error: Unable to handle line:"
154 print "Warning: Unable to open %s for reading." % output
155 print " Old translations will be lost."
157 # walon is not a known document language
158 # FIXME: Do not hardcode, read from lib/languages!
159 if 'wa' in languages:
160 languages.remove('wa')
162 out = open(output, 'w')
163 for src in input_files:
164 readingDescription = False
165 readingI18nPreamble = False
167 readingCiteFormats = False
175 for line in open(src).readlines():
177 if readingDescription:
178 res = DescEnd.search(line)
180 readingDescription = False
181 desc = " ".join(descLines)
182 if not layouttranslations:
183 writeString(out, src, base, lineno + 1, desc)
185 descLines.append(line[1:].strip())
187 res = DescBegin.search(line)
189 readingDescription = True
190 descStartLine = lineno
192 if readingI18nPreamble:
193 res = EndI18nPreamble.search(line)
195 readingI18nPreamble = False
197 res = I18nString.search(line)
199 string = res.group(1)
200 if layouttranslations:
203 writeString(out, src, base, lineno, string)
205 res = I18nPreamble.search(line)
207 readingI18nPreamble = True
209 res = NameRE.search(line)
211 string = res.group(1)
212 if not layouttranslations:
213 writeString(out, src, base, lineno + 1, string)
215 res = Style.search(line)
217 string = res.group(1)
218 string = string.replace('_', ' ')
219 # Style means something else inside a float definition
221 if not layouttranslations:
222 writeString(out, src, base, lineno, string)
224 res = LabelString.search(line)
226 string = res.group(1)
227 if not layouttranslations:
228 writeString(out, src, base, lineno, string)
230 res = GuiName.search(line)
232 string = res.group(1)
233 if layouttranslations:
234 # gui name must only be added for floats
238 writeString(out, src, base, lineno, string)
240 res = CategoryName.search(line)
242 string = res.group(1)
243 if not layouttranslations:
244 writeString(out, src, base, lineno, string)
246 res = ListName.search(line)
248 string = res.group(1)
249 if layouttranslations:
250 listname = string.strip('"')
252 writeString(out, src, base, lineno, string)
254 res = InsetLayout.search(line)
256 string = res.group(1)
257 string = string.replace('_', ' ')
258 #Flex:xxx is not used in translation
259 #if not layouttranslations:
260 # writeString(out, src, base, lineno, string)
261 m = FlexCheck.search(string)
263 if not layouttranslations:
264 writeString(out, src, base, lineno, m.group(1))
266 res = Category.search(line)
268 string = res.group(1)
269 if not layouttranslations:
270 writeString(out, src, base, lineno, string)
272 res = CounterFormat.search(line)
274 string = res.group(1)
275 if not layouttranslations:
276 writeString(out, src, base, lineno, string)
278 res = Float.search(line)
282 res = IsPredefined.search(line)
284 string = res.group(1).lower()
290 res = UsesFloatPkg.search(line)
292 string = res.group(1).lower()
298 res = CiteFormat.search(line)
300 readingCiteFormats = True
302 res = End.search(line)
304 # If a float is predefined by the package and it does not need
305 # the float package then it uses the standard babel translations.
306 # This is even true for MarginFigure, MarginTable (both from
307 # tufte-book.layout) and Planotable, Plate (both from aguplus.inc).
308 if layouttranslations and readingFloat and usesFloatPkg and not isPredefined:
310 keyset.add(floatname)
317 readingCiteFormats = False
320 if readingCiteFormats:
321 res = KeyVal.search(line)
324 if not layouttranslations:
325 writeString(out, src, base, lineno, val)
327 if layouttranslations:
328 # Extract translations of layout files
331 # Sort languages and key to minimize the diff between different runs
332 # with changed translations
339 print >> out, '''# This file has been automatically generated by po/lyx_pot.py.
340 # PLEASE MODIFY ONLY THE LAGUAGES HAVING NO .po FILE! If you want to regenerate
341 # this file from the translations, run `make ../lib/layouttranslations' in po.
342 # Python polib library is needed for building the output file.
344 # This file should remain fixed during minor LyX releases.
345 # For more comments see README.localization file.'''
346 for lang in languages:
347 print >> out, '\nTranslation %s' % lang
348 if lang in oldtrans.keys():
349 trans = oldtrans[lang]
352 if not lang in oldlanguages:
353 poname = os.path.join(base, 'po/' + lang + '.po')
354 po = polib.pofile(poname)
355 # Iterate through po entries and not keys for speed reasons.
356 # FIXME: The code is still too slow
358 if not entry.translated():
360 if entry.msgid in keys:
363 # some translators keep untranslated entries
367 if key in trans.keys():
368 val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
369 key = key.replace('\\', '\\\\').replace('"', '\\"')
370 print >> out, '\t"%s" "%s"' % \
371 (key.encode('utf-8'), val.encode('utf-8'))
372 # also print untranslated entries to help translators
373 elif not lang in oldlanguages:
374 key = key.replace('\\', '\\\\').replace('"', '\\"')
375 print >> out, '\t"%s" "%s"' % \
376 (key.encode('utf-8'), key.encode('utf-8'))
382 def qt4_l10n(input_files, output, base):
383 '''Generate pot file from src/frontends/qt4/ui/*.ui'''
384 output = open(output, 'w')
385 pat = re.compile(r'\s*<string>(.*)</string>')
386 prop = re.compile(r'\s*<property.*name.*=.*shortcut')
387 for src in input_files:
390 for lineno, line in enumerate(input.readlines()):
391 # skip the line after <property name=shortcut>
398 # get lines that match <string>...</string>
400 (string,) = pat.match(line).groups()
401 string = string.replace('&', '&').replace('"', '"')
402 string = string.replace('<', '<').replace('>', '>')
403 string = string.replace('\\', '\\\\').replace('"', r'\"')
404 string = string.replace('
', r'\n')
405 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
406 (relativePath(src, base), lineno+1, string)
411 def languages_l10n(input_files, output, base):
412 '''Generate pot file from lib/languages'''
413 out = open(output, 'w')
414 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
416 for src in input_files:
420 for line in open(src).readlines():
422 res = GuiName.search(line)
424 string = res.group(1)
425 writeString(out, src, base, lineno, string)
431 def external_l10n(input_files, output, base):
432 '''Generate pot file from lib/external_templates'''
433 output = open(output, 'w')
434 Template = re.compile(r'^Template\s+(.*)', re.IGNORECASE)
435 GuiName = re.compile(r'\s*GuiName\s+(.*)', re.IGNORECASE)
436 HelpTextStart = re.compile(r'\s*HelpText\s', re.IGNORECASE)
437 HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
438 HelpTextEnd = re.compile(r'\s*HelpTextEnd\s', re.IGNORECASE)
440 for src in input_files:
444 prev_help_string = ''
445 for lineno, line in enumerate(input.readlines()):
446 if Template.match(line):
447 (string,) = Template.match(line).groups()
448 elif GuiName.match(line):
449 (string,) = GuiName.match(line).groups()
451 if HelpTextEnd.match(line):
453 print >> output, '\nmsgstr ""\n'
456 prev_help_string = ''
457 elif HelpTextSection.match(line):
458 (help_string,) = HelpTextSection.match(line).groups()
459 help_string = help_string.replace('"', '')
460 if help_string != "" and prev_help_string == '':
461 print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
462 (relativePath(src, base), lineno+1, help_string)
464 elif help_string != "":
465 print >> output, '"%s\\n"' % help_string
466 prev_help_string = help_string
467 elif HelpTextStart.match(line):
469 prev_help_string = ''
472 string = string.replace('"', '')
473 if string != "" and not inHelp:
474 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
475 (relativePath(src, base), lineno+1, string)
480 def formats_l10n(input_files, output, base):
481 '''Generate pot file from configure.py'''
482 output = open(output, 'w')
483 GuiName = re.compile(r'.*\\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*', re.IGNORECASE)
484 GuiName2 = re.compile(r'.*\\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*', re.IGNORECASE)
485 input = open(input_files[0])
486 for lineno, line in enumerate(input.readlines()):
489 if GuiName.match(line):
490 label = GuiName.match(line).group(1)
491 shortcut = GuiName.match(line).group(2).replace('"', '')
492 elif GuiName2.match(line):
493 label = GuiName2.match(line).group(1)
494 shortcut = GuiName2.match(line).group(2).replace('"', '')
497 label = label.replace('\\', '\\\\').replace('"', '')
499 labelsc = label + "|" + shortcut
501 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
502 (relativePath(input_files[0], base), lineno+1, label)
504 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
505 (relativePath(input_files[0], base), lineno+1, labelsc)
510 def encodings_l10n(input_files, output, base):
511 '''Generate pot file from lib/encodings'''
512 output = open(output, 'w')
513 # assuming only one encodings file
514 # Encoding utf8 utf8 "Unicode (utf8)" UTF-8 variable inputenc
515 reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
516 input = open(input_files[0])
517 for lineno, line in enumerate(input.readlines()):
518 if not line.startswith('Encoding'):
521 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
522 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
524 print "Error: Unable to handle line:"
526 # No need to abort if the parsing fails
534 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
538 path to the top source directory. default to '.'
540 output pot file, default to './lyx.pot'
542 filename that contains a list of input files in each line
545 layouts: lib/layouts/*
546 layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
548 languages: file lib/languages
549 encodings: file lib/encodings
550 external: external templates file
551 formats: formats predefined in lib/configure.py
554 if __name__ == '__main__':
560 optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
561 ['help', 'type=', 'output=', 'base=', 'src_file='])
562 for (opt, value) in optlist:
563 if opt in ['-h', '--help']:
566 elif opt in ['-o', '--output']:
568 elif opt in ['-b', '--base']:
570 elif opt in ['-t', '--type']:
572 elif opt in ['-s', '--src_file']:
573 input_files = [f.strip() for f in open(value)]
575 if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'encodings', 'external', 'formats'] or output is None:
576 print 'Wrong input type or output filename.'
581 if input_type == 'ui':
582 ui_l10n(input_files, output, base)
583 elif input_type == 'layouts':
584 layouts_l10n(input_files, output, base, False)
585 elif input_type == 'layouttranslations':
586 layouts_l10n(input_files, output, base, True)
587 elif input_type == 'qt4':
588 qt4_l10n(input_files, output, base)
589 elif input_type == 'external':
590 external_l10n(input_files, output, base)
591 elif input_type == 'formats':
592 formats_l10n(input_files, output, base)
593 elif input_type == 'encodings':
594 encodings_l10n(input_files, output, base)
596 languages_l10n(input_files, output, base)