from trunk
[bpt/emacs.git] / src / font.c
index ce70913..557f1fb 100644 (file)
@@ -1,6 +1,6 @@
 /* font.c -- "Font" primitives.
-   Copyright (C) 2006, 2007, 2008 Free Software Foundation, Inc.
-   Copyright (C) 2006, 2007, 2008
+   Copyright (C) 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
+   Copyright (C) 2006, 2007, 2008, 2009, 2010
      National Institute of Advanced Industrial Science and Technology (AIST)
      Registration Number H13PRO009
 
@@ -23,6 +23,7 @@ along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
 #include <stdio.h>
 #include <stdlib.h>
 #include <ctype.h>
+#include <setjmp.h>
 
 #include "lisp.h"
 #include "buffer.h"
@@ -47,8 +48,6 @@ along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
 #include "nsterm.h"
 #endif /* HAVE_NS */
 
-Lisp_Object Qfont_spec, Qfont_entity, Qfont_object;
 #ifdef HAVE_NS
 extern Lisp_Object Qfontsize;
 #endif
@@ -58,11 +57,7 @@ Lisp_Object Qopentype;
 /* Important character set strings.  */
 Lisp_Object Qascii_0, Qiso8859_1, Qiso10646_1, Qunicode_bmp, Qunicode_sip;
 
-#ifdef HAVE_NS
-#define DEFAULT_ENCODING Qiso10646_1
-#else
 #define DEFAULT_ENCODING Qiso8859_1
-#endif
 
 /* Unicode category `Cf'.  */
 static Lisp_Object QCf;
@@ -84,21 +79,20 @@ struct table_entry
   int numeric;
   /* The first one is a valid name as a face attribute.
      The second one (if any) is a typical name in XLFD field.  */
-  char *names[5];
-  Lisp_Object *symbols;
+  const char *names[5];
 };
 
 /* Table of weight numeric values and their names.  This table must be
    sorted by numeric values in ascending order.  */
 
-static struct table_entry weight_table[] =
+static const struct table_entry weight_table[] =
 {
   { 0, { "thin" }},
   { 20, { "ultra-light", "ultralight" }},
   { 40, { "extra-light", "extralight" }},
   { 50, { "light" }},
   { 75, { "semi-light", "semilight", "demilight", "book" }},
-  { 100, { "normal", "medium", "regular" }},
+  { 100, { "normal", "medium", "regular", "unspecified" }},
   { 180, { "semi-bold", "semibold", "demibold", "demi" }},
   { 200, { "bold" }},
   { 205, { "extra-bold", "extrabold" }},
@@ -108,11 +102,11 @@ static struct table_entry weight_table[] =
 /* Table of slant numeric values and their names.  This table must be
    sorted by numeric values in ascending order.  */
 
-static struct table_entry slant_table[] =
+static const struct table_entry slant_table[] =
 {
   { 0, { "reverse-oblique", "ro" }},
   { 10, { "reverse-italic", "ri" }},
-  { 100, { "normal", "r" }},
+  { 100, { "normal", "r", "unspecified" }},
   { 200, { "italic" ,"i", "ot" }},
   { 210, { "oblique", "o" }}
 };
@@ -120,13 +114,13 @@ static struct table_entry slant_table[] =
 /* Table of width numeric values and their names.  This table must be
    sorted by numeric values in ascending order.  */
 
-static struct table_entry width_table[] =
+static const struct table_entry width_table[] =
 {
   { 50, { "ultra-condensed", "ultracondensed" }},
   { 63, { "extra-condensed", "extracondensed" }},
   { 75, { "condensed", "compressed", "narrow" }},
   { 87, { "semi-condensed", "semicondensed", "demicondensed" }},
-  { 100, { "normal", "medium", "regular" }},
+  { 100, { "normal", "medium", "regular", "unspecified" }},
   { 113, { "semi-expanded", "semiexpanded", "demiexpanded" }},
   { 125, { "expanded" }},
   { 150, { "extra-expanded", "extraexpanded" }},
@@ -145,6 +139,11 @@ Lisp_Object QCspacing, QCdpi, QCscalable, QCotf, QClang, QCscript, QCavgwidth;
 Lisp_Object QCantialias, QCfont_entity, QCfc_unknown_spec;
 /* Symbols representing values of font spacing property.  */
 Lisp_Object Qc, Qm, Qp, Qd;
+/* Special ADSTYLE properties to avoid fonts used for Latin
+   characters; used in xfont.c and ftfont.c.  */
+Lisp_Object Qja, Qko;
+
+Lisp_Object QCuser_spec;
 
 Lisp_Object Vfont_encoding_alist;
 
@@ -221,7 +220,7 @@ font_make_object (size, entity, pixelsize)
        font->props[i] = AREF (entity, i);
       if (! NILP (AREF (entity, FONT_EXTRA_INDEX)))
        font->props[FONT_EXTRA_INDEX]
-         = Fcopy_sequence (AREF (entity, FONT_EXTRA_INDEX));
+         = Fcopy_alist (AREF (entity, FONT_EXTRA_INDEX));
     }
   if (size > 0)
     font->props[FONT_SIZE_INDEX] = make_number (pixelsize);
@@ -254,6 +253,7 @@ font_intern_prop (str, len, force_symbol)
   int i;
   Lisp_Object tem;
   Lisp_Object obarray;
+  int nbytes, nchars;
 
   if (len == 1 && *str == '*')
     return Qnil;
@@ -266,14 +266,25 @@ font_intern_prop (str, len, force_symbol)
        return make_number (atoi (str));
     }
 
-  /* The following code is copied from the function intern (in lread.c).  */
+  /* The following code is copied from the function intern (in
+     lread.c), and modified to suite our purpose.  */
   obarray = Vobarray;
   if (!VECTORP (obarray) || XVECTOR (obarray)->size == 0)
     obarray = check_obarray (obarray);
-  tem = oblookup (obarray, str, len, len);
+  parse_str_as_multibyte ((unsigned char *) str, len, &nchars, &nbytes);
+  if (len == nchars || len != nbytes)
+    /* CONTENTS contains no multibyte sequences or contains an invalid
+       multibyte sequence.  We'll make a unibyte string.  */
+    tem = oblookup (obarray, str, len, len);
+  else
+    tem = oblookup (obarray, str, nchars, len);
   if (SYMBOLP (tem))
     return tem;
-  return Fintern (make_unibyte_string (str, len), obarray);
+  if (len == nchars || len != nbytes)
+    tem = make_unibyte_string (str, len);
+  else
+    tem = make_multibyte_string (str, nchars, len);
+  return Fintern (tem, obarray);
 }
 
 /* Return a pixel size of font-spec SPEC on frame F.  */
@@ -350,12 +361,12 @@ font_style_to_value (prop, val, noerror)
        return -1;
       if (len == 255)
        abort ();
-      elt = Fmake_vector (make_number (2), make_number (255));
+      elt = Fmake_vector (make_number (2), make_number (100));
       ASET (elt, 1, val);
       args[0] = table;
       args[1] = Fmake_vector (make_number (1), elt);
       ASET (font_style_table, prop - FONT_WEIGHT_INDEX, Fvconcat (2, args));
-      return (255 << 8) | (i << 4);
+      return (100 << 8) | (i << 4);
     }
   else
     {
@@ -400,7 +411,7 @@ font_style_symbolic (font, prop, for_face)
   font_assert (((i >> 4) & 0xF) < ASIZE (table));
   elt = AREF (table, ((i >> 4) & 0xF));
   font_assert ((i & 0xF) + 1 < ASIZE (elt));
-  return (for_face ? AREF (elt, 1) : AREF (elt, (i & 0xF) + 1));  
+  return (for_face ? AREF (elt, 1) : AREF (elt, (i & 0xF) + 1));
 }
 
 extern Lisp_Object Vface_alternative_font_family_alist;
@@ -429,8 +440,7 @@ find_font_encoding (fontname)
              : CONSP (XCDR (elt)) && CHARSETP (XCAR (XCDR (elt)))))
        return (XCDR (elt));
     }
-  /* We don't know the encoding of this font.  Let's assume `ascii'.  */
-  return Qascii;
+  return Qnil;
 }
 
 /* Return encoding charset and repertory charset for REGISTRY in
@@ -713,13 +723,17 @@ font_put_extra (font, prop, val)
       while (CONSP (extra)
             && NILP (Fstring_lessp (prop, XCAR (XCAR (extra)))))
        prev = extra, extra = XCDR (extra);
+
       if (NILP (prev))
-       ASET (font, FONT_EXTRA_INDEX, Fcons (Fcons (prop, val), extra));
+        ASET (font, FONT_EXTRA_INDEX, Fcons (Fcons (prop, val), extra));
       else
-       XSETCDR (prev, Fcons (Fcons (prop, val), extra));
+        XSETCDR (prev, Fcons (Fcons (prop, val), extra));
+
       return val;
     }
   XSETCDR (slot, val);
+  if (NILP (val))
+    ASET (font, FONT_EXTRA_INDEX, Fdelq (slot, extra));
   return val;
 }
 
@@ -1054,11 +1068,11 @@ font_parse_xlfd (name, font)
   Lisp_Object val;
   char *p;
 
-  if (len > 255)
+  if (len > 255 || !len)
     /* Maximum XLFD name length is 255. */
     return -1;
   /* Accept "*-.." as a fully specified XLFD. */
-  if (name[0] == '*' && name[1] == '-')
+  if (name[0] == '*' && (len == 1 || name[1] == '-'))
     i = 1, f[XLFD_FOUNDRY_INDEX] = name;
   else
     i = 0;
@@ -1123,7 +1137,10 @@ font_parse_xlfd (name, font)
            }
        }
 
-      ASET (font, FONT_DPI_INDEX, INTERN_FIELD (XLFD_RESY_INDEX));
+      val = INTERN_FIELD (XLFD_RESY_INDEX);
+      if (! NILP (val) && ! INTEGERP (val))
+       return -1;
+      ASET (font, FONT_DPI_INDEX, val);
       val = INTERN_FIELD (XLFD_SPACING_INDEX);
       if (! NILP (val))
        {
@@ -1135,8 +1152,10 @@ font_parse_xlfd (name, font)
       p = f[XLFD_AVGWIDTH_INDEX];
       if (*p == '~')
        p++;
-      ASET (font, FONT_AVGWIDTH_INDEX,
-           font_intern_prop (p, f[XLFD_REGISTRY_INDEX] - 1 - p, 0));
+      val = font_intern_prop (p, f[XLFD_REGISTRY_INDEX] - 1 - p, 0);
+      if (! NILP (val) && ! INTEGERP (val))
+       return -1;
+      ASET (font, FONT_AVGWIDTH_INDEX, val);
     }
   else
     {
@@ -1335,8 +1354,8 @@ font_unparse_xlfd (font, pixel_size, name, nbytes)
   if (INTEGERP (AREF (font,  FONT_AVGWIDTH_INDEX)))
     {
       f[XLFD_AVGWIDTH_INDEX] = alloca (11);
-      len += sprintf (f[XLFD_AVGWIDTH_INDEX],
-                     "%d", XINT (AREF (font, FONT_AVGWIDTH_INDEX))) + 1;
+      len += sprintf (f[XLFD_AVGWIDTH_INDEX], "%ld",
+                      (long) XINT (AREF (font, FONT_AVGWIDTH_INDEX))) + 1;
     }
   else
     f[XLFD_AVGWIDTH_INDEX] = "*", len += 2;
@@ -1414,6 +1433,8 @@ font_parse_fcname (name, font)
 
   if (family_end)
     {
+      Lisp_Object extra_props = Qnil;
+
       /* A fontconfig name with size and/or property data.  */
       if (family_end > name)
        {
@@ -1487,13 +1508,25 @@ font_parse_fcname (name, font)
 
                  if (prop >= FONT_FOUNDRY_INDEX
                      && prop < FONT_EXTRA_INDEX)
-                   ASET (font, prop, font_prop_validate (prop, Qnil, val));
+                    ASET (font, prop, font_prop_validate (prop, Qnil, val));
                  else
-                   Ffont_put (font, key, val);
+                    {
+                      extra_props = nconc2 (extra_props,
+                                            Fcons (Fcons (key, val), Qnil));
+                    }
                }
              p = q;
            }
        }
+
+      if (! NILP (extra_props))
+        {
+          struct font_driver_list *driver_list = font_driver_list;
+          for ( ; driver_list; driver_list = driver_list->next)
+            if (driver_list->driver->filter_properties)
+              (*driver_list->driver->filter_properties) (font, extra_props);
+        }
+
     }
   else
     {
@@ -1652,7 +1685,7 @@ font_unparse_fcname (font, pixel_size, name, nbytes)
     }
 
   if (INTEGERP (AREF (font, FONT_DPI_INDEX)))
-    len += sprintf (work, ":dpi=%d", XINT (AREF (font, FONT_DPI_INDEX)));
+    len += sprintf (work, ":dpi=%ld", (long)XINT (AREF (font, FONT_DPI_INDEX)));
   if (INTEGERP (AREF (font, FONT_SPACING_INDEX)))
     len += strlen (":spacing=100");
   if (INTEGERP (AREF (font, FONT_AVGWIDTH_INDEX)))
@@ -1665,7 +1698,7 @@ font_unparse_fcname (font, pixel_size, name, nbytes)
       if (STRINGP (val))
        len += SBYTES (val);
       else if (INTEGERP (val))
-       len += sprintf (work, "%d", XINT (val));
+       len += sprintf (work, "%ld", (long) XINT (val));
       else if (SYMBOLP (val))
        len += (NILP (val) ? 5 : 4); /* for "false" or "true" */
     }
@@ -1692,9 +1725,10 @@ font_unparse_fcname (font, pixel_size, name, nbytes)
       p += sprintf (p, ":%s=%s", style_names[i],
                    SDATA (SYMBOL_NAME (styles[i])));
   if (INTEGERP (AREF (font, FONT_DPI_INDEX)))
-    p += sprintf (p, ":dpi=%d", XINT (AREF (font, FONT_DPI_INDEX)));
+    p += sprintf (p, ":dpi=%ld", (long) XINT (AREF (font, FONT_DPI_INDEX)));
   if (INTEGERP (AREF (font, FONT_SPACING_INDEX)))
-    p += sprintf (p, ":spacing=%d", XINT (AREF (font, FONT_SPACING_INDEX)));
+    p += sprintf (p, ":spacing=%ld",
+                  (long) XINT (AREF (font, FONT_SPACING_INDEX)));
   if (INTEGERP (AREF (font, FONT_AVGWIDTH_INDEX)))
     {
       if (XINT (AREF (font, FONT_AVGWIDTH_INDEX)) == 0)
@@ -1802,7 +1836,7 @@ font_parse_name (name, font)
      char *name;
      Lisp_Object font;
 {
-  if (name[0] == '-' || index (name, '*'))
+  if (name[0] == '-' || index (name, '*') || index (name, '?'))
     return font_parse_xlfd (name, font);
   return font_parse_fcname (name, font);
 }
@@ -1828,7 +1862,7 @@ font_parse_family_registry (family, registry, font_spec)
       p1 = index (p0, '-');
       if (p1)
        {
-         if ((*p0 != '*' || p1 - p0 > 1)
+         if ((*p0 != '*' && p1 - p0 > 0)
              && NILP (AREF (font_spec, FONT_FOUNDRY_INDEX)))
            Ffont_put (font_spec, QCfoundry, font_intern_prop (p0, p1 - p0, 1));
          p1++;
@@ -2162,9 +2196,41 @@ font_otf_Anchor (anchor)
 
 static unsigned font_score P_ ((Lisp_Object, Lisp_Object *));
 static int font_compare P_ ((const void *, const void *));
-static Lisp_Object font_sort_entites P_ ((Lisp_Object, Lisp_Object,
+static Lisp_Object font_sort_entities P_ ((Lisp_Object, Lisp_Object,
                                          Lisp_Object, int));
 
+/* Return a rescaling ratio of FONT_ENTITY.  */
+extern Lisp_Object Vface_font_rescale_alist;
+
+static double
+font_rescale_ratio (font_entity)
+     Lisp_Object font_entity;
+{
+  Lisp_Object tail, elt;
+  Lisp_Object name = Qnil;
+
+  for (tail = Vface_font_rescale_alist; CONSP (tail); tail = XCDR (tail))
+    {
+      elt = XCAR (tail);
+      if (FLOATP (XCDR (elt)))
+       {
+         if (STRINGP (XCAR (elt)))
+           {
+             if (NILP (name))
+               name = Ffont_xlfd_name (font_entity, Qnil);
+             if (fast_string_match_ignore_case (XCAR (elt), name) >= 0)
+               return XFLOAT_DATA (XCDR (elt));
+           }
+         else if (FONT_SPEC_P (XCAR (elt)))
+           {
+             if (font_match_p (XCAR (elt), font_entity))
+               return XFLOAT_DATA (XCDR (elt));
+           }
+       }
+    }
+  return 1.0;
+}
+
 /* We sort fonts by scoring each of them against a specified
    font-spec.  The score value is 32 bit (`unsigned'), and the smaller
    the value is, the closer the font is to the font-spec.
@@ -2205,18 +2271,26 @@ font_score (entity, spec_prop)
 
   /* Score the size.  Maximum difference is 127.  */
   i = FONT_SIZE_INDEX;
-  if (! NILP (spec_prop[i]) && XINT (AREF (entity, i)) > 0)
+  if (! NILP (spec_prop[FONT_SIZE_INDEX])
+      && XINT (AREF (entity, FONT_SIZE_INDEX)) > 0)
     {
       /* We use the higher 6-bit for the actual size difference.  The
         lowest bit is set if the DPI is different.  */
-      int diff = XINT (spec_prop[i]) - XINT (AREF (entity, i));
+      int diff;
+      int pixel_size = XINT (spec_prop[FONT_SIZE_INDEX]);
 
+      if (CONSP (Vface_font_rescale_alist))
+       pixel_size *= font_rescale_ratio (entity);
+      diff = pixel_size - XINT (AREF (entity, FONT_SIZE_INDEX));
       if (diff < 0)
        diff = - diff;
       diff <<= 1;
       if (! NILP (spec_prop[FONT_DPI_INDEX])
          && ! EQ (spec_prop[FONT_DPI_INDEX], AREF (entity, FONT_DPI_INDEX)))
        diff |= 1;
+      if (! NILP (spec_prop[FONT_AVGWIDTH_INDEX])
+         && ! EQ (spec_prop[FONT_AVGWIDTH_INDEX], AREF (entity, FONT_AVGWIDTH_INDEX)))
+       diff |= 1;
       score |= min (diff, 127) << sort_shift_bits[FONT_SIZE_INDEX];
     }
 
@@ -2224,13 +2298,19 @@ font_score (entity, spec_prop)
 }
 
 
-/* The comparison function for qsort.  */
+/* Concatenate all elements of LIST into one vector.  LIST is a list
+   of font-entity vectors.  */
 
-static int
-font_compare (d1, d2)
-     const void *d1, *d2;
+static Lisp_Object
+font_vconcat_entity_vectors (Lisp_Object list)
 {
-  return (*(unsigned *) d1 - *(unsigned *) d2);
+  int nargs = XINT (Flength (list));
+  Lisp_Object *args = alloca (sizeof (Lisp_Object) * nargs);
+  int i;
+
+  for (i = 0; i < nargs; i++, list = XCDR (list))
+    args[i] = XCAR (list);
+  return Fvconcat (nargs, args);
 }
 
 
@@ -2238,83 +2318,139 @@ font_compare (d1, d2)
 struct font_sort_data
 {
   unsigned score;
+  int font_driver_preference;
   Lisp_Object entity;
 };
 
 
-/* Sort font-entities in vector VEC by closeness to font-spec PREFER.
+/* The comparison function for qsort.  */
+
+static int
+font_compare (d1, d2)
+     const void *d1, *d2;
+{
+  const struct font_sort_data *data1 = d1;
+  const struct font_sort_data *data2 = d2;
+
+  if (data1->score < data2->score)
+    return -1;
+  else if (data1->score > data2->score)
+    return 1;
+  return (data1->font_driver_preference - data2->font_driver_preference);
+}
+
+
+/* Sort each font-entity vector in LIST by closeness to font-spec PREFER.
    If PREFER specifies a point-size, calculate the corresponding
    pixel-size from QCdpi property of PREFER or from the Y-resolution
    of FRAME before sorting.
 
-   If BEST-ONLY is nonzero, return the best matching entity.  Otherwise,
-   return the sorted VEC.  */
+   If BEST-ONLY is nonzero, return the best matching entity (that
+   supports the character BEST-ONLY if BEST-ONLY is positive, or any
+   if BEST-ONLY is negative).  Otherwise, return the sorted result as
+   a single vector of font-entities.
+
+   This function does no optimization for the case that the total
+   number of elements is 1.  The caller should avoid calling this in
+   such a case.  */
 
 static Lisp_Object
-font_sort_entites (vec, prefer, frame, best_only)
-     Lisp_Object vec, prefer, frame;
+font_sort_entities (list, prefer, frame, best_only)
+     Lisp_Object list, prefer, frame;
      int best_only;
 {
   Lisp_Object prefer_prop[FONT_SPEC_MAX];
-  int len, i;
+  int len, maxlen, i;
   struct font_sort_data *data;
   unsigned best_score;
-  Lisp_Object best_entity, driver_type;
-  int driver_order;
+  Lisp_Object best_entity;
   struct frame *f = XFRAME (frame);
-  struct font_driver_list *list;
+  Lisp_Object tail, vec;
   USE_SAFE_ALLOCA;
 
-  len = ASIZE (vec);
-  if (len <= 1)
-    return best_only ? AREF (vec, 0) : vec;
-
-  for (i = FONT_WEIGHT_INDEX; i <= FONT_DPI_INDEX; i++)
+  for (i = FONT_WEIGHT_INDEX; i <= FONT_AVGWIDTH_INDEX; i++)
     prefer_prop[i] = AREF (prefer, i);
   if (FLOATP (prefer_prop[FONT_SIZE_INDEX]))
     prefer_prop[FONT_SIZE_INDEX]
       = make_number (font_pixel_size (XFRAME (frame), prefer));
 
-  /* Scoring and sorting.  */
-  SAFE_ALLOCA (data, struct font_sort_data *, (sizeof *data) * len);
-  best_score = 0xFFFFFFFF;
-  /* We are sure that the length of VEC > 1.  */
-  driver_type = AREF (AREF (vec, 0), FONT_TYPE_INDEX);
-  for (driver_order = 0, list = f->font_driver_list; list;
-       driver_order++, list = list->next)
-    if (EQ (driver_type, list->driver->type))
-      break;
-  best_entity = data[0].entity = AREF (vec, 0);
-  best_score = data[0].score
-    = font_score (data[0].entity, prefer_prop) | driver_order;
-  for (i = 0; i < len; i++)
+  if (NILP (XCDR (list)))
     {
-      if (!EQ (driver_type, AREF (AREF (vec, i), FONT_TYPE_INDEX)))
-       for (driver_order = 0, list = f->font_driver_list; list;
-            driver_order++, list = list->next)
-         if (EQ (driver_type, list->driver->type))
-           break;
-      data[i].entity = AREF (vec, i);
-      data[i].score = font_score (data[i].entity, prefer_prop) | driver_order;
-      if (best_only && best_score > data[i].score)
-       {
-         best_score = data[i].score;
-         best_entity = data[i].entity;
-         if (best_score == 0)
-           break;
-       }
+      /* What we have to take care of is this single vector.  */
+      vec = XCAR (list);
+      maxlen = ASIZE (vec);
     }
-  if (! best_only)
+  else if (best_only)
     {
-      qsort (data, len, sizeof *data, font_compare);
-      for (i = 0; i < len; i++)
-       ASET (vec, i, data[i].entity);
+      /* We don't have to perform sort, so there's no need of creating
+        a single vector.  But, we must find the length of the longest
+        vector.  */
+      maxlen = 0;
+      for (tail = list; CONSP (tail); tail = XCDR (tail))
+       if (maxlen < ASIZE (XCAR (tail)))
+         maxlen = ASIZE (XCAR (tail));
     }
   else
-    vec = best_entity;
+    {
+      /* We have to create a single vector to sort it.  */
+      vec = font_vconcat_entity_vectors (list);
+      maxlen = ASIZE (vec);
+    }
+
+  SAFE_ALLOCA (data, struct font_sort_data *, (sizeof *data) * maxlen);
+  best_score = 0xFFFFFFFF;
+  best_entity = Qnil;
+
+  for (tail = list; CONSP (tail); tail = XCDR (tail))
+    {
+      int font_driver_preference = 0;
+      Lisp_Object current_font_driver;
+
+      if (best_only)
+       vec = XCAR (tail);
+      len = ASIZE (vec);
+
+      /* We are sure that the length of VEC > 0.  */
+      current_font_driver = AREF (AREF (vec, 0), FONT_TYPE_INDEX);
+      /* Score the elements.  */
+      for (i = 0; i < len; i++)
+       {
+         data[i].entity = AREF (vec, i);
+         data[i].score
+           = ((best_only <= 0 || font_has_char (f, data[i].entity, best_only)
+               > 0)
+              ? font_score (data[i].entity, prefer_prop)
+              : 0xFFFFFFFF);
+         if (best_only && best_score > data[i].score)
+           {
+             best_score = data[i].score;
+             best_entity = data[i].entity;
+             if (best_score == 0)
+               break;
+           }
+         if (! EQ (current_font_driver, AREF (AREF (vec, i), FONT_TYPE_INDEX)))
+           {
+             current_font_driver = AREF (AREF (vec, i), FONT_TYPE_INDEX);
+             font_driver_preference++;
+           }
+         data[i].font_driver_preference = font_driver_preference;
+       }
+
+      /* Sort if necessary.  */
+      if (! best_only)
+       {
+         qsort (data, len, sizeof *data, font_compare);
+         for (i = 0; i < len; i++)
+           ASET (vec, i, data[i].entity);
+         break;
+       }
+      else
+       vec = best_entity;
+    }
+
   SAFE_FREE ();
 
-  font_add_log ("sort-by", prefer, vec);
+  FONT_ADD_LOG ("sort-by", prefer, vec);
   return vec;
 }
 
@@ -2375,7 +2511,10 @@ font_check_otf_features (script, langsys, features, table)
   for (negative = 0; CONSP (features); features = XCDR (features))
     {
       if (NILP (XCAR (features)))
-       negative = 1;
+       {
+         negative = 1;
+         continue;
+       }
       if (NILP (Fmemq (XCAR (features), table)) != negative)
        return 0;
     }
@@ -2614,21 +2753,21 @@ font_clear_cache (f, cache, driver)
      struct font_driver *driver;
 {
   Lisp_Object tail, elt;
+  Lisp_Object tail2, entity;
 
   /* CACHE = (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...) */
   for (tail = XCDR (XCDR (cache)); CONSP (tail); tail = XCDR (tail))
     {
       elt = XCAR (tail);
-      if (CONSP (elt) && FONT_SPEC_P (XCAR (elt)) && VECTORP (XCDR (elt)))
+      /* elt should have the form (FONT-SPEC FONT-ENTITY ...) */
+      if (CONSP (elt) && FONT_SPEC_P (XCAR (elt)))
        {
-         Lisp_Object vec = XCDR (elt);
-         int i;
-
-         for (i = 0; i < ASIZE (vec); i++)
+         for (tail2 = XCDR (elt); CONSP (tail2); tail2 = XCDR (tail2))
            {
-             Lisp_Object entity = AREF (vec, i);
+             entity = XCAR (tail2);
 
-             if (EQ (driver->type, AREF (entity, FONT_TYPE_INDEX)))
+             if (FONT_ENTITY_P (entity)
+                 && EQ (driver->type, AREF (entity, FONT_TYPE_INDEX)))
                {
                  Lisp_Object objlist = AREF (entity, FONT_OBJLIST_INDEX);
 
@@ -2657,16 +2796,17 @@ font_clear_cache (f, cache, driver)
 static Lisp_Object scratch_font_spec, scratch_font_prefer;
 
 Lisp_Object
-font_delete_unmatched (list, spec, size)
-     Lisp_Object list, spec;
+font_delete_unmatched (vec, spec, size)
+     Lisp_Object vec, spec;
      int size;
 {
   Lisp_Object entity, val;
   enum font_property_index prop;
+  int i;
 
-  for (val = Qnil; CONSP (list); list = XCDR (list))
+  for (val = Qnil, i = ASIZE (vec) - 1; i >= 0; i--)
     {
-      entity = XCAR (list);
+      entity = AREF (vec, i);
       for (prop = FONT_WEIGHT_INDEX; prop < FONT_SIZE_INDEX; prop++)
        if (INTEGERP (AREF (spec, prop))
            && ((XINT (AREF (spec, prop)) >> 8)
@@ -2699,11 +2839,13 @@ font_delete_unmatched (list, spec, size)
       if (prop < FONT_SPEC_MAX)
        val = Fcons (entity, val);
     }
-  return val;
+  return (Fvconcat (1, &val));
 }
 
 
-/* Return a vector of font-entities matching with SPEC on FRAME.  */
+/* Return a list of vectors of font-entities matching with SPEC on
+   FRAME.  Each elements in the list is a vector of entities from the
+   same font-driver.  */
 
 Lisp_Object
 font_list_entities (frame, spec)
@@ -2712,7 +2854,7 @@ font_list_entities (frame, spec)
   FRAME_PTR f = XFRAME (frame);
   struct font_driver_list *driver_list = f->font_driver_list;
   Lisp_Object ftype, val;
-  Lisp_Object *vec;
+  Lisp_Object list = Qnil;
   int size;
   int need_filtering = 0;
   int i;
@@ -2741,10 +2883,6 @@ font_list_entities (frame, spec)
   ASET (scratch_font_spec, FONT_SPACING_INDEX, AREF (spec, FONT_SPACING_INDEX));
   ASET (scratch_font_spec, FONT_EXTRA_INDEX, AREF (spec, FONT_EXTRA_INDEX));
 
-  vec = alloca (sizeof (Lisp_Object) * num_font_drivers);
-  if (! vec)
-    return null_vector;
-
   for (i = 0; driver_list; driver_list = driver_list->next)
     if (driver_list->on
        && (NILP (ftype) || EQ (driver_list->driver->type, ftype)))
@@ -2760,19 +2898,23 @@ font_list_entities (frame, spec)
            Lisp_Object copy;
 
            val = driver_list->driver->list (frame, scratch_font_spec);
+           if (NILP (val))
+             val = null_vector;
+           else
+             val = Fvconcat (1, &val);
            copy = Fcopy_font_spec (scratch_font_spec);
            ASET (copy, FONT_TYPE_INDEX, driver_list->driver->type);
            XSETCDR (cache, Fcons (Fcons (copy, val), XCDR (cache)));
          }
-       if (! NILP (val) && need_filtering)
+       if (ASIZE (val) > 0 && need_filtering)
          val = font_delete_unmatched (val, spec, size);
-       if (! NILP (val))
-         vec[i++] = val;
+       if (ASIZE (val) > 0)
+         list = Fcons (val, list);
       }
 
-  val = (i > 0 ? Fvconcat (i, vec) : null_vector);
-  font_add_log ("list", spec, val);
-  return (val);
+  list = Fnreverse (list);
+  FONT_ADD_LOG ("list", spec, list);
+  return list;
 }
 
 
@@ -2822,7 +2964,7 @@ font_matching_entity (f, attrs, spec)
        if (! NILP (entity))
          break;
       }
-  font_add_log ("match", work, entity);
+  FONT_ADD_LOG ("match", work, entity);
   return entity;
 }
 
@@ -2840,17 +2982,14 @@ font_open_entity (f, entity, pixel_size)
   Lisp_Object objlist, size, val, font_object;
   struct font *font;
   int min_width, height;
+  int scaled_pixel_size;
 
   font_assert (FONT_ENTITY_P (entity));
   size = AREF (entity, FONT_SIZE_INDEX);
   if (XINT (size) != 0)
-    pixel_size = XINT (size);
-
-  for (objlist = AREF (entity, FONT_OBJLIST_INDEX); CONSP (objlist);
-       objlist = XCDR (objlist))
-    if (! NILP (AREF (XCAR (objlist), FONT_TYPE_INDEX))
-       && XFONT_OBJECT (XCAR (objlist))->pixel_size == pixel_size)
-      return  XCAR (objlist);
+    scaled_pixel_size = pixel_size = XINT (size);
+  else if (CONSP (Vface_font_rescale_alist))
+    scaled_pixel_size = pixel_size * font_rescale_ratio (entity);
 
   val = AREF (entity, FONT_TYPE_INDEX);
   for (driver_list = f->font_driver_list;
@@ -2859,8 +2998,23 @@ font_open_entity (f, entity, pixel_size)
   if (! driver_list)
     return Qnil;
 
-  font_object = driver_list->driver->open (f, entity, pixel_size);
-  font_add_log ("open", entity, font_object);
+  for (objlist = AREF (entity, FONT_OBJLIST_INDEX); CONSP (objlist);
+       objlist = XCDR (objlist))
+    {
+      Lisp_Object fn = XCAR (objlist);
+      if (! NILP (AREF (fn, FONT_TYPE_INDEX))
+          && XFONT_OBJECT (fn)->pixel_size == pixel_size)
+        {
+          if (driver_list->driver->cached_font_ok == NULL
+              || driver_list->driver->cached_font_ok (f, fn, entity))
+            return fn;
+        }
+    }
+
+  font_object = driver_list->driver->open (f, entity, scaled_pixel_size);
+  if (!NILP (font_object))
+    ASET (font_object, FONT_SIZE_INDEX, make_number (pixel_size));
+  FONT_ADD_LOG ("open", entity, font_object);
   if (NILP (font_object))
     return Qnil;
   ASET (entity, FONT_OBJLIST_INDEX,
@@ -2907,7 +3061,7 @@ font_close_object (f, font_object)
   if (NILP (AREF (font_object, FONT_TYPE_INDEX)))
     /* Already closed.  */
     return;
-  font_add_log ("close", font_object, Qnil);
+  FONT_ADD_LOG ("close", font_object, Qnil);
   font->driver->close (f, font);
 #ifdef HAVE_WINDOW_SYSTEM
   font_assert (FRAME_X_DISPLAY_INFO (f)->n_fonts);
@@ -2998,15 +3152,22 @@ font_get_spec (font_object)
   return spec;
 }
 
+
+/* Create a new font spec from FONT_NAME, and return it.  If FONT_NAME
+   could not be parsed by font_parse_name, return Qnil.  */
+
 Lisp_Object
 font_spec_from_name (font_name)
      Lisp_Object font_name;
 {
-  Lisp_Object args[2];
+  Lisp_Object spec = Ffont_spec (0, NULL);
 
-  args[0] = QCname;
-  args[1] = font_name;
-  return Ffont_spec (2, args);
+  CHECK_STRING (font_name);
+  if (font_parse_name ((char *) SDATA (font_name), spec) == -1)
+    return Qnil;
+  font_put_extra (spec, QCname, font_name);
+  font_put_extra (spec, QCuser_spec, font_name);
+  return spec;
 }
 
 
@@ -3019,18 +3180,32 @@ font_clear_prop (attrs, prop)
 
   if (! FONTP (font))
     return;
+
+  if (! NILP (Ffont_get (font, QCname)))
+    {
+      font = Fcopy_font_spec (font);
+      font_put_extra (font, QCname, Qnil);
+    }
+
   if (NILP (AREF (font, prop))
       && prop != FONT_FAMILY_INDEX
       && prop != FONT_FOUNDRY_INDEX
       && prop != FONT_WIDTH_INDEX
       && prop != FONT_SIZE_INDEX)
     return;
-  font = Fcopy_font_spec (font);
+  if (EQ (font, attrs[LFACE_FONT_INDEX]))
+    font = Fcopy_font_spec (font);
   ASET (font, prop, Qnil);
   if (prop == FONT_FAMILY_INDEX || prop == FONT_FOUNDRY_INDEX)
     {
       if (prop == FONT_FAMILY_INDEX)
-       ASET (font, FONT_FOUNDRY_INDEX, Qnil);
+       {
+         ASET (font, FONT_FOUNDRY_INDEX, Qnil);
+         /* If we are setting the font family, we must also clear
+            FONT_WIDTH_INDEX to avoid rejecting families that lack
+            support for some widths.  */
+         ASET (font, FONT_WIDTH_INDEX, Qnil);
+       }
       ASET (font, FONT_ADSTYLE_INDEX, Qnil);
       ASET (font, FONT_REGISTRY_INDEX, Qnil);
       ASET (font, FONT_SIZE_INDEX, Qnil);
@@ -3067,7 +3242,7 @@ font_update_lface (f, attrs)
   if (! NILP (AREF (spec, FONT_WEIGHT_INDEX)))
     attrs[LFACE_WEIGHT_INDEX] = FONT_WEIGHT_FOR_FACE (spec);
   if (! NILP (AREF (spec, FONT_SLANT_INDEX)))
-    attrs[LFACE_SLANT_INDEX] = FONT_SLANT_FOR_FACE (spec);;
+    attrs[LFACE_SLANT_INDEX] = FONT_SLANT_FOR_FACE (spec);
   if (! NILP (AREF (spec, FONT_WIDTH_INDEX)))
     attrs[LFACE_SWIDTH_INDEX] = FONT_WIDTH_FOR_FACE (spec);
   if (! NILP (AREF (spec, FONT_SIZE_INDEX)))
@@ -3084,14 +3259,63 @@ font_update_lface (f, attrs)
            dpi = XINT (val);
          point = PIXEL_TO_POINT (XINT (AREF (spec, FONT_SIZE_INDEX)) * 10,
                                  dpi);
+         attrs[LFACE_HEIGHT_INDEX] = make_number (point);
        }
       else if (FLOATP (AREF (spec, FONT_SIZE_INDEX)))
-       point = XFLOAT_DATA (AREF (spec, FONT_SIZE_INDEX)) * 10;
-      attrs[LFACE_HEIGHT_INDEX] = make_number (point);
+       {
+         point = XFLOAT_DATA (AREF (spec, FONT_SIZE_INDEX)) * 10;
+         attrs[LFACE_HEIGHT_INDEX] = make_number (point);
+       }
     }
 }
 
 
+/* Selecte a font from ENTITIES (list of font-entity vectors) that
+   supports C and matches best with ATTRS and PIXEL_SIZE.  */
+
+static Lisp_Object
+font_select_entity (frame, entities, attrs, pixel_size, c)
+     Lisp_Object frame, entities, *attrs;
+     int pixel_size, c;
+{
+  Lisp_Object font_entity;
+  Lisp_Object prefer;
+  int result, i;
+  FRAME_PTR f = XFRAME (frame);
+
+  if (NILP (XCDR (entities))
+      && ASIZE (XCAR (entities)) == 1)
+    {
+      font_entity = AREF (XCAR (entities), 0);
+      if (c < 0
+         || (result = font_has_char (f, font_entity, c)) > 0)
+       return font_entity;
+      return Qnil;
+    }
+
+  /* Sort fonts by properties specified in ATTRS.  */
+  prefer = scratch_font_prefer;
+
+  for (i = FONT_WEIGHT_INDEX; i <= FONT_SIZE_INDEX; i++)
+    ASET (prefer, i, Qnil);
+  if (FONTP (attrs[LFACE_FONT_INDEX]))
+    {
+      Lisp_Object face_font = attrs[LFACE_FONT_INDEX];
+
+      for (i = FONT_WEIGHT_INDEX; i <= FONT_SIZE_INDEX; i++)
+       ASET (prefer, i, AREF (face_font, i));
+    }
+  if (NILP (AREF (prefer, FONT_WEIGHT_INDEX)))
+    FONT_SET_STYLE (prefer, FONT_WEIGHT_INDEX, attrs[LFACE_WEIGHT_INDEX]);
+  if (NILP (AREF (prefer, FONT_SLANT_INDEX)))
+    FONT_SET_STYLE (prefer, FONT_SLANT_INDEX, attrs[LFACE_SLANT_INDEX]);
+  if (NILP (AREF (prefer, FONT_WIDTH_INDEX)))
+    FONT_SET_STYLE (prefer, FONT_WIDTH_INDEX, attrs[LFACE_SWIDTH_INDEX]);
+  ASET (prefer, FONT_SIZE_INDEX, make_number (pixel_size));
+
+  return font_sort_entities (entities, prefer, frame, c);
+}
+
 /* Return a font-entity satisfying SPEC and best matching with face's
    font related attributes in ATTRS.  C, if not negative, is a
    character that the entity must support.  */
@@ -3104,10 +3328,10 @@ font_find_for_lface (f, attrs, spec, c)
      int c;
 {
   Lisp_Object work;
-  Lisp_Object frame, entities, val, props[FONT_REGISTRY_INDEX + 1] ;
+  Lisp_Object frame, entities, val;
   Lisp_Object size, foundry[3], *family, registry[3], adstyle[3];
   int pixel_size;
-  int i, j, k, l, result;
+  int i, j, k, l;
 
   registry[0] = AREF (spec, FONT_REGISTRY_INDEX);
   if (NILP (registry[0]))
@@ -3126,19 +3350,15 @@ font_find_for_lface (f, attrs, spec, c)
       if (font_registry_charsets (AREF (spec, FONT_REGISTRY_INDEX),
                                  &encoding, &repertory) < 0)
        return Qnil;
-      if (repertory)
-       {
-         if (ENCODE_CHAR (repertory, c) == CHARSET_INVALID_CODE (repertory))
-           return Qnil;
-         /* Any font of this registry support C.  So, let's
-            suppress the further checking.  */
-         c = -1;
-       }
+      if (repertory
+         && ENCODE_CHAR (repertory, c) == CHARSET_INVALID_CODE (repertory))
+       return Qnil;
       else if (c > encoding->max_char)
        return Qnil;
     }
 
   work = Fcopy_font_spec (spec);
+  ASET (work, FONT_TYPE_INDEX, AREF (spec, FONT_TYPE_INDEX));
   XSETFRAME (frame, f);
   size = AREF (spec, FONT_SIZE_INDEX);
   pixel_size = font_pixel_size (f, spec);
@@ -3198,6 +3418,7 @@ font_find_for_lface (f, attrs, spec, c)
     {
       Lisp_Object alters
        = Fassoc_string (val, Vface_alternative_font_family_alist,
+                         /* Font family names are case-sensitive under NS. */
 #ifndef HAVE_NS
                         Qt
 #else
@@ -3238,75 +3459,18 @@ font_find_for_lface (f, attrs, spec, c)
                {
                  ASET (work, FONT_ADSTYLE_INDEX, adstyle[l]);
                  entities = font_list_entities (frame, work);
-                 if (ASIZE (entities) > 0)
-                   goto found;
+                 if (! NILP (entities))
+                   {
+                     val = font_select_entity (frame, entities,
+                                               attrs, pixel_size, c);
+                     if (! NILP (val))
+                        return val;
+                   }
                }
            }
        }
     }
   return Qnil;
- found:
-  if (ASIZE (entities) == 1)
-    {
-      if (c < 0)
-       return AREF (entities, 0);
-    }
-  else
-    {
-      /* Sort fonts by properties specified in LFACE.  */
-      Lisp_Object prefer = scratch_font_prefer;
-
-      for (i = 0; i < FONT_EXTRA_INDEX; i++)
-       ASET (prefer, i, AREF (work, i));
-      if (FONTP (attrs[LFACE_FONT_INDEX]))
-       {
-         Lisp_Object face_font = attrs[LFACE_FONT_INDEX];
-
-         for (i = 0; i < FONT_EXTRA_INDEX; i++)
-           if (NILP (AREF (prefer, i)))
-             ASET (prefer, i, AREF (face_font, i));
-       }
-      if (NILP (AREF (prefer, FONT_WEIGHT_INDEX)))
-       FONT_SET_STYLE (prefer, FONT_WEIGHT_INDEX, attrs[LFACE_WEIGHT_INDEX]);
-      if (NILP (AREF (prefer, FONT_SLANT_INDEX)))
-       FONT_SET_STYLE (prefer, FONT_SLANT_INDEX, attrs[LFACE_SLANT_INDEX]);
-      if (NILP (AREF (prefer, FONT_WIDTH_INDEX)))
-       FONT_SET_STYLE (prefer, FONT_WIDTH_INDEX, attrs[LFACE_SWIDTH_INDEX]);
-      ASET (prefer, FONT_SIZE_INDEX, make_number (pixel_size));
-      entities = font_sort_entites (entities, prefer, frame, c < 0);
-    }
-  if (c < 0)
-    return entities;
-
-  for (i = 0; i < ASIZE (entities); i++)
-    {
-      int j;
-
-      val = AREF (entities, i);
-      if (i > 0)
-       {
-         for (j = FONT_FOUNDRY_INDEX; j <= FONT_REGISTRY_INDEX; j++)
-           if (! EQ (AREF (val, j), props[j]))
-             break;
-         if (j > FONT_REGISTRY_INDEX)
-           continue;
-       }
-      for (j = FONT_FOUNDRY_INDEX; j <= FONT_REGISTRY_INDEX; j++)
-       props[j] = AREF (val, j);
-      result = font_has_char (f, val, c);
-      if (result > 0)
-       return val;
-      if (result == 0)
-       return Qnil;
-      val = font_open_for_lface (f, val, attrs, spec);
-      if (NILP (val))
-       continue;
-      result = font_has_char (f, val, c);
-      font_close_object (f, val);
-      if (result > 0)
-       return AREF (entities, i);
-    }
-  return Qnil;
 }
 
 
@@ -3326,7 +3490,18 @@ font_open_for_lface (f, entity, attrs, spec)
     size = font_pixel_size (f, spec);
   else
     {
-      double pt = XINT (attrs[LFACE_HEIGHT_INDEX]);
+      double pt;
+      if (INTEGERP (attrs[LFACE_HEIGHT_INDEX]))
+       pt = XINT (attrs[LFACE_HEIGHT_INDEX]);
+      else
+       {
+         struct face *def = FACE_FROM_ID (f, DEFAULT_FACE_ID);
+         Lisp_Object height = def->lface[LFACE_HEIGHT_INDEX];
+         if (INTEGERP (height))
+           pt = XINT (height);
+         else
+           abort(); /* We should never end up here.  */
+       }
 
       pt /= 10;
       size = POINT_TO_PIXEL (pt, f->resy);
@@ -3351,7 +3526,7 @@ font_load_for_lface (f, attrs, spec)
      FRAME_PTR f;
      Lisp_Object *attrs, spec;
 {
-  Lisp_Object entity;
+  Lisp_Object entity, name;
 
   entity = font_find_for_lface (f, attrs, spec, -1);
   if (NILP (entity))
@@ -3363,7 +3538,16 @@ font_load_for_lface (f, attrs, spec)
       if (NILP (entity))
        return Qnil;
     }
-  return font_open_for_lface (f, entity, attrs, spec);
+  /* Don't loose the original name that was put in initially.  We need
+     it to re-apply the font when font parameters (like hinting or dpi) have
+     changed.  */
+  entity = font_open_for_lface (f, entity, attrs, spec);
+  if (!NILP (entity))
+    {
+      name = Ffont_get (spec, QCuser_spec);
+      if (STRINGP (name)) font_put_extra (entity, QCuser_spec, name);
+    }
+  return entity;
 }
 
 
@@ -3392,20 +3576,16 @@ font_done_for_face (f, face)
 }
 
 
-/* Open a font best matching with NAME on frame F.  If no proper font
-   is found, return Qnil.  */
+/* Open a font matching with font-spec SPEC on frame F.  If no proper
+   font is found, return Qnil.  */
 
 Lisp_Object
-font_open_by_name (f, name)
+font_open_by_spec (f, spec)
      FRAME_PTR f;
-     char *name;
+     Lisp_Object spec;
 {
-  Lisp_Object args[2];
-  Lisp_Object spec, attrs[LFACE_VECTOR_SIZE];
+  Lisp_Object attrs[LFACE_VECTOR_SIZE];
 
-  args[0] = QCname;
-  args[1] = make_unibyte_string (name, strlen (name));
-  spec = Ffont_spec (2, args);
   /* We set up the default font-related attributes of a face to prefer
      a moderate font.  */
   attrs[LFACE_FAMILY_INDEX] = attrs[LFACE_FOUNDRY_INDEX] = Qnil;
@@ -3422,6 +3602,29 @@ font_open_by_name (f, name)
 }
 
 
+/* Open a font matching with NAME on frame F.  If no proper font is
+   found, return Qnil.  */
+
+Lisp_Object
+font_open_by_name (f, name)
+     FRAME_PTR f;
+     char *name;
+{
+  Lisp_Object args[2];
+  Lisp_Object spec, ret;
+
+  args[0] = QCname;
+  args[1] = make_unibyte_string (name, strlen (name));
+  spec = Ffont_spec (2, args);
+  ret = font_open_by_spec (f, spec);
+  /* Do not loose name originally put in.  */
+  if (!NILP (ret))
+    font_put_extra (ret, QCuser_spec, args[1]);
+
+  return ret;
+}
+
+
 /* Register font-driver DRIVER.  This function is used in two ways.
 
    The first is with frame F non-NULL.  In this case, make DRIVER
@@ -3464,6 +3667,20 @@ register_font_driver (driver, f)
     num_font_drivers++;
 }
 
+void
+free_font_driver_list (f)
+     FRAME_PTR f;
+{
+  struct font_driver_list *list, *next;
+
+  for (list = f->font_driver_list; list; list = next)
+    {
+      next = list->next;
+      xfree (list);
+    }
+  f->font_driver_list = NULL;
+}
+
 
 /* Make the frame F use font backends listed in NEW_DRIVERS (list of
    symbols, e.g. xft, x).  If NEW_DRIVERS is t, make F use all
@@ -3530,7 +3747,7 @@ font_update_drivers (f, new_drivers)
        }
       for (list = f->font_driver_list; list; list = list->next)
        if (! list->on)
-         list_table[i] = list;
+         list_table[i++] = list;
       list_table[i] = NULL;
 
       next = &f->font_driver_list;
@@ -3540,6 +3757,23 @@ font_update_drivers (f, new_drivers)
          next = &(*next)->next;
        }
       *next = NULL;
+
+      if (! f->font_driver_list->on)
+       { /* None of the drivers is enabled: enable them all.
+            Happens if you set the list of drivers to (xft x) in your .emacs
+            and then use it under w32 or ns.  */
+         for (list = f->font_driver_list; list; list = list->next)
+           {
+             struct font_driver *driver = list->driver;
+             eassert (! list->on);
+             if (! driver->start_for_frame
+                 || driver->start_for_frame (f) == 0)
+               {
+                 font_prepare_cache (f, driver);
+                 list->on = 1;
+               }
+           }
+       }
     }
 
   for (list = f->font_driver_list; list; list = list->next)
@@ -3569,7 +3803,7 @@ font_put_frame_data (f, driver, data)
            prev->next = list->next;
          else
            f->font_data_list = list->next;
-         free (list);
+         xfree (list);
        }
       return 0;
     }
@@ -3619,11 +3853,13 @@ font_at (c, pos, face, w, string)
   int multibyte;
   Lisp_Object font_object;
 
+  multibyte = (NILP (string)
+              ? ! NILP (current_buffer->enable_multibyte_characters)
+              : STRING_MULTIBYTE (string));
   if (c < 0)
     {
       if (NILP (string))
        {
-         multibyte = ! NILP (current_buffer->enable_multibyte_characters);
          if (multibyte)
            {
              EMACS_INT pos_byte = CHAR_TO_BYTE (pos);
@@ -3643,7 +3879,7 @@ font_at (c, pos, face, w, string)
              EMACS_INT pos_byte = string_char_to_byte (string, pos);
 
              str = SDATA (string) + pos_byte;
-             c = STRING_CHAR (str, 0);
+             c = STRING_CHAR (str);
            }
          else
            c = SDATA (string)[pos];
@@ -3663,7 +3899,7 @@ font_at (c, pos, face, w, string)
                                           DEFAULT_FACE_ID, 0);
       else
        face_id = face_at_buffer_position (w, pos, -1, -1, &endptr,
-                                          pos + 100, 0);
+                                          pos + 100, 0, -1);
       face = FACE_FROM_ID (f, face_id);
     }
   if (multibyte)
@@ -3710,7 +3946,8 @@ font_range (pos, limit, w, face, string)
        {
          int face_id;
 
-         face_id = face_at_buffer_position (w, pos, 0, 0, &ignore, *limit, 0);
+         face_id = face_at_buffer_position (w, pos, 0, 0, &ignore,
+                                            *limit, 0, -1);
          face = FACE_FROM_ID (XFRAME (w->frame), face_id);
        }
     }
@@ -3739,6 +3976,7 @@ font_range (pos, limit, w, face, string)
 
       category = CHAR_TABLE_REF (Vunicode_category_table, c);
       if (! EQ (category, QCf)
+         && ! CHAR_VARIATION_SELECTOR_P (c)
          && font_encode_char (font_object, c) == FONT_INVALID_CODE)
        {
          Lisp_Object f = font_for_char (face, c, pos - 1, string);
@@ -3760,6 +3998,7 @@ font_range (pos, limit, w, face, string)
                FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, string, i, i_byte);
              category = CHAR_TABLE_REF (Vunicode_category_table, c);
              if (! EQ (category, QCf)
+                 && ! CHAR_VARIATION_SELECTOR_P (c)
                  && font_encode_char (f, c) == FONT_INVALID_CODE)
                {
                  *limit = pos - 1;
@@ -3824,18 +4063,43 @@ encoding of a font, e.g. ``iso8859-1''.
 `:size'
 
 VALUE must be a non-negative integer or a floating point number
-specifying the font size.  It specifies the font size in pixels
-(if VALUE is an integer), or in points (if VALUE is a float).
+specifying the font size.  It specifies the font size in pixels (if
+VALUE is an integer), or in points (if VALUE is a float).
 
 `:name'
 
 VALUE must be a string of XLFD-style or fontconfig-style font name.
-usage: (font-spec ARGS ...)
 
 `:script'
 
 VALUE must be a symbol representing a script that the font must
-support.  */)
+support.  It may be a symbol representing a subgroup of a script
+listed in the variable `script-representative-chars'.
+
+`:lang'
+
+VALUE must be a symbol of two-letter ISO-639 language names,
+e.g. `ja'.
+
+`:otf'
+
+VALUE must be a list (SCRIPT-TAG LANGSYS-TAG GSUB [ GPOS ]) to specify
+required OpenType features.
+
+  SCRIPT-TAG: OpenType script tag symbol (e.g. `deva').
+  LANGSYS-TAG: OpenType language system tag symbol,
+     or nil for the default language system.
+  GSUB: List of OpenType GSUB feature tag symbols, or nil if none required.
+  GPOS: List of OpenType GPOS feature tag symbols, or nil if none required.
+
+GSUB and GPOS may contain `nil' element.  In such a case, the font
+must not have any of the remaining elements.
+
+For instance, if the VALUE is `(thai nil nil (mark))', the font must
+be an OpenType font, and whose GPOS table of `thai' script's default
+language system must contain `mark' feature.
+
+usage: (font-spec ARGS...)  */)
      (nargs, args)
      int nargs;
      Lisp_Object *args;
@@ -3845,7 +4109,12 @@ support.  */)
 
   for (i = 0; i < nargs; i += 2)
     {
-      Lisp_Object key = args[i], val = args[i + 1];
+      Lisp_Object key = args[i], val;
+
+      CHECK_SYMBOL (key);
+      if (i + 1 >= nargs)
+       error ("No value for key `%s'", SDATA (SYMBOL_NAME (key)));
+      val = args[i + 1];
 
       if (EQ (key, QCname))
        {
@@ -3884,7 +4153,7 @@ DEFUN ("copy-font-spec", Fcopy_font_spec, Scopy_font_spec, 1, 1, 0,
   new_spec = font_make_spec ();
   for (i = 1; i < FONT_EXTRA_INDEX; i++)
     ASET (new_spec, i, AREF (font, i));
-  extra = Fcopy_sequence (AREF (font, FONT_EXTRA_INDEX));
+  extra = Fcopy_alist (AREF (font, FONT_EXTRA_INDEX));
   /* We must remove :font-entity property.  */
   for (prev = Qnil, tail = extra; CONSP (tail); prev = tail, tail = XCDR (tail))
     if (EQ (XCAR (XCAR (tail)), QCfont_entity))
@@ -4068,8 +4337,8 @@ how close they are to PREFER.  */)
      (font_spec, frame, num, prefer)
      Lisp_Object font_spec, frame, num, prefer;
 {
-  Lisp_Object vec, list, tail;
-  int n = 0, i, len;
+  Lisp_Object vec, list;
+  int n = 0;
 
   if (NILP (frame))
     frame = selected_frame;
@@ -4085,25 +4354,29 @@ how close they are to PREFER.  */)
   if (! NILP (prefer))
     CHECK_FONT_SPEC (prefer);
 
-  vec = font_list_entities (frame, font_spec);
-  len = ASIZE (vec);
-  if (len == 0)
+  list = font_list_entities (frame, font_spec);
+  if (NILP (list))
     return Qnil;
-  if (len == 1)
-    return Fcons (AREF (vec, 0), Qnil);
+  if (NILP (XCDR (list))
+      && ASIZE (XCAR (list)) == 1)
+    return Fcons (AREF (XCAR (list), 0), Qnil);
 
   if (! NILP (prefer))
-    vec = font_sort_entites (vec, prefer, frame, 0);
-
-  list = tail = Fcons (AREF (vec, 0), Qnil);
-  if (n == 0 || n > len)
-    n = len;
-  for (i = 1; i < n; i++)
+    vec = font_sort_entities (list, prefer, frame, 0);
+  else
+    vec = font_vconcat_entity_vectors (list);
+  if (n == 0 || n >= ASIZE (vec))
     {
-      Lisp_Object val = Fcons (AREF (vec, i), Qnil);
+      Lisp_Object args[2];
 
-      XSETCDR (tail, val);
-      tail = val;
+      args[0] = vec;
+      args[1] = Qnil;
+      list = Fappend (2, args);
+    }
+  else
+    {
+      for (list = Qnil, n--; n >= 0; n--)
+       list = Fcons (AREF (vec, n), list);
     }
   return list;
 }
@@ -4128,17 +4401,12 @@ Optional argument FRAME, if non-nil, specifies the target frame.  */)
     if (driver_list->driver->list_family)
       {
        Lisp_Object val = driver_list->driver->list_family (frame);
+       Lisp_Object tail = list;
 
-       if (NILP (list))
-         list = val;
-       else
-         {
-           Lisp_Object tail = list;
-
-           for (; CONSP (val); val = XCDR (val))
-             if (NILP (Fmemq (XCAR (val), tail)))
-               list = Fcons (XCAR (val), list);
-         }
+       for (; CONSP (val); val = XCDR (val))
+         if (NILP (Fmemq (XCAR (val), tail))
+             && SYMBOLP (XCAR (val)))
+           list = Fcons (SYMBOL_NAME (XCAR (val)), list);
       }
   return list;
 }
@@ -4216,15 +4484,15 @@ DEFUN ("clear-font-cache", Fclear_font_cache, Sclear_font_cache, 0, 0, 0,
        if (driver_list->on)
          {
            Lisp_Object cache = driver_list->driver->get_cache (f);
-           Lisp_Object val;
+           Lisp_Object val, tmp;
 
            val = XCDR (cache);
            while (! NILP (val)
                   && ! EQ (XCAR (XCAR (val)), driver_list->driver->type))
              val = XCDR (val);
            font_assert (! NILP (val));
-           val = XCDR (XCAR (val));
-           if (XINT (XCAR (val)) == 0)
+           tmp = XCDR (XCAR (val));
+           if (XINT (XCAR (tmp)) == 0)
              {
                font_clear_cache (f, XCAR (val), driver_list->driver);
                XSETCDR (cache, XCDR (val));
@@ -4271,7 +4539,7 @@ created glyph-string.  Otherwise, the value is nil.  */)
   struct font *font;
   Lisp_Object font_object, n, glyph;
   int i, j, from, to;
-  
+
   if (! composition_gstring_p (gstring))
     signal_error ("Invalid glyph-string: ", gstring);
   if (! NILP (LGSTRING_ID (gstring)))
@@ -4294,7 +4562,7 @@ created glyph-string.  Otherwise, the value is nil.  */)
     }
   if (i == 3 || XINT (n) == 0)
     return Qnil;
-  
+
   glyph = LGSTRING_GLYPH (gstring, 0);
   from = LGLYPH_FROM (glyph);
   to = LGLYPH_TO (glyph);
@@ -4335,6 +4603,49 @@ created glyph-string.  Otherwise, the value is nil.  */)
   return composition_gstring_put_cache (gstring, XINT (n));
 }
 
+DEFUN ("font-variation-glyphs", Ffont_variation_glyphs, Sfont_variation_glyphs,
+       2, 2, 0,
+       doc: /* Return a list of variation glyphs for CHAR in FONT-OBJECT.
+Each element of the value is a cons (VARIATION-SELECTOR . GLYPH-ID),
+where
+  VARIATION-SELECTOR is a chracter code of variation selection
+    (#xFE00..#xFE0F or #xE0100..#xE01EF)
+  GLYPH-ID is a glyph code of the corresponding variation glyph.  */)
+     (font_object, character)
+     Lisp_Object font_object, character;
+{
+  unsigned variations[256];
+  struct font *font;
+  int i, n;
+  Lisp_Object val;
+
+  CHECK_FONT_OBJECT (font_object);
+  CHECK_CHARACTER (character);
+  font = XFONT_OBJECT (font_object);
+  if (! font->driver->get_variation_glyphs)
+    return Qnil;
+  n = font->driver->get_variation_glyphs (font, XINT (character), variations);
+  if (! n)
+    return Qnil;
+  val = Qnil;
+  for (i = 0; i < 255; i++)
+    if (variations[i])
+      {
+       Lisp_Object code;
+       int vs = (i < 16 ? 0xFE00 + i : 0xE0100 + (i - 16));
+       /* Stops GCC whining about limited range of data type.  */
+       EMACS_INT var = variations[i];
+
+       if (var > MOST_POSITIVE_FIXNUM)
+         code = Fcons (make_number ((variations[i]) >> 16),
+                       make_number ((variations[i]) & 0xFFFF));
+       else
+         code = make_number (variations[i]);
+       val = Fcons (Fcons (make_number (vs), code), val);
+      }
+  return val;
+}
+
 #if 0
 
 DEFUN ("font-drive-otf", Ffont_drive_otf, Sfont_drive_otf, 6, 6, 0,
@@ -4480,7 +4791,7 @@ DEFUN ("open-font", Fopen_font, Sopen_font, 1, 3, 0,
     {
       CHECK_NUMBER_OR_FLOAT (size);
       if (FLOATP (size))
-       isize = POINT_TO_PIXEL (- isize, XFRAME (frame)->resy);
+       isize = POINT_TO_PIXEL (XFLOAT_DATA (size), XFRAME (frame)->resy);
       else
        isize = XINT (size);
       if (isize == 0)
@@ -4702,13 +5013,13 @@ Type C-l to recover what previously shown.  */)
 DEFUN ("font-info", Ffont_info, Sfont_info, 1, 2, 0,
        doc: /* Return information about a font named NAME on frame FRAME.
 If FRAME is omitted or nil, use the selected frame.
-The returned value is a vector of OPENED-NAME, FULL-NAME, CHARSET, SIZE,
+The returned value is a vector of OPENED-NAME, FULL-NAME, SIZE,
   HEIGHT, BASELINE-OFFSET, RELATIVE-COMPOSE, and DEFAULT-ASCENT,
 where
   OPENED-NAME is the name used for opening the font,
   FULL-NAME is the full name of the font,
-  SIZE is the maximum bound width of the font,
-  HEIGHT is the height of the font,
+  SIZE is the pixelsize of the font,
+  HEIGHT is the pixel-height of the font (i.e ascent + descent),
   BASELINE-OFFSET is the upward offset pixels from ASCII baseline,
   RELATIVE-COMPOSE and DEFAULT-ASCENT are the numbers controlling
     how to compose characters.
@@ -4755,7 +5066,7 @@ If the named font is not yet loaded, return nil.  */)
 
   info = Fmake_vector (make_number (7), Qnil);
   XVECTOR (info)->contents[0] = AREF (font_object, FONT_NAME_INDEX);
-  XVECTOR (info)->contents[1] = AREF (font_object, FONT_NAME_INDEX);
+  XVECTOR (info)->contents[1] = AREF (font_object, FONT_FULLNAME_INDEX);
   XVECTOR (info)->contents[2] = make_number (font->pixel_size);
   XVECTOR (info)->contents[3] = make_number (font->height);
   XVECTOR (info)->contents[4] = make_number (font->baseline_offset);
@@ -4791,14 +5102,13 @@ build_style_table (entry, nelement)
       elt = Fmake_vector (make_number (j + 1), Qnil);
       ASET (elt, 0, make_number (entry[i].numeric));
       for (j = 0; entry[i].names[j]; j++)
-       ASET (elt, j + 1, intern (entry[i].names[j]));
+       ASET (elt, j + 1, intern_c_string (entry[i].names[j]));
       ASET (table, i, elt);
     }
   return table;
 }
 
-static Lisp_Object Vfont_log;
-static int font_log_env_checked;
+Lisp_Object Vfont_log;
 
 /* The deferred font-log data of the form [ACTION ARG RESULT].
    If ACTION is not nil, that is added to the log when font_add_log is
@@ -4817,11 +5127,6 @@ font_add_log (action, arg, result)
   Lisp_Object tail, val;
   int i;
 
-  if (! font_log_env_checked)
-    {
-      Vfont_log = egetenv ("EMACS_FONT_LOG") ? Qnil : Qt;
-      font_log_env_checked = 1;
-    }
   if (EQ (Vfont_log, Qt))
     return;
   if (STRINGP (AREF (Vfont_log_deferred, 0)))
@@ -4859,6 +5164,12 @@ font_add_log (action, arg, result)
        }
       arg = val;
     }
+
+  if (CONSP (result)
+      && VECTORP (XCAR (result))
+      && ASIZE (XCAR (result)) > 0
+      && FONTP (AREF (XCAR (result), 0)))
+    result = font_vconcat_entity_vectors (result);
   if (FONTP (result))
     {
       val = Ffont_xlfd_name (result, Qt);
@@ -4901,10 +5212,12 @@ font_deferred_log (action, arg, result)
      char *action;
      Lisp_Object arg, result;
 {
+  if (EQ (Vfont_log, Qt))
+    return;
   ASET (Vfont_log_deferred, 0, build_string (action));
   ASET (Vfont_log_deferred, 1, arg);
   ASET (Vfont_log_deferred, 2, result);
-}     
+}
 
 extern void syms_of_ftfont P_ (());
 extern void syms_of_xfont P_ (());
@@ -4928,10 +5241,6 @@ syms_of_font ()
   staticpro (&font_charset_alist);
   font_charset_alist = Qnil;
 
-  DEFSYM (Qfont_spec, "font-spec");
-  DEFSYM (Qfont_entity, "font-entity");
-  DEFSYM (Qfont_object, "font-object");
-
   DEFSYM (Qopentype, "opentype");
 
   DEFSYM (Qascii_0, "ascii-0");
@@ -4962,6 +5271,11 @@ syms_of_font ()
   DEFSYM (Qp, "p");
   DEFSYM (Qd, "d");
 
+  DEFSYM (Qja, "ja");
+  DEFSYM (Qko, "ko");
+
+  DEFSYM (QCuser_spec, "user-spec");
+
   staticpro (&null_vector);
   null_vector = Fmake_vector (make_number (0), Qnil);
 
@@ -4993,6 +5307,7 @@ syms_of_font ()
   defsubr (&Sfont_xlfd_name);
   defsubr (&Sclear_font_cache);
   defsubr (&Sfont_shape_gstring);
+  defsubr (&Sfont_variation_glyphs);
 #if 0
   defsubr (&Sfont_drive_otf);
   defsubr (&Sfont_otf_alternates);
@@ -5092,5 +5407,11 @@ EMACS_FONT_LOG is set.  Otherwise, it is set to t.  */);
 #endif /* HAVE_WINDOW_SYSTEM */
 }
 
+void
+init_font ()
+{
+  Vfont_log = egetenv ("EMACS_FONT_LOG") ? Qnil : Qt;
+}
+
 /* arch-tag: 74c9475d-5976-4c93-a327-942ae3072846
    (do not change this comment) */