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