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+"([^"]*)"')
48 Popupmenu = re.compile(r'^[^#]*PopupMenu\s+"[^"]+"\s+"([^"]*)"')
49 IconPalette = re.compile(r'^[^#]*IconPalette\s+"[^"]+"\s+"([^"]*)"')
50 Toolbar = re.compile(r'^[^#]*Toolbar\s+"[^"]+"\s+"([^"]*)"')
51 Item = re.compile(r'[^#]*Item\s+"([^"]*)"')
52 TableInsert = re.compile(r'[^#]*TableInsert\s+"([^"]*)"')
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'^Style\s+(.*)', re.IGNORECASE)
82 # include ???LabelString???, but exclude comment lines
83 LabelString = re.compile(r'^[^#]*LabelString\S*\s+(.*)')
84 GuiName = re.compile(r'\s*GuiName\s+(.*)')
85 ListName = re.compile(r'\s*ListName\s+(.*)')
86 CategoryName = re.compile(r'\s*Category\s+(.*)')
87 NameRE = re.compile(r'DeclareLyXModule.*{(.*)}')
88 InsetLayout = re.compile(r'^InsetLayout\s+\"?(.*)\"?')
89 FlexCheck = re.compile(r'^Flex:(.*)')
90 DescBegin = re.compile(r'#+\s*DescriptionBegin\s*$')
91 DescEnd = re.compile(r'#+\s*DescriptionEnd\s*$')
92 Category = re.compile(r'#Category: (.*)$')
93 I18nPreamble = re.compile(r'\s*(Lang)|(Babel)Preamble\s*$')
94 EndI18nPreamble = re.compile(r'\s*End(Lang)|(Babel)Preamble\s*$')
95 I18nString = re.compile(r'_\(([^\)]+)\)')
96 CounterFormat = re.compile(r'\s*PrettyFormat\s+"?(.*)"?')
97 CiteFormat = re.compile(r'\s*CiteFormat')
98 KeyVal = re.compile(r'^\s*_\w+\s+(.*)$')
99 Float = re.compile(r'\s*Float')
100 End = re.compile(r'\s*End')
101 Comment = re.compile(r'\s*#')
102 Translation = re.compile(r'\s*Translation\s+(.*)\s*$')
103 KeyValPair = re.compile(r'\s*"(.*)"\s+"(.*)"')
109 if layouttranslations:
110 linguas_file = os.path.join(base, 'po/LINGUAS')
111 for line in open(linguas_file).readlines():
112 if Comment.search(line) == None:
113 languages.extend(line.split())
115 # read old translations if available
119 for line in input.readlines():
120 res = Comment.search(line)
123 if line.strip() == '':
125 res = Translation.search(line)
128 if lang not in languages:
129 oldlanguages.append(lang)
130 languages.append(lang)
131 oldtrans[lang] = dict()
133 res = End.search(line)
137 res = KeyValPair.search(line)
138 if res and lang != '':
139 key = res.group(1).decode('utf-8')
140 val = res.group(2).decode('utf-8')
141 key = key.replace('\\"', '"').replace('\\\\', '\\')
142 val = val.replace('\\"', '"').replace('\\\\', '\\')
143 oldtrans[lang][key] = val
146 print "Error: Unable to handle line:"
149 print "Warning: Unable to open %s for reading." % output
150 print " Old translations will be lost."
152 # walon is not a known document language
153 # FIXME: Do not hardcode, read from lib/languages!
154 if 'wa' in languages:
155 languages.remove('wa')
157 out = open(output, 'w')
158 for src in input_files:
159 readingDescription = False
160 readingI18nPreamble = False
162 readingCiteFormats = False
166 for line in open(src).readlines():
168 if readingDescription:
169 res = DescEnd.search(line)
171 readingDescription = False
172 desc = " ".join(descLines)
173 if not layouttranslations:
174 writeString(out, src, base, lineno + 1, desc)
176 descLines.append(line[1:].strip())
178 res = DescBegin.search(line)
180 readingDescription = True
181 descStartLine = lineno
183 if readingI18nPreamble:
184 res = EndI18nPreamble.search(line)
186 readingI18nPreamble = False
188 res = I18nString.search(line)
190 string = res.group(1)
191 if layouttranslations:
194 writeString(out, src, base, lineno, string)
196 res = I18nPreamble.search(line)
198 readingI18nPreamble = True
200 res = NameRE.search(line)
202 string = res.group(1)
203 if not layouttranslations:
204 writeString(out, src, base, lineno + 1, string)
206 res = Style.search(line)
208 string = res.group(1)
209 string = string.replace('_', ' ')
210 if not layouttranslations:
211 writeString(out, src, base, lineno, string)
213 res = LabelString.search(line)
215 string = res.group(1)
216 if not layouttranslations:
217 writeString(out, src, base, lineno, string)
219 res = GuiName.search(line)
221 string = res.group(1)
222 if layouttranslations:
223 # gui name must only be added for floats
227 writeString(out, src, base, lineno, string)
229 res = CategoryName.search(line)
231 string = res.group(1)
232 if not layouttranslations:
233 writeString(out, src, base, lineno, string)
235 res = ListName.search(line)
237 string = res.group(1)
238 if layouttranslations:
239 keyset.add(string.strip('"'))
241 writeString(out, src, base, lineno, string)
243 res = InsetLayout.search(line)
245 string = res.group(1)
246 string = string.replace('_', ' ')
247 #Flex:xxx is not used in translation
248 #if not layouttranslations:
249 # writeString(out, src, base, lineno, string)
250 m = FlexCheck.search(string)
252 if not layouttranslations:
253 writeString(out, src, base, lineno, m.group(1))
255 res = Category.search(line)
257 string = res.group(1)
258 if not layouttranslations:
259 writeString(out, src, base, lineno, string)
261 res = CounterFormat.search(line)
263 string = res.group(1)
264 if not layouttranslations:
265 writeString(out, src, base, lineno, string)
267 res = Float.search(line)
271 res = CiteFormat.search(line)
273 readingCiteFormats = True
274 res = End.search(line)
276 readingCiteFormats = False
278 if readingCiteFormats:
279 res = KeyVal.search(line)
282 if not layouttranslations:
283 writeString(out, src, base, lineno, val)
285 if layouttranslations:
286 # Extract translations of layout files
289 # Sort languages and key to minimize the diff between different runs
290 # with changed translations
297 print >> out, '''# This file has been automatically generated by po/lyx_pot.py.
298 # PLEASE MODIFY ONLY THE LAGUAGES HAVING NO .po FILE! If you want to regenerate
299 # this file from the translations, run `make ../lib/layouttranslations' in po.
300 # Python polib library is needed for building the output file.
302 # This file should remain fixed during minor LyX releases.
303 # For more comments see README.localization file.'''
304 for lang in languages:
305 print >> out, '\nTranslation %s' % lang
306 if lang in oldtrans.keys():
307 trans = oldtrans[lang]
310 if not lang in oldlanguages:
311 poname = os.path.join(base, 'po/' + lang + '.po')
312 po = polib.pofile(poname)
313 # Iterate through po entries and not keys for speed reasons.
314 # FIXME: The code is still too slow
316 if not entry.translated():
318 if entry.msgid in keys:
321 # some translators keep untranslated entries
325 if key in trans.keys():
326 val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
327 key = key.replace('\\', '\\\\').replace('"', '\\"')
328 print >> out, '\t"%s" "%s"' % \
329 (key.encode('utf-8'), val.encode('utf-8'))
330 # also print untranslated entries to help translators
331 elif not lang in oldlanguages:
332 key = key.replace('\\', '\\\\').replace('"', '\\"')
333 print >> out, '\t"%s" "%s"' % \
334 (key.encode('utf-8'), key.encode('utf-8'))
340 def qt4_l10n(input_files, output, base):
341 '''Generate pot file from src/frontends/qt4/ui/*.ui'''
342 output = open(output, 'w')
343 pat = re.compile(r'\s*<string>(.*)</string>')
344 prop = re.compile(r'\s*<property.*name.*=.*shortcut')
345 for src in input_files:
348 for lineno, line in enumerate(input.readlines()):
349 # skip the line after <property name=shortcut>
356 # get lines that match <string>...</string>
358 (string,) = pat.match(line).groups()
359 string = string.replace('&', '&').replace('"', '"')
360 string = string.replace('<', '<').replace('>', '>')
361 string = string.replace('\\', '\\\\').replace('"', r'\"')
362 string = string.replace('
', r'\n')
363 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
364 (relativePath(src, base), lineno+1, string)
369 def languages_l10n(input_files, output, base):
370 '''Generate pot file from lib/languages'''
371 out = open(output, 'w')
372 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)')
374 for src in input_files:
378 for line in open(src).readlines():
380 res = GuiName.search(line)
382 string = res.group(1)
383 writeString(out, src, base, lineno, string)
389 def external_l10n(input_files, output, base):
390 '''Generate pot file from lib/external_templates'''
391 output = open(output, 'w')
392 Template = re.compile(r'^Template\s+(.*)')
393 GuiName = re.compile(r'\s*GuiName\s+(.*)')
394 HelpTextStart = re.compile(r'\s*HelpText\s')
395 HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
396 HelpTextEnd = re.compile(r'\s*HelpTextEnd\s')
398 for src in input_files:
402 prev_help_string = ''
403 for lineno, line in enumerate(input.readlines()):
404 if Template.match(line):
405 (string,) = Template.match(line).groups()
406 elif GuiName.match(line):
407 (string,) = GuiName.match(line).groups()
409 if HelpTextEnd.match(line):
411 print >> output, '\nmsgstr ""\n'
414 prev_help_string = ''
415 elif HelpTextSection.match(line):
416 (help_string,) = HelpTextSection.match(line).groups()
417 help_string = help_string.replace('"', '')
418 if help_string != "" and prev_help_string == '':
419 print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
420 (relativePath(src, base), lineno+1, help_string)
422 elif help_string != "":
423 print >> output, '"%s\\n"' % help_string
424 prev_help_string = help_string
425 elif HelpTextStart.match(line):
427 prev_help_string = ''
430 string = string.replace('"', '')
431 if string != "" and not inHelp:
432 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
433 (relativePath(src, base), lineno+1, string)
438 def formats_l10n(input_files, output, base):
439 '''Generate pot file from configure.py'''
440 output = open(output, 'w')
441 GuiName = re.compile(r'.*\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*')
442 GuiName2 = re.compile(r'.*\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*')
443 input = open(input_files[0])
444 for lineno, line in enumerate(input.readlines()):
447 if GuiName.match(line):
448 label = GuiName.match(line).group(1)
449 shortcut = GuiName.match(line).group(2).replace('"', '')
450 elif GuiName2.match(line):
451 label = GuiName2.match(line).group(1)
452 shortcut = GuiName2.match(line).group(2).replace('"', '')
455 label = label.replace('\\', '\\\\').replace('"', '')
457 labelsc = label + "|" + shortcut
459 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
460 (relativePath(input_files[0], base), lineno+1, label)
462 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
463 (relativePath(input_files[0], base), lineno+1, labelsc)
468 def encodings_l10n(input_files, output, base):
469 '''Generate pot file from lib/encodings'''
470 output = open(output, 'w')
471 # assuming only one encodings file
472 # Encoding utf8 utf8 "Unicode (utf8)" UTF-8 variable inputenc
473 reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
474 input = open(input_files[0])
475 for lineno, line in enumerate(input.readlines()):
476 if not line.startswith('Encoding'):
479 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
480 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
482 print "Error: Unable to handle line:"
484 # No need to abort if the parsing fails
492 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
496 path to the top source directory. default to '.'
498 output pot file, default to './lyx.pot'
500 filename that contains a list of input files in each line
503 layouts: lib/layouts/*
504 layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
506 languages: file lib/languages
507 encodings: file lib/encodings
508 external: external templates file
509 formats: formats predefined in lib/configure.py
512 if __name__ == '__main__':
518 optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
519 ['help', 'type=', 'output=', 'base=', 'src_file='])
520 for (opt, value) in optlist:
521 if opt in ['-h', '--help']:
524 elif opt in ['-o', '--output']:
526 elif opt in ['-b', '--base']:
528 elif opt in ['-t', '--type']:
530 elif opt in ['-s', '--src_file']:
531 input_files = [f.strip() for f in open(value)]
533 if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'encodings', 'external', 'formats'] or output is None:
534 print 'Wrong input type or output filename.'
539 if input_type == 'ui':
540 ui_l10n(input_files, output, base)
541 elif input_type == 'layouts':
542 layouts_l10n(input_files, output, base, False)
543 elif input_type == 'layouttranslations':
544 layouts_l10n(input_files, output, base, True)
545 elif input_type == 'qt4':
546 qt4_l10n(input_files, output, base)
547 elif input_type == 'external':
548 external_l10n(input_files, output, base)
549 elif input_type == 'formats':
550 formats_l10n(input_files, output, base)
551 elif input_type == 'encodings':
552 encodings_l10n(input_files, output, base)
554 languages_l10n(input_files, output, base)