Fix -Wimplicit warnings.
[bpt/emacs.git] / src / xterm.c
index d06335b..4afe386 100644 (file)
@@ -1,5 +1,5 @@
 /* X Communication module for terminals which understand the X protocol.
-   Copyright (C) 1989, 93, 94, 95, 1996 Free Software Foundation, Inc.
+   Copyright (C) 1989, 93, 94, 95, 96, 1997 Free Software Foundation, Inc.
 
 This file is part of GNU Emacs.
 
@@ -68,6 +68,9 @@ Boston, MA 02111-1307, USA.  */
 /* Caused redefinition of DBL_DIG on Netbsd; seems not to be needed.  */
 /* #include <sys/param.h>  */
 
+#include "charset.h"
+#include "ccl.h"
+#include "fontset.h"
 #include "frame.h"
 #include "dispextern.h"
 #include "termhooks.h"
@@ -83,6 +86,7 @@ Boston, MA 02111-1307, USA.  */
 #include "window.h"
 #include "keyboard.h"
 #include "intervals.h"
+#include "process.h"
 
 #ifdef USE_X_TOOLKIT
 #include <X11/Shell.h>
@@ -144,7 +148,7 @@ Lisp_Object x_display_name_list;
    is the frame to apply to.  */
 extern struct frame *updating_frame;
 
-extern waiting_for_input;
+extern int waiting_for_input;
 
 /* This is a frame waiting to be autoraised, within XTread_socket.  */
 struct frame *pending_autoraise_frame;
@@ -262,10 +266,10 @@ static void clear_mouse_face ();
 static void show_mouse_face ();
 static void do_line_dance ();
 
-static int XTcursor_to ();
-static int XTclear_end_of_line ();
+static void XTcursor_to ();
+static void XTclear_end_of_line ();
 static int x_io_error_quitter ();
-void x_catch_errors ();
+int x_catch_errors ();
 void x_uncatch_errors ();
 \f
 #if 0
@@ -320,7 +324,7 @@ x_display_info_for_display (dpy)
    should never be called except during an update, the only exceptions
    being XTcursor_to, XTwrite_glyphs and XTreassert_line_highlight.  */
 
-static
+static void
 XTupdate_begin (f)
      struct frame *f;
 {
@@ -380,7 +384,7 @@ XTupdate_begin (f)
   UNBLOCK_INPUT;
 }
 
-static
+static void
 XTupdate_end (f)
      struct frame *f;
 {
@@ -410,7 +414,7 @@ XTupdate_end (f)
 
 /* This is called after a redisplay on frame F.  */
 
-static
+static void
 XTframe_up_to_date (f)
      FRAME_PTR f;
 {
@@ -418,9 +422,10 @@ XTframe_up_to_date (f)
   if (FRAME_X_DISPLAY_INFO (f)->mouse_face_deferred_gc
       || f == FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_frame)
     {
-      note_mouse_highlight (FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_frame,
-                           FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_x,
-                           FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_y);
+      if (FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_frame)
+       note_mouse_highlight (FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_frame,
+                             FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_x,
+                             FRAME_X_DISPLAY_INFO (f)->mouse_face_mouse_y);
       FRAME_X_DISPLAY_INFO (f)->mouse_face_deferred_gc = 0;
     }
   UNBLOCK_INPUT;
@@ -430,6 +435,7 @@ XTframe_up_to_date (f)
    Call this when about to modify line at position VPOS
    and not change whether it is highlighted.  */
 
+void
 XTreassert_line_highlight (new, vpos)
      int new, vpos;
 {
@@ -439,7 +445,7 @@ XTreassert_line_highlight (new, vpos)
 /* Call this when about to modify line at position VPOS
    and change whether it is highlighted.  */
 
-static
+static void
 XTchange_line_highlight (new_highlight, vpos, first_unused_hpos)
      int new_highlight, vpos, first_unused_hpos;
 {
@@ -452,7 +458,7 @@ XTchange_line_highlight (new_highlight, vpos, first_unused_hpos)
    When starting Emacs, no X window is mapped.  And nothing must be done
    to Emacs's own window if it is suspended (though that rarely happens).  */
 
-static
+static void
 XTset_terminal_modes ()
 {
 }
@@ -461,7 +467,7 @@ XTset_terminal_modes ()
    Exiting will make the X-windows go away, and suspending
    requires no action.  */
 
-static
+static void
 XTreset_terminal_modes ()
 {
 /*  XTclear_frame ();  */
@@ -471,7 +477,7 @@ XTreset_terminal_modes ()
    This is where display update commands will take effect.
    This does not affect the place where the cursor-box is displayed.  */
 
-static int
+static void
 XTcursor_to (row, col)
      register int row, col;
 {
@@ -490,6 +496,19 @@ XTcursor_to (row, col)
     }
 }
 \f
+
+/* Return a pointer to per char metric information in FONT of a
+   character pointed by B (*XChar2b).  */
+
+#define PER_CHAR_METRIC(font, b)                                          \
+  ((font)->per_char                                                       \
+   ? ((font)->per_char + (b)->byte2 - (font)->min_char_or_byte2                   \
+      + (((font)->min_byte1 || (font)->max_byte1)                         \
+        ? (((b)->byte1 - (font)->min_byte1)                               \
+           * ((font)->max_char_or_byte2 - (font)->min_char_or_byte2 + 1)) \
+        : 0))                                                             \
+   : &((font)->max_bounds))
+
 /* Display a sequence of N glyphs found at GP.
    WINDOW is the x-window to output to.  LEFT and TOP are starting coords.
    HL is 1 if this text is highlighted, 2 if the cursor is on it,
@@ -497,6 +516,11 @@ XTcursor_to (row, col)
    JUST_FOREGROUND if 1 means draw only the foreground;
    don't alter the background.
 
+   CMPCHARP if non NULL is a pointer to the struct cmpchar_info, which
+   means drawing glyphs on the same column.  This is set to non NULL
+   only when recursively called within dumpglyphs to draw a composite
+   character specified by CMPCHAR.
+
    FONT is the default font to use (for glyphs whose font-code is 0).
 
    Since the display generation code is responsible for calling
@@ -504,62 +528,135 @@ XTcursor_to (row, col)
    the display structure, we can assume that the face code on each
    glyph is a valid index into FRAME_COMPUTED_FACES (f), and the one
    to which we can actually apply intern_face.
-   Call this function with input blocked.  */
+   Call this function with input blocked.
+
+   Return overall pixel width of the drawn glyphs.  */
 
 #if 1
 /* This is the multi-face code.  */
 
-static void
-dumpglyphs (f, left, top, gp, n, hl, just_foreground)
+static int
+dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
      struct frame *f;
      int left, top;
      register GLYPH *gp; /* Points to first GLYPH. */
      register int n;  /* Number of glyphs to display. */
      int hl;
      int just_foreground;
+     struct cmpchar_info *cmpcharp;
 {
   /* Holds characters to be displayed. */
-  char *buf = (char *) alloca (FRAME_WINDOW_WIDTH (f) * sizeof (*buf));
-  register char *cp;           /* Steps through buf[]. */
+  XChar2b *x_2byte_buffer
+    = (XChar2b *) alloca (FRAME_WINDOW_WIDTH (f) * sizeof (*x_2byte_buffer));
+  register XChar2b *cp;                /* Steps through x_2byte_buffer[]. */
+  char *x_1byte_buffer
+    = (char *) alloca (FRAME_WINDOW_WIDTH (f) * sizeof (*x_1byte_buffer));
   register int tlen = GLYPH_TABLE_LENGTH;
   register Lisp_Object *tbase = GLYPH_TABLE_BASE;
   Window window = FRAME_X_WINDOW (f);
   int orig_left = left;
+  int gidx = 0;
+  int i;
 
   while (n > 0)
     {
       /* Get the face-code of the next GLYPH.  */
       int cf, len;
-      int g = *gp;
+      GLYPH g = *gp;
+      int ch, charset;
+      Lisp_Object first_ch;
+      /* HIGHEST and LOWEST are used while drawing a composite
+         character.  The meanings are described later.  */
+      int highest, lowest;
 
       GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
-      cf = FAST_GLYPH_FACE (g);
+      cf = (cmpcharp ? cmpcharp->face_work : FAST_GLYPH_FACE (g));
+      ch = FAST_GLYPH_CHAR (g);
+      if (gidx == 0) XSETFASTINT (first_ch, ch);
+      charset = CHAR_CHARSET (ch);
+      if (charset == CHARSET_COMPOSITION)
+       {
+         /* We must draw components of the composite character on the
+             same column.  */
+         cmpcharp = cmpchar_table[COMPOSITE_CHAR_ID (ch)];
+
+         /* Set the face in the slot for work.  */
+         cmpcharp->face_work = cf;
+
+         /* We don't need the return value ... */
+         dumpglyphs (f, left, top, cmpcharp->glyph, cmpcharp->glyph_len,
+                     hl, just_foreground, cmpcharp);
+         /* ... because the width of just drawn text can be
+             calculated as follows.  */
+         left += FONT_WIDTH (f->output_data.x->font) * cmpcharp->width;
+
+         ++gp, --n;
+         while (gp && (*gp & GLYPH_MASK_PADDING)) ++gp, --n;
+         cmpcharp = NULL;
+         continue;
+       }
 
-      /* Find the run of consecutive glyphs with the same face-code.
-        Extract their character codes into BUF.  */
-      cp = buf;
+      /* Find the run of consecutive glyphs which can be drawn with
+        the same GC (i.e. the same charset and the same face-code).
+        Extract their character codes into X_2BYTE_BUFFER.
+        If CMPCHARP is not NULL, face-code is not checked because we
+        use only the face specified in `cmpcharp->face_work'.  */
+      cp = x_2byte_buffer;
       while (n > 0)
        {
+         int this_charset, c1, c2;
+
          g = *gp;
          GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
-         if (FAST_GLYPH_FACE (g) != cf)
+         ch = FAST_GLYPH_CHAR (g);
+         SPLIT_CHAR (ch, this_charset, c1, c2);
+         if (this_charset != charset
+             || (cmpcharp == NULL && FAST_GLYPH_FACE (g) != cf))
            break;
 
-         *cp++ = FAST_GLYPH_CHAR (g);
-         --n;
-         ++gp;
+         if (c2 > 0)
+           cp->byte1 = c1, cp->byte2 = c2;
+         else
+           cp->byte1 = 0, cp->byte2 = c1;
+         ++cp;
+         ++gp, --n;
+         while (gp && (*gp & GLYPH_MASK_PADDING))
+           ++gp, --n;
        }
 
       /* LEN gets the length of the run.  */
-      len = cp - buf;
-
+      len = cp - x_2byte_buffer;
       /* Now output this run of chars, with the font and pixel values
         determined by the face code CF.  */
       {
        struct face *face = FRAME_DEFAULT_FACE (f);
-       XFontStruct *font = FACE_FONT (face);
-       GC gc = FACE_GC (face);
+       XFontStruct *font = NULL;
+       GC gc;
        int stippled = 0;
+       int line_height = f->output_data.x->line_height;
+       /* Pixel width of each glyph in this run.  */
+       int glyph_width
+         = (FONT_WIDTH (f->output_data.x->font)
+            * (cmpcharp ? cmpcharp->width : CHARSET_WIDTH (charset)));
+       /* Overall pixel width of this run.  */
+       int run_width
+         = (FONT_WIDTH (f->output_data.x->font)
+            * (cmpcharp ? cmpcharp->width : len * CHARSET_WIDTH (charset)));
+       /* A flag to tell if we have already filled background.  We
+          fill background in advance in the following cases:
+          1) A face has stipple.
+          2) A height of font is shorter than LINE_HEIGHT.
+          3) Drawing a composite character.
+          4) Font has non-zero _MULE_BASELINE_OFFSET property.
+          After filling background, we draw glyphs by XDrawString16.  */
+       int background_filled;
+       /* Baseline position of a character, offset from TOP.  */
+       int baseline;
+       /* The property value of `_MULE_RELATIVE_COMPOSE' and
+           `_MULE_DEFAULT_ASCENT'.  */
+       int relative_compose = 0, default_ascent = 0;
+       /* 1 if we find no font or a font of inappropriate size.  */
+       int require_clipping;
 
        /* HL = 3 means use a mouse face previously chosen.  */
        if (hl == 3)
@@ -578,8 +675,6 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground)
              face = FRAME_MODE_LINE_FACE (f);
            else
              face = intern_face (f, FRAME_COMPUTED_FACES (f) [cf]);
-           font = FACE_FONT (face);
-           gc = FACE_GC (face);
            if (FACE_STIPPLE (face))
              stippled = 1;
          }
@@ -590,25 +685,124 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground)
        else if (hl == 1)
          {
            face = FRAME_MODE_LINE_FACE (f);
-           font = FACE_FONT (face);
-           gc   = FACE_GC   (face);
            if (FACE_STIPPLE (face))
              stippled = 1;
          }
 
 #define FACE_DEFAULT (~0)
 
+       /* Setting appropriate font and gc for this charset.  */
+       if (charset != CHARSET_ASCII)
+         {
+           int font_id;
+           int fontset = FACE_FONTSET (face);
+           struct font_info *fontp;
+
+           if ((fontset < 0 && (fontset = FRAME_FONTSET (f)) < 0)
+               || !(fontp = FS_LOAD_FONT (f, FRAME_X_FONT_TABLE (f),
+                                          charset, NULL, fontset)))
+             goto font_not_found;
+
+           font = (XFontStruct *) (fontp->font);
+           gc = FACE_NON_ASCII_GC (face);
+           XSetFont (FRAME_X_DISPLAY (f), gc, font->fid);
+           baseline
+             = (font->max_byte1 != 0
+                ? (line_height + font->ascent - font->descent) / 2
+                : f->output_data.x->font_baseline - fontp->baseline_offset);
+           if (FONT_HEIGHT (font) <= line_height
+               && (font->ascent > baseline
+                   || font->descent > line_height - baseline))
+             /* Adjust baseline for this font to show the whole
+                 glyphs in a line.  */
+             baseline = line_height - font->descent;
+             
+           if (cmpcharp && cmpcharp->cmp_rule == NULL)
+             {
+               relative_compose = fontp->relative_compose;
+               default_ascent = fontp->default_ascent;
+             }
+
+           /* We have to change code points in the following cases.  */
+           if (fontp->font_encoder)
+             {
+               /* This font requires CCL program to calculate code
+                   point of characters.  */
+               struct ccl_program *ccl = fontp->font_encoder;
+
+               if (CHARSET_DIMENSION (charset) == 1)
+                 for (cp = x_2byte_buffer; cp < x_2byte_buffer + len; cp++)
+                   {
+                     ccl->reg[0] = charset;
+                     ccl->reg[1] = cp->byte2;
+                     ccl_driver (ccl, NULL, NULL, 0, 0, NULL);
+                     /* We assume that MSBs are appropriately
+                         set/reset by CCL program.  */
+                     if (font->max_byte1 == 0) /* 1-byte font */
+                       cp->byte2 = ccl->reg[1];
+                     else
+                       cp->byte1 = ccl->reg[1], cp->byte2 = ccl->reg[2];
+                   }
+               else
+                 for (cp = x_2byte_buffer; cp < x_2byte_buffer + len; cp++)
+                   {
+                     ccl->reg[0] = charset;
+                     ccl->reg[1] = cp->byte1, ccl->reg[2] = cp->byte2;
+                     ccl_driver (ccl, NULL, NULL, 0, 0, NULL);
+                     /* We assume that MSBs are appropriately
+                         set/reset by CCL program.  */
+                     if (font->max_byte1 == 0) /* 1-byte font */
+                       cp->byte2 = ccl->reg[1];
+                     else
+                       cp->byte1 = ccl->reg[1], cp->byte2 = ccl->reg[2];
+                   }
+             }
+           else if (fontp->encoding[charset])
+             {
+               int enc = fontp->encoding[charset];
+
+               if ((enc == 1 || enc == 2) && CHARSET_DIMENSION (charset) == 2)
+                 for (cp = x_2byte_buffer; cp < x_2byte_buffer + len; cp++)
+                   cp->byte1 |= 0x80;
+               if (enc == 1 || enc == 3)
+                 for (cp = x_2byte_buffer; cp < x_2byte_buffer + len; cp++)
+                   cp->byte2 |= 0x80;
+             }
+         }
+       else
+         {
+         font_not_found:
+           if (charset == CHARSET_ASCII || charset == charset_latin_iso8859_1)
+             {
+               font = FACE_FONT (face);
+               if (font == (XFontStruct *) FACE_DEFAULT)
+                 font = f->output_data.x->font;
+               baseline = FONT_BASE (f->output_data.x->font);
+               if (charset == charset_latin_iso8859_1)
+                 {
+                   if (font->max_char_or_byte2 < 0x80)
+                     /* This font can't display Latin1 characters.  */
+                     font = NULL;
+                   else
+                     {
+                       for (cp = x_2byte_buffer; cp < x_2byte_buffer + len; cp++)
+                         cp->byte2 |= 0x80;
+                     }
+                 }
+             }
+           gc = FACE_GC (face);
+         }
+
        /* Now override that if the cursor's on this character.  */
        if (hl == 2)
          {
            /* The cursor overrides stippling.  */
            stippled = 0;
 
-           if ((!face->font
-                || face->font == (XFontStruct *) FACE_DEFAULT
-                || face->font == f->output_data.x->font)
+           if (font == f->output_data.x->font
                && face->background == f->output_data.x->background_pixel
-               && face->foreground == f->output_data.x->foreground_pixel)
+               && face->foreground == f->output_data.x->foreground_pixel
+               && !cmpcharp)
              {
                gc = f->output_data.x->cursor_gc;
              }
@@ -635,7 +829,10 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground)
                    xgcv.background = face->foreground;
                    xgcv.foreground = face->background;
                  }
-               xgcv.font = face->font->fid;
+               if (font)
+                 xgcv.font = font->fid;
+               else
+                 xgcv.font = FACE_FONT (face)->fid;
                xgcv.graphics_exposures = 0;
                mask = GCForeground | GCBackground | GCFont | GCGraphicsExposures;
                if (FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc)
@@ -655,81 +852,299 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground)
              }
          }
 
-       if (font == (XFontStruct *) FACE_DEFAULT)
-         font = f->output_data.x->font;
+       if (font)
+         require_clipping = (!NILP (Vclip_large_size_font)
+                             && (font->ascent > baseline
+                                 || font->descent > line_height - baseline
+                                 || (!cmpcharp
+                                     && FONT_WIDTH (font) > glyph_width)));
+
+       if (font && (just_foreground || (cmpcharp && gidx > 0)))
+         background_filled = 1;
+       else if (stippled)
+         {
+           /* Turn stipple on.  */
+           XSetFillStyle (FRAME_X_DISPLAY (f), gc, FillOpaqueStippled);
+
+           /* Draw stipple or background color on background.  */
+           XFillRectangle (FRAME_X_DISPLAY (f), window, gc,
+                           left, top, run_width, line_height);
+
+           /* Turn stipple off.  */
+           XSetFillStyle (FRAME_X_DISPLAY (f), gc, FillSolid);
 
-       if (just_foreground)
-         XDrawString (FRAME_X_DISPLAY (f), window, gc,
-                      left, top + FONT_BASE (font), buf, len);
+           background_filled = 1;
+         }
+       else if (!font
+                || FONT_HEIGHT (font) < line_height
+                || FONT_WIDTH (font) < glyph_width
+                || cmpcharp)
+         {
+           /* Fill a area for the current run in background pixle of GC.  */
+           XGCValues xgcv;
+           unsigned long mask = GCForeground | GCBackground | GCFillStyle;
+
+           /* The current code at first set foreground to background,
+             fill the area, then recover the original foreground.
+             Aren't there any smarter ways?  */
+
+           XGetGCValues (FRAME_X_DISPLAY (f), gc, mask, &xgcv);
+           XSetForeground (FRAME_X_DISPLAY (f), gc, xgcv.background);
+           XSetFillStyle (FRAME_X_DISPLAY (f), gc, FillSolid);
+           XFillRectangle (FRAME_X_DISPLAY (f), window, gc,
+                           left, top, run_width, line_height);
+           XSetForeground (FRAME_X_DISPLAY (f), gc, xgcv.foreground);
+
+           background_filled = 1;
+           if (cmpcharp)
+             /* To assure not to fill background while drawing
+                remaining components.  */
+             just_foreground = 1;
+         }
        else
+         background_filled = 0;
+
+       if (font)
          {
-           if (stippled)
+           if (require_clipping)
              {
-               /* Turn stipple on.  */
-               XSetFillStyle (FRAME_X_DISPLAY (f), gc, FillOpaqueStippled);
-
-               /* Draw stipple on background.  */
-               XFillRectangle (FRAME_X_DISPLAY (f), window, gc,
-                               left, top,
-                               FONT_WIDTH (font) * len,
-                               FONT_HEIGHT (font));
+               Region region;  /* Region used for setting clip mask to GC.  */
+               XPoint x[4];    /* Data used for creating REGION.  */
+
+               x[0].x = x[3].x = left, x[1].x = x[2].x = left + glyph_width;
+               x[0].y = x[1].y = top,  x[2].y = x[3].y = top + line_height;
+               region = XPolygonRegion (x, 4, EvenOddRule);
+               XSetRegion (FRAME_X_DISPLAY (f), gc, region);
+               XDestroyRegion (region);
+             }
 
-               /* Turn stipple off.  */
-               XSetFillStyle (FRAME_X_DISPLAY (f), gc, FillSolid);
+           if (!cmpcharp)
+             {
+               if (require_clipping || FONT_WIDTH (font) != glyph_width)
+                 for (i = 0; i < len; i++)
+                   {
+                     if (require_clipping && i > 0) 
+                       XSetClipOrigin (FRAME_X_DISPLAY (f), gc,
+                                       glyph_width * i, 0);
+                     if (background_filled)
+                       XDrawString16 (FRAME_X_DISPLAY (f), window, gc,
+                                      left + glyph_width * i,
+                                      top + baseline, x_2byte_buffer + i, 1);
+                     else
+                       XDrawImageString16 (FRAME_X_DISPLAY (f), window, gc,
+                                           left + glyph_width * i,
+                                           top + baseline, x_2byte_buffer + i, 1);
+                   }
+               else
+                 {
+                   /* See if this whole buffer can be output as 8-bit chars.
+                      If so, copy x_2byte_buffer to x_1byte_buffer
+                      and do it as 8-bit chars.  */
+                   for (i = 0; i < len; i++)
+                     {
+                       if (x_2byte_buffer[i].byte1 != 0)
+                         break;
+                       x_1byte_buffer[i] = x_2byte_buffer[i].byte2;
+                     }
 
-               /* Draw the text, solidly, onto the stipple pattern.  */
-               XDrawString (FRAME_X_DISPLAY (f), window, gc,
-                            left, top + FONT_BASE (font), buf, len);
+                   if (i == len)
+                     {
+                       if (background_filled)
+                         XDrawString (FRAME_X_DISPLAY (f), window, gc,
+                                      left, top + baseline, x_1byte_buffer, len);
+                       else
+                         XDrawImageString (FRAME_X_DISPLAY (f), window, gc,
+                                           left, top + baseline, x_1byte_buffer, len);
+                     }
+                   else
+                     {
+                       /* We can't output them as 8-bit chars,
+                          so do it as 16-bit chars.  */
+
+                       if (background_filled)
+                         XDrawString16 (FRAME_X_DISPLAY (f), window, gc,
+                                        left, top + baseline, x_2byte_buffer, len);
+                       else
+                         XDrawImageString16 (FRAME_X_DISPLAY (f), window, gc,
+                                             left, top + baseline, x_2byte_buffer, len);
+                     }
+                 }
              }
            else
-             XDrawImageString (FRAME_X_DISPLAY (f), window, gc,
-                               left, top + FONT_BASE (font), buf, len);
-
-           /* Clear the rest of the line's height.  */
-           if (f->output_data.x->line_height != FONT_HEIGHT (font))
-             XClearArea (FRAME_X_DISPLAY (f), window, left,
-                         top + FONT_HEIGHT (font),
-                         FONT_WIDTH (font) * len,
-                         /* This is how many pixels of height
-                            we have to clear.  */
-                         f->output_data.x->line_height - FONT_HEIGHT (font),
-                         False);
-         }
+             {
+               /* Handle composite characters.  */
+               XCharStruct *pcm; /* Pointer to per char metric info.  */
+
+               if ((cmpcharp->cmp_rule || relative_compose)
+                   && gidx == 0)
+                 {
+                   /* This is the first character.  Initialize variables.
+                      HIGHEST is the highest position of glyphs ever
+                      written, LOWEST the lowest position.  */
+                   int x_offset = 0;
+
+                   if (default_ascent
+                       && CHAR_TABLE_P (Vuse_default_ascent)
+                       && !NILP (Faref (Vuse_default_ascent, first_ch)))
+                     {
+                       highest = default_ascent;
+                       lowest = 0;
+                     }
+                   else
+                     {
+                       pcm = PER_CHAR_METRIC (font, x_2byte_buffer);
+                       highest = pcm->ascent + 1;
+                       lowest = - pcm->descent;
+                     }
+
+                   if (cmpcharp->cmp_rule)
+                     x_offset = (cmpcharp->col_offset[0]
+                                 * FONT_WIDTH (f->output_data.x->font));
+                   /* Draw the first character at the normal position.  */
+                   XDrawString16 (FRAME_X_DISPLAY (f), window, gc,
+                                  left + x_offset, top + baseline, x_2byte_buffer, 1);
+                   i = 1;
+                   gidx++;
+                 }
+               else
+                 i = 0;
+
+               for (; i < len; i++, gidx++)
+                 {
+                   int x_offset = 0, y_offset = 0;
+
+                   if (relative_compose)
+                     {
+                       pcm = PER_CHAR_METRIC (font, x_2byte_buffer + i);
+                       if (NILP (Vignore_relative_composition)
+                           || NILP (Faref (Vignore_relative_composition,
+                                           make_number (cmpcharp->glyph[gidx]))))
+                         {
+                           if (- pcm->descent >= relative_compose)
+                             {
+                               /* Draw above the current glyphs.  */
+                               y_offset = highest + pcm->descent;
+                               highest += pcm->ascent + pcm->descent;
+                             }
+                           else if (pcm->ascent <= 0)
+                             {
+                               /* Draw beneath the current glyphs.  */
+                               y_offset = lowest - pcm->ascent;
+                               lowest -= pcm->ascent + pcm->descent;
+                             }
+                         }
+                       else
+                         {
+                           /* Draw the glyph at normal position.  If
+                               it sticks out of HIGHEST or LOWEST,
+                               update them appropriately.  */
+                           if (pcm->ascent > highest)
+                             highest = pcm->ascent;
+                           else if (- pcm->descent < lowest)
+                             lowest = - pcm->descent;
+                         }
+                     }
+                   else if (cmpcharp->cmp_rule)
+                     {
+                       int gref = (cmpcharp->cmp_rule[gidx] - 0xA0) / 9;
+                       int nref = (cmpcharp->cmp_rule[gidx] - 0xA0) % 9;
+                       int bottom, top;
+
+                       /* Re-encode GREF and NREF so that they specify
+                          only Y-axis information:
+                          0:top, 1:base, 2:bottom, 3:center  */
+                       gref = gref / 3 + (gref == 4) * 2;
+                       nref = nref / 3 + (nref == 4) * 2;
+
+                       pcm = PER_CHAR_METRIC (font, x_2byte_buffer + i);
+                       bottom = ((gref == 0 ? highest : gref == 1 ? 0
+                                  : gref == 2 ? lowest
+                                  : (highest + lowest) / 2)
+                                 - (nref == 0 ? pcm->ascent + pcm->descent
+                                    : nref == 1 ? pcm->descent : nref == 2 ? 0
+                                    : (pcm->ascent + pcm->descent) / 2));
+                       top = bottom + (pcm->ascent + pcm->descent);
+                       if (top > highest)
+                         highest = top;
+                       if (bottom < lowest)
+                         lowest = bottom;
+                       y_offset = bottom + pcm->descent;
+                       x_offset = (cmpcharp->col_offset[gidx]
+                                   * FONT_WIDTH (f->output_data.x->font));
+                     }
+                   XDrawString16 (FRAME_X_DISPLAY (f), window, gc,
+                                  left + x_offset, top + baseline - y_offset,
+                                  x_2byte_buffer + i, 1);
+                 }
+             }
+           if (require_clipping)
+             XSetClipMask (FRAME_X_DISPLAY (f), gc, None);
 
 #if 0 /* Doesn't work, because it uses FRAME_CURRENT_GLYPHS,
         which often is not up to date yet.  */
-       if (!just_foreground)
+           if (!just_foreground)
+             {
+               if (left == orig_left)
+                 redraw_previous_char (f, PIXEL_TO_CHAR_COL (f, left),
+                                       PIXEL_TO_CHAR_ROW (f, top), hl == 1);
+               if (n == 0)
+                 redraw_following_char (f, PIXEL_TO_CHAR_COL (f, left + len * FONT_WIDTH (font)),
+                                        PIXEL_TO_CHAR_ROW (f, top), hl == 1);
+             }
+#endif
+         }
+       if (!font)
+         {
+           /* Show rectangles to indicate that we found no font.  */
+           int limit = cmpcharp ? 1 : len;
+
+           for (i = 0; i < limit; i++)
+             XDrawRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
+                             left + glyph_width * i, top,
+                             glyph_width - 1, line_height - 1);
+         }
+       else if (require_clipping && !NILP (Vhighlight_wrong_size_font))
          {
-           if (left == orig_left)
-             redraw_previous_char (f, PIXEL_TO_CHAR_COL (f, left),
-                                   PIXEL_TO_CHAR_ROW (f, top), hl == 1);
-           if (n == 0)
-             redraw_following_char (f, PIXEL_TO_CHAR_COL (f, left + len * FONT_WIDTH (font)),
-                                    PIXEL_TO_CHAR_ROW (f, top), hl == 1);
+           /* Show ??? to indicate that we found a font of
+               inappropriate size.  */
+           int limit = cmpcharp ? 1 : len;
+
+           for (i = 0; i < limit; i++)
+             {
+               XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
+                          left + glyph_width * i, top + line_height - 1,
+                          left + glyph_width * i + 1, top + line_height - 1);
+               XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
+                          left + glyph_width * i, top + line_height - 3,
+                          left + glyph_width * i, top + line_height - 1);
+             }
          }
-#endif
 
        /* We should probably check for XA_UNDERLINE_POSITION and
           XA_UNDERLINE_THICKNESS properties on the font, but let's
           just get the thing working, and come back to that.  */
        {
-         int underline_position = 1;
+         /* Setting underline position based on the metric of the
+            current font results in shaky underline if it strides
+            over different fonts.  So, we set the position based only
+            on the default font of this frame.  */
+         int underline_position = f->output_data.x->font_baseline + 1;
 
-         if (font->descent <= underline_position)
-           underline_position = font->descent - 1;
+         if (underline_position >= line_height)
+           underline_position = line_height - 1;
 
          if (face->underline)
            XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                            FACE_GC (face),
-                           left, (top
-                                  + FONT_BASE (font)
-                                  + underline_position),
-                           len * FONT_WIDTH (font), 1);
+                           left, top + underline_position, run_width, 1);
        }
 
-       left += len * FONT_WIDTH (font);
+       if (!cmpcharp)
+         left += run_width;
       }
     }
+
+  return (left - orig_left);
 }
 #endif /* 1 */
 
@@ -771,7 +1186,7 @@ dumpglyphs (f, left, top, gp, n, hl, font)
    `highlight', set up by XTreassert_line_highlight or XTchange_line_highlight,
    controls the pixel values used for foreground and background.  */
 
-static
+static void
 XTwrite_glyphs (start, len)
      register GLYPH *start;
      int len;
@@ -796,13 +1211,13 @@ XTwrite_glyphs (start, len)
   dumpglyphs (f,
              CHAR_TO_PIXEL_COL (f, curs_x),
              CHAR_TO_PIXEL_ROW (f, curs_y),
-             start, len, highlight, 0);
+             start, len, highlight, 0, NULL);
 
   /* If we drew on top of the cursor, note that it is turned off.  */
   if (curs_y == f->phys_cursor_y
       && curs_x <= f->phys_cursor_x
       && curs_x + len > f->phys_cursor_x)
-    f->phys_cursor_x = -1;
+    f->phys_cursor_on = 0;
 
   if (updating_frame == 0)
     x_display_cursor (f, 1, FRAME_CURSOR_X (f) + len, FRAME_CURSOR_Y (f));
@@ -817,7 +1232,7 @@ XTwrite_glyphs (start, len)
    to column FIRST_UNUSED (exclusive).  The idea is that everything
    from FIRST_UNUSED onward is already erased.  */
 
-static
+static void
 XTclear_end_of_line (first_unused)
      register int first_unused;
 {
@@ -845,7 +1260,7 @@ XTclear_end_of_line (first_unused)
   if (curs_y == f->phys_cursor_y
       && curs_x <= f->phys_cursor_x
       && f->phys_cursor_x < first_unused)
-    f->phys_cursor_x = -1;
+    f->phys_cursor_on = 0;
 
   XClearArea (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
              CHAR_TO_PIXEL_COL (f, curs_x),
@@ -859,7 +1274,7 @@ XTclear_end_of_line (first_unused)
   UNBLOCK_INPUT;
 }
 
-static
+static void
 XTclear_frame ()
 {
   int mask;
@@ -868,7 +1283,7 @@ XTclear_frame ()
   if (f == 0)
     f = selected_frame;
 
-  f->phys_cursor_x = -1;       /* Cursor not visible.  */
+  f->phys_cursor_on = 0;       /* Cursor not visible.  */
   curs_x = 0;                  /* Nominal cursor position is top left.  */
   curs_y = 0;
 
@@ -923,7 +1338,7 @@ redraw_previous_char (f, x, y, highlight_flag)
       dumpglyphs (f, CHAR_TO_PIXEL_COL (f, start_x),
                  CHAR_TO_PIXEL_ROW (f, y),
                  &FRAME_CURRENT_GLYPHS (f)->glyphs[y][start_x],
-                 x - start_x, highlight_flag, 1);
+                 x - start_x, highlight_flag, 1, NULL);
     }
 }
 
@@ -959,7 +1374,7 @@ redraw_following_char (f, x, y, highlight_flag)
       dumpglyphs (f, CHAR_TO_PIXEL_COL (f, x),
                  CHAR_TO_PIXEL_ROW (f, y),
                  &FRAME_CURRENT_GLYPHS (f)->glyphs[y][x],
-                 end_x - x, highlight_flag, 1);
+                 end_x - x, highlight_flag, 1, NULL);
     }
 }
 #endif /* 0 */
@@ -1095,6 +1510,7 @@ timeval_subtract (result, x, y)
   return x.tv_sec < y.tv_sec;
 }
 
+void
 XTflash (f)
      struct frame *f;
 {
@@ -1222,6 +1638,7 @@ XTflash (f)
 
 #define XRINGBELL XBell (FRAME_X_DISPLAY (selected_frame), 0)
 
+void
 XTring_bell ()
 {
   if (FRAME_X_DISPLAY (selected_frame) == 0)
@@ -1244,7 +1661,7 @@ XTring_bell ()
    These are not supposed to be used because we are supposed to turn
    off the feature of using them.  */
 
-static
+static void
 XTinsert_glyphs (start, len)
      register char *start;
      register int len;
@@ -1252,7 +1669,7 @@ XTinsert_glyphs (start, len)
   abort ();
 }
 
-static
+static void
 XTdelete_glyphs (n)
      register int n;
 {
@@ -1264,7 +1681,7 @@ XTdelete_glyphs (n)
    This, and those operations, are used only within an update
    that is bounded by calls to XTupdate_begin and XTupdate_end.  */
 
-static
+static void
 XTset_terminal_window (n)
      register int n;
 {
@@ -1295,6 +1712,7 @@ static int line_dance_in_progress;
 
 /* Perform an insert-lines or delete-lines operation,
    inserting N lines or deleting -N lines at vertical position VPOS.  */
+void
 XTins_del_lines (vpos, n)
      int vpos, n;
 {
@@ -1476,11 +1894,19 @@ dumprectangle (f, left, top, cols, rows)
       if (! active_frame->enable[y] || left > active_frame->used[y])
        continue;
 
+      while (*line & GLYPH_MASK_PADDING)
+       {
+         /* We must display the whole glyph of a wide-column
+             character.  */
+         left--;
+         line--;
+         cols++;
+       }
       dumpglyphs (f,
                  CHAR_TO_PIXEL_COL (f, left),
                  CHAR_TO_PIXEL_ROW (f, y),
                  line, min (cols, active_frame->used[y] - left),
-                 active_frame->highlight[y], 0);
+                 active_frame->highlight[y], 0, NULL);
     }
 
   /* Turn the cursor on if we turned it off.  */
@@ -1869,7 +2295,7 @@ construct_menu_click (result, event, f)
   /* Make the event type no_event; we'll change that when we decide
      otherwise.  */
   result->kind = mouse_click;
-  XSETINT (result->code, event->button - Button1);
+  result->code = event->button - Button1;
   result->timestamp = event->time;
   result->modifiers = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
                                               event->state)
@@ -1969,8 +2395,9 @@ note_mouse_highlight (f, x, y)
   if (WINDOWP (window) && portion == 0 && row >= 0 && column >= 0
       && row < FRAME_HEIGHT (f) && column < FRAME_WIDTH (f)
       && EQ (w->window_end_valid, w->buffer)
-      && w->last_modified == BUF_MODIFF (XBUFFER (w->buffer))
-      && w->last_overlay_modified == BUF_OVERLAY_MODIFF (XBUFFER (w->buffer)))
+      && XFASTINT (w->last_modified) == BUF_MODIFF (XBUFFER (w->buffer))
+      && (XFASTINT (w->last_overlay_modified)
+         == BUF_OVERLAY_MODIFF (XBUFFER (w->buffer))))
     {
       int *ptr = FRAME_CURRENT_GLYPHS (f)->charstarts[row];
       int i, pos;
@@ -2022,7 +2449,7 @@ note_mouse_highlight (f, x, y)
 
          /* Put all the overlays we want in a vector in overlay_vec.
             Store the length in len.  */
-         noverlays = overlays_at (XINT (pos), 1, &overlay_vec, &len,
+         noverlays = overlays_at (pos, 1, &overlay_vec, &len,
                                   NULL, NULL);
          noverlays = sort_overlays (overlay_vec, noverlays, w);
 
@@ -2129,7 +2556,7 @@ fast_find_position (window, pos, columnp, rowp)
   int i;
   int row = 0;
   int left = WINDOW_LEFT_MARGIN (w);
-  int top = w->top;
+  int top = XFASTINT (w->top);
   int height = XFASTINT (w->height) - ! MINI_WINDOW_P (w);
   int width = window_internal_width (w);
   int *charstarts;
@@ -2199,7 +2626,14 @@ show_mouse_face (dpyinfo, hl)
   FRAME_PTR f = XFRAME (WINDOW_FRAME (w));
   int i;
   int cursor_off = 0;
-
+  int old_curs_x = curs_x;
+  int old_curs_y = curs_y;
+
+  /* Set these variables temporarily
+     so that if we have to turn the cursor off and on again
+     we will put it back at the same place.  */
+  curs_x = f->phys_cursor_x;
+  curs_y = f->phys_cursor_y;  
   for (i = FRAME_X_DISPLAY_INFO (f)->mouse_face_beg_row;
        i <= FRAME_X_DISPLAY_INFO (f)->mouse_face_end_row; i++)
     {
@@ -2227,12 +2661,15 @@ show_mouse_face (dpyinfo, hl)
                  FRAME_CURRENT_GLYPHS (f)->glyphs[i] + column,
                  endcolumn - column,
                  /* Highlight with mouse face if hl > 0.  */
-                 hl > 0 ? 3 : 0, 0);
+                 hl > 0 ? 3 : 0, 0, NULL);
     }
 
   /* If we turned the cursor off, turn it back on.  */
   if (cursor_off)
-    x_update_cursor (f, 1);
+    x_display_cursor (f, 1, curs_x, curs_y);
+
+  curs_x = old_curs_x;
+  curs_y = old_curs_y;
 
   /* Change the mouse cursor according to the value of HL.  */
   if (hl > 0)
@@ -2257,6 +2694,25 @@ clear_mouse_face (dpyinfo)
   dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
   dpyinfo->mouse_face_window = Qnil;
 }
+
+/* Just discard the mouse face information for frame F, if any.
+   This is used when the size of F is changed.  */
+
+void
+cancel_mouse_face (f)
+     FRAME_PTR f;
+{
+  Lisp_Object window;
+  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
+
+  window = dpyinfo->mouse_face_window;
+  if (! NILP (window) && XFRAME (XWINDOW (window)->frame) == f)
+    {
+      dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
+      dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
+      dpyinfo->mouse_face_window = Qnil;
+    }
+}
 \f
 static struct scroll_bar *x_window_to_scroll_bar ();
 static void x_scroll_bar_report_motion ();
@@ -2294,7 +2750,7 @@ XTmouse_position (fp, insist, bar_window, part, x, y, time)
 
   BLOCK_INPUT;
 
-  if (! NILP (last_mouse_scroll_bar))
+  if (! NILP (last_mouse_scroll_bar) && insist == 0)
     x_scroll_bar_report_motion (fp, bar_window, part, x, y, time);
   else
     {
@@ -2340,6 +2796,7 @@ XTmouse_position (fp, insist, bar_window, part, x, y, time)
        Window win, child;
        int win_x, win_y;
        int parent_x, parent_y;
+       int count;
 
        win = root;
 
@@ -2347,7 +2804,7 @@ XTmouse_position (fp, insist, bar_window, part, x, y, time)
           structure is changing at the same time this function
           is running.  So at least we must not crash from them.  */
 
-       x_catch_errors (FRAME_X_DISPLAY (*fp));
+       count = x_catch_errors (FRAME_X_DISPLAY (*fp));
 
        if (FRAME_X_DISPLAY_INFO (*fp)->grabbed && last_mouse_frame
            && FRAME_LIVE_P (last_mouse_frame))
@@ -2407,7 +2864,7 @@ XTmouse_position (fp, insist, bar_window, part, x, y, time)
        if (x_had_errors_p (FRAME_X_DISPLAY (*fp)))
          f1 = 0;
 
-       x_uncatch_errors (FRAME_X_DISPLAY (*fp));
+       x_uncatch_errors (FRAME_X_DISPLAY (*fp), count);
 
        /* If not, is it one of our scroll bars?  */
        if (! f1)
@@ -2422,7 +2879,7 @@ XTmouse_position (fp, insist, bar_window, part, x, y, time)
              }
          }
 
-       if (f1 == 0 && insist)
+       if (f1 == 0 && insist > 0)
          f1 = selected_frame;
 
        if (f1)
@@ -3109,6 +3566,7 @@ x_scroll_bar_report_motion (fp, bar_window, part, x, y, time)
    Clear out the scroll bars, and ask for expose events, so we can
    redraw them.  */
 
+void
 x_scroll_bar_clear (f)
      FRAME_PTR f;
 {
@@ -3145,6 +3603,7 @@ process_expose_from_menu (event)
        {
          f->async_visible = 1;
          f->async_iconified = 0;
+         f->output_data.x->has_been_visible = 1;
          SET_FRAME_GARBAGED (f);
        }
       else
@@ -3395,20 +3854,32 @@ XTread_socket (sd, bufp, numchars, expected)
                    if (event.xclient.data.l[0]
                        == dpyinfo->Xatom_wm_take_focus)
                      {
-                       f = x_window_to_frame (dpyinfo, event.xclient.window);
-                       /* Since we set WM_TAKE_FOCUS, we must call
-                          XSetInputFocus explicitly.  But not if f is null,
-                          since that might be an event for a deleted frame.  */
+                       /* Use x_any_window_to_frame because this
+                          could be the shell widget window
+                          if the frame has no title bar.  */
+                       f = x_any_window_to_frame (dpyinfo, event.xclient.window);
 #ifdef HAVE_X_I18N
                        /* Not quite sure this is needed -pd */
-                       if (f)
+                       if (f && FRAME_XIC (f))
                          XSetICFocus (FRAME_XIC (f));
 #endif
+                       /* Since we set WM_TAKE_FOCUS, we must call
+                          XSetInputFocus explicitly.  But not if f is null,
+                          since that might be an event for a deleted frame.  */
                        if (f)
-                         XSetInputFocus (event.xclient.display,
-                                         event.xclient.window,
-                                         RevertToPointerRoot,
-                                         event.xclient.data.l[1]);
+                         {
+                           Display *d = event.xclient.display;
+                           /* Catch and ignore errors, in case window has been
+                              iconified by a window manager such as GWM.  */
+                           int count = x_catch_errors (d);
+                           XSetInputFocus (d, event.xclient.window,
+                                           RevertToPointerRoot,
+                                           event.xclient.data.l[1]);
+                           /* This is needed to detect the error
+                              if there is an error.  */
+                           XSync (d, False);
+                           x_uncatch_errors (d, count);
+                         }  
                        /* Not certain about handling scroll bars here */
                      }
                    else if (event.xclient.data.l[0]
@@ -3495,7 +3966,7 @@ XTread_socket (sd, bufp, numchars, expected)
              if (! x_window_to_frame (dpyinfo, event.xselection.requestor))
                goto OTHER;
 #endif /* not USE_X_TOOLKIT */
-             x_handle_selection_notify (&event);
+             x_handle_selection_notify (&event.xselection);
              break;
 
            case SelectionClear:        /* Someone has grabbed ownership. */
@@ -3556,7 +4027,7 @@ XTread_socket (sd, bufp, numchars, expected)
              if (!x_any_window_to_frame (dpyinfo, event.xproperty.window))
                goto OTHER;
 #endif /* not USE_X_TOOLKIT */
-             x_handle_property_notify (&event);
+             x_handle_property_notify (&event.xproperty);
              break;
 
            case ReparentNotify:
@@ -3579,6 +4050,7 @@ XTread_socket (sd, bufp, numchars, expected)
                    {
                      f->async_visible = 1;
                      f->async_iconified = 0;
+                     f->output_data.x->has_been_visible = 1;
                      SET_FRAME_GARBAGED (f);
                    }
                  else
@@ -3635,15 +4107,19 @@ XTread_socket (sd, bufp, numchars, expected)
                  /* We can't distinguish, from the event, whether the window
                     has become iconified or invisible.  So assume, if it
                     was previously visible, than now it is iconified.
-                    We depend on x_make_frame_invisible to mark it invisible.  */
+                    But x_make_frame_invisible clears both
+                    the visible flag and the iconified flag;
+                    and that way, we know the window is not iconified now.  */
                  if (FRAME_VISIBLE_P (f) || FRAME_ICONIFIED_P (f))
-                   f->async_iconified = 1;
+                   {
+                     f->async_iconified = 1;
 
-                 bufp->kind = iconify_event;
-                 XSETFRAME (bufp->frame_or_window, f);
-                 bufp++;
-                 count++;
-                 numchars--;
+                     bufp->kind = iconify_event;
+                     XSETFRAME (bufp->frame_or_window, f);
+                     bufp++;
+                     count++;
+                     numchars--;
+                   }
                }
              goto OTHER;
 
@@ -3655,6 +4131,7 @@ XTread_socket (sd, bufp, numchars, expected)
                {
                  f->async_visible = 1;
                  f->async_iconified = 0;
+                 f->output_data.x->has_been_visible = 1;
 
                  /* wait_reading_process_input will notice this and update
                     the frame's display structures.  */
@@ -3668,7 +4145,7 @@ XTread_socket (sd, bufp, numchars, expected)
                      count++;
                      numchars--;
                    }
-                 else if (! NILP(Vframe_list)
+                 else if (! NILP (Vframe_list)
                           && ! NILP (XCONS (Vframe_list)->cdr))
                    /* Force a redisplay sooner or later
                       to update the frame titles
@@ -3722,9 +4199,21 @@ XTread_socket (sd, bufp, numchars, expected)
                                        | dpyinfo->hyper_mod_mask
                                        | dpyinfo->alt_mod_mask);
 
+                 /* In case Meta is ComposeCharacter,
+                    clear its status.  According to Markus Ehrnsperger
+                    Markus.Ehrnsperger@lehrstuhl-bross.physik.uni-muenchen.de
+                    this enables ComposeCharacter to work whether or
+                    not it is combined with Meta.  */
+                 if (modifiers & dpyinfo->meta_mod_mask)
+                   bzero (&compose_status, sizeof (compose_status));
+
 #ifdef HAVE_X_I18N
                  if (FRAME_XIC (f))
                    {
+                     /* The necessity of the following line took me
+                        a full work-day to decipher from the docs!!  */
+                     if (XFilterEvent (&event, None))
+                       break;
                      nbytes = XmbLookupString (FRAME_XIC (f),
                                                &event.xkey, copy_buffer,
                                                80, &keysym,
@@ -3744,6 +4233,9 @@ XTread_socket (sd, bufp, numchars, expected)
                    {
                      if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
                           || keysym == XK_Delete
+#ifdef XK_ISO_Left_Tab
+                          || (keysym >= XK_ISO_Left_Tab && keysym <= XK_ISO_Enter)
+#endif
                           || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
                           || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
 #ifdef HPUX
@@ -3955,12 +4447,8 @@ XTread_socket (sd, bufp, numchars, expected)
              goto OTHER;
 
            case ConfigureNotify:
-             f = x_any_window_to_frame (dpyinfo, event.xconfigure.window);
-             if (f
-#ifdef USE_X_TOOLKIT
-                 && (event.xconfigure.window == XtWindow (f->output_data.x->widget))
-#endif
-                 )
+             f = x_top_window_to_frame (dpyinfo, event.xconfigure.window);
+             if (f)
                {
 #ifndef USE_X_TOOLKIT
                  /* In the toolkit version, change_frame_size
@@ -3980,66 +4468,35 @@ XTread_socket (sd, bufp, numchars, expected)
                    {
                      change_frame_size (f, rows, columns, 0, 1);
                      SET_FRAME_GARBAGED (f);
+                     cancel_mouse_face (f);
                    }
 #endif
 
-                 /* Formerly, in the USE_X_TOOLKIT version,
-                    we did not test send_event here.  */
-                 if (1
-#ifndef USE_X_TOOLKIT
-                     && ! event.xconfigure.send_event
-#endif
-                     )
-                   {
-                     Window win, child;
-                     int win_x, win_y;
-
-                     /* Find the position of the outside upper-left corner of
-                        the window, in the root coordinate system.  Don't
-                        refer to the parent window here; we may be processing
-                        this event after the window manager has changed our
-                        parent, but before we have reached the ReparentNotify.  */
-                     XTranslateCoordinates (FRAME_X_DISPLAY (f),
-
-                                            /* From-window, to-window.  */
-                                            event.xconfigure.window,
-                                            FRAME_X_DISPLAY_INFO (f)->root_window,
-
-                                            /* From-position, to-position.  */
-                                            -event.xconfigure.border_width,
-                                            -event.xconfigure.border_width,
-                                            &win_x, &win_y,
-
-                                            /* Child of win.  */
-                                            &child);
-                     event.xconfigure.x = win_x;
-                     event.xconfigure.y = win_y;
-                   }
-
                  f->output_data.x->pixel_width = event.xconfigure.width;
                  f->output_data.x->pixel_height = event.xconfigure.height;
-                 f->output_data.x->left_pos = event.xconfigure.x;
-                 f->output_data.x->top_pos = event.xconfigure.y;
 
                  /* What we have now is the position of Emacs's own window.
                     Convert that to the position of the window manager window.  */
-                 {
-                   int x, y;
-                   x_real_positions (f, &x, &y);
-                   f->output_data.x->left_pos = x;
-                   f->output_data.x->top_pos = y;
-                   /* Formerly we did not do this in the USE_X_TOOLKIT
-                      version.  Let's try making them the same.  */
-/* #ifndef USE_X_TOOLKIT */
-                   if (y != event.xconfigure.y)
-                     {
-                       /* Since the WM decorations come below top_pos now,
-                          we must put them below top_pos in the future.  */
-                       f->output_data.x->win_gravity = NorthWestGravity;
-                       x_wm_set_size_hint (f, (long) 0, 0);
-                     }
-/* #endif */
-                 }
+                 x_real_positions (f, &f->output_data.x->left_pos,
+                                   &f->output_data.x->top_pos);
+
+                 if (f->output_data.x->parent_desc != FRAME_X_DISPLAY_INFO (f)->root_window)
+                   {
+                     /* Since the WM decorations come below top_pos now,
+                        we must put them below top_pos in the future.  */
+                     f->output_data.x->win_gravity = NorthWestGravity;
+                     x_wm_set_size_hint (f, (long) 0, 0);
+                   }
+#ifdef USE_MOTIF
+                 /* Some window managers pass (0,0) as the location of
+                    the window, and the Motif event handler stores it
+                    in the emacs widget, which messes up Motif menus.  */
+                 if (event.xconfigure.x == 0 && event.xconfigure.y == 0)
+                   {
+                     event.xconfigure.x = f->output_data.x->widget->core.x;
+                     event.xconfigure.y = f->output_data.x->widget->core.y;
+                   }
+#endif
                }
              goto OTHER;
 
@@ -4217,9 +4674,30 @@ x_draw_box (f, x, y)
   int top  = CHAR_TO_PIXEL_ROW (f, y);
   int width = FONT_WIDTH (f->output_data.x->font);
   int height = f->output_data.x->line_height;
+  int c = FAST_GLYPH_CHAR (f->phys_cursor_glyph);
+  int charset = CHAR_CHARSET (c);
+
+  XGCValues xgcv;
+  unsigned long mask = GCForeground;
+
+  xgcv.foreground = f->output_data.x->cursor_pixel;
 
+  /* cursor_gc's foreground color is typically the same as the normal
+     background color, which can cause the cursor box to be invisible.  */
+  if (FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc)
+    XChangeGC (FRAME_X_DISPLAY (f),
+               FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc,
+               mask, &xgcv);
+  else
+    FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc
+      = XCreateGC (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), mask, &xgcv);
+
+  /* If cursor is on a multi-column character, multiply WIDTH by columns.  */
+  width *= (charset == CHARSET_COMPOSITION
+           ? cmpchar_table[COMPOSITE_CHAR_ID (c)]->width
+           : CHARSET_WIDTH (charset));
   XDrawRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
-                 f->output_data.x->cursor_gc,
+                  FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc,
                  left, top, width - 1, height - 1);
 }
 
@@ -4235,11 +4713,11 @@ clear_cursor (f)
   int mask;
 
   if (! FRAME_VISIBLE_P (f)
-      || f->phys_cursor_x < 0)
+      || ! f->phys_cursor_on)
     return;
 
   x_update_cursor (f, 0);
-  f->phys_cursor_x = -1;
+  f->phys_cursor_on = 0;
 }
 
 /* Redraw the glyph at ROW, COLUMN on frame F, in the style
@@ -4256,7 +4734,7 @@ x_draw_single_glyph (f, row, column, glyph, highlight)
   dumpglyphs (f,
              CHAR_TO_PIXEL_COL (f, column),
              CHAR_TO_PIXEL_ROW (f, row),
-             &glyph, 1, highlight, 0);
+             &glyph, 1, highlight, 0, NULL);
 }
 
 static void
@@ -4273,11 +4751,11 @@ x_display_bar_cursor (f, on, x, y)
   if (! FRAME_VISIBLE_P (f) || FRAME_GARBAGED_P (f))
     return;
 
-  if (! on && f->phys_cursor_x < 0)
+  if (! on && ! f->phys_cursor_on)
     return;
 
   /* If there is anything wrong with the current cursor state, remove it.  */
-  if (f->phys_cursor_x >= 0
+  if (f->phys_cursor_on
       && (!on
          || f->phys_cursor_x != x
          || f->phys_cursor_y != y
@@ -4287,12 +4765,12 @@ x_display_bar_cursor (f, on, x, y)
       x_draw_single_glyph (f, f->phys_cursor_y, f->phys_cursor_x,
                           f->phys_cursor_glyph,
                           current_glyphs->highlight[f->phys_cursor_y]);
-      f->phys_cursor_x = -1;
+      f->phys_cursor_on = 0;
     }
 
   /* If we now need a cursor in the new place or in the new form, do it so.  */
   if (on
-      && (f->phys_cursor_x < 0
+      && (! f->phys_cursor_on
          || (f->output_data.x->current_cursor != bar_cursor)))
     {
       f->phys_cursor_glyph
@@ -4309,6 +4787,7 @@ x_display_bar_cursor (f, on, x, y)
 
       f->phys_cursor_x = x;
       f->phys_cursor_y = y;
+      f->phys_cursor_on = 1;
 
       f->output_data.x->current_cursor = bar_cursor;
     }
@@ -4336,14 +4815,14 @@ x_display_box_cursor (f, on, x, y)
     return;
 
   /* If cursor is off and we want it off, return quickly.  */
-  if (!on && f->phys_cursor_x < 0)
+  if (!on && ! f->phys_cursor_on)
     return;
 
   /* If cursor is currently being shown and we don't want it to be
      or it is in the wrong place,
      or we want a hollow box and it's not so, (pout!)
      erase it.  */
-  if (f->phys_cursor_x >= 0
+  if (f->phys_cursor_on
       && (!on
          || f->phys_cursor_x != x
          || f->phys_cursor_y != y
@@ -4384,14 +4863,14 @@ x_display_box_cursor (f, on, x, y)
                           (mouse_face_here
                            ? 3
                            : current_glyphs->highlight[f->phys_cursor_y]));
-      f->phys_cursor_x = -1;
+      f->phys_cursor_on = 0;
     }
 
   /* If we want to show a cursor,
      or we want a box cursor and it's not so,
      write it in the right place.  */
   if (on
-      && (f->phys_cursor_x < 0
+      && (! f->phys_cursor_on
          || (f->output_data.x->current_cursor != filled_box_cursor
              && f == FRAME_X_DISPLAY_INFO (f)->x_highlight_frame)))
     {
@@ -4414,6 +4893,7 @@ x_display_box_cursor (f, on, x, y)
 
       f->phys_cursor_x = x;
       f->phys_cursor_y = y;
+      f->phys_cursor_on = 1;
     }
 
   if (updating_frame != f)
@@ -4423,6 +4903,7 @@ x_display_box_cursor (f, on, x, y)
 /* Display the cursor on frame F, or clear it, according to ON.
    Also set the frame's cursor position to X and Y.  */
 
+void
 x_display_cursor (f, on, x, y)
      struct frame *f;
      int on;
@@ -4430,6 +4911,10 @@ x_display_cursor (f, on, x, y)
 {
   BLOCK_INPUT;
 
+ if ((unsigned) x >= FRAME_WIDTH (f) + FRAME_LEFT_SCROLL_BAR_WIDTH (f)
+      || (unsigned) y >= FRAME_HEIGHT (f))
+    abort ();
+
   if (FRAME_DESIRED_CURSOR (f) == filled_box_cursor)
     x_display_box_cursor (f, on, x, y);
   else if (FRAME_DESIRED_CURSOR (f) == bar_cursor)
@@ -4444,15 +4929,11 @@ x_display_cursor (f, on, x, y)
 /* Display the cursor on frame F, or clear it, according to ON.
    Don't change the cursor's position.  */
 
+void
 x_update_cursor (f, on)
      struct frame *f;
      int on;
 {
-  /* If we don't have any previous cursor position to use,
-     leave the cursor off.  */
-  if (f->phys_cursor_x < 0)
-    return;
-
   BLOCK_INPUT;
 
   if (FRAME_DESIRED_CURSOR (f) == filled_box_cursor)
@@ -4471,6 +4952,7 @@ x_update_cursor (f, on)
 /* Refresh bitmap kitchen sink icon for frame F
    when we get an expose event for it. */
 
+void
 refreshicon (f)
      struct frame *f;
 {
@@ -4558,107 +5040,129 @@ x_text_icon (f, icon_name)
   return 0;
 }
 \f
-/* Handling X errors.  */
+#define X_ERROR_MESSAGE_SIZE 200
 
-/* Handle the loss of connection to display DISPLAY.  */
+/* If non-nil, this should be a string.
+   It means catch X errors  and store the error message in this string.  */
 
-static SIGTYPE
-x_connection_closed (display, error_message)
+static Lisp_Object x_error_message_string;
+
+/* An X error handler which stores the error message in
+   x_error_message_string.  This is called from x_error_handler if
+   x_catch_errors is in effect.  */
+
+static int
+x_error_catcher (display, error)
      Display *display;
-     char *error_message;
+     XErrorEvent *error;
 {
-  struct x_display_info *dpyinfo = x_display_info_for_display (display);
-  Lisp_Object frame, tail;
+  XGetErrorText (display, error->error_code,
+                XSTRING (x_error_message_string)->data,
+                X_ERROR_MESSAGE_SIZE);
+}
 
-  /* Indicate that this display is dead.  */
+/* Begin trapping X errors for display DPY.  Actually we trap X errors
+   for all displays, but DPY should be the display you are actually
+   operating on.
 
-  #ifdef USE_X_TOOLKIT
-  XtCloseDisplay (display);
-  #endif
+   After calling this function, X protocol errors no longer cause
+   Emacs to exit; instead, they are recorded in the string
+   stored in x_error_message_string.
 
-  dpyinfo->display = 0;
+   Calling x_check_errors signals an Emacs error if an X error has
+   occurred since the last call to x_catch_errors or x_check_errors.
 
-  /* First delete frames whose minibuffers are on frames
-     that are on the dead display.  */
-  FOR_EACH_FRAME (tail, frame)
-    {
-      Lisp_Object minibuf_frame;
-      minibuf_frame
-       = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
-      if (FRAME_X_P (XFRAME (frame))
-         && FRAME_X_P (XFRAME (minibuf_frame))
-         && ! EQ (frame, minibuf_frame)
-         && FRAME_X_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
-       Fdelete_frame (frame, Qt);
-    }
+   Calling x_uncatch_errors resumes the normal error handling.  */
 
-  /* Now delete all remaining frames on the dead display.
-     We are now sure none of these is used as the minibuffer
-     for another frame that we need to delete.  */
-  FOR_EACH_FRAME (tail, frame)
-    if (FRAME_X_P (XFRAME (frame))
-       && FRAME_X_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
-      {
-       /* Set this to t so that Fdelete_frame won't get confused
-          trying to find a replacement.  */
-       FRAME_KBOARD (XFRAME (frame))->Vdefault_minibuffer_frame = Qt;
-       Fdelete_frame (frame, Qt);
-      }
+void x_check_errors ();
+static Lisp_Object x_catch_errors_unwind ();
 
-  if (dpyinfo)
-    x_delete_display (dpyinfo);
+int
+x_catch_errors (dpy)
+     Display *dpy;
+{
+  int count = specpdl_ptr - specpdl;
 
-  if (x_display_list == 0)
-    {
-      fprintf (stderr, "%s\n", error_message);
-      shut_down_emacs (0, 0, Qnil);
-      exit (70);
-    }
+  /* Make sure any errors from previous requests have been dealt with.  */
+  XSync (dpy, False);
 
-  /* Ordinary stack unwind doesn't deal with these.  */
-#ifdef SIGIO
-  sigunblock (sigmask (SIGIO));
-#endif
-  sigunblock (sigmask (SIGALRM));
-  TOTALLY_UNBLOCK_INPUT;
+  record_unwind_protect (x_catch_errors_unwind, x_error_message_string);
 
-  clear_waiting_for_input ();
-  error ("%s", error_message);
+  x_error_message_string = make_uninit_string (X_ERROR_MESSAGE_SIZE);
+  XSTRING (x_error_message_string)->data[0] = 0;
+
+  return count;
 }
 
-/* This is the usual handler for X protocol errors.
-   It kills all frames on the display that we got the error for.
-   If that was the only one, it prints an error message and kills Emacs.  */
+/* Unbind the binding that we made to check for X errors.  */
 
-static int
-x_error_quitter (display, error)
-     Display *display;
-     XErrorEvent *error;
+static Lisp_Object
+x_catch_errors_unwind (old_val)
+     Lisp_Object old_val;
 {
-  char buf[256], buf1[356];
+  x_error_message_string = old_val;
+  return Qnil;
+}
 
-  /* Note that there is no real way portable across R3/R4 to get the
-     original error handler.  */
+/* If any X protocol errors have arrived since the last call to
+   x_catch_errors or x_check_errors, signal an Emacs error using
+   sprintf (a buffer, FORMAT, the x error message text) as the text.  */
 
-  XGetErrorText (display, error->error_code, buf, sizeof (buf));
-  sprintf (buf1, "X protocol error: %s on protocol request %d",
-          buf, error->request_code);
-  x_connection_closed (display, buf1);
+void
+x_check_errors (dpy, format)
+     Display *dpy;
+     char *format;
+{
+  /* Make sure to catch any errors incurred so far.  */
+  XSync (dpy, False);
+
+  if (XSTRING (x_error_message_string)->data[0])
+    error (format, XSTRING (x_error_message_string)->data);
 }
 
-/* This is the handler for X IO errors, always.
-   It kills all frames on the display that we lost touch with.
-   If that was the only one, it prints an error message and kills Emacs.  */
+/* Nonzero if we had any X protocol errors
+   since we did x_catch_errors on DPY.  */
 
-static int
-x_io_error_quitter (display)
-     Display *display;
+int
+x_had_errors_p (dpy)
+     Display *dpy;
 {
-  char buf[256];
+  /* Make sure to catch any errors incurred so far.  */
+  XSync (dpy, False);
 
-  sprintf (buf, "Connection lost to X server `%s'", DisplayString (display));
-  x_connection_closed (display, buf);
+  return XSTRING (x_error_message_string)->data[0] != 0;
 }
+
+/* Forget about any errors we have had, since we did x_catch_errors on DPY.  */
+
+int
+x_clear_errors (dpy)
+     Display *dpy;
+{
+  XSTRING (x_error_message_string)->data[0] = 0;
+}
+
+/* Stop catching X protocol errors and let them make Emacs die.
+   DPY should be the display that was passed to x_catch_errors.
+   COUNT should be the value that was returned by
+   the corresponding call to x_catch_errors.  */
+
+void
+x_uncatch_errors (dpy, count)
+     Display *dpy;
+     int count;
+{
+  unbind_to (count, Qnil);
+}
+
+#if 0
+static unsigned int x_wire_count;
+x_trace_wire ()
+{
+  fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
+}
+#endif /* ! 0 */
+
 \f
 /* Handle SIGPIPE, which can happen when the connection to a server
    simply goes away.  SIGPIPE is handled by x_connection_signal.
@@ -4677,107 +5181,123 @@ x_connection_signal (signalnum)       /* If we don't have an argument, */
 #endif /* USG */
 }
 \f
-/* A buffer for storing X error messages.  */
-static char *x_caught_error_message;
-#define X_CAUGHT_ERROR_MESSAGE_SIZE 200
+/* Handling X errors.  */
 
-/* An X error handler which stores the error message in
-   x_caught_error_message.  This is what's installed when
-   x_catch_errors is in effect.  */
+/* Handle the loss of connection to display DISPLAY.  */
 
-static int
-x_error_catcher (display, error)
+static SIGTYPE
+x_connection_closed (display, error_message)
      Display *display;
-     XErrorEvent *error;
+     char *error_message;
 {
-  XGetErrorText (display, error->error_code,
-                x_caught_error_message, X_CAUGHT_ERROR_MESSAGE_SIZE);
-}
+  struct x_display_info *dpyinfo = x_display_info_for_display (display);
+  Lisp_Object frame, tail;
 
+  /* Indicate that this display is dead.  */
 
-/* Begin trapping X errors for display DPY.  Actually we trap X errors
-   for all displays, but DPY should be the display you are actually
-   operating on.
+#ifdef USE_X_TOOLKIT
+  XtCloseDisplay (display);
+#endif
 
-   After calling this function, X protocol errors no longer cause
-   Emacs to exit; instead, they are recorded in x_cfc_error_message.
+  dpyinfo->display = 0;
 
-   Calling x_check_errors signals an Emacs error if an X error has
-   occurred since the last call to x_catch_errors or x_check_errors.
+  /* First delete frames whose minibuffers are on frames
+     that are on the dead display.  */
+  FOR_EACH_FRAME (tail, frame)
+    {
+      Lisp_Object minibuf_frame;
+      minibuf_frame
+       = WINDOW_FRAME (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
+      if (FRAME_X_P (XFRAME (frame))
+         && FRAME_X_P (XFRAME (minibuf_frame))
+         && ! EQ (frame, minibuf_frame)
+         && FRAME_X_DISPLAY_INFO (XFRAME (minibuf_frame)) == dpyinfo)
+       Fdelete_frame (frame, Qt);
+    }
 
-   Calling x_uncatch_errors resumes the normal error handling.  */
+  /* Now delete all remaining frames on the dead display.
+     We are now sure none of these is used as the minibuffer
+     for another frame that we need to delete.  */
+  FOR_EACH_FRAME (tail, frame)
+    if (FRAME_X_P (XFRAME (frame))
+       && FRAME_X_DISPLAY_INFO (XFRAME (frame)) == dpyinfo)
+      {
+       /* Set this to t so that Fdelete_frame won't get confused
+          trying to find a replacement.  */
+       FRAME_KBOARD (XFRAME (frame))->Vdefault_minibuffer_frame = Qt;
+       Fdelete_frame (frame, Qt);
+      }
 
-void x_catch_errors (), x_check_errors (), x_uncatch_errors ();
+  if (dpyinfo)
+    x_delete_display (dpyinfo);
 
-void
-x_catch_errors (dpy)
-     Display *dpy;
-{
-  /* Make sure any errors from previous requests have been dealt with.  */
-  XSync (dpy, False);
+  if (x_display_list == 0)
+    {
+      fprintf (stderr, "%s\n", error_message);
+      shut_down_emacs (0, 0, Qnil);
+      exit (70);
+    }
 
-  /* Set up the error buffer.  */
-  x_caught_error_message
-    = (char*) xmalloc (X_CAUGHT_ERROR_MESSAGE_SIZE);
-  x_caught_error_message[0] = '\0';
+  /* Ordinary stack unwind doesn't deal with these.  */
+#ifdef SIGIO
+  sigunblock (sigmask (SIGIO));
+#endif
+  sigunblock (sigmask (SIGALRM));
+  TOTALLY_UNBLOCK_INPUT;
 
-  /* Install our little error handler.  */
-  XSetErrorHandler (x_error_catcher);
+  clear_waiting_for_input ();
+  error ("%s", error_message);
 }
 
-/* If any X protocol errors have arrived since the last call to
-   x_catch_errors or x_check_errors, signal an Emacs error using
-   sprintf (a buffer, FORMAT, the x error message text) as the text.  */
+/* This is the usual handler for X protocol errors.
+   It kills all frames on the display that we got the error for.
+   If that was the only one, it prints an error message and kills Emacs.  */
 
-void
-x_check_errors (dpy, format)
-     Display *dpy;
-     char *format;
+static int
+x_error_quitter (display, error)
+     Display *display;
+     XErrorEvent *error;
 {
-  /* Make sure to catch any errors incurred so far.  */
-  XSync (dpy, False);
+  char buf[256], buf1[356];
 
-  if (x_caught_error_message[0])
-    {
-      char buf[X_CAUGHT_ERROR_MESSAGE_SIZE + 56];
+  /* Note that there is no real way portable across R3/R4 to get the
+     original error handler.  */
 
-      sprintf (buf, format, x_caught_error_message);
-      x_uncatch_errors (dpy);
-      error (buf);
-    }
+  XGetErrorText (display, error->error_code, buf, sizeof (buf));
+  sprintf (buf1, "X protocol error: %s on protocol request %d",
+          buf, error->request_code);
+  x_connection_closed (display, buf1);
 }
 
-/* Nonzero if we had any X protocol errors since we did x_catch_errors.  */
+/* This is the first-level handler for X protocol errors.
+   It calls x_error_quitter or x_error_catcher.  */
 
-int
-x_had_errors_p (dpy)
-     Display *dpy;
+static int
+x_error_handler (display, error)
+     Display *display;
+     XErrorEvent *error;
 {
-  /* Make sure to catch any errors incurred so far.  */
-  XSync (dpy, False);
+  char buf[256], buf1[356];
 
-  return x_caught_error_message[0] != 0;
+  if (! NILP (x_error_message_string))
+    x_error_catcher (display, error);
+  else
+    x_error_quitter (display, error);
 }
 
-/* Stop catching X protocol errors and let them make Emacs die.  */
+/* This is the handler for X IO errors, always.
+   It kills all frames on the display that we lost touch with.
+   If that was the only one, it prints an error message and kills Emacs.  */
 
-void
-x_uncatch_errors (dpy)
-     Display *dpy;
+static int
+x_io_error_quitter (display)
+     Display *display;
 {
-  xfree (x_caught_error_message);
-  x_caught_error_message = 0;
-  XSetErrorHandler (x_error_quitter);
-}
+  char buf[256];
 
-#if 0
-static unsigned int x_wire_count;
-x_trace_wire ()
-{
-  fprintf (stderr, "Lib call: %d\n", ++x_wire_count);
+  sprintf (buf, "Connection lost to X server `%s'", DisplayString (display));
+  x_connection_closed (display, buf);
 }
-#endif /* ! 0 */
-
 \f
 /* Changing the font of the frame.  */
 
@@ -4791,140 +5311,17 @@ x_new_font (f, fontname)
      struct frame *f;
      register char *fontname;
 {
-  int already_loaded;
-  int n_matching_fonts;
-  XFontStruct *font_info;
-  char **font_names;
-
-  /* Get a list of all the fonts that match this name.  Once we
-     have a list of matching fonts, we compare them against the fonts
-     we already have by comparing font ids.  */
-  font_names = (char **) XListFonts (FRAME_X_DISPLAY (f), fontname,
-                                    1024, &n_matching_fonts);
-  /* Apparently it doesn't set n_matching_fonts to zero when it can't
-     find any matches; font_names == 0 is the only clue.  */
-  if (! font_names)
-    n_matching_fonts = 0;
-
-  /* Don't just give up if n_matching_fonts is 0.
-     Apparently there's a bug on Suns: XListFontsWithInfo can
-     fail to find a font, but XLoadQueryFont may still find it.  */
-
-  /* See if we've already loaded a matching font. */
-  already_loaded = -1;
-  if (n_matching_fonts != 0)
-    {
-      int i, j;
-
-      for (i = 0; i < FRAME_X_DISPLAY_INFO (f)->n_fonts; i++)
-       for (j = 0; j < n_matching_fonts; j++)
-         if (!strcmp (FRAME_X_DISPLAY_INFO (f)->font_table[i].name, font_names[j])
-             || !strcmp (FRAME_X_DISPLAY_INFO (f)->font_table[i].full_name, font_names[j]))
-           {
-             already_loaded = i;
-             fontname = FRAME_X_DISPLAY_INFO (f)->font_table[i].full_name;
-             goto found_font;
-           }
-    }
- found_font:
-
-  /* If we have, just return it from the table.  */
-  if (already_loaded >= 0)
-    f->output_data.x->font = FRAME_X_DISPLAY_INFO (f)->font_table[already_loaded].font;
-  /* Otherwise, load the font and add it to the table.  */
-  else
-    {
-      int i;
-      char *full_name;
-      XFontStruct *font;
-      int n_fonts;
-
-      /* Try to find a character-cell font in the list.  */
-#if 0
-      /* A laudable goal, but this isn't how to do it.  */
-      for (i = 0; i < n_matching_fonts; i++)
-       if (! font_info[i].per_char)
-         break;
-#else
-      i = 0;
-#endif
-
-      /* See comment above.  */
-      if (n_matching_fonts != 0)
-       fontname = font_names[i];
-
-      font = (XFontStruct *) XLoadQueryFont (FRAME_X_DISPLAY (f), fontname);
-      if (! font)
-       {
-         /* Free the information from XListFonts.  */
-         if (n_matching_fonts)
-           XFreeFontNames (font_names);
-         return Qnil;
-       }
-
-      /* Do we need to create the table?  */
-      if (FRAME_X_DISPLAY_INFO (f)->font_table_size == 0)
-       {
-         FRAME_X_DISPLAY_INFO (f)->font_table_size = 16;
-         FRAME_X_DISPLAY_INFO (f)->font_table
-           = (struct font_info *) xmalloc (FRAME_X_DISPLAY_INFO (f)->font_table_size
-                                           * sizeof (struct font_info));
-       }
-      /* Do we need to grow the table?  */
-      else if (FRAME_X_DISPLAY_INFO (f)->n_fonts
-              >= FRAME_X_DISPLAY_INFO (f)->font_table_size)
-       {
-         FRAME_X_DISPLAY_INFO (f)->font_table_size *= 2;
-         FRAME_X_DISPLAY_INFO (f)->font_table
-           = (struct font_info *) xrealloc (FRAME_X_DISPLAY_INFO (f)->font_table,
-                                            (FRAME_X_DISPLAY_INFO (f)->font_table_size
-                                             * sizeof (struct font_info)));
-       }
-
-      /* Try to get the full name of FONT.  Put it in full_name.  */
-      full_name = 0;
-      for (i = 0; i < font->n_properties; i++)
-       {
-         if (FRAME_X_DISPLAY_INFO (f)->Xatom_FONT == font->properties[i].name)
-           {
-             char *name = XGetAtomName (FRAME_X_DISPLAY (f),
-                                        (Atom) (font->properties[i].card32));
-             char *p = name;
-             int dashes = 0;
-
-             /* Count the number of dashes in the "full name".
-                If it is too few, this isn't really the font's full name,
-                so don't use it.
-                In X11R4, the fonts did not come with their canonical names
-                stored in them.  */
-             while (*p)
-               {
-                 if (*p == '-')
-                   dashes++;
-                 p++;
-               }
-
-             if (dashes >= 13)
-               full_name = name;
-
-             break;
-           }
-       }
+  struct font_info *fontp
+    = fs_load_font (f, FRAME_X_FONT_TABLE (f), CHARSET_ASCII, fontname, -1);
 
-      n_fonts = FRAME_X_DISPLAY_INFO (f)->n_fonts;
-      FRAME_X_DISPLAY_INFO (f)->font_table[n_fonts].name = (char *) xmalloc (strlen (fontname) + 1);
-      bcopy (fontname, FRAME_X_DISPLAY_INFO (f)->font_table[n_fonts].name, strlen (fontname) + 1);
-      if (full_name != 0)
-       FRAME_X_DISPLAY_INFO (f)->font_table[n_fonts].full_name = full_name;
-      else
-       FRAME_X_DISPLAY_INFO (f)->font_table[n_fonts].full_name = FRAME_X_DISPLAY_INFO (f)->font_table[n_fonts].name;
-      f->output_data.x->font = FRAME_X_DISPLAY_INFO (f)->font_table[n_fonts].font = font;
-      FRAME_X_DISPLAY_INFO (f)->n_fonts++;
-
-      if (full_name)
-       fontname = full_name;
-    }
+  if (!fontp)
+    return Qnil;
 
+  f->output_data.x->font = (XFontStruct *) (fontp->font);
+  f->output_data.x->font_baseline
+    = (f->output_data.x->font->ascent + fontp->baseline_offset);
+  f->output_data.x->fontset = -1;
+  
   /* Compute the scroll bar width in character columns.  */
   if (f->scroll_bar_pixel_width > 0)
     {
@@ -4932,7 +5329,10 @@ x_new_font (f, fontname)
       f->scroll_bar_cols = (f->scroll_bar_pixel_width + wid-1) / wid;
     }
   else
-    f->scroll_bar_cols = 2;
+    {
+      int wid = FONT_WIDTH (f->output_data.x->font);
+      f->scroll_bar_cols = (14 + wid - 1) / wid;
+    }
 
   /* Now make the frame display the given font.  */
   if (FRAME_X_WINDOW (f) != 0)
@@ -4952,22 +5352,55 @@ x_new_font (f, fontname)
        there are no faces yet, so this font's height is the line height.  */
     f->output_data.x->line_height = FONT_HEIGHT (f->output_data.x->font);
 
-  {
-    Lisp_Object lispy_name;
+  return build_string (fontp->full_name);
+}
 
-    lispy_name = build_string (fontname);
+/* Give frame F the fontset named FONTSETNAME as its default font, and
+   return the full name of that fontset.  FONTSETNAME may be a wildcard
+   pattern; in that case, we choose some fontset that fits the pattern.
+   The return value shows which fontset we chose.  */
 
-    /* Free the information from XListFonts.  The data
-       we actually retain comes from XLoadQueryFont.  */
-    XFreeFontNames (font_names);
+Lisp_Object
+x_new_fontset (f, fontsetname)
+     struct frame *f;
+     char *fontsetname;
+{
+  int fontset = fs_query_fontset (f, fontsetname);
+  struct fontset_info *fontsetp;
+  Lisp_Object result;
 
-    return lispy_name;
-  }
+  if (fontset < 0)
+    return Qnil;
+
+  if (f->output_data.x->fontset == fontset)
+    /* This fontset is already set in frame F.  There's nothing more
+       to do.  */
+    return build_string (fontsetname);
+
+  fontsetp = FRAME_FONTSET_DATA (f)->fontset_table[fontset];
+
+  if (!fontsetp->fontname[CHARSET_ASCII])
+    /* This fontset doesn't contain ASCII font.  */
+    return Qnil;
+
+  result = x_new_font (f, fontsetp->fontname[CHARSET_ASCII]);
+
+  if (!STRINGP (result))
+    /* Can't load ASCII font.  */
+    return Qnil;
+
+  /* Since x_new_font doesn't update any fontset information, do it now.  */
+  f->output_data.x->fontset = fontset;
+  FS_LOAD_FONT (f, FRAME_X_FONT_TABLE (f),
+               CHARSET_ASCII, XSTRING (result)->data, fontset);
+
+  return build_string (fontsetname);
 }
 \f
 /* Calculate the absolute position in frame F
    from its current recorded position values and gravity.  */
 
+void
 x_calc_absolute_position (f)
      struct frame *f;
 {
@@ -4976,6 +5409,11 @@ x_calc_absolute_position (f)
   int flags = f->output_data.x->size_hint_flags;
   int this_window;
 
+  /* We have nothing to do if the current position
+     is already for the top-left corner.  */
+  if (! ((flags & XNegative) || (flags & YNegative)))
+    return;
+
 #ifdef USE_X_TOOLKIT
   this_window = XtWindow (f->output_data.x->widget);
 #else
@@ -4983,21 +5421,47 @@ x_calc_absolute_position (f)
 #endif
 
   /* Find the position of the outside upper-left corner of
-     the inner window, with respect to the outer window.  */
+     the inner window, with respect to the outer window.
+     But do this only if we will need the results.  */
   if (f->output_data.x->parent_desc != FRAME_X_DISPLAY_INFO (f)->root_window)
     {
+      int count;
+
       BLOCK_INPUT;
-      XTranslateCoordinates (FRAME_X_DISPLAY (f),
+      count = x_catch_errors (FRAME_X_DISPLAY (f));
+      while (1)
+       {
+         x_clear_errors (FRAME_X_DISPLAY (f));
+         XTranslateCoordinates (FRAME_X_DISPLAY (f),
+
+                                /* From-window, to-window.  */
+                                this_window,
+                                f->output_data.x->parent_desc,
+
+                                /* From-position, to-position.  */
+                                0, 0, &win_x, &win_y,
+
+                                /* Child of win.  */
+                                &child);
+         if (x_had_errors_p (FRAME_X_DISPLAY (f)))
+           {
+             Window newroot, newparent = 0xdeadbeef;
+             Window *newchildren;
+             int nchildren;
 
-                            /* From-window, to-window.  */
-                            this_window,
-                            f->output_data.x->parent_desc,
+             if (! XQueryTree (FRAME_X_DISPLAY (f), this_window, &newroot,
+                               &newparent, &newchildren, &nchildren))
+               break;
 
-                            /* From-position, to-position.  */
-                            0, 0, &win_x, &win_y,
+             XFree (newchildren);
 
-                            /* Child of win.  */
-                            &child);
+             f->output_data.x->parent_desc = newparent;
+           }
+         else
+           break;
+       }
+
+      x_uncatch_errors (FRAME_X_DISPLAY (f), count);
       UNBLOCK_INPUT;
     }
 
@@ -5029,6 +5493,7 @@ x_calc_absolute_position (f)
    position values).  It is -1 when calling from x_set_frame_parameters,
    which means, do adjust for borders but don't change the gravity.  */
 
+void
 x_set_offset (f, xoff, yoff, change_gravity)
      struct frame *f;
      register int xoff, yoff;
@@ -5052,15 +5517,18 @@ x_set_offset (f, xoff, yoff, change_gravity)
   BLOCK_INPUT;
   x_wm_set_size_hint (f, (long) 0, 0);
 
-  /* It is a mystery why we need to add the border_width here
-     when the frame is already visible, but experiment says we do.  */
   modified_left = f->output_data.x->left_pos;
   modified_top = f->output_data.x->top_pos;
+#if 0 /* Running on psilocin (Debian), and displaying on the NCD X-terminal,
+        this seems to be unnecessary and incorrect.  rms, 4/17/97.  */
+  /* It is a mystery why we need to add the border_width here
+     when the frame is already visible, but experiment says we do.  */
   if (change_gravity != 0)
     {
       modified_left += f->output_data.x->border_width;
       modified_top += f->output_data.x->border_width;
     }
+#endif
 
 #ifdef USE_X_TOOLKIT
   XMoveWindow (FRAME_X_DISPLAY (f), XtWindow (f->output_data.x->widget),
@@ -5077,6 +5545,7 @@ x_set_offset (f, xoff, yoff, change_gravity)
    for this size change and subsequent size changes.
    Otherwise we leave the window gravity unchanged.  */
 
+void
 x_set_window_size (f, change_gravity, cols, rows)
      struct frame *f;
      int change_gravity;
@@ -5084,7 +5553,6 @@ x_set_window_size (f, change_gravity, cols, rows)
 {
   int pixelwidth, pixelheight;
   int mask;
-  Lisp_Object window;
   struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
 
   BLOCK_INPUT;
@@ -5149,21 +5617,16 @@ x_set_window_size (f, change_gravity, cols, rows)
   if (f->phys_cursor_y >= rows
       || f->phys_cursor_x >= cols)
     {
-      f->phys_cursor_x = -1;
-      f->phys_cursor_y = -1;
+      f->phys_cursor_x = 0;
+      f->phys_cursor_y = 0;
+      f->phys_cursor_on = 0;
     }
 
   /* Clear out any recollection of where the mouse highlighting was,
      since it might be in a place that's outside the new frame size. 
      Actually checking whether it is outside is a pain in the neck,
      so don't try--just let the highlighting be done afresh with new size.  */
-  window = dpyinfo->mouse_face_window;
-  if (! NILP (window) && XFRAME (window) == f)
-    {
-      dpyinfo->mouse_face_beg_row = dpyinfo->mouse_face_beg_col = -1;
-      dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
-      dpyinfo->mouse_face_window = Qnil;
-    }
+  cancel_mouse_face (f);
 
   UNBLOCK_INPUT;
 }
@@ -5209,6 +5672,7 @@ x_set_mouse_pixel_position (f, pix_x, pix_y)
 \f
 /* focus shifting, raising and lowering.  */
 
+void
 x_focus_on_frame (f)
      struct frame *f;
 {
@@ -5224,6 +5688,7 @@ x_focus_on_frame (f)
 #endif /* ! 0 */
 }
 
+void
 x_unfocus_frame (f)
      struct frame *f;
 {
@@ -5237,6 +5702,7 @@ x_unfocus_frame (f)
 
 /* Raise frame F.  */
 
+void
 x_raise_frame (f)
      struct frame *f;
 {
@@ -5255,6 +5721,7 @@ x_raise_frame (f)
 
 /* Lower frame F.  */
 
+void
 x_lower_frame (f)
      struct frame *f;
 {
@@ -5291,11 +5758,14 @@ XTframe_raise_lower (f, raise_flag)
    but it will become visible later when the window manager
    finishes with it.  */
 
+void
 x_make_frame_visible (f)
      struct frame *f;
 {
   int mask;
   Lisp_Object type;
+  int starting_flags = f->output_data.x->size_hint_flags;
+  int original_top, original_left;
 
   BLOCK_INPUT;
 
@@ -5339,10 +5809,44 @@ x_make_frame_visible (f)
   {
     Lisp_Object frame;
     int count = input_signal_count;
+    /* This must be before UNBLOCK_INPUT
+       since events that arrive in response to the actions above
+       will set it when they are handled.  */
+    int previously_visible = f->output_data.x->has_been_visible;
+
+    original_left = f->output_data.x->left_pos;
+    original_top = f->output_data.x->top_pos;
 
     /* This must come after we set COUNT.  */
     UNBLOCK_INPUT;
 
+    /* Arriving X events are processed here.  */
+
+    /* Now move the window back to where it was "supposed to be".
+       But don't do it if the gravity is negative.
+       When the gravity is negative, this uses a position
+       that is 3 pixels too low.  Perhaps that's really the border width.
+
+       Don't do this if the window has never been visible before,
+       because the window manager may choose the position
+       and we don't want to override it.  */
+
+    if (! FRAME_VISIBLE_P (f) && ! FRAME_ICONIFIED_P (f)
+       && f->output_data.x->win_gravity == NorthWestGravity
+       && previously_visible)
+      {
+       BLOCK_INPUT;
+
+#ifdef USE_X_TOOLKIT
+       XMoveWindow (FRAME_X_DISPLAY (f), XtWindow (f->output_data.x->widget),
+                    original_left, original_top);
+#else /* not USE_X_TOOLKIT */
+       XMoveWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
+                    original_left, original_top);
+#endif /* not USE_X_TOOLKIT */
+       UNBLOCK_INPUT;
+      }
+
     XSETFRAME (frame, f);
 
     while (1)
@@ -5365,7 +5869,7 @@ x_make_frame_visible (f)
            /* It could be confusing if a real alarm arrives while processing
               the fake one.  Turn it off and let the handler reset it.  */
            alarm (0);
-           input_poll_signal ();
+           input_poll_signal (0);
          }
        /* Once we have handled input events,
           we should have received the MapNotify if one is coming.
@@ -5383,6 +5887,7 @@ x_make_frame_visible (f)
 
 /* Make the frame visible (mapped and not iconified).  */
 
+void
 x_make_frame_invisible (f)
      struct frame *f;
 {
@@ -5465,6 +5970,7 @@ x_make_frame_invisible (f)
 
 /* Change window state from mapped to iconified. */
 
+void
 x_iconify_frame (f)
      struct frame *f;
 {
@@ -5499,7 +6005,9 @@ x_iconify_frame (f)
         that an invisible frame was changed to an icon,
         so we have to record it here.  */
       f->iconified = 1;
+      f->visible = 1;
       f->async_iconified = 1;
+      f->async_visible = 0;
       UNBLOCK_INPUT;
       return;
     }
@@ -5513,6 +6021,8 @@ x_iconify_frame (f)
     error ("Can't notify window manager of iconification");
 
   f->async_iconified = 1;
+  f->async_visible = 0;
+
 
   BLOCK_INPUT;
   XFlush (FRAME_X_DISPLAY (f));
@@ -5560,6 +6070,7 @@ x_iconify_frame (f)
     }
 
   f->async_iconified = 1;
+  f->async_visible = 0;
 
   XFlush (FRAME_X_DISPLAY (f));
   UNBLOCK_INPUT;
@@ -5568,6 +6079,7 @@ x_iconify_frame (f)
 \f
 /* Destroy the X window of frame F.  */
 
+void
 x_destroy_window (f)
      struct frame *f;
 {
@@ -5603,6 +6115,9 @@ x_destroy_window (f)
       XFlush (FRAME_X_DISPLAY (f));
     }
 
+  if (f->output_data.x->saved_menu_event)
+    free (f->output_data.x->saved_menu_event);
+
   xfree (f->output_data.x);
   f->output_data.x = 0;
   if (f == dpyinfo->x_focus_frame)
@@ -5621,6 +6136,8 @@ x_destroy_window (f)
       dpyinfo->mouse_face_end_row
        = dpyinfo->mouse_face_end_col = -1;
       dpyinfo->mouse_face_window = Qnil;
+      dpyinfo->mouse_face_deferred_gc = 0;
+      dpyinfo->mouse_face_mouse_frame = 0;
     }
 
   UNBLOCK_INPUT;
@@ -5634,6 +6151,7 @@ x_destroy_window (f)
    If USER_POSITION is nonzero, we set the USPosition
    flag (this is useful when FLAGS is 0).  */
 
+void
 x_wm_set_size_hint (f, flags, user_position)
      struct frame *f;
      long flags;
@@ -5777,6 +6295,7 @@ x_wm_set_size_hint (f, flags, user_position)
 }
 
 /* Used for IconicState or NormalState */
+void
 x_wm_set_window_state (f, state)
      struct frame *f;
      int state;
@@ -5796,6 +6315,7 @@ x_wm_set_window_state (f, state)
 #endif /* not USE_X_TOOLKIT */
 }
 
+void
 x_wm_set_icon_pixmap (f, pixmap_id)
      struct frame *f;
      int pixmap_id;
@@ -5845,6 +6365,7 @@ x_wm_set_icon_pixmap (f, pixmap_id)
 #endif /* not USE_X_TOOLKIT */
 }
 
+void
 x_wm_set_icon_position (f, icon_x, icon_y)
      struct frame *f;
      int icon_x, icon_y;
@@ -5863,6 +6384,405 @@ x_wm_set_icon_position (f, icon_x, icon_y)
 }
 
 \f
+/* Interface to fontset handler.  */
+
+/* Return a pointer to struct font_info of font FONT_IDX of frame F.  */
+struct font_info *
+x_get_font_info (f, font_idx)
+     FRAME_PTR f;
+     int font_idx;
+{
+  return (FRAME_X_FONT_TABLE (f) + font_idx);
+}
+
+
+/* Return a list of names of available fonts matching PATTERN on frame
+   F.  If SIZE is not 0, it is the size (maximum bound width) of fonts
+   to be listed.  Frame F NULL means we have not yet created any
+   frame on X, and consult the first display in x_display_list.
+   MAXNAMES sets a limit on how many fonts to match.  */
+
+Lisp_Object
+x_list_fonts (f, pattern, size, maxnames)
+     FRAME_PTR f;
+     Lisp_Object pattern;
+     int size;
+     int maxnames;
+{
+  Lisp_Object list = Qnil, patterns, newlist = Qnil, key, tem, second_best;
+  Display *dpy = f != NULL ? FRAME_X_DISPLAY (f) : x_display_list->display;
+
+  patterns = Fassoc (pattern, Valternate_fontname_alist);
+  if (NILP (patterns))
+    patterns = Fcons (pattern, Qnil);
+
+  /* We try at least 10 fonts because X server will return auto-scaled
+     fonts at the head.  */
+  if (maxnames < 10) maxnames = 10;
+
+  for (; CONSP (patterns); patterns = XCONS (patterns)->cdr)
+    {
+      int num_fonts;
+      char **names;
+
+      pattern = XCONS (patterns)->car;
+      /* See if we cached the result for this particular query.
+         The cache is an alist of the form:
+          (((PATTERN . MAXNAMES) (FONTNAME . WIDTH) ...) ...)
+      */
+      if (f && (tem = XCONS (FRAME_X_DISPLAY_INFO (f)->name_list_element)->cdr,
+               key = Fcons (pattern, make_number (maxnames)),
+               !NILP (list = Fassoc (key, tem))))
+       {
+         list = Fcdr_safe (list);
+         /* We have a cashed list.  Don't have to get the list again.  */
+         goto label_cached;
+       }
+
+      /* At first, put PATTERN in the cache.  */
+      BLOCK_INPUT;
+      names = XListFonts (dpy, XSTRING (pattern)->data, maxnames, &num_fonts);
+      UNBLOCK_INPUT;
+
+      if (names)
+       {
+         int i;
+
+         /* Make a list of all the fonts we got back.
+            Store that in the font cache for the display.  */
+         for (i = 0; i < num_fonts; i++)
+           {
+             char *p = names[i];
+             int average_width = -1, dashes = 0, width = 0;
+
+             /* Count the number of dashes in NAMES[I].  If there are
+               14 dashes, and the field value following 12th dash
+               (AVERAGE_WIDTH) is 0, this is a auto-scaled font which
+               is usually too ugly to be used for editing.  Let's
+               ignore it.  */
+             while (*p)
+               if (*p++ == '-')
+                 {
+                   dashes++;
+                   if (dashes == 7) /* PIXEL_SIZE field */
+                     width = atoi (p);
+                   else if (dashes == 12) /* AVERAGE_WIDTH field */
+                     average_width = atoi (p);
+                 }
+             if (dashes < 14 || average_width != 0)
+               {
+                 tem = build_string (names[i]);
+                 if (NILP (Fassoc (tem, list)))
+                   {
+                     if (STRINGP (Vx_pixel_size_width_font_regexp)
+                         && ((fast_c_string_match_ignore_case
+                              (Vx_pixel_size_width_font_regexp, names[i]))
+                             >= 0))
+                       /* We can set the value of PIXEL_SIZE to the
+                         width of this font.  */
+                       list = Fcons (Fcons (tem, make_number (width)), list);
+                     else
+                       /* For the moment, width is not known.  */
+                       list = Fcons (Fcons (tem, Qnil), list);
+                   }
+               }
+           }
+         XFreeFontNames (names);
+       }
+
+      /* Now store the result in the cache.  */
+      if (f != NULL)
+       XCONS (FRAME_X_DISPLAY_INFO (f)->name_list_element)->cdr
+         = Fcons (Fcons (key, list),
+                  XCONS (FRAME_X_DISPLAY_INFO (f)->name_list_element)->cdr);
+
+    label_cached:
+      if (NILP (list)) continue; /* Try the remaining alternatives.  */
+
+      newlist = second_best = Qnil;
+      /* Make a list of the fonts that have the right width.  */
+      for (; CONSP (list); list = XCONS (list)->cdr)
+       {
+         int found_size;
+
+         tem = XCONS (list)->car;
+
+         if (!CONSP (tem) || NILP (XCONS (tem)->car))
+           continue;
+         if (!size)
+           {
+             newlist = Fcons (XCONS (tem)->car, newlist);
+             continue;
+           }
+
+         if (!INTEGERP (XCONS (tem)->cdr))
+           {
+             /* Since we have not yet known the size of this font, we
+               must try slow function call XLoadQueryFont.  */
+             XFontStruct *thisinfo;
+
+             BLOCK_INPUT;
+             thisinfo = XLoadQueryFont (dpy,
+                                        XSTRING (XCONS (tem)->car)->data);
+             UNBLOCK_INPUT;
+
+             if (thisinfo)
+               {
+                 XCONS (tem)->cdr
+                   = (thisinfo->min_bounds.width == 0
+                      ? make_number (0)
+                      : make_number (thisinfo->max_bounds.width));
+                 XFreeFont (dpy, thisinfo);
+               }
+             else
+               /* For unknown reason, the previous call of XListFont had
+                 retruned a font which can't be opened.  Record the size
+                 as 0 not to try to open it again.  */
+               XCONS (tem)->cdr = make_number (0);
+           }
+
+         found_size = XINT (XCONS (tem)->cdr);
+         if (found_size == size)
+           newlist = Fcons (XCONS (tem)->car, newlist);
+         else if (found_size > 0)
+           {
+             if (NILP (second_best))
+               second_best = tem;
+             else if (found_size < size)
+               {
+                 if (XINT (XCONS (second_best)->cdr) > size
+                     || XINT (XCONS (second_best)->cdr) < found_size)
+                   second_best = tem;
+               }
+             else
+               {
+                 if (XINT (XCONS (second_best)->cdr) > size
+                     && XINT (XCONS (second_best)->cdr) > found_size)
+                   second_best = tem;
+               }
+           }
+       }
+      if (!NILP (newlist))
+       break;
+      else if (!NILP (second_best))
+       {
+         newlist = Fcons (XCONS (second_best)->car, Qnil);
+         break;
+       }
+    }
+
+  return newlist;
+}  
+
+/* Load font named FONTNAME of the size SIZE for frame F, and return a
+   pointer to the structure font_info while allocating it dynamically.
+   If SIZE is 0, load any size of font.
+   If loading is failed, return NULL.  */
+
+struct font_info *
+x_load_font (f, fontname, size)
+     struct frame *f;
+     register char *fontname;
+     int size;
+{
+  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
+  Lisp_Object font_names;
+
+  /* Get a list of all the fonts that match this name.  Once we
+     have a list of matching fonts, we compare them against the fonts
+     we already have by comparing names.  */
+  font_names = x_list_fonts (f, build_string (fontname), size, 256);
+
+  if (!NILP (font_names))
+    {
+      Lisp_Object tail;
+      int i;
+
+      for (i = 0; i < dpyinfo->n_fonts; i++)
+       for (tail = font_names; CONSP (tail); tail = XCONS (tail)->cdr)
+         if (!strcmp (dpyinfo->font_table[i].name,
+                      XSTRING (XCONS (tail)->car)->data)
+             || !strcmp (dpyinfo->font_table[i].full_name,
+                         XSTRING (XCONS (tail)->car)->data))
+           return (dpyinfo->font_table + i);
+    }
+
+  /* Load the font and add it to the table.  */
+  {
+    char *full_name;
+    XFontStruct *font;
+    struct font_info *fontp;
+    unsigned long value;
+
+    /* If we have found fonts by x_list_font, load one of them.  If
+       not, we still try to load a font by the name given as FONTNAME
+       because XListFonts (called in x_list_font) of some X server has
+       a bug of not finding a font even if the font surely exists and
+       is loadable by XLoadQueryFont.  */
+    if (!NILP (font_names))
+      fontname = (char *) XSTRING (XCONS (font_names)->car)->data;
+
+    BLOCK_INPUT;
+    font = (XFontStruct *) XLoadQueryFont (FRAME_X_DISPLAY (f), fontname);
+    UNBLOCK_INPUT;
+    if (!font)
+      return NULL;
+
+    /* Do we need to create the table?  */
+    if (dpyinfo->font_table_size == 0)
+      {
+       dpyinfo->font_table_size = 16;
+       dpyinfo->font_table
+         = (struct font_info *) xmalloc (dpyinfo->font_table_size
+                                         * sizeof (struct font_info));
+      }
+    /* Do we need to grow the table?  */
+    else if (dpyinfo->n_fonts
+            >= dpyinfo->font_table_size)
+      {
+       dpyinfo->font_table_size *= 2;
+       dpyinfo->font_table
+         = (struct font_info *) xrealloc (dpyinfo->font_table,
+                                          (dpyinfo->font_table_size
+                                           * sizeof (struct font_info)));
+      }
+
+    fontp = dpyinfo->font_table + dpyinfo->n_fonts;
+
+    /* Now fill in the slots of *FONTP.  */
+    BLOCK_INPUT;
+    fontp->font = font;
+    fontp->font_idx = dpyinfo->n_fonts;
+    fontp->name = (char *) xmalloc (strlen (fontname) + 1);
+    bcopy (fontname, fontp->name, strlen (fontname) + 1);
+
+    /* Try to get the full name of FONT.  Put it in FULL_NAME.  */
+    full_name = 0;
+    if (XGetFontProperty (font, XA_FONT, &value))
+      {
+       char *name = (char *) XGetAtomName (FRAME_X_DISPLAY (f), (Atom) value);
+       char *p = name;
+       int dashes = 0;
+
+       /* Count the number of dashes in the "full name".
+          If it is too few, this isn't really the font's full name,
+          so don't use it.
+          In X11R4, the fonts did not come with their canonical names
+          stored in them.  */
+       while (*p)
+         {
+           if (*p == '-')
+             dashes++;
+           p++;
+         }
+
+       if (dashes >= 13)
+         {
+           full_name = (char *) xmalloc (p - name + 1);
+           bcopy (name, full_name, p - name + 1);
+         }
+
+       XFree (name);
+      }
+    
+    if (full_name != 0)
+      fontp->full_name = full_name;
+    else
+      fontp->full_name = fontp->name;
+
+    fontp->size = font->max_bounds.width;
+    fontp->height = font->max_bounds.ascent + font->max_bounds.descent;
+
+    if (NILP (font_names))
+      {
+       /* We come here because of a bug of XListFonts mentioned at
+          the head of this block.  Let's store this information in
+          the cache for x_list_fonts.  */
+       Lisp_Object lispy_name = build_string (fontname);
+       Lisp_Object lispy_full_name = build_string (fontp->full_name);
+
+       XCONS (dpyinfo->name_list_element)->cdr
+         = Fcons (Fcons (Fcons (lispy_name, make_number (256)),
+                         Fcons (Fcons (lispy_full_name,
+                                       make_number (fontp->size)),
+                                Qnil)),
+                  XCONS (dpyinfo->name_list_element)->cdr);
+       if (full_name)
+         XCONS (dpyinfo->name_list_element)->cdr
+           = Fcons (Fcons (Fcons (lispy_full_name, make_number (256)),
+                           Fcons (Fcons (lispy_full_name,
+                                         make_number (fontp->size)),
+                                  Qnil)),
+                    XCONS (dpyinfo->name_list_element)->cdr);
+      }
+
+    /* The slot `encoding' specifies how to map a character
+       code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
+       the font code-points (0:0x20..0x7F, 1:0xA0..0xFF, 0:0x2020..0x7F7F,
+       the font code-points (0:0x20..0x7F, 1:0xA0..0xFF,
+       0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF, or
+       2:0xA020..0xFF7F).  For the moment, we don't know which charset
+       uses this font.  So, we set informatoin in fontp->encoding[1]
+       which is never used by any charset.  If mapping can't be
+       decided, set FONT_ENCODING_NOT_DECIDED.  */
+    fontp->encoding[1]
+      = (font->max_byte1 == 0
+        /* 1-byte font */
+        ? (font->min_char_or_byte2 < 0x80
+           ? (font->max_char_or_byte2 < 0x80
+              ? 0              /* 0x20..0x7F */
+              : FONT_ENCODING_NOT_DECIDED) /* 0x20..0xFF */
+           : 1)                /* 0xA0..0xFF */
+        /* 2-byte font */
+        : (font->min_byte1 < 0x80
+           ? (font->max_byte1 < 0x80
+              ? (font->min_char_or_byte2 < 0x80
+                 ? (font->max_char_or_byte2 < 0x80
+                    ? 0                /* 0x2020..0x7F7F */
+                    : FONT_ENCODING_NOT_DECIDED) /* 0x2020..0x7FFF */
+                 : 3)          /* 0x20A0..0x7FFF */
+              : FONT_ENCODING_NOT_DECIDED) /* 0x20??..0xA0?? */
+           : (font->min_char_or_byte2 < 0x80
+              ? (font->max_char_or_byte2 < 0x80
+                 ? 2           /* 0xA020..0xFF7F */
+                 : FONT_ENCODING_NOT_DECIDED) /* 0xA020..0xFFFF */
+              : 1)));          /* 0xA0A0..0xFFFF */
+
+    fontp->baseline_offset
+      = (XGetFontProperty (font, dpyinfo->Xatom_MULE_BASELINE_OFFSET, &value)
+        ? (long) value : 0);
+    fontp->relative_compose
+      = (XGetFontProperty (font, dpyinfo->Xatom_MULE_RELATIVE_COMPOSE, &value)
+        ? (long) value : 0);
+    fontp->default_ascent
+      = (XGetFontProperty (font, dpyinfo->Xatom_MULE_DEFAULT_ASCENT, &value)
+        ? (long) value : 0);
+
+    UNBLOCK_INPUT;
+    dpyinfo->n_fonts++;
+
+    return fontp;
+  }
+}
+
+/* Return a pointer to struct font_info of a font named FONTNAME for frame F.
+   If no such font is loaded, return NULL.  */
+struct font_info *
+x_query_font (f, fontname)
+     struct frame *f;
+     register char *fontname;
+{
+  struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
+  int i;
+
+  for (i = 0; i < dpyinfo->n_fonts; i++)
+    if (!strcmp (dpyinfo->font_table[i].name, fontname)
+       || !strcmp (dpyinfo->font_table[i].full_name, fontname))
+      return (dpyinfo->font_table + i);
+  return NULL;
+}
+
+\f
 /* Initialization.  */
 
 #ifdef USE_X_TOOLKIT
@@ -6038,8 +6958,8 @@ x_term_init (display_name, xrm_option, resource_name)
 #endif /* ! 0 */
 
   dpyinfo->x_id_name
-    = (char *) xmalloc (XSTRING (Vinvocation_name)->size
-                       + XSTRING (Vsystem_name)->size
+    = (char *) xmalloc (STRING_BYTES (XSTRING (Vinvocation_name))
+                       + STRING_BYTES (XSTRING (Vsystem_name))
                        + 2);
   sprintf (dpyinfo->x_id_name, "%s@%s",
           XSTRING (Vinvocation_name)->data, XSTRING (Vsystem_name)->data);
@@ -6106,14 +7026,14 @@ x_term_init (display_name, xrm_option, resource_name)
     = XInternAtom (dpyinfo->display, "WM_MOVED", False);
   dpyinfo->Xatom_editres
     = XInternAtom (dpyinfo->display, "Editres", False);
-  dpyinfo->Xatom_FONT
-    = XInternAtom (dpyinfo->display, "FONT", False);
   dpyinfo->Xatom_CLIPBOARD
     = XInternAtom (dpyinfo->display, "CLIPBOARD", False);
   dpyinfo->Xatom_TIMESTAMP
     = XInternAtom (dpyinfo->display, "TIMESTAMP", False);
   dpyinfo->Xatom_TEXT
     = XInternAtom (dpyinfo->display, "TEXT", False);
+  dpyinfo->Xatom_COMPOUND_TEXT
+    = XInternAtom (dpyinfo->display, "COMPOUND_TEXT", False);
   dpyinfo->Xatom_DELETE
     = XInternAtom (dpyinfo->display, "DELETE", False);
   dpyinfo->Xatom_MULTIPLE
@@ -6128,12 +7048,32 @@ x_term_init (display_name, xrm_option, resource_name)
     = XInternAtom (dpyinfo->display, "NULL", False);
   dpyinfo->Xatom_ATOM_PAIR
     = XInternAtom (dpyinfo->display, "ATOM_PAIR", False);
+  /* For properties of font.  */
+  dpyinfo->Xatom_PIXEL_SIZE
+    = XInternAtom (dpyinfo->display, "PIXEL_SIZE", False);
+  dpyinfo->Xatom_MULE_BASELINE_OFFSET
+    = XInternAtom (dpyinfo->display, "_MULE_BASELINE_OFFSET", False);
+  dpyinfo->Xatom_MULE_RELATIVE_COMPOSE
+    = XInternAtom (dpyinfo->display, "_MULE_RELATIVE_COMPOSE", False);
+  dpyinfo->Xatom_MULE_DEFAULT_ASCENT
+    = XInternAtom (dpyinfo->display, "_MULE_DEFAULT_ASCENT", False);
 
   dpyinfo->cut_buffers_initialized = 0;
 
   connection = ConnectionNumber (dpyinfo->display);
   dpyinfo->connection = connection;
 
+  {
+    char null_bits[1];
+
+    null_bits[0] = 0x00;
+
+    dpyinfo->null_pixel
+      = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window, 
+                                    null_bits, 1, 1, (long) 0, (long) 0,
+                                    1);
+  }
+
 #ifdef subprocesses
   /* This is only needed for distinguishing keyboard and process input.  */
   if (connection != 0)
@@ -6157,12 +7097,14 @@ x_term_init (display_name, xrm_option, resource_name)
 #endif /* ! defined (SIGIO) */
 
 #ifdef USE_LUCID
+#ifdef HAVE_X11R5 /* It seems X11R4 lacks XtCvtStringToFont, and XPointer.  */
   /* Make sure that we have a valid font for dialog boxes
      so that Xt does not crash.  */
   {
     Display *dpy = dpyinfo->display;
     XrmValue d, fr, to;
     Font font;
+    int count;
     
     d.addr = (XPointer)&dpy;
     d.size = sizeof (Display *);
@@ -6170,14 +7112,15 @@ x_term_init (display_name, xrm_option, resource_name)
     fr.size = sizeof (XtDefaultFont);
     to.size = sizeof (Font *);
     to.addr = (XPointer)&font;
-    x_catch_errors (dpy);
+    count = x_catch_errors (dpy);
     if (!XtCallConverter (dpy, XtCvtStringToFont, &d, 1, &fr, &to, NULL))
       abort ();
     if (x_had_errors_p (dpy) || !XQueryFont (dpy, font))
       XrmPutLineResource (&xrdb, "Emacs.dialog.*.font: 9x15");
-    x_uncatch_errors (dpy);
+    x_uncatch_errors (dpy, count);
   }
 #endif
+#endif
 
 
   UNBLOCK_INPUT;
@@ -6243,6 +7186,7 @@ x_delete_display (dpyinfo)
 \f
 /* Set up use of X before we make the first connection.  */
 
+void
 x_initialize ()
 {
   clear_frame_hook = XTclear_frame;
@@ -6291,7 +7235,7 @@ x_initialize ()
 
   /* Note that there is no real way portable across R3/R4 to get the
      original error handler.  */
-  XSetErrorHandler (x_error_quitter);
+  XSetErrorHandler (x_error_handler);
   XSetIOErrorHandler (x_io_error_quitter);
 
   /* Disable Window Change signals;  they are handled by X events. */
@@ -6305,6 +7249,9 @@ x_initialize ()
 void
 syms_of_xterm ()
 {
+  staticpro (&x_error_message_string);
+  x_error_message_string = Qnil;
+
   staticpro (&x_display_name_list);
   x_display_name_list = Qnil;