]> git.lyx.org Git - lyx.git/blob - po/lyx_pot.py
Better fix for bug 1476 (following an idea by Jean-Marc).
[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
21 def relativePath(path, base):
22     '''return relative path from top source dir'''
23     # full pathname of path
24     path1 = os.path.normpath(os.path.realpath(path)).split(os.sep)
25     path2 = os.path.normpath(os.path.realpath(base)).split(os.sep)
26     if path1[:len(path2)] != path2:
27         print "Path %s is not under top source directory" % path
28     path3 = os.path.join(*path1[len(path2):]);
29     # replace all \ by / such that we get the same comments on Windows and *nix
30     path3 = path3.replace('\\', '/')
31     return path3
32
33
34 def writeString(outfile, infile, basefile, lineno, string):
35     string = string.replace('\\', '\\\\').replace('"', '')
36     if string == "":
37         return
38     print >> outfile, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
39         (relativePath(infile, basefile), lineno, string)
40
41
42 def ui_l10n(input_files, output, base):
43     '''Generate pot file from lib/ui/*'''
44     output = open(output, 'w')
45     Submenu = re.compile(r'^[^#]*Submenu\s+"([^"]*)"')
46     Popupmenu = re.compile(r'^[^#]*PopupMenu\s+"[^"]+"\s+"([^"]*)"')
47     Toolbar = re.compile(r'^[^#]*Toolbar\s+"[^"]+"\s+"([^"]*)"')
48     Item = re.compile(r'[^#]*Item\s+"([^"]*)"')
49     TableInsert = re.compile(r'[^#]*TableInsert\s+"([^"]*)"')
50     for src in input_files:
51         input = open(src)
52         for lineno, line in enumerate(input.readlines()):
53             if Submenu.match(line):
54                 (string,) = Submenu.match(line).groups()
55                 string = string.replace('_', ' ')
56             elif Popupmenu.match(line):
57                 (string,) = Popupmenu.match(line).groups()
58             elif Toolbar.match(line):
59                 (string,) = Toolbar.match(line).groups()
60             elif Item.match(line):
61                 (string,) = Item.match(line).groups()
62             elif TableInsert.match(line):
63                 (string,) = TableInsert.match(line).groups()
64             else:
65                 continue
66             string = string.replace('"', '')
67             if string != "":
68                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
69                     (relativePath(src, base), lineno+1, string)
70         input.close()
71     output.close()
72
73
74 def layouts_l10n(input_files, output, base):
75     '''Generate pot file from lib/layouts/*.{layout,inc,module}'''
76     out = open(output, 'w')
77     Style = re.compile(r'^Style\s+(.*)')
78     # include ???LabelString???, but exclude comment lines
79     LabelString = re.compile(r'^[^#]*LabelString\S*\s+(.*)')
80     GuiName = re.compile(r'\s*GuiName\s+(.*)')
81     ListName = re.compile(r'\s*ListName\s+(.*)')
82     CategoryName = re.compile(r'\s*Category\s+(.*)')
83     NameRE = re.compile(r'DeclareLyXModule.*{(.*)}')
84     InsetLayout = re.compile(r'^InsetLayout\s+(.*)')
85     DescBegin = re.compile(r'#+\s*DescriptionBegin\s*$')
86     DescEnd = re.compile(r'#+\s*DescriptionEnd\s*$')
87     I18nPreamble = re.compile(r'\s*(Lang)|(Babel)Preamble\s*$')
88     EndI18nPreamble = re.compile(r'\s*End(Lang)|(Babel)Preamble\s*$')
89     I18nString = re.compile(r'_\(([^\)]+)\)')
90
91     for src in input_files:
92         readingDescription = False
93         readingI18nPreamble = False
94         descStartLine = -1
95         descLines = []
96         lineno = 0
97         for line in open(src).readlines():
98             lineno += 1
99             if readingDescription:
100                 res = DescEnd.search(line)
101                 if res != None:
102                     readingDescription = False
103                     desc = " ".join(descLines)
104                     writeString(out, src, base, lineno + 1, desc)
105                     continue
106                 descLines.append(line[1:].strip())
107                 continue
108             res = DescBegin.search(line)
109             if res != None:
110                 readingDescription = True
111                 descStartLine = lineno
112                 continue
113             if readingI18nPreamble:
114                 res = EndI18nPreamble.search(line)
115                 if res != None:
116                     readingI18nPreamble = False
117                     continue
118                 res = I18nString.search(line)
119                 if res != None:
120                     string = res.group(1)
121                     writeString(out, src, base, lineno, string)
122                 continue
123             res = I18nPreamble.search(line)
124             if res != None:
125                 readingI18nPreamble = True
126                 continue
127             res = NameRE.search(line)
128             if res != None:
129                 string = res.group(1)
130                 string = string.replace('\\', '\\\\').replace('"', '')
131                 if string != "":
132                     print >> out, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
133                         (relativePath(src, base), lineno + 1, string)
134                 continue
135             res = Style.search(line)
136             if res != None:
137                 string = res.group(1)
138                 string = string.replace('_', ' ')
139                 writeString(out, src, base, lineno, string)
140                 continue
141             res = LabelString.search(line)
142             if res != None:
143                 string = res.group(1)
144                 writeString(out, src, base, lineno, string)
145                 continue
146             res = GuiName.search(line)
147             if res != None:
148                 string = res.group(1)
149                 writeString(out, src, base, lineno, string)
150                 continue
151             res = CategoryName.search(line)
152             if res != None:
153                 string = res.group(1)
154                 writeString(out, src, base, lineno, string)
155                 continue
156             res = ListName.search(line)
157             if res != None:
158                 string = res.group(1)
159                 writeString(out, src, base, lineno, string)
160                 continue
161             res = InsetLayout.search(line)
162             if res != None:
163                 string = res.group(1)
164                 string = string.replace('_', ' ')
165                 writeString(out, src, base, lineno, string)
166                 continue
167     out.close()
168
169
170 def qt4_l10n(input_files, output, base):
171     '''Generate pot file from src/frontends/qt4/ui/*.ui'''
172     output = open(output, 'w')
173     pat = re.compile(r'\s*<string>(.*)</string>')
174     prop = re.compile(r'\s*<property.*name.*=.*shortcut')
175     for src in input_files:
176         input = open(src)
177         skipNextLine = False
178         for lineno, line in enumerate(input.readlines()):
179             # skip the line after <property name=shortcut>
180             if skipNextLine:
181                 skipNextLine = False
182                 continue
183             if prop.match(line):
184                 skipNextLine = True
185                 continue
186             # get lines that match <string>...</string>
187             if pat.match(line):
188                 (string,) = pat.match(line).groups()
189                 string = string.replace('&amp;', '&').replace('&lt;', '<').replace('&gt;', '>')
190                 string = string.replace('\\', '\\\\').replace('"', r'\"')
191                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
192                     (relativePath(src, base), lineno+1, string) 
193         input.close()
194     output.close()
195
196
197 def languages_l10n(input_files, output, base):
198     '''Generate pot file from lib/language'''
199     output = open(output, 'w')
200     # assuming only one language file
201     reg = re.compile('[\w-]+\s+[\w"]+\s+"([\w \-\(\),]+)"\s+(true|false)\s+[\w-]+\s+\w+\s+"[^"]*"')
202     input = open(input_files[0])
203     for lineno, line in enumerate(input.readlines()):
204         if line[0] == '#':
205             continue
206         # From:
207         #   afrikaans   afrikaans       "Afrikaans"     false  iso8859-15 af_ZA  ""
208         # To:
209         #   #: lib/languages:2
210         #   msgid "Afrikaans"
211         #   msgstr ""
212         if reg.match(line):
213             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
214                 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
215         else:
216             print "Error: Unable to handle line:"
217             print line
218             # No need to abort if the parsing fails (e.g. "ignore" language has no encoding)
219             # sys.exit(1)
220     input.close()
221     output.close()
222
223
224 def external_l10n(input_files, output, base):
225     '''Generate pot file from lib/external_templates'''
226     output = open(output, 'w')
227     Template = re.compile(r'^Template\s+(.*)')
228     GuiName = re.compile(r'\s*GuiName\s+(.*)')
229     HelpTextStart = re.compile(r'\s*HelpText\s')
230     HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
231     HelpTextEnd = re.compile(r'\s*HelpTextEnd\s')
232     i = -1
233     for src in input_files:
234         input = open(src)
235         inHelp = False
236         hadHelp = False
237         prev_help_string = ''
238         for lineno, line in enumerate(input.readlines()):
239             if Template.match(line):
240                 (string,) = Template.match(line).groups()
241             elif GuiName.match(line):
242                 (string,) = GuiName.match(line).groups()
243             elif inHelp:
244                 if HelpTextEnd.match(line):
245                     if hadHelp:
246                         print >> output, '\nmsgstr ""\n'
247                     inHelp = False
248                     hadHelp = False
249                     prev_help_string = ''
250                 elif HelpTextSection.match(line):
251                     (help_string,) = HelpTextSection.match(line).groups()
252                     help_string = help_string.replace('"', '')
253                     if help_string != "" and prev_help_string == '':
254                         print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
255                             (relativePath(src, base), lineno+1, help_string)
256                         hadHelp = True
257                     elif help_string != "":
258                         print >> output, '"%s\\n"' % help_string
259                     prev_help_string = help_string
260             elif HelpTextStart.match(line):
261                 inHelp = True
262                 prev_help_string = ''
263             else:
264                 continue
265             string = string.replace('"', '')
266             if string != "" and not inHelp:
267                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
268                     (relativePath(src, base), lineno+1, string)
269         input.close()
270     output.close()
271
272
273 def formats_l10n(input_files, output, base):
274     '''Generate pot file from configure.py'''
275     output = open(output, 'w')
276     GuiName = re.compile(r'.*\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*')
277     GuiName2 = re.compile(r'.*\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*')
278     input = open(input_files[0])
279     for lineno, line in enumerate(input.readlines()):
280         label = ""
281         labelsc = ""
282         if GuiName.match(line):
283             label = GuiName.match(line).group(1)
284             shortcut = GuiName.match(line).group(2).replace('"', '')
285         elif GuiName2.match(line):
286             label = GuiName2.match(line).group(1)
287             shortcut = GuiName2.match(line).group(2).replace('"', '')
288         else:
289             continue
290         label = label.replace('\\', '\\\\').replace('"', '')
291         if shortcut != "":
292             labelsc = label + "|" + shortcut
293         if label != "":
294             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
295                 (relativePath(input_files[0], base), lineno+1, label)
296         if labelsc != "":
297             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
298                 (relativePath(input_files[0], base), lineno+1, labelsc)
299     input.close()
300     output.close()
301
302
303 def encodings_l10n(input_files, output, base):
304     '''Generate pot file from lib/encodings'''
305     output = open(output, 'w')
306     # assuming only one encodings file
307     #                 Encoding utf8      utf8    "Unicode (utf8)" UTF-8    variable inputenc
308     reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
309     input = open(input_files[0])
310     for lineno, line in enumerate(input.readlines()):
311         if not line.startswith('Encoding'):
312             continue
313         if reg.match(line):
314             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
315                 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
316         else:
317             print "Error: Unable to handle line:"
318             print line
319             # No need to abort if the parsing fails
320             # sys.exit(1)
321     input.close()
322     output.close()
323
324
325
326 Usage = '''
327 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] -t|--type input_type input_files
328
329 where 
330     --base:
331         path to the top source directory. default to '.'
332     --output:
333         output pot file, default to './lyx.pot'
334     --input_type can be
335         ui: lib/ui/*
336         layouts: lib/layouts/*
337         qt4: qt4 ui files
338         languages: file lib/languages
339         encodings: file lib/encodings
340         external: external templates file
341         formats: formats predefined in lib/configure.py
342 '''
343
344 if __name__ == '__main__':
345     input_type = None
346     output = 'lyx.pot'
347     base = '.'
348     #
349     optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:',
350         ['help', 'type=', 'output=', 'base='])
351     for (opt, value) in optlist:
352         if opt in ['-h', '--help']:
353             print Usage
354             sys.exit(0)
355         elif opt in ['-o', '--output']:
356             output = value
357         elif opt in ['-b', '--base']:
358             base = value
359         elif opt in ['-t', '--type']:
360             input_type = value
361     if input_type not in ['ui', 'layouts', 'modules', 'qt4', 'languages', 'encodings', 'external', 'formats'] or output is None:
362         print 'Wrong input type or output filename.'
363         sys.exit(1)
364     if input_type == 'ui':
365         ui_l10n(args, output, base)
366     elif input_type == 'layouts':
367         layouts_l10n(args, output, base)
368     elif input_type == 'qt4':
369         qt4_l10n(args, output, base)
370     elif input_type == 'external':
371         external_l10n(args, output, base)
372     elif input_type == 'formats':
373         formats_l10n(args, output, base)
374     elif input_type == 'encodings':
375         encodings_l10n(args, output, base)
376     else:
377         languages_l10n(args, output, base)
378
379