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 " The LyX module has all the rules related with different lyx file formats."
22 from parser_tools import get_value, check_token, find_token, \
23 find_tokens, find_end_of
32 import lyx2lyx_version
33 version__ = lyx2lyx_version.version
34 except: # we are running from build directory so assume the last version
39 ####################################################################
40 # Private helper functions
42 def find_end_of_inset(lines, i):
43 " Find beginning of inset, where lines[i] is included."
44 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
46 def minor_versions(major, last_minor_version):
47 """ Generate minor versions, using major as prefix and minor
48 versions from 0 until last_minor_version, plus the generic version.
52 minor_versions("1.2", 4) ->
53 [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
55 return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
58 # End of helper functions
59 ####################################################################
62 # Regular expressions used
63 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
64 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
65 original_version = re.compile(r".*?LyX ([\d.]*)")
68 # file format information:
69 # file, supported formats, stable release versions
70 format_relation = [("0_06", [200], minor_versions("0.6" , 4)),
71 ("0_08", [210], minor_versions("0.8" , 6) + ["0.7"]),
72 ("0_10", [210], minor_versions("0.10", 7) + ["0.9"]),
73 ("0_12", [215], minor_versions("0.12", 1) + ["0.11"]),
74 ("1_0", [215], minor_versions("1.0" , 4)),
75 ("1_1", [215], minor_versions("1.1" , 4)),
76 ("1_1_5", [216], ["1.1", "1.1.5","1.1.5.1","1.1.5.2"]),
77 ("1_1_6_0", [217], ["1.1", "1.1.6","1.1.6.1","1.1.6.2"]),
78 ("1_1_6_3", [218], ["1.1", "1.1.6.3","1.1.6.4"]),
79 ("1_2", [220], minor_versions("1.2" , 4)),
80 ("1_3", [221], minor_versions("1.3" , 7)),
81 ("1_4", range(222,246), minor_versions("1.4" , 5)),
82 ("1_5", range(246,277), minor_versions("1.5" , 7)),
83 ("1_6", range(277,346), minor_versions("1.6" , 0)),
84 ("2_0", [], minor_versions("2.0", 0))]
86 ####################################################################
87 # This is useful just for development versions #
88 # if the list of supported formats is empty get it from last step #
89 if not format_relation[-1][1]:
90 step, mode = format_relation[-1][0], "convert"
91 convert = getattr(__import__("lyx_" + step), mode)
92 format_relation[-1] = (step,
93 [conv[0] for conv in convert],
94 format_relation[-1][2])
96 ####################################################################
99 " Returns a list with supported file formats."
101 for version in format_relation:
102 for format in version[1]:
103 if format not in formats:
104 formats.append(format)
109 " Returns a list with supported file formats."
110 out = """Major version:
114 for version in format_relation:
115 major = str(version[2][0])
116 versions = str(version[2][1:])
117 if len(version[1]) == 1:
118 formats = str(version[1][0])
120 formats = "%s - %s" % (version[1][-1], version[1][0])
121 out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats)
125 def get_end_format():
126 " Returns the more recent file format available."
127 return format_relation[-1][1][-1]
130 def get_backend(textclass):
131 " For _textclass_ returns its backend."
132 if textclass == "linuxdoc" or textclass == "manpage":
134 if textclass.startswith("docbook") or textclass.startswith("agu-"):
140 " Remove end of line char(s)."
141 if line[-2:-1] == '\r':
147 def get_encoding(language, inputencoding, format, cjk_encoding):
148 " Returns enconding of the lyx file"
151 # CJK-LyX encodes files using the current locale encoding.
152 # This means that files created by CJK-LyX can only be converted using
153 # the correct locale settings unless the encoding is given as commandline
155 if cjk_encoding == 'auto':
156 return locale.getpreferredencoding()
159 from lyx2lyx_lang import lang
160 if inputencoding == "auto" or inputencoding == "default":
161 return lang[language][3]
162 if inputencoding == "":
164 if inputencoding == "utf8x":
166 # python does not know the alias latin9
167 if inputencoding == "latin9":
175 """This class carries all the information of the LyX file."""
177 def __init__(self, end_format = 0, input = "", output = "", error = "",
178 debug = default_debug__, try_hard = 0, cjk_encoding = '',
179 final_version = "", language = "english", encoding = "auto"):
182 end_format: final format that the file should be converted. (integer)
183 input: the name of the input source, if empty resort to standard input.
184 output: the name of the output file, if empty use the standard output.
185 error: the name of the error file, if empty use the standard error.
186 debug: debug level, O means no debug, as its value increases be more verbose.
188 self.choose_io(input, output)
191 self.err = open(error, "w")
193 self.err = sys.stderr
196 self.try_hard = try_hard
197 self.cjk_encoding = cjk_encoding
200 self.end_format = self.lyxformat(end_format)
202 # In case the target version and format are both specified
203 # verify that they are compatible. If not send a warning
204 # and ignore the version.
206 message = "Incompatible version %s for specified format %d" % (
207 final_version, self.end_format)
208 for version in format_relation:
209 if self.end_format in version[1]:
210 if final_version not in version[2]:
211 self.warning(message)
214 for version in format_relation:
215 if final_version in version[2]:
216 # set the last format for that version
217 self.end_format = version[1][-1]
222 self.end_format = get_end_format()
224 if not final_version:
225 for step in format_relation:
226 if self.end_format in step[1]:
227 final_version = step[2][1]
228 self.final_version = final_version
229 self.warning("Final version: %s" % self.final_version, 10)
230 self.warning("Final format: %d" % self.end_format, 10)
232 self.backend = "latex"
233 self.textclass = "article"
234 # This is a hack: We use '' since we don't know the default
235 # layout of the text class. LyX will parse it as default layout.
236 # FIXME: Read the layout file and use the real default layout
237 self.default_layout = ''
242 self.encoding = encoding
243 self.language = language
246 def warning(self, message, debug_level= default_debug__):
247 """ Emits warning to self.error, if the debug_level is less
248 than the self.debug."""
249 if debug_level <= self.debug:
250 self.err.write("Warning: " + message + "\n")
253 def error(self, message):
254 " Emits a warning and exits if not in try_hard mode."
255 self.warning(message)
256 if not self.try_hard:
257 self.warning("Quitting.")
264 """Reads a file into the self.header and
265 self.body parts, from self.input."""
268 line = self.input.readline()
270 self.error("Invalid LyX file.")
272 line = trim_eol(line)
273 if check_token(line, '\\begin_preamble'):
275 line = self.input.readline()
277 self.error("Invalid LyX file.")
279 line = trim_eol(line)
280 if check_token(line, '\\end_preamble'):
283 if line.split()[:0] in ("\\layout",
284 "\\begin_layout", "\\begin_body"):
286 self.warning("Malformed LyX file:"
287 "Missing '\\end_preamble'."
288 "\nAdding it now and hoping"
291 self.preamble.append(line)
293 if check_token(line, '\\end_preamble'):
300 if line.split()[0] in ("\\layout", "\\begin_layout",
301 "\\begin_body", "\\begin_deeper"):
302 self.body.append(line)
305 self.header.append(line)
307 i = find_token(self.header, '\\textclass', 0)
309 self.warning("Malformed LyX file: Missing '\\textclass'.")
310 i = find_token(self.header, '\\lyxformat', 0) + 1
311 self.header[i:i] = ['\\textclass article']
313 self.textclass = get_value(self.header, "\\textclass", 0)
314 self.backend = get_backend(self.textclass)
315 self.format = self.read_format()
316 self.language = get_value(self.header, "\\language", 0,
318 self.inputencoding = get_value(self.header, "\\inputencoding",
320 self.encoding = get_encoding(self.language,
321 self.inputencoding, self.format,
323 self.initial_version = self.read_version()
325 # Second pass over header and preamble, now we know the file encoding
326 for i in range(len(self.header)):
327 self.header[i] = self.header[i].decode(self.encoding)
328 for i in range(len(self.preamble)):
329 self.preamble[i] = self.preamble[i].decode(self.encoding)
333 line = self.input.readline().decode(self.encoding)
336 self.body.append(trim_eol(line))
340 " Writes the LyX file to self.output."
344 if self.encoding == "auto":
345 self.encoding = get_encoding(self.language, self.encoding,
346 self.format, self.cjk_encoding)
348 i = find_token(self.header, '\\textclass', 0) + 1
349 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
350 header = self.header[:i] + preamble + self.header[i:]
354 for line in header + [''] + self.body:
355 self.output.write(line.encode(self.encoding)+"\n")
358 def choose_io(self, input, output):
359 """Choose input and output streams, dealing transparently with
363 self.output = open(output, "wb")
365 self.output = sys.stdout
367 if input and input != '-':
368 self.dir = os.path.dirname(os.path.abspath(input))
370 gzip.open(input).readline()
371 self.input = gzip.open(input)
372 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
374 self.input = open(input)
377 self.input = sys.stdin
380 def lyxformat(self, format):
381 " Returns the file format representation, an integer."
382 result = format_re.match(format)
384 format = int(result.group(1) + result.group(2))
388 self.error(str(format) + ": " + "Invalid LyX file.")
390 if format in formats_list():
393 self.error(str(format) + ": " + "Format not supported.")
397 def read_version(self):
398 """ Searchs for clues of the LyX version used to write the
399 file, returns the most likely value, or None otherwise."""
401 for line in self.header:
405 line = line.replace("fix",".")
406 result = original_version.match(line)
408 # Special know cases: reLyX and KLyX
409 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
412 res = result.group(1)
415 #self.warning("Version %s" % result.group(1))
417 self.warning(str(self.header[:2]))
421 def set_version(self):
422 " Set the header with the version used."
423 self.header[0] = " ".join(["#LyX %s created this file." % version__,
424 "For more info see http://www.lyx.org/"])
425 if self.header[1][0] == '#':
429 def read_format(self):
430 " Read from the header the fileformat of the present LyX file."
431 for line in self.header:
432 result = fileformat.match(line)
434 return self.lyxformat(result.group(1))
436 self.error("Invalid LyX File.")
440 def set_format(self):
441 " Set the file format of the file, in the header."
442 if self.format <= 217:
443 format = str(float(self.format)/100)
445 format = str(self.format)
446 i = find_token(self.header, "\\lyxformat", 0)
447 self.header[i] = "\\lyxformat %s" % format
450 def set_textclass(self):
451 i = find_token(self.header, "\\textclass", 0)
452 self.header[i] = "\\textclass %s" % self.textclass
455 #Note that the module will be added at the END of the extant ones
456 def add_module(self, module):
457 i = find_token(self.header, "\\begin_modules", 0)
459 #No modules yet included
460 i = find_token(self.header, "\\textclass", 0)
462 self.warning("Malformed LyX document: No \\textclass!!")
464 modinfo = ["\\begin_modules", module, "\\end_modules"]
465 self.header[i + 1: i + 1] = modinfo
467 j = find_token(self.header, "\\end_modules", i)
469 self.warning("(add_module)Malformed LyX document: No \\end_modules.")
471 k = find_token(self.header, module, i)
472 if k != -1 and k < j:
474 self.header.insert(j, module)
477 def get_module_list(self):
478 i = find_token(self.header, "\\begin_modules", 0)
481 j = find_token(self.header, "\\end_modules", i)
482 return self.header[i + 1 : j]
485 def set_module_list(self, mlist):
486 modbegin = find_token(self.header, "\\begin_modules", 0)
487 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
489 #No modules yet included
490 tclass = find_token(self.header, "\\textclass", 0)
492 self.warning("Malformed LyX document: No \\textclass!!")
494 modbegin = tclass + 1
495 self.header[modbegin:modbegin] = newmodlist
497 modend = find_token(self.header, "\\end_modules", modbegin)
499 self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
501 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
502 self.header[modbegin:modend + 1] = newmodlist
505 def set_parameter(self, param, value):
506 " Set the value of the header parameter."
507 i = find_token(self.header, '\\' + param, 0)
509 self.warning('Parameter not found in the header: %s' % param, 3)
511 self.header[i] = '\\%s %s' % (param, str(value))
514 def is_default_layout(self, layout):
515 " Check whether a layout is the default layout of this class."
516 # FIXME: Check against the real text class default layout
517 if layout == 'Standard' or layout == self.default_layout:
523 "Convert from current (self.format) to self.end_format."
524 mode, conversion_chain = self.chain()
525 self.warning("conversion chain: " + str(conversion_chain), 3)
527 for step in conversion_chain:
528 steps = getattr(__import__("lyx_" + step), mode)
530 self.warning("Convertion step: %s - %s" % (step, mode),
533 self.error("The conversion to an older "
534 "format (%s) is not implemented." % self.format)
536 multi_conv = len(steps) != 1
537 for version, table in steps:
539 (self.format >= version and mode == "convert") or\
540 (self.format <= version and mode == "revert"):
548 self.warning("An error ocurred in %s, %s" %
549 (version, str(conv)),
551 if not self.try_hard:
555 self.warning("%lf: Elapsed time on %s" %
556 (time.time() - init_t,
557 str(conv)), default_debug__ +
559 self.format = version
560 if self.end_format == self.format:
565 """ This is where all the decisions related with the
566 conversion are taken. It returns a list of modules needed to
567 convert the LyX file from self.format to self.end_format"""
569 self.start = self.format
573 for rel in format_relation:
574 if self.initial_version in rel[2]:
576 initial_step = rel[0]
580 if not correct_version:
582 self.warning("Version does not match file format, "
583 "discarding it. (Version %s, format %d)" %
584 (self.initial_version, self.format))
585 for rel in format_relation:
587 initial_step = rel[0]
590 # This should not happen, really.
591 self.error("Format not supported.")
593 # Find the final step
594 for rel in format_relation:
595 if self.end_format in rel[1]:
599 self.error("Format not supported.")
601 # Convertion mode, back or forth
603 if (initial_step, self.start) < (final_step, self.end_format):
606 for step in format_relation:
607 if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
608 full_steps.append(step)
609 if full_steps[0][1][-1] == self.format:
610 full_steps = full_steps[1:]
611 for step in full_steps:
612 steps.append(step[0])
615 relation_format = format_relation[:]
616 relation_format.reverse()
619 for step in relation_format:
620 if final_step <= step[0] <= initial_step:
621 steps.append(step[0])
624 if last_step[1][-1] == self.end_format:
627 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
631 # Part of an unfinished attempt to make lyx2lyx gave a more
632 # structured view of the document.
633 # def get_toc(self, depth = 4):
634 # " Returns the TOC of this LyX document."
635 # paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
636 # 'Subsection' : 3, 'Subsubsection': 4}
637 # allowed_insets = ['Quotes']
638 # allowed_parameters = ('\\paragraph_spacing', '\\noindent',
639 # '\\align', '\\labelwidthstring',
640 # "\\start_of_appendix", "\\leftindent")
642 # for section in paragraphs_filter.keys():
643 # sections.append('\\begin_layout %s' % section)
648 # i = find_tokens(self.body, sections, i)
652 # j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
654 # self.warning('Incomplete file.', 0)
657 # section = self.body[i].split()[1]
658 # if section[-1] == '*':
659 # section = section[:-1]
664 # # skip paragraph parameters
665 # while not self.body[k].strip() or self.body[k].split()[0] \
666 # in allowed_parameters:
670 # if check_token(self.body[k], '\\begin_inset'):
671 # inset = self.body[k].split()[1]
672 # end = find_end_of_inset(self.body, k)
673 # if end == -1 or end > j:
674 # self.warning('Malformed file.', 0)
676 # if inset in allowed_insets:
677 # par.extend(self.body[k: end+1])
680 # par.append(self.body[k])
683 # # trim empty lines in the end.
684 # while par and par[-1].strip() == '':
687 # toc_par.append(Paragraph(section, par))
694 class File(LyX_base):
695 " This class reads existing LyX files."
697 def __init__(self, end_format = 0, input = "", output = "", error = "",
698 debug = default_debug__, try_hard = 0, cjk_encoding = '',
700 LyX_base.__init__(self, end_format, input, output, error,
701 debug, try_hard, cjk_encoding, final_version)
705 #class NewFile(LyX_base):
706 # " This class is to create new LyX files."
707 # def set_header(self, **params):
708 # # set default values
709 # self.header.extend([
710 # "#LyX xxxx created this file."
711 # "For more info see http://www.lyx.org/",
713 # "\\begin_document",
715 # "\\textclass article",
716 # "\\language english",
717 # "\\inputencoding auto",
718 # "\\font_roman default",
719 # "\\font_sans default",
720 # "\\font_typewriter default",
721 # "\\font_default_family default",
723 # "\\font_osf false",
724 # "\\font_sf_scale 100",
725 # "\\font_tt_scale 100",
726 # "\\graphics default",
727 # "\\paperfontsize default",
728 # "\\papersize default",
729 # "\\use_geometry false",
731 # "\\cite_engine basic",
732 # "\\use_bibtopic false",
733 # "\\paperorientation portrait",
736 # "\\paragraph_separation indent",
737 # "\\defskip medskip",
738 # "\\quotes_language english",
739 # "\\papercolumns 1",
741 # "\\paperpagestyle default",
742 # "\\tracking_changes false",
745 # self.format = get_end_format()
746 # for param in params:
747 # self.set_parameter(param, params[param])
750 # def set_body(self, paragraphs):
751 # self.body.extend(['\\begin_body',''])
753 # for par in paragraphs:
754 # self.body.extend(par.asLines())
756 # self.body.extend(['','\\end_body', '\\end_document'])
759 # Part of an unfinished attempt to make lyx2lyx gave a more
760 # structured view of the document.
762 # # unfinished implementation, it is missing the Text and Insets
764 # " This class represents the LyX paragraphs."
765 # def __init__(self, name, body=[], settings = [], child = []):
767 # name: paragraph name.
768 # body: list of lines of body text.
769 # child: list of paragraphs that descend from this paragraph.
773 # self.settings = settings
777 # """ Converts the paragraph to a list of strings, representing
778 # it in the LyX file."""
780 # result = ['','\\begin_layout %s' % self.name]
781 # result.extend(self.settings)
783 # result.extend(self.body)
784 # result.append('\\end_layout')
789 # result.append('\\begin_deeper')
790 # for node in self.child:
791 # result.extend(node.asLines())
792 # result.append('\\end_deeper')