]> git.lyx.org Git - features.git/blob - lib/lyx2lyx/LyX.py
6d9605f06a1e0e7a8ba1c53ea1f7e018ad1db065
[features.git] / lib / lyx2lyx / LyX.py
1 # This file is part of lyx2lyx
2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2002-2004 Dekel Tsur <dekel@lyx.org>, José Matos <jamatos@lyx.org>
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 from parser_tools import get_value, check_token, find_token,\
20      find_tokens, find_end_of
21 import os.path
22 import gzip
23 import sys
24 import re
25 import string
26 import time
27
28 import lyx2lyx_version
29 version_lyx2lyx = lyx2lyx_version.version
30
31 default_debug_level = 2
32
33 ####################################################################
34 # Private helper functions
35
36 def find_end_of_inset(lines, i):
37     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
38
39 # End of helper functions
40 ####################################################################
41
42
43 # Regular expressions used
44 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
45 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
46 original_version = re.compile(r"\#LyX (\S*)")
47
48 ##
49 # file format information:
50 #  file, supported formats, stable release versions
51 format_relation = [("0_10",  [210], ["0.10.7","0.10"]),
52                    ("0_12",  [215], ["0.12","0.12.1","0.12"]),
53                    ("1_0_0", [215], ["1.0.0","1.0"]),
54                    ("1_0_1", [215], ["1.0.1","1.0.2","1.0.3","1.0.4", "1.1.2","1.1"]),
55                    ("1_1_4", [215], ["1.1.4","1.1"]),
56                    ("1_1_5", [216], ["1.1.5","1.1.5fix1","1.1.5fix2","1.1"]),
57                    ("1_1_6", [217], ["1.1.6","1.1.6fix1","1.1.6fix2","1.1"]),
58                    ("1_1_6fix3", [218], ["1.1.6fix3","1.1.6fix4","1.1"]),
59                    ("1_2", [220], ["1.2.0","1.2.1","1.2.3","1.2.4","1.2"]),
60                    ("1_3", [221], ["1.3.0","1.3.1","1.3.2","1.3.3","1.3.4","1.3.5","1.3.6","1.3.7","1.3"]),
61                    ("1_4", range(222,246), ["1.4.0", "1.4.1", "1.4.2svn"]),
62                    ("1_5", range(246,249), ["1.5.0svn","1.5"])]
63
64
65 def formats_list():
66     " Returns a list with supported file formats."
67     formats = []
68     for version in format_relation:
69         for format in version[1]:
70             if format not in formats:
71                 formats.append(format)
72     return formats
73
74
75 def get_end_format():
76     " Returns the more recent file format available."
77     return format_relation[-1][1][-1]
78
79
80 def get_backend(textclass):
81     " For _textclass_ returns its backend."
82     if textclass == "linuxdoc" or textclass == "manpage":
83         return "linuxdoc"
84     if textclass[:7] == "docbook":
85         return "docbook"
86     return "latex"
87
88
89 def trim_eol(line):
90     " Remove end of line char(s)."
91     if line[-2:-1] == '\r':
92         return line[:-2]
93     else:
94         return line[:-1]
95
96
97 ##
98 # Class
99 #
100 class LyX_Base:
101     """This class carries all the information of the LyX file."""
102     def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0):
103         """Arguments:
104         end_format: final format that the file should be converted. (integer)
105         input: the name of the input source, if empty resort to standard input.
106         output: the name of the output file, if empty use the standard output.
107         error: the name of the error file, if empty use the standard error.
108         debug: debug level, O means no debug, as its value increases be more verbose.
109         """
110         self.choose_io(input, output)
111
112         if error:
113             self.err = open(error, "w")
114         else:
115             self.err = sys.stderr
116
117         self.debug = debug
118         self.try_hard = try_hard
119
120         if end_format:
121             self.end_format = self.lyxformat(end_format)
122         else:
123             self.end_format = get_end_format()
124
125         self.backend = "latex"
126         self.textclass = "article"
127         # This is a hack: We use '' since we don't know the default
128         # layout of the text class. LyX will parse it as default layout.
129         # FIXME: Read the layout file and use the real default layout
130         self.default_layout = ''
131         self.header = []
132         self.preamble = []
133         self.body = []
134         self.status = 0
135
136
137     def warning(self, message, debug_level= default_debug_level):
138         " Emits warning to self.error, if the debug_level is less than the self.debug."
139         if debug_level <= self.debug:
140             self.err.write("Warning: " + message + "\n")
141
142
143     def error(self, message):
144         " Emits a warning and exits if not in try_hard mode."
145         self.warning(message)
146         if not self.try_hard:
147             self.warning("Quiting.")
148             sys.exit(1)
149
150         self.status = 2
151
152
153     def read(self):
154         """Reads a file into the self.header and self.body parts, from self.input."""
155
156         while 1:
157             line = self.input.readline()
158             if not line:
159                 self.error("Invalid LyX file.")
160
161             line = trim_eol(line)
162             if check_token(line, '\\begin_preamble'):
163                 while 1:
164                     line = self.input.readline()
165                     if not line:
166                         self.error("Invalid LyX file.")
167
168                     line = trim_eol(line)
169                     if check_token(line, '\\end_preamble'):
170                         break
171                     
172                     if string.split(line)[:0] in ("\\layout", "\\begin_layout", "\\begin_body"):
173                         self.warning("Malformed LyX file: Missing '\\end_preamble'.")
174                         self.warning("Adding it now and hoping for the best.")
175
176                     self.preamble.append(line)
177
178             if check_token(line, '\\end_preamble'):
179                 continue
180
181             line = string.strip(line)
182             if not line:
183                 continue
184
185             if string.split(line)[0] in ("\\layout", "\\begin_layout", "\\begin_body"):
186                 self.body.append(line)
187                 break
188
189             self.header.append(line)
190
191         while 1:
192             line = self.input.readline()
193             if not line:
194                 break
195             self.body.append(trim_eol(line))
196
197         self.textclass = get_value(self.header, "\\textclass", 0)
198         self.backend = get_backend(self.textclass)
199         self.format  = self.read_format()
200         self.language = get_value(self.header, "\\language", 0)
201         if self.language == "":
202             self.language = "english"
203         self.initial_version = self.read_version()
204
205
206     def write(self):
207         " Writes the LyX file to self.output."
208         self.set_version()
209         self.set_format()
210
211         if self.preamble:
212             i = find_token(self.header, '\\textclass', 0) + 1
213             preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
214             if i == 0:
215                 self.error("Malformed LyX file: Missing '\\textclass'.")
216             else:
217                 header = self.header[:i] + preamble + self.header[i:]
218         else:
219             header = self.header
220
221         for line in header + [''] + self.body:
222             self.output.write(line+"\n")
223
224
225     def choose_io(self, input, output):
226         """Choose input and output streams, dealing transparently with
227         compressed files."""
228
229         if output:
230             self.output = open(output, "wb")
231         else:
232             self.output = sys.stdout
233
234         if input and input != '-':
235             self.dir = os.path.dirname(os.path.abspath(input))
236             try:
237                 gzip.open(input).readline()
238                 self.input = gzip.open(input)
239                 self.output = gzip.GzipFile(mode="wb", fileobj=self.output) 
240             except:
241                 self.input = open(input)
242         else:
243             self.dir = ''
244             self.input = sys.stdin
245
246
247     def lyxformat(self, format):
248         " Returns the file format representation, an integer."
249         result = format_re.match(format)
250         if result:
251             format = int(result.group(1) + result.group(2))
252         else:
253             self.error(str(format) + ": " + "Invalid LyX file.")
254
255         if format in formats_list():
256             return format
257
258         self.error(str(format) + ": " + "Format not supported.")
259         return None
260
261
262     def read_version(self):
263         """ Searchs for clues of the LyX version used to write the file, returns the
264         most likely value, or None otherwise."""
265         for line in self.header:
266             if line[0] != "#":
267                 return None
268
269             result = original_version.match(line)
270             if result:
271                 return result.group(1)
272         return None
273
274
275     def set_version(self):
276         " Set the header with the version used."
277         self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx
278         if self.header[1][0] == '#':
279             del self.header[1]
280
281
282     def read_format(self):
283         " Read from the header the fileformat of the present LyX file."
284         for line in self.header:
285             result = fileformat.match(line)
286             if result:
287                 return self.lyxformat(result.group(1))
288         else:
289             self.error("Invalid LyX File.")
290         return None
291
292
293     def set_format(self):
294         " Set the file format of the file, in the header."
295         if self.format <= 217:
296             format = str(float(self.format)/100)
297         else:
298             format = str(self.format)
299         i = find_token(self.header, "\\lyxformat", 0)
300         self.header[i] = "\\lyxformat %s" % format
301
302
303     def set_parameter(self, param, value):
304         " Set the value of the header parameter."
305         i = find_token(self.header, '\\' + param, 0)
306         if i == -1:
307             self.warning('Parameter not found in the header: %s' % param, 3)
308             return
309         self.header[i] = '\\%s %s' % (param, str(value))
310
311
312     def is_default_layout(self, layout):
313         " Check whether a layout is the default layout of this class."
314         # FIXME: Check against the real text class default layout
315         if layout == 'Standard' or layout == self.default_layout:
316             return 1
317         return 0
318
319
320     def convert(self):
321         "Convert from current (self.format) to self.end_format."
322         mode, convertion_chain = self.chain()
323         self.warning("convertion chain: " + str(convertion_chain), 3)
324
325         for step in convertion_chain:
326             steps = getattr(__import__("lyx_" + step), mode)
327
328             self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1)
329             if not steps:
330                     self.error("The convertion to an older format (%s) is not implemented." % self.format)
331
332             multi_conv = len(steps) != 1
333             for version, table in steps:
334                 if multi_conv and \
335                    (self.format >= version and mode == "convert") or\
336                    (self.format <= version and mode == "revert"):
337                     continue
338
339                 for conv in table:
340                     init_t = time.time()
341                     try:
342                         conv(self)
343                     except:
344                         self.warning("An error ocurred in %s, %s" % (version, str(conv)),
345                                      default_debug_level)
346                         if not self.try_hard:
347                             raise
348                         self.status = 2
349                     else:
350                         self.warning("%lf: Elapsed time on %s"  % (time.time() - init_t, str(conv)),
351                                      default_debug_level + 1)
352
353                 self.format = version
354                 if self.end_format == self.format:
355                     return
356
357
358     def chain(self):
359         """ This is where all the decisions related with the convertion are taken.
360         It returns a list of modules needed to convert the LyX file from
361         self.format to self.end_format"""
362
363         self.start =  self.format
364         format = self.format
365         correct_version = 0
366
367         for rel in format_relation:
368             if self.initial_version in rel[2]:
369                 if format in rel[1]:
370                     initial_step = rel[0]
371                     correct_version = 1
372                     break
373
374         if not correct_version:
375             if format <= 215:
376                 self.warning("Version does not match file format, discarding it.")
377             for rel in format_relation:
378                 if format in rel[1]:
379                     initial_step = rel[0]
380                     break
381             else:
382                 # This should not happen, really.
383                 self.error("Format not supported.")
384
385         # Find the final step
386         for rel in format_relation:
387             if self.end_format in rel[1]:
388                 final_step = rel[0]
389                 break
390         else:
391             self.error("Format not supported.")
392
393         # Convertion mode, back or forth
394         steps = []
395         if (initial_step, self.start) < (final_step, self.end_format):
396             mode = "convert"
397             first_step = 1
398             for step in format_relation:
399                 if  initial_step <= step[0] <= final_step:
400                     if first_step and len(step[1]) == 1:
401                         first_step = 0
402                         continue
403                     steps.append(step[0])
404         else:
405             mode = "revert"
406             relation_format = format_relation[:]
407             relation_format.reverse()
408             last_step = None
409
410             for step in relation_format:
411                 if  final_step <= step[0] <= initial_step:
412                     steps.append(step[0])
413                     last_step = step
414
415             if last_step[1][-1] == self.end_format:
416                 steps.pop()
417
418         return mode, steps
419
420
421     def get_toc(self, depth = 4):
422         " Returns the TOC of this LyX document."
423         paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4}
424         allowed_insets = ['Quotes']
425         allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix", "\\leftindent"
426
427         sections = []
428         for section in paragraphs_filter.keys():
429             sections.append('\\begin_layout %s' % section)
430
431         toc_par = []
432         i = 0
433         while 1:
434             i = find_tokens(self.body, sections, i)
435             if i == -1:
436                 break
437
438             j = find_end_of(self.body,  i + 1, '\\begin_layout', '\\end_layout')
439             if j == -1:
440                 self.warning('Incomplete file.', 0)
441                 break
442
443             section = string.split(self.body[i])[1]
444             if section[-1] == '*':
445                 section = section[:-1]
446
447             par = []
448
449             k = i + 1
450             # skip paragraph parameters
451             while not string.strip(self.body[k]) or string.split(self.body[k])[0] in allowed_parameters:
452                 k = k +1
453
454             while k < j:
455                 if check_token(self.body[k], '\\begin_inset'):
456                     inset = string.split(self.body[k])[1]
457                     end = find_end_of_inset(self.body, k)
458                     if end == -1 or end > j:
459                         self.warning('Malformed file.', 0)
460
461                     if inset in allowed_insets:
462                         par.extend(self.body[k: end+1])
463                     k = end + 1
464                 else:
465                     par.append(self.body[k])
466                     k = k + 1
467
468             # trim empty lines in the end.
469             while string.strip(par[-1]) == '' and par:
470                 par.pop()
471
472             toc_par.append(Paragraph(section, par))
473
474             i = j + 1
475
476         return toc_par
477
478
479 class File(LyX_Base):
480     " This class reads existing LyX files."
481     def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0):
482         LyX_Base.__init__(self, end_format, input, output, error, debug, try_hard)
483         self.read()
484
485
486 class NewFile(LyX_Base):
487     " This class is to create new LyX files."
488     def set_header(self, **params):
489         # set default values
490         self.header.extend([
491             "#LyX xxxx created this file. For more info see http://www.lyx.org/",
492             "\\lyxformat xxx",
493             "\\begin_document",
494             "\\begin_header",
495             "\\textclass article",
496             "\\language english",
497             "\\inputencoding auto",
498             "\\font_roman default",
499             "\\font_sans default",
500             "\\font_typewriter default",
501             "\\font_default_family default",
502             "\\font_sc false",
503             "\\font_osf false",
504             "\\font_sf_scale 100",
505             "\\font_tt_scale 100",
506             "\\graphics default",
507             "\\paperfontsize default",
508             "\\papersize default",
509             "\\use_geometry false",
510             "\\use_amsmath 1",
511             "\\cite_engine basic",
512             "\\use_bibtopic false",
513             "\\paperorientation portrait",
514             "\\secnumdepth 3",
515             "\\tocdepth 3",
516             "\\paragraph_separation indent",
517             "\\defskip medskip",
518             "\\quotes_language english",
519             "\\papercolumns 1",
520             "\\papersides 1",
521             "\\paperpagestyle default",
522             "\\tracking_changes false",
523             "\\end_header"])
524
525         self.format = get_end_format()
526         for param in params:
527             self.set_parameter(param, params[param])
528
529
530     def set_body(self, paragraphs):
531         self.body.extend(['\\begin_body',''])
532
533         for par in paragraphs:
534             self.body.extend(par.asLines())
535
536         self.body.extend(['','\\end_body', '\\end_document'])
537
538
539 class Paragraph:
540     # unfinished implementation, it is missing the Text and Insets representation.
541     " This class represents the LyX paragraphs."
542     def __init__(self, name, body=[], settings = [], child = []):
543         """ Parameters:
544         name: paragraph name.
545         body: list of lines of body text.
546         child: list of paragraphs that descend from this paragraph.
547         """
548         self.name = name
549         self.body = body
550         self.settings = settings
551         self.child = child
552
553     def asLines(self):
554         " Converts the paragraph to a list of strings, representing it in the LyX file."
555         result = ['','\\begin_layout %s' % self.name]
556         result.extend(self.settings)
557         result.append('')
558         result.extend(self.body)
559         result.append('\\end_layout')
560
561         if not self.child:
562             return result
563
564         result.append('\\begin_deeper')
565         for node in self.child:
566             result.extend(node.asLines())
567         result.append('\\end_deeper')
568
569         return result
570
571
572 class Inset:
573     " This class represents the LyX insets."
574     pass
575
576
577 class Text:
578     " This class represents simple chuncks of text."
579     pass