]> git.lyx.org Git - features.git/blob - po/lyx_pot.py
lyx_pot.py cannot deal with raw newlines in ui files. So, use the
[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     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                 #Flex:xxx is not used in translation
176                 #writeString(out, src, base, lineno, string)
177                 m = FlexCheck.search(string)
178                 if m:
179                   writeString(out, src, base, lineno, m.group(1))
180                 continue
181             res = Category.search(line)
182             if res != None:
183                 string = res.group(1)
184                 writeString(out, src, base, lineno, string)
185                 continue
186             res = CounterFormat.search(line)
187             if res != None:
188                 string = res.group(1)
189                 writeString(out, src, base, lineno, string)
190                 continue
191             res = CiteFormat.search(line)
192             if res != None:
193                 readingCiteFormats = True
194             res = End.search(line)
195             if res != None and readingCiteFormats:
196                 readingCiteFormats = False
197             if readingCiteFormats:
198                 res = KeyVal.search(line)
199                 if res != None:
200                     val = res.group(1)
201                     writeString(out, src, base, lineno, val)
202                 
203     out.close()
204
205
206 def qt4_l10n(input_files, output, base):
207     '''Generate pot file from src/frontends/qt4/ui/*.ui'''
208     output = open(output, 'w')
209     pat = re.compile(r'\s*<string>(.*)</string>')
210     prop = re.compile(r'\s*<property.*name.*=.*shortcut')
211     for src in input_files:
212         input = open(src)
213         skipNextLine = False
214         for lineno, line in enumerate(input.readlines()):
215             # skip the line after <property name=shortcut>
216             if skipNextLine:
217                 skipNextLine = False
218                 continue
219             if prop.match(line):
220                 skipNextLine = True
221                 continue
222             # get lines that match <string>...</string>
223             if pat.match(line):
224                 (string,) = pat.match(line).groups()
225                 string = string.replace('&amp;', '&').replace('&lt;', '<').replace('&gt;', '>')
226                 string = string.replace('\\', '\\\\').replace('"', r'\"')
227                 string = string.replace('&#x0a;', r'\n')
228                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
229                     (relativePath(src, base), lineno+1, string)
230         input.close()
231     output.close()
232
233
234 def languages_l10n(input_files, output, base):
235     '''Generate pot file from lib/languages'''
236     out = open(output, 'w')
237     GuiName = re.compile(r'^[^#]*GuiName\s+(.*)')
238     
239     for src in input_files:
240         descStartLine = -1
241         descLines = []
242         lineno = 0
243         for line in open(src).readlines():
244             lineno += 1
245             res = GuiName.search(line)
246             if res != None:
247                 string = res.group(1)
248                 writeString(out, src, base, lineno, string)
249                 continue
250                
251     out.close()
252
253
254 def external_l10n(input_files, output, base):
255     '''Generate pot file from lib/external_templates'''
256     output = open(output, 'w')
257     Template = re.compile(r'^Template\s+(.*)')
258     GuiName = re.compile(r'\s*GuiName\s+(.*)')
259     HelpTextStart = re.compile(r'\s*HelpText\s')
260     HelpTextSection = re.compile(r'\s*(\S.*)\s*$')
261     HelpTextEnd = re.compile(r'\s*HelpTextEnd\s')
262     i = -1
263     for src in input_files:
264         input = open(src)
265         inHelp = False
266         hadHelp = False
267         prev_help_string = ''
268         for lineno, line in enumerate(input.readlines()):
269             if Template.match(line):
270                 (string,) = Template.match(line).groups()
271             elif GuiName.match(line):
272                 (string,) = GuiName.match(line).groups()
273             elif inHelp:
274                 if HelpTextEnd.match(line):
275                     if hadHelp:
276                         print >> output, '\nmsgstr ""\n'
277                     inHelp = False
278                     hadHelp = False
279                     prev_help_string = ''
280                 elif HelpTextSection.match(line):
281                     (help_string,) = HelpTextSection.match(line).groups()
282                     help_string = help_string.replace('"', '')
283                     if help_string != "" and prev_help_string == '':
284                         print >> output, '#: %s:%d\nmsgid ""\n"%s\\n"' % \
285                             (relativePath(src, base), lineno+1, help_string)
286                         hadHelp = True
287                     elif help_string != "":
288                         print >> output, '"%s\\n"' % help_string
289                     prev_help_string = help_string
290             elif HelpTextStart.match(line):
291                 inHelp = True
292                 prev_help_string = ''
293             else:
294                 continue
295             string = string.replace('"', '')
296             if string != "" and not inHelp:
297                 print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
298                     (relativePath(src, base), lineno+1, string)
299         input.close()
300     output.close()
301
302
303 def formats_l10n(input_files, output, base):
304     '''Generate pot file from configure.py'''
305     output = open(output, 'w')
306     GuiName = re.compile(r'.*\Format\s+\S+\s+\S+\s+"([^"]*)"\s+(\S*)\s+.*')
307     GuiName2 = re.compile(r'.*\Format\s+\S+\s+\S+\s+([^"]\S+)\s+(\S*)\s+.*')
308     input = open(input_files[0])
309     for lineno, line in enumerate(input.readlines()):
310         label = ""
311         labelsc = ""
312         if GuiName.match(line):
313             label = GuiName.match(line).group(1)
314             shortcut = GuiName.match(line).group(2).replace('"', '')
315         elif GuiName2.match(line):
316             label = GuiName2.match(line).group(1)
317             shortcut = GuiName2.match(line).group(2).replace('"', '')
318         else:
319             continue
320         label = label.replace('\\', '\\\\').replace('"', '')
321         if shortcut != "":
322             labelsc = label + "|" + shortcut
323         if label != "":
324             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
325                 (relativePath(input_files[0], base), lineno+1, label)
326         if labelsc != "":
327             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
328                 (relativePath(input_files[0], base), lineno+1, labelsc)
329     input.close()
330     output.close()
331
332
333 def encodings_l10n(input_files, output, base):
334     '''Generate pot file from lib/encodings'''
335     output = open(output, 'w')
336     # assuming only one encodings file
337     #                 Encoding utf8      utf8    "Unicode (utf8)" UTF-8    variable inputenc
338     reg = re.compile('Encoding [\w-]+\s+[\w-]+\s+"([\w \-\(\)]+)"\s+[\w-]+\s+(fixed|variable)\s+\w+.*')
339     input = open(input_files[0])
340     for lineno, line in enumerate(input.readlines()):
341         if not line.startswith('Encoding'):
342             continue
343         if reg.match(line):
344             print >> output, '#: %s:%d\nmsgid "%s"\nmsgstr ""\n' % \
345                 (relativePath(input_files[0], base), lineno+1, reg.match(line).groups()[0])
346         else:
347             print "Error: Unable to handle line:"
348             print line
349             # No need to abort if the parsing fails
350             # sys.exit(1)
351     input.close()
352     output.close()
353
354
355
356 Usage = '''
357 lyx_pot.py [-b|--base top_src_dir] [-o|--output output_file] [-h|--help] [-s|src_file filename] -t|--type input_type input_files
358
359 where
360     --base:
361         path to the top source directory. default to '.'
362     --output:
363         output pot file, default to './lyx.pot'
364     --src_file
365         filename that contains a list of input files in each line
366     --input_type can be
367         ui: lib/ui/*
368         layouts: lib/layouts/*
369         qt4: qt4 ui files
370         languages: file lib/languages
371         encodings: file lib/encodings
372         external: external templates file
373         formats: formats predefined in lib/configure.py
374 '''
375
376 if __name__ == '__main__':
377     input_type = None
378     output = 'lyx.pot'
379     base = '.'
380     input_files = []
381     #
382     optlist, args = getopt.getopt(sys.argv[1:], 'ht:o:b:s:',
383         ['help', 'type=', 'output=', 'base=', 'src_file='])
384     for (opt, value) in optlist:
385         if opt in ['-h', '--help']:
386             print Usage
387             sys.exit(0)
388         elif opt in ['-o', '--output']:
389             output = value
390         elif opt in ['-b', '--base']:
391             base = value
392         elif opt in ['-t', '--type']:
393             input_type = value
394         elif opt in ['-s', '--src_file']:
395             input_files = [f.strip() for f in open(value)]
396
397     if input_type not in ['ui', 'layouts', 'modules', 'qt4', 'languages', 'encodings', 'external', 'formats'] or output is None:
398         print 'Wrong input type or output filename.'
399         sys.exit(1)
400
401     input_files += args
402
403     if input_type == 'ui':
404         ui_l10n(input_files, output, base)
405     elif input_type == 'layouts':
406         layouts_l10n(input_files, output, base)
407     elif input_type == 'qt4':
408         qt4_l10n(input_files, output, base)
409     elif input_type == 'external':
410         external_l10n(input_files, output, base)
411     elif input_type == 'formats':
412         formats_l10n(input_files, output, base)
413     elif input_type == 'encodings':
414         encodings_l10n(input_files, output, base)
415     else:
416         languages_l10n(input_files, output, base)
417
418