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" , 0)),
89 ("2_2", list(range(475,508)), minor_versions("2.2" , 0))
92 ####################################################################
93 # This is useful just for development versions #
94 # if the list of supported formats is empty get it from last step #
95 if not format_relation[-1][1]:
96 step, mode = format_relation[-1][0], "convert"
97 convert = getattr(__import__("lyx_" + step), mode)
98 format_relation[-1] = (step,
99 [conv[0] for conv in convert],
100 format_relation[-1][2])
102 ####################################################################
105 " Returns a list with supported file formats."
107 for version in format_relation:
108 for format in version[1]:
109 if format not in formats:
110 formats.append(format)
115 " Returns a list with supported file formats."
116 out = """Major version:
120 for version in format_relation:
121 major = str(version[2][0])
122 versions = str(version[2][1:])
123 if len(version[1]) == 1:
124 formats = str(version[1][0])
126 formats = "%s - %s" % (version[1][-1], version[1][0])
127 out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats)
131 def get_end_format():
132 " Returns the more recent file format available."
133 # this check will fail only when we have a new version
134 # and there is no format change yet.
135 if format_relation[-1][1]:
136 return format_relation[-1][1][-1]
137 return format_relation[-2][1][-1]
140 def get_backend(textclass):
141 " For _textclass_ returns its backend."
142 if textclass == "linuxdoc" or textclass == "manpage":
144 if textclass.startswith("docbook") or textclass.startswith("agu-"):
150 " Remove end of line char(s)."
151 if line[-1] != '\n' and line[-1] != '\r':
152 # May happen for the last line of a document
154 if line[-2:-1] == '\r':
160 def get_encoding(language, inputencoding, format, cjk_encoding):
161 " Returns enconding of the lyx file"
164 # CJK-LyX encodes files using the current locale encoding.
165 # This means that files created by CJK-LyX can only be converted using
166 # the correct locale settings unless the encoding is given as commandline
168 if cjk_encoding == 'auto':
169 return locale.getpreferredencoding()
172 from lyx2lyx_lang import lang
173 if inputencoding == "auto" or inputencoding == "default":
174 return lang[language][3]
175 if inputencoding == "":
177 if inputencoding == "utf8x":
179 # python does not know the alias latin9
180 if inputencoding == "latin9":
188 """This class carries all the information of the LyX file."""
190 def __init__(self, end_format = 0, input = "", output = "", error = "",
191 debug = default_debug__, try_hard = 0, cjk_encoding = '',
192 final_version = "", systemlyxdir = '', language = "english",
196 end_format: final format that the file should be converted. (integer)
197 input: the name of the input source, if empty resort to standard input.
198 output: the name of the output file, if empty use the standard output.
199 error: the name of the error file, if empty use the standard error.
200 debug: debug level, O means no debug, as its value increases be more verbose.
202 self.choose_io(input, output)
205 self.err = open(error, "w")
207 self.err = sys.stderr
210 self.try_hard = try_hard
211 self.cjk_encoding = cjk_encoding
214 self.end_format = self.lyxformat(end_format)
216 # In case the target version and format are both specified
217 # verify that they are compatible. If not send a warning
218 # and ignore the version.
220 message = "Incompatible version %s for specified format %d" % (
221 final_version, self.end_format)
222 for version in format_relation:
223 if self.end_format in version[1]:
224 if final_version not in version[2]:
225 self.warning(message)
228 for version in format_relation:
229 if final_version in version[2]:
230 # set the last format for that version
231 self.end_format = version[1][-1]
236 self.end_format = get_end_format()
238 if not final_version:
239 for step in format_relation:
240 if self.end_format in step[1]:
241 final_version = step[2][1]
242 self.final_version = final_version
243 self.warning("Final version: %s" % self.final_version, 10)
244 self.warning("Final format: %d" % self.end_format, 10)
246 self.backend = "latex"
247 self.textclass = "article"
248 # This is a hack: We use '' since we don't know the default
249 # layout of the text class. LyX will parse it as default layout.
250 # FIXME: Read the layout file and use the real default layout
251 self.default_layout = ''
256 self.encoding = encoding
257 self.language = language
258 self.systemlyxdir = systemlyxdir
261 def warning(self, message, debug_level= default_debug__):
262 """ Emits warning to self.error, if the debug_level is less
263 than the self.debug."""
264 if debug_level <= self.debug:
265 self.err.write("Warning: " + message + "\n")
268 def error(self, message):
269 " Emits a warning and exits if not in try_hard mode."
270 self.warning(message)
271 if not self.try_hard:
272 self.warning("Quitting.")
279 """Reads a file into the self.header and
280 self.body parts, from self.input."""
283 line = self.input.readline()
285 self.error("Invalid LyX file.")
287 line = trim_eol(line)
288 if check_token(line, '\\begin_preamble'):
290 line = self.input.readline()
292 self.error("Invalid LyX file.")
294 line = trim_eol(line)
295 if check_token(line, '\\end_preamble'):
298 if line.split()[:0] in ("\\layout",
299 "\\begin_layout", "\\begin_body"):
301 self.warning("Malformed LyX file:"
302 "Missing '\\end_preamble'."
303 "\nAdding it now and hoping"
306 self.preamble.append(line)
308 if check_token(line, '\\end_preamble'):
315 if line.split()[0] in ("\\layout", "\\begin_layout",
316 "\\begin_body", "\\begin_deeper"):
317 self.body.append(line)
320 self.header.append(line)
322 i = find_token(self.header, '\\textclass', 0)
324 self.warning("Malformed LyX file: Missing '\\textclass'.")
325 i = find_token(self.header, '\\lyxformat', 0) + 1
326 self.header[i:i] = ['\\textclass article']
328 self.textclass = get_value(self.header, "\\textclass", 0)
329 self.backend = get_backend(self.textclass)
330 self.format = self.read_format()
331 self.language = get_value(self.header, "\\language", 0,
333 self.inputencoding = get_value(self.header, "\\inputencoding",
335 self.encoding = get_encoding(self.language,
336 self.inputencoding, self.format,
338 self.initial_version = self.read_version()
340 # Second pass over header and preamble, now we know the file encoding
341 # Do not forget the textclass (Debian bug #700828)
342 self.textclass = self.textclass.decode(self.encoding)
343 for i in range(len(self.header)):
344 self.header[i] = self.header[i].decode(self.encoding)
345 for i in range(len(self.preamble)):
346 self.preamble[i] = self.preamble[i].decode(self.encoding)
350 line = self.input.readline().decode(self.encoding)
353 self.body.append(trim_eol(line))
357 " Writes the LyX file to self.output."
361 if self.encoding == "auto":
362 self.encoding = get_encoding(self.language, self.encoding,
363 self.format, self.cjk_encoding)
365 i = find_token(self.header, '\\textclass', 0) + 1
366 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
367 header = self.header[:i] + preamble + self.header[i:]
371 for line in header + [''] + self.body:
372 self.output.write(line.encode(self.encoding)+"\n")
375 def choose_io(self, input, output):
376 """Choose input and output streams, dealing transparently with
380 self.output = open(output, "wb")
382 self.output = sys.stdout
384 if input and input != '-':
385 self.dir = os.path.dirname(os.path.abspath(input))
387 gzip.open(input).readline()
388 self.input = gzip.open(input)
389 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
391 self.input = open(input)
394 self.input = sys.stdin
397 def lyxformat(self, format):
398 " Returns the file format representation, an integer."
399 result = format_re.match(format)
401 format = int(result.group(1) + result.group(2))
405 self.error(str(format) + ": " + "Invalid LyX file.")
407 if format in formats_list():
410 self.error(str(format) + ": " + "Format not supported.")
414 def read_version(self):
415 """ Searchs for clues of the LyX version used to write the
416 file, returns the most likely value, or None otherwise."""
418 for line in self.header:
422 line = line.replace("fix",".")
423 # need to test original_tex2lyx_version first because tex2lyx
424 # writes "#LyX file created by tex2lyx 2.2"
425 result = original_tex2lyx_version.match(line)
427 result = original_version.match(line)
429 # Special know cases: reLyX and KLyX
430 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
433 res = result.group(1)
436 #self.warning("Version %s" % result.group(1))
438 self.warning(str(self.header[:2]))
442 def set_version(self):
443 " Set the header with the version used."
445 initial_comment = " ".join(["#LyX %s created this file." % version__,
446 "For more info see http://www.lyx.org/"])
448 # Simple heuristic to determine the comment that always starts
450 if self.header[0].startswith("#"):
451 self.header[0] = initial_comment
453 self.header.insert(0, initial_comment)
455 # Old lyx files had a two lines comment header:
456 # 1) the first line had the user who had created it
457 # 2) the second line had the lyx version used
458 # later we decided that 1) was a privacy risk for no gain
459 # here we remove the second line effectively erasing 1)
460 if self.header[1][0] == '#':
464 def read_format(self):
465 " Read from the header the fileformat of the present LyX file."
466 for line in self.header:
467 result = fileformat.match(line)
469 return self.lyxformat(result.group(1))
471 self.error("Invalid LyX File.")
475 def set_format(self):
476 " Set the file format of the file, in the header."
477 if self.format <= 217:
478 format = str(float(self.format)/100)
480 format = str(self.format)
481 i = find_token(self.header, "\\lyxformat", 0)
482 self.header[i] = "\\lyxformat %s" % format
485 def set_textclass(self):
486 i = find_token(self.header, "\\textclass", 0)
487 self.header[i] = "\\textclass %s" % self.textclass
490 #Note that the module will be added at the END of the extant ones
491 def add_module(self, module):
492 i = find_token(self.header, "\\begin_modules", 0)
494 #No modules yet included
495 i = find_token(self.header, "\\textclass", 0)
497 self.warning("Malformed LyX document: No \\textclass!!")
499 modinfo = ["\\begin_modules", module, "\\end_modules"]
500 self.header[i + 1: i + 1] = modinfo
502 j = find_token(self.header, "\\end_modules", i)
504 self.warning("(add_module)Malformed LyX document: No \\end_modules.")
506 k = find_token(self.header, module, i)
507 if k != -1 and k < j:
509 self.header.insert(j, module)
512 def get_module_list(self):
513 i = find_token(self.header, "\\begin_modules", 0)
516 j = find_token(self.header, "\\end_modules", i)
517 return self.header[i + 1 : j]
520 def set_module_list(self, mlist):
521 modbegin = find_token(self.header, "\\begin_modules", 0)
522 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
524 #No modules yet included
525 tclass = find_token(self.header, "\\textclass", 0)
527 self.warning("Malformed LyX document: No \\textclass!!")
529 modbegin = tclass + 1
530 self.header[modbegin:modbegin] = newmodlist
532 modend = find_token(self.header, "\\end_modules", modbegin)
534 self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
536 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
537 self.header[modbegin:modend + 1] = newmodlist
540 def set_parameter(self, param, value):
541 " Set the value of the header parameter."
542 i = find_token(self.header, '\\' + param, 0)
544 self.warning('Parameter not found in the header: %s' % param, 3)
546 self.header[i] = '\\%s %s' % (param, str(value))
549 def is_default_layout(self, layout):
550 " Check whether a layout is the default layout of this class."
551 # FIXME: Check against the real text class default layout
552 if layout == 'Standard' or layout == self.default_layout:
558 "Convert from current (self.format) to self.end_format."
559 if self.format == self.end_format:
560 self.warning("No conversion needed: Target format %s "
561 "same as current format!" % self.format, default_debug__)
564 mode, conversion_chain = self.chain()
565 self.warning("conversion chain: " + str(conversion_chain), 3)
567 for step in conversion_chain:
568 steps = getattr(__import__("lyx_" + step), mode)
570 self.warning("Convertion step: %s - %s" % (step, mode),
573 self.error("The conversion to an older "
574 "format (%s) is not implemented." % self.format)
576 multi_conv = len(steps) != 1
577 for version, table in steps:
579 (self.format >= version and mode == "convert") or\
580 (self.format <= version and mode == "revert"):
588 self.warning("An error ocurred in %s, %s" %
589 (version, str(conv)),
591 if not self.try_hard:
595 self.warning("%lf: Elapsed time on %s" %
596 (time.time() - init_t,
597 str(conv)), default_debug__ +
599 self.format = version
600 if self.end_format == self.format:
605 """ This is where all the decisions related with the
606 conversion are taken. It returns a list of modules needed to
607 convert the LyX file from self.format to self.end_format"""
609 self.start = self.format
613 for rel in format_relation:
614 if self.initial_version in rel[2]:
616 initial_step = rel[0]
620 if not correct_version:
622 self.warning("Version does not match file format, "
623 "discarding it. (Version %s, format %d)" %
624 (self.initial_version, self.format))
625 for rel in format_relation:
627 initial_step = rel[0]
630 # This should not happen, really.
631 self.error("Format not supported.")
633 # Find the final step
634 for rel in format_relation:
635 if self.end_format in rel[1]:
639 self.error("Format not supported.")
641 # Convertion mode, back or forth
643 if (initial_step, self.start) < (final_step, self.end_format):
646 for step in format_relation:
647 if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
648 full_steps.append(step)
649 if full_steps[0][1][-1] == self.format:
650 full_steps = full_steps[1:]
651 for step in full_steps:
652 steps.append(step[0])
655 relation_format = format_relation[:]
656 relation_format.reverse()
659 for step in relation_format:
660 if final_step <= step[0] <= initial_step:
661 steps.append(step[0])
664 if last_step[1][-1] == self.end_format:
667 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
671 # Part of an unfinished attempt to make lyx2lyx gave a more
672 # structured view of the document.
673 # def get_toc(self, depth = 4):
674 # " Returns the TOC of this LyX document."
675 # paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
676 # 'Subsection' : 3, 'Subsubsection': 4}
677 # allowed_insets = ['Quotes']
678 # allowed_parameters = ('\\paragraph_spacing', '\\noindent',
679 # '\\align', '\\labelwidthstring',
680 # "\\start_of_appendix", "\\leftindent")
682 # for section in paragraphs_filter.keys():
683 # sections.append('\\begin_layout %s' % section)
688 # i = find_tokens(self.body, sections, i)
692 # j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
694 # self.warning('Incomplete file.', 0)
697 # section = self.body[i].split()[1]
698 # if section[-1] == '*':
699 # section = section[:-1]
704 # # skip paragraph parameters
705 # while not self.body[k].strip() or self.body[k].split()[0] \
706 # in allowed_parameters:
710 # if check_token(self.body[k], '\\begin_inset'):
711 # inset = self.body[k].split()[1]
712 # end = find_end_of_inset(self.body, k)
713 # if end == -1 or end > j:
714 # self.warning('Malformed file.', 0)
716 # if inset in allowed_insets:
717 # par.extend(self.body[k: end+1])
720 # par.append(self.body[k])
723 # # trim empty lines in the end.
724 # while par and par[-1].strip() == '':
727 # toc_par.append(Paragraph(section, par))
734 class File(LyX_base):
735 " This class reads existing LyX files."
737 def __init__(self, end_format = 0, input = "", output = "", error = "",
738 debug = default_debug__, try_hard = 0, cjk_encoding = '',
739 final_version = '', systemlyxdir = ''):
740 LyX_base.__init__(self, end_format, input, output, error,
741 debug, try_hard, cjk_encoding, final_version,
746 # FIXME: header settings are completely outdated, don't use like this
747 #class NewFile(LyX_base):
748 # " This class is to create new LyX files."
749 # def set_header(self, **params):
750 # # set default values
751 # self.header.extend([
752 # "#LyX xxxx created this file."
753 # "For more info see http://www.lyx.org/",
755 # "\\begin_document",
757 # "\\textclass article",
758 # "\\language english",
759 # "\\inputencoding auto",
760 # "\\font_roman default",
761 # "\\font_sans default",
762 # "\\font_typewriter default",
763 # "\\font_default_family default",
765 # "\\font_osf false",
766 # "\\font_sf_scale 100",
767 # "\\font_tt_scale 100",
768 # "\\graphics default",
769 # "\\paperfontsize default",
770 # "\\papersize default",
771 # "\\use_geometry false",
773 # "\\cite_engine basic",
774 # "\\use_bibtopic false",
775 # "\\use_indices false",
776 # "\\paperorientation portrait",
779 # "\\paragraph_separation indent",
780 # "\\defskip medskip",
781 # "\\quotes_language english",
782 # "\\papercolumns 1",
784 # "\\paperpagestyle default",
785 # "\\tracking_changes false",
788 # self.format = get_end_format()
789 # for param in params:
790 # self.set_parameter(param, params[param])
793 # def set_body(self, paragraphs):
794 # self.body.extend(['\\begin_body',''])
796 # for par in paragraphs:
797 # self.body.extend(par.asLines())
799 # self.body.extend(['','\\end_body', '\\end_document'])
802 # Part of an unfinished attempt to make lyx2lyx gave a more
803 # structured view of the document.
805 # # unfinished implementation, it is missing the Text and Insets
807 # " This class represents the LyX paragraphs."
808 # def __init__(self, name, body=[], settings = [], child = []):
810 # name: paragraph name.
811 # body: list of lines of body text.
812 # child: list of paragraphs that descend from this paragraph.
816 # self.settings = settings
820 # """ Converts the paragraph to a list of strings, representing
821 # it in the LyX file."""
823 # result = ['','\\begin_layout %s' % self.name]
824 # result.extend(self.settings)
826 # result.extend(self.body)
827 # result.append('\\end_layout')
832 # result.append('\\begin_deeper')
833 # for node in self.child:
834 # result.extend(node.asLines())
835 # result.append('\\end_deeper')