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