]> git.lyx.org Git - lyx.git/blobdiff - lib/lyx2lyx/lyx_2_0.py
Fix bug #6113: Customized font color in footnote is not rendered in LyX.
[lyx.git] / lib / lyx2lyx / lyx_2_0.py
index 90f4d0e1e3f6d8c18ff79532b1eb14d50102d8f1..d668bfa745ac4dc8ecb95b6e534d539776f0f48a 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
+        
+
 ####################################################################
 
 
@@ -207,38 +259,54 @@ def revert_tabularvalign(document):
            document.warning("Malformed LyX document: Could not find end of tabular.")
            i = j
            continue
-
-       k = find_token(document.body, "<features tabularvalignment=", i)
-       if k == -1:
-           i = j
-           continue
-
-       # which valignment is specified?
-       tabularvalignment_re = re.compile(r'<features tabularvalignment="(top|bottom)">')
-       m = tabularvalignment_re.match(document.body[k])
-       if not m:
-           i = j
-           continue
-
-       tabularvalignment = m.group(1)
-
-       subst = ['\\end_layout', '\\end_inset']
-       document.body[j+1:j+1] = subst # just inserts those lines
-       subst = ['\\begin_inset Box Frameless',
-           'position "' + tabularvalignment[0] +'"',
-           'hor_pos "c"',
-           'has_inner_box 1',
-           'inner_pos "c"',
-           'use_parbox 0',
-           'width "0col%"',
-           'special "none"',
-           'height "1in"',
-           'height_special "totalheight"',
-           'status open',
-           '',
-           '\\begin_layout Plain Layout']
-       document.body[i:i] = subst # this just inserts the array at i
-       i += len(subst) + 2 # adjust i to save a few cycles
+       # don't set a box for longtables, only delete tabularvalignment
+       # the alignment is 2 lines below \\begin_inset Tabular
+       p = document.body[i+2].find("islongtable")
+       if p > -1:
+           q = document.body[i+2].find("tabularvalignment")
+           if q > -1:
+               document.body[i+2] = document.body[i+2][:q-1]
+               document.body[i+2] = document.body[i+2] + '>'
+           i = i + 1
+
+       # when no longtable
+       if p == -1:
+         tabularvalignment = 'c'
+         # which valignment is specified?
+         m = document.body[i+2].find('tabularvalignment="top"')
+         if m > -1:
+             tabularvalignment = 't'
+         m = document.body[i+2].find('tabularvalignment="bottom"')
+         if m > -1:
+             tabularvalignment = 'b'
+         # delete tabularvalignment
+         q = document.body[i+2].find("tabularvalignment")
+         if q > -1:
+             document.body[i+2] = document.body[i+2][:q-1]
+             document.body[i+2] = document.body[i+2] + '>'
+
+         # don't add a box when centered
+         if tabularvalignment == 'c':
+             i = j
+             continue
+         subst = ['\\end_layout', '\\end_inset']
+         document.body[j+1:j+1] = subst # just inserts those lines
+         subst = ['\\begin_inset Box Frameless',
+             'position "' + tabularvalignment +'"',
+             'hor_pos "c"',
+             'has_inner_box 1',
+             'inner_pos "c"',
+             'use_parbox 0',
+             # we don't know the width, assume 50%
+             'width "50col%"',
+             'special "none"',
+             'height "1in"',
+             'height_special "totalheight"',
+             'status open',
+             '',
+             '\\begin_layout Plain Layout']
+         document.body[i:i] = subst # this just inserts the array at i
+         i += len(subst) + 2 # adjust i to save a few cycles
 
 
 def revert_phantom(document):
@@ -707,6 +775,300 @@ def revert_nomencl_cwidth(document):
       i = i + 1
 
 
+def revert_applemac(document):
+    " Revert applemac encoding to auto "
+    i = 0
+    if document.encoding == "applemac":
+        document.encoding = "auto"
+        i = find_token(document.header, "\\encoding", 0)
+        if i != -1:
+            document.header[i] = "\\encoding auto"
+
+
+def revert_longtable_align(document):
+    " Remove longtable alignment setting "
+    i = 0
+    j = 0
+    while True:
+      i = find_token(document.body, "\\begin_inset Tabular", i)
+      if i == -1:
+          break
+      # the alignment is 2 lines below \\begin_inset Tabular
+      j = document.body[i+2].find("longtabularalignment")
+      if j == -1:
+          break
+      document.body[i+2] = document.body[i+2][:j-1]
+      document.body[i+2] = document.body[i+2] + '>'
+      i = i + 1
+
+
+def revert_branch_filename(document):
+    " Remove \\filename_suffix parameter from branches "
+    i = 0
+    while True:
+        i = find_token(document.header, "\\filename_suffix", i)
+        if i == -1:
+            return
+        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]
+
+
 ##
 # Conversion hub
 #
@@ -727,10 +1089,30 @@ convert = [[346, []],
            [358, []],
            [359, [convert_nomencl_width]],
            [360, []],
-           [361, []]
+           [361, []],
+           [362, []],
+           [363, []],
+           [364, []],
+           [365, []],
+           [366, []],
+           [367, []],
+           [368, []],
+           [369, [convert_author_id]],
+           [370, []],
+           [371, []]
           ]
 
-revert =  [[360, []],
+revert =  [[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, []],
            [359, [revert_nomencl_cwidth]],
            [358, [revert_nomencl_width]],
            [357, [revert_custom_processors]],