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