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))
88 ####################################################################
89 # This is useful just for development versions #
90 # if the list of supported formats is empty get it from last step #
91 if not format_relation[-1][1]:
92 step, mode = format_relation[-1][0], "convert"
93 convert = getattr(__import__("lyx_" + step), mode)
94 format_relation[-1] = (step,
95 [conv[0] for conv in convert],
96 format_relation[-1][2])
98 ####################################################################
101 " Returns a list with supported file formats."
103 for version in format_relation:
104 for format in version[1]:
105 if format not in formats:
106 formats.append(format)
111 " Returns a list with supported file formats."
112 out = """Major version:
116 for version in format_relation:
117 major = str(version[2][0])
118 versions = str(version[2][1:])
119 if len(version[1]) == 1:
120 formats = str(version[1][0])
122 formats = "%s - %s" % (version[1][-1], version[1][0])
123 out += "%s\n\t%s\n\t%s\n\n" % (major, versions, formats)
127 def get_end_format():
128 " Returns the more recent file format available."
129 # this check will fail only when we have a new version
130 # and there is no format change yet.
131 if format_relation[-1][1]:
132 return format_relation[-1][1][-1]
133 return format_relation[-2][1][-1]
136 def get_backend(textclass):
137 " For _textclass_ returns its backend."
138 if textclass == "linuxdoc" or textclass == "manpage":
140 if textclass.startswith("docbook") or textclass.startswith("agu-"):
146 " Remove end of line char(s)."
147 if line[-2:-1] == '\r':
153 def get_encoding(language, inputencoding, format, cjk_encoding):
154 " Returns enconding of the lyx file"
157 # CJK-LyX encodes files using the current locale encoding.
158 # This means that files created by CJK-LyX can only be converted using
159 # the correct locale settings unless the encoding is given as commandline
161 if cjk_encoding == 'auto':
162 return locale.getpreferredencoding()
165 from lyx2lyx_lang import lang
166 if inputencoding == "auto" or inputencoding == "default":
167 return lang[language][3]
168 if inputencoding == "":
170 if inputencoding == "utf8x":
172 # python does not know the alias latin9
173 if inputencoding == "latin9":
181 """This class carries all the information of the LyX file."""
183 def __init__(self, end_format = 0, input = "", output = "", error = "",
184 debug = default_debug__, try_hard = 0, cjk_encoding = '',
185 final_version = "", language = "english", encoding = "auto"):
188 end_format: final format that the file should be converted. (integer)
189 input: the name of the input source, if empty resort to standard input.
190 output: the name of the output file, if empty use the standard output.
191 error: the name of the error file, if empty use the standard error.
192 debug: debug level, O means no debug, as its value increases be more verbose.
194 self.choose_io(input, output)
197 self.err = open(error, "w")
199 self.err = sys.stderr
202 self.try_hard = try_hard
203 self.cjk_encoding = cjk_encoding
206 self.end_format = self.lyxformat(end_format)
208 # In case the target version and format are both specified
209 # verify that they are compatible. If not send a warning
210 # and ignore the version.
212 message = "Incompatible version %s for specified format %d" % (
213 final_version, self.end_format)
214 for version in format_relation:
215 if self.end_format in version[1]:
216 if final_version not in version[2]:
217 self.warning(message)
220 for version in format_relation:
221 if final_version in version[2]:
222 # set the last format for that version
223 self.end_format = version[1][-1]
228 self.end_format = get_end_format()
230 if not final_version:
231 for step in format_relation:
232 if self.end_format in step[1]:
233 final_version = step[2][1]
234 self.final_version = final_version
235 self.warning("Final version: %s" % self.final_version, 10)
236 self.warning("Final format: %d" % self.end_format, 10)
238 self.backend = "latex"
239 self.textclass = "article"
240 # This is a hack: We use '' since we don't know the default
241 # layout of the text class. LyX will parse it as default layout.
242 # FIXME: Read the layout file and use the real default layout
243 self.default_layout = ''
248 self.encoding = encoding
249 self.language = language
252 def warning(self, message, debug_level= default_debug__):
253 """ Emits warning to self.error, if the debug_level is less
254 than the self.debug."""
255 if debug_level <= self.debug:
256 self.err.write("Warning: " + message + "\n")
259 def error(self, message):
260 " Emits a warning and exits if not in try_hard mode."
261 self.warning(message)
262 if not self.try_hard:
263 self.warning("Quitting.")
270 """Reads a file into the self.header and
271 self.body parts, from self.input."""
274 line = self.input.readline()
276 self.error("Invalid LyX file.")
278 line = trim_eol(line)
279 if check_token(line, '\\begin_preamble'):
281 line = self.input.readline()
283 self.error("Invalid LyX file.")
285 line = trim_eol(line)
286 if check_token(line, '\\end_preamble'):
289 if line.split()[:0] in ("\\layout",
290 "\\begin_layout", "\\begin_body"):
292 self.warning("Malformed LyX file:"
293 "Missing '\\end_preamble'."
294 "\nAdding it now and hoping"
297 self.preamble.append(line)
299 if check_token(line, '\\end_preamble'):
306 if line.split()[0] in ("\\layout", "\\begin_layout",
307 "\\begin_body", "\\begin_deeper"):
308 self.body.append(line)
311 self.header.append(line)
313 i = find_token(self.header, '\\textclass', 0)
315 self.warning("Malformed LyX file: Missing '\\textclass'.")
316 i = find_token(self.header, '\\lyxformat', 0) + 1
317 self.header[i:i] = ['\\textclass article']
319 self.textclass = get_value(self.header, "\\textclass", 0)
320 self.backend = get_backend(self.textclass)
321 self.format = self.read_format()
322 self.language = get_value(self.header, "\\language", 0,
324 self.inputencoding = get_value(self.header, "\\inputencoding",
326 self.encoding = get_encoding(self.language,
327 self.inputencoding, self.format,
329 self.initial_version = self.read_version()
331 # Second pass over header and preamble, now we know the file encoding
332 for i in range(len(self.header)):
333 self.header[i] = self.header[i].decode(self.encoding)
334 for i in range(len(self.preamble)):
335 self.preamble[i] = self.preamble[i].decode(self.encoding)
339 line = self.input.readline().decode(self.encoding)
342 self.body.append(trim_eol(line))
346 " Writes the LyX file to self.output."
350 if self.encoding == "auto":
351 self.encoding = get_encoding(self.language, self.encoding,
352 self.format, self.cjk_encoding)
354 i = find_token(self.header, '\\textclass', 0) + 1
355 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
356 header = self.header[:i] + preamble + self.header[i:]
360 for line in header + [''] + self.body:
361 self.output.write(line.encode(self.encoding)+"\n")
364 def choose_io(self, input, output):
365 """Choose input and output streams, dealing transparently with
369 self.output = open(output, "wb")
371 self.output = sys.stdout
373 if input and input != '-':
374 self.dir = os.path.dirname(os.path.abspath(input))
376 gzip.open(input).readline()
377 self.input = gzip.open(input)
378 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
380 self.input = open(input)
383 self.input = sys.stdin
386 def lyxformat(self, format):
387 " Returns the file format representation, an integer."
388 result = format_re.match(format)
390 format = int(result.group(1) + result.group(2))
394 self.error(str(format) + ": " + "Invalid LyX file.")
396 if format in formats_list():
399 self.error(str(format) + ": " + "Format not supported.")
403 def read_version(self):
404 """ Searchs for clues of the LyX version used to write the
405 file, returns the most likely value, or None otherwise."""
407 for line in self.header:
411 line = line.replace("fix",".")
412 result = original_version.match(line)
414 # Special know cases: reLyX and KLyX
415 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
418 res = result.group(1)
421 #self.warning("Version %s" % result.group(1))
423 self.warning(str(self.header[:2]))
427 def set_version(self):
428 " Set the header with the version used."
429 self.header[0] = " ".join(["#LyX %s created this file." % version__,
430 "For more info see http://www.lyx.org/"])
431 if self.header[1][0] == '#':
435 def read_format(self):
436 " Read from the header the fileformat of the present LyX file."
437 for line in self.header:
438 result = fileformat.match(line)
440 return self.lyxformat(result.group(1))
442 self.error("Invalid LyX File.")
446 def set_format(self):
447 " Set the file format of the file, in the header."
448 if self.format <= 217:
449 format = str(float(self.format)/100)
451 format = str(self.format)
452 i = find_token(self.header, "\\lyxformat", 0)
453 self.header[i] = "\\lyxformat %s" % format
456 def set_textclass(self):
457 i = find_token(self.header, "\\textclass", 0)
458 self.header[i] = "\\textclass %s" % self.textclass
461 #Note that the module will be added at the END of the extant ones
462 def add_module(self, module):
463 i = find_token(self.header, "\\begin_modules", 0)
465 #No modules yet included
466 i = find_token(self.header, "\\textclass", 0)
468 self.warning("Malformed LyX document: No \\textclass!!")
470 modinfo = ["\\begin_modules", module, "\\end_modules"]
471 self.header[i + 1: i + 1] = modinfo
473 j = find_token(self.header, "\\end_modules", i)
475 self.warning("(add_module)Malformed LyX document: No \\end_modules.")
477 k = find_token(self.header, module, i)
478 if k != -1 and k < j:
480 self.header.insert(j, module)
483 def get_module_list(self):
484 i = find_token(self.header, "\\begin_modules", 0)
487 j = find_token(self.header, "\\end_modules", i)
488 return self.header[i + 1 : j]
491 def set_module_list(self, mlist):
492 modbegin = find_token(self.header, "\\begin_modules", 0)
493 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
495 #No modules yet included
496 tclass = find_token(self.header, "\\textclass", 0)
498 self.warning("Malformed LyX document: No \\textclass!!")
500 modbegin = tclass + 1
501 self.header[modbegin:modbegin] = newmodlist
503 modend = find_token(self.header, "\\end_modules", modbegin)
505 self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
507 newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
508 self.header[modbegin:modend + 1] = newmodlist
511 def set_parameter(self, param, value):
512 " Set the value of the header parameter."
513 i = find_token(self.header, '\\' + param, 0)
515 self.warning('Parameter not found in the header: %s' % param, 3)
517 self.header[i] = '\\%s %s' % (param, str(value))
520 def is_default_layout(self, layout):
521 " Check whether a layout is the default layout of this class."
522 # FIXME: Check against the real text class default layout
523 if layout == 'Standard' or layout == self.default_layout:
529 "Convert from current (self.format) to self.end_format."
530 mode, conversion_chain = self.chain()
531 self.warning("conversion chain: " + str(conversion_chain), 3)
533 for step in conversion_chain:
534 steps = getattr(__import__("lyx_" + step), mode)
536 self.warning("Convertion step: %s - %s" % (step, mode),
539 self.error("The conversion to an older "
540 "format (%s) is not implemented." % self.format)
542 multi_conv = len(steps) != 1
543 for version, table in steps:
545 (self.format >= version and mode == "convert") or\
546 (self.format <= version and mode == "revert"):
554 self.warning("An error ocurred in %s, %s" %
555 (version, str(conv)),
557 if not self.try_hard:
561 self.warning("%lf: Elapsed time on %s" %
562 (time.time() - init_t,
563 str(conv)), default_debug__ +
565 self.format = version
566 if self.end_format == self.format:
571 """ This is where all the decisions related with the
572 conversion are taken. It returns a list of modules needed to
573 convert the LyX file from self.format to self.end_format"""
575 self.start = self.format
579 for rel in format_relation:
580 if self.initial_version in rel[2]:
582 initial_step = rel[0]
586 if not correct_version:
588 self.warning("Version does not match file format, "
589 "discarding it. (Version %s, format %d)" %
590 (self.initial_version, self.format))
591 for rel in format_relation:
593 initial_step = rel[0]
596 # This should not happen, really.
597 self.error("Format not supported.")
599 # Find the final step
600 for rel in format_relation:
601 if self.end_format in rel[1]:
605 self.error("Format not supported.")
607 # Convertion mode, back or forth
609 if (initial_step, self.start) < (final_step, self.end_format):
612 for step in format_relation:
613 if initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
614 full_steps.append(step)
615 if full_steps[0][1][-1] == self.format:
616 full_steps = full_steps[1:]
617 for step in full_steps:
618 steps.append(step[0])
621 relation_format = format_relation[:]
622 relation_format.reverse()
625 for step in relation_format:
626 if final_step <= step[0] <= initial_step:
627 steps.append(step[0])
630 if last_step[1][-1] == self.end_format:
633 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
637 # Part of an unfinished attempt to make lyx2lyx gave a more
638 # structured view of the document.
639 # def get_toc(self, depth = 4):
640 # " Returns the TOC of this LyX document."
641 # paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
642 # 'Subsection' : 3, 'Subsubsection': 4}
643 # allowed_insets = ['Quotes']
644 # allowed_parameters = ('\\paragraph_spacing', '\\noindent',
645 # '\\align', '\\labelwidthstring',
646 # "\\start_of_appendix", "\\leftindent")
648 # for section in paragraphs_filter.keys():
649 # sections.append('\\begin_layout %s' % section)
654 # i = find_tokens(self.body, sections, i)
658 # j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
660 # self.warning('Incomplete file.', 0)
663 # section = self.body[i].split()[1]
664 # if section[-1] == '*':
665 # section = section[:-1]
670 # # skip paragraph parameters
671 # while not self.body[k].strip() or self.body[k].split()[0] \
672 # in allowed_parameters:
676 # if check_token(self.body[k], '\\begin_inset'):
677 # inset = self.body[k].split()[1]
678 # end = find_end_of_inset(self.body, k)
679 # if end == -1 or end > j:
680 # self.warning('Malformed file.', 0)
682 # if inset in allowed_insets:
683 # par.extend(self.body[k: end+1])
686 # par.append(self.body[k])
689 # # trim empty lines in the end.
690 # while par and par[-1].strip() == '':
693 # toc_par.append(Paragraph(section, par))
700 class File(LyX_base):
701 " This class reads existing LyX files."
703 def __init__(self, end_format = 0, input = "", output = "", error = "",
704 debug = default_debug__, try_hard = 0, cjk_encoding = '',
706 LyX_base.__init__(self, end_format, input, output, error,
707 debug, try_hard, cjk_encoding, final_version)
711 #class NewFile(LyX_base):
712 # " This class is to create new LyX files."
713 # def set_header(self, **params):
714 # # set default values
715 # self.header.extend([
716 # "#LyX xxxx created this file."
717 # "For more info see http://www.lyx.org/",
719 # "\\begin_document",
721 # "\\textclass article",
722 # "\\language english",
723 # "\\inputencoding auto",
724 # "\\font_roman default",
725 # "\\font_sans default",
726 # "\\font_typewriter default",
727 # "\\font_default_family default",
729 # "\\font_osf false",
730 # "\\font_sf_scale 100",
731 # "\\font_tt_scale 100",
732 # "\\graphics default",
733 # "\\paperfontsize default",
734 # "\\papersize default",
735 # "\\use_geometry false",
737 # "\\cite_engine basic",
738 # "\\use_bibtopic false",
739 # "\\paperorientation portrait",
742 # "\\paragraph_separation indent",
743 # "\\defskip medskip",
744 # "\\quotes_language english",
745 # "\\papercolumns 1",
747 # "\\paperpagestyle default",
748 # "\\tracking_changes false",
751 # self.format = get_end_format()
752 # for param in params:
753 # self.set_parameter(param, params[param])
756 # def set_body(self, paragraphs):
757 # self.body.extend(['\\begin_body',''])
759 # for par in paragraphs:
760 # self.body.extend(par.asLines())
762 # self.body.extend(['','\\end_body', '\\end_document'])
765 # Part of an unfinished attempt to make lyx2lyx gave a more
766 # structured view of the document.
768 # # unfinished implementation, it is missing the Text and Insets
770 # " This class represents the LyX paragraphs."
771 # def __init__(self, name, body=[], settings = [], child = []):
773 # name: paragraph name.
774 # body: list of lines of body text.
775 # child: list of paragraphs that descend from this paragraph.
779 # self.settings = settings
783 # """ Converts the paragraph to a list of strings, representing
784 # it in the LyX file."""
786 # result = ['','\\begin_layout %s' % self.name]
787 # result.extend(self.settings)
789 # result.extend(self.body)
790 # result.append('\\end_layout')
795 # result.append('\\begin_deeper')
796 # for node in self.child:
797 # result.extend(node.asLines())
798 # result.append('\\end_deeper')