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