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 # Python polib library is needed for building the output file.
301 # This file should remain fixed during minor LyX releases.'''
302 for lang in languages:
303 print >> out, '\nTranslation %s' % lang
304 if lang in oldtrans.keys():
305 trans = oldtrans[lang]
308 if not lang in oldlanguages:
309 poname = os.path.join(base, 'po/' + lang + '.po')
310 po = polib.pofile(poname)
311 # Iterate through po entries and not keys for speed reasons.
312 # FIXME: The code is still too slow
314 if not entry.translated():
316 if entry.msgid in keys:
319 # some translators keep untranslated entries
323 if key in trans.keys():
324 val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
325 key = key.replace('\\', '\\\\').replace('"', '\\"')
326 print >> out, '\t"%s" "%s"' % \
327 (key.encode('utf-8'), val.encode('utf-8'))
328 # to print untranslated entries, uncomment the following lines
330 # key = key.replace('\\', '\\\\').replace('"', '\\"')
331 # print >> out, '\t"%s" "%s"' % \
332 # (key.encode('utf-8'), key.encode('utf-8'))
338 def qt4_l10n(input_files, output, base):
339 '''Generate pot file from src/frontends/qt4/ui/*.ui'''
340 output = open(output, 'w')
341 pat = re.compile(r'\s*<string>(.*)</string>')
342 prop = re.compile(r'\s*<property.*name.*=.*shortcut')
343 for src in input_files:
346 for lineno, line in enumerate(input.readlines()):
347 # skip the line after <property name=shortcut>
354 # get lines that match <string>...</string>
356 (string,) = pat.match(line).groups()
357 string = string.replace('&', '&').replace('"', '"')
358 string = string.replace('<', '<').replace('>', '>')
359 string = string.replace('\\', '\\\\').replace('"', r'\"')
360 string = string.replace('
', r'\n')
361 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
362 (relativePath(src, base), lineno+1, string)
367 def languages_l10n(input_files, output, base):
368 '''Generate pot file from lib/languages'''
369 out = open(output, 'w')
370 GuiName = re.compile(r'^[^#]*GuiName\s+(.*)')
372 for src in input_files:
376 for line in open(src).readlines():
378 res = GuiName.search(line)
380 string = res.group(1)
381 writeString(out, src, base, lineno, string)
387 def external_l10n(input_files, output, base):
388 '''Generate pot file from lib/external_templates'''
389 output = open(output, 'w')
390 Template = re.compile(r'^Template\s+(.*)')
391 GuiName = re.compile(r'\s*GuiName\s+(.*)')
392 HelpTextStart = re.compile(r'\s*HelpText\s')
393 HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
394 HelpTextEnd = re.compile(r'\s*HelpTextEnd\s')
396 for src in input_files:
400 prev_help_string = ''
401 for lineno, line in enumerate(input.readlines()):
402 if Template.match(line):
403 (string,) = Template.match(line).groups()
404 elif GuiName.match(line):
405 (string,) = GuiName.match(line).groups()
407 if HelpTextEnd.match(line):
409 print >> output, '\nmsgstr ""\n'
412 prev_help_string = ''
413 elif HelpTextSection.match(line):
414 (help_string,) = HelpTextSection.match(line).groups()
415 help_string = help_string.replace('"', '')
416 if help_string != "" and prev_help_string == '':
417 print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
418 (relativePath(src, base), lineno+1, help_string)
420 elif help_string != "":
421 print >> output, '"%s\\n"' % help_string
422 prev_help_string = help_string
423 elif HelpTextStart.match(line):
425 prev_help_string = ''
428 string = string.replace('"', '')
429 if string != "" and not inHelp:
430 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
431 (relativePath(src, base), lineno+1, string)
436 def formats_l10n(input_files, output, base):
437 '''Generate pot file from configure.py'''
438 output = open(output, 'w')
439 GuiName = re.compile(r'.*\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*')
440 GuiName2 = re.compile(r'.*\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*')
441 input = open(input_files[0])
442 for lineno, line in enumerate(input.readlines()):
445 if GuiName.match(line):
446 label = GuiName.match(line).group(1)
447 shortcut = GuiName.match(line).group(2).replace('"', '')
448 elif GuiName2.match(line):
449 label = GuiName2.match(line).group(1)
450 shortcut = GuiName2.match(line).group(2).replace('"', '')
453 label = label.replace('\\', '\\\\').replace('"', '')
455 labelsc = label + "|" + shortcut
457 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
458 (relativePath(input_files[0], base), lineno+1, label)
460 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
461 (relativePath(input_files[0], base), lineno+1, labelsc)
466 def encodings_l10n(input_files, output, base):
467 '''Generate pot file from lib/encodings'''
468 output = open(output, 'w')
469 # assuming only one encodings file
470 # Encoding utf8 utf8 "Unicode (utf8)" UTF-8 variable inputenc
471 reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
472 input = open(input_files[0])
473 for lineno, line in enumerate(input.readlines()):
474 if not line.startswith('Encoding'):
477 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
478 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
480 print "Error: Unable to handle line:"
482 # No need to abort if the parsing fails
490 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
494 path to the top source directory. default to '.'
496 output pot file, default to './lyx.pot'
498 filename that contains a list of input files in each line
501 layouts: lib/layouts/*
502 layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
504 languages: file lib/languages
505 encodings: file lib/encodings
506 external: external templates file
507 formats: formats predefined in lib/configure.py
510 if __name__ == '__main__':
516 optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
517 ['help', 'type=', 'output=', 'base=', 'src_file='])
518 for (opt, value) in optlist:
519 if opt in ['-h', '--help']:
522 elif opt in ['-o', '--output']:
524 elif opt in ['-b', '--base']:
526 elif opt in ['-t', '--type']:
528 elif opt in ['-s', '--src_file']:
529 input_files = [f.strip() for f in open(value)]
531 if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'encodings', 'external', 'formats'] or output is None:
532 print 'Wrong input type or output filename.'
537 if input_type == 'ui':
538 ui_l10n(input_files, output, base)
539 elif input_type == 'layouts':
540 layouts_l10n(input_files, output, base, False)
541 elif input_type == 'layouttranslations':
542 layouts_l10n(input_files, output, base, True)
543 elif input_type == 'qt4':
544 qt4_l10n(input_files, output, base)
545 elif input_type == 'external':
546 external_l10n(input_files, output, base)
547 elif input_type == 'formats':
548 formats_l10n(input_files, output, base)
549 elif input_type == 'encodings':
550 encodings_l10n(input_files, output, base)
552 languages_l10n(input_files, output, base)