]> git.lyx.org Git - lyx.git/blobdiff - lib/lyx2lyx/lyx_2_0.py
Math.lyx: fix #6369
[lyx.git] / lib / lyx2lyx / lyx_2_0.py
index cb2461dd52f10b5267ed25bbfc611869d2b7010d..cd665bfd1db782f0738ec8ad84db2df33306de5d 100644 (file)
@@ -93,7 +93,7 @@ def put_cmd_in_ert(string):
     for rep in unicode_reps:
         string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
     string = string.replace('\\', "\\backslash\n")
-    string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Standard\n" \
+    string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
       + string + "\n\\end_layout\n\\end_inset"
     return string
 
@@ -175,6 +175,58 @@ def lyx2latex(document, lines):
     return content
 
 
+def latex_length(string):
+    'Convert lengths to their LaTeX representation.'
+    i = 0
+    percent = False
+    # the string has the form
+    # ValueUnit+ValueUnit-ValueUnit or
+    # ValueUnit+-ValueUnit
+    # the + and - (glue lengths) are optional
+    # the + always precedes the -
+
+    # Convert relative lengths to LaTeX units
+    units = {"text%":"\\textwidth", "col%":"\\columnwidth",
+             "page%":"\\pagewidth", "line%":"\\linewidth",
+             "theight%":"\\textheight", "pheight%":"\\pageheight"}
+    for unit in units.keys():
+        i = string.find(unit)
+        if i != -1:
+            percent = True
+            minus = string.rfind("-", 1, i)
+            plus = string.rfind("+", 0, i)
+            latex_unit = units[unit]
+            if plus == -1 and minus == -1:
+                value = string[:i]
+                value = str(float(value)/100)
+                end = string[i + len(unit):]
+                string = value + latex_unit + end
+            if plus > minus:
+                value = string[plus+1:i]
+                value = str(float(value)/100)
+                begin = string[:plus+1]
+                end = string[i+len(unit):]
+                string = begin + value + latex_unit + end
+            if plus < minus:
+                value = string[minus+1:i]
+                value = str(float(value)/100)
+                begin = string[:minus+1]
+                string = begin + value + latex_unit
+
+    # replace + and -, but only if the - is not the first character
+    string = string[0] + string[1:].replace("+", " plus ").replace("-", " minus ")
+    # handle the case where "+-1mm" was used, because LaTeX only understands
+    # "plus 1mm minus 1mm"
+    if string.find("plus  minus"):
+        lastvaluepos = string.rfind(" ")
+        lastvalue = string[lastvaluepos:]
+        string = string.replace("  ", lastvalue + " ")
+    if percent ==  False:
+        return "False," + string
+    else:
+        return "True," + string
+        
+
 ####################################################################
 
 
@@ -760,6 +812,325 @@ def revert_branch_filename(document):
         del document.header[i]
 
 
+def revert_paragraph_indentation(document):
+    " Revert custom paragraph indentation to preamble code "
+    i = 0
+    while True:
+      i = find_token(document.header, "\\paragraph_indentation", i)
+      if i == -1:
+          break
+      # only remove the preamble line if default
+      # otherwise also write the value to the preamble
+      length = get_value(document.header, "\\paragraph_indentation", i)
+      if length == "default":
+          del document.header[i]
+          break
+      else:
+          # handle percent lengths
+          # latex_length returns "bool,length"
+          length = latex_length(length).split(",")[1]
+          add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
+          add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
+          del document.header[i]
+      i = i + 1
+
+
+def revert_percent_skip_lengths(document):
+    " Revert relative lengths for paragraph skip separation to preamble code "
+    i = 0
+    while True:
+      i = find_token(document.header, "\\defskip", i)
+      if i == -1:
+          break
+      length = get_value(document.header, "\\defskip", i)
+      # only revert when a custom length was set and when
+      # it used a percent length
+      if length not in ('smallskip', 'medskip', 'bigskip'):
+          # handle percent lengths
+          length = latex_length(length)
+          # latex_length returns "bool,length"
+          percent = length.split(",")[0]
+          length = length.split(",")[1]
+          if percent == "True":
+              add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
+              add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
+              # set defskip to medskip as default
+              document.header[i] = "\\defskip medskip"
+      i = i + 1
+
+
+def revert_percent_vspace_lengths(document):
+    " Revert relative VSpace lengths to ERT "
+    i = 0
+    while True:
+      i = find_token(document.body, "\\begin_inset VSpace", i)
+      if i == -1:
+          break
+      # only revert if a custom length was set and if
+      # it used a percent length
+      line = document.body[i]
+      r = re.compile(r'\\begin_inset VSpace (.*)$')
+      m = r.match(line)
+      length = m.group(1)
+      if length not in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
+          # check if the space has a star (protected space)
+          protected = (document.body[i].rfind("*") != -1)
+          if protected:
+              length = length.rstrip('*')
+          # handle percent lengths
+          length = latex_length(length)
+          # latex_length returns "bool,length"
+          percent = length.split(",")[0]
+          length = length.split(",")[1]
+          # revert the VSpace inset to ERT
+          if percent == "True":
+              if protected:
+                  subst = [put_cmd_in_ert("\\vspace*{" + length + "}")]
+              else:
+                  subst = [put_cmd_in_ert("\\vspace{" + length + "}")]
+              document.body[i:i+2] = subst
+      i = i + 1
+
+
+def revert_percent_hspace_lengths(document):
+    " Revert relative HSpace lengths to ERT "
+    i = 0
+    while True:
+      i = find_token(document.body, "\\begin_inset space \\hspace", i)
+      if i == -1:
+          break
+      protected = (document.body[i].find("\\hspace*{}") != -1)
+      # only revert if a custom length was set and if
+      # it used a percent length
+      length = get_value(document.body, '\\length', i+1)
+      if length == '':
+          document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
+          return
+      # handle percent lengths
+      length = latex_length(length)
+      # latex_length returns "bool,length"
+      percent = length.split(",")[0]
+      length = length.split(",")[1]
+      # revert the HSpace inset to ERT
+      if percent == "True":
+          if protected:
+              subst = [put_cmd_in_ert("\\hspace*{" + length + "}")]
+          else:
+              subst = [put_cmd_in_ert("\\hspace{" + length + "}")]
+          document.body[i:i+3] = subst
+      i = i + 2
+
+
+def revert_hspace_glue_lengths(document):
+    " Revert HSpace glue lengths to ERT "
+    i = 0
+    while True:
+      i = find_token(document.body, "\\begin_inset space \\hspace", i)
+      if i == -1:
+          break
+      protected = (document.body[i].find("\\hspace*{}") != -1)
+      length = get_value(document.body, '\\length', i+1)
+      if length == '':
+          document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
+          return
+      # only revert if the length contains a plus or minus at pos != 0
+      glue  = re.compile(r'.+[\+-]')
+      if glue.search(length):
+          # handle percent lengths
+          # latex_length returns "bool,length"
+          length = latex_length(length).split(",")[1]
+          # revert the HSpace inset to ERT
+          if protected:
+              subst = [put_cmd_in_ert("\\hspace*{" + length + "}")]
+          else:
+              subst = [put_cmd_in_ert("\\hspace{" + length + "}")]
+          document.body[i:i+3] = subst
+      i = i + 2
+
+def convert_author_id(document):
+    " Add the author_id to the \\author definition and make sure 0 is not used"
+    i = 0
+    j = 1
+    while True:
+        i = find_token(document.header, "\\author", i)
+        if i == -1:
+            break
+        
+        r = re.compile(r'(\\author) (\".*\")\s?(.*)$')
+        m = r.match(document.header[i])
+        if m != None:
+            name = m.group(2)
+            
+            email = ''
+            if m.lastindex == 3:
+                email = m.group(3)
+            document.header[i] = "\\author %i %s %s" % (j, name, email)
+        j = j + 1
+        i = i + 1
+        
+    k = 0
+    while True:
+        k = find_token(document.body, "\\change_", k)
+        if k == -1:
+            break
+
+        change = document.body[k].split(' ');
+        if len(change) == 3:
+            type = change[0]
+            author_id = int(change[1])
+            time = change[2]
+            document.body[k] = "%s %i %s" % (type, author_id + 1, time)
+        k = k + 1
+
+def revert_author_id(document):
+    " Remove the author_id from the \\author definition "
+    i = 0
+    j = 0
+    idmap = dict()
+    while True:
+        i = find_token(document.header, "\\author", i)
+        if i == -1:
+            break
+        
+        r = re.compile(r'(\\author) (\d+) (\".*\")\s?(.*)$')
+        m = r.match(document.header[i])
+        if m != None:
+            author_id = int(m.group(2))
+            idmap[author_id] = j
+            name = m.group(3)
+            
+            email = ''
+            if m.lastindex == 4:
+                email = m.group(4)
+            document.header[i] = "\\author %s %s" % (name, email)
+        i = i + 1
+        j = j + 1
+
+    k = 0
+    while True:
+        k = find_token(document.body, "\\change_", k)
+        if k == -1:
+            break
+
+        change = document.body[k].split(' ');
+        if len(change) == 3:
+            type = change[0]
+            author_id = int(change[1])
+            time = change[2]
+            document.body[k] = "%s %i %s" % (type, idmap[author_id], time)
+        k = k + 1
+
+
+def revert_suppress_date(document):
+    " Revert suppressing of default document date to preamble code "
+    i = 0
+    while True:
+      i = find_token(document.header, "\\suppress_date", i)
+      if i == -1:
+          break
+      # remove the preamble line and write to the preamble
+      # when suppress_date was true
+      date = get_value(document.header, "\\suppress_date", i)
+      if date == "true":
+          add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
+          add_to_preamble(document, ["\\date{}"])
+      del document.header[i]
+      i = i + 1
+
+
+def revert_mhchem(document):
+    "Revert mhchem loading to preamble code"
+    i = 0
+    j = 0
+    k = 0
+    i = find_token(document.header, "\\use_mhchem 1", 0)
+    if i != -1:
+        mhchem = "auto"
+    else:
+        i = find_token(document.header, "\\use_mhchem 2", 0)
+        if i != -1:
+            mhchem = "on"
+    if mhchem == "auto":
+        j = find_token(document.body, "\\cf{", 0)
+        if j != -1:
+            mhchem = "on"
+        else:
+            j = find_token(document.body, "\\ce{", 0)
+            if j != -1:
+                mhchem = "on"
+    if mhchem == "on":
+        add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
+        add_to_preamble(document, ["\\PassOptionsToPackage{version=3}{mhchem}"])
+        add_to_preamble(document, ["\\usepackage{mhchem}"])
+    k = find_token(document.header, "\\use_mhchem", 0)
+    if k == -1:
+        document.warning("Malformed LyX document: Could not find mhchem setting.")
+        return
+    del document.header[k]
+
+
+def revert_fontenc(document):
+    " Remove fontencoding param "
+    i = find_token(document.header, '\\fontencoding', 0)
+    if i == -1:
+        document.warning("Malformed LyX document: Missing \\fontencoding.")
+        return
+    del document.header[i]
+
+
+def merge_gbrief(document):
+    " Merge g-brief-en and g-brief-de to one class "
+
+    if document.textclass != "g-brief-de":
+        if document.textclass == "g-brief-en":
+            document.textclass = "g-brief"
+            document.set_textclass()
+        return
+
+    obsoletedby = { "Brieftext":       "Letter",
+                    "Unterschrift":    "Signature",
+                    "Strasse":         "Street",
+                    "Zusatz":          "Addition",
+                    "Ort":             "Town",
+                    "Land":            "State",
+                    "RetourAdresse":   "ReturnAddress",
+                    "MeinZeichen":     "MyRef",
+                    "IhrZeichen":      "YourRef",
+                    "IhrSchreiben":    "YourMail",
+                    "Telefon":         "Phone",
+                    "BLZ":             "BankCode",
+                    "Konto":           "BankAccount",
+                    "Postvermerk":     "PostalComment",
+                    "Adresse":         "Address",
+                    "Datum":           "Date",
+                    "Betreff":         "Reference",
+                    "Anrede":          "Opening",
+                    "Anlagen":         "Encl.",
+                    "Verteiler":       "cc",
+                    "Gruss":           "Closing"}
+    i = 0
+    while 1:
+        i = find_token(document.body, "\\begin_layout", i)
+        if i == -1:
+            break
+
+        layout = document.body[i][14:]
+        if layout in obsoletedby:
+            document.body[i] = "\\begin_layout " + obsoletedby[layout]
+
+        i += 1
+        
+    document.textclass = "g-brief"
+    document.set_textclass()
+
+
+def revert_gbrief(document):
+    " Revert g-brief to g-brief-en "
+    if document.textclass == "g-brief":
+        document.textclass = "g-brief-en"
+        document.set_textclass()
+
+
 ##
 # Conversion hub
 #
@@ -783,10 +1154,28 @@ convert = [[346, []],
            [361, []],
            [362, []],
            [363, []],
-           [364, []]
+           [364, []],
+           [365, []],
+           [366, []],
+           [367, []],
+           [368, []],
+           [369, [convert_author_id]],
+           [370, []],
+           [371, []],
+           [372, []],
+           [373, [merge_gbrief]]
           ]
 
-revert =  [[363, [revert_branch_filename]],
+revert =  [[372, [revert_gbrief]],
+           [371, [revert_fontenc]],
+           [370, [revert_mhchem]],
+           [369, [revert_suppress_date]],
+           [368, [revert_author_id]],
+           [367, [revert_hspace_glue_lengths]],
+           [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
+           [365, [revert_percent_skip_lengths]],
+           [364, [revert_paragraph_indentation]],
+           [363, [revert_branch_filename]],
            [362, [revert_longtable_align]],
            [361, [revert_applemac]],
            [360, []],