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
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.]*)")
67 original_tex2lyx_version = re.compile(r".*?tex2lyx ([\d.]*)")
70 # file format information:
71 # file, supported formats, stable release versions
72 format_relation = [("0_06", [200], minor_versions("0.6" , 4)),
73 ("0_08", [210], minor_versions("0.8" , 6) + ["0.7"]),
74 ("0_10", [210], minor_versions("0.10", 7) + ["0.9"]),
75 ("0_12", [215], minor_versions("0.12", 1) + ["0.11"]),
76 ("1_0", [215], minor_versions("1.0" , 4)),
77 ("1_1", [215], minor_versions("1.1" , 4)),
78 ("1_1_5", [216], ["1.1", "1.1.5","1.1.5.1","1.1.5.2"]),
79 ("1_1_6_0", [217], ["1.1", "1.1.6","1.1.6.1","1.1.6.2"]),
80 ("1_1_6_3", [218], ["1.1", "1.1.6.3","1.1.6.4"]),
81 ("1_2", [220], minor_versions("1.2" , 4)),
82 ("1_3", [221], minor_versions("1.3" , 7)),
83 # Note that range(i,j) is up to j *excluded*.
84 ("1_4", list(range(222,246)), minor_versions("1.4" , 5)),
85 ("1_5", list(range(246,277)), minor_versions("1.5" , 7)),
86 ("1_6", list(range(277,346)), minor_versions("1.6" , 10)),
87 ("2_0", list(range(346,414)), minor_versions("2.0" , 8)),
88 ("2_1", list(range(414,475)), minor_versions("2.1" , 5)),
89 ("2_2", list(range(475,509)), minor_versions("2.2" , 0)),
90 ("2_3", list(range(509,510)), minor_versions("2.3" , 0))
93 ####################################################################
94 # This is useful just for development versions #
95 # if the list of supported formats is empty get it from last step #
96 if not format_relation[-1][1]:
97 step, mode = format_relation[-1][0], "convert"
98 convert = getattr(__import__("lyx_" + step), mode)
99 format_relation[-1] = (step,
100 [conv[0] for conv in convert],
101 format_relation[-1][2])
103 ####################################################################
106 " Returns a list with supported file formats."
108 for version in format_relation:
109 for format in version[1]:
110 if format not in formats:
111 formats.append(format)
116 " Returns a list with supported file formats."
117 out = """Major version:
121 for version in format_relation:
122 major = str(version[2][0])
123 versions = str(version[2][1:])
124 if len(version[1]) == 1:
125 formats = str(version[1][0])
127 formats = "%s - %s" % (version[1][-1], version[1][0])
128 out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats)
132 def get_end_format():
133 " Returns the more recent file format available."
134 # this check will fail only when we have a new version
135 # and there is no format change yet.
136 if format_relation[-1][1]:
137 return format_relation[-1][1][-1]
138 return format_relation[-2][1][-1]
141 def get_backend(textclass):
142 " For _textclass_ returns its backend."
143 if textclass == "linuxdoc" or textclass == "manpage":
145 if textclass.startswith("docbook") or textclass.startswith("agu-"):
151 " Remove end of line char(s)."
152 if line[-1] != '\n' and line[-1] != '\r':
153 # May happen for the last line of a document
155 if line[-2:-1] == '\r':
161 def get_encoding(language, inputencoding, format, cjk_encoding):
162 " Returns enconding of the lyx file"
165 # CJK-LyX encodes files using the current locale encoding.
166 # This means that files created by CJK-LyX can only be converted using
167 # the correct locale settings unless the encoding is given as commandline
169 if cjk_encoding == 'auto':
170 return locale.getpreferredencoding()
173 from lyx2lyx_lang import lang
174 if inputencoding == "auto" or inputencoding == "default":
175 return lang[language][3]
176 if inputencoding == "":
178 if inputencoding == "utf8x":
180 # python does not know the alias latin9
181 if inputencoding == "latin9":
189 """This class carries all the information of the LyX file."""
191 def __init__(self, end_format = 0, input = "", output = "", error = "",
192 debug = default_debug__, try_hard = 0, cjk_encoding = '',
193 final_version = "", systemlyxdir = '', language = "english",
197 end_format: final format that the file should be converted. (integer)
198 input: the name of the input source, if empty resort to standard input.
199 output: the name of the output file, if empty use the standard output.
200 error: the name of the error file, if empty use the standard error.
201 debug: debug level, O means no debug, as its value increases be more verbose.
203 self.choose_io(input, output)
206 self.err = open(error, "w")
208 self.err = sys.stderr
211 self.try_hard = try_hard
212 self.cjk_encoding = cjk_encoding
215 self.end_format = self.lyxformat(end_format)
217 # In case the target version and format are both specified
218 # verify that they are compatible. If not send a warning
219 # and ignore the version.
221 message = "Incompatible version %s for specified format %d" % (
222 final_version, self.end_format)
223 for version in format_relation:
224 if self.end_format in version[1]:
225 if final_version not in version[2]:
226 self.warning(message)
229 for version in format_relation:
230 if final_version in version[2]:
231 # set the last format for that version
232 self.end_format = version[1][-1]
237 self.end_format = get_end_format()
239 if not final_version:
240 for step in format_relation:
241 if self.end_format in step[1]:
242 final_version = step[2][1]
243 self.final_version = final_version
244 self.warning("Final version: %s" % self.final_version, 10)
245 self.warning("Final format: %d" % self.end_format, 10)
247 self.backend = "latex"
248 self.textclass = "article"
249 # This is a hack: We use '' since we don't know the default
250 # layout of the text class. LyX will parse it as default layout.
251 # FIXME: Read the layout file and use the real default layout
252 self.default_layout = ''
257 self.encoding = encoding
258 self.language = language
259 self.systemlyxdir = systemlyxdir
262 def warning(self, message, debug_level= default_debug__):
263 """ Emits warning to self.error, if the debug_level is less
264 than the self.debug."""
265 if debug_level <= self.debug:
266 self.err.write("Warning: " + message + "\n")
269 def error(self, message):
270 " Emits a warning and exits if not in try_hard mode."
271 self.warning(message)
272 if not self.try_hard:
273 self.warning("Quitting.")
280 """Reads a file into the self.header and
281 self.body parts, from self.input."""
283 # First pass: Read header to determine file encoding
285 line = self.input.readline()
287 # eof found before end of header
288 self.error("Invalid LyX file: Missing body.")
290 line = trim_eol(line)
291 if check_token(line, '\\begin_preamble'):
293 line = self.input.readline()
295 # eof found before end of header
296 self.error("Invalid LyX file: Missing body.")
298 line = trim_eol(line)
299 if check_token(line, '\\end_preamble'):
302 if line.split()[:0] in ("\\layout",
303 "\\begin_layout", "\\begin_body"):
305 self.warning("Malformed LyX file:"
306 "Missing '\\end_preamble'."
307 "\nAdding it now and hoping"
310 self.preamble.append(line)
312 if check_token(line, '\\end_preamble'):
319 if line.split()[0] in ("\\layout", "\\begin_layout",
320 "\\begin_body", "\\begin_deeper"):
321 self.body.append(line)
324 self.header.append(line)
326 i = find_token(self.header, '\\textclass', 0)
328 self.warning("Malformed LyX file: Missing '\\textclass'.")
329 i = find_token(self.header, '\\lyxformat', 0) + 1
330 self.header[i:i] = ['\\textclass article']
332 self.textclass = get_value(self.header, "\\textclass", 0)
333 self.backend = get_backend(self.textclass)
334 self.format = self.read_format()
335 self.language = get_value(self.header, "\\language", 0,
337 self.inputencoding = get_value(self.header, "\\inputencoding",
339 self.encoding = get_encoding(self.language,
340 self.inputencoding, self.format,
342 self.initial_version = self.read_version()
344 # Second pass over header and preamble, now we know the file encoding
345 # Do not forget the textclass (Debian bug #700828)
346 self.textclass = self.textclass.decode(self.encoding)
347 for i in range(len(self.header)):
348 self.header[i] = self.header[i].decode(self.encoding)
349 for i in range(len(self.preamble)):
350 self.preamble[i] = self.preamble[i].decode(self.encoding)
351 for i in range(len(self.body)):
352 self.body[i] = self.body[i].decode(self.encoding)
356 line = self.input.readline().decode(self.encoding)
359 self.body.append(trim_eol(line))
363 " Writes the LyX file to self.output."
367 if self.encoding == "auto":
368 self.encoding = get_encoding(self.language, self.encoding,
369 self.format, self.cjk_encoding)
371 i = find_token(self.header, '\\textclass', 0) + 1
372 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
373 header = self.header[:i] + preamble + self.header[i:]
377 for line in header + [''] + self.body:
378 self.output.write(line.encode(self.encoding)+"\n")
381 def choose_io(self, input, output):
382 """Choose input and output streams, dealing transparently with
386 self.output = open(output, "wb")
388 self.output = sys.stdout
390 if input and input != '-':
391 self.dir = os.path.dirname(os.path.abspath(input))
393 gzip.open(input).readline()
394 self.input = gzip.open(input)
395 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
397 self.input = open(input)
400 self.input = sys.stdin
403 def lyxformat(self, format):
404 " Returns the file format representation, an integer."
405 result = format_re.match(format)
407 format = int(result.group(1) + result.group(2))
411 self.error(str(format) + ": " + "Invalid LyX file.")
413 if format in formats_list():
416 self.error(str(format) + ": " + "Format not supported.")
420 def read_version(self):
421 """ Searchs for clues of the LyX version used to write the
422 file, returns the most likely value, or None otherwise."""
424 for line in self.header:
428 line = line.replace("fix",".")
429 # need to test original_tex2lyx_version first because tex2lyx
430 # writes "#LyX file created by tex2lyx 2.2"
431 result = original_tex2lyx_version.match(line)
433 result = original_version.match(line)
435 # Special know cases: reLyX and KLyX
436 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
439 res = result.group(1)
442 #self.warning("Version %s" % result.group(1))
444 self.warning(str(self.header[:2]))
448 def set_version(self):
449 " Set the header with the version used."
451 initial_comment = " ".join(["#LyX %s created this file." % version__,
452 "For more info see http://www.lyx.org/"])
454 # Simple heuristic to determine the comment that always starts
456 if self.header[0].startswith("#"):
457 self.header[0] = initial_comment
459 self.header.insert(0, initial_comment)
461 # Old lyx files had a two lines comment header:
462 # 1) the first line had the user who had created it
463 # 2) the second line had the lyx version used
464 # later we decided that 1) was a privacy risk for no gain
465 # here we remove the second line effectively erasing 1)
466 if self.header[1][0] == '#':
470 def read_format(self):
471 " Read from the header the fileformat of the present LyX file."
472 for line in self.header:
473 result = fileformat.match(line)
475 return self.lyxformat(result.group(1))
477 self.error("Invalid LyX File.")
481 def set_format(self):
482 " Set the file format of the file, in the header."
483 if self.format <= 217:
484 format = str(float(self.format)/100)
486 format = str(self.format)
487 i = find_token(self.header, "\\lyxformat", 0)
488 self.header[i] = "\\lyxformat %s" % format
491 def set_textclass(self):
492 i = find_token(self.header, "\\textclass", 0)
493 self.header[i] = "\\textclass %s" % self.textclass
496 #Note that the module will be added at the END of the extant ones
497 def add_module(self, module):
498 i = find_token(self.header, "\\begin_modules", 0)
500 #No modules yet included
501 i = find_token(self.header, "\\textclass", 0)
503 self.warning("Malformed LyX document: No \\textclass!!")
505 modinfo = ["\\begin_modules", module, "\\end_modules"]
506 self.header[i + 1: i + 1] = modinfo
508 j = find_token(self.header, "\\end_modules", i)
510 self.warning("(add_module)Malformed LyX document: No \\end_modules.")
512 k = find_token(self.header, module, i)
513 if k != -1 and k < j:
515 self.header.insert(j, module)
518 def get_module_list(self):
519 i = find_token(self.header, "\\begin_modules", 0)
522 j = find_token(self.header, "\\end_modules", i)
523 return self.header[i + 1 : j]
526 def set_module_list(self, mlist):
527 modbegin = find_token(self.header, "\\begin_modules", 0)
528 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
530 #No modules yet included
531 tclass = find_token(self.header, "\\textclass", 0)
533 self.warning("Malformed LyX document: No \\textclass!!")
535 modbegin = tclass + 1
536 self.header[modbegin:modbegin] = newmodlist
538 modend = find_token(self.header, "\\end_modules", modbegin)
540 self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
542 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
543 self.header[modbegin:modend + 1] = newmodlist
546 def set_parameter(self, param, value):
547 " Set the value of the header parameter."
548 i = find_token(self.header, '\\' + param, 0)
550 self.warning('Parameter not found in the header: %s' % param, 3)
552 self.header[i] = '\\%s %s' % (param, str(value))
555 def is_default_layout(self, layout):
556 " Check whether a layout is the default layout of this class."
557 # FIXME: Check against the real text class default layout
558 if layout == 'Standard' or layout == self.default_layout:
564 "Convert from current (self.format) to self.end_format."
565 if self.format == self.end_format:
566 self.warning("No conversion needed: Target format %s "
567 "same as current format!" % self.format, default_debug__)
570 mode, conversion_chain = self.chain()
571 self.warning("conversion chain: " + str(conversion_chain), 3)
573 for step in conversion_chain:
574 steps = getattr(__import__("lyx_" + step), mode)
576 self.warning("Convertion step: %s - %s" % (step, mode),
579 self.error("The conversion to an older "
580 "format (%s) is not implemented." % self.format)
582 multi_conv = len(steps) != 1
583 for version, table in steps:
585 (self.format >= version and mode == "convert") or\
586 (self.format <= version and mode == "revert"):
594 self.warning("An error ocurred in %s, %s" %
595 (version, str(conv)),
597 if not self.try_hard:
601 self.warning("%lf: Elapsed time on %s" %
602 (time.time() - init_t,
603 str(conv)), default_debug__ +
605 self.format = version
606 if self.end_format == self.format:
611 """ This is where all the decisions related with the
612 conversion are taken. It returns a list of modules needed to
613 convert the LyX file from self.format to self.end_format"""
615 self.start = self.format
619 for rel in format_relation:
620 if self.initial_version in rel[2]:
622 initial_step = rel[0]
626 if not correct_version:
628 self.warning("Version does not match file format, "
629 "discarding it. (Version %s, format %d)" %
630 (self.initial_version, self.format))
631 for rel in format_relation:
633 initial_step = rel[0]
636 # This should not happen, really.
637 self.error("Format not supported.")
639 # Find the final step
640 for rel in format_relation:
641 if self.end_format in rel[1]:
645 self.error("Format not supported.")
647 # Convertion mode, back or forth
649 if (initial_step, self.start) < (final_step, self.end_format):
652 for step in format_relation:
653 if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
654 full_steps.append(step)
655 if full_steps[0][1][-1] == self.format:
656 full_steps = full_steps[1:]
657 for step in full_steps:
658 steps.append(step[0])
661 relation_format = format_relation[:]
662 relation_format.reverse()
665 for step in relation_format:
666 if final_step <= step[0] <= initial_step:
667 steps.append(step[0])
670 if last_step[1][-1] == self.end_format:
673 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
677 # Part of an unfinished attempt to make lyx2lyx gave a more
678 # structured view of the document.
679 # def get_toc(self, depth = 4):
680 # " Returns the TOC of this LyX document."
681 # paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
682 # 'Subsection' : 3, 'Subsubsection': 4}
683 # allowed_insets = ['Quotes']
684 # allowed_parameters = ('\\paragraph_spacing', '\\noindent',
685 # '\\align', '\\labelwidthstring',
686 # "\\start_of_appendix", "\\leftindent")
688 # for section in paragraphs_filter.keys():
689 # sections.append('\\begin_layout %s' % section)
694 # i = find_tokens(self.body, sections, i)
698 # j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
700 # self.warning('Incomplete file.', 0)
703 # section = self.body[i].split()[1]
704 # if section[-1] == '*':
705 # section = section[:-1]
710 # # skip paragraph parameters
711 # while not self.body[k].strip() or self.body[k].split()[0] \
712 # in allowed_parameters:
716 # if check_token(self.body[k], '\\begin_inset'):
717 # inset = self.body[k].split()[1]
718 # end = find_end_of_inset(self.body, k)
719 # if end == -1 or end > j:
720 # self.warning('Malformed file.', 0)
722 # if inset in allowed_insets:
723 # par.extend(self.body[k: end+1])
726 # par.append(self.body[k])
729 # # trim empty lines in the end.
730 # while par and par[-1].strip() == '':
733 # toc_par.append(Paragraph(section, par))
740 class File(LyX_base):
741 " This class reads existing LyX files."
743 def __init__(self, end_format = 0, input = "", output = "", error = "",
744 debug = default_debug__, try_hard = 0, cjk_encoding = '',
745 final_version = '', systemlyxdir = ''):
746 LyX_base.__init__(self, end_format, input, output, error,
747 debug, try_hard, cjk_encoding, final_version,
752 # FIXME: header settings are completely outdated, don't use like this
753 #class NewFile(LyX_base):
754 # " This class is to create new LyX files."
755 # def set_header(self, **params):
756 # # set default values
757 # self.header.extend([
758 # "#LyX xxxx created this file."
759 # "For more info see http://www.lyx.org/",
761 # "\\begin_document",
763 # "\\textclass article",
764 # "\\language english",
765 # "\\inputencoding auto",
766 # "\\font_roman default",
767 # "\\font_sans default",
768 # "\\font_typewriter default",
769 # "\\font_default_family default",
771 # "\\font_osf false",
772 # "\\font_sf_scale 100",
773 # "\\font_tt_scale 100",
774 # "\\graphics default",
775 # "\\paperfontsize default",
776 # "\\papersize default",
777 # "\\use_geometry false",
779 # "\\cite_engine basic",
780 # "\\use_bibtopic false",
781 # "\\use_indices false",
782 # "\\paperorientation portrait",
785 # "\\paragraph_separation indent",
786 # "\\defskip medskip",
787 # "\\quotes_language english",
788 # "\\papercolumns 1",
790 # "\\paperpagestyle default",
791 # "\\tracking_changes false",
794 # self.format = get_end_format()
795 # for param in params:
796 # self.set_parameter(param, params[param])
799 # def set_body(self, paragraphs):
800 # self.body.extend(['\\begin_body',''])
802 # for par in paragraphs:
803 # self.body.extend(par.asLines())
805 # self.body.extend(['','\\end_body', '\\end_document'])
808 # Part of an unfinished attempt to make lyx2lyx gave a more
809 # structured view of the document.
811 # # unfinished implementation, it is missing the Text and Insets
813 # " This class represents the LyX paragraphs."
814 # def __init__(self, name, body=[], settings = [], child = []):
816 # name: paragraph name.
817 # body: list of lines of body text.
818 # child: list of paragraphs that descend from this paragraph.
822 # self.settings = settings
826 # """ Converts the paragraph to a list of strings, representing
827 # it in the LyX file."""
829 # result = ['','\\begin_layout %s' % self.name]
830 # result.extend(self.settings)
832 # result.extend(self.body)
833 # result.append('\\end_layout')
838 # result.append('\\begin_deeper')
839 # for node in self.child:
840 # result.extend(node.asLines())
841 # result.append('\\end_deeper')