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>
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.
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.
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.
20 from parser_tools import get_value, check_token, find_token,\
21 find_tokens, find_end_of
28 import lyx2lyx_version
29 version_lyx2lyx = lyx2lyx_version.version
31 default_debug_level = 2
33 ####################################################################
34 # Private helper functions
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")
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.
46 generate_minor_versions("1.2", 4) ->
47 [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
49 return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
52 # End of helper functions
53 ####################################################################
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.]*)")
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))]
80 " Returns a list with supported file formats."
82 for version in format_relation:
83 for format in version[1]:
84 if format not in formats:
85 formats.append(format)
90 " Returns the more recent file format available."
91 return format_relation[-1][1][-1]
94 def get_backend(textclass):
95 " For _textclass_ returns its backend."
96 if textclass == "linuxdoc" or textclass == "manpage":
98 if textclass[:7] == "docbook":
104 " Remove end of line char(s)."
105 if line[-2:-1] == '\r':
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 == "":
117 # python does not know the alias latin9
118 if inputencoding == "latin9":
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):
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.
135 self.choose_io(input, output)
138 self.err = open(error, "w")
140 self.err = sys.stderr
143 self.try_hard = try_hard
146 self.end_format = self.lyxformat(end_format)
148 self.end_format = get_end_format()
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 = ''
160 self.encoding = "auto"
163 def warning(self, message, debug_level= default_debug_level):
164 " Emits warning to self.error, if the debug_level is less than the self.debug."
165 if debug_level <= self.debug:
166 self.err.write("Warning: " + message + "\n")
169 def error(self, message):
170 " Emits a warning and exits if not in try_hard mode."
171 self.warning(message)
172 if not self.try_hard:
173 self.warning("Quiting.")
180 """Reads a file into the self.header and self.body parts, from self.input."""
183 line = self.input.readline()
185 self.error("Invalid LyX file.")
187 line = trim_eol(line)
188 if check_token(line, '\\begin_preamble'):
190 line = self.input.readline()
192 self.error("Invalid LyX file.")
194 line = trim_eol(line)
195 if check_token(line, '\\end_preamble'):
198 if line.split()[:0] in ("\\layout", "\\begin_layout", "\\begin_body"):
199 self.warning("Malformed LyX file: Missing '\\end_preamble'.")
200 self.warning("Adding it now and hoping for the best.")
202 self.preamble.append(line)
204 if check_token(line, '\\end_preamble'):
211 if line.split()[0] in ("\\layout", "\\begin_layout", "\\begin_body"):
212 self.body.append(line)
215 self.header.append(line)
217 self.textclass = get_value(self.header, "\\textclass", 0)
218 self.backend = get_backend(self.textclass)
219 self.format = self.read_format()
220 self.language = get_value(self.header, "\\language", 0, default = "english")
221 self.inputencoding = get_value(self.header, "\\inputencoding", 0, default = "auto")
222 self.encoding = get_encoding(self.language, self.inputencoding)
223 self.initial_version = self.read_version()
225 # Second pass over header and preamble, now we know the file encoding
226 for i in range(len(self.header)):
227 self.header[i] = self.header[i].decode(self.encoding)
228 for i in range(len(self.preamble)):
229 self.preamble[i] = self.preamble[i].decode(self.encoding)
233 line = self.input.readline().decode(self.encoding)
236 self.body.append(trim_eol(line))
240 " Writes the LyX file to self.output."
245 i = find_token(self.header, '\\textclass', 0) + 1
246 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
248 self.error("Malformed LyX file: Missing '\\textclass'.")
250 header = self.header[:i] + preamble + self.header[i:]
254 for line in header + [''] + self.body:
255 self.output.write(line.encode(self.encoding)+"\n")
258 def choose_io(self, input, output):
259 """Choose input and output streams, dealing transparently with
263 self.output = open(output, "wb")
265 self.output = sys.stdout
267 if input and input != '-':
268 self.dir = os.path.dirname(os.path.abspath(input))
270 gzip.open(input).readline()
271 self.input = gzip.open(input)
272 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
274 self.input = open(input)
277 self.input = sys.stdin
280 def lyxformat(self, format):
281 " Returns the file format representation, an integer."
282 result = format_re.match(format)
284 format = int(result.group(1) + result.group(2))
288 self.error(str(format) + ": " + "Invalid LyX file.")
290 if format in formats_list():
293 self.error(str(format) + ": " + "Format not supported.")
297 def read_version(self):
298 """ Searchs for clues of the LyX version used to write the file, returns the
299 most likely value, or None otherwise."""
300 for line in self.header:
304 line = line.replace("fix",".")
305 result = original_version.match(line)
307 # Special know cases: reLyX and KLyX
308 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
311 res = result.group(1)
314 #self.warning("Version %s" % result.group(1))
316 self.warning(str(self.header[:2]))
320 def set_version(self):
321 " Set the header with the version used."
322 self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx
323 if self.header[1][0] == '#':
327 def read_format(self):
328 " Read from the header the fileformat of the present LyX file."
329 for line in self.header:
330 result = fileformat.match(line)
332 return self.lyxformat(result.group(1))
334 self.error("Invalid LyX File.")
338 def set_format(self):
339 " Set the file format of the file, in the header."
340 if self.format <= 217:
341 format = str(float(self.format)/100)
343 format = str(self.format)
344 i = find_token(self.header, "\\lyxformat", 0)
345 self.header[i] = "\\lyxformat %s" % format
348 def set_parameter(self, param, value):
349 " Set the value of the header parameter."
350 i = find_token(self.header, '\\' + param, 0)
352 self.warning('Parameter not found in the header: %s' % param, 3)
354 self.header[i] = '\\%s %s' % (param, str(value))
357 def is_default_layout(self, layout):
358 " Check whether a layout is the default layout of this class."
359 # FIXME: Check against the real text class default layout
360 if layout == 'Standard' or layout == self.default_layout:
366 "Convert from current (self.format) to self.end_format."
367 mode, convertion_chain = self.chain()
368 self.warning("convertion chain: " + str(convertion_chain), 3)
370 for step in convertion_chain:
371 steps = getattr(__import__("lyx_" + step), mode)
373 self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1)
375 self.error("The convertion to an older format (%s) is not implemented." % self.format)
377 multi_conv = len(steps) != 1
378 for version, table in steps:
380 (self.format >= version and mode == "convert") or\
381 (self.format <= version and mode == "revert"):
389 self.warning("An error ocurred in %s, %s" % (version, str(conv)),
391 if not self.try_hard:
395 self.warning("%lf: Elapsed time on %s" % (time.time() - init_t, str(conv)),
396 default_debug_level + 1)
398 self.format = version
399 if self.end_format == self.format:
404 """ This is where all the decisions related with the convertion are taken.
405 It returns a list of modules needed to convert the LyX file from
406 self.format to self.end_format"""
408 self.start = self.format
412 for rel in format_relation:
413 if self.initial_version in rel[2]:
415 initial_step = rel[0]
419 if not correct_version:
421 self.warning("Version does not match file format, discarding it. (Version %s, format %d)" %(self.initial_version, self.format))
422 for rel in format_relation:
424 initial_step = rel[0]
427 # This should not happen, really.
428 self.error("Format not supported.")
430 # Find the final step
431 for rel in format_relation:
432 if self.end_format in rel[1]:
436 self.error("Format not supported.")
438 # Convertion mode, back or forth
440 if (initial_step, self.start) < (final_step, self.end_format):
443 for step in format_relation:
444 if initial_step <= step[0] <= final_step:
445 if first_step and len(step[1]) == 1:
448 steps.append(step[0])
451 relation_format = format_relation[:]
452 relation_format.reverse()
455 for step in relation_format:
456 if final_step <= step[0] <= initial_step:
457 steps.append(step[0])
460 if last_step[1][-1] == self.end_format:
466 def get_toc(self, depth = 4):
467 " Returns the TOC of this LyX document."
468 paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4}
469 allowed_insets = ['Quotes']
470 allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix", "\\leftindent"
473 for section in paragraphs_filter.keys():
474 sections.append('\\begin_layout %s' % section)
479 i = find_tokens(self.body, sections, i)
483 j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
485 self.warning('Incomplete file.', 0)
488 section = self.body[i].split()[1]
489 if section[-1] == '*':
490 section = section[:-1]
495 # skip paragraph parameters
496 while not self.body[k].strip() or self.body[k].split()[0] in allowed_parameters:
500 if check_token(self.body[k], '\\begin_inset'):
501 inset = self.body[k].split()[1]
502 end = find_end_of_inset(self.body, k)
503 if end == -1 or end > j:
504 self.warning('Malformed file.', 0)
506 if inset in allowed_insets:
507 par.extend(self.body[k: end+1])
510 par.append(self.body[k])
513 # trim empty lines in the end.
514 while par[-1].strip() == '' and par:
517 toc_par.append(Paragraph(section, par))
524 class File(LyX_Base):
525 " This class reads existing LyX files."
526 def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0):
527 LyX_Base.__init__(self, end_format, input, output, error, debug, try_hard)
531 class NewFile(LyX_Base):
532 " This class is to create new LyX files."
533 def set_header(self, **params):
536 "#LyX xxxx created this file. For more info see http://www.lyx.org/",
540 "\\textclass article",
541 "\\language english",
542 "\\inputencoding auto",
543 "\\font_roman default",
544 "\\font_sans default",
545 "\\font_typewriter default",
546 "\\font_default_family default",
549 "\\font_sf_scale 100",
550 "\\font_tt_scale 100",
551 "\\graphics default",
552 "\\paperfontsize default",
553 "\\papersize default",
554 "\\use_geometry false",
556 "\\cite_engine basic",
557 "\\use_bibtopic false",
558 "\\paperorientation portrait",
561 "\\paragraph_separation indent",
563 "\\quotes_language english",
566 "\\paperpagestyle default",
567 "\\tracking_changes false",
570 self.format = get_end_format()
572 self.set_parameter(param, params[param])
575 def set_body(self, paragraphs):
576 self.body.extend(['\\begin_body',''])
578 for par in paragraphs:
579 self.body.extend(par.asLines())
581 self.body.extend(['','\\end_body', '\\end_document'])
585 # unfinished implementation, it is missing the Text and Insets representation.
586 " This class represents the LyX paragraphs."
587 def __init__(self, name, body=[], settings = [], child = []):
589 name: paragraph name.
590 body: list of lines of body text.
591 child: list of paragraphs that descend from this paragraph.
595 self.settings = settings
599 " Converts the paragraph to a list of strings, representing it in the LyX file."
600 result = ['','\\begin_layout %s' % self.name]
601 result.extend(self.settings)
603 result.extend(self.body)
604 result.append('\\end_layout')
609 result.append('\\begin_deeper')
610 for node in self.child:
611 result.extend(node.asLines())
612 result.append('\\end_deeper')
618 " This class represents the LyX insets."
623 " This class represents simple chuncks of text."