1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2002-2011 The LyX Team
4 # Copyright (C) 2002-2004 Dekel Tsur <dekel@lyx.org>
5 # Copyright (C) 2002-2006 José Matos <jamatos@lyx.org>
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License
9 # as published by the Free Software Foundation; either version 2
10 # of the License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 " The LyX module has all the rules related with different lyx file formats."
23 from parser_tools import get_value, check_token, find_token, \
24 find_tokens, find_end_of
33 import lyx2lyx_version
34 version__ = lyx2lyx_version.version
35 except: # we are running from build directory so assume the last version
40 ####################################################################
41 # Private helper functions
43 def find_end_of_inset(lines, i):
44 " Find beginning of inset, where lines[i] is included."
45 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
47 def minor_versions(major, last_minor_version):
48 """ Generate minor versions, using major as prefix and minor
49 versions from 0 until last_minor_version, plus the generic version.
53 minor_versions("1.2", 4) ->
54 [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
56 return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
59 # End of helper functions
60 ####################################################################
63 # Regular expressions used
64 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
65 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
66 original_version = re.compile(r".*?LyX ([\d.]*)")
69 # file format information:
70 # file, supported formats, stable release versions
71 format_relation = [("0_06", [200], minor_versions("0.6" , 4)),
72 ("0_08", [210], minor_versions("0.8" , 6) + ["0.7"]),
73 ("0_10", [210], minor_versions("0.10", 7) + ["0.9"]),
74 ("0_12", [215], minor_versions("0.12", 1) + ["0.11"]),
75 ("1_0", [215], minor_versions("1.0" , 4)),
76 ("1_1", [215], minor_versions("1.1" , 4)),
77 ("1_1_5", [216], ["1.1", "1.1.5","1.1.5.1","1.1.5.2"]),
78 ("1_1_6_0", [217], ["1.1", "1.1.6","1.1.6.1","1.1.6.2"]),
79 ("1_1_6_3", [218], ["1.1", "1.1.6.3","1.1.6.4"]),
80 ("1_2", [220], minor_versions("1.2" , 4)),
81 ("1_3", [221], minor_versions("1.3" , 7)),
82 ("1_4", range(222,246), minor_versions("1.4" , 5)),
83 ("1_5", range(246,277), minor_versions("1.5" , 7)),
84 ("1_6", range(277,346), minor_versions("1.6" , 10)),
85 ("2_0", range(347,414), minor_versions("2.0", 0)),
86 ("2_1", [], minor_versions("2.1", 0))
89 ####################################################################
90 # This is useful just for development versions #
91 # if the list of supported formats is empty get it from last step #
92 if not format_relation[-1][1]:
93 step, mode = format_relation[-1][0], "convert"
94 convert = getattr(__import__("lyx_" + step), mode)
95 format_relation[-1] = (step,
96 [conv[0] for conv in convert],
97 format_relation[-1][2])
99 ####################################################################
102 " Returns a list with supported file formats."
104 for version in format_relation:
105 for format in version[1]:
106 if format not in formats:
107 formats.append(format)
112 " Returns a list with supported file formats."
113 out = """Major version:
117 for version in format_relation:
118 major = str(version[2][0])
119 versions = str(version[2][1:])
120 if len(version[1]) == 1:
121 formats = str(version[1][0])
123 formats = "%s - %s" % (version[1][-1], version[1][0])
124 out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats)
128 def get_end_format():
129 " Returns the more recent file format available."
130 # this check will fail only when we have a new version
131 # and there is no format change yet.
132 if format_relation[-1][1]:
133 return format_relation[-1][1][-1]
134 return format_relation[-2][1][-1]
137 def get_backend(textclass):
138 " For _textclass_ returns its backend."
139 if textclass == "linuxdoc" or textclass == "manpage":
141 if textclass.startswith("docbook") or textclass.startswith("agu-"):
147 " Remove end of line char(s)."
148 if line[-2:-1] == '\r':
154 def get_encoding(language, inputencoding, format, cjk_encoding):
155 " Returns enconding of the lyx file"
158 # CJK-LyX encodes files using the current locale encoding.
159 # This means that files created by CJK-LyX can only be converted using
160 # the correct locale settings unless the encoding is given as commandline
162 if cjk_encoding == 'auto':
163 return locale.getpreferredencoding()
166 from lyx2lyx_lang import lang
167 if inputencoding == "auto" or inputencoding == "default":
168 return lang[language][3]
169 if inputencoding == "":
171 if inputencoding == "utf8x":
173 # python does not know the alias latin9
174 if inputencoding == "latin9":
182 """This class carries all the information of the LyX file."""
184 def __init__(self, end_format = 0, input = "", output = "", error = "",
185 debug = default_debug__, try_hard = 0, cjk_encoding = '',
186 final_version = "", language = "english", encoding = "auto"):
189 end_format: final format that the file should be converted. (integer)
190 input: the name of the input source, if empty resort to standard input.
191 output: the name of the output file, if empty use the standard output.
192 error: the name of the error file, if empty use the standard error.
193 debug: debug level, O means no debug, as its value increases be more verbose.
195 self.choose_io(input, output)
198 self.err = open(error, "w")
200 self.err = sys.stderr
203 self.try_hard = try_hard
204 self.cjk_encoding = cjk_encoding
207 self.end_format = self.lyxformat(end_format)
209 # In case the target version and format are both specified
210 # verify that they are compatible. If not send a warning
211 # and ignore the version.
213 message = "Incompatible version %s for specified format %d" % (
214 final_version, self.end_format)
215 for version in format_relation:
216 if self.end_format in version[1]:
217 if final_version not in version[2]:
218 self.warning(message)
221 for version in format_relation:
222 if final_version in version[2]:
223 # set the last format for that version
224 self.end_format = version[1][-1]
229 self.end_format = get_end_format()
231 if not final_version:
232 for step in format_relation:
233 if self.end_format in step[1]:
234 final_version = step[2][1]
235 self.final_version = final_version
236 self.warning("Final version: %s" % self.final_version, 10)
237 self.warning("Final format: %d" % self.end_format, 10)
239 self.backend = "latex"
240 self.textclass = "article"
241 # This is a hack: We use '' since we don't know the default
242 # layout of the text class. LyX will parse it as default layout.
243 # FIXME: Read the layout file and use the real default layout
244 self.default_layout = ''
249 self.encoding = encoding
250 self.language = language
253 def warning(self, message, debug_level= default_debug__):
254 """ Emits warning to self.error, if the debug_level is less
255 than the self.debug."""
256 if debug_level <= self.debug:
257 self.err.write("Warning: " + message + "\n")
260 def error(self, message):
261 " Emits a warning and exits if not in try_hard mode."
262 self.warning(message)
263 if not self.try_hard:
264 self.warning("Quitting.")
271 """Reads a file into the self.header and
272 self.body parts, from self.input."""
275 line = self.input.readline()
277 self.error("Invalid LyX file.")
279 line = trim_eol(line)
280 if check_token(line, '\\begin_preamble'):
282 line = self.input.readline()
284 self.error("Invalid LyX file.")
286 line = trim_eol(line)
287 if check_token(line, '\\end_preamble'):
290 if line.split()[:0] in ("\\layout",
291 "\\begin_layout", "\\begin_body"):
293 self.warning("Malformed LyX file:"
294 "Missing '\\end_preamble'."
295 "\nAdding it now and hoping"
298 self.preamble.append(line)
300 if check_token(line, '\\end_preamble'):
307 if line.split()[0] in ("\\layout", "\\begin_layout",
308 "\\begin_body", "\\begin_deeper"):
309 self.body.append(line)
312 self.header.append(line)
314 i = find_token(self.header, '\\textclass', 0)
316 self.warning("Malformed LyX file: Missing '\\textclass'.")
317 i = find_token(self.header, '\\lyxformat', 0) + 1
318 self.header[i:i] = ['\\textclass article']
320 self.textclass = get_value(self.header, "\\textclass", 0)
321 self.backend = get_backend(self.textclass)
322 self.format = self.read_format()
323 self.language = get_value(self.header, "\\language", 0,
325 self.inputencoding = get_value(self.header, "\\inputencoding",
327 self.encoding = get_encoding(self.language,
328 self.inputencoding, self.format,
330 self.initial_version = self.read_version()
332 # Second pass over header and preamble, now we know the file encoding
333 for i in range(len(self.header)):
334 self.header[i] = self.header[i].decode(self.encoding)
335 for i in range(len(self.preamble)):
336 self.preamble[i] = self.preamble[i].decode(self.encoding)
340 line = self.input.readline().decode(self.encoding)
343 self.body.append(trim_eol(line))
347 " Writes the LyX file to self.output."
351 if self.encoding == "auto":
352 self.encoding = get_encoding(self.language, self.encoding,
353 self.format, self.cjk_encoding)
355 i = find_token(self.header, '\\textclass', 0) + 1
356 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
357 header = self.header[:i] + preamble + self.header[i:]
361 for line in header + [''] + self.body:
362 self.output.write(line.encode(self.encoding)+"\n")
365 def choose_io(self, input, output):
366 """Choose input and output streams, dealing transparently with
370 self.output = open(output, "wb")
372 self.output = sys.stdout
374 if input and input != '-':
375 self.dir = os.path.dirname(os.path.abspath(input))
377 gzip.open(input).readline()
378 self.input = gzip.open(input)
379 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
381 self.input = open(input)
384 self.input = sys.stdin
387 def lyxformat(self, format):
388 " Returns the file format representation, an integer."
389 result = format_re.match(format)
391 format = int(result.group(1) + result.group(2))
395 self.error(str(format) + ": " + "Invalid LyX file.")
397 if format in formats_list():
400 self.error(str(format) + ": " + "Format not supported.")
404 def read_version(self):
405 """ Searchs for clues of the LyX version used to write the
406 file, returns the most likely value, or None otherwise."""
408 for line in self.header:
412 line = line.replace("fix",".")
413 result = original_version.match(line)
415 # Special know cases: reLyX and KLyX
416 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
419 res = result.group(1)
422 #self.warning("Version %s" % result.group(1))
424 self.warning(str(self.header[:2]))
428 def set_version(self):
429 " Set the header with the version used."
430 self.header[0] = " ".join(["#LyX %s created this file." % version__,
431 "For more info see http://www.lyx.org/"])
432 if self.header[1][0] == '#':
436 def read_format(self):
437 " Read from the header the fileformat of the present LyX file."
438 for line in self.header:
439 result = fileformat.match(line)
441 return self.lyxformat(result.group(1))
443 self.error("Invalid LyX File.")
447 def set_format(self):
448 " Set the file format of the file, in the header."
449 if self.format <= 217:
450 format = str(float(self.format)/100)
452 format = str(self.format)
453 i = find_token(self.header, "\\lyxformat", 0)
454 self.header[i] = "\\lyxformat %s" % format
457 def set_textclass(self):
458 i = find_token(self.header, "\\textclass", 0)
459 self.header[i] = "\\textclass %s" % self.textclass
462 #Note that the module will be added at the END of the extant ones
463 def add_module(self, module):
464 i = find_token(self.header, "\\begin_modules", 0)
466 #No modules yet included
467 i = find_token(self.header, "\\textclass", 0)
469 self.warning("Malformed LyX document: No \\textclass!!")
471 modinfo = ["\\begin_modules", module, "\\end_modules"]
472 self.header[i + 1: i + 1] = modinfo
474 j = find_token(self.header, "\\end_modules", i)
476 self.warning("(add_module)Malformed LyX document: No \\end_modules.")
478 k = find_token(self.header, module, i)
479 if k != -1 and k < j:
481 self.header.insert(j, module)
484 def get_module_list(self):
485 i = find_token(self.header, "\\begin_modules", 0)
488 j = find_token(self.header, "\\end_modules", i)
489 return self.header[i + 1 : j]
492 def set_module_list(self, mlist):
493 modbegin = find_token(self.header, "\\begin_modules", 0)
494 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
496 #No modules yet included
497 tclass = find_token(self.header, "\\textclass", 0)
499 self.warning("Malformed LyX document: No \\textclass!!")
501 modbegin = tclass + 1
502 self.header[modbegin:modbegin] = newmodlist
504 modend = find_token(self.header, "\\end_modules", modbegin)
506 self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
508 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
509 self.header[modbegin:modend + 1] = newmodlist
512 def set_parameter(self, param, value):
513 " Set the value of the header parameter."
514 i = find_token(self.header, '\\' + param, 0)
516 self.warning('Parameter not found in the header: %s' % param, 3)
518 self.header[i] = '\\%s %s' % (param, str(value))
521 def is_default_layout(self, layout):
522 " Check whether a layout is the default layout of this class."
523 # FIXME: Check against the real text class default layout
524 if layout == 'Standard' or layout == self.default_layout:
530 "Convert from current (self.format) to self.end_format."
531 mode, conversion_chain = self.chain()
532 self.warning("conversion chain: " + str(conversion_chain), 3)
534 for step in conversion_chain:
535 steps = getattr(__import__("lyx_" + step), mode)
537 self.warning("Convertion step: %s - %s" % (step, mode),
540 self.error("The conversion to an older "
541 "format (%s) is not implemented." % self.format)
543 multi_conv = len(steps) != 1
544 for version, table in steps:
546 (self.format >= version and mode == "convert") or\
547 (self.format <= version and mode == "revert"):
555 self.warning("An error ocurred in %s, %s" %
556 (version, str(conv)),
558 if not self.try_hard:
562 self.warning("%lf: Elapsed time on %s" %
563 (time.time() - init_t,
564 str(conv)), default_debug__ +
566 self.format = version
567 if self.end_format == self.format:
572 """ This is where all the decisions related with the
573 conversion are taken. It returns a list of modules needed to
574 convert the LyX file from self.format to self.end_format"""
576 self.start = self.format
580 for rel in format_relation:
581 if self.initial_version in rel[2]:
583 initial_step = rel[0]
587 if not correct_version:
589 self.warning("Version does not match file format, "
590 "discarding it. (Version %s, format %d)" %
591 (self.initial_version, self.format))
592 for rel in format_relation:
594 initial_step = rel[0]
597 # This should not happen, really.
598 self.error("Format not supported.")
600 # Find the final step
601 for rel in format_relation:
602 if self.end_format in rel[1]:
606 self.error("Format not supported.")
608 # Convertion mode, back or forth
610 if (initial_step, self.start) < (final_step, self.end_format):
613 for step in format_relation:
614 if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
615 full_steps.append(step)
616 if full_steps[0][1][-1] == self.format:
617 full_steps = full_steps[1:]
618 for step in full_steps:
619 steps.append(step[0])
622 relation_format = format_relation[:]
623 relation_format.reverse()
626 for step in relation_format:
627 if final_step <= step[0] <= initial_step:
628 steps.append(step[0])
631 if last_step[1][-1] == self.end_format:
634 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
638 # Part of an unfinished attempt to make lyx2lyx gave a more
639 # structured view of the document.
640 # def get_toc(self, depth = 4):
641 # " Returns the TOC of this LyX document."
642 # paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
643 # 'Subsection' : 3, 'Subsubsection': 4}
644 # allowed_insets = ['Quotes']
645 # allowed_parameters = ('\\paragraph_spacing', '\\noindent',
646 # '\\align', '\\labelwidthstring',
647 # "\\start_of_appendix", "\\leftindent")
649 # for section in paragraphs_filter.keys():
650 # sections.append('\\begin_layout %s' % section)
655 # i = find_tokens(self.body, sections, i)
659 # j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
661 # self.warning('Incomplete file.', 0)
664 # section = self.body[i].split()[1]
665 # if section[-1] == '*':
666 # section = section[:-1]
671 # # skip paragraph parameters
672 # while not self.body[k].strip() or self.body[k].split()[0] \
673 # in allowed_parameters:
677 # if check_token(self.body[k], '\\begin_inset'):
678 # inset = self.body[k].split()[1]
679 # end = find_end_of_inset(self.body, k)
680 # if end == -1 or end > j:
681 # self.warning('Malformed file.', 0)
683 # if inset in allowed_insets:
684 # par.extend(self.body[k: end+1])
687 # par.append(self.body[k])
690 # # trim empty lines in the end.
691 # while par and par[-1].strip() == '':
694 # toc_par.append(Paragraph(section, par))
701 class File(LyX_base):
702 " This class reads existing LyX files."
704 def __init__(self, end_format = 0, input = "", output = "", error = "",
705 debug = default_debug__, try_hard = 0, cjk_encoding = '',
707 LyX_base.__init__(self, end_format, input, output, error,
708 debug, try_hard, cjk_encoding, final_version)
712 #class NewFile(LyX_base):
713 # " This class is to create new LyX files."
714 # def set_header(self, **params):
715 # # set default values
716 # self.header.extend([
717 # "#LyX xxxx created this file."
718 # "For more info see http://www.lyx.org/",
720 # "\\begin_document",
722 # "\\textclass article",
723 # "\\language english",
724 # "\\inputencoding auto",
725 # "\\font_roman default",
726 # "\\font_sans default",
727 # "\\font_typewriter default",
728 # "\\font_default_family default",
730 # "\\font_osf false",
731 # "\\font_sf_scale 100",
732 # "\\font_tt_scale 100",
733 # "\\graphics default",
734 # "\\paperfontsize default",
735 # "\\papersize default",
736 # "\\use_geometry false",
738 # "\\cite_engine basic",
739 # "\\use_bibtopic false",
740 # "\\paperorientation portrait",
743 # "\\paragraph_separation indent",
744 # "\\defskip medskip",
745 # "\\quotes_language english",
746 # "\\papercolumns 1",
748 # "\\paperpagestyle default",
749 # "\\tracking_changes false",
752 # self.format = get_end_format()
753 # for param in params:
754 # self.set_parameter(param, params[param])
757 # def set_body(self, paragraphs):
758 # self.body.extend(['\\begin_body',''])
760 # for par in paragraphs:
761 # self.body.extend(par.asLines())
763 # self.body.extend(['','\\end_body', '\\end_document'])
766 # Part of an unfinished attempt to make lyx2lyx gave a more
767 # structured view of the document.
769 # # unfinished implementation, it is missing the Text and Insets
771 # " This class represents the LyX paragraphs."
772 # def __init__(self, name, body=[], settings = [], child = []):
774 # name: paragraph name.
775 # body: list of lines of body text.
776 # child: list of paragraphs that descend from this paragraph.
780 # self.settings = settings
784 # """ Converts the paragraph to a list of strings, representing
785 # it in the LyX file."""
787 # result = ['','\\begin_layout %s' % self.name]
788 # result.extend(self.settings)
790 # result.extend(self.body)
791 # result.append('\\end_layout')
796 # result.append('\\begin_deeper')
797 # for node in self.child:
798 # result.extend(node.asLines())
799 # result.append('\\end_deeper')