1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2002-2004 Dekel Tsur <dekel@lyx.org>
4 # Copyright (C) 2002-2006 José Matos <jamatos@lyx.org>
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 " The LyX module has all the rules related with different lyx file formats."
22 from parser_tools import get_value, check_token, find_token, \
23 find_tokens, find_end_of
32 import lyx2lyx_version
33 version__ = lyx2lyx_version.version
34 except: # we are running from build directory so assume the last version
39 ####################################################################
40 # Private helper functions
42 def find_end_of_inset(lines, i):
43 " Find beginning of inset, where lines[i] is included."
44 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
46 def minor_versions(major, last_minor_version):
47 """ Generate minor versions, using major as prefix and minor
48 versions from 0 until last_minor_version, plus the generic version.
52 minor_versions("1.2", 4) ->
53 [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
55 return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
58 # End of helper functions
59 ####################################################################
62 # Regular expressions used
63 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
64 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
65 original_version = re.compile(r".*?LyX ([\d.]*)")
68 # file format information:
69 # file, supported formats, stable release versions
70 format_relation = [("0_06", [200], minor_versions("0.6" , 4)),
71 ("0_08", [210], minor_versions("0.8" , 6) + ["0.7"]),
72 ("0_10", [210], minor_versions("0.10", 7) + ["0.9"]),
73 ("0_12", [215], minor_versions("0.12", 1) + ["0.11"]),
74 ("1_0", [215], minor_versions("1.0" , 4)),
75 ("1_1", [215], minor_versions("1.1" , 4)),
76 ("1_1_5", [216], ["1.1", "1.1.5","1.1.5.1","1.1.5.2"]),
77 ("1_1_6_0", [217], ["1.1", "1.1.6","1.1.6.1","1.1.6.2"]),
78 ("1_1_6_3", [218], ["1.1", "1.1.6.3","1.1.6.4"]),
79 ("1_2", [220], minor_versions("1.2" , 4)),
80 ("1_3", [221], minor_versions("1.3" , 7)),
81 ("1_4", range(222,246), minor_versions("1.4" , 5)),
82 ("1_5", range(246,277), minor_versions("1.5" , 7)),
83 ("1_6", range(277,346), minor_versions("1.6" , 10)),
84 ("2_0", range(347,414), minor_versions("2.0", 0)),
85 ("2_1", [], minor_versions("2.1", 0))]
87 ####################################################################
88 # This is useful just for development versions #
89 # if the list of supported formats is empty get it from last step #
90 if not format_relation[-1][1]:
91 step, mode = format_relation[-1][0], "convert"
92 convert = getattr(__import__("lyx_" + step), mode)
93 format_relation[-1] = (step,
94 [conv[0] for conv in convert],
95 format_relation[-1][2])
97 ####################################################################
100 " Returns a list with supported file formats."
102 for version in format_relation:
103 for format in version[1]:
104 if format not in formats:
105 formats.append(format)
110 " Returns a list with supported file formats."
111 out = """Major version:
115 for version in format_relation:
116 major = str(version[2][0])
117 versions = str(version[2][1:])
118 if len(version[1]) == 1:
119 formats = str(version[1][0])
121 formats = "%s - %s" % (version[1][-1], version[1][0])
122 out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats)
126 def get_end_format():
127 " Returns the more recent file format available."
128 return format_relation[-1][1][-1]
131 def get_backend(textclass):
132 " For _textclass_ returns its backend."
133 if textclass == "linuxdoc" or textclass == "manpage":
135 if textclass.startswith("docbook") or textclass.startswith("agu-"):
141 " Remove end of line char(s)."
142 if line[-2:-1] == '\r':
148 def get_encoding(language, inputencoding, format, cjk_encoding):
149 " Returns enconding of the lyx file"
152 # CJK-LyX encodes files using the current locale encoding.
153 # This means that files created by CJK-LyX can only be converted using
154 # the correct locale settings unless the encoding is given as commandline
156 if cjk_encoding == 'auto':
157 return locale.getpreferredencoding()
160 from lyx2lyx_lang import lang
161 if inputencoding == "auto" or inputencoding == "default":
162 return lang[language][3]
163 if inputencoding == "":
165 if inputencoding == "utf8x":
167 # python does not know the alias latin9
168 if inputencoding == "latin9":
176 """This class carries all the information of the LyX file."""
178 def __init__(self, end_format = 0, input = "", output = "", error = "",
179 debug = default_debug__, try_hard = 0, cjk_encoding = '',
180 final_version = "", language = "english", encoding = "auto"):
183 end_format: final format that the file should be converted. (integer)
184 input: the name of the input source, if empty resort to standard input.
185 output: the name of the output file, if empty use the standard output.
186 error: the name of the error file, if empty use the standard error.
187 debug: debug level, O means no debug, as its value increases be more verbose.
189 self.choose_io(input, output)
192 self.err = open(error, "w")
194 self.err = sys.stderr
197 self.try_hard = try_hard
198 self.cjk_encoding = cjk_encoding
201 self.end_format = self.lyxformat(end_format)
203 # In case the target version and format are both specified
204 # verify that they are compatible. If not send a warning
205 # and ignore the version.
207 message = "Incompatible version %s for specified format %d" % (
208 final_version, self.end_format)
209 for version in format_relation:
210 if self.end_format in version[1]:
211 if final_version not in version[2]:
212 self.warning(message)
215 for version in format_relation:
216 if final_version in version[2]:
217 # set the last format for that version
218 self.end_format = version[1][-1]
223 self.end_format = get_end_format()
225 if not final_version:
226 for step in format_relation:
227 if self.end_format in step[1]:
228 final_version = step[2][1]
229 self.final_version = final_version
230 self.warning("Final version: %s" % self.final_version, 10)
231 self.warning("Final format: %d" % self.end_format, 10)
233 self.backend = "latex"
234 self.textclass = "article"
235 # This is a hack: We use '' since we don't know the default
236 # layout of the text class. LyX will parse it as default layout.
237 # FIXME: Read the layout file and use the real default layout
238 self.default_layout = ''
243 self.encoding = encoding
244 self.language = language
247 def warning(self, message, debug_level= default_debug__):
248 """ Emits warning to self.error, if the debug_level is less
249 than the self.debug."""
250 if debug_level <= self.debug:
251 self.err.write("Warning: " + message + "\n")
254 def error(self, message):
255 " Emits a warning and exits if not in try_hard mode."
256 self.warning(message)
257 if not self.try_hard:
258 self.warning("Quitting.")
265 """Reads a file into the self.header and
266 self.body parts, from self.input."""
269 line = self.input.readline()
271 self.error("Invalid LyX file.")
273 line = trim_eol(line)
274 if check_token(line, '\\begin_preamble'):
276 line = self.input.readline()
278 self.error("Invalid LyX file.")
280 line = trim_eol(line)
281 if check_token(line, '\\end_preamble'):
284 if line.split()[:0] in ("\\layout",
285 "\\begin_layout", "\\begin_body"):
287 self.warning("Malformed LyX file:"
288 "Missing '\\end_preamble'."
289 "\nAdding it now and hoping"
292 self.preamble.append(line)
294 if check_token(line, '\\end_preamble'):
301 if line.split()[0] in ("\\layout", "\\begin_layout",
302 "\\begin_body", "\\begin_deeper"):
303 self.body.append(line)
306 self.header.append(line)
308 i = find_token(self.header, '\\textclass', 0)
310 self.warning("Malformed LyX file: Missing '\\textclass'.")
311 i = find_token(self.header, '\\lyxformat', 0) + 1
312 self.header[i:i] = ['\\textclass article']
314 self.textclass = get_value(self.header, "\\textclass", 0)
315 self.backend = get_backend(self.textclass)
316 self.format = self.read_format()
317 self.language = get_value(self.header, "\\language", 0,
319 self.inputencoding = get_value(self.header, "\\inputencoding",
321 self.encoding = get_encoding(self.language,
322 self.inputencoding, self.format,
324 self.initial_version = self.read_version()
326 # Second pass over header and preamble, now we know the file encoding
327 for i in range(len(self.header)):
328 self.header[i] = self.header[i].decode(self.encoding)
329 for i in range(len(self.preamble)):
330 self.preamble[i] = self.preamble[i].decode(self.encoding)
334 line = self.input.readline().decode(self.encoding)
337 self.body.append(trim_eol(line))
341 " Writes the LyX file to self.output."
345 if self.encoding == "auto":
346 self.encoding = get_encoding(self.language, self.encoding,
347 self.format, self.cjk_encoding)
349 i = find_token(self.header, '\\textclass', 0) + 1
350 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
351 header = self.header[:i] + preamble + self.header[i:]
355 for line in header + [''] + self.body:
356 self.output.write(line.encode(self.encoding)+"\n")
359 def choose_io(self, input, output):
360 """Choose input and output streams, dealing transparently with
364 self.output = open(output, "wb")
366 self.output = sys.stdout
368 if input and input != '-':
369 self.dir = os.path.dirname(os.path.abspath(input))
371 gzip.open(input).readline()
372 self.input = gzip.open(input)
373 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
375 self.input = open(input)
378 self.input = sys.stdin
381 def lyxformat(self, format):
382 " Returns the file format representation, an integer."
383 result = format_re.match(format)
385 format = int(result.group(1) + result.group(2))
389 self.error(str(format) + ": " + "Invalid LyX file.")
391 if format in formats_list():
394 self.error(str(format) + ": " + "Format not supported.")
398 def read_version(self):
399 """ Searchs for clues of the LyX version used to write the
400 file, returns the most likely value, or None otherwise."""
402 for line in self.header:
406 line = line.replace("fix",".")
407 result = original_version.match(line)
409 # Special know cases: reLyX and KLyX
410 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
413 res = result.group(1)
416 #self.warning("Version %s" % result.group(1))
418 self.warning(str(self.header[:2]))
422 def set_version(self):
423 " Set the header with the version used."
424 self.header[0] = " ".join(["#LyX %s created this file." % version__,
425 "For more info see http://www.lyx.org/"])
426 if self.header[1][0] == '#':
430 def read_format(self):
431 " Read from the header the fileformat of the present LyX file."
432 for line in self.header:
433 result = fileformat.match(line)
435 return self.lyxformat(result.group(1))
437 self.error("Invalid LyX File.")
441 def set_format(self):
442 " Set the file format of the file, in the header."
443 if self.format <= 217:
444 format = str(float(self.format)/100)
446 format = str(self.format)
447 i = find_token(self.header, "\\lyxformat", 0)
448 self.header[i] = "\\lyxformat %s" % format
451 def set_textclass(self):
452 i = find_token(self.header, "\\textclass", 0)
453 self.header[i] = "\\textclass %s" % self.textclass
456 #Note that the module will be added at the END of the extant ones
457 def add_module(self, module):
458 i = find_token(self.header, "\\begin_modules", 0)
460 #No modules yet included
461 i = find_token(self.header, "\\textclass", 0)
463 self.warning("Malformed LyX document: No \\textclass!!")
465 modinfo = ["\\begin_modules", module, "\\end_modules"]
466 self.header[i + 1: i + 1] = modinfo
468 j = find_token(self.header, "\\end_modules", i)
470 self.warning("(add_module)Malformed LyX document: No \\end_modules.")
472 k = find_token(self.header, module, i)
473 if k != -1 and k < j:
475 self.header.insert(j, module)
478 def get_module_list(self):
479 i = find_token(self.header, "\\begin_modules", 0)
482 j = find_token(self.header, "\\end_modules", i)
483 return self.header[i + 1 : j]
486 def set_module_list(self, mlist):
487 modbegin = find_token(self.header, "\\begin_modules", 0)
488 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
490 #No modules yet included
491 tclass = find_token(self.header, "\\textclass", 0)
493 self.warning("Malformed LyX document: No \\textclass!!")
495 modbegin = tclass + 1
496 self.header[modbegin:modbegin] = newmodlist
498 modend = find_token(self.header, "\\end_modules", modbegin)
500 self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
502 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
503 self.header[modbegin:modend + 1] = newmodlist
506 def set_parameter(self, param, value):
507 " Set the value of the header parameter."
508 i = find_token(self.header, '\\' + param, 0)
510 self.warning('Parameter not found in the header: %s' % param, 3)
512 self.header[i] = '\\%s %s' % (param, str(value))
515 def is_default_layout(self, layout):
516 " Check whether a layout is the default layout of this class."
517 # FIXME: Check against the real text class default layout
518 if layout == 'Standard' or layout == self.default_layout:
524 "Convert from current (self.format) to self.end_format."
525 mode, conversion_chain = self.chain()
526 self.warning("conversion chain: " + str(conversion_chain), 3)
528 for step in conversion_chain:
529 steps = getattr(__import__("lyx_" + step), mode)
531 self.warning("Convertion step: %s - %s" % (step, mode),
534 self.error("The conversion to an older "
535 "format (%s) is not implemented." % self.format)
537 multi_conv = len(steps) != 1
538 for version, table in steps:
540 (self.format >= version and mode == "convert") or\
541 (self.format <= version and mode == "revert"):
549 self.warning("An error ocurred in %s, %s" %
550 (version, str(conv)),
552 if not self.try_hard:
556 self.warning("%lf: Elapsed time on %s" %
557 (time.time() - init_t,
558 str(conv)), default_debug__ +
560 self.format = version
561 if self.end_format == self.format:
566 """ This is where all the decisions related with the
567 conversion are taken. It returns a list of modules needed to
568 convert the LyX file from self.format to self.end_format"""
570 self.start = self.format
574 for rel in format_relation:
575 if self.initial_version in rel[2]:
577 initial_step = rel[0]
581 if not correct_version:
583 self.warning("Version does not match file format, "
584 "discarding it. (Version %s, format %d)" %
585 (self.initial_version, self.format))
586 for rel in format_relation:
588 initial_step = rel[0]
591 # This should not happen, really.
592 self.error("Format not supported.")
594 # Find the final step
595 for rel in format_relation:
596 if self.end_format in rel[1]:
600 self.error("Format not supported.")
602 # Convertion mode, back or forth
604 if (initial_step, self.start) < (final_step, self.end_format):
607 for step in format_relation:
608 if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
609 full_steps.append(step)
610 if full_steps[0][1][-1] == self.format:
611 full_steps = full_steps[1:]
612 for step in full_steps:
613 steps.append(step[0])
616 relation_format = format_relation[:]
617 relation_format.reverse()
620 for step in relation_format:
621 if final_step <= step[0] <= initial_step:
622 steps.append(step[0])
625 if last_step[1][-1] == self.end_format:
628 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
632 # Part of an unfinished attempt to make lyx2lyx gave a more
633 # structured view of the document.
634 # def get_toc(self, depth = 4):
635 # " Returns the TOC of this LyX document."
636 # paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
637 # 'Subsection' : 3, 'Subsubsection': 4}
638 # allowed_insets = ['Quotes']
639 # allowed_parameters = ('\\paragraph_spacing', '\\noindent',
640 # '\\align', '\\labelwidthstring',
641 # "\\start_of_appendix", "\\leftindent")
643 # for section in paragraphs_filter.keys():
644 # sections.append('\\begin_layout %s' % section)
649 # i = find_tokens(self.body, sections, i)
653 # j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
655 # self.warning('Incomplete file.', 0)
658 # section = self.body[i].split()[1]
659 # if section[-1] == '*':
660 # section = section[:-1]
665 # # skip paragraph parameters
666 # while not self.body[k].strip() or self.body[k].split()[0] \
667 # in allowed_parameters:
671 # if check_token(self.body[k], '\\begin_inset'):
672 # inset = self.body[k].split()[1]
673 # end = find_end_of_inset(self.body, k)
674 # if end == -1 or end > j:
675 # self.warning('Malformed file.', 0)
677 # if inset in allowed_insets:
678 # par.extend(self.body[k: end+1])
681 # par.append(self.body[k])
684 # # trim empty lines in the end.
685 # while par and par[-1].strip() == '':
688 # toc_par.append(Paragraph(section, par))
695 class File(LyX_base):
696 " This class reads existing LyX files."
698 def __init__(self, end_format = 0, input = "", output = "", error = "",
699 debug = default_debug__, try_hard = 0, cjk_encoding = '',
701 LyX_base.__init__(self, end_format, input, output, error,
702 debug, try_hard, cjk_encoding, final_version)
706 #class NewFile(LyX_base):
707 # " This class is to create new LyX files."
708 # def set_header(self, **params):
709 # # set default values
710 # self.header.extend([
711 # "#LyX xxxx created this file."
712 # "For more info see http://www.lyx.org/",
714 # "\\begin_document",
716 # "\\textclass article",
717 # "\\language english",
718 # "\\inputencoding auto",
719 # "\\font_roman default",
720 # "\\font_sans default",
721 # "\\font_typewriter default",
722 # "\\font_default_family default",
724 # "\\font_osf false",
725 # "\\font_sf_scale 100",
726 # "\\font_tt_scale 100",
727 # "\\graphics default",
728 # "\\paperfontsize default",
729 # "\\papersize default",
730 # "\\use_geometry false",
732 # "\\cite_engine basic",
733 # "\\use_bibtopic false",
734 # "\\paperorientation portrait",
737 # "\\paragraph_separation indent",
738 # "\\defskip medskip",
739 # "\\quotes_language english",
740 # "\\papercolumns 1",
742 # "\\paperpagestyle default",
743 # "\\tracking_changes false",
746 # self.format = get_end_format()
747 # for param in params:
748 # self.set_parameter(param, params[param])
751 # def set_body(self, paragraphs):
752 # self.body.extend(['\\begin_body',''])
754 # for par in paragraphs:
755 # self.body.extend(par.asLines())
757 # self.body.extend(['','\\end_body', '\\end_document'])
760 # Part of an unfinished attempt to make lyx2lyx gave a more
761 # structured view of the document.
763 # # unfinished implementation, it is missing the Text and Insets
765 # " This class represents the LyX paragraphs."
766 # def __init__(self, name, body=[], settings = [], child = []):
768 # name: paragraph name.
769 # body: list of lines of body text.
770 # child: list of paragraphs that descend from this paragraph.
774 # self.settings = settings
778 # """ Converts the paragraph to a list of strings, representing
779 # it in the LyX file."""
781 # result = ['','\\begin_layout %s' % self.name]
782 # result.extend(self.settings)
784 # result.extend(self.body)
785 # result.append('\\end_layout')
790 # result.append('\\begin_deeper')
791 # for node in self.child:
792 # result.extend(node.asLines())
793 # result.append('\\end_deeper')