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