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", 0)),
86 ("2_1", range(414,475), minor_versions("2.1", 0))
89 ####################################################################
90 # This is useful just for development versions #
91 # if the list of supported formats is empty get it from last step #
92 if not format_relation[-1][1]:
93 step, mode = format_relation[-1][0], "convert"
94 convert = getattr(__import__("lyx_" + step), mode)
95 format_relation[-1] = (step,
96 [conv[0] for conv in convert],
97 format_relation[-1][2])
99 ####################################################################
102 " Returns a list with supported file formats."
104 for version in format_relation:
105 for format in version[1]:
106 if format not in formats:
107 formats.append(format)
112 " Returns a list with supported file formats."
113 out = """Major version:
117 for version in format_relation:
118 major = str(version[2][0])
119 versions = str(version[2][1:])
120 if len(version[1]) == 1:
121 formats = str(version[1][0])
123 formats = "%s - %s" % (version[1][-1], version[1][0])
124 out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats)
128 def get_end_format():
129 " Returns the more recent file format available."
130 # this check will fail only when we have a new version
131 # and there is no format change yet.
132 if format_relation[-1][1]:
133 return format_relation[-1][1][-1]
134 return format_relation[-2][1][-1]
137 def get_backend(textclass):
138 " For _textclass_ returns its backend."
139 if textclass == "linuxdoc" or textclass == "manpage":
141 if textclass.startswith("docbook") or textclass.startswith("agu-"):
147 " Remove end of line char(s)."
148 if line[-2:-1] == '\r':
154 def get_encoding(language, inputencoding, format, cjk_encoding):
155 " Returns enconding of the lyx file"
158 # CJK-LyX encodes files using the current locale encoding.
159 # This means that files created by CJK-LyX can only be converted using
160 # the correct locale settings unless the encoding is given as commandline
162 if cjk_encoding == 'auto':
163 return locale.getpreferredencoding()
166 from lyx2lyx_lang import lang
167 if inputencoding == "auto" or inputencoding == "default":
168 return lang[language][3]
169 if inputencoding == "":
171 if inputencoding == "utf8x":
173 # python does not know the alias latin9
174 if inputencoding == "latin9":
182 """This class carries all the information of the LyX file."""
184 def __init__(self, end_format = 0, input = "", output = "", error = "",
185 debug = default_debug__, try_hard = 0, cjk_encoding = '',
186 final_version = "", language = "english", encoding = "auto"):
189 end_format: final format that the file should be converted. (integer)
190 input: the name of the input source, if empty resort to standard input.
191 output: the name of the output file, if empty use the standard output.
192 error: the name of the error file, if empty use the standard error.
193 debug: debug level, O means no debug, as its value increases be more verbose.
195 self.choose_io(input, output)
198 self.err = open(error, "w")
200 self.err = sys.stderr
203 self.try_hard = try_hard
204 self.cjk_encoding = cjk_encoding
207 self.end_format = self.lyxformat(end_format)
209 # In case the target version and format are both specified
210 # verify that they are compatible. If not send a warning
211 # and ignore the version.
213 message = "Incompatible version %s for specified format %d" % (
214 final_version, self.end_format)
215 for version in format_relation:
216 if self.end_format in version[1]:
217 if final_version not in version[2]:
218 self.warning(message)
221 for version in format_relation:
222 if final_version in version[2]:
223 # set the last format for that version
224 self.end_format = version[1][-1]
229 self.end_format = get_end_format()
231 if not final_version:
232 for step in format_relation:
233 if self.end_format in step[1]:
234 final_version = step[2][1]
235 self.final_version = final_version
236 self.warning("Final version: %s" % self.final_version, 10)
237 self.warning("Final format: %d" % self.end_format, 10)
239 self.backend = "latex"
240 self.textclass = "article"
241 # This is a hack: We use '' since we don't know the default
242 # layout of the text class. LyX will parse it as default layout.
243 # FIXME: Read the layout file and use the real default layout
244 self.default_layout = ''
249 self.encoding = encoding
250 self.language = language
253 def warning(self, message, debug_level= default_debug__):
254 """ Emits warning to self.error, if the debug_level is less
255 than the self.debug."""
256 if debug_level <= self.debug:
257 self.err.write("Warning: " + message + "\n")
260 def error(self, message):
261 " Emits a warning and exits if not in try_hard mode."
262 self.warning(message)
263 if not self.try_hard:
264 self.warning("Quitting.")
271 """Reads a file into the self.header and
272 self.body parts, from self.input."""
275 line = self.input.readline()
277 self.error("Invalid LyX file.")
279 line = trim_eol(line)
280 if check_token(line, '\\begin_preamble'):
282 line = self.input.readline()
284 self.error("Invalid LyX file.")
286 line = trim_eol(line)
287 if check_token(line, '\\end_preamble'):
290 if line.split()[:0] in ("\\layout",
291 "\\begin_layout", "\\begin_body"):
293 self.warning("Malformed LyX file:"
294 "Missing '\\end_preamble'."
295 "\nAdding it now and hoping"
298 self.preamble.append(line)
300 if check_token(line, '\\end_preamble'):
307 if line.split()[0] in ("\\layout", "\\begin_layout",
308 "\\begin_body", "\\begin_deeper"):
309 self.body.append(line)
312 self.header.append(line)
314 i = find_token(self.header, '\\textclass', 0)
316 self.warning("Malformed LyX file: Missing '\\textclass'.")
317 i = find_token(self.header, '\\lyxformat', 0) + 1
318 self.header[i:i] = ['\\textclass article']
320 self.textclass = get_value(self.header, "\\textclass", 0)
321 self.backend = get_backend(self.textclass)
322 self.format = self.read_format()
323 self.language = get_value(self.header, "\\language", 0,
325 self.inputencoding = get_value(self.header, "\\inputencoding",
327 self.encoding = get_encoding(self.language,
328 self.inputencoding, self.format,
330 self.initial_version = self.read_version()
332 # Second pass over header and preamble, now we know the file encoding
333 # Do not forget the textclass (Debian bug #700828)
334 self.textclass = self.textclass.decode(self.encoding)
335 for i in range(len(self.header)):
336 self.header[i] = self.header[i].decode(self.encoding)
337 for i in range(len(self.preamble)):
338 self.preamble[i] = self.preamble[i].decode(self.encoding)
342 line = self.input.readline().decode(self.encoding)
345 self.body.append(trim_eol(line))
349 " Writes the LyX file to self.output."
353 if self.encoding == "auto":
354 self.encoding = get_encoding(self.language, self.encoding,
355 self.format, self.cjk_encoding)
357 i = find_token(self.header, '\\textclass', 0) + 1
358 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
359 header = self.header[:i] + preamble + self.header[i:]
363 for line in header + [''] + self.body:
364 self.output.write(line.encode(self.encoding)+"\n")
367 def choose_io(self, input, output):
368 """Choose input and output streams, dealing transparently with
372 self.output = open(output, "wb")
374 self.output = sys.stdout
376 if input and input != '-':
377 self.dir = os.path.dirname(os.path.abspath(input))
379 gzip.open(input).readline()
380 self.input = gzip.open(input)
381 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
383 self.input = open(input)
386 self.input = sys.stdin
389 def lyxformat(self, format):
390 " Returns the file format representation, an integer."
391 result = format_re.match(format)
393 format = int(result.group(1) + result.group(2))
397 self.error(str(format) + ": " + "Invalid LyX file.")
399 if format in formats_list():
402 self.error(str(format) + ": " + "Format not supported.")
406 def read_version(self):
407 """ Searchs for clues of the LyX version used to write the
408 file, returns the most likely value, or None otherwise."""
410 for line in self.header:
414 line = line.replace("fix",".")
415 result = original_version.match(line)
417 # Special know cases: reLyX and KLyX
418 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
421 res = result.group(1)
424 #self.warning("Version %s" % result.group(1))
426 self.warning(str(self.header[:2]))
430 def set_version(self):
431 " Set the header with the version used."
432 self.header[0] = " ".join(["#LyX %s created this file." % version__,
433 "For more info see http://www.lyx.org/"])
434 if self.header[1][0] == '#':
438 def read_format(self):
439 " Read from the header the fileformat of the present LyX file."
440 for line in self.header:
441 result = fileformat.match(line)
443 return self.lyxformat(result.group(1))
445 self.error("Invalid LyX File.")
449 def set_format(self):
450 " Set the file format of the file, in the header."
451 if self.format <= 217:
452 format = str(float(self.format)/100)
454 format = str(self.format)
455 i = find_token(self.header, "\\lyxformat", 0)
456 self.header[i] = "\\lyxformat %s" % format
459 def set_textclass(self):
460 i = find_token(self.header, "\\textclass", 0)
461 self.header[i] = "\\textclass %s" % self.textclass
464 #Note that the module will be added at the END of the extant ones
465 def add_module(self, module):
466 i = find_token(self.header, "\\begin_modules", 0)
468 #No modules yet included
469 i = find_token(self.header, "\\textclass", 0)
471 self.warning("Malformed LyX document: No \\textclass!!")
473 modinfo = ["\\begin_modules", module, "\\end_modules"]
474 self.header[i + 1: i + 1] = modinfo
476 j = find_token(self.header, "\\end_modules", i)
478 self.warning("(add_module)Malformed LyX document: No \\end_modules.")
480 k = find_token(self.header, module, i)
481 if k != -1 and k < j:
483 self.header.insert(j, module)
486 def get_module_list(self):
487 i = find_token(self.header, "\\begin_modules", 0)
490 j = find_token(self.header, "\\end_modules", i)
491 return self.header[i + 1 : j]
494 def set_module_list(self, mlist):
495 modbegin = find_token(self.header, "\\begin_modules", 0)
496 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
498 #No modules yet included
499 tclass = find_token(self.header, "\\textclass", 0)
501 self.warning("Malformed LyX document: No \\textclass!!")
503 modbegin = tclass + 1
504 self.header[modbegin:modbegin] = newmodlist
506 modend = find_token(self.header, "\\end_modules", modbegin)
508 self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
510 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
511 self.header[modbegin:modend + 1] = newmodlist
514 def set_parameter(self, param, value):
515 " Set the value of the header parameter."
516 i = find_token(self.header, '\\' + param, 0)
518 self.warning('Parameter not found in the header: %s' % param, 3)
520 self.header[i] = '\\%s %s' % (param, str(value))
523 def is_default_layout(self, layout):
524 " Check whether a layout is the default layout of this class."
525 # FIXME: Check against the real text class default layout
526 if layout == 'Standard' or layout == self.default_layout:
532 "Convert from current (self.format) to self.end_format."
533 mode, conversion_chain = self.chain()
534 self.warning("conversion chain: " + str(conversion_chain), 3)
536 for step in conversion_chain:
537 steps = getattr(__import__("lyx_" + step), mode)
539 self.warning("Convertion step: %s - %s" % (step, mode),
542 self.error("The conversion to an older "
543 "format (%s) is not implemented." % self.format)
545 multi_conv = len(steps) != 1
546 for version, table in steps:
548 (self.format >= version and mode == "convert") or\
549 (self.format <= version and mode == "revert"):
557 self.warning("An error ocurred in %s, %s" %
558 (version, str(conv)),
560 if not self.try_hard:
564 self.warning("%lf: Elapsed time on %s" %
565 (time.time() - init_t,
566 str(conv)), default_debug__ +
568 self.format = version
569 if self.end_format == self.format:
574 """ This is where all the decisions related with the
575 conversion are taken. It returns a list of modules needed to
576 convert the LyX file from self.format to self.end_format"""
578 self.start = self.format
582 for rel in format_relation:
583 if self.initial_version in rel[2]:
585 initial_step = rel[0]
589 if not correct_version:
591 self.warning("Version does not match file format, "
592 "discarding it. (Version %s, format %d)" %
593 (self.initial_version, self.format))
594 for rel in format_relation:
596 initial_step = rel[0]
599 # This should not happen, really.
600 self.error("Format not supported.")
602 # Find the final step
603 for rel in format_relation:
604 if self.end_format in rel[1]:
608 self.error("Format not supported.")
610 # Convertion mode, back or forth
612 if (initial_step, self.start) < (final_step, self.end_format):
615 for step in format_relation:
616 if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
617 full_steps.append(step)
618 if full_steps[0][1][-1] == self.format:
619 full_steps = full_steps[1:]
620 for step in full_steps:
621 steps.append(step[0])
624 relation_format = format_relation[:]
625 relation_format.reverse()
628 for step in relation_format:
629 if final_step <= step[0] <= initial_step:
630 steps.append(step[0])
633 if last_step[1][-1] == self.end_format:
636 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
640 # Part of an unfinished attempt to make lyx2lyx gave a more
641 # structured view of the document.
642 # def get_toc(self, depth = 4):
643 # " Returns the TOC of this LyX document."
644 # paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
645 # 'Subsection' : 3, 'Subsubsection': 4}
646 # allowed_insets = ['Quotes']
647 # allowed_parameters = ('\\paragraph_spacing', '\\noindent',
648 # '\\align', '\\labelwidthstring',
649 # "\\start_of_appendix", "\\leftindent")
651 # for section in paragraphs_filter.keys():
652 # sections.append('\\begin_layout %s' % section)
657 # i = find_tokens(self.body, sections, i)
661 # j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
663 # self.warning('Incomplete file.', 0)
666 # section = self.body[i].split()[1]
667 # if section[-1] == '*':
668 # section = section[:-1]
673 # # skip paragraph parameters
674 # while not self.body[k].strip() or self.body[k].split()[0] \
675 # in allowed_parameters:
679 # if check_token(self.body[k], '\\begin_inset'):
680 # inset = self.body[k].split()[1]
681 # end = find_end_of_inset(self.body, k)
682 # if end == -1 or end > j:
683 # self.warning('Malformed file.', 0)
685 # if inset in allowed_insets:
686 # par.extend(self.body[k: end+1])
689 # par.append(self.body[k])
692 # # trim empty lines in the end.
693 # while par and par[-1].strip() == '':
696 # toc_par.append(Paragraph(section, par))
703 class File(LyX_base):
704 " This class reads existing LyX files."
706 def __init__(self, end_format = 0, input = "", output = "", error = "",
707 debug = default_debug__, try_hard = 0, cjk_encoding = '',
709 LyX_base.__init__(self, end_format, input, output, error,
710 debug, try_hard, cjk_encoding, final_version)
714 #class NewFile(LyX_base):
715 # " This class is to create new LyX files."
716 # def set_header(self, **params):
717 # # set default values
718 # self.header.extend([
719 # "#LyX xxxx created this file."
720 # "For more info see http://www.lyx.org/",
722 # "\\begin_document",
724 # "\\textclass article",
725 # "\\language english",
726 # "\\inputencoding auto",
727 # "\\font_roman default",
728 # "\\font_sans default",
729 # "\\font_typewriter default",
730 # "\\font_default_family default",
732 # "\\font_osf false",
733 # "\\font_sf_scale 100",
734 # "\\font_tt_scale 100",
735 # "\\graphics default",
736 # "\\paperfontsize default",
737 # "\\papersize default",
738 # "\\use_geometry false",
740 # "\\cite_engine basic",
741 # "\\use_bibtopic false",
742 # "\\paperorientation portrait",
745 # "\\paragraph_separation indent",
746 # "\\defskip medskip",
747 # "\\quotes_language english",
748 # "\\papercolumns 1",
750 # "\\paperpagestyle default",
751 # "\\tracking_changes false",
754 # self.format = get_end_format()
755 # for param in params:
756 # self.set_parameter(param, params[param])
759 # def set_body(self, paragraphs):
760 # self.body.extend(['\\begin_body',''])
762 # for par in paragraphs:
763 # self.body.extend(par.asLines())
765 # self.body.extend(['','\\end_body', '\\end_document'])
768 # Part of an unfinished attempt to make lyx2lyx gave a more
769 # structured view of the document.
771 # # unfinished implementation, it is missing the Text and Insets
773 # " This class represents the LyX paragraphs."
774 # def __init__(self, name, body=[], settings = [], child = []):
776 # name: paragraph name.
777 # body: list of lines of body text.
778 # child: list of paragraphs that descend from this paragraph.
782 # self.settings = settings
786 # """ Converts the paragraph to a list of strings, representing
787 # it in the LyX file."""
789 # result = ['','\\begin_layout %s' % self.name]
790 # result.extend(self.settings)
792 # result.extend(self.body)
793 # result.append('\\end_layout')
798 # result.append('\\begin_deeper')
799 # for node in self.child:
800 # result.extend(node.asLines())
801 # result.append('\\end_deeper')