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