1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2002-2015 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
35 import lyx2lyx_version
36 version__ = lyx2lyx_version.version
37 except: # we are running from build directory so assume the last version
42 # Provide support for both python 2 and 3
43 PY2 = sys.version_info[0] == 2
44 # End of code to support for both python 2 and 3
46 ####################################################################
47 # Private helper functions
49 def find_end_of_inset(lines, i):
50 " Find beginning of inset, where lines[i] is included."
51 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
53 def minor_versions(major, last_minor_version):
54 """ Generate minor versions, using major as prefix and minor
55 versions from 0 until last_minor_version, plus the generic version.
59 minor_versions("1.2", 4) ->
60 [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
62 return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
65 # End of helper functions
66 ####################################################################
69 # Regular expressions used
70 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
71 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
72 original_version = re.compile(r".*?LyX ([\d.]*)")
73 original_tex2lyx_version = re.compile(r".*?tex2lyx ([\d.]*)")
76 # file format information:
77 # file, supported formats, stable release versions
78 format_relation = [("0_06", [200], minor_versions("0.6" , 4)),
79 ("0_08", [210], minor_versions("0.8" , 6) + ["0.7"]),
80 ("0_10", [210], minor_versions("0.10", 7) + ["0.9"]),
81 ("0_12", [215], minor_versions("0.12", 1) + ["0.11"]),
82 ("1_0", [215], minor_versions("1.0" , 4)),
83 ("1_1", [215], minor_versions("1.1" , 4)),
84 ("1_1_5", [216], ["1.1", "1.1.5","1.1.5.1","1.1.5.2"]),
85 ("1_1_6_0", [217], ["1.1", "1.1.6","1.1.6.1","1.1.6.2"]),
86 ("1_1_6_3", [218], ["1.1", "1.1.6.3","1.1.6.4"]),
87 ("1_2", [220], minor_versions("1.2" , 4)),
88 ("1_3", [221], minor_versions("1.3" , 7)),
89 # Note that range(i,j) is up to j *excluded*.
90 ("1_4", list(range(222,246)), minor_versions("1.4" , 5)),
91 ("1_5", list(range(246,277)), minor_versions("1.5" , 7)),
92 ("1_6", list(range(277,346)), minor_versions("1.6" , 10)),
93 ("2_0", list(range(346,414)), minor_versions("2.0" , 8)),
94 ("2_1", list(range(414,475)), minor_versions("2.1" , 5)),
95 ("2_2", list(range(475,509)), minor_versions("2.2" , 0)),
96 ("2_3", (), minor_versions("2.3" , 0))
99 ####################################################################
100 # This is useful just for development versions #
101 # if the list of supported formats is empty get it from last step #
102 if not format_relation[-1][1]:
103 step, mode = format_relation[-1][0], "convert"
104 convert = getattr(__import__("lyx_" + step), mode)
105 format_relation[-1] = (step,
106 [conv[0] for conv in convert],
107 format_relation[-1][2])
109 ####################################################################
112 " Returns a list with supported file formats."
114 for version in format_relation:
115 for format in version[1]:
116 if format not in formats:
117 formats.append(format)
122 " Returns a list with supported file formats."
123 out = """Major version:
127 for version in format_relation:
128 major = str(version[2][0])
129 versions = str(version[2][1:])
130 if len(version[1]) == 1:
131 formats = str(version[1][0])
133 formats = "%s - %s" % (version[1][-1], version[1][0])
134 out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats)
138 def get_end_format():
139 " Returns the more recent file format available."
140 # this check will fail only when we have a new version
141 # and there is no format change yet.
142 if format_relation[-1][1]:
143 return format_relation[-1][1][-1]
144 return format_relation[-2][1][-1]
147 def get_backend(textclass):
148 " For _textclass_ returns its backend."
149 if textclass == "linuxdoc" or textclass == "manpage":
151 if textclass.startswith("docbook") or textclass.startswith("agu-"):
157 " Remove end of line char(s)."
158 if line[-1] != '\n' and line[-1] != '\r':
159 # May happen for the last line of a document
161 if line[-2:-1] == '\r':
167 def trim_eol_binary(line):
168 " Remove end of line char(s)."
169 if line[-1] != 10 and line[-1] != 13:
170 # May happen for the last line of a document
172 if line[-2:-1] == 13:
178 def get_encoding(language, inputencoding, format, cjk_encoding):
179 " Returns enconding of the lyx file"
182 # CJK-LyX encodes files using the current locale encoding.
183 # This means that files created by CJK-LyX can only be converted using
184 # the correct locale settings unless the encoding is given as commandline
186 if cjk_encoding == 'auto':
187 return locale.getpreferredencoding()
190 from lyx2lyx_lang import lang
191 if inputencoding == "auto" or inputencoding == "default":
192 return lang[language][3]
193 if inputencoding == "":
195 if inputencoding == "utf8x":
197 # python does not know the alias latin9
198 if inputencoding == "latin9":
206 """This class carries all the information of the LyX file."""
208 def __init__(self, end_format = 0, input = u'', output = u'', error = u'',
209 debug = default_debug__, try_hard = 0, cjk_encoding = u'',
210 final_version = u'', systemlyxdir = u'', language = u'english',
214 end_format: final format that the file should be converted. (integer)
215 input: the name of the input source, if empty resort to standard input.
216 output: the name of the output file, if empty use the standard output.
217 error: the name of the error file, if empty use the standard error.
218 debug: debug level, O means no debug, as its value increases be more verbose.
220 self.choose_input(input)
224 self.err = open(error, "w")
226 self.err = sys.stderr
229 self.try_hard = try_hard
230 self.cjk_encoding = cjk_encoding
233 self.end_format = self.lyxformat(end_format)
235 # In case the target version and format are both specified
236 # verify that they are compatible. If not send a warning
237 # and ignore the version.
239 message = "Incompatible version %s for specified format %d" % (
240 final_version, self.end_format)
241 for version in format_relation:
242 if self.end_format in version[1]:
243 if final_version not in version[2]:
244 self.warning(message)
247 for version in format_relation:
248 if final_version in version[2]:
249 # set the last format for that version
250 self.end_format = version[1][-1]
255 self.end_format = get_end_format()
257 if not final_version:
258 for step in format_relation:
259 if self.end_format in step[1]:
260 final_version = step[2][1]
261 self.final_version = final_version
262 self.warning("Final version: %s" % self.final_version, 10)
263 self.warning("Final format: %d" % self.end_format, 10)
265 self.backend = "latex"
266 self.textclass = "article"
267 # This is a hack: We use '' since we don't know the default
268 # layout of the text class. LyX will parse it as default layout.
269 # FIXME: Read the layout file and use the real default layout
270 self.default_layout = ''
275 self.encoding = encoding
276 self.language = language
277 self.systemlyxdir = systemlyxdir
280 def warning(self, message, debug_level= default_debug__):
281 """ Emits warning to self.error, if the debug_level is less
282 than the self.debug."""
283 if debug_level <= self.debug:
284 self.err.write("Warning: " + message + "\n")
287 def error(self, message):
288 " Emits a warning and exits if not in try_hard mode."
289 self.warning(message)
290 if not self.try_hard:
291 self.warning("Quitting.")
298 """Reads a file into the self.header and
299 self.body parts, from self.input."""
301 # First pass: Read header to determine file encoding
302 # If we are running under python3 then all strings are binary in this
303 # pass. In some cases we need to convert binary to unicode in order to
304 # use our parser tools. Since we do not know the true encoding yet we
305 # use latin1. This works since a) the parts we are interested in are
306 # pure ASCII (subset of latin1) and b) in contrast to pure ascii or
307 # utf8, one can decode any 8byte string using latin1.
310 line = self.input.readline()
312 # eof found before end of header
313 self.error("Invalid LyX file: Missing body.")
316 # Remove UTF8 BOM marker if present
317 if line.startswith(codecs.BOM_UTF8):
318 line = line[len(codecs.BOM_UTF8):]
323 line = trim_eol(line)
326 line = trim_eol_binary(line)
327 decoded = line.decode('latin1')
328 if check_token(decoded, '\\begin_preamble'):
330 line = self.input.readline()
332 # eof found before end of header
333 self.error("Invalid LyX file: Missing body.")
336 line = trim_eol(line)
339 line = trim_eol_binary(line)
340 decoded = line.decode('latin1')
341 if check_token(decoded, '\\end_preamble'):
344 if decoded.split()[:0] in ("\\layout",
345 "\\begin_layout", "\\begin_body"):
347 self.warning("Malformed LyX file:"
348 "Missing '\\end_preamble'."
349 "\nAdding it now and hoping"
352 self.preamble.append(line)
354 if check_token(decoded, '\\end_preamble'):
361 if decoded.split()[0] in ("\\layout", "\\begin_layout",
362 "\\begin_body", "\\begin_deeper"):
363 self.body.append(line)
366 self.header.append(line)
369 i = find_token(self.header, '\\textclass', 0)
371 i = find_token(self.header, b'\\textclass', 0)
373 self.warning("Malformed LyX file: Missing '\\textclass'.")
375 i = find_token(self.header, '\\lyxformat', 0) + 1
376 self.header[i:i] = ['\\textclass article']
378 i = find_token(self.header, b'\\lyxformat', 0) + 1
379 self.header[i:i] = [b'\\textclass article']
382 self.textclass = get_value(self.header, "\\textclass", 0,
384 self.language = get_value(self.header, "\\language", 0,
386 self.inputencoding = get_value(self.header, "\\inputencoding", 0,
389 self.textclass = get_value(self.header, b"\\textclass", 0,
391 self.language = get_value(self.header, b"\\language", 0,
392 default = b"english").decode('ascii')
393 self.inputencoding = get_value(self.header, b"\\inputencoding", 0,
394 default = b"auto").decode('ascii')
395 self.format = self.read_format()
396 self.encoding = get_encoding(self.language,
397 self.inputencoding, self.format,
399 self.initial_version = self.read_version()
401 # Second pass over header and preamble, now we know the file encoding
402 # Do not forget the textclass (Debian bug #700828)
403 self.textclass = self.textclass.decode(self.encoding)
404 self.backend = get_backend(self.textclass)
405 for i in range(len(self.header)):
406 self.header[i] = self.header[i].decode(self.encoding)
407 for i in range(len(self.preamble)):
408 self.preamble[i] = self.preamble[i].decode(self.encoding)
409 for i in range(len(self.body)):
410 self.body[i] = self.body[i].decode(self.encoding)
414 line = self.input.readline().decode(self.encoding)
417 self.body.append(trim_eol(line))
421 " Writes the LyX file to self.output."
422 self.choose_output(self.output)
426 if self.encoding == "auto":
427 self.encoding = get_encoding(self.language, self.encoding,
428 self.format, self.cjk_encoding)
430 i = find_token(self.header, '\\textclass', 0) + 1
431 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
432 header = self.header[:i] + preamble + self.header[i:]
436 for line in header + [''] + self.body:
437 self.output.write(line+u"\n")
440 def choose_output(self, output):
441 """Choose output streams dealing transparently with
444 # This is a bit complicated, because we need to be compatible both with
445 # python 2 and python 3. Therefore we handle the encoding here and not
446 # when writing individual lines and may need up to 3 layered file like
450 outputfileobj = open(output, 'wb')
452 # We cannot not use stdout directly since it needs text, not bytes in python 3
453 outputfileobj = os.fdopen(sys.stdout.fileno(), 'wb')
454 # We cannot not use gzip.open() since it is not supported by python 2
455 zipbuffer = gzip.GzipFile(mode='wb', fileobj=outputfileobj)
456 # We do not want to use different newlines on different OSes inside zipped files
457 self.output = io.TextIOWrapper(zipbuffer, encoding=self.encoding, newline='\n')
460 self.output = io.open(output, 'w', encoding=self.encoding)
462 self.output = io.open(sys.stdout.fileno(), 'w', encoding=self.encoding)
465 def choose_input(self, input):
466 """Choose input stream, dealing transparently with
469 # Since we do not know the encoding yet we need to read the input as
470 # bytes in binary mode, and convert later to unicode.
471 if input and input != u'-':
472 self.dir = os.path.dirname(os.path.abspath(input))
474 gzip.open(input).readline()
475 self.input = gzip.open(input)
476 self.compressed = True
478 self.input = open(input, 'rb')
479 self.compressed = False
482 self.input = os.fdopen(sys.stdin.fileno(), 'rb')
483 self.compressed = False
486 def lyxformat(self, format):
487 " Returns the file format representation, an integer."
488 result = format_re.match(format)
490 format = int(result.group(1) + result.group(2))
494 self.error(str(format) + ": " + "Invalid LyX file.")
496 if format in formats_list():
499 self.error(str(format) + ": " + "Format not supported.")
503 def read_version(self):
504 """ Searchs for clues of the LyX version used to write the
505 file, returns the most likely value, or None otherwise."""
507 for line in self.header:
511 line = line.replace("fix",".")
512 # need to test original_tex2lyx_version first because tex2lyx
513 # writes "#LyX file created by tex2lyx 2.2"
514 result = original_tex2lyx_version.match(line)
516 result = original_version.match(line)
518 # Special know cases: reLyX and KLyX
519 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
522 res = result.group(1)
525 #self.warning("Version %s" % result.group(1))
527 self.warning(str(self.header[:2]))
531 def set_version(self):
532 " Set the header with the version used."
534 initial_comment = " ".join(["#LyX %s created this file." % version__,
535 "For more info see http://www.lyx.org/"])
537 # Simple heuristic to determine the comment that always starts
539 if self.header[0].startswith("#"):
540 self.header[0] = initial_comment
542 self.header.insert(0, initial_comment)
544 # Old lyx files had a two lines comment header:
545 # 1) the first line had the user who had created it
546 # 2) the second line had the lyx version used
547 # later we decided that 1) was a privacy risk for no gain
548 # here we remove the second line effectively erasing 1)
549 if self.header[1][0] == '#':
553 def read_format(self):
554 " Read from the header the fileformat of the present LyX file."
555 for line in self.header:
557 result = fileformat.match(line)
559 result = fileformat.match(line.decode('ascii'))
561 return self.lyxformat(result.group(1))
563 self.error("Invalid LyX File: Missing format.")
567 def set_format(self):
568 " Set the file format of the file, in the header."
569 if self.format <= 217:
570 format = str(float(self.format)/100)
572 format = str(self.format)
573 i = find_token(self.header, "\\lyxformat", 0)
574 self.header[i] = "\\lyxformat %s" % format
577 def set_textclass(self):
578 i = find_token(self.header, "\\textclass", 0)
579 self.header[i] = "\\textclass %s" % self.textclass
582 #Note that the module will be added at the END of the extant ones
583 def add_module(self, module):
584 i = find_token(self.header, "\\begin_modules", 0)
586 #No modules yet included
587 i = find_token(self.header, "\\textclass", 0)
589 self.warning("Malformed LyX document: No \\textclass!!")
591 modinfo = ["\\begin_modules", module, "\\end_modules"]
592 self.header[i + 1: i + 1] = modinfo
594 j = find_token(self.header, "\\end_modules", i)
596 self.warning("(add_module)Malformed LyX document: No \\end_modules.")
598 k = find_token(self.header, module, i)
599 if k != -1 and k < j:
601 self.header.insert(j, module)
604 def get_module_list(self):
605 i = find_token(self.header, "\\begin_modules", 0)
608 j = find_token(self.header, "\\end_modules", i)
609 return self.header[i + 1 : j]
612 def set_module_list(self, mlist):
613 modbegin = find_token(self.header, "\\begin_modules", 0)
614 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
616 #No modules yet included
617 tclass = find_token(self.header, "\\textclass", 0)
619 self.warning("Malformed LyX document: No \\textclass!!")
621 modbegin = tclass + 1
622 self.header[modbegin:modbegin] = newmodlist
624 modend = find_token(self.header, "\\end_modules", modbegin)
626 self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
628 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
629 self.header[modbegin:modend + 1] = newmodlist
632 def set_parameter(self, param, value):
633 " Set the value of the header parameter."
634 i = find_token(self.header, '\\' + param, 0)
636 self.warning('Parameter not found in the header: %s' % param, 3)
638 self.header[i] = '\\%s %s' % (param, str(value))
641 def is_default_layout(self, layout):
642 " Check whether a layout is the default layout of this class."
643 # FIXME: Check against the real text class default layout
644 if layout == 'Standard' or layout == self.default_layout:
650 "Convert from current (self.format) to self.end_format."
651 if self.format == self.end_format:
652 self.warning("No conversion needed: Target format %s "
653 "same as current format!" % self.format, default_debug__)
656 mode, conversion_chain = self.chain()
657 self.warning("conversion chain: " + str(conversion_chain), 3)
659 for step in conversion_chain:
660 steps = getattr(__import__("lyx_" + step), mode)
662 self.warning("Convertion step: %s - %s" % (step, mode),
665 self.error("The conversion to an older "
666 "format (%s) is not implemented." % self.format)
668 multi_conv = len(steps) != 1
669 for version, table in steps:
671 (self.format >= version and mode == "convert") or\
672 (self.format <= version and mode == "revert"):
680 self.warning("An error ocurred in %s, %s" %
681 (version, str(conv)),
683 if not self.try_hard:
687 self.warning("%lf: Elapsed time on %s" %
688 (time.time() - init_t,
689 str(conv)), default_debug__ +
691 self.format = version
692 if self.end_format == self.format:
697 """ This is where all the decisions related with the
698 conversion are taken. It returns a list of modules needed to
699 convert the LyX file from self.format to self.end_format"""
701 self.start = self.format
705 for rel in format_relation:
706 if self.initial_version in rel[2]:
708 initial_step = rel[0]
712 if not correct_version:
714 self.warning("Version does not match file format, "
715 "discarding it. (Version %s, format %d)" %
716 (self.initial_version, self.format))
717 for rel in format_relation:
719 initial_step = rel[0]
722 # This should not happen, really.
723 self.error("Format not supported.")
725 # Find the final step
726 for rel in format_relation:
727 if self.end_format in rel[1]:
731 self.error("Format not supported.")
733 # Convertion mode, back or forth
735 if (initial_step, self.start) < (final_step, self.end_format):
738 for step in format_relation:
739 if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
740 full_steps.append(step)
741 if full_steps[0][1][-1] == self.format:
742 full_steps = full_steps[1:]
743 for step in full_steps:
744 steps.append(step[0])
747 relation_format = format_relation[:]
748 relation_format.reverse()
751 for step in relation_format:
752 if final_step <= step[0] <= initial_step:
753 steps.append(step[0])
756 if last_step[1][-1] == self.end_format:
759 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
763 # Part of an unfinished attempt to make lyx2lyx gave a more
764 # structured view of the document.
765 # def get_toc(self, depth = 4):
766 # " Returns the TOC of this LyX document."
767 # paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
768 # 'Subsection' : 3, 'Subsubsection': 4}
769 # allowed_insets = ['Quotes']
770 # allowed_parameters = ('\\paragraph_spacing', '\\noindent',
771 # '\\align', '\\labelwidthstring',
772 # "\\start_of_appendix", "\\leftindent")
774 # for section in paragraphs_filter.keys():
775 # sections.append('\\begin_layout %s' % section)
780 # i = find_tokens(self.body, sections, i)
784 # j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
786 # self.warning('Incomplete file.', 0)
789 # section = self.body[i].split()[1]
790 # if section[-1] == '*':
791 # section = section[:-1]
796 # # skip paragraph parameters
797 # while not self.body[k].strip() or self.body[k].split()[0] \
798 # in allowed_parameters:
802 # if check_token(self.body[k], '\\begin_inset'):
803 # inset = self.body[k].split()[1]
804 # end = find_end_of_inset(self.body, k)
805 # if end == -1 or end > j:
806 # self.warning('Malformed file.', 0)
808 # if inset in allowed_insets:
809 # par.extend(self.body[k: end+1])
812 # par.append(self.body[k])
815 # # trim empty lines in the end.
816 # while par and par[-1].strip() == '':
819 # toc_par.append(Paragraph(section, par))
826 class File(LyX_base):
827 " This class reads existing LyX files."
829 def __init__(self, end_format = 0, input = u'', output = u'', error = u'',
830 debug = default_debug__, try_hard = 0, cjk_encoding = u'',
831 final_version = u'', systemlyxdir = u''):
832 LyX_base.__init__(self, end_format, input, output, error,
833 debug, try_hard, cjk_encoding, final_version,
838 # FIXME: header settings are completely outdated, don't use like this
839 #class NewFile(LyX_base):
840 # " This class is to create new LyX files."
841 # def set_header(self, **params):
842 # # set default values
843 # self.header.extend([
844 # "#LyX xxxx created this file."
845 # "For more info see http://www.lyx.org/",
847 # "\\begin_document",
849 # "\\textclass article",
850 # "\\language english",
851 # "\\inputencoding auto",
852 # "\\font_roman default",
853 # "\\font_sans default",
854 # "\\font_typewriter default",
855 # "\\font_default_family default",
857 # "\\font_osf false",
858 # "\\font_sf_scale 100",
859 # "\\font_tt_scale 100",
860 # "\\graphics default",
861 # "\\paperfontsize default",
862 # "\\papersize default",
863 # "\\use_geometry false",
865 # "\\cite_engine basic",
866 # "\\use_bibtopic false",
867 # "\\use_indices false",
868 # "\\paperorientation portrait",
871 # "\\paragraph_separation indent",
872 # "\\defskip medskip",
873 # "\\quotes_language english",
874 # "\\papercolumns 1",
876 # "\\paperpagestyle default",
877 # "\\tracking_changes false",
880 # self.format = get_end_format()
881 # for param in params:
882 # self.set_parameter(param, params[param])
885 # def set_body(self, paragraphs):
886 # self.body.extend(['\\begin_body',''])
888 # for par in paragraphs:
889 # self.body.extend(par.asLines())
891 # self.body.extend(['','\\end_body', '\\end_document'])
894 # Part of an unfinished attempt to make lyx2lyx gave a more
895 # structured view of the document.
897 # # unfinished implementation, it is missing the Text and Insets
899 # " This class represents the LyX paragraphs."
900 # def __init__(self, name, body=[], settings = [], child = []):
902 # name: paragraph name.
903 # body: list of lines of body text.
904 # child: list of paragraphs that descend from this paragraph.
908 # self.settings = settings
912 # """ Converts the paragraph to a list of strings, representing
913 # it in the LyX file."""
915 # result = ['','\\begin_layout %s' % self.name]
916 # result.extend(self.settings)
918 # result.extend(self.body)
919 # result.append('\\end_layout')
924 # result.append('\\begin_deeper')
925 # for node in self.child:
926 # result.extend(node.asLines())
927 # result.append('\\end_deeper')