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