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