1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2002-2011 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.]*)")
69 # file format information:
70 # file, supported formats, stable release versions
71 format_relation = [("0_06", [200], minor_versions("0.6" , 4)),
72 ("0_08", [210], minor_versions("0.8" , 6) + ["0.7"]),
73 ("0_10", [210], minor_versions("0.10", 7) + ["0.9"]),
74 ("0_12", [215], minor_versions("0.12", 1) + ["0.11"]),
75 ("1_0", [215], minor_versions("1.0" , 4)),
76 ("1_1", [215], minor_versions("1.1" , 4)),
77 ("1_1_5", [216], ["1.1", "1.1.5","1.1.5.1","1.1.5.2"]),
78 ("1_1_6_0", [217], ["1.1", "1.1.6","1.1.6.1","1.1.6.2"]),
79 ("1_1_6_3", [218], ["1.1", "1.1.6.3","1.1.6.4"]),
80 ("1_2", [220], minor_versions("1.2" , 4)),
81 ("1_3", [221], minor_versions("1.3" , 7)),
82 ("1_4", range(222,246), minor_versions("1.4" , 5)),
83 ("1_5", range(246,277), minor_versions("1.5" , 7)),
84 ("1_6", range(277,346), minor_versions("1.6" , 10)),
85 ("2_0", range(346,414), minor_versions("2.0", 8)),
86 ("2_1", range(414,475), minor_versions("2.1", 0)),
87 ("2_2", [], minor_versions("2.2", 0))
90 ####################################################################
91 # This is useful just for development versions #
92 # if the list of supported formats is empty get it from last step #
93 if not format_relation[-1][1]:
94 step, mode = format_relation[-1][0], "convert"
95 convert = getattr(__import__("lyx_" + step), mode)
96 format_relation[-1] = (step,
97 [conv[0] for conv in convert],
98 format_relation[-1][2])
100 ####################################################################
103 " Returns a list with supported file formats."
105 for version in format_relation:
106 for format in version[1]:
107 if format not in formats:
108 formats.append(format)
113 " Returns a list with supported file formats."
114 out = """Major version:
118 for version in format_relation:
119 major = str(version[2][0])
120 versions = str(version[2][1:])
121 if len(version[1]) == 1:
122 formats = str(version[1][0])
124 formats = "%s - %s" % (version[1][-1], version[1][0])
125 out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats)
129 def get_end_format():
130 " Returns the more recent file format available."
131 # this check will fail only when we have a new version
132 # and there is no format change yet.
133 if format_relation[-1][1]:
134 return format_relation[-1][1][-1]
135 return format_relation[-2][1][-1]
138 def get_backend(textclass):
139 " For _textclass_ returns its backend."
140 if textclass == "linuxdoc" or textclass == "manpage":
142 if textclass.startswith("docbook") or textclass.startswith("agu-"):
148 " Remove end of line char(s)."
149 if line[-2:-1] == '\r':
155 def get_encoding(language, inputencoding, format, cjk_encoding):
156 " Returns enconding of the lyx file"
159 # CJK-LyX encodes files using the current locale encoding.
160 # This means that files created by CJK-LyX can only be converted using
161 # the correct locale settings unless the encoding is given as commandline
163 if cjk_encoding == 'auto':
164 return locale.getpreferredencoding()
167 from lyx2lyx_lang import lang
168 if inputencoding == "auto" or inputencoding == "default":
169 return lang[language][3]
170 if inputencoding == "":
172 if inputencoding == "utf8x":
174 # python does not know the alias latin9
175 if inputencoding == "latin9":
183 """This class carries all the information of the LyX file."""
185 def __init__(self, end_format = 0, input = "", output = "", error = "",
186 debug = default_debug__, try_hard = 0, cjk_encoding = '',
187 final_version = "", language = "english", encoding = "auto"):
190 end_format: final format that the file should be converted. (integer)
191 input: the name of the input source, if empty resort to standard input.
192 output: the name of the output file, if empty use the standard output.
193 error: the name of the error file, if empty use the standard error.
194 debug: debug level, O means no debug, as its value increases be more verbose.
196 self.choose_io(input, output)
199 self.err = open(error, "w")
201 self.err = sys.stderr
204 self.try_hard = try_hard
205 self.cjk_encoding = cjk_encoding
208 self.end_format = self.lyxformat(end_format)
210 # In case the target version and format are both specified
211 # verify that they are compatible. If not send a warning
212 # and ignore the version.
214 message = "Incompatible version %s for specified format %d" % (
215 final_version, self.end_format)
216 for version in format_relation:
217 if self.end_format in version[1]:
218 if final_version not in version[2]:
219 self.warning(message)
222 for version in format_relation:
223 if final_version in version[2]:
224 # set the last format for that version
225 self.end_format = version[1][-1]
230 self.end_format = get_end_format()
232 if not final_version:
233 for step in format_relation:
234 if self.end_format in step[1]:
235 final_version = step[2][1]
236 self.final_version = final_version
237 self.warning("Final version: %s" % self.final_version, 10)
238 self.warning("Final format: %d" % self.end_format, 10)
240 self.backend = "latex"
241 self.textclass = "article"
242 # This is a hack: We use '' since we don't know the default
243 # layout of the text class. LyX will parse it as default layout.
244 # FIXME: Read the layout file and use the real default layout
245 self.default_layout = ''
250 self.encoding = encoding
251 self.language = language
254 def warning(self, message, debug_level= default_debug__):
255 """ Emits warning to self.error, if the debug_level is less
256 than the self.debug."""
257 if debug_level <= self.debug:
258 self.err.write("Warning: " + message + "\n")
261 def error(self, message):
262 " Emits a warning and exits if not in try_hard mode."
263 self.warning(message)
264 if not self.try_hard:
265 self.warning("Quitting.")
272 """Reads a file into the self.header and
273 self.body parts, from self.input."""
276 line = self.input.readline()
278 self.error("Invalid LyX file.")
280 line = trim_eol(line)
281 if check_token(line, '\\begin_preamble'):
283 line = self.input.readline()
285 self.error("Invalid LyX file.")
287 line = trim_eol(line)
288 if check_token(line, '\\end_preamble'):
291 if line.split()[:0] in ("\\layout",
292 "\\begin_layout", "\\begin_body"):
294 self.warning("Malformed LyX file:"
295 "Missing '\\end_preamble'."
296 "\nAdding it now and hoping"
299 self.preamble.append(line)
301 if check_token(line, '\\end_preamble'):
308 if line.split()[0] in ("\\layout", "\\begin_layout",
309 "\\begin_body", "\\begin_deeper"):
310 self.body.append(line)
313 self.header.append(line)
315 i = find_token(self.header, '\\textclass', 0)
317 self.warning("Malformed LyX file: Missing '\\textclass'.")
318 i = find_token(self.header, '\\lyxformat', 0) + 1
319 self.header[i:i] = ['\\textclass article']
321 self.textclass = get_value(self.header, "\\textclass", 0)
322 self.backend = get_backend(self.textclass)
323 self.format = self.read_format()
324 self.language = get_value(self.header, "\\language", 0,
326 self.inputencoding = get_value(self.header, "\\inputencoding",
328 self.encoding = get_encoding(self.language,
329 self.inputencoding, self.format,
331 self.initial_version = self.read_version()
333 # Second pass over header and preamble, now we know the file encoding
334 # Do not forget the textclass (Debian bug #700828)
335 self.textclass = self.textclass.decode(self.encoding)
336 for i in range(len(self.header)):
337 self.header[i] = self.header[i].decode(self.encoding)
338 for i in range(len(self.preamble)):
339 self.preamble[i] = self.preamble[i].decode(self.encoding)
343 line = self.input.readline().decode(self.encoding)
346 self.body.append(trim_eol(line))
350 " Writes the LyX file to self.output."
354 if self.encoding == "auto":
355 self.encoding = get_encoding(self.language, self.encoding,
356 self.format, self.cjk_encoding)
358 i = find_token(self.header, '\\textclass', 0) + 1
359 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
360 header = self.header[:i] + preamble + self.header[i:]
364 for line in header + [''] + self.body:
365 self.output.write(line.encode(self.encoding)+"\n")
368 def choose_io(self, input, output):
369 """Choose input and output streams, dealing transparently with
373 self.output = open(output, "wb")
375 self.output = sys.stdout
377 if input and input != '-':
378 self.dir = os.path.dirname(os.path.abspath(input))
380 gzip.open(input).readline()
381 self.input = gzip.open(input)
382 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
384 self.input = open(input)
387 self.input = sys.stdin
390 def lyxformat(self, format):
391 " Returns the file format representation, an integer."
392 result = format_re.match(format)
394 format = int(result.group(1) + result.group(2))
398 self.error(str(format) + ": " + "Invalid LyX file.")
400 if format in formats_list():
403 self.error(str(format) + ": " + "Format not supported.")
407 def read_version(self):
408 """ Searchs for clues of the LyX version used to write the
409 file, returns the most likely value, or None otherwise."""
411 for line in self.header:
415 line = line.replace("fix",".")
416 result = original_version.match(line)
418 # Special know cases: reLyX and KLyX
419 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
422 res = result.group(1)
425 #self.warning("Version %s" % result.group(1))
427 self.warning(str(self.header[:2]))
431 def set_version(self):
432 " Set the header with the version used."
433 self.header[0] = " ".join(["#LyX %s created this file." % version__,
434 "For more info see http://www.lyx.org/"])
435 if self.header[1][0] == '#':
439 def read_format(self):
440 " Read from the header the fileformat of the present LyX file."
441 for line in self.header:
442 result = fileformat.match(line)
444 return self.lyxformat(result.group(1))
446 self.error("Invalid LyX File.")
450 def set_format(self):
451 " Set the file format of the file, in the header."
452 if self.format <= 217:
453 format = str(float(self.format)/100)
455 format = str(self.format)
456 i = find_token(self.header, "\\lyxformat", 0)
457 self.header[i] = "\\lyxformat %s" % format
460 def set_textclass(self):
461 i = find_token(self.header, "\\textclass", 0)
462 self.header[i] = "\\textclass %s" % self.textclass
465 #Note that the module will be added at the END of the extant ones
466 def add_module(self, module):
467 i = find_token(self.header, "\\begin_modules", 0)
469 #No modules yet included
470 i = find_token(self.header, "\\textclass", 0)
472 self.warning("Malformed LyX document: No \\textclass!!")
474 modinfo = ["\\begin_modules", module, "\\end_modules"]
475 self.header[i + 1: i + 1] = modinfo
477 j = find_token(self.header, "\\end_modules", i)
479 self.warning("(add_module)Malformed LyX document: No \\end_modules.")
481 k = find_token(self.header, module, i)
482 if k != -1 and k < j:
484 self.header.insert(j, module)
487 def get_module_list(self):
488 i = find_token(self.header, "\\begin_modules", 0)
491 j = find_token(self.header, "\\end_modules", i)
492 return self.header[i + 1 : j]
495 def set_module_list(self, mlist):
496 modbegin = find_token(self.header, "\\begin_modules", 0)
497 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
499 #No modules yet included
500 tclass = find_token(self.header, "\\textclass", 0)
502 self.warning("Malformed LyX document: No \\textclass!!")
504 modbegin = tclass + 1
505 self.header[modbegin:modbegin] = newmodlist
507 modend = find_token(self.header, "\\end_modules", modbegin)
509 self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
511 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
512 self.header[modbegin:modend + 1] = newmodlist
515 def set_parameter(self, param, value):
516 " Set the value of the header parameter."
517 i = find_token(self.header, '\\' + param, 0)
519 self.warning('Parameter not found in the header: %s' % param, 3)
521 self.header[i] = '\\%s %s' % (param, str(value))
524 def is_default_layout(self, layout):
525 " Check whether a layout is the default layout of this class."
526 # FIXME: Check against the real text class default layout
527 if layout == 'Standard' or layout == self.default_layout:
533 "Convert from current (self.format) to self.end_format."
534 mode, conversion_chain = self.chain()
535 self.warning("conversion chain: " + str(conversion_chain), 3)
537 for step in conversion_chain:
538 steps = getattr(__import__("lyx_" + step), mode)
540 self.warning("Convertion step: %s - %s" % (step, mode),
543 self.error("The conversion to an older "
544 "format (%s) is not implemented." % self.format)
546 multi_conv = len(steps) != 1
547 for version, table in steps:
549 (self.format >= version and mode == "convert") or\
550 (self.format <= version and mode == "revert"):
558 self.warning("An error ocurred in %s, %s" %
559 (version, str(conv)),
561 if not self.try_hard:
565 self.warning("%lf: Elapsed time on %s" %
566 (time.time() - init_t,
567 str(conv)), default_debug__ +
569 self.format = version
570 if self.end_format == self.format:
575 """ This is where all the decisions related with the
576 conversion are taken. It returns a list of modules needed to
577 convert the LyX file from self.format to self.end_format"""
579 self.start = self.format
583 for rel in format_relation:
584 if self.initial_version in rel[2]:
586 initial_step = rel[0]
590 if not correct_version:
592 self.warning("Version does not match file format, "
593 "discarding it. (Version %s, format %d)" %
594 (self.initial_version, self.format))
595 for rel in format_relation:
597 initial_step = rel[0]
600 # This should not happen, really.
601 self.error("Format not supported.")
603 # Find the final step
604 for rel in format_relation:
605 if self.end_format in rel[1]:
609 self.error("Format not supported.")
611 # Convertion mode, back or forth
613 if (initial_step, self.start) < (final_step, self.end_format):
616 for step in format_relation:
617 if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
618 full_steps.append(step)
619 if full_steps[0][1][-1] == self.format:
620 full_steps = full_steps[1:]
621 for step in full_steps:
622 steps.append(step[0])
625 relation_format = format_relation[:]
626 relation_format.reverse()
629 for step in relation_format:
630 if final_step <= step[0] <= initial_step:
631 steps.append(step[0])
634 if last_step[1][-1] == self.end_format:
637 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
641 # Part of an unfinished attempt to make lyx2lyx gave a more
642 # structured view of the document.
643 # def get_toc(self, depth = 4):
644 # " Returns the TOC of this LyX document."
645 # paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
646 # 'Subsection' : 3, 'Subsubsection': 4}
647 # allowed_insets = ['Quotes']
648 # allowed_parameters = ('\\paragraph_spacing', '\\noindent',
649 # '\\align', '\\labelwidthstring',
650 # "\\start_of_appendix", "\\leftindent")
652 # for section in paragraphs_filter.keys():
653 # sections.append('\\begin_layout %s' % section)
658 # i = find_tokens(self.body, sections, i)
662 # j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
664 # self.warning('Incomplete file.', 0)
667 # section = self.body[i].split()[1]
668 # if section[-1] == '*':
669 # section = section[:-1]
674 # # skip paragraph parameters
675 # while not self.body[k].strip() or self.body[k].split()[0] \
676 # in allowed_parameters:
680 # if check_token(self.body[k], '\\begin_inset'):
681 # inset = self.body[k].split()[1]
682 # end = find_end_of_inset(self.body, k)
683 # if end == -1 or end > j:
684 # self.warning('Malformed file.', 0)
686 # if inset in allowed_insets:
687 # par.extend(self.body[k: end+1])
690 # par.append(self.body[k])
693 # # trim empty lines in the end.
694 # while par and par[-1].strip() == '':
697 # toc_par.append(Paragraph(section, par))
704 class File(LyX_base):
705 " This class reads existing LyX files."
707 def __init__(self, end_format = 0, input = "", output = "", error = "",
708 debug = default_debug__, try_hard = 0, cjk_encoding = '',
710 LyX_base.__init__(self, end_format, input, output, error,
711 debug, try_hard, cjk_encoding, final_version)
715 #class NewFile(LyX_base):
716 # " This class is to create new LyX files."
717 # def set_header(self, **params):
718 # # set default values
719 # self.header.extend([
720 # "#LyX xxxx created this file."
721 # "For more info see http://www.lyx.org/",
723 # "\\begin_document",
725 # "\\textclass article",
726 # "\\language english",
727 # "\\inputencoding auto",
728 # "\\font_roman default",
729 # "\\font_sans default",
730 # "\\font_typewriter default",
731 # "\\font_default_family default",
733 # "\\font_osf false",
734 # "\\font_sf_scale 100",
735 # "\\font_tt_scale 100",
736 # "\\graphics default",
737 # "\\paperfontsize default",
738 # "\\papersize default",
739 # "\\use_geometry false",
741 # "\\cite_engine basic",
742 # "\\use_bibtopic false",
743 # "\\paperorientation portrait",
746 # "\\paragraph_separation indent",
747 # "\\defskip medskip",
748 # "\\quotes_language english",
749 # "\\papercolumns 1",
751 # "\\paperpagestyle default",
752 # "\\tracking_changes false",
755 # self.format = get_end_format()
756 # for param in params:
757 # self.set_parameter(param, params[param])
760 # def set_body(self, paragraphs):
761 # self.body.extend(['\\begin_body',''])
763 # for par in paragraphs:
764 # self.body.extend(par.asLines())
766 # self.body.extend(['','\\end_body', '\\end_document'])
769 # Part of an unfinished attempt to make lyx2lyx gave a more
770 # structured view of the document.
772 # # unfinished implementation, it is missing the Text and Insets
774 # " This class represents the LyX paragraphs."
775 # def __init__(self, name, body=[], settings = [], child = []):
777 # name: paragraph name.
778 # body: list of lines of body text.
779 # child: list of paragraphs that descend from this paragraph.
783 # self.settings = settings
787 # """ Converts the paragraph to a list of strings, representing
788 # it in the LyX file."""
790 # result = ['','\\begin_layout %s' % self.name]
791 # result.extend(self.settings)
793 # result.extend(self.body)
794 # result.append('\\end_layout')
799 # result.append('\\begin_deeper')
800 # for node in self.child:
801 # result.extend(node.asLines())
802 # result.append('\\end_deeper')