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
34 import lyx2lyx_version
35 version__ = lyx2lyx_version.version
36 except: # we are running from build directory so assume the last version
41 # Provide support for both python 2 and 3
42 PY2 = sys.version_info[0] == 2
43 # End of code to support for both python 2 and 3
45 ####################################################################
46 # Private helper functions
48 def find_end_of_inset(lines, i):
49 " Find beginning of inset, where lines[i] is included."
50 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
52 def minor_versions(major, last_minor_version):
53 """ Generate minor versions, using major as prefix and minor
54 versions from 0 until last_minor_version, plus the generic version.
58 minor_versions("1.2", 4) ->
59 [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
61 return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
64 # End of helper functions
65 ####################################################################
68 # Regular expressions used
69 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
70 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
71 original_version = re.compile(r".*?LyX ([\d.]*)")
72 original_tex2lyx_version = re.compile(r".*?tex2lyx ([\d.]*)")
75 # file format information:
76 # file, supported formats, stable release versions
77 format_relation = [("0_06", [200], minor_versions("0.6" , 4)),
78 ("0_08", [210], minor_versions("0.8" , 6) + ["0.7"]),
79 ("0_10", [210], minor_versions("0.10", 7) + ["0.9"]),
80 ("0_12", [215], minor_versions("0.12", 1) + ["0.11"]),
81 ("1_0", [215], minor_versions("1.0" , 4)),
82 ("1_1", [215], minor_versions("1.1" , 4)),
83 ("1_1_5", [216], ["1.1", "1.1.5","1.1.5.1","1.1.5.2"]),
84 ("1_1_6_0", [217], ["1.1", "1.1.6","1.1.6.1","1.1.6.2"]),
85 ("1_1_6_3", [218], ["1.1", "1.1.6.3","1.1.6.4"]),
86 ("1_2", [220], minor_versions("1.2" , 4)),
87 ("1_3", [221], minor_versions("1.3" , 7)),
88 # Note that range(i,j) is up to j *excluded*.
89 ("1_4", list(range(222,246)), minor_versions("1.4" , 5)),
90 ("1_5", list(range(246,277)), minor_versions("1.5" , 7)),
91 ("1_6", list(range(277,346)), minor_versions("1.6" , 10)),
92 ("2_0", list(range(346,414)), minor_versions("2.0" , 8)),
93 ("2_1", list(range(414,475)), minor_versions("2.1" , 5)),
94 ("2_2", list(range(475,509)), minor_versions("2.2" , 0)),
95 ("2_3", (), minor_versions("2.3" , 0))
98 ####################################################################
99 # This is useful just for development versions #
100 # if the list of supported formats is empty get it from last step #
101 if not format_relation[-1][1]:
102 step, mode = format_relation[-1][0], "convert"
103 convert = getattr(__import__("lyx_" + step), mode)
104 format_relation[-1] = (step,
105 [conv[0] for conv in convert],
106 format_relation[-1][2])
108 ####################################################################
111 " Returns a list with supported file formats."
113 for version in format_relation:
114 for format in version[1]:
115 if format not in formats:
116 formats.append(format)
121 " Returns a list with supported file formats."
122 out = """Major version:
126 for version in format_relation:
127 major = str(version[2][0])
128 versions = str(version[2][1:])
129 if len(version[1]) == 1:
130 formats = str(version[1][0])
132 formats = "%s - %s" % (version[1][-1], version[1][0])
133 out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats)
137 def get_end_format():
138 " Returns the more recent file format available."
139 # this check will fail only when we have a new version
140 # and there is no format change yet.
141 if format_relation[-1][1]:
142 return format_relation[-1][1][-1]
143 return format_relation[-2][1][-1]
146 def get_backend(textclass):
147 " For _textclass_ returns its backend."
148 if textclass == "linuxdoc" or textclass == "manpage":
150 if textclass.startswith("docbook") or textclass.startswith("agu-"):
156 " Remove end of line char(s)."
157 if line[-1] != '\n' and line[-1] != '\r':
158 # May happen for the last line of a document
160 if line[-2:-1] == '\r':
166 def trim_eol_binary(line):
167 " Remove end of line char(s)."
168 if line[-1] != 10 and line[-1] != 13:
169 # May happen for the last line of a document
171 if line[-2:-1] == 13:
177 def get_encoding(language, inputencoding, format, cjk_encoding):
178 " Returns enconding of the lyx file"
181 # CJK-LyX encodes files using the current locale encoding.
182 # This means that files created by CJK-LyX can only be converted using
183 # the correct locale settings unless the encoding is given as commandline
185 if cjk_encoding == 'auto':
186 return locale.getpreferredencoding()
189 from lyx2lyx_lang import lang
190 if inputencoding == "auto" or inputencoding == "default":
191 return lang[language][3]
192 if inputencoding == "":
194 if inputencoding == "utf8x":
196 # python does not know the alias latin9
197 if inputencoding == "latin9":
205 """This class carries all the information of the LyX file."""
207 def __init__(self, end_format = 0, input = u'', output = u'', error = u'',
208 debug = default_debug__, try_hard = 0, cjk_encoding = u'',
209 final_version = u'', systemlyxdir = u'', language = u'english',
213 end_format: final format that the file should be converted. (integer)
214 input: the name of the input source, if empty resort to standard input.
215 output: the name of the output file, if empty use the standard output.
216 error: the name of the error file, if empty use the standard error.
217 debug: debug level, O means no debug, as its value increases be more verbose.
219 self.choose_input(input)
223 self.err = open(error, "w")
225 self.err = sys.stderr
228 self.try_hard = try_hard
229 self.cjk_encoding = cjk_encoding
232 self.end_format = self.lyxformat(end_format)
234 # In case the target version and format are both specified
235 # verify that they are compatible. If not send a warning
236 # and ignore the version.
238 message = "Incompatible version %s for specified format %d" % (
239 final_version, self.end_format)
240 for version in format_relation:
241 if self.end_format in version[1]:
242 if final_version not in version[2]:
243 self.warning(message)
246 for version in format_relation:
247 if final_version in version[2]:
248 # set the last format for that version
249 self.end_format = version[1][-1]
254 self.end_format = get_end_format()
256 if not final_version:
257 for step in format_relation:
258 if self.end_format in step[1]:
259 final_version = step[2][1]
260 self.final_version = final_version
261 self.warning("Final version: %s" % self.final_version, 10)
262 self.warning("Final format: %d" % self.end_format, 10)
264 self.backend = "latex"
265 self.textclass = "article"
266 # This is a hack: We use '' since we don't know the default
267 # layout of the text class. LyX will parse it as default layout.
268 # FIXME: Read the layout file and use the real default layout
269 self.default_layout = ''
274 self.encoding = encoding
275 self.language = language
276 self.systemlyxdir = systemlyxdir
279 def warning(self, message, debug_level= default_debug__):
280 """ Emits warning to self.error, if the debug_level is less
281 than the self.debug."""
282 if debug_level <= self.debug:
283 self.err.write("Warning: " + message + "\n")
286 def error(self, message):
287 " Emits a warning and exits if not in try_hard mode."
288 self.warning(message)
289 if not self.try_hard:
290 self.warning("Quitting.")
297 """Reads a file into the self.header and
298 self.body parts, from self.input."""
300 # First pass: Read header to determine file encoding
301 # If we are running under python3 then all strings are binary in this
302 # pass. In some cases we need to convert binary to unicode in order to
303 # use our parser tools. Since we do not know the true encoding yet we
304 # use latin1. This works since a) the parts we are interested in are
305 # pure ASCII (subset of latin1) and b) in contrast to pure ascii or
306 # utf8, one can decode any 8byte string using latin1.
308 line = self.input.readline()
310 # eof found before end of header
311 self.error("Invalid LyX file: Missing body.")
314 line = trim_eol(line)
317 line = trim_eol_binary(line)
318 decoded = line.decode('latin1')
319 if check_token(decoded, '\\begin_preamble'):
321 line = self.input.readline()
323 # eof found before end of header
324 self.error("Invalid LyX file: Missing body.")
327 line = trim_eol(line)
330 line = trim_eol_binary(line)
331 decoded = line.decode('latin1')
332 if check_token(decoded, '\\end_preamble'):
335 if decoded.split()[:0] in ("\\layout",
336 "\\begin_layout", "\\begin_body"):
338 self.warning("Malformed LyX file:"
339 "Missing '\\end_preamble'."
340 "\nAdding it now and hoping"
343 self.preamble.append(line)
345 if check_token(decoded, '\\end_preamble'):
352 if decoded.split()[0] in ("\\layout", "\\begin_layout",
353 "\\begin_body", "\\begin_deeper"):
354 self.body.append(line)
357 self.header.append(line)
360 i = find_token(self.header, '\\textclass', 0)
362 i = find_token(self.header, b'\\textclass', 0)
364 self.warning("Malformed LyX file: Missing '\\textclass'.")
366 i = find_token(self.header, '\\lyxformat', 0) + 1
367 self.header[i:i] = ['\\textclass article']
369 i = find_token(self.header, b'\\lyxformat', 0) + 1
370 self.header[i:i] = [b'\\textclass article']
373 self.textclass = get_value(self.header, "\\textclass", 0,
375 self.language = get_value(self.header, "\\language", 0,
377 self.inputencoding = get_value(self.header, "\\inputencoding", 0,
380 self.textclass = get_value(self.header, b"\\textclass", 0,
382 self.language = get_value(self.header, b"\\language", 0,
383 default = b"english").decode('ascii')
384 self.inputencoding = get_value(self.header, b"\\inputencoding", 0,
385 default = b"auto").decode('ascii')
386 self.format = self.read_format()
387 self.encoding = get_encoding(self.language,
388 self.inputencoding, self.format,
390 self.initial_version = self.read_version()
392 # Second pass over header and preamble, now we know the file encoding
393 # Do not forget the textclass (Debian bug #700828)
394 self.textclass = self.textclass.decode(self.encoding)
395 self.backend = get_backend(self.textclass)
396 for i in range(len(self.header)):
397 self.header[i] = self.header[i].decode(self.encoding)
398 for i in range(len(self.preamble)):
399 self.preamble[i] = self.preamble[i].decode(self.encoding)
400 for i in range(len(self.body)):
401 self.body[i] = self.body[i].decode(self.encoding)
405 line = self.input.readline().decode(self.encoding)
408 self.body.append(trim_eol(line))
412 " Writes the LyX file to self.output."
413 self.choose_output(self.output)
417 if self.encoding == "auto":
418 self.encoding = get_encoding(self.language, self.encoding,
419 self.format, self.cjk_encoding)
421 i = find_token(self.header, '\\textclass', 0) + 1
422 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
423 header = self.header[:i] + preamble + self.header[i:]
427 for line in header + [''] + self.body:
428 self.output.write(line+u"\n")
431 def choose_output(self, output):
432 """Choose output streams dealing transparently with
435 # This is a bit complicated, because we need to be compatible both with
436 # python 2 and python 3. Therefore we handle the encoding here and not
437 # when writing individual lines and may need up to 3 layered file like
441 outputfileobj = open(output, 'wb')
443 # We cannot not use stdout directly since it needs text, not bytes in python 3
444 outputfileobj = os.fdopen(sys.stdout.fileno(), 'wb')
445 # We cannot not use gzip.open() since it is not supported by python 2
446 zipbuffer = gzip.GzipFile(mode='wb', fileobj=outputfileobj)
447 # We do not want to use different newlines on different OSes inside zipped files
448 self.output = io.TextIOWrapper(zipbuffer, encoding=self.encoding, newline='\n')
451 self.output = io.open(output, 'w', encoding=self.encoding)
453 self.output = io.open(sys.stdout.fileno(), 'w', encoding=self.encoding)
456 def choose_input(self, input):
457 """Choose input stream, dealing transparently with
460 # Since we do not know the encoding yet we need to read the input as
461 # bytes in binary mode, and convert later to unicode.
462 if input and input != u'-':
463 self.dir = os.path.dirname(os.path.abspath(input))
465 gzip.open(input).readline()
466 self.input = gzip.open(input)
467 self.compressed = True
469 self.input = open(input, 'rb')
470 self.compressed = False
473 self.input = os.fdopen(sys.stdin.fileno(), 'rb')
474 self.compressed = False
477 def lyxformat(self, format):
478 " Returns the file format representation, an integer."
479 result = format_re.match(format)
481 format = int(result.group(1) + result.group(2))
485 self.error(str(format) + ": " + "Invalid LyX file.")
487 if format in formats_list():
490 self.error(str(format) + ": " + "Format not supported.")
494 def read_version(self):
495 """ Searchs for clues of the LyX version used to write the
496 file, returns the most likely value, or None otherwise."""
498 for line in self.header:
502 line = line.replace("fix",".")
503 # need to test original_tex2lyx_version first because tex2lyx
504 # writes "#LyX file created by tex2lyx 2.2"
505 result = original_tex2lyx_version.match(line)
507 result = original_version.match(line)
509 # Special know cases: reLyX and KLyX
510 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
513 res = result.group(1)
516 #self.warning("Version %s" % result.group(1))
518 self.warning(str(self.header[:2]))
522 def set_version(self):
523 " Set the header with the version used."
525 initial_comment = " ".join(["#LyX %s created this file." % version__,
526 "For more info see http://www.lyx.org/"])
528 # Simple heuristic to determine the comment that always starts
530 if self.header[0].startswith("#"):
531 self.header[0] = initial_comment
533 self.header.insert(0, initial_comment)
535 # Old lyx files had a two lines comment header:
536 # 1) the first line had the user who had created it
537 # 2) the second line had the lyx version used
538 # later we decided that 1) was a privacy risk for no gain
539 # here we remove the second line effectively erasing 1)
540 if self.header[1][0] == '#':
544 def read_format(self):
545 " Read from the header the fileformat of the present LyX file."
546 for line in self.header:
548 result = fileformat.match(line)
550 result = fileformat.match(line.decode('ascii'))
552 return self.lyxformat(result.group(1))
554 self.error("Invalid LyX File: Missing format.")
558 def set_format(self):
559 " Set the file format of the file, in the header."
560 if self.format <= 217:
561 format = str(float(self.format)/100)
563 format = str(self.format)
564 i = find_token(self.header, "\\lyxformat", 0)
565 self.header[i] = "\\lyxformat %s" % format
568 def set_textclass(self):
569 i = find_token(self.header, "\\textclass", 0)
570 self.header[i] = "\\textclass %s" % self.textclass
573 #Note that the module will be added at the END of the extant ones
574 def add_module(self, module):
575 i = find_token(self.header, "\\begin_modules", 0)
577 #No modules yet included
578 i = find_token(self.header, "\\textclass", 0)
580 self.warning("Malformed LyX document: No \\textclass!!")
582 modinfo = ["\\begin_modules", module, "\\end_modules"]
583 self.header[i + 1: i + 1] = modinfo
585 j = find_token(self.header, "\\end_modules", i)
587 self.warning("(add_module)Malformed LyX document: No \\end_modules.")
589 k = find_token(self.header, module, i)
590 if k != -1 and k < j:
592 self.header.insert(j, module)
595 def get_module_list(self):
596 i = find_token(self.header, "\\begin_modules", 0)
599 j = find_token(self.header, "\\end_modules", i)
600 return self.header[i + 1 : j]
603 def set_module_list(self, mlist):
604 modbegin = find_token(self.header, "\\begin_modules", 0)
605 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
607 #No modules yet included
608 tclass = find_token(self.header, "\\textclass", 0)
610 self.warning("Malformed LyX document: No \\textclass!!")
612 modbegin = tclass + 1
613 self.header[modbegin:modbegin] = newmodlist
615 modend = find_token(self.header, "\\end_modules", modbegin)
617 self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
619 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
620 self.header[modbegin:modend + 1] = newmodlist
623 def set_parameter(self, param, value):
624 " Set the value of the header parameter."
625 i = find_token(self.header, '\\' + param, 0)
627 self.warning('Parameter not found in the header: %s' % param, 3)
629 self.header[i] = '\\%s %s' % (param, str(value))
632 def is_default_layout(self, layout):
633 " Check whether a layout is the default layout of this class."
634 # FIXME: Check against the real text class default layout
635 if layout == 'Standard' or layout == self.default_layout:
641 "Convert from current (self.format) to self.end_format."
642 if self.format == self.end_format:
643 self.warning("No conversion needed: Target format %s "
644 "same as current format!" % self.format, default_debug__)
647 mode, conversion_chain = self.chain()
648 self.warning("conversion chain: " + str(conversion_chain), 3)
650 for step in conversion_chain:
651 steps = getattr(__import__("lyx_" + step), mode)
653 self.warning("Convertion step: %s - %s" % (step, mode),
656 self.error("The conversion to an older "
657 "format (%s) is not implemented." % self.format)
659 multi_conv = len(steps) != 1
660 for version, table in steps:
662 (self.format >= version and mode == "convert") or\
663 (self.format <= version and mode == "revert"):
671 self.warning("An error ocurred in %s, %s" %
672 (version, str(conv)),
674 if not self.try_hard:
678 self.warning("%lf: Elapsed time on %s" %
679 (time.time() - init_t,
680 str(conv)), default_debug__ +
682 self.format = version
683 if self.end_format == self.format:
688 """ This is where all the decisions related with the
689 conversion are taken. It returns a list of modules needed to
690 convert the LyX file from self.format to self.end_format"""
692 self.start = self.format
696 for rel in format_relation:
697 if self.initial_version in rel[2]:
699 initial_step = rel[0]
703 if not correct_version:
705 self.warning("Version does not match file format, "
706 "discarding it. (Version %s, format %d)" %
707 (self.initial_version, self.format))
708 for rel in format_relation:
710 initial_step = rel[0]
713 # This should not happen, really.
714 self.error("Format not supported.")
716 # Find the final step
717 for rel in format_relation:
718 if self.end_format in rel[1]:
722 self.error("Format not supported.")
724 # Convertion mode, back or forth
726 if (initial_step, self.start) < (final_step, self.end_format):
729 for step in format_relation:
730 if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
731 full_steps.append(step)
732 if full_steps[0][1][-1] == self.format:
733 full_steps = full_steps[1:]
734 for step in full_steps:
735 steps.append(step[0])
738 relation_format = format_relation[:]
739 relation_format.reverse()
742 for step in relation_format:
743 if final_step <= step[0] <= initial_step:
744 steps.append(step[0])
747 if last_step[1][-1] == self.end_format:
750 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
754 # Part of an unfinished attempt to make lyx2lyx gave a more
755 # structured view of the document.
756 # def get_toc(self, depth = 4):
757 # " Returns the TOC of this LyX document."
758 # paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
759 # 'Subsection' : 3, 'Subsubsection': 4}
760 # allowed_insets = ['Quotes']
761 # allowed_parameters = ('\\paragraph_spacing', '\\noindent',
762 # '\\align', '\\labelwidthstring',
763 # "\\start_of_appendix", "\\leftindent")
765 # for section in paragraphs_filter.keys():
766 # sections.append('\\begin_layout %s' % section)
771 # i = find_tokens(self.body, sections, i)
775 # j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
777 # self.warning('Incomplete file.', 0)
780 # section = self.body[i].split()[1]
781 # if section[-1] == '*':
782 # section = section[:-1]
787 # # skip paragraph parameters
788 # while not self.body[k].strip() or self.body[k].split()[0] \
789 # in allowed_parameters:
793 # if check_token(self.body[k], '\\begin_inset'):
794 # inset = self.body[k].split()[1]
795 # end = find_end_of_inset(self.body, k)
796 # if end == -1 or end > j:
797 # self.warning('Malformed file.', 0)
799 # if inset in allowed_insets:
800 # par.extend(self.body[k: end+1])
803 # par.append(self.body[k])
806 # # trim empty lines in the end.
807 # while par and par[-1].strip() == '':
810 # toc_par.append(Paragraph(section, par))
817 class File(LyX_base):
818 " This class reads existing LyX files."
820 def __init__(self, end_format = 0, input = u'', output = u'', error = u'',
821 debug = default_debug__, try_hard = 0, cjk_encoding = u'',
822 final_version = u'', systemlyxdir = u''):
823 LyX_base.__init__(self, end_format, input, output, error,
824 debug, try_hard, cjk_encoding, final_version,
829 # FIXME: header settings are completely outdated, don't use like this
830 #class NewFile(LyX_base):
831 # " This class is to create new LyX files."
832 # def set_header(self, **params):
833 # # set default values
834 # self.header.extend([
835 # "#LyX xxxx created this file."
836 # "For more info see http://www.lyx.org/",
838 # "\\begin_document",
840 # "\\textclass article",
841 # "\\language english",
842 # "\\inputencoding auto",
843 # "\\font_roman default",
844 # "\\font_sans default",
845 # "\\font_typewriter default",
846 # "\\font_default_family default",
848 # "\\font_osf false",
849 # "\\font_sf_scale 100",
850 # "\\font_tt_scale 100",
851 # "\\graphics default",
852 # "\\paperfontsize default",
853 # "\\papersize default",
854 # "\\use_geometry false",
856 # "\\cite_engine basic",
857 # "\\use_bibtopic false",
858 # "\\use_indices false",
859 # "\\paperorientation portrait",
862 # "\\paragraph_separation indent",
863 # "\\defskip medskip",
864 # "\\quotes_language english",
865 # "\\papercolumns 1",
867 # "\\paperpagestyle default",
868 # "\\tracking_changes false",
871 # self.format = get_end_format()
872 # for param in params:
873 # self.set_parameter(param, params[param])
876 # def set_body(self, paragraphs):
877 # self.body.extend(['\\begin_body',''])
879 # for par in paragraphs:
880 # self.body.extend(par.asLines())
882 # self.body.extend(['','\\end_body', '\\end_document'])
885 # Part of an unfinished attempt to make lyx2lyx gave a more
886 # structured view of the document.
888 # # unfinished implementation, it is missing the Text and Insets
890 # " This class represents the LyX paragraphs."
891 # def __init__(self, name, body=[], settings = [], child = []):
893 # name: paragraph name.
894 # body: list of lines of body text.
895 # child: list of paragraphs that descend from this paragraph.
899 # self.settings = settings
903 # """ Converts the paragraph to a list of strings, representing
904 # it in the LyX file."""
906 # result = ['','\\begin_layout %s' % self.name]
907 # result.extend(self.settings)
909 # result.extend(self.body)
910 # result.append('\\end_layout')
915 # result.append('\\begin_deeper')
916 # for node in self.child:
917 # result.extend(node.asLines())
918 # result.append('\\end_deeper')