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