]> git.lyx.org Git - lyx.git/blob - po/lyx_pot.py
document view/update master
[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+"([^"]*)"')
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:
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'^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+"(.*)"')
104
105     oldlanguages = []
106     languages = []
107     keyset = set()
108     oldtrans = dict()
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())
114
115         # read old translations if available
116         try:
117             input = open(output)
118             lang = ''
119             for line in input.readlines():
120                 res = Comment.search(line)
121                 if res:
122                     continue
123                 if line.strip() == '':
124                     continue
125                 res = Translation.search(line)
126                 if res:
127                     lang = res.group(1)
128                     if lang not in languages:
129                         oldlanguages.append(lang)
130                         languages.append(lang)
131                     oldtrans[lang] = dict()
132                     continue
133                 res = End.search(line)
134                 if res:
135                     lang = ''
136                     continue
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
144                     keyset.add(key)
145                     continue
146                 print "Error: Unable to handle line:"
147                 print line
148         except IOError:
149             pass
150
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')
155
156     out = open(output, 'w')
157     for src in input_files:
158         readingDescription = False
159         readingI18nPreamble = False
160         readingFloat = False
161         readingCiteFormats = False
162         descStartLine = -1
163         descLines = []
164         lineno = 0
165         for line in open(src).readlines():
166             lineno += 1
167             if readingDescription:
168                 res = DescEnd.search(line)
169                 if res != None:
170                     readingDescription = False
171                     desc = " ".join(descLines)
172                     if not layouttranslations:
173                         writeString(out, src, base, lineno + 1, desc)
174                     continue
175                 descLines.append(line[1:].strip())
176                 continue
177             res = DescBegin.search(line)
178             if res != None:
179                 readingDescription = True
180                 descStartLine = lineno
181                 continue
182             if readingI18nPreamble:
183                 res = EndI18nPreamble.search(line)
184                 if res != None:
185                     readingI18nPreamble = False
186                     continue
187                 res = I18nString.search(line)
188                 if res != None:
189                     string = res.group(1)
190                     if layouttranslations:
191                         keyset.add(string)
192                     else:
193                         writeString(out, src, base, lineno, string)
194                 continue
195             res = I18nPreamble.search(line)
196             if res != None:
197                 readingI18nPreamble = True
198                 continue
199             res = NameRE.search(line)
200             if res != None:
201                 string = res.group(1)
202                 if not layouttranslations:
203                     writeString(out, src, base, lineno + 1, string)
204                 continue
205             res = Style.search(line)
206             if res != None:
207                 string = res.group(1)
208                 string = string.replace('_', ' ')
209                 if not layouttranslations:
210                     writeString(out, src, base, lineno, string)
211                 continue
212             res = LabelString.search(line)
213             if res != None:
214                 string = res.group(1)
215                 if not layouttranslations:
216                     writeString(out, src, base, lineno, string)
217                 continue
218             res = GuiName.search(line)
219             if res != None:
220                 string = res.group(1)
221                 if layouttranslations:
222                     # gui name must only be added for floats
223                     if readingFloat:
224                         keyset.add(string)
225                 else:
226                     writeString(out, src, base, lineno, string)
227                 continue
228             res = CategoryName.search(line)
229             if res != None:
230                 string = res.group(1)
231                 if not layouttranslations:
232                     writeString(out, src, base, lineno, string)
233                 continue
234             res = ListName.search(line)
235             if res != None:
236                 string = res.group(1)
237                 if layouttranslations:
238                     keyset.add(string.strip('"'))
239                 else:
240                     writeString(out, src, base, lineno, string)
241                 continue
242             res = InsetLayout.search(line)
243             if res != None:
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)
250                 if m:
251                     if not layouttranslations:
252                         writeString(out, src, base, lineno, m.group(1))
253                 continue
254             res = Category.search(line)
255             if res != None:
256                 string = res.group(1)
257                 if not layouttranslations:
258                     writeString(out, src, base, lineno, string)
259                 continue
260             res = CounterFormat.search(line)
261             if res != None:
262                 string = res.group(1)
263                 if not layouttranslations:
264                     writeString(out, src, base, lineno, string)
265                 continue
266             res = Float.search(line)
267             if res != None:
268                 readingFloat = True
269                 continue
270             res = CiteFormat.search(line)
271             if res != None:
272                 readingCiteFormats = True
273             res = End.search(line)
274             if res != None:
275                 readingCiteFormats = False
276                 readingFloat = False
277             if readingCiteFormats:
278                 res = KeyVal.search(line)
279                 if res != None:
280                     val = res.group(1)
281                     if not layouttranslations:
282                         writeString(out, src, base, lineno, val)
283
284     if layouttranslations:
285         # Extract translations of layout files
286         import polib
287
288         # Sort languages and key to minimize the diff between different runs
289         # with changed translations
290         languages.sort()
291         keys = []
292         for key in keyset:
293             keys.append(key)
294         keys.sort()
295
296         print >> out, '''# This file has been automatically generated by po/lyx_pot.py.
297 # PLEASE MODIFY ONLY THE LAGUAGES HAVING NO .po FILE! If you want to regenerate
298 # this file from the translations, run `make ../lib/layouttranslations' in po.'''
299         for lang in languages:
300             print >> out, '\nTranslation %s' % lang
301             if lang in oldtrans.keys():
302                 trans = oldtrans[lang]
303             else:
304                 trans = dict()
305             if not lang in oldlanguages:
306                 poname = os.path.join(base, 'po/' + lang + '.po')
307                 po = polib.pofile(poname)
308                 # Iterate through po entries and not keys for speed reasons.
309                 # FIXME: The code is still too slow
310                 for entry in po:
311                     if not entry.translated():
312                         continue
313                     if entry.msgid in keys:
314                         key = entry.msgid
315                         val = entry.msgstr
316                         # some translators keep untranslated entries
317                         if val != key:
318                             trans[key] = val
319             for key in keys:
320                 if key in trans.keys():
321                     val = trans[key].replace('\\', '\\\\').replace('"', '\\"')
322                     key = key.replace('\\', '\\\\').replace('"', '\\"')
323                     print >> out, '\t"%s" "%s"' % \
324                              (key.encode('utf-8'), val.encode('utf-8'))
325                 # to print untranslated entries, uncomment the following lines
326                 #else:
327                 #    key = key.replace('\\', '\\\\').replace('"', '\\"')
328                 #    print >> out, '\t"%s" "%s"' % \
329                 #             (key.encode('utf-8'), key.encode('utf-8'))
330             print >> out, 'End'
331
332     out.close()
333
334
335 def qt4_l10n(input_files, output, base):
336     '''Generate pot file from src/frontends/qt4/ui/*.ui'''
337     output = open(output, 'w')
338     pat = re.compile(r'\s*<string>(.*)</string>')
339     prop = re.compile(r'\s*<property.*name.*=.*shortcut')
340     for src in input_files:
341         input = open(src)
342         skipNextLine = False
343         for lineno, line in enumerate(input.readlines()):
344             # skip the line after <property name=shortcut>
345             if skipNextLine:
346                 skipNextLine = False
347                 continue
348             if prop.match(line):
349                 skipNextLine = True
350                 continue
351             # get lines that match <string>...</string>
352             if pat.match(line):
353                 (string,) = pat.match(line).groups()
354                 string = string.replace('&amp;', '&').replace('&quot;', '"')
355                 string = string.replace('&lt;', '<').replace('&gt;', '>')
356                 string = string.replace('\\', '\\\\').replace('"', r'\"')
357                 string = string.replace('&#x0a;', r'\n')
358                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
359                     (relativePath(src, base), lineno+1, string)
360         input.close()
361     output.close()
362
363
364 def languages_l10n(input_files, output, base):
365     '''Generate pot file from lib/languages'''
366     out = open(output, 'w')
367     GuiName = re.compile(r'^[^#]*GuiName\s+(.*)')
368     
369     for src in input_files:
370         descStartLine = -1
371         descLines = []
372         lineno = 0
373         for line in open(src).readlines():
374             lineno += 1
375             res = GuiName.search(line)
376             if res != None:
377                 string = res.group(1)
378                 writeString(out, src, base, lineno, string)
379                 continue
380                
381     out.close()
382
383
384 def external_l10n(input_files, output, base):
385     '''Generate pot file from lib/external_templates'''
386     output = open(output, 'w')
387     Template = re.compile(r'^Template\s+(.*)')
388     GuiName = re.compile(r'\s*GuiName\s+(.*)')
389     HelpTextStart = re.compile(r'\s*HelpText\s')
390     HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
391     HelpTextEnd = re.compile(r'\s*HelpTextEnd\s')
392     i = -1
393     for src in input_files:
394         input = open(src)
395         inHelp = False
396         hadHelp = False
397         prev_help_string = ''
398         for lineno, line in enumerate(input.readlines()):
399             if Template.match(line):
400                 (string,) = Template.match(line).groups()
401             elif GuiName.match(line):
402                 (string,) = GuiName.match(line).groups()
403             elif inHelp:
404                 if HelpTextEnd.match(line):
405                     if hadHelp:
406                         print >> output, '\nmsgstr ""\n'
407                     inHelp = False
408                     hadHelp = False
409                     prev_help_string = ''
410                 elif HelpTextSection.match(line):
411                     (help_string,) = HelpTextSection.match(line).groups()
412                     help_string = help_string.replace('"', '')
413                     if help_string != "" and prev_help_string == '':
414                         print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
415                             (relativePath(src, base), lineno+1, help_string)
416                         hadHelp = True
417                     elif help_string != "":
418                         print >> output, '"%s\\n"' % help_string
419                     prev_help_string = help_string
420             elif HelpTextStart.match(line):
421                 inHelp = True
422                 prev_help_string = ''
423             else:
424                 continue
425             string = string.replace('"', '')
426             if string != "" and not inHelp:
427                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
428                     (relativePath(src, base), lineno+1, string)
429         input.close()
430     output.close()
431
432
433 def formats_l10n(input_files, output, base):
434     '''Generate pot file from configure.py'''
435     output = open(output, 'w')
436     GuiName = re.compile(r'.*\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*')
437     GuiName2 = re.compile(r'.*\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*')
438     input = open(input_files[0])
439     for lineno, line in enumerate(input.readlines()):
440         label = ""
441         labelsc = ""
442         if GuiName.match(line):
443             label = GuiName.match(line).group(1)
444             shortcut = GuiName.match(line).group(2).replace('"', '')
445         elif GuiName2.match(line):
446             label = GuiName2.match(line).group(1)
447             shortcut = GuiName2.match(line).group(2).replace('"', '')
448         else:
449             continue
450         label = label.replace('\\', '\\\\').replace('"', '')
451         if shortcut != "":
452             labelsc = label + "|" + shortcut
453         if label != "":
454             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
455                 (relativePath(input_files[0], base), lineno+1, label)
456         if labelsc != "":
457             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
458                 (relativePath(input_files[0], base), lineno+1, labelsc)
459     input.close()
460     output.close()
461
462
463 def encodings_l10n(input_files, output, base):
464     '''Generate pot file from lib/encodings'''
465     output = open(output, 'w')
466     # assuming only one encodings file
467     #                 Encoding utf8      utf8    "Unicode (utf8)" UTF-8    variable inputenc
468     reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
469     input = open(input_files[0])
470     for lineno, line in enumerate(input.readlines()):
471         if not line.startswith('Encoding'):
472             continue
473         if reg.match(line):
474             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
475                 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
476         else:
477             print "Error: Unable to handle line:"
478             print line
479             # No need to abort if the parsing fails
480             # sys.exit(1)
481     input.close()
482     output.close()
483
484
485
486 Usage = '''
487 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
488
489 where
490     --base:
491         path to the top source directory. default to '.'
492     --output:
493         output pot file, default to './lyx.pot'
494     --src_file
495         filename that contains a list of input files in each line
496     --input_type can be
497         ui: lib/ui/*
498         layouts: lib/layouts/*
499         layouttranslations: create lib/layouttranslations from po/*.po and lib/layouts/*
500         qt4: qt4 ui files
501         languages: file lib/languages
502         encodings: file lib/encodings
503         external: external templates file
504         formats: formats predefined in lib/configure.py
505 '''
506
507 if __name__ == '__main__':
508     input_type = None
509     output = 'lyx.pot'
510     base = '.'
511     input_files = []
512     #
513     optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
514         ['help', 'type=', 'output=', 'base=', 'src_file='])
515     for (opt, value) in optlist:
516         if opt in ['-h', '--help']:
517             print Usage
518             sys.exit(0)
519         elif opt in ['-o', '--output']:
520             output = value
521         elif opt in ['-b', '--base']:
522             base = value
523         elif opt in ['-t', '--type']:
524             input_type = value
525         elif opt in ['-s', '--src_file']:
526             input_files = [f.strip() for f in open(value)]
527
528     if input_type not in ['ui', 'layouts', 'layouttranslations', 'qt4', 'languages', 'encodings', 'external', 'formats'] or output is None:
529         print 'Wrong input type or output filename.'
530         sys.exit(1)
531
532     input_files += args
533
534     if input_type == 'ui':
535         ui_l10n(input_files, output, base)
536     elif input_type == 'layouts':
537         layouts_l10n(input_files, output, base, False)
538     elif input_type == 'layouttranslations':
539         layouts_l10n(input_files, output, base, True)
540     elif input_type == 'qt4':
541         qt4_l10n(input_files, output, base)
542     elif input_type == 'external':
543         external_l10n(input_files, output, base)
544     elif input_type == 'formats':
545         formats_l10n(input_files, output, base)
546     elif input_type == 'encodings':
547         encodings_l10n(input_files, output, base)
548     else:
549         languages_l10n(input_files, output, base)
550
551