]> git.lyx.org Git - lyx.git/blob - po/lyx_pot.py
Fix lyx2lyx revertion for natbib.
[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         print >> out, '''# This file has been automatically generated by po/lyx_pot.py.
340 # PLEASE MODIFY ONLY THE LAGUAGES HAVING NO .po FILE! If you want to regenerate
341 # this file from the translations, run `make ../lib/layouttranslations' in po.
342 # Python polib library is needed for building the output file.
343 #
344 # This file should remain fixed during minor LyX releases.
345 # For more comments see README.localization file.'''
346         for lang in languages:
347             print >> out, '\nTranslation %s' % lang
348             if lang in oldtrans.keys():
349                 trans = oldtrans[lang]
350             else:
351                 trans = dict()
352             if not lang in oldlanguages:
353                 poname = os.path.join(base, 'po/' + lang + '.po')
354                 po = polib.pofile(poname)
355                 # Iterate through po entries and not keys for speed reasons.
356                 # FIXME: The code is still too slow
357                 for entry in po:
358                     if not entry.translated():
359                         continue
360                     if entry.msgid in keys:
361                         key = entry.msgid
362                         val = entry.msgstr
363                         # some translators keep untranslated entries
364                         if val != key:
365                             trans[key] = val
366             for key in keys:
367                 if key in trans.keys():
368                     val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
369                     key = key.replace('\\', '\\\\').replace('"', '\\"')
370                     print >> out, '\t"%s" "%s"' % \
371                              (key.encode('utf-8'), val.encode('utf-8'))
372                 # also print untranslated entries to help translators
373                 elif not lang in oldlanguages:
374                     key = key.replace('\\', '\\\\').replace('"', '\\"')
375                     print >> out, '\t"%s" "%s"' % \
376                              (key.encode('utf-8'), key.encode('utf-8'))
377             print >> out, 'End'
378
379     out.close()
380
381
382 def qt4_l10n(input_files, output, base):
383     '''Generate pot file from src/frontends/qt4/ui/*.ui'''
384     output = open(output, 'w')
385     pat = re.compile(r'\s*<string>(.*)</string>')
386     prop = re.compile(r'\s*<property.*name.*=.*shortcut')
387     for src in input_files:
388         input = open(src)
389         skipNextLine = False
390         for lineno, line in enumerate(input.readlines()):
391             # skip the line after <property name=shortcut>
392             if skipNextLine:
393                 skipNextLine = False
394                 continue
395             if prop.match(line):
396                 skipNextLine = True
397                 continue
398             # get lines that match <string>...</string>
399             if pat.match(line):
400                 (string,) = pat.match(line).groups()
401                 string = string.replace('&amp;', '&').replace('&quot;', '"')
402                 string = string.replace('&lt;', '<').replace('&gt;', '>')
403                 string = string.replace('\\', '\\\\').replace('"', r'\"')
404                 string = string.replace('&#x0a;', r'\n')
405                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
406                     (relativePath(src, base), lineno+1, string)
407         input.close()
408     output.close()
409
410
411 def languages_l10n(input_files, output, base):
412     '''Generate pot file from lib/languages'''
413     out = open(output, 'w')
414     GuiName = re.compile(r'^[^#]*GuiName\s+(.*)', re.IGNORECASE)
415     
416     for src in input_files:
417         descStartLine = -1
418         descLines = []
419         lineno = 0
420         for line in open(src).readlines():
421             lineno += 1
422             res = GuiName.search(line)
423             if res != None:
424                 string = res.group(1)
425                 writeString(out, src, base, lineno, string)
426                 continue
427                
428     out.close()
429
430
431 def external_l10n(input_files, output, base):
432     '''Generate pot file from lib/external_templates'''
433     output = open(output, 'w')
434     Template = re.compile(r'^Template\s+(.*)', re.IGNORECASE)
435     GuiName = re.compile(r'\s*GuiName\s+(.*)', re.IGNORECASE)
436     HelpTextStart = re.compile(r'\s*HelpText\s', re.IGNORECASE)
437     HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
438     HelpTextEnd = re.compile(r'\s*HelpTextEnd\s', re.IGNORECASE)
439     i = -1
440     for src in input_files:
441         input = open(src)
442         inHelp = False
443         hadHelp = False
444         prev_help_string = ''
445         for lineno, line in enumerate(input.readlines()):
446             if Template.match(line):
447                 (string,) = Template.match(line).groups()
448             elif GuiName.match(line):
449                 (string,) = GuiName.match(line).groups()
450             elif inHelp:
451                 if HelpTextEnd.match(line):
452                     if hadHelp:
453                         print >> output, '\nmsgstr ""\n'
454                     inHelp = False
455                     hadHelp = False
456                     prev_help_string = ''
457                 elif HelpTextSection.match(line):
458                     (help_string,) = HelpTextSection.match(line).groups()
459                     help_string = help_string.replace('"', '')
460                     if help_string != "" and prev_help_string == '':
461                         print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
462                             (relativePath(src, base), lineno+1, help_string)
463                         hadHelp = True
464                     elif help_string != "":
465                         print >> output, '"%s\\n"' % help_string
466                     prev_help_string = help_string
467             elif HelpTextStart.match(line):
468                 inHelp = True
469                 prev_help_string = ''
470             else:
471                 continue
472             string = string.replace('"', '')
473             if string != "" and not inHelp:
474                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
475                     (relativePath(src, base), lineno+1, string)
476         input.close()
477     output.close()
478
479
480 def formats_l10n(input_files, output, base):
481     '''Generate pot file from configure.py'''
482     output = open(output, 'w')
483     GuiName = re.compile(r'.*\\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*', re.IGNORECASE)
484     GuiName2 = re.compile(r'.*\\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*', re.IGNORECASE)
485     input = open(input_files[0])
486     for lineno, line in enumerate(input.readlines()):
487         label = ""
488         labelsc = ""
489         if GuiName.match(line):
490             label = GuiName.match(line).group(1)
491             shortcut = GuiName.match(line).group(2).replace('"', '')
492         elif GuiName2.match(line):
493             label = GuiName2.match(line).group(1)
494             shortcut = GuiName2.match(line).group(2).replace('"', '')
495         else:
496             continue
497         label = label.replace('\\', '\\\\').replace('"', '')
498         if shortcut != "":
499             labelsc = label + "|" + shortcut
500         if label != "":
501             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
502                 (relativePath(input_files[0], base), lineno+1, label)
503         if labelsc != "":
504             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
505                 (relativePath(input_files[0], base), lineno+1, labelsc)
506     input.close()
507     output.close()
508
509
510 def encodings_l10n(input_files, output, base):
511     '''Generate pot file from lib/encodings'''
512     output = open(output, 'w')
513     # assuming only one encodings file
514     #                 Encoding utf8      utf8    "Unicode (utf8)" UTF-8    variable inputenc
515     reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
516     input = open(input_files[0])
517     for lineno, line in enumerate(input.readlines()):
518         if not line.startswith('Encoding'):
519             continue
520         if reg.match(line):
521             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
522                 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
523         else:
524             print "Error: Unable to handle line:"
525             print line
526             # No need to abort if the parsing fails
527             # sys.exit(1)
528     input.close()
529     output.close()
530
531
532
533 Usage = '''
534 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
535
536 where
537     --base:
538         path to the top source directory. default to '.'
539     --output:
540         output pot file, default to './lyx.pot'
541     --src_file
542         filename that contains a list of input files in each line
543     --input_type can be
544         ui: lib/ui/*
545         layouts: lib/layouts/*
546         layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
547         qt4: qt4 ui files
548         languages: file lib/languages
549         encodings: file lib/encodings
550         external: external templates file
551         formats: formats predefined in lib/configure.py
552 '''
553
554 if __name__ == '__main__':
555     input_type = None
556     output = 'lyx.pot'
557     base = '.'
558     input_files = []
559     #
560     optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
561         ['help', 'type=', 'output=', 'base=', 'src_file='])
562     for (opt, value) in optlist:
563         if opt in ['-h', '--help']:
564             print Usage
565             sys.exit(0)
566         elif opt in ['-o', '--output']:
567             output = value
568         elif opt in ['-b', '--base']:
569             base = value
570         elif opt in ['-t', '--type']:
571             input_type = value
572         elif opt in ['-s', '--src_file']:
573             input_files = [f.strip() for f in open(value)]
574
575     if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'encodings', 'external', 'formats'] or output is None:
576         print 'Wrong input type or output filename.'
577         sys.exit(1)
578
579     input_files += args
580
581     if input_type == 'ui':
582         ui_l10n(input_files, output, base)
583     elif input_type == 'layouts':
584         layouts_l10n(input_files, output, base, False)
585     elif input_type == 'layouttranslations':
586         layouts_l10n(input_files, output, base, True)
587     elif input_type == 'qt4':
588         qt4_l10n(input_files, output, base)
589     elif input_type == 'external':
590         external_l10n(input_files, output, base)
591     elif input_type == 'formats':
592         formats_l10n(input_files, output, base)
593     elif input_type == 'encodings':
594         encodings_l10n(input_files, output, base)
595     else:
596         languages_l10n(input_files, output, base)
597
598