]> git.lyx.org Git - lyx.git/blobdiff - lib/lyx2lyx/LyX.py
fix bug 2026 and bug 2088
[lyx.git] / lib / lyx2lyx / LyX.py
index 85f2c8339f9a7c331d47743c03fcddda798672df..187a30821322fa0edc13db30ac5aff2ac16c7eb4 100644 (file)
@@ -45,8 +45,8 @@ format_relation = [("0_10",  [210], ["0.10.7","0.10"]),
                    ("1_1_6", [217], ["1.1.6","1.1.6fix1","1.1.6fix2","1.1"]),
                    ("1_1_6fix3", [218], ["1.1.6fix3","1.1.6fix4","1.1"]),
                    ("1_2", [220], ["1.2.0","1.2.1","1.2.3","1.2.4","1.2"]),
-                   ("1_3", [221], ["1.3.0","1.3.1","1.3.2","1.3.3","1.3.4","1.3.5","1.3"]),
-                   ("1_4", range(223,242), ["1.4.0cvs","1.4"])]
+                   ("1_3", [221], ["1.3.0","1.3.1","1.3.2","1.3.3","1.3.4","1.3.5","1.3.6","1.3"]),
+                   ("1_4", range(222,246), ["1.4.0cvs","1.4"])]
 
 
 def formats_list():
@@ -73,6 +73,14 @@ def get_backend(textclass):
     return "latex"
 
 
+def trim_eol(line):
+    " Remove end of line char(s)."
+    if line[-2:-1] == '\r':
+        return line[:-2]
+    else:
+        return line[:-1]
+
+
 ##
 # Class
 #
@@ -86,14 +94,7 @@ 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.
         """
-        if input and input != '-':
-            self.input = self.open(input)
-        else:
-            self.input = sys.stdin
-        if output:
-            self.output = open(output, "w")
-        else:
-            self.output = sys.stdout
+        self.choose_io(input, output)
 
         if error:
             self.err = open(error, "w")
@@ -110,7 +111,12 @@ class LyX_Base:
 
         self.backend = "latex"
         self.textclass = "article"
+        # This is a hack: We use '' since we don't know the default
+        # layout of the text class. LyX will parse it as default layout.
+        # FIXME: Read the layout file and use the real default layout
+        self.default_layout = ''
         self.header = []
+        self.preamble = []
         self.body = []
         self.status = 0
 
@@ -133,33 +139,39 @@ class LyX_Base:
 
     def read(self):
         """Reads a file into the self.header and self.body parts, from self.input."""
-        preamble = 0
 
         while 1:
             line = self.input.readline()
             if not line:
                 self.error("Invalid LyX file.")
 
-            line = line[:-1]
-            # remove '\r' from line's end, if present
-            if line[-1:] == '\r':
-                line = line[:-1]
-
+            line = trim_eol(line)
             if check_token(line, '\\begin_preamble'):
-                preamble = 1
-            if check_token(line, '\\end_preamble'):
-                preamble = 0
+                while 1:
+                    line = self.input.readline()
+                    if not line:
+                        self.error("Invalid LyX file.")
 
-            if not preamble:
-                line = string.strip(line)
+                    line = trim_eol(line)
+                    if check_token(line, '\\end_preamble'):
+                        break
+                    
+                    if string.split(line)[: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 not preamble:
-                if not line:
-                    continue
+                    self.preamble.append(line)
 
-                if string.split(line)[0] in ("\\layout", "\\begin_layout", "\\begin_body"):
-                    self.body.append(line)
-                    break
+            if check_token(line, '\\end_preamble'):
+                continue
+
+            line = string.strip(line)
+            if not line:
+                continue
+
+            if string.split(line)[0] in ("\\layout", "\\begin_layout", "\\begin_body"):
+                self.body.append(line)
+                break
 
             self.header.append(line)
 
@@ -167,11 +179,7 @@ class LyX_Base:
             line = self.input.readline()
             if not line:
                 break
-            # remove '\r' from line's end, if present
-            if line[-2:-1] == '\r':
-                self.body.append(line[:-2])
-            else:
-                self.body.append(line[:-1])
+            self.body.append(trim_eol(line))
 
         self.textclass = get_value(self.header, "\\textclass", 0)
         self.backend = get_backend(self.textclass)
@@ -187,23 +195,39 @@ class LyX_Base:
         self.set_version()
         self.set_format()
 
-        for line in self.header:
-            self.output.write(line+"\n")
-        self.output.write("\n")
-        for line in self.body:
+        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:]
+        else:
+            header = self.header
+
+        for line in header + [''] + self.body:
             self.output.write(line+"\n")
 
 
-    def open(self, file):
-        """Transparently deals with compressed files."""
+    def choose_io(self, input, output):
+        """Choose input and output streams, dealing transparently with
+        compressed files."""
+
+        if output:
+            self.output = open(output, "wb")
+        else:
+            self.output = sys.stdout
 
-        self.dir = os.path.dirname(os.path.abspath(file))
-        try:
-            gzip.open(file).readline()
-            self.output = gzip.GzipFile("","wb",6,self.output)
-            return gzip.open(file)
-        except:
-            return open(file)
+        if input and input != '-':
+            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) 
+            except:
+                self.input = open(input)
+        else:
+            self.input = sys.stdin
 
 
     def lyxformat(self, format):
@@ -266,11 +290,19 @@ class LyX_Base:
         " Set the value of the header parameter."
         i = find_token(self.header, '\\' + param, 0)
         if i == -1:
-            self.warning(3, 'Parameter not found in the header: %s' % param)
+            self.warning('Parameter not found in the header: %s' % param, 3)
             return
         self.header[i] = '\\%s %s' % (param, str(value))
 
 
+    def is_default_layout(self, layout):
+        " Check whether a layout is the default layout of this class."
+        # FIXME: Check against the real text class default layout
+        if layout == 'Standard' or layout == self.default_layout:
+            return 1
+        return 0
+
+
     def convert(self):
         "Convert from current (self.format) to self.end_format."
         mode, convertion_chain = self.chain()
@@ -357,7 +389,7 @@ class LyX_Base:
                     steps.append(step[0])
         else:
             mode = "revert"
-            relation_format = format_relation
+            relation_format = format_relation[:]
             relation_format.reverse()
             last_step = None
 
@@ -376,7 +408,7 @@ class LyX_Base:
         " 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"
+        allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix", "\\leftindent"
 
         sections = []
         for section in paragraphs_filter.keys():
@@ -402,7 +434,7 @@ class LyX_Base:
 
             k = i + 1
             # skip paragraph parameters
-            while not string.strip(self.body[k]) and string.split(self.body[k])[0] in allowed_parameters:
+            while not string.strip(self.body[k]) or string.split(self.body[k])[0] in allowed_parameters:
                 k = k +1
 
             while k < j:
@@ -453,7 +485,6 @@ class NewFile(LyX_Base):
             "\\graphics default",
             "\\paperfontsize default",
             "\\papersize default",
-            "\\paperpackage none",
             "\\use_geometry false",
             "\\use_amsmath 1",
             "\\cite_engine basic",
@@ -464,7 +495,6 @@ class NewFile(LyX_Base):
             "\\paragraph_separation indent",
             "\\defskip medskip",
             "\\quotes_language english",
-            "\\quotes_times 2",
             "\\papercolumns 1",
             "\\papersides 1",
             "\\paperpagestyle default",