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:"
151 # walon is not a known document language
152 # FIXME: Do not hardcode, read from lib/languages!
153 if 'wa' in languages:
154 languages.remove('wa')
156 out = open(output, 'w')
157 for src in input_files:
158 readingDescription = False
159 readingI18nPreamble = False
161 readingCiteFormats = False
165 for line in open(src).readlines():
167 if readingDescription:
168 res = DescEnd.search(line)
170 readingDescription = False
171 desc = " ".join(descLines)
172 if not layouttranslations:
173 writeString(out, src, base, lineno + 1, desc)
175 descLines.append(line[1:].strip())
177 res = DescBegin.search(line)
179 readingDescription = True
180 descStartLine = lineno
182 if readingI18nPreamble:
183 res = EndI18nPreamble.search(line)
185 readingI18nPreamble = False
187 res = I18nString.search(line)
189 string = res.group(1)
190 if layouttranslations:
193 writeString(out, src, base, lineno, string)
195 res = I18nPreamble.search(line)
197 readingI18nPreamble = True
199 res = NameRE.search(line)
201 string = res.group(1)
202 if not layouttranslations:
203 writeString(out, src, base, lineno + 1, string)
205 res = Style.search(line)
207 string = res.group(1)
208 string = string.replace('_', ' ')
209 if not layouttranslations:
210 writeString(out, src, base, lineno, string)
212 res = LabelString.search(line)
214 string = res.group(1)
215 if not layouttranslations:
216 writeString(out, src, base, lineno, string)
218 res = GuiName.search(line)
220 string = res.group(1)
221 if layouttranslations:
222 # gui name must only be added for floats
226 writeString(out, src, base, lineno, string)
228 res = CategoryName.search(line)
230 string = res.group(1)
231 if not layouttranslations:
232 writeString(out, src, base, lineno, string)
234 res = ListName.search(line)
236 string = res.group(1)
237 if layouttranslations:
238 keyset.add(string.strip('"'))
240 writeString(out, src, base, lineno, string)
242 res = InsetLayout.search(line)
244 string = res.group(1)
245 string = string.replace('_', ' ')
246 #Flex:xxx is not used in translation
247 #if not layouttranslations:
248 # writeString(out, src, base, lineno, string)
249 m = FlexCheck.search(string)
251 if not layouttranslations:
252 writeString(out, src, base, lineno, m.group(1))
254 res = Category.search(line)
256 string = res.group(1)
257 if not layouttranslations:
258 writeString(out, src, base, lineno, string)
260 res = CounterFormat.search(line)
262 string = res.group(1)
263 if not layouttranslations:
264 writeString(out, src, base, lineno, string)
266 res = Float.search(line)
270 res = CiteFormat.search(line)
272 readingCiteFormats = True
273 res = End.search(line)
275 readingCiteFormats = False
277 if readingCiteFormats:
278 res = KeyVal.search(line)
281 if not layouttranslations:
282 writeString(out, src, base, lineno, val)
284 if layouttranslations:
285 # Extract translations of layout files
288 # Sort languages and key to minimize the diff between different runs
289 # with changed translations
296 print >> out, '''# This file has been automatically generated by po/lyx_pot.py.
297 # PLEASE MODIFY ONLY THE LAGUAGES HAVING NO .po FILE! If you want to regenerate
298 # this file from the translations, run `make ../lib/layouttranslations' in po.'''
299 for lang in languages:
300 print >> out, '\nTranslation %s' % lang
301 if lang in oldtrans.keys():
302 trans = oldtrans[lang]
305 if not lang in oldlanguages:
306 poname = os.path.join(base, 'po/' + lang + '.po')
307 po = polib.pofile(poname)
308 # Iterate through po entries and not keys for speed reasons.
309 # FIXME: The code is still too slow
311 if not entry.translated():
313 if entry.msgid in keys:
316 # some translators keep untranslated entries
320 if key in trans.keys():
321 val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
322 key = key.replace('\\', '\\\\').replace('"', '\\"')
323 print >> out, '\t"%s" "%s"' % \
324 (key.encode('utf-8'), val.encode('utf-8'))
325 # to print untranslated entries, uncomment the following lines
327 # key = key.replace('\\', '\\\\').replace('"', '\\"')
328 # print >> out, '\t"%s" "%s"' % \
329 # (key.encode('utf-8'), key.encode('utf-8'))
335 def qt4_l10n(input_files, output, base):
336 '''Generate pot file from src/frontends/qt4/ui/*.ui'''
337 output = open(output, 'w')
338 pat = re.compile(r'\s*<string>(.*)</string>')
339 prop = re.compile(r'\s*<property.*name.*=.*shortcut')
340 for src in input_files:
343 for lineno, line in enumerate(input.readlines()):
344 # skip the line after <property name=shortcut>
351 # get lines that match <string>...</string>
353 (string,) = pat.match(line).groups()
354 string = string.replace('&', '&').replace('"', '"')
355 string = string.replace('<', '<').replace('>', '>')
356 string = string.replace('\\', '\\\\').replace('"', r'\"')
357 string = string.replace('
', r'\n')
358 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
359 (relativePath(src, base), lineno+1, string)
364 def languages_l10n(input_files, output, base):
365 '''Generate pot file from lib/languages'''
366 out = open(output, 'w')
367 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)')
369 for src in input_files:
373 for line in open(src).readlines():
375 res = GuiName.search(line)
377 string = res.group(1)
378 writeString(out, src, base, lineno, string)
384 def external_l10n(input_files, output, base):
385 '''Generate pot file from lib/external_templates'''
386 output = open(output, 'w')
387 Template = re.compile(r'^Template\s+(.*)')
388 GuiName = re.compile(r'\s*GuiName\s+(.*)')
389 HelpTextStart = re.compile(r'\s*HelpText\s')
390 HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
391 HelpTextEnd = re.compile(r'\s*HelpTextEnd\s')
393 for src in input_files:
397 prev_help_string = ''
398 for lineno, line in enumerate(input.readlines()):
399 if Template.match(line):
400 (string,) = Template.match(line).groups()
401 elif GuiName.match(line):
402 (string,) = GuiName.match(line).groups()
404 if HelpTextEnd.match(line):
406 print >> output, '\nmsgstr ""\n'
409 prev_help_string = ''
410 elif HelpTextSection.match(line):
411 (help_string,) = HelpTextSection.match(line).groups()
412 help_string = help_string.replace('"', '')
413 if help_string != "" and prev_help_string == '':
414 print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
415 (relativePath(src, base), lineno+1, help_string)
417 elif help_string != "":
418 print >> output, '"%s\\n"' % help_string
419 prev_help_string = help_string
420 elif HelpTextStart.match(line):
422 prev_help_string = ''
425 string = string.replace('"', '')
426 if string != "" and not inHelp:
427 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
428 (relativePath(src, base), lineno+1, string)
433 def formats_l10n(input_files, output, base):
434 '''Generate pot file from configure.py'''
435 output = open(output, 'w')
436 GuiName = re.compile(r'.*\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*')
437 GuiName2 = re.compile(r'.*\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*')
438 input = open(input_files[0])
439 for lineno, line in enumerate(input.readlines()):
442 if GuiName.match(line):
443 label = GuiName.match(line).group(1)
444 shortcut = GuiName.match(line).group(2).replace('"', '')
445 elif GuiName2.match(line):
446 label = GuiName2.match(line).group(1)
447 shortcut = GuiName2.match(line).group(2).replace('"', '')
450 label = label.replace('\\', '\\\\').replace('"', '')
452 labelsc = label + "|" + shortcut
454 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
455 (relativePath(input_files[0], base), lineno+1, label)
457 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
458 (relativePath(input_files[0], base), lineno+1, labelsc)
463 def encodings_l10n(input_files, output, base):
464 '''Generate pot file from lib/encodings'''
465 output = open(output, 'w')
466 # assuming only one encodings file
467 # Encoding utf8 utf8 "Unicode (utf8)" UTF-8 variable inputenc
468 reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
469 input = open(input_files[0])
470 for lineno, line in enumerate(input.readlines()):
471 if not line.startswith('Encoding'):
474 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
475 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
477 print "Error: Unable to handle line:"
479 # No need to abort if the parsing fails
487 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
491 path to the top source directory. default to '.'
493 output pot file, default to './lyx.pot'
495 filename that contains a list of input files in each line
498 layouts: lib/layouts/*
499 layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
501 languages: file lib/languages
502 encodings: file lib/encodings
503 external: external templates file
504 formats: formats predefined in lib/configure.py
507 if __name__ == '__main__':
513 optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
514 ['help', 'type=', 'output=', 'base=', 'src_file='])
515 for (opt, value) in optlist:
516 if opt in ['-h', '--help']:
519 elif opt in ['-o', '--output']:
521 elif opt in ['-b', '--base']:
523 elif opt in ['-t', '--type']:
525 elif opt in ['-s', '--src_file']:
526 input_files = [f.strip() for f in open(value)]
528 if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'encodings', 'external', 'formats'] or output is None:
529 print 'Wrong input type or output filename.'
534 if input_type == 'ui':
535 ui_l10n(input_files, output, base)
536 elif input_type == 'layouts':
537 layouts_l10n(input_files, output, base, False)
538 elif input_type == 'layouttranslations':
539 layouts_l10n(input_files, output, base, True)
540 elif input_type == 'qt4':
541 qt4_l10n(input_files, output, base)
542 elif input_type == 'external':
543 external_l10n(input_files, output, base)
544 elif input_type == 'formats':
545 formats_l10n(input_files, output, base)
546 elif input_type == 'encodings':
547 encodings_l10n(input_files, output, base)
549 languages_l10n(input_files, output, base)