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