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