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