]> git.lyx.org Git - lyx.git/blob - po/lyx_pot.py
Update the button text of InsetInclude insets
[lyx.git] / po / lyx_pot.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # file lyx_pot.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7 #
8 # \author Bo Peng
9 #
10 # Full author contact details are available in file CREDITS
11
12 # Usage: use
13 #     lyx_pot.py -h
14 # to get usage message
15
16 # This script will extract translatable strings from input files and write
17 # to output in gettext .pot format.
18 #
19 import sys, os, re, getopt
20 if sys.version_info < (2, 4, 0):
21     from sets import Set as set
22
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('\\', '/')
33     return path3
34
35
36 def writeString(outfile, infile, basefile, lineno, string):
37     string = string.replace('\\', '\\\\').replace('"', '')
38     if string == "":
39         return
40     print >> outfile, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
41         (relativePath(infile, basefile), lineno, string)
42
43
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:
54         input = open(src)
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()
69             else:
70                 continue
71             string = string.replace('"', '')
72             if string != "":
73                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
74                     (relativePath(src, base), lineno+1, string)
75         input.close()
76     output.close()
77
78
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+"(.*)"')
106
107     oldlanguages = []
108     languages = []
109     keyset = set()
110     oldtrans = dict()
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)
115             if res:
116                 line = res.group(1)
117             if line.strip() != '':
118                 languages.extend(line.split())
119
120         # read old translations if available
121         try:
122             input = open(output)
123             lang = ''
124             for line in input.readlines():
125                 res = Comment.search(line)
126                 if res:
127                     line = res.group(1)
128                 if line.strip() == '':
129                     continue
130                 res = Translation.search(line)
131                 if res:
132                     lang = res.group(1)
133                     if lang not in languages:
134                         oldlanguages.append(lang)
135                         languages.append(lang)
136                     oldtrans[lang] = dict()
137                     continue
138                 res = End.search(line)
139                 if res:
140                     lang = ''
141                     continue
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
149                     keyset.add(key)
150                     continue
151                 print "Error: Unable to handle line:"
152                 print line
153         except IOError:
154             print "Warning: Unable to open %s for reading." % output
155             print "         Old translations will be lost."
156
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')
161
162     out = open(output, 'w')
163     for src in input_files:
164         readingDescription = False
165         readingI18nPreamble = False
166         readingFloat = False
167         readingCiteFormats = False
168         isPredefined = False
169         usesFloatPkg = True
170         listname = ''
171         floatname = ''
172         descStartLine = -1
173         descLines = []
174         lineno = 0
175         for line in open(src).readlines():
176             lineno += 1
177             if readingDescription:
178                 res = DescEnd.search(line)
179                 if res != None:
180                     readingDescription = False
181                     desc = " ".join(descLines)
182                     if not layouttranslations:
183                         writeString(out, src, base, lineno + 1, desc)
184                     continue
185                 descLines.append(line[1:].strip())
186                 continue
187             res = DescBegin.search(line)
188             if res != None:
189                 readingDescription = True
190                 descStartLine = lineno
191                 continue
192             if readingI18nPreamble:
193                 res = EndI18nPreamble.search(line)
194                 if res != None:
195                     readingI18nPreamble = False
196                     continue
197                 res = I18nString.search(line)
198                 if res != None:
199                     string = res.group(1)
200                     if layouttranslations:
201                         keyset.add(string)
202                     else:
203                         writeString(out, src, base, lineno, string)
204                 continue
205             res = I18nPreamble.search(line)
206             if res != None:
207                 readingI18nPreamble = True
208                 continue
209             res = NameRE.search(line)
210             if res != None:
211                 string = res.group(1)
212                 if not layouttranslations:
213                     writeString(out, src, base, lineno + 1, string)
214                 continue
215             res = Style.search(line)
216             if res != None:
217                 string = res.group(1)
218                 string = string.replace('_', ' ')
219                 # Style means something else inside a float definition
220                 if not readingFloat:
221                     if not layouttranslations:
222                         writeString(out, src, base, lineno, string)
223                 continue
224             res = LabelString.search(line)
225             if res != None:
226                 string = res.group(1)
227                 if not layouttranslations:
228                     writeString(out, src, base, lineno, string)
229                 continue
230             res = GuiName.search(line)
231             if res != None:
232                 string = res.group(1)
233                 if layouttranslations:
234                     # gui name must only be added for floats
235                     if readingFloat:
236                         floatname = string
237                 else:
238                     writeString(out, src, base, lineno, string)
239                 continue
240             res = CategoryName.search(line)
241             if res != None:
242                 string = res.group(1)
243                 if not layouttranslations:
244                     writeString(out, src, base, lineno, string)
245                 continue
246             res = ListName.search(line)
247             if res != None:
248                 string = res.group(1)
249                 if layouttranslations:
250                     listname = string.strip('"')
251                 else:
252                     writeString(out, src, base, lineno, string)
253                 continue
254             res = InsetLayout.search(line)
255             if res != None:
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)
262                 if m:
263                     if not layouttranslations:
264                         writeString(out, src, base, lineno, m.group(1))
265                 continue
266             res = Category.search(line)
267             if res != None:
268                 string = res.group(1)
269                 if not layouttranslations:
270                     writeString(out, src, base, lineno, string)
271                 continue
272             res = CounterFormat.search(line)
273             if res != None:
274                 string = res.group(1)
275                 if not layouttranslations:
276                     writeString(out, src, base, lineno, string)
277                 continue
278             res = Float.search(line)
279             if res != None:
280                 readingFloat = True
281                 continue
282             res = IsPredefined.search(line)
283             if res != None:
284                 string = res.group(1).lower()
285                 if string == 'true':
286                     isPredefined = True
287                 else:
288                     isPredefined = False
289                 continue
290             res = UsesFloatPkg.search(line)
291             if res != None:
292                 string = res.group(1).lower()
293                 if string == 'true':
294                     usesFloatPkg = True
295                 else:
296                     usesFloatPkg = False
297                 continue
298             res = CiteFormat.search(line)
299             if res != None:
300                 readingCiteFormats = True
301                 continue
302             res = End.search(line)
303             if res != None:
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:
309                     if floatname != '':
310                         keyset.add(floatname)
311                     if listname != '':
312                         keyset.add(listname)
313                 isPredefined = False
314                 usesFloatPkg = True
315                 listname = ''
316                 floatname = ''
317                 readingCiteFormats = False
318                 readingFloat = False
319                 continue
320             if readingCiteFormats:
321                 res = KeyVal.search(line)
322                 if res != None:
323                     val = res.group(1)
324                     if not layouttranslations:
325                         writeString(out, src, base, lineno, val)
326
327     if layouttranslations:
328         # Extract translations of layout files
329         import polib
330
331         # Sort languages and key to minimize the diff between different runs
332         # with changed translations
333         languages.sort()
334         keys = []
335         for key in keyset:
336             keys.append(key)
337         keys.sort()
338
339         ContextRe = re.compile(r'(.*)(\[\[.*\]\])')
340
341         print >> out, '''# This file has been automatically generated by po/lyx_pot.py.
342 # PLEASE MODIFY ONLY THE LAGUAGES HAVING NO .po FILE! If you want to regenerate
343 # this file from the translations, run `make ../lib/layouttranslations' in po.
344 # Python polib library is needed for building the output file.
345 #
346 # This file should remain fixed during minor LyX releases.
347 # For more comments see README.localization file.'''
348         for lang in languages:
349             print >> out, '\nTranslation %s' % lang
350             if lang in oldtrans.keys():
351                 trans = oldtrans[lang]
352             else:
353                 trans = dict()
354             if not lang in oldlanguages:
355                 poname = os.path.join(base, 'po/' + lang + '.po')
356                 po = polib.pofile(poname)
357                 # Iterate through po entries and not keys for speed reasons.
358                 # FIXME: The code is still too slow
359                 for entry in po:
360                     if not entry.translated():
361                         continue
362                     if entry.msgid in keys:
363                         key = entry.msgid
364                         val = entry.msgstr
365                         # some translators keep untranslated entries
366                         if val != key:
367                             trans[key] = val
368             for key in keys:
369                 if key in trans.keys():
370                     val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
371                     key = key.replace('\\', '\\\\').replace('"', '\\"')
372                     print >> out, '\t"%s" "%s"' % \
373                              (key.encode('utf-8'), val.encode('utf-8'))
374                 # also print untranslated entries to help translators
375                 elif not lang in oldlanguages:
376                     key = key.replace('\\', '\\\\').replace('"', '\\"')
377                     res = ContextRe.search(key)
378                     if res != None:
379                         val = res.group(1)
380                     else:
381                         val = key
382                     print >> out, '\t"%s" "%s"' % \
383                              (key.encode('utf-8'), val.encode('utf-8'))
384             print >> out, 'End'
385
386     out.close()
387
388
389 def qt4_l10n(input_files, output, base):
390     '''Generate pot file from src/frontends/qt4/ui/*.ui'''
391     output = open(output, 'w')
392     pat = re.compile(r'\s*<string>(.*)</string>')
393     prop = re.compile(r'\s*<property.*name.*=.*shortcut')
394     for src in input_files:
395         input = open(src)
396         skipNextLine = False
397         for lineno, line in enumerate(input.readlines()):
398             # skip the line after <property name=shortcut>
399             if skipNextLine:
400                 skipNextLine = False
401                 continue
402             if prop.match(line):
403                 skipNextLine = True
404                 continue
405             # get lines that match <string>...</string>
406             if pat.match(line):
407                 (string,) = pat.match(line).groups()
408                 string = string.replace('&amp;', '&').replace('&quot;', '"')
409                 string = string.replace('&lt;', '<').replace('&gt;', '>')
410                 string = string.replace('\\', '\\\\').replace('"', r'\"')
411                 string = string.replace('&#x0a;', r'\n')
412                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
413                     (relativePath(src, base), lineno+1, string)
414         input.close()
415     output.close()
416
417
418 def languages_l10n(input_files, output, base):
419     '''Generate pot file from lib/languages'''
420     out = open(output, 'w')
421     GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
422     
423     for src in input_files:
424         descStartLine = -1
425         descLines = []
426         lineno = 0
427         for line in open(src).readlines():
428             lineno += 1
429             res = GuiName.search(line)
430             if res != None:
431                 string = res.group(1)
432                 writeString(out, src, base, lineno, string)
433                 continue
434                
435     out.close()
436
437
438 def external_l10n(input_files, output, base):
439     '''Generate pot file from lib/external_templates'''
440     output = open(output, 'w')
441     Template = re.compile(r'^Template\s+(.*)', re.IGNORECASE)
442     GuiName = re.compile(r'\s*GuiName\s+(.*)', re.IGNORECASE)
443     HelpTextStart = re.compile(r'\s*HelpText\s', re.IGNORECASE)
444     HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
445     HelpTextEnd = re.compile(r'\s*HelpTextEnd\s', re.IGNORECASE)
446     i = -1
447     for src in input_files:
448         input = open(src)
449         inHelp = False
450         hadHelp = False
451         prev_help_string = ''
452         for lineno, line in enumerate(input.readlines()):
453             if Template.match(line):
454                 (string,) = Template.match(line).groups()
455             elif GuiName.match(line):
456                 (string,) = GuiName.match(line).groups()
457             elif inHelp:
458                 if HelpTextEnd.match(line):
459                     if hadHelp:
460                         print >> output, '\nmsgstr ""\n'
461                     inHelp = False
462                     hadHelp = False
463                     prev_help_string = ''
464                 elif HelpTextSection.match(line):
465                     (help_string,) = HelpTextSection.match(line).groups()
466                     help_string = help_string.replace('"', '')
467                     if help_string != "" and prev_help_string == '':
468                         print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
469                             (relativePath(src, base), lineno+1, help_string)
470                         hadHelp = True
471                     elif help_string != "":
472                         print >> output, '"%s\\n"' % help_string
473                     prev_help_string = help_string
474             elif HelpTextStart.match(line):
475                 inHelp = True
476                 prev_help_string = ''
477             else:
478                 continue
479             string = string.replace('"', '')
480             if string != "" and not inHelp:
481                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
482                     (relativePath(src, base), lineno+1, string)
483         input.close()
484     output.close()
485
486
487 def formats_l10n(input_files, output, base):
488     '''Generate pot file from configure.py'''
489     output = open(output, 'w')
490     GuiName = re.compile(r'.*\\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*', re.IGNORECASE)
491     GuiName2 = re.compile(r'.*\\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*', re.IGNORECASE)
492     input = open(input_files[0])
493     for lineno, line in enumerate(input.readlines()):
494         label = ""
495         labelsc = ""
496         if GuiName.match(line):
497             label = GuiName.match(line).group(1)
498             shortcut = GuiName.match(line).group(2).replace('"', '')
499         elif GuiName2.match(line):
500             label = GuiName2.match(line).group(1)
501             shortcut = GuiName2.match(line).group(2).replace('"', '')
502         else:
503             continue
504         label = label.replace('\\', '\\\\').replace('"', '')
505         if shortcut != "":
506             labelsc = label + "|" + shortcut
507         if label != "":
508             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
509                 (relativePath(input_files[0], base), lineno+1, label)
510         if labelsc != "":
511             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
512                 (relativePath(input_files[0], base), lineno+1, labelsc)
513     input.close()
514     output.close()
515
516
517 def encodings_l10n(input_files, output, base):
518     '''Generate pot file from lib/encodings'''
519     output = open(output, 'w')
520     # assuming only one encodings file
521     #                 Encoding utf8      utf8    "Unicode (utf8)" UTF-8    variable inputenc
522     reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
523     input = open(input_files[0])
524     for lineno, line in enumerate(input.readlines()):
525         if not line.startswith('Encoding'):
526             continue
527         if reg.match(line):
528             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
529                 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
530         else:
531             print "Error: Unable to handle line:"
532             print line
533             # No need to abort if the parsing fails
534             # sys.exit(1)
535     input.close()
536     output.close()
537
538
539
540 Usage = '''
541 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
542
543 where
544     --base:
545         path to the top source directory. default to '.'
546     --output:
547         output pot file, default to './lyx.pot'
548     --src_file
549         filename that contains a list of input files in each line
550     --input_type can be
551         ui: lib/ui/*
552         layouts: lib/layouts/*
553         layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
554         qt4: qt4 ui files
555         languages: file lib/languages
556         encodings: file lib/encodings
557         external: external templates file
558         formats: formats predefined in lib/configure.py
559 '''
560
561 if __name__ == '__main__':
562     input_type = None
563     output = 'lyx.pot'
564     base = '.'
565     input_files = []
566     #
567     optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
568         ['help', 'type=', 'output=', 'base=', 'src_file='])
569     for (opt, value) in optlist:
570         if opt in ['-h', '--help']:
571             print Usage
572             sys.exit(0)
573         elif opt in ['-o', '--output']:
574             output = value
575         elif opt in ['-b', '--base']:
576             base = value
577         elif opt in ['-t', '--type']:
578             input_type = value
579         elif opt in ['-s', '--src_file']:
580             input_files = [f.strip() for f in open(value)]
581
582     if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'encodings', 'external', 'formats'] or output is None:
583         print 'Wrong input type or output filename.'
584         sys.exit(1)
585
586     input_files += args
587
588     if input_type == 'ui':
589         ui_l10n(input_files, output, base)
590     elif input_type == 'layouts':
591         layouts_l10n(input_files, output, base, False)
592     elif input_type == 'layouttranslations':
593         layouts_l10n(input_files, output, base, True)
594     elif input_type == 'qt4':
595         qt4_l10n(input_files, output, base)
596     elif input_type == 'external':
597         external_l10n(input_files, output, base)
598     elif input_type == 'formats':
599         formats_l10n(input_files, output, base)
600     elif input_type == 'encodings':
601         encodings_l10n(input_files, output, base)
602     else:
603         languages_l10n(input_files, output, base)
604
605