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,501)), 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 = "", language = "english", encoding = "auto"):
194 end_format: final format that the file should be converted. (integer)
195 input: the name of the input source, if empty resort to standard input.
196 output: the name of the output file, if empty use the standard output.
197 error: the name of the error file, if empty use the standard error.
198 debug: debug level, O means no debug, as its value increases be more verbose.
200 self.choose_io(input, output)
203 self.err = open(error, "w")
205 self.err = sys.stderr
208 self.try_hard = try_hard
209 self.cjk_encoding = cjk_encoding
212 self.end_format = self.lyxformat(end_format)
214 # In case the target version and format are both specified
215 # verify that they are compatible. If not send a warning
216 # and ignore the version.
218 message = "Incompatible version %s for specified format %d" % (
219 final_version, self.end_format)
220 for version in format_relation:
221 if self.end_format in version[1]:
222 if final_version not in version[2]:
223 self.warning(message)
226 for version in format_relation:
227 if final_version in version[2]:
228 # set the last format for that version
229 self.end_format = version[1][-1]
234 self.end_format = get_end_format()
236 if not final_version:
237 for step in format_relation:
238 if self.end_format in step[1]:
239 final_version = step[2][1]
240 self.final_version = final_version
241 self.warning("Final version: %s" % self.final_version, 10)
242 self.warning("Final format: %d" % self.end_format, 10)
244 self.backend = "latex"
245 self.textclass = "article"
246 # This is a hack: We use '' since we don't know the default
247 # layout of the text class. LyX will parse it as default layout.
248 # FIXME: Read the layout file and use the real default layout
249 self.default_layout = ''
254 self.encoding = encoding
255 self.language = language
258 def warning(self, message, debug_level= default_debug__):
259 """ Emits warning to self.error, if the debug_level is less
260 than the self.debug."""
261 if debug_level <= self.debug:
262 self.err.write("Warning: " + message + "\n")
265 def error(self, message):
266 " Emits a warning and exits if not in try_hard mode."
267 self.warning(message)
268 if not self.try_hard:
269 self.warning("Quitting.")
276 """Reads a file into the self.header and
277 self.body parts, from self.input."""
280 line = self.input.readline()
282 self.error("Invalid LyX file.")
284 line = trim_eol(line)
285 if check_token(line, '\\begin_preamble'):
287 line = self.input.readline()
289 self.error("Invalid LyX file.")
291 line = trim_eol(line)
292 if check_token(line, '\\end_preamble'):
295 if line.split()[:0] in ("\\layout",
296 "\\begin_layout", "\\begin_body"):
298 self.warning("Malformed LyX file:"
299 "Missing '\\end_preamble'."
300 "\nAdding it now and hoping"
303 self.preamble.append(line)
305 if check_token(line, '\\end_preamble'):
312 if line.split()[0] in ("\\layout", "\\begin_layout",
313 "\\begin_body", "\\begin_deeper"):
314 self.body.append(line)
317 self.header.append(line)
319 i = find_token(self.header, '\\textclass', 0)
321 self.warning("Malformed LyX file: Missing '\\textclass'.")
322 i = find_token(self.header, '\\lyxformat', 0) + 1
323 self.header[i:i] = ['\\textclass article']
325 self.textclass = get_value(self.header, "\\textclass", 0)
326 self.backend = get_backend(self.textclass)
327 self.format = self.read_format()
328 self.language = get_value(self.header, "\\language", 0,
330 self.inputencoding = get_value(self.header, "\\inputencoding",
332 self.encoding = get_encoding(self.language,
333 self.inputencoding, self.format,
335 self.initial_version = self.read_version()
337 # Second pass over header and preamble, now we know the file encoding
338 # Do not forget the textclass (Debian bug #700828)
339 self.textclass = self.textclass.decode(self.encoding)
340 for i in range(len(self.header)):
341 self.header[i] = self.header[i].decode(self.encoding)
342 for i in range(len(self.preamble)):
343 self.preamble[i] = self.preamble[i].decode(self.encoding)
347 line = self.input.readline().decode(self.encoding)
350 self.body.append(trim_eol(line))
354 " Writes the LyX file to self.output."
358 if self.encoding == "auto":
359 self.encoding = get_encoding(self.language, self.encoding,
360 self.format, self.cjk_encoding)
362 i = find_token(self.header, '\\textclass', 0) + 1
363 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
364 header = self.header[:i] + preamble + self.header[i:]
368 for line in header + [''] + self.body:
369 self.output.write(line.encode(self.encoding)+"\n")
372 def choose_io(self, input, output):
373 """Choose input and output streams, dealing transparently with
377 self.output = open(output, "wb")
379 self.output = sys.stdout
381 if input and input != '-':
382 self.dir = os.path.dirname(os.path.abspath(input))
384 gzip.open(input).readline()
385 self.input = gzip.open(input)
386 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
388 self.input = open(input)
391 self.input = sys.stdin
394 def lyxformat(self, format):
395 " Returns the file format representation, an integer."
396 result = format_re.match(format)
398 format = int(result.group(1) + result.group(2))
402 self.error(str(format) + ": " + "Invalid LyX file.")
404 if format in formats_list():
407 self.error(str(format) + ": " + "Format not supported.")
411 def read_version(self):
412 """ Searchs for clues of the LyX version used to write the
413 file, returns the most likely value, or None otherwise."""
415 for line in self.header:
419 line = line.replace("fix",".")
420 # need to test original_tex2lyx_version first because tex2lyx
421 # writes "#LyX file created by tex2lyx 2.2"
422 result = original_tex2lyx_version.match(line)
424 result = original_version.match(line)
426 # Special know cases: reLyX and KLyX
427 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
430 res = result.group(1)
433 #self.warning("Version %s" % result.group(1))
435 self.warning(str(self.header[:2]))
439 def set_version(self):
440 " Set the header with the version used."
442 initial_comment = " ".join(["#LyX %s created this file." % version__,
443 "For more info see http://www.lyx.org/"])
445 # Simple heuristic to determine the comment that always starts
447 if self.header[0].startswith("#"):
448 self.header[0] = initial_comment
450 self.header.insert(0, initial_comment)
452 # Old lyx files had a two lines comment header:
453 # 1) the first line had the user who had created it
454 # 2) the second line had the lyx version used
455 # later we decided that 1) was a privacy risk for no gain
456 # here we remove the second line effectively erasing 1)
457 if self.header[1][0] == '#':
461 def read_format(self):
462 " Read from the header the fileformat of the present LyX file."
463 for line in self.header:
464 result = fileformat.match(line)
466 return self.lyxformat(result.group(1))
468 self.error("Invalid LyX File.")
472 def set_format(self):
473 " Set the file format of the file, in the header."
474 if self.format <= 217:
475 format = str(float(self.format)/100)
477 format = str(self.format)
478 i = find_token(self.header, "\\lyxformat", 0)
479 self.header[i] = "\\lyxformat %s" % format
482 def set_textclass(self):
483 i = find_token(self.header, "\\textclass", 0)
484 self.header[i] = "\\textclass %s" % self.textclass
487 #Note that the module will be added at the END of the extant ones
488 def add_module(self, module):
489 i = find_token(self.header, "\\begin_modules", 0)
491 #No modules yet included
492 i = find_token(self.header, "\\textclass", 0)
494 self.warning("Malformed LyX document: No \\textclass!!")
496 modinfo = ["\\begin_modules", module, "\\end_modules"]
497 self.header[i + 1: i + 1] = modinfo
499 j = find_token(self.header, "\\end_modules", i)
501 self.warning("(add_module)Malformed LyX document: No \\end_modules.")
503 k = find_token(self.header, module, i)
504 if k != -1 and k < j:
506 self.header.insert(j, module)
509 def get_module_list(self):
510 i = find_token(self.header, "\\begin_modules", 0)
513 j = find_token(self.header, "\\end_modules", i)
514 return self.header[i + 1 : j]
517 def set_module_list(self, mlist):
518 modbegin = find_token(self.header, "\\begin_modules", 0)
519 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
521 #No modules yet included
522 tclass = find_token(self.header, "\\textclass", 0)
524 self.warning("Malformed LyX document: No \\textclass!!")
526 modbegin = tclass + 1
527 self.header[modbegin:modbegin] = newmodlist
529 modend = find_token(self.header, "\\end_modules", modbegin)
531 self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
533 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
534 self.header[modbegin:modend + 1] = newmodlist
537 def set_parameter(self, param, value):
538 " Set the value of the header parameter."
539 i = find_token(self.header, '\\' + param, 0)
541 self.warning('Parameter not found in the header: %s' % param, 3)
543 self.header[i] = '\\%s %s' % (param, str(value))
546 def is_default_layout(self, layout):
547 " Check whether a layout is the default layout of this class."
548 # FIXME: Check against the real text class default layout
549 if layout == 'Standard' or layout == self.default_layout:
555 "Convert from current (self.format) to self.end_format."
556 if self.format == self.end_format:
557 self.warning("No conversion needed: Target format %s "
558 "same as current format!" % self.format, default_debug__)
561 mode, conversion_chain = self.chain()
562 self.warning("conversion chain: " + str(conversion_chain), 3)
564 for step in conversion_chain:
565 steps = getattr(__import__("lyx_" + step), mode)
567 self.warning("Convertion step: %s - %s" % (step, mode),
570 self.error("The conversion to an older "
571 "format (%s) is not implemented." % self.format)
573 multi_conv = len(steps) != 1
574 for version, table in steps:
576 (self.format >= version and mode == "convert") or\
577 (self.format <= version and mode == "revert"):
585 self.warning("An error ocurred in %s, %s" %
586 (version, str(conv)),
588 if not self.try_hard:
592 self.warning("%lf: Elapsed time on %s" %
593 (time.time() - init_t,
594 str(conv)), default_debug__ +
596 self.format = version
597 if self.end_format == self.format:
602 """ This is where all the decisions related with the
603 conversion are taken. It returns a list of modules needed to
604 convert the LyX file from self.format to self.end_format"""
606 self.start = self.format
610 for rel in format_relation:
611 if self.initial_version in rel[2]:
613 initial_step = rel[0]
617 if not correct_version:
619 self.warning("Version does not match file format, "
620 "discarding it. (Version %s, format %d)" %
621 (self.initial_version, self.format))
622 for rel in format_relation:
624 initial_step = rel[0]
627 # This should not happen, really.
628 self.error("Format not supported.")
630 # Find the final step
631 for rel in format_relation:
632 if self.end_format in rel[1]:
636 self.error("Format not supported.")
638 # Convertion mode, back or forth
640 if (initial_step, self.start) < (final_step, self.end_format):
643 for step in format_relation:
644 if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
645 full_steps.append(step)
646 if full_steps[0][1][-1] == self.format:
647 full_steps = full_steps[1:]
648 for step in full_steps:
649 steps.append(step[0])
652 relation_format = format_relation[:]
653 relation_format.reverse()
656 for step in relation_format:
657 if final_step <= step[0] <= initial_step:
658 steps.append(step[0])
661 if last_step[1][-1] == self.end_format:
664 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
668 # Part of an unfinished attempt to make lyx2lyx gave a more
669 # structured view of the document.
670 # def get_toc(self, depth = 4):
671 # " Returns the TOC of this LyX document."
672 # paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
673 # 'Subsection' : 3, 'Subsubsection': 4}
674 # allowed_insets = ['Quotes']
675 # allowed_parameters = ('\\paragraph_spacing', '\\noindent',
676 # '\\align', '\\labelwidthstring',
677 # "\\start_of_appendix", "\\leftindent")
679 # for section in paragraphs_filter.keys():
680 # sections.append('\\begin_layout %s' % section)
685 # i = find_tokens(self.body, sections, i)
689 # j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
691 # self.warning('Incomplete file.', 0)
694 # section = self.body[i].split()[1]
695 # if section[-1] == '*':
696 # section = section[:-1]
701 # # skip paragraph parameters
702 # while not self.body[k].strip() or self.body[k].split()[0] \
703 # in allowed_parameters:
707 # if check_token(self.body[k], '\\begin_inset'):
708 # inset = self.body[k].split()[1]
709 # end = find_end_of_inset(self.body, k)
710 # if end == -1 or end > j:
711 # self.warning('Malformed file.', 0)
713 # if inset in allowed_insets:
714 # par.extend(self.body[k: end+1])
717 # par.append(self.body[k])
720 # # trim empty lines in the end.
721 # while par and par[-1].strip() == '':
724 # toc_par.append(Paragraph(section, par))
731 class File(LyX_base):
732 " This class reads existing LyX files."
734 def __init__(self, end_format = 0, input = "", output = "", error = "",
735 debug = default_debug__, try_hard = 0, cjk_encoding = '',
737 LyX_base.__init__(self, end_format, input, output, error,
738 debug, try_hard, cjk_encoding, final_version)
742 # FIXME: header settings are completely outdated, don't use like this
743 #class NewFile(LyX_base):
744 # " This class is to create new LyX files."
745 # def set_header(self, **params):
746 # # set default values
747 # self.header.extend([
748 # "#LyX xxxx created this file."
749 # "For more info see http://www.lyx.org/",
751 # "\\begin_document",
753 # "\\textclass article",
754 # "\\language english",
755 # "\\inputencoding auto",
756 # "\\font_roman default",
757 # "\\font_sans default",
758 # "\\font_typewriter default",
759 # "\\font_default_family default",
761 # "\\font_osf false",
762 # "\\font_sf_scale 100",
763 # "\\font_tt_scale 100",
764 # "\\graphics default",
765 # "\\paperfontsize default",
766 # "\\papersize default",
767 # "\\use_geometry false",
769 # "\\cite_engine basic",
770 # "\\use_bibtopic false",
771 # "\\use_indices false",
772 # "\\paperorientation portrait",
775 # "\\paragraph_separation indent",
776 # "\\defskip medskip",
777 # "\\quotes_language english",
778 # "\\papercolumns 1",
780 # "\\paperpagestyle default",
781 # "\\tracking_changes false",
784 # self.format = get_end_format()
785 # for param in params:
786 # self.set_parameter(param, params[param])
789 # def set_body(self, paragraphs):
790 # self.body.extend(['\\begin_body',''])
792 # for par in paragraphs:
793 # self.body.extend(par.asLines())
795 # self.body.extend(['','\\end_body', '\\end_document'])
798 # Part of an unfinished attempt to make lyx2lyx gave a more
799 # structured view of the document.
801 # # unfinished implementation, it is missing the Text and Insets
803 # " This class represents the LyX paragraphs."
804 # def __init__(self, name, body=[], settings = [], child = []):
806 # name: paragraph name.
807 # body: list of lines of body text.
808 # child: list of paragraphs that descend from this paragraph.
812 # self.settings = settings
816 # """ Converts the paragraph to a list of strings, representing
817 # it in the LyX file."""
819 # result = ['','\\begin_layout %s' % self.name]
820 # result.extend(self.settings)
822 # result.extend(self.body)
823 # result.append('\\end_layout')
828 # result.append('\\begin_deeper')
829 # for node in self.child:
830 # result.extend(node.asLines())
831 # result.append('\\end_deeper')