]> git.lyx.org Git - lyx.git/blobdiff - lib/lyx2lyx/LyX.py
Use acadian rather than canadien
[lyx.git] / lib / lyx2lyx / LyX.py
index 306b736be530064ca39a5e82272148ff243e0dd8..3d62da5d4b786985d3ca8c8b523ac1190d4e1ead 100644 (file)
@@ -1,5 +1,6 @@
 # This file is part of lyx2lyx
 # -*- coding: utf-8 -*-
+# Copyright (C) 2002-2018 The LyX Team
 # Copyright (C) 2002-2004 Dekel Tsur <dekel@lyx.org>
 # Copyright (C) 2002-2006 José Matos <jamatos@lyx.org>
 #
 #
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 
-from parser_tools import get_value, check_token, find_token,\
-     find_tokens, find_end_of
+" The LyX module has all the rules related with different lyx file formats."
+
+from parser_tools import (get_value, check_token, find_token, find_tokens,
+                          find_end_of, find_complete_lines)
 import os.path
 import gzip
 import locale
 import sys
 import re
 import time
+import io
+import codecs
+
+try:
+    import lyx2lyx_version
+    version__ = lyx2lyx_version.version
+    stable_version = True
+except: # we are running from build directory so assume the last version
+    version__ = '2.4'
+    stable_version = False
 
-import lyx2lyx_version
-version_lyx2lyx = lyx2lyx_version.version
+default_debug__ = 2
 
-default_debug_level = 2
+# Provide support for both python 2 and 3
+PY2 = sys.version_info[0] == 2
+# End of code to support for both python 2 and 3
 
 ####################################################################
 # Private helper functions
@@ -38,13 +52,13 @@ def find_end_of_inset(lines, i):
     " Find beginning of inset, where lines[i] is included."
     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
 
-def generate_minor_versions(major, last_minor_version):
+def minor_versions(major, last_minor_version):
     """ Generate minor versions, using major as prefix and minor
     versions from 0 until last_minor_version, plus the generic version.
 
     Example:
 
-      generate_minor_versions("1.2", 4) ->
+      minor_versions("1.2", 4) ->
       [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
     """
     return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
@@ -57,25 +71,45 @@ def generate_minor_versions(major, last_minor_version):
 # Regular expressions used
 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
-original_version = re.compile(r".*?LyX ([\d.]*)")
+original_version = re.compile(b".*?LyX ([\\d.]*)")
+original_tex2lyx_version = re.compile(b".*?tex2lyx ([\\d.]*)")
 
 ##
 # file format information:
 #  file, supported formats, stable release versions
-format_relation = [("0_06",    [200], generate_minor_versions("0.6" , 4)),
-                   ("0_08",    [210], generate_minor_versions("0.8" , 6) + ["0.7"]),
-                   ("0_10",    [210], generate_minor_versions("0.10", 7) + ["0.9"]),
-                   ("0_12",    [215], generate_minor_versions("0.12", 1) + ["0.11"]),
-                   ("1_0",     [215], generate_minor_versions("1.0" , 4)),
-                   ("1_1",     [215], generate_minor_versions("1.1" , 4)),
-                   ("1_1_5",   [216], ["1.1.5","1.1.5.1","1.1.5.2","1.1"]),
-                   ("1_1_6_0", [217], ["1.1.6","1.1.6.1","1.1.6.2","1.1"]),
-                   ("1_1_6_3", [218], ["1.1.6.3","1.1.6.4","1.1"]),
-                   ("1_2",     [220], generate_minor_versions("1.2" , 4)),
-                   ("1_3",     [221], generate_minor_versions("1.3" , 7)),
-                   ("1_4", range(222,246), generate_minor_versions("1.4" , 3)),
-                   ("1_5", range(246,263), generate_minor_versions("1.5" , 0))]
+format_relation = [("0_06",    [200], minor_versions("0.6" , 4)),
+                   ("0_08",    [210], minor_versions("0.8" , 6) + ["0.7"]),
+                   ("0_10",    [210], minor_versions("0.10", 7) + ["0.9"]),
+                   ("0_12",    [215], minor_versions("0.12", 1) + ["0.11"]),
+                   ("1_0",     [215], minor_versions("1.0" , 4)),
+                   ("1_1",     [215], minor_versions("1.1" , 4)),
+                   ("1_1_5",   [216], ["1.1", "1.1.5","1.1.5.1","1.1.5.2"]),
+                   ("1_1_6_0", [217], ["1.1", "1.1.6","1.1.6.1","1.1.6.2"]),
+                   ("1_1_6_3", [218], ["1.1", "1.1.6.3","1.1.6.4"]),
+                   ("1_2",     [220], minor_versions("1.2" , 4)),
+                   ("1_3",     [221], minor_versions("1.3" , 7)),
+                   # Note that range(i,j) is up to j *excluded*.
+                   ("1_4", list(range(222,246)), minor_versions("1.4" , 5)),
+                   ("1_5", list(range(246,277)), minor_versions("1.5" , 7)),
+                   ("1_6", list(range(277,346)), minor_versions("1.6" , 10)),
+                   ("2_0", list(range(346,414)), minor_versions("2.0" , 8)),
+                   ("2_1", list(range(414,475)), minor_versions("2.1" , 5)),
+                   ("2_2", list(range(475,509)), minor_versions("2.2" , 4)),
+                   ("2_3", list(range(509,545)), minor_versions("2.3" , 0)),
+                   ("2_4", (), minor_versions("2.4" , 0))
+                  ]
 
+####################################################################
+# This is useful just for development versions                     #
+# if the list of supported formats is empty get it from last step  #
+if not format_relation[-1][1]:
+    step, mode = format_relation[-1][0], "convert"
+    convert = getattr(__import__("lyx_" + step), mode)
+    format_relation[-1] = (step,
+                           [conv[0] for conv in convert],
+                           format_relation[-1][2])
+#                                                                  #
+####################################################################
 
 def formats_list():
     " Returns a list with supported file formats."
@@ -87,29 +121,75 @@ def formats_list():
     return formats
 
 
+def format_info():
+    " Returns a list with the supported file formats."
+    template = """
+%s\tstable format:       %s
+  \tstable versions:     %s
+  \tdevelopment formats: %s
+"""
+
+    out = "version: formats and versions"
+    for version in format_relation:
+        major = str(version[2][0])
+        versions = str(version[2][1:])
+        if len(version[1]) == 1:
+            formats = str(version[1][0])
+            stable_format = str(version[1][0])
+        elif not stable_version and major == version__:
+            stable_format = "-- not yet --"
+            versions = "-- not yet --"
+            formats = "%s - %s" % (version[1][0], version[1][-1])
+        else:
+            formats = "%s - %s" % (version[1][0], version[1][-2])
+            stable_format = str(version[1][-1])
+
+        out += template % (major, stable_format, versions, formats)
+    return out + '\n'
+
+
 def get_end_format():
     " Returns the more recent file format available."
-    return format_relation[-1][1][-1]
+    # this check will fail only when we have a new version
+    # and there is no format change yet.
+    if format_relation[-1][1]:
+      return format_relation[-1][1][-1]
+    return format_relation[-2][1][-1]
 
 
 def get_backend(textclass):
     " For _textclass_ returns its backend."
     if textclass == "linuxdoc" or textclass == "manpage":
         return "linuxdoc"
-    if textclass[:7] == "docbook":
+    if textclass.startswith("docbook") or textclass.startswith("agu-"):
         return "docbook"
     return "latex"
 
 
 def trim_eol(line):
     " Remove end of line char(s)."
+    if line[-1] != '\n' and line[-1] != '\r':
+        # May happen for the last line of a document
+        return line
     if line[-2:-1] == '\r':
         return line[:-2]
     else:
         return line[:-1]
 
 
+def trim_eol_binary(line):
+    " Remove end of line char(s)."
+    if line[-1] != 10 and line[-1] != 13:
+        # May happen for the last line of a document
+        return line
+    if line[-2:-1] == 13:
+        return line[:-2]
+    else:
+        return line[:-1]
+
+
 def get_encoding(language, inputencoding, format, cjk_encoding):
+    " Returns enconding of the lyx file"
     if format > 248:
         return "utf8"
     # CJK-LyX encodes files using the current locale encoding.
@@ -118,13 +198,15 @@ def get_encoding(language, inputencoding, format, cjk_encoding):
     # argument.
     if cjk_encoding == 'auto':
         return locale.getpreferredencoding()
-    elif cjk_encoding != '':
+    elif cjk_encoding:
         return cjk_encoding
     from lyx2lyx_lang import lang
     if inputencoding == "auto" or inputencoding == "default":
         return lang[language][3]
     if inputencoding == "":
         return "latin1"
+    if inputencoding == "utf8x":
+        return "utf8"
     # python does not know the alias latin9
     if inputencoding == "latin9":
         return "iso-8859-15"
@@ -133,12 +215,13 @@ def get_encoding(language, inputencoding, format, cjk_encoding):
 ##
 # Class
 #
-class LyX_Base:
+class LyX_base:
     """This class carries all the information of the LyX file."""
-    
-    def __init__(self, end_format = 0, input = "", output = "", error
-                 = "", debug = default_debug_level, try_hard = 0, cjk_encoding = '',
-                 language = "english", encoding = "auto"):
+
+    def __init__(self, end_format = 0, input = u'', output = u'', error = u'',
+                 debug = default_debug__, try_hard = 0, cjk_encoding = u'',
+                 final_version = u'', systemlyxdir = u'', language = u'english',
+                 encoding = u'auto'):
 
         """Arguments:
         end_format: final format that the file should be converted. (integer)
@@ -147,7 +230,8 @@ class LyX_Base:
         error: the name of the error file, if empty use the standard error.
         debug: debug level, O means no debug, as its value increases be more verbose.
         """
-        self.choose_io(input, output)
+        self.choose_input(input)
+        self.output = output
 
         if error:
             self.err = open(error, "w")
@@ -160,9 +244,37 @@ class LyX_Base:
 
         if end_format:
             self.end_format = self.lyxformat(end_format)
+
+            # In case the target version and format are both specified
+            # verify that they are compatible. If not send a warning
+            # and ignore the version.
+            if final_version:
+                message = "Incompatible version %s for specified format %d" % (
+                    final_version, self.end_format)
+                for version in format_relation:
+                    if self.end_format in version[1]:
+                        if final_version not in version[2]:
+                            self.warning(message)
+                            final_version = ""
+        elif final_version:
+            for version in format_relation:
+                if final_version in version[2]:
+                    # set the last format for that version
+                    self.end_format = version[1][-1]
+                    break
+            else:
+                final_version = ""
         else:
             self.end_format = get_end_format()
 
+        if not final_version:
+            for step in format_relation:
+                if self.end_format in step[1]:
+                    final_version = step[2][1]
+        self.final_version = final_version
+        self.warning("Final version: %s" % self.final_version, 10)
+        self.warning("Final format: %d" % self.end_format, 10)
+
         self.backend = "latex"
         self.textclass = "article"
         # This is a hack: We use '' since we don't know the default
@@ -175,10 +287,12 @@ class LyX_Base:
         self.status = 0
         self.encoding = encoding
         self.language = language
+        self.systemlyxdir = systemlyxdir
 
 
-    def warning(self, message, debug_level= default_debug_level):
-        " Emits warning to self.error, if the debug_level is less than the self.debug."
+    def warning(self, message, debug_level= default_debug__):
+        """ Emits warning to self.error, if the debug_level is less
+        than the self.debug."""
         if debug_level <= self.debug:
             self.err.write("Warning: " + message + "\n")
 
@@ -187,66 +301,130 @@ class LyX_Base:
         " Emits a warning and exits if not in try_hard mode."
         self.warning(message)
         if not self.try_hard:
-            self.warning("Quiting.")
+            self.warning("Quitting.")
             sys.exit(1)
 
         self.status = 2
 
 
     def read(self):
-        """Reads a file into the self.header and self.body parts, from self.input."""
-
-        while 1:
+        """Reads a file into the self.header and
+        self.body parts, from self.input."""
+
+        # First pass: Read header to determine file encoding
+        # If we are running under python3 then all strings are binary in this
+        # pass. In some cases we need to convert binary to unicode in order to
+        # use our parser tools. Since we do not know the true encoding yet we
+        # use latin1. This works since a) the parts we are interested in are
+        # pure ASCII (subset of latin1) and b) in contrast to pure ascii or
+        # utf8, one can decode any 8byte string using latin1.
+        first_line = True
+        while True:
             line = self.input.readline()
             if not line:
-                self.error("Invalid LyX file.")
+                # eof found before end of header
+                self.error("Invalid LyX file: Missing body.")
+
+            if first_line:
+                # Remove UTF8 BOM marker if present
+                if line.startswith(codecs.BOM_UTF8):
+                    line = line[len(codecs.BOM_UTF8):]
 
-            line = trim_eol(line)
-            if check_token(line, '\\begin_preamble'):
-                while 1:
+                first_line = False
+
+            if PY2:
+                line = trim_eol(line)
+                decoded = line
+            else:
+                line = trim_eol_binary(line)
+                decoded = line.decode('latin1')
+            if check_token(decoded, '\\begin_preamble'):
+                while True:
                     line = self.input.readline()
                     if not line:
-                        self.error("Invalid LyX file.")
+                        # eof found before end of header
+                        self.error("Invalid LyX file: Missing body.")
 
-                    line = trim_eol(line)
-                    if check_token(line, '\\end_preamble'):
+                    if PY2:
+                        line = trim_eol(line)
+                        decoded = line
+                    else:
+                        line = trim_eol_binary(line)
+                        decoded = line.decode('latin1')
+                    if check_token(decoded, '\\end_preamble'):
                         break
-                    
-                    if line.split()[:0] in ("\\layout", "\\begin_layout", "\\begin_body"):
-                        self.warning("Malformed LyX file: Missing '\\end_preamble'.")
-                        self.warning("Adding it now and hoping for the best.")
+
+                    if decoded.split()[:0] in ("\\layout",
+                                            "\\begin_layout", "\\begin_body"):
+
+                        self.warning("Malformed LyX file:"
+                                     "Missing '\\end_preamble'."
+                                     "\nAdding it now and hoping"
+                                     "for the best.")
 
                     self.preamble.append(line)
 
-            if check_token(line, '\\end_preamble'):
+            if check_token(decoded, '\\end_preamble'):
                 continue
 
-            line = line.strip()
+            line = line.rstrip()
             if not line:
                 continue
 
-            if line.split()[0] in ("\\layout", "\\begin_layout", "\\begin_body"):
+            if decoded.split()[0] in ("\\layout", "\\begin_layout",
+                                   "\\begin_body", "\\begin_deeper"):
                 self.body.append(line)
                 break
 
             self.header.append(line)
 
-        self.textclass = get_value(self.header, "\\textclass", 0)
-        self.backend = get_backend(self.textclass)
-        self.format  = self.read_format()
-        self.language = get_value(self.header, "\\language", 0, default = "english")
-        self.inputencoding = get_value(self.header, "\\inputencoding", 0, default = "auto")
-        self.encoding = get_encoding(self.language, self.inputencoding, self.format, self.cjk_encoding)
+        if PY2:
+            i = find_token(self.header, '\\textclass', 0)
+        else:
+            i = find_token(self.header, b'\\textclass', 0)
+        if i == -1:
+            self.warning("Malformed LyX file: Missing '\\textclass'.")
+            if PY2:
+                i = find_token(self.header, '\\lyxformat', 0) + 1
+                self.header[i:i] = ['\\textclass article']
+            else:
+                i = find_token(self.header, b'\\lyxformat', 0) + 1
+                self.header[i:i] = [b'\\textclass article']
+
+        if PY2:
+            self.textclass = get_value(self.header, "\\textclass", 0,
+                                       default = "")
+            self.language = get_value(self.header, "\\language", 0,
+                                      default = "english")
+            self.inputencoding = get_value(self.header, "\\inputencoding", 0,
+                                           default = "auto")
+        else:
+            self.textclass = get_value(self.header, b"\\textclass", 0,
+                                       default = b"")
+            self.language = get_value(self.header, b"\\language", 0,
+                                      default = b"english").decode('ascii')
+            self.inputencoding = get_value(self.header, b"\\inputencoding", 0,
+                                           default = b"auto").decode('ascii')
+        self.format = self.read_format()
+        self.initial_format = self.format
+        self.encoding = get_encoding(self.language,
+                                     self.inputencoding, self.format,
+                                     self.cjk_encoding)
         self.initial_version = self.read_version()
 
         # Second pass over header and preamble, now we know the file encoding
+        # Do not forget the textclass (Debian bug #700828)
+        self.textclass = self.textclass.decode(self.encoding)
+        self.backend = get_backend(self.textclass)
         for i in range(len(self.header)):
             self.header[i] = self.header[i].decode(self.encoding)
         for i in range(len(self.preamble)):
             self.preamble[i] = self.preamble[i].decode(self.encoding)
+        for i in range(len(self.body)):
+            self.body[i] = self.body[i].decode(self.encoding)
 
         # Read document body
-        while 1:
+        while True:
             line = self.input.readline().decode(self.encoding)
             if not line:
                 break
@@ -255,45 +433,68 @@ class LyX_Base:
 
     def write(self):
         " Writes the LyX file to self.output."
+        self.choose_output(self.output)
         self.set_version()
         self.set_format()
+        self.set_textclass()
         if self.encoding == "auto":
-            self.encoding = get_encoding(self.language, self.encoding, self.format, self.cjk_encoding)
-
+            self.encoding = get_encoding(self.language, self.encoding,
+                                         self.format, self.cjk_encoding)
         if self.preamble:
             i = find_token(self.header, '\\textclass', 0) + 1
             preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
-            if i == 0:
-                self.error("Malformed LyX file: Missing '\\textclass'.")
-            else:
-                header = self.header[:i] + preamble + self.header[i:]
+            header = self.header[:i] + preamble + self.header[i:]
         else:
             header = self.header
 
-        for line in header + [''] + self.body:
-            self.output.write(line.encode(self.encoding)+"\n")
+        for line in header + [u''] + self.body:
+            self.output.write(line+u'\n')
 
 
-    def choose_io(self, input, output):
-        """Choose input and output streams, dealing transparently with
+    def choose_output(self, output):
+        """Choose output streams dealing transparently with
         compressed files."""
 
-        if output:
-            self.output = open(output, "wb")
+        # This is a bit complicated, because we need to be compatible both with
+        # python 2 and python 3. Therefore we handle the encoding here and not
+        # when writing individual lines and may need up to 3 layered file like
+        # interfaces.
+        if self.compressed:
+            if output:
+                outputfileobj = open(output, 'wb')
+            else:
+                # We cannot not use stdout directly since it needs text, not bytes in python 3
+                outputfileobj = os.fdopen(sys.stdout.fileno(), 'wb')
+            # We cannot not use gzip.open() since it is not supported by python 2
+            zipbuffer = gzip.GzipFile(mode='wb', fileobj=outputfileobj)
+            # We do not want to use different newlines on different OSes inside zipped files
+            self.output = io.TextIOWrapper(zipbuffer, encoding=self.encoding, newline='\n')
         else:
-            self.output = sys.stdout
+            if output:
+                self.output = io.open(output, 'w', encoding=self.encoding)
+            else:
+                self.output = io.open(sys.stdout.fileno(), 'w', encoding=self.encoding)
+
 
-        if input and input != '-':
+    def choose_input(self, input):
+        """Choose input stream, dealing transparently with
+        compressed files."""
+
+        # Since we do not know the encoding yet we need to read the input as
+        # bytes in binary mode, and convert later to unicode.
+        if input and input != u'-':
             self.dir = os.path.dirname(os.path.abspath(input))
             try:
                 gzip.open(input).readline()
                 self.input = gzip.open(input)
-                self.output = gzip.GzipFile(mode="wb", fileobj=self.output) 
+                self.compressed = True
             except:
-                self.input = open(input)
+                self.input = open(input, 'rb')
+                self.compressed = False
         else:
-            self.dir = ''
-            self.input = sys.stdin
+            self.dir = u''
+            self.input = os.fdopen(sys.stdin.fileno(), 'rb')
+            self.compressed = False
 
 
     def lyxformat(self, format):
@@ -314,31 +515,51 @@ class LyX_Base:
 
 
     def read_version(self):
-        """ Searchs for clues of the LyX version used to write the file, returns the
-        most likely value, or None otherwise."""
+        """ Searchs for clues of the LyX version used to write the
+        file, returns the most likely value, or None otherwise."""
+
         for line in self.header:
-            if line[0] != "#":
+            if line[0:1] != b"#":
                 return None
 
-            line = line.replace("fix",".")
-            result = original_version.match(line)
+            line = line.replace(b"fix",b".")
+            # need to test original_tex2lyx_version first because tex2lyx
+            # writes "#LyX file created by tex2lyx 2.2"
+            result = original_tex2lyx_version.match(line)
+            if not result:
+                result = original_version.match(line)
+                if result:
+                    # Special know cases: reLyX and KLyX
+                    if line.find(b"reLyX") != -1 or line.find(b"KLyX") != -1:
+                        return "0.12"
             if result:
-                # Special know cases: reLyX and KLyX
-                if line.find("reLyX") != -1 or line.find("KLyX") != -1:
-                    return "0.12"
-
                 res = result.group(1)
                 if not res:
                     self.warning(line)
                 #self.warning("Version %s" % result.group(1))
-                return res
+                return res.decode('ascii') if not PY2 else res
         self.warning(str(self.header[:2]))
         return None
 
 
     def set_version(self):
         " Set the header with the version used."
-        self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx
+
+        initial_comment = " ".join(["#LyX %s created this file." % version__,
+                                    "For more info see https://www.lyx.org/"])
+
+        # Simple heuristic to determine the comment that always starts
+        # a lyx file
+        if self.header[0].startswith("#"):
+            self.header[0] = initial_comment
+        else:
+            self.header.insert(0, initial_comment)
+
+        # Old lyx files had a two lines comment header:
+        # 1) the first line had the user who had created it
+        # 2) the second line had the lyx version used
+        # later we decided that 1) was a privacy risk for no gain
+        # here we remove the second line effectively erasing 1)
         if self.header[1][0] == '#':
             del self.header[1]
 
@@ -346,11 +567,14 @@ class LyX_Base:
     def read_format(self):
         " Read from the header the fileformat of the present LyX file."
         for line in self.header:
-            result = fileformat.match(line)
+            if PY2:
+                result = fileformat.match(line)
+            else:
+                result = fileformat.match(line.decode('ascii'))
             if result:
                 return self.lyxformat(result.group(1))
         else:
-            self.error("Invalid LyX File.")
+            self.error("Invalid LyX File: Missing format.")
         return None
 
 
@@ -364,6 +588,71 @@ class LyX_Base:
         self.header[i] = "\\lyxformat %s" % format
 
 
+    def set_textclass(self):
+        i = find_token(self.header, "\\textclass", 0)
+        self.header[i] = "\\textclass %s" % self.textclass
+
+
+    #Note that the module will be added at the END of the extant ones
+    def add_module(self, module):
+      " Append module to the modules list."
+      i = find_token(self.header, "\\begin_modules", 0)
+      if i == -1:
+        #No modules yet included
+        i = find_token(self.header, "\\textclass", 0)
+        if i == -1:
+          self.warning("Malformed LyX document: No \\textclass!!")
+          return
+        modinfo = ["\\begin_modules", module, "\\end_modules"]
+        self.header[i + 1: i + 1] = modinfo
+        return
+      j = find_token(self.header, "\\end_modules", i)
+      if j == -1:
+        self.warning("(add_module)Malformed LyX document: No \\end_modules.")
+        return
+      k = find_token(self.header, module, i)
+      if k != -1 and k < j:
+        return
+      self.header.insert(j, module)
+
+
+    def del_module(self, module):
+        " Delete `module` from module list, return success."
+        modlist = self.get_module_list()
+        if module not in modlist:
+            return False
+        self.set_module_list([line for line in modlist if line != module])
+        return True
+
+    def get_module_list(self):
+      " Return list of modules."
+      i = find_token(self.header, "\\begin_modules", 0)
+      if (i == -1):
+        return []
+      j = find_token(self.header, "\\end_modules", i)
+      return self.header[i + 1 : j]
+
+
+    def set_module_list(self, mlist):
+      i = find_token(self.header, "\\begin_modules", 0)
+      if (i == -1):
+        #No modules yet included
+        tclass = find_token(self.header, "\\textclass", 0)
+        if tclass == -1:
+          self.warning("Malformed LyX document: No \\textclass!!")
+          return
+        i = j = tclass + 1
+      else:
+        j = find_token(self.header, "\\end_modules", i)
+        if j == -1:
+            self.warning("(set_module_list) Malformed LyX document: No \\end_modules.")
+            return
+        j += 1
+      if mlist:
+          mlist = ['\\begin_modules'] + mlist + ['\\end_modules']
+      self.header[i:j] = mlist
+
+
     def set_parameter(self, param, value):
         " Set the value of the header parameter."
         i = find_token(self.header, '\\' + param, 0)
@@ -383,15 +672,22 @@ class LyX_Base:
 
     def convert(self):
         "Convert from current (self.format) to self.end_format."
-        mode, convertion_chain = self.chain()
-        self.warning("convertion chain: " + str(convertion_chain), 3)
+        if self.format == self.end_format:
+            self.warning("No conversion needed: Target format %s "
+                "same as current format!" % self.format, default_debug__)
+            return
+
+        mode, conversion_chain = self.chain()
+        self.warning("conversion chain: " + str(conversion_chain), 3)
 
-        for step in convertion_chain:
+        for step in conversion_chain:
             steps = getattr(__import__("lyx_" + step), mode)
 
-            self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1)
+            self.warning("Convertion step: %s - %s" % (step, mode),
+                         default_debug__ + 1)
             if not steps:
-                    self.error("The convertion to an older format (%s) is not implemented." % self.format)
+                self.error("The conversion to an older "
+                "format (%s) is not implemented." % self.format)
 
             multi_conv = len(steps) != 1
             for version, table in steps:
@@ -405,26 +701,27 @@ class LyX_Base:
                     try:
                         conv(self)
                     except:
-                        self.warning("An error ocurred in %s, %s" % (version, str(conv)),
-                                     default_debug_level)
+                        self.warning("An error ocurred in %s, %s" %
+                                     (version, str(conv)),
+                                     default_debug__)
                         if not self.try_hard:
                             raise
                         self.status = 2
                     else:
-                        self.warning("%lf: Elapsed time on %s"  % (time.time() - init_t, str(conv)),
-                                     default_debug_level + 1)
-
+                        self.warning("%lf: Elapsed time on %s" %
+                                     (time.time() - init_t,
+                                      str(conv)), default_debug__ +
+                                     1)
                 self.format = version
                 if self.end_format == self.format:
                     return
 
 
     def chain(self):
-        """ This is where all the decisions related with the convertion are taken.
-        It returns a list of modules needed to convert the LyX file from
-        self.format to self.end_format"""
+        """ This is where all the decisions related with the
+        conversion are taken.  It returns a list of modules needed to
+        convert the LyX file from self.format to self.end_format"""
 
-        self.start =  self.format
         format = self.format
         correct_version = 0
 
@@ -437,7 +734,9 @@ class LyX_Base:
 
         if not correct_version:
             if format <= 215:
-                self.warning("Version does not match file format, discarding it. (Version %s, format %d)" %(self.initial_version, self.format))
+                self.warning("Version does not match file format, "
+                             "discarding it. (Version %s, format %d)" %
+                             (self.initial_version, self.format))
             for rel in format_relation:
                 if format in rel[1]:
                     initial_step = rel[0]
@@ -456,15 +755,16 @@ class LyX_Base:
 
         # Convertion mode, back or forth
         steps = []
-        if (initial_step, self.start) < (final_step, self.end_format):
+        if (initial_step, self.initial_format) < (final_step, self.end_format):
             mode = "convert"
-            first_step = 1
+            full_steps = []
             for step in format_relation:
-                if  initial_step <= step[0] <= final_step:
-                    if first_step and len(step[1]) == 1:
-                        first_step = 0
-                        continue
-                    steps.append(step[0])
+                if  initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
+                    full_steps.append(step)
+            if full_steps[0][1][-1] == self.format:
+                full_steps = full_steps[1:]
+            for step in full_steps:
+                steps.append(step[0])
         else:
             mode = "revert"
             relation_format = format_relation[:]
@@ -479,165 +779,221 @@ class LyX_Base:
             if last_step[1][-1] == self.end_format:
                 steps.pop()
 
+        self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
         return mode, steps
 
 
-    def get_toc(self, depth = 4):
-        " Returns the TOC of this LyX document."
-        paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4}
-        allowed_insets = ['Quotes']
-        allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix", "\\leftindent"
-
-        sections = []
-        for section in paragraphs_filter.keys():
-            sections.append('\\begin_layout %s' % section)
-
-        toc_par = []
-        i = 0
-        while 1:
-            i = find_tokens(self.body, sections, i)
-            if i == -1:
-                break
-
-            j = find_end_of(self.body,  i + 1, '\\begin_layout', '\\end_layout')
-            if j == -1:
-                self.warning('Incomplete file.', 0)
-                break
-
-            section = self.body[i].split()[1]
-            if section[-1] == '*':
-                section = section[:-1]
-
-            par = []
-
-            k = i + 1
-            # skip paragraph parameters
-            while not self.body[k].strip() or self.body[k].split()[0] in allowed_parameters:
-                k = k +1
-
-            while k < j:
-                if check_token(self.body[k], '\\begin_inset'):
-                    inset = self.body[k].split()[1]
-                    end = find_end_of_inset(self.body, k)
-                    if end == -1 or end > j:
-                        self.warning('Malformed file.', 0)
-
-                    if inset in allowed_insets:
-                        par.extend(self.body[k: end+1])
-                    k = end + 1
-                else:
-                    par.append(self.body[k])
-                    k = k + 1
-
-            # trim empty lines in the end.
-            while par[-1].strip() == '' and par:
-                par.pop()
-
-            toc_par.append(Paragraph(section, par))
-
-            i = j + 1
-
-        return toc_par
+    def append_local_layout(self, new_layout):
+        " Append `new_layout` to the local layouts."
+        # new_layout may be a string or a list of strings (lines)
+        try:
+            new_layout = new_layout.splitlines()
+        except AttributeError:
+            pass
+        i = find_token(self.header, "\\begin_local_layout", 0)
+        if i == -1:
+            k = find_token(self.header, "\\language", 0)
+            if k == -1:
+                # this should not happen
+                self.warning("Malformed LyX document! No \\language header found!")
+                return
+            self.header[k : k] = ["\\begin_local_layout", "\\end_local_layout"]
+            i = k
+
+        j = find_end_of(self.header, i, "\\begin_local_layout", "\\end_local_layout")
+        if j == -1:
+            # this should not happen
+            self.warning("Malformed LyX document: Can't find end of local layout!")
+            return
 
+        self.header[i+1 : i+1] = new_layout
 
-class File(LyX_Base):
+    def del_local_layout(self, layout_def):
+        " Delete `layout_def` from local layouts, return success."
+        i = find_complete_lines(self.header, layout_def)
+        if i == -1:
+            return False
+        j = i+len(layout_def)
+        if (self.header[i-1] == "\\begin_local_layout" and
+            self.header[j] == "\\end_local_layout"):
+            i -=1
+            j +=1
+        self.header[i:j] = []
+        return True
+
+    def del_from_header(self, lines):
+        " Delete `lines` from the document header, return success."
+        i = find_complete_lines(self.header, lines)
+        if i == -1:
+            return False
+        j = i + len(lines)
+        self.header[i:j] = []
+        return True
+
+# Part of an unfinished attempt to make lyx2lyx gave a more
+# structured view of the document.
+#    def get_toc(self, depth = 4):
+#        " Returns the TOC of this LyX document."
+#        paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
+#                             'Subsection' : 3, 'Subsubsection': 4}
+#        allowed_insets = ['Quotes']
+#        allowed_parameters = ('\\paragraph_spacing', '\\noindent',
+#                              '\\align', '\\labelwidthstring',
+#                              "\\start_of_appendix", "\\leftindent")
+#        sections = []
+#        for section in paragraphs_filter.keys():
+#            sections.append('\\begin_layout %s' % section)
+
+#        toc_par = []
+#        i = 0
+#        while True:
+#            i = find_tokens(self.body, sections, i)
+#            if i == -1:
+#                break
+
+#            j = find_end_of(self.body,  i + 1, '\\begin_layout', '\\end_layout')
+#            if j == -1:
+#                self.warning('Incomplete file.', 0)
+#                break
+
+#            section = self.body[i].split()[1]
+#            if section[-1] == '*':
+#                section = section[:-1]
+
+#            par = []
+
+#            k = i + 1
+#            # skip paragraph parameters
+#            while not self.body[k].strip() or self.body[k].split()[0] \
+#                      in allowed_parameters:
+#                k += 1
+
+#            while k < j:
+#                if check_token(self.body[k], '\\begin_inset'):
+#                    inset = self.body[k].split()[1]
+#                    end = find_end_of_inset(self.body, k)
+#                    if end == -1 or end > j:
+#                        self.warning('Malformed file.', 0)
+
+#                    if inset in allowed_insets:
+#                        par.extend(self.body[k: end+1])
+#                    k = end + 1
+#                else:
+#                    par.append(self.body[k])
+#                    k += 1
+
+#            # trim empty lines in the end.
+#            while par and par[-1].strip() == '':
+#                par.pop()
+
+#            toc_par.append(Paragraph(section, par))
+
+#            i = j + 1
+
+#        return toc_par
+
+
+class File(LyX_base):
     " This class reads existing LyX files."
-    def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0, cjk_encoding = ''):
-        LyX_Base.__init__(self, end_format, input, output, error, debug, try_hard, cjk_encoding)
-        self.read()
-
-
-class NewFile(LyX_Base):
-    " This class is to create new LyX files."
-    def set_header(self, **params):
-        # set default values
-        self.header.extend([
-            "#LyX xxxx created this file. For more info see http://www.lyx.org/",
-            "\\lyxformat xxx",
-            "\\begin_document",
-            "\\begin_header",
-            "\\textclass article",
-            "\\language english",
-            "\\inputencoding auto",
-            "\\font_roman default",
-            "\\font_sans default",
-            "\\font_typewriter default",
-            "\\font_default_family default",
-            "\\font_sc false",
-            "\\font_osf false",
-            "\\font_sf_scale 100",
-            "\\font_tt_scale 100",
-            "\\graphics default",
-            "\\paperfontsize default",
-            "\\papersize default",
-            "\\use_geometry false",
-            "\\use_amsmath 1",
-            "\\cite_engine basic",
-            "\\use_bibtopic false",
-            "\\paperorientation portrait",
-            "\\secnumdepth 3",
-            "\\tocdepth 3",
-            "\\paragraph_separation indent",
-            "\\defskip medskip",
-            "\\quotes_language english",
-            "\\papercolumns 1",
-            "\\papersides 1",
-            "\\paperpagestyle default",
-            "\\tracking_changes false",
-            "\\end_header"])
-
-        self.format = get_end_format()
-        for param in params:
-            self.set_parameter(param, params[param])
-
-
-    def set_body(self, paragraphs):
-        self.body.extend(['\\begin_body',''])
-
-        for par in paragraphs:
-            self.body.extend(par.asLines())
-
-        self.body.extend(['','\\end_body', '\\end_document'])
-
-
-class Paragraph:
-    # unfinished implementation, it is missing the Text and Insets representation.
-    " This class represents the LyX paragraphs."
-    def __init__(self, name, body=[], settings = [], child = []):
-        """ Parameters:
-        name: paragraph name.
-        body: list of lines of body text.
-        child: list of paragraphs that descend from this paragraph.
-        """
-        self.name = name
-        self.body = body
-        self.settings = settings
-        self.child = child
-
-    def asLines(self):
-        " Converts the paragraph to a list of strings, representing it in the LyX file."
-        result = ['','\\begin_layout %s' % self.name]
-        result.extend(self.settings)
-        result.append('')
-        result.extend(self.body)
-        result.append('\\end_layout')
 
-        if not self.child:
-            return result
-
-        result.append('\\begin_deeper')
-        for node in self.child:
-            result.extend(node.asLines())
-        result.append('\\end_deeper')
-
-        return result
-
-
-class Inset:
-    " This class represents the LyX insets."
-    pass
+    def __init__(self, end_format = 0, input = u'', output = u'', error = u'',
+                 debug = default_debug__, try_hard = 0, cjk_encoding = u'',
+                 final_version = u'', systemlyxdir = u''):
+        LyX_base.__init__(self, end_format, input, output, error,
+                          debug, try_hard, cjk_encoding, final_version,
+                          systemlyxdir)
+        self.read()
 
 
-class Text:
-    " This class represents simple chuncks of text."
-    pass
+# FIXME: header settings are completely outdated, don't use like this
+#class NewFile(LyX_base):
+#    " This class is to create new LyX files."
+#    def set_header(self, **params):
+#        # set default values
+#        self.header.extend([
+#            "#LyX xxxx created this file."
+#            "For more info see http://www.lyx.org/",
+#            "\\lyxformat xxx",
+#            "\\begin_document",
+#            "\\begin_header",
+#            "\\textclass article",
+#            "\\language english",
+#            "\\inputencoding auto",
+#            "\\font_roman default",
+#            "\\font_sans default",
+#            "\\font_typewriter default",
+#            "\\font_default_family default",
+#            "\\font_sc false",
+#            "\\font_osf false",
+#            "\\font_sf_scale 100",
+#            "\\font_tt_scale 100",
+#            "\\graphics default",
+#            "\\paperfontsize default",
+#            "\\papersize default",
+#            "\\use_geometry false",
+#            "\\use_amsmath 1",
+#            "\\cite_engine basic",
+#            "\\use_bibtopic false",
+#            "\\use_indices false",
+#            "\\paperorientation portrait",
+#            "\\secnumdepth 3",
+#            "\\tocdepth 3",
+#            "\\paragraph_separation indent",
+#            "\\defskip medskip",
+#            "\\quotes_language english",
+#            "\\papercolumns 1",
+#            "\\papersides 1",
+#            "\\paperpagestyle default",
+#            "\\tracking_changes false",
+#            "\\end_header"])
+
+#        self.format = get_end_format()
+#        for param in params:
+#            self.set_parameter(param, params[param])
+
+
+#    def set_body(self, paragraphs):
+#        self.body.extend(['\\begin_body',''])
+
+#        for par in paragraphs:
+#            self.body.extend(par.asLines())
+
+#        self.body.extend(['','\\end_body', '\\end_document'])
+
+
+# Part of an unfinished attempt to make lyx2lyx gave a more
+# structured view of the document.
+#class Paragraph:
+#    # unfinished implementation, it is missing the Text and Insets
+#    # representation.
+#    " This class represents the LyX paragraphs."
+#    def __init__(self, name, body=[], settings = [], child = []):
+#        """ Parameters:
+#        name: paragraph name.
+#        body: list of lines of body text.
+#        child: list of paragraphs that descend from this paragraph.
+#        """
+#        self.name = name
+#        self.body = body
+#        self.settings = settings
+#        self.child = child
+
+#    def asLines(self):
+#        """ Converts the paragraph to a list of strings, representing
+#        it in the LyX file."""
+
+#        result = ['','\\begin_layout %s' % self.name]
+#        result.extend(self.settings)
+#        result.append('')
+#        result.extend(self.body)
+#        result.append('\\end_layout')
+
+#        if not self.child:
+#            return result
+
+#        result.append('\\begin_deeper')
+#        for node in self.child:
+#            result.extend(node.asLines())
+#        result.append('\\end_deeper')
+
+#        return result