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 ("1_4", list(range(222,246)), minor_versions("1.4" , 5)),
84 ("1_5", list(range(246,277)), minor_versions("1.5" , 7)),
85 ("1_6", list(range(277,346)), minor_versions("1.6" , 10)),
86 ("2_0", list(range(346,414)), minor_versions("2.0" , 8)),
87 ("2_1", list(range(414,475)), minor_versions("2.1" , 0)),
88 ("2_2", list(range(475,503)), minor_versions("2.2" , 0))
91 ####################################################################
92 # This is useful just for development versions #
93 # if the list of supported formats is empty get it from last step #
94 if not format_relation[-1][1]:
95 step, mode = format_relation[-1][0], "convert"
96 convert = getattr(__import__("lyx_" + step), mode)
97 format_relation[-1] = (step,
98 [conv[0] for conv in convert],
99 format_relation[-1][2])
101 ####################################################################
104 " Returns a list with supported file formats."
106 for version in format_relation:
107 for format in version[1]:
108 if format not in formats:
109 formats.append(format)
114 " Returns a list with supported file formats."
115 out = """Major version:
119 for version in format_relation:
120 major = str(version[2][0])
121 versions = str(version[2][1:])
122 if len(version[1]) == 1:
123 formats = str(version[1][0])
125 formats = "%s - %s" % (version[1][-1], version[1][0])
126 out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats)
130 def get_end_format():
131 " Returns the more recent file format available."
132 # this check will fail only when we have a new version
133 # and there is no format change yet.
134 if format_relation[-1][1]:
135 return format_relation[-1][1][-1]
136 return format_relation[-2][1][-1]
139 def get_backend(textclass):
140 " For _textclass_ returns its backend."
141 if textclass == "linuxdoc" or textclass == "manpage":
143 if textclass.startswith("docbook") or textclass.startswith("agu-"):
149 " Remove end of line char(s)."
150 if line[-1] != '\n' and line[-1] != '\r':
151 # May happen for the last line of a document
153 if line[-2:-1] == '\r':
159 def get_encoding(language, inputencoding, format, cjk_encoding):
160 " Returns enconding of the lyx file"
163 # CJK-LyX encodes files using the current locale encoding.
164 # This means that files created by CJK-LyX can only be converted using
165 # the correct locale settings unless the encoding is given as commandline
167 if cjk_encoding == 'auto':
168 return locale.getpreferredencoding()
171 from lyx2lyx_lang import lang
172 if inputencoding == "auto" or inputencoding == "default":
173 return lang[language][3]
174 if inputencoding == "":
176 if inputencoding == "utf8x":
178 # python does not know the alias latin9
179 if inputencoding == "latin9":
187 """This class carries all the information of the LyX file."""
189 def __init__(self, end_format = 0, input = "", output = "", error = "",
190 debug = default_debug__, try_hard = 0, cjk_encoding = '',
191 final_version = "", systemlyxdir = '', language = "english",
195 end_format: final format that the file should be converted. (integer)
196 input: the name of the input source, if empty resort to standard input.
197 output: the name of the output file, if empty use the standard output.
198 error: the name of the error file, if empty use the standard error.
199 debug: debug level, O means no debug, as its value increases be more verbose.
201 self.choose_io(input, output)
204 self.err = open(error, "w")
206 self.err = sys.stderr
209 self.try_hard = try_hard
210 self.cjk_encoding = cjk_encoding
213 self.end_format = self.lyxformat(end_format)
215 # In case the target version and format are both specified
216 # verify that they are compatible. If not send a warning
217 # and ignore the version.
219 message = "Incompatible version %s for specified format %d" % (
220 final_version, self.end_format)
221 for version in format_relation:
222 if self.end_format in version[1]:
223 if final_version not in version[2]:
224 self.warning(message)
227 for version in format_relation:
228 if final_version in version[2]:
229 # set the last format for that version
230 self.end_format = version[1][-1]
235 self.end_format = get_end_format()
237 if not final_version:
238 for step in format_relation:
239 if self.end_format in step[1]:
240 final_version = step[2][1]
241 self.final_version = final_version
242 self.warning("Final version: %s" % self.final_version, 10)
243 self.warning("Final format: %d" % self.end_format, 10)
245 self.backend = "latex"
246 self.textclass = "article"
247 # This is a hack: We use '' since we don't know the default
248 # layout of the text class. LyX will parse it as default layout.
249 # FIXME: Read the layout file and use the real default layout
250 self.default_layout = ''
255 self.encoding = encoding
256 self.language = language
257 self.systemlyxdir = systemlyxdir
260 def warning(self, message, debug_level= default_debug__):
261 """ Emits warning to self.error, if the debug_level is less
262 than the self.debug."""
263 if debug_level <= self.debug:
264 self.err.write("Warning: " + message + "\n")
267 def error(self, message):
268 " Emits a warning and exits if not in try_hard mode."
269 self.warning(message)
270 if not self.try_hard:
271 self.warning("Quitting.")
278 """Reads a file into the self.header and
279 self.body parts, from self.input."""
282 line = self.input.readline()
284 self.error("Invalid LyX file.")
286 line = trim_eol(line)
287 if check_token(line, '\\begin_preamble'):
289 line = self.input.readline()
291 self.error("Invalid LyX file.")
293 line = trim_eol(line)
294 if check_token(line, '\\end_preamble'):
297 if line.split()[:0] in ("\\layout",
298 "\\begin_layout", "\\begin_body"):
300 self.warning("Malformed LyX file:"
301 "Missing '\\end_preamble'."
302 "\nAdding it now and hoping"
305 self.preamble.append(line)
307 if check_token(line, '\\end_preamble'):
314 if line.split()[0] in ("\\layout", "\\begin_layout",
315 "\\begin_body", "\\begin_deeper"):
316 self.body.append(line)
319 self.header.append(line)
321 i = find_token(self.header, '\\textclass', 0)
323 self.warning("Malformed LyX file: Missing '\\textclass'.")
324 i = find_token(self.header, '\\lyxformat', 0) + 1
325 self.header[i:i] = ['\\textclass article']
327 self.textclass = get_value(self.header, "\\textclass", 0)
328 self.backend = get_backend(self.textclass)
329 self.format = self.read_format()
330 self.language = get_value(self.header, "\\language", 0,
332 self.inputencoding = get_value(self.header, "\\inputencoding",
334 self.encoding = get_encoding(self.language,
335 self.inputencoding, self.format,
337 self.initial_version = self.read_version()
339 # Second pass over header and preamble, now we know the file encoding
340 # Do not forget the textclass (Debian bug #700828)
341 self.textclass = self.textclass.decode(self.encoding)
342 for i in range(len(self.header)):
343 self.header[i] = self.header[i].decode(self.encoding)
344 for i in range(len(self.preamble)):
345 self.preamble[i] = self.preamble[i].decode(self.encoding)
349 line = self.input.readline().decode(self.encoding)
352 self.body.append(trim_eol(line))
356 " Writes the LyX file to self.output."
360 if self.encoding == "auto":
361 self.encoding = get_encoding(self.language, self.encoding,
362 self.format, self.cjk_encoding)
364 i = find_token(self.header, '\\textclass', 0) + 1
365 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
366 header = self.header[:i] + preamble + self.header[i:]
370 for line in header + [''] + self.body:
371 self.output.write(line.encode(self.encoding)+"\n")
374 def choose_io(self, input, output):
375 """Choose input and output streams, dealing transparently with
379 self.output = open(output, "wb")
381 self.output = sys.stdout
383 if input and input != '-':
384 self.dir = os.path.dirname(os.path.abspath(input))
386 gzip.open(input).readline()
387 self.input = gzip.open(input)
388 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
390 self.input = open(input)
393 self.input = sys.stdin
396 def lyxformat(self, format):
397 " Returns the file format representation, an integer."
398 result = format_re.match(format)
400 format = int(result.group(1) + result.group(2))
404 self.error(str(format) + ": " + "Invalid LyX file.")
406 if format in formats_list():
409 self.error(str(format) + ": " + "Format not supported.")
413 def read_version(self):
414 """ Searchs for clues of the LyX version used to write the
415 file, returns the most likely value, or None otherwise."""
417 for line in self.header:
421 line = line.replace("fix",".")
422 # need to test original_tex2lyx_version first because tex2lyx
423 # writes "#LyX file created by tex2lyx 2.2"
424 result = original_tex2lyx_version.match(line)
426 result = original_version.match(line)
428 # Special know cases: reLyX and KLyX
429 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
432 res = result.group(1)
435 #self.warning("Version %s" % result.group(1))
437 self.warning(str(self.header[:2]))
441 def set_version(self):
442 " Set the header with the version used."
444 initial_comment = " ".join(["#LyX %s created this file." % version__,
445 "For more info see http://www.lyx.org/"])
447 # Simple heuristic to determine the comment that always starts
449 if self.header[0].startswith("#"):
450 self.header[0] = initial_comment
452 self.header.insert(0, initial_comment)
454 # Old lyx files had a two lines comment header:
455 # 1) the first line had the user who had created it
456 # 2) the second line had the lyx version used
457 # later we decided that 1) was a privacy risk for no gain
458 # here we remove the second line effectively erasing 1)
459 if self.header[1][0] == '#':
463 def read_format(self):
464 " Read from the header the fileformat of the present LyX file."
465 for line in self.header:
466 result = fileformat.match(line)
468 return self.lyxformat(result.group(1))
470 self.error("Invalid LyX File.")
474 def set_format(self):
475 " Set the file format of the file, in the header."
476 if self.format <= 217:
477 format = str(float(self.format)/100)
479 format = str(self.format)
480 i = find_token(self.header, "\\lyxformat", 0)
481 self.header[i] = "\\lyxformat %s" % format
484 def set_textclass(self):
485 i = find_token(self.header, "\\textclass", 0)
486 self.header[i] = "\\textclass %s" % self.textclass
489 #Note that the module will be added at the END of the extant ones
490 def add_module(self, module):
491 i = find_token(self.header, "\\begin_modules", 0)
493 #No modules yet included
494 i = find_token(self.header, "\\textclass", 0)
496 self.warning("Malformed LyX document: No \\textclass!!")
498 modinfo = ["\\begin_modules", module, "\\end_modules"]
499 self.header[i + 1: i + 1] = modinfo
501 j = find_token(self.header, "\\end_modules", i)
503 self.warning("(add_module)Malformed LyX document: No \\end_modules.")
505 k = find_token(self.header, module, i)
506 if k != -1 and k < j:
508 self.header.insert(j, module)
511 def get_module_list(self):
512 i = find_token(self.header, "\\begin_modules", 0)
515 j = find_token(self.header, "\\end_modules", i)
516 return self.header[i + 1 : j]
519 def set_module_list(self, mlist):
520 modbegin = find_token(self.header, "\\begin_modules", 0)
521 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
523 #No modules yet included
524 tclass = find_token(self.header, "\\textclass", 0)
526 self.warning("Malformed LyX document: No \\textclass!!")
528 modbegin = tclass + 1
529 self.header[modbegin:modbegin] = newmodlist
531 modend = find_token(self.header, "\\end_modules", modbegin)
533 self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
535 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
536 self.header[modbegin:modend + 1] = newmodlist
539 def set_parameter(self, param, value):
540 " Set the value of the header parameter."
541 i = find_token(self.header, '\\' + param, 0)
543 self.warning('Parameter not found in the header: %s' % param, 3)
545 self.header[i] = '\\%s %s' % (param, str(value))
548 def is_default_layout(self, layout):
549 " Check whether a layout is the default layout of this class."
550 # FIXME: Check against the real text class default layout
551 if layout == 'Standard' or layout == self.default_layout:
557 "Convert from current (self.format) to self.end_format."
558 if self.format == self.end_format:
559 self.warning("No conversion needed: Target format %s "
560 "same as current format!" % self.format, default_debug__)
563 mode, conversion_chain = self.chain()
564 self.warning("conversion chain: " + str(conversion_chain), 3)
566 for step in conversion_chain:
567 steps = getattr(__import__("lyx_" + step), mode)
569 self.warning("Convertion step: %s - %s" % (step, mode),
572 self.error("The conversion to an older "
573 "format (%s) is not implemented." % self.format)
575 multi_conv = len(steps) != 1
576 for version, table in steps:
578 (self.format >= version and mode == "convert") or\
579 (self.format <= version and mode == "revert"):
587 self.warning("An error ocurred in %s, %s" %
588 (version, str(conv)),
590 if not self.try_hard:
594 self.warning("%lf: Elapsed time on %s" %
595 (time.time() - init_t,
596 str(conv)), default_debug__ +
598 self.format = version
599 if self.end_format == self.format:
604 """ This is where all the decisions related with the
605 conversion are taken. It returns a list of modules needed to
606 convert the LyX file from self.format to self.end_format"""
608 self.start = self.format
612 for rel in format_relation:
613 if self.initial_version in rel[2]:
615 initial_step = rel[0]
619 if not correct_version:
621 self.warning("Version does not match file format, "
622 "discarding it. (Version %s, format %d)" %
623 (self.initial_version, self.format))
624 for rel in format_relation:
626 initial_step = rel[0]
629 # This should not happen, really.
630 self.error("Format not supported.")
632 # Find the final step
633 for rel in format_relation:
634 if self.end_format in rel[1]:
638 self.error("Format not supported.")
640 # Convertion mode, back or forth
642 if (initial_step, self.start) < (final_step, self.end_format):
645 for step in format_relation:
646 if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
647 full_steps.append(step)
648 if full_steps[0][1][-1] == self.format:
649 full_steps = full_steps[1:]
650 for step in full_steps:
651 steps.append(step[0])
654 relation_format = format_relation[:]
655 relation_format.reverse()
658 for step in relation_format:
659 if final_step <= step[0] <= initial_step:
660 steps.append(step[0])
663 if last_step[1][-1] == self.end_format:
666 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
670 # Part of an unfinished attempt to make lyx2lyx gave a more
671 # structured view of the document.
672 # def get_toc(self, depth = 4):
673 # " Returns the TOC of this LyX document."
674 # paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
675 # 'Subsection' : 3, 'Subsubsection': 4}
676 # allowed_insets = ['Quotes']
677 # allowed_parameters = ('\\paragraph_spacing', '\\noindent',
678 # '\\align', '\\labelwidthstring',
679 # "\\start_of_appendix", "\\leftindent")
681 # for section in paragraphs_filter.keys():
682 # sections.append('\\begin_layout %s' % section)
687 # i = find_tokens(self.body, sections, i)
691 # j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
693 # self.warning('Incomplete file.', 0)
696 # section = self.body[i].split()[1]
697 # if section[-1] == '*':
698 # section = section[:-1]
703 # # skip paragraph parameters
704 # while not self.body[k].strip() or self.body[k].split()[0] \
705 # in allowed_parameters:
709 # if check_token(self.body[k], '\\begin_inset'):
710 # inset = self.body[k].split()[1]
711 # end = find_end_of_inset(self.body, k)
712 # if end == -1 or end > j:
713 # self.warning('Malformed file.', 0)
715 # if inset in allowed_insets:
716 # par.extend(self.body[k: end+1])
719 # par.append(self.body[k])
722 # # trim empty lines in the end.
723 # while par and par[-1].strip() == '':
726 # toc_par.append(Paragraph(section, par))
733 class File(LyX_base):
734 " This class reads existing LyX files."
736 def __init__(self, end_format = 0, input = "", output = "", error = "",
737 debug = default_debug__, try_hard = 0, cjk_encoding = '',
738 final_version = '', systemlyxdir = ''):
739 LyX_base.__init__(self, end_format, input, output, error,
740 debug, try_hard, cjk_encoding, final_version,
745 # FIXME: header settings are completely outdated, don't use like this
746 #class NewFile(LyX_base):
747 # " This class is to create new LyX files."
748 # def set_header(self, **params):
749 # # set default values
750 # self.header.extend([
751 # "#LyX xxxx created this file."
752 # "For more info see http://www.lyx.org/",
754 # "\\begin_document",
756 # "\\textclass article",
757 # "\\language english",
758 # "\\inputencoding auto",
759 # "\\font_roman default",
760 # "\\font_sans default",
761 # "\\font_typewriter default",
762 # "\\font_default_family default",
764 # "\\font_osf false",
765 # "\\font_sf_scale 100",
766 # "\\font_tt_scale 100",
767 # "\\graphics default",
768 # "\\paperfontsize default",
769 # "\\papersize default",
770 # "\\use_geometry false",
772 # "\\cite_engine basic",
773 # "\\use_bibtopic false",
774 # "\\use_indices false",
775 # "\\paperorientation portrait",
778 # "\\paragraph_separation indent",
779 # "\\defskip medskip",
780 # "\\quotes_language english",
781 # "\\papercolumns 1",
783 # "\\paperpagestyle default",
784 # "\\tracking_changes false",
787 # self.format = get_end_format()
788 # for param in params:
789 # self.set_parameter(param, params[param])
792 # def set_body(self, paragraphs):
793 # self.body.extend(['\\begin_body',''])
795 # for par in paragraphs:
796 # self.body.extend(par.asLines())
798 # self.body.extend(['','\\end_body', '\\end_document'])
801 # Part of an unfinished attempt to make lyx2lyx gave a more
802 # structured view of the document.
804 # # unfinished implementation, it is missing the Text and Insets
806 # " This class represents the LyX paragraphs."
807 # def __init__(self, name, body=[], settings = [], child = []):
809 # name: paragraph name.
810 # body: list of lines of body text.
811 # child: list of paragraphs that descend from this paragraph.
815 # self.settings = settings
819 # """ Converts the paragraph to a list of strings, representing
820 # it in the LyX file."""
822 # result = ['','\\begin_layout %s' % self.name]
823 # result.extend(self.settings)
825 # result.extend(self.body)
826 # result.append('\\end_layout')
831 # result.append('\\begin_deeper')
832 # for node in self.child:
833 # result.extend(node.asLines())
834 # result.append('\\end_deeper')