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