]> git.lyx.org Git - features.git/blob - po/lyx_pot.py
Clean up LaTeX font handling (#4999)
[features.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 latexfonts_l10n(input_files, output, base):
439     '''Generate pot file from lib/latexfonts'''
440     out = open(output, 'w')
441     GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
442     
443     for src in input_files:
444         descStartLine = -1
445         descLines = []
446         lineno = 0
447         for line in open(src).readlines():
448             lineno += 1
449             res = GuiName.search(line)
450             if res != None:
451                 string = res.group(1)
452                 writeString(out, src, base, lineno, string)
453                 continue
454                
455     out.close()
456
457
458 def external_l10n(input_files, output, base):
459     '''Generate pot file from lib/external_templates'''
460     output = open(output, 'w')
461     Template = re.compile(r'^Template\s+(.*)', re.IGNORECASE)
462     GuiName = re.compile(r'\s*GuiName\s+(.*)', re.IGNORECASE)
463     HelpTextStart = re.compile(r'\s*HelpText\s', re.IGNORECASE)
464     HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
465     HelpTextEnd = re.compile(r'\s*HelpTextEnd\s', re.IGNORECASE)
466     i = -1
467     for src in input_files:
468         input = open(src)
469         inHelp = False
470         hadHelp = False
471         prev_help_string = ''
472         for lineno, line in enumerate(input.readlines()):
473             if Template.match(line):
474                 (string,) = Template.match(line).groups()
475             elif GuiName.match(line):
476                 (string,) = GuiName.match(line).groups()
477             elif inHelp:
478                 if HelpTextEnd.match(line):
479                     if hadHelp:
480                         print >> output, '\nmsgstr ""\n'
481                     inHelp = False
482                     hadHelp = False
483                     prev_help_string = ''
484                 elif HelpTextSection.match(line):
485                     (help_string,) = HelpTextSection.match(line).groups()
486                     help_string = help_string.replace('"', '')
487                     if help_string != "" and prev_help_string == '':
488                         print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
489                             (relativePath(src, base), lineno+1, help_string)
490                         hadHelp = True
491                     elif help_string != "":
492                         print >> output, '"%s\\n"' % help_string
493                     prev_help_string = help_string
494             elif HelpTextStart.match(line):
495                 inHelp = True
496                 prev_help_string = ''
497             else:
498                 continue
499             string = string.replace('"', '')
500             if string != "" and not inHelp:
501                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
502                     (relativePath(src, base), lineno+1, string)
503         input.close()
504     output.close()
505
506
507 def formats_l10n(input_files, output, base):
508     '''Generate pot file from configure.py'''
509     output = open(output, 'w')
510     GuiName = re.compile(r'.*\\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*', re.IGNORECASE)
511     GuiName2 = re.compile(r'.*\\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*', re.IGNORECASE)
512     input = open(input_files[0])
513     for lineno, line in enumerate(input.readlines()):
514         label = ""
515         labelsc = ""
516         if GuiName.match(line):
517             label = GuiName.match(line).group(1)
518             shortcut = GuiName.match(line).group(2).replace('"', '')
519         elif GuiName2.match(line):
520             label = GuiName2.match(line).group(1)
521             shortcut = GuiName2.match(line).group(2).replace('"', '')
522         else:
523             continue
524         label = label.replace('\\', '\\\\').replace('"', '')
525         if shortcut != "":
526             labelsc = label + "|" + shortcut
527         if label != "":
528             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
529                 (relativePath(input_files[0], base), lineno+1, label)
530         if labelsc != "":
531             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
532                 (relativePath(input_files[0], base), lineno+1, labelsc)
533     input.close()
534     output.close()
535
536
537 def encodings_l10n(input_files, output, base):
538     '''Generate pot file from lib/encodings'''
539     output = open(output, 'w')
540     # assuming only one encodings file
541     #                 Encoding utf8      utf8    "Unicode (utf8)" UTF-8    variable inputenc
542     reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
543     input = open(input_files[0])
544     for lineno, line in enumerate(input.readlines()):
545         if not line.startswith('Encoding'):
546             continue
547         if reg.match(line):
548             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
549                 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
550         else:
551             print "Error: Unable to handle line:"
552             print line
553             # No need to abort if the parsing fails
554             # sys.exit(1)
555     input.close()
556     output.close()
557
558
559
560 Usage = '''
561 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
562
563 where
564     --base:
565         path to the top source directory. default to '.'
566     --output:
567         output pot file, default to './lyx.pot'
568     --src_file
569         filename that contains a list of input files in each line
570     --input_type can be
571         ui: lib/ui/*
572         layouts: lib/layouts/*
573         layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
574         qt4: qt4 ui files
575         languages: file lib/languages
576         latexfonts: file lib/latexfonts
577         encodings: file lib/encodings
578         external: external templates file
579         formats: formats predefined in lib/configure.py
580 '''
581
582 if __name__ == '__main__':
583     input_type = None
584     output = 'lyx.pot'
585     base = '.'
586     input_files = []
587     #
588     optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
589         ['help', 'type=', 'output=', 'base=', 'src_file='])
590     for (opt, value) in optlist:
591         if opt in ['-h', '--help']:
592             print Usage
593             sys.exit(0)
594         elif opt in ['-o', '--output']:
595             output = value
596         elif opt in ['-b', '--base']:
597             base = value
598         elif opt in ['-t', '--type']:
599             input_type = value
600         elif opt in ['-s', '--src_file']:
601             input_files = [f.strip() for f in open(value)]
602
603     if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'latexfonts', 'encodings', 'external', 'formats'] or output is None:
604         print 'Wrong input type or output filename.'
605         sys.exit(1)
606
607     input_files += args
608
609     if input_type == 'ui':
610         ui_l10n(input_files, output, base)
611     elif input_type == 'latexfonts':
612         latexfonts_l10n(input_files, output, base)
613     elif input_type == 'layouts':
614         layouts_l10n(input_files, output, base, False)
615     elif input_type == 'layouttranslations':
616         layouts_l10n(input_files, output, base, True)
617     elif input_type == 'qt4':
618         qt4_l10n(input_files, output, base)
619     elif input_type == 'external':
620         external_l10n(input_files, output, base)
621     elif input_type == 'formats':
622         formats_l10n(input_files, output, base)
623     elif input_type == 'encodings':
624         encodings_l10n(input_files, output, base)
625     else:
626         languages_l10n(input_files, output, base)
627
628