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
29 import lyx2lyx_version
30 version_lyx2lyx = lyx2lyx_version.version
32 default_debug_level = 2
34 ####################################################################
35 # Private helper functions
37 def find_end_of_inset(lines, i):
38 " Find beginning of inset, where lines[i] is included."
39 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
41 def generate_minor_versions(major, last_minor_version):
42 """ Generate minor versions, using major as prefix and minor
43 versions from 0 until last_minor_version, plus the generic version.
47 generate_minor_versions("1.2", 4) ->
48 [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
50 return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
53 # End of helper functions
54 ####################################################################
57 # Regular expressions used
58 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
59 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
60 original_version = re.compile(r".*?LyX ([\d.]*)")
63 # file format information:
64 # file, supported formats, stable release versions
65 format_relation = [("0_06", [200], generate_minor_versions("0.6" , 4)),
66 ("0_08", [210], generate_minor_versions("0.8" , 6) + ["0.7"]),
67 ("0_10", [210], generate_minor_versions("0.10", 7) + ["0.9"]),
68 ("0_12", [215], generate_minor_versions("0.12", 1) + ["0.11"]),
69 ("1_0", [215], generate_minor_versions("1.0" , 4)),
70 ("1_1", [215], generate_minor_versions("1.1" , 4)),
71 ("1_1_5", [216], ["1.1.5","1.1.5.1","1.1.5.2","1.1"]),
72 ("1_1_6_0", [217], ["1.1.6","1.1.6.1","1.1.6.2","1.1"]),
73 ("1_1_6_3", [218], ["1.1.6.3","1.1.6.4","1.1"]),
74 ("1_2", [220], generate_minor_versions("1.2" , 4)),
75 ("1_3", [221], generate_minor_versions("1.3" , 7)),
76 ("1_4", range(222,246), generate_minor_versions("1.4" , 4)),
77 ("1_5", range(246,270), generate_minor_versions("1.5" , 0))]
81 " Returns a list with supported file formats."
83 for version in format_relation:
84 for format in version[1]:
85 if format not in formats:
86 formats.append(format)
91 " Returns the more recent file format available."
92 return format_relation[-1][1][-1]
95 def get_backend(textclass):
96 " For _textclass_ returns its backend."
97 if textclass == "linuxdoc" or textclass == "manpage":
99 if textclass[:7] == "docbook":
105 " Remove end of line char(s)."
106 if line[-2:-1] == '\r':
112 def get_encoding(language, inputencoding, format, cjk_encoding):
115 # CJK-LyX encodes files using the current locale encoding.
116 # This means that files created by CJK-LyX can only be converted using
117 # the correct locale settings unless the encoding is given as commandline
119 if cjk_encoding == 'auto':
120 return locale.getpreferredencoding()
121 elif cjk_encoding != '':
123 from lyx2lyx_lang import lang
124 if inputencoding == "auto" or inputencoding == "default":
125 return lang[language][3]
126 if inputencoding == "":
128 # python does not know the alias latin9
129 if inputencoding == "latin9":
137 """This class carries all the information of the LyX file."""
139 def __init__(self, end_format = 0, input = "", output = "", error
140 = "", debug = default_debug_level, try_hard = 0, cjk_encoding = '',
141 language = "english", encoding = "auto"):
144 end_format: final format that the file should be converted. (integer)
145 input: the name of the input source, if empty resort to standard input.
146 output: the name of the output file, if empty use the standard output.
147 error: the name of the error file, if empty use the standard error.
148 debug: debug level, O means no debug, as its value increases be more verbose.
150 self.choose_io(input, output)
153 self.err = open(error, "w")
155 self.err = sys.stderr
158 self.try_hard = try_hard
159 self.cjk_encoding = cjk_encoding
162 self.end_format = self.lyxformat(end_format)
164 self.end_format = get_end_format()
166 self.backend = "latex"
167 self.textclass = "article"
168 # This is a hack: We use '' since we don't know the default
169 # layout of the text class. LyX will parse it as default layout.
170 # FIXME: Read the layout file and use the real default layout
171 self.default_layout = ''
176 self.encoding = encoding
177 self.language = language
180 def warning(self, message, debug_level= default_debug_level):
181 " Emits warning to self.error, if the debug_level is less than the self.debug."
182 if debug_level <= self.debug:
183 self.err.write("Warning: " + message + "\n")
186 def error(self, message):
187 " Emits a warning and exits if not in try_hard mode."
188 self.warning(message)
189 if not self.try_hard:
190 self.warning("Quiting.")
197 """Reads a file into the self.header and self.body parts, from self.input."""
200 line = self.input.readline()
202 self.error("Invalid LyX file.")
204 line = trim_eol(line)
205 if check_token(line, '\\begin_preamble'):
207 line = self.input.readline()
209 self.error("Invalid LyX file.")
211 line = trim_eol(line)
212 if check_token(line, '\\end_preamble'):
215 if line.split()[:0] in ("\\layout", "\\begin_layout", "\\begin_body"):
216 self.warning("Malformed LyX file: Missing '\\end_preamble'.")
217 self.warning("Adding it now and hoping for the best.")
219 self.preamble.append(line)
221 if check_token(line, '\\end_preamble'):
228 if line.split()[0] in ("\\layout", "\\begin_layout", "\\begin_body"):
229 self.body.append(line)
232 self.header.append(line)
234 self.textclass = get_value(self.header, "\\textclass", 0)
235 self.backend = get_backend(self.textclass)
236 self.format = self.read_format()
237 self.language = get_value(self.header, "\\language", 0, default = "english")
238 self.inputencoding = get_value(self.header, "\\inputencoding", 0, default = "auto")
239 self.encoding = get_encoding(self.language, self.inputencoding, self.format, self.cjk_encoding)
240 self.initial_version = self.read_version()
242 # Second pass over header and preamble, now we know the file encoding
243 for i in range(len(self.header)):
244 self.header[i] = self.header[i].decode(self.encoding)
245 for i in range(len(self.preamble)):
246 self.preamble[i] = self.preamble[i].decode(self.encoding)
250 line = self.input.readline().decode(self.encoding)
253 self.body.append(trim_eol(line))
257 " Writes the LyX file to self.output."
261 if self.encoding == "auto":
262 self.encoding = get_encoding(self.language, self.encoding, self.format, self.cjk_encoding)
265 i = find_token(self.header, '\\textclass', 0) + 1
266 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
268 self.error("Malformed LyX file: Missing '\\textclass'.")
270 header = self.header[:i] + preamble + self.header[i:]
274 for line in header + [''] + self.body:
275 self.output.write(line.encode(self.encoding)+"\n")
278 def choose_io(self, input, output):
279 """Choose input and output streams, dealing transparently with
283 self.output = open(output, "wb")
285 self.output = sys.stdout
287 if input and input != '-':
288 self.dir = os.path.dirname(os.path.abspath(input))
290 gzip.open(input).readline()
291 self.input = gzip.open(input)
292 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
294 self.input = open(input)
297 self.input = sys.stdin
300 def lyxformat(self, format):
301 " Returns the file format representation, an integer."
302 result = format_re.match(format)
304 format = int(result.group(1) + result.group(2))
308 self.error(str(format) + ": " + "Invalid LyX file.")
310 if format in formats_list():
313 self.error(str(format) + ": " + "Format not supported.")
317 def read_version(self):
318 """ Searchs for clues of the LyX version used to write the file, returns the
319 most likely value, or None otherwise."""
320 for line in self.header:
324 line = line.replace("fix",".")
325 result = original_version.match(line)
327 # Special know cases: reLyX and KLyX
328 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
331 res = result.group(1)
334 #self.warning("Version %s" % result.group(1))
336 self.warning(str(self.header[:2]))
340 def set_version(self):
341 " Set the header with the version used."
342 self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx
343 if self.header[1][0] == '#':
347 def read_format(self):
348 " Read from the header the fileformat of the present LyX file."
349 for line in self.header:
350 result = fileformat.match(line)
352 return self.lyxformat(result.group(1))
354 self.error("Invalid LyX File.")
358 def set_format(self):
359 " Set the file format of the file, in the header."
360 if self.format <= 217:
361 format = str(float(self.format)/100)
363 format = str(self.format)
364 i = find_token(self.header, "\\lyxformat", 0)
365 self.header[i] = "\\lyxformat %s" % format
368 def set_textclass(self):
369 i = find_token(self.header, "\\textclass", 0)
370 self.header[i] = "\\textclass %s" % self.textclass
373 def set_parameter(self, param, value):
374 " Set the value of the header parameter."
375 i = find_token(self.header, '\\' + param, 0)
377 self.warning('Parameter not found in the header: %s' % param, 3)
379 self.header[i] = '\\%s %s' % (param, str(value))
382 def is_default_layout(self, layout):
383 " Check whether a layout is the default layout of this class."
384 # FIXME: Check against the real text class default layout
385 if layout == 'Standard' or layout == self.default_layout:
391 "Convert from current (self.format) to self.end_format."
392 mode, convertion_chain = self.chain()
393 self.warning("convertion chain: " + str(convertion_chain), 3)
395 for step in convertion_chain:
396 steps = getattr(__import__("lyx_" + step), mode)
398 self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1)
400 self.error("The convertion to an older format (%s) is not implemented." % self.format)
402 multi_conv = len(steps) != 1
403 for version, table in steps:
405 (self.format >= version and mode == "convert") or\
406 (self.format <= version and mode == "revert"):
414 self.warning("An error ocurred in %s, %s" % (version, str(conv)),
416 if not self.try_hard:
420 self.warning("%lf: Elapsed time on %s" % (time.time() - init_t, str(conv)),
421 default_debug_level + 1)
423 self.format = version
424 if self.end_format == self.format:
429 """ This is where all the decisions related with the convertion are taken.
430 It returns a list of modules needed to convert the LyX file from
431 self.format to self.end_format"""
433 self.start = self.format
437 for rel in format_relation:
438 if self.initial_version in rel[2]:
440 initial_step = rel[0]
444 if not correct_version:
446 self.warning("Version does not match file format, discarding it. (Version %s, format %d)" %(self.initial_version, self.format))
447 for rel in format_relation:
449 initial_step = rel[0]
452 # This should not happen, really.
453 self.error("Format not supported.")
455 # Find the final step
456 for rel in format_relation:
457 if self.end_format in rel[1]:
461 self.error("Format not supported.")
463 # Convertion mode, back or forth
465 if (initial_step, self.start) < (final_step, self.end_format):
468 for step in format_relation:
469 if initial_step <= step[0] <= final_step:
470 if first_step and len(step[1]) == 1:
473 steps.append(step[0])
476 relation_format = format_relation[:]
477 relation_format.reverse()
480 for step in relation_format:
481 if final_step <= step[0] <= initial_step:
482 steps.append(step[0])
485 if last_step[1][-1] == self.end_format:
491 def get_toc(self, depth = 4):
492 " Returns the TOC of this LyX document."
493 paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4}
494 allowed_insets = ['Quotes']
495 allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix", "\\leftindent"
498 for section in paragraphs_filter.keys():
499 sections.append('\\begin_layout %s' % section)
504 i = find_tokens(self.body, sections, i)
508 j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
510 self.warning('Incomplete file.', 0)
513 section = self.body[i].split()[1]
514 if section[-1] == '*':
515 section = section[:-1]
520 # skip paragraph parameters
521 while not self.body[k].strip() or self.body[k].split()[0] in allowed_parameters:
525 if check_token(self.body[k], '\\begin_inset'):
526 inset = self.body[k].split()[1]
527 end = find_end_of_inset(self.body, k)
528 if end == -1 or end > j:
529 self.warning('Malformed file.', 0)
531 if inset in allowed_insets:
532 par.extend(self.body[k: end+1])
535 par.append(self.body[k])
538 # trim empty lines in the end.
539 while par[-1].strip() == '' and par:
542 toc_par.append(Paragraph(section, par))
549 class File(LyX_Base):
550 " This class reads existing LyX files."
551 def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0, cjk_encoding = ''):
552 LyX_Base.__init__(self, end_format, input, output, error, debug, try_hard, cjk_encoding)
556 class NewFile(LyX_Base):
557 " This class is to create new LyX files."
558 def set_header(self, **params):
561 "#LyX xxxx created this file. For more info see http://www.lyx.org/",
565 "\\textclass article",
566 "\\language english",
567 "\\inputencoding auto",
568 "\\font_roman default",
569 "\\font_sans default",
570 "\\font_typewriter default",
571 "\\font_default_family default",
574 "\\font_sf_scale 100",
575 "\\font_tt_scale 100",
576 "\\graphics default",
577 "\\paperfontsize default",
578 "\\papersize default",
579 "\\use_geometry false",
581 "\\cite_engine basic",
582 "\\use_bibtopic false",
583 "\\paperorientation portrait",
586 "\\paragraph_separation indent",
588 "\\quotes_language english",
591 "\\paperpagestyle default",
592 "\\tracking_changes false",
595 self.format = get_end_format()
597 self.set_parameter(param, params[param])
600 def set_body(self, paragraphs):
601 self.body.extend(['\\begin_body',''])
603 for par in paragraphs:
604 self.body.extend(par.asLines())
606 self.body.extend(['','\\end_body', '\\end_document'])
610 # unfinished implementation, it is missing the Text and Insets representation.
611 " This class represents the LyX paragraphs."
612 def __init__(self, name, body=[], settings = [], child = []):
614 name: paragraph name.
615 body: list of lines of body text.
616 child: list of paragraphs that descend from this paragraph.
620 self.settings = settings
624 " Converts the paragraph to a list of strings, representing it in the LyX file."
625 result = ['','\\begin_layout %s' % self.name]
626 result.extend(self.settings)
628 result.extend(self.body)
629 result.append('\\end_layout')
634 result.append('\\begin_deeper')
635 for node in self.child:
636 result.extend(node.asLines())
637 result.append('\\end_deeper')
643 " This class represents the LyX insets."
648 " This class represents simple chuncks of text."