]> git.lyx.org Git - lyx.git/blobdiff - lib/lyx2lyx/lyx_2_4.py
Added Adobe Source Pro fonts to lyx-GUI
[lyx.git] / lib / lyx2lyx / lyx_2_4.py
index 2d6caabaa46597d476ba36996abd3cee826d3b76..bbc184e5bedc43c28bd7919db6c59822ea6c3def 100644 (file)
@@ -27,11 +27,12 @@ from datetime import (datetime, date, time)
 # Uncomment only what you need to import, please.
 
 from parser_tools import (count_pars_in_inset, find_end_of_inset, find_end_of_layout,
-                          find_token, find_re, get_bool_value, get_option_value, get_value, get_quoted_value)
+                          find_token, find_re, get_bool_value, get_containing_layout,
+                          get_option_value, get_value, get_quoted_value)
 #    del_token, del_value, del_complete_lines,
 #    find_complete_lines, find_end_of,
 #    find_re, find_substring, find_token_backwards,
-#    get_containing_inset, get_containing_layout,
+#    get_containing_inset,
 #    is_in_inset, set_bool_value
 #    find_tokens, find_token_exact, check_token
 
@@ -43,27 +44,162 @@ from lyx2lyx_tools import (put_cmd_in_ert, add_to_preamble)
 ####################################################################
 # Private helper functions
 
-def convert_fonts(document, font_list, font_type, scale_type):
+def add_preamble_fonts(document, fontmap):
+    " Add collected font-packages with their option to user-preamble"
+
+    for pkg in fontmap:
+        if len(fontmap[pkg]) > 0:
+            xoption = "[" + ",".join(fontmap[pkg]) + "]"
+        else:
+            xoption = ""
+        preamble = "\\usepackage" + xoption + "{%s}" % pkg
+        add_to_preamble(document, [preamble])
+
+
+def createkey(pkg, options):
+    options.sort()
+    return pkg + ':' + "-".join(options)
+
+class fontinfo:
+    def __init__(self):
+        self.fontname = None    # key into font2pkgmap
+        self.fonttype = None    # roman,sans,typewriter,math
+        self.scaletype = None   # None,sf,tt
+        self.scaleopt = None    # None, 'scaled', 'scale'
+        self.scaleval = 1
+        self.package = None
+        self.options = []
+        self.pkgkey = None      # key into pkg2fontmap
+
+    def addkey(self):
+        self.pkgkey = createkey(self.package, self.options)
+
+class fontmapping:
+    def __init__(self):
+        self.font2pkgmap = dict()
+        self.pkg2fontmap = dict()
+        self.pkginmap = dict()  # defines, if a map for package exists
+
+    def expandFontMapping(self, font_list, font_type, scale_type, pkg, scaleopt = None):
+        " Expand fontinfo mapping"
+        #
+        # fontlist:    list of fontnames, each element
+        #              may contain a ','-separated list of needed options
+        #              like e.g. 'IBMPlexSansCondensed,condensed'
+        # font_type:   one of 'roman', 'sans', 'typewriter', 'math'
+        # scale_type:  one of None, 'sf', 'tt'
+        # pkg:         package defining the font. Defaults to fontname if None
+        # scaleopt:    one of None, 'scale', 'scaled', or some other string
+        #              to be used in scale option (e.g. scaled=0.7)
+        for fl in font_list:
+            fe = fontinfo()
+            fe.fonttype = font_type
+            fe.scaletype = scale_type
+            flt = fl.split(",")
+            font_name = flt[0]
+            fe.fontname = font_name
+            fe.options = flt[1:]
+            fe.scaleopt = scaleopt
+            if pkg == None:
+                fe.package = font_name
+            else:
+                fe.package = pkg
+            fe.addkey()
+            self.font2pkgmap[font_name] = fe
+            if fe.pkgkey in self.pkg2fontmap:
+                # Repeated the same entry? Check content
+                if self.pkg2fontmap[fe.pkgkey] != font_name:
+                    document.error("Something is wrong in pkgname+options <-> fontname mapping")
+            self.pkg2fontmap[fe.pkgkey] = font_name
+            self.pkginmap[fe.package] = 1
+
+    def getfontname(self, pkg, options):
+        options.sort()
+        pkgkey = createkey(pkg, options)
+        if not pkgkey in self.pkg2fontmap:
+            return None
+        fontname = self.pkg2fontmap[pkgkey]
+        if not fontname in self.font2pkgmap:
+            document.error("Something is wrong in pkgname+options <-> fontname mapping")
+            return None
+        if pkgkey == self.font2pkgmap[fontname].pkgkey:
+            return fontname
+        return None
+
+def createFontMapping():
+    # Create info for known fonts for the use in
+    #   convert_latexFonts() and
+    #   revert_latexFonts()
+    #
+    # * Would be more handy to parse latexFonts file,
+    #   but the path to this file is unknown
+    # * For now, add DejaVu and IBMPlex only.
+    # * Expand, if desired
+    fm = fontmapping()
+    fm.expandFontMapping(['DejaVuSerif', 'DejaVuSerifCondensed'], "roman", None, None)
+    fm.expandFontMapping(['DejaVuSans','DejaVuSansCondensed'], "sans", "sf", None, "scaled")
+    fm.expandFontMapping(['DejaVuSansMono'], "typewriter", "tt", None, "scaled")
+    fm.expandFontMapping(['IBMPlexSerif', 'IBMPlexSerifThin,thin',
+                          'IBMPlexSerifExtraLight,extralight', 'IBMPlexSerifLight,light',
+                          'IBMPlexSerifSemibold,semibold'],
+                         "roman", None, "plex-serif")
+    fm.expandFontMapping(['IBMPlexSans','IBMPlexSansCondensed,condensed',
+                          'IBMPlexSansThin,thin', 'IBMPlexSansExtraLight,extralight',
+                          'IBMPlexSansLight,light', 'IBMPlexSansSemibold,semibold'],
+                         "sans", "sf", "plex-sans", "scale")
+    fm.expandFontMapping(['IBMPlexMono', 'IBMPlexMonoThin,thin',
+                          'IBMPlexMonoExtraLight,extralight', 'IBMPlexMonoLight,light',
+                          'IBMPlexMonoSemibold,semibold'],
+                         "typewriter", "tt", "plex-mono", "scale")
+    fm.expandFontMapping(['ADOBESourceSerifPro'], "roman", None, "sourceserifpro")
+    fm.expandFontMapping(['ADOBESourceSansPro'], "sans", "sf", "sourcesanspro", "scaled")
+    fm.expandFontMapping(['ADOBESourceCodePro'], "typewriter", "tt", "sourcecodepro", "scaled")
+    return fm
+
+def convert_fonts(document, fm):
     " Handle font definition to LaTeX "
 
-    rpkg = re.compile(r'^\\usepackage(\[scaled=([^\]]*)\])?\{([^\}]+)\}')
-    ft = font_type
-    if scale_type == None:
-        fontscale = None
-    else:
-        fontscale = "\\font_" + scale_type + "_scale"
+    rpkg = re.compile(r'^\\usepackage(\[([^\]]*)\])?\{([^\}]+)\}')
+    rscaleopt = re.compile(r'^scaled?=(.*)')
+
     i = 0
     while i < len(document.preamble):
         i = find_re(document.preamble, rpkg, i)
         if i == -1:
             return
         mo = rpkg.search(document.preamble[i])
-        option = mo.group(2)
+        if mo == None or mo.group(2) == None:
+            options = []
+        else:
+            options = mo.group(2).replace(' ', '').split(",")
         pkg = mo.group(3)
-        if not pkg in font_list:
+        o = 0
+        oscale = 1
+        while o < len(options):
+            mo = rscaleopt.search(options[o])
+            if mo == None:
+                o += 1
+                continue
+            oscale = mo.group(1)
+            del options[o]
+            break
+
+        if not pkg in fm.pkginmap:
+            i += 1
+            continue
+        # determine fontname
+        fn = fm.getfontname(pkg, options)
+        if fn == None:
             i += 1
             continue
         del document.preamble[i]
+        fontinfo = fm.font2pkgmap[fn]
+        if fontinfo.scaletype == None:
+            fontscale = None
+        else:
+            fontscale = "\\font_" + fontinfo.scaletype + "_scale"
+            fontinfo.scaleval = oscale
+
         if i > 0 and document.preamble[i-1] == "% Added by lyx2lyx":
             del document.preamble[i-1]
         if fontscale != None:
@@ -72,39 +208,58 @@ def convert_fonts(document, font_list, font_type, scale_type):
                 val = get_value(document.header, fontscale, j)
                 vals = val.split()
                 scale = "100"
-                if option != None:
-                    scale = "%03d" % int(float(option) * 100)
+                if oscale != None:
+                    scale = "%03d" % int(float(oscale) * 100)
                 document.header[j] = fontscale + " " + scale + " " + vals[1]
+        ft = "\\font_" + fontinfo.fonttype
         j = find_token(document.header, ft, 0)
         if j != -1:
             val = get_value(document.header, ft, j)
             vals = val.split()
-            document.header[j] = ft + ' "' + pkg + '" ' + vals[1]
+            document.header[j] = ft + ' "' + fn + '" ' + vals[1]
 
-def revert_fonts(document, font_list):
+def revert_fonts(document, fm, fontmap):
     " Revert native font definition to LaTeX "
+    # fonlist := list of fonts created from the same package
+    # Empty package means that the font-name is the same as the package-name
+    # fontmap (key = package, val += found options) will be filled
+    # and used later in add_preamble_fonts() to be added to user-preamble
 
-    if find_token(document.header, "\\use_non_tex_fonts false", 0) != -1:
-        font_types = ["\\font_roman", "\\font_sans,sf", "\\font_typewriter,tt"]
-        for ft1 in font_types:
-            fts = ft1.split(",")
-            ft = fts[0]
-            i = find_token(document.header, ft, 0)
-            if i != -1:
-                val = get_value(document.header, ft, i)
-                words = val.split()
-                val = words[0].replace('"', '')
-                if val in font_list:
-                    xoption = ""
-                    document.header[i] = ft + ' "default" ' + words[1]
-                    if len(fts) > 1:
-                        xval =  get_value(document.header, "\\font_" + fts[1] + "_scale", 0)
-                        # cutoff " 100"
-                        xval = xval[:-4]
-                        if xval != "100":
-                            xoption = "[scaled=" + format(float(xval) / 100, '.2f') + "]"
-                    preamble = "\\usepackage" + xoption + "{%s}" % val
-                    add_to_preamble(document, [preamble])
+    rfontscale = re.compile(r'^\s*(\\font_(roman|sans|typewriter|math))\s+')
+    rscales = re.compile(r'^\s*(\d+)\s+(\d+)')
+    i = 0
+    while i < len(document.header):
+        i = find_re(document.header, rfontscale, i)
+        if (i == -1):
+            break
+        mo = rfontscale.search(document.header[i])
+        if mo == None:
+            i += 1
+            continue
+        ft = mo.group(1)    # 'roman', 'sans', 'typewriter', 'math'
+        val = get_value(document.header, ft, i)
+        words = val.split()
+        font = words[0].replace('"', '')
+        if not font in fm.font2pkgmap:
+            i += 1
+            continue
+        fontinfo = fm.font2pkgmap[font]
+        val = fontinfo.package
+        if not val in fontmap:
+            fontmap[val] = []
+        document.header[i] = ft + ' "default" ' + words[1]
+        if fontinfo.scaleopt != None:
+            xval =  get_value(document.header, "\\font_" + fontinfo.scaletype + "_scale", 0)
+            mo = rscales.search(xval)
+            if mo != None:
+                xval1 = mo.group(1)
+                xval2 = mo.group(2)
+                if xval1 != "100":
+                    # set correct scale option
+                    fontmap[val].extend([fontinfo.scaleopt + "=" + format(float(xval1) / 100, '.2f')])
+        if len(fontinfo.options) > 0:
+            fontmap[val].extend(fontinfo.options)
+        i += 1
 
 ###############################################################################
 ###
@@ -112,23 +267,21 @@ def revert_fonts(document, font_list):
 ###
 ###############################################################################
 
-def convert_dejavu(document):
-    " Handle DejaVu font definition to LaTeX "
-
-    dejavu_fonts_roman = ['DejaVuSerif', 'DejaVuSerifCondensed']
-    dejavu_fonts_sans = ['DejaVuSans','DejaVuSansCondensed']
-    dejavu_fonts_typewriter = ['DejaVuSansMono']
+def convert_latexFonts(document):
+    " Handle DejaVu and IBMPlex fonts definition to LaTeX "
 
-    convert_fonts(document, dejavu_fonts_roman, "\\font_roman", None)
-    convert_fonts(document, dejavu_fonts_sans, "\\font_sans", "sf")
-    convert_fonts(document, dejavu_fonts_typewriter, "\\font_typewriter", "tt")
+    if find_token(document.header, "\\use_non_tex_fonts false", 0) != -1:
+        fm = createFontMapping()
+        convert_fonts(document, fm)
 
-def revert_dejavu(document):
+def revert_latexFonts(document):
     " Revert native DejaVu font definition to LaTeX "
 
-    dejavu_fonts = ['DejaVuSerif', 'DejaVuSerifCondensed', 'DejaVuSans',
-                    'DejaVuSansMono', 'DejaVuSansCondensed']
-    revert_fonts(document, dejavu_fonts)
+    if find_token(document.header, "\\use_non_tex_fonts false", 0) != -1:
+        fontmap = dict()
+        fm = createFontMapping()
+        revert_fonts(document, fm, fontmap)
+        add_preamble_fonts(document, fontmap)
 
 def removeFrontMatterStyles(document):
     " Remove styles Begin/EndFrontmatter"
@@ -1155,6 +1308,59 @@ def revert_l7ninfo(document):
         i = i + 1
 
 
+def revert_listpargs(document):
+    " Reverts listpreamble arguments to TeX-code "
+    i = 0
+    while True:
+        i = find_token(document.body, "\\begin_inset Argument listpreamble:", i)
+        if i == -1:
+            return
+        j = find_end_of_inset(document.body, i)
+        # Find containing paragraph layout
+        parent = get_containing_layout(document.body, i)
+        if parent == False:
+            document.warning("Malformed LyX document: Can't find parent paragraph layout")
+            i += 1
+            continue
+        parbeg = parent[3]
+        beginPlain = find_token(document.body, "\\begin_layout Plain Layout", i)
+        endPlain = find_end_of_layout(document.body, beginPlain)
+        content = document.body[beginPlain + 1 : endPlain]
+        del document.body[i:j+1]
+        subst = ["\\begin_inset ERT", "status collapsed", "", "\\begin_layout Plain Layout",
+                 "{"] + content + ["}", "\\end_layout", "", "\\end_inset", ""]
+        document.body[parbeg : parbeg] = subst
+        i += 1
+
+
+def revert_lformatinfo(document):
+    " Revert layout format Info inset to text. "
+
+    i = 0
+    while True:
+        i = find_token(document.body, "\\begin_inset Info", i)
+        if i == -1:
+            return
+        j = find_end_of_inset(document.body, i + 1)
+        if j == -1:
+            document.warning("Malformed LyX document: Could not find end of Info inset.")
+            i = i + 1
+            continue
+        tp = find_token(document.body, 'type', i, j)
+        tpv = get_quoted_value(document.body, "type", tp)
+        if tpv != "lyxinfo":
+            i = i + 1
+            continue
+        arg = find_token(document.body, 'arg', i, j)
+        argv = get_quoted_value(document.body, "arg", arg)
+        if argv != "layoutformat":
+            i = i + 1
+            continue
+        # hardcoded for now
+        document.body[i : j+1] = "69"
+        i = i + 1
+
+
 ##
 # Conversion hub
 #
@@ -1177,13 +1383,17 @@ convert = [
            [558, [removeFrontMatterStyles]],
            [559, []],
            [560, []],
-           [561, [convert_dejavu]],
-           [562, []]
+           [561, [convert_latexFonts]], # Handle dejavu, ibmplex fonts in GUI
+           [562, []],
+           [563, []],
+           [564, []]
           ]
 
 revert =  [
+           [563, [revert_lformatinfo]],
+           [562, [revert_listpargs]],
            [561, [revert_l7ninfo]],
-           [560, [revert_dejavu]],
+           [560, [revert_latexFonts]], # Handle dejavu, ibmplex fonts in user preamble
            [559, [revert_timeinfo, revert_namenoextinfo]],
            [558, [revert_dateinfo]],
            [557, [addFrontMatterStyles]],