Fix -Wimplicit warnings.
[bpt/emacs.git] / src / xterm.c
index 6bd821c..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.
 
@@ -86,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>
@@ -147,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;
@@ -265,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
@@ -323,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;
 {
@@ -383,7 +384,7 @@ XTupdate_begin (f)
   UNBLOCK_INPUT;
 }
 
-static
+static void
 XTupdate_end (f)
      struct frame *f;
 {
@@ -413,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;
 {
@@ -421,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;
@@ -433,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;
 {
@@ -442,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;
 {
@@ -455,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 ()
 {
 }
@@ -464,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 ();  */
@@ -474,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;
 {
@@ -543,14 +546,17 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
      struct cmpchar_info *cmpcharp;
 {
   /* Holds characters to be displayed. */
-  XChar2b *buf = (XChar2b *) alloca (FRAME_WINDOW_WIDTH (f) * sizeof (*buf));
-  register XChar2b *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 pixel_width;
+  int i;
 
   while (n > 0)
     {
@@ -558,6 +564,7 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
       int cf, len;
       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;
@@ -565,6 +572,7 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
       GLYPH_FOLLOW_ALIASES (tbase, tlen, 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)
        {
@@ -590,10 +598,10 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
 
       /* 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 BUF.
+        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 = buf;
+      cp = x_2byte_buffer;
       while (n > 0)
        {
          int this_charset, c1, c2;
@@ -606,7 +614,7 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
              || (cmpcharp == NULL && FAST_GLYPH_FACE (g) != cf))
            break;
 
-         if (c2)
+         if (c2 > 0)
            cp->byte1 = c1, cp->byte2 = c2;
          else
            cp->byte1 = 0, cp->byte2 = c1;
@@ -617,12 +625,7 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
        }
 
       /* LEN gets the length of the run.  */
-      len = cp - buf;
-      /* PIXEL_WIDTH get the pixcel width of the run.  */
-      pixel_width
-       = (FONT_WIDTH (f->output_data.x->font)
-          * (cmpcharp ? cmpcharp->width : len * CHARSET_WIDTH (charset)));
-
+      len = cp - x_2byte_buffer;
       /* Now output this run of chars, with the font and pixel values
         determined by the face code CF.  */
       {
@@ -630,17 +633,30 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
        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 different from that of the current line.
+          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'.  */
-       int relative_compose = 0;
+       /* 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)
@@ -673,6 +689,8 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
              stippled = 1;
          }
 
+#define FACE_DEFAULT (~0)
+
        /* Setting appropriate font and gc for this charset.  */
        if (charset != CHARSET_ASCII)
          {
@@ -681,21 +699,29 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
            struct font_info *fontp;
 
            if ((fontset < 0 && (fontset = FRAME_FONTSET (f)) < 0)
-               || !(fontp = fs_load_font (f, FRAME_X_FONT_TABLE (f),
+               || !(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);
-           if (font->max_byte1 != 0)
-             baseline = (f->output_data.x->line_height
-                         + font->ascent - font->descent) / 2;
-           else
-             baseline = (f->output_data.x->font_baseline
-                         - fontp->baseline_offset);
+           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;
+             {
+               relative_compose = fontp->relative_compose;
+               default_ascent = fontp->default_ascent;
+             }
 
            /* We have to change code points in the following cases.  */
            if (fontp->font_encoder)
@@ -705,20 +731,30 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
                struct ccl_program *ccl = fontp->font_encoder;
 
                if (CHARSET_DIMENSION (charset) == 1)
-                 for (cp = buf; cp < buf + len; cp++)
+                 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);
-                     cp->byte2 = ccl->reg[1];
+                     /* 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 = buf; cp < buf + len; cp++)
+                 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);
-                     cp->byte1 = ccl->reg[1], cp->byte2 = ccl->reg[2];
+                     /* 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])
@@ -726,35 +762,47 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
                int enc = fontp->encoding[charset];
 
                if ((enc == 1 || enc == 2) && CHARSET_DIMENSION (charset) == 2)
-                 for (cp = buf; cp < buf + len; cp++)
+                 for (cp = x_2byte_buffer; cp < x_2byte_buffer + len; cp++)
                    cp->byte1 |= 0x80;
                if (enc == 1 || enc == 3)
-                 for (cp = buf; cp < buf + len; cp++)
+                 for (cp = x_2byte_buffer; cp < x_2byte_buffer + len; cp++)
                    cp->byte2 |= 0x80;
              }
          }
        else
          {
-           font = FACE_FONT (face);
-           baseline = FONT_BASE (font);
          font_not_found:
-           gc   = FACE_GC   (face);
+           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);
          }
 
-#define FACE_DEFAULT (~0)
-
        /* Now override that if the cursor's on this character.  */
        if (hl == 2)
          {
            /* The cursor overrides stippling.  */
            stippled = 0;
 
-           if (!cmpcharp
-               && (!font
-                   || font == (XFontStruct *) FACE_DEFAULT
-                   || 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;
              }
@@ -804,31 +852,49 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
              }
          }
 
-       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 (!font
-                || stippled
-                || f->output_data.x->line_height != FONT_HEIGHT (font)
-                || cmpcharp)
+       else if (stippled)
          {
-           if (!stippled)
-             /* This is to fill a rectangle with background color.  */
-             XSetStipple (FRAME_X_DISPLAY (f), gc,
-                          FRAME_X_DISPLAY_INFO (f)->null_pixel);
            /* 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, pixel_width,
-                           f->output_data.x->line_height);
+                           left, top, run_width, line_height);
 
            /* Turn stipple off.  */
            XSetFillStyle (FRAME_X_DISPLAY (f), gc, FillSolid);
 
+           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
@@ -840,10 +906,74 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
 
        if (font)
          {
-           if (cmpcharp)
+           if (require_clipping)
+             {
+               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);
+             }
+
+           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;
+                     }
+
+                   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
              {
+               /* Handle composite characters.  */
                XCharStruct *pcm; /* Pointer to per char metric info.  */
-               int i;
 
                if ((cmpcharp->cmp_rule || relative_compose)
                    && gidx == 0)
@@ -853,16 +983,26 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
                       written, LOWEST the lowest position.  */
                    int x_offset = 0;
 
-                   pcm = PER_CHAR_METRIC (font, buf);
-                   highest = pcm->ascent + 1;
-                   lowest = - pcm->descent;
+                   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, buf, 1);
+                                  left + x_offset, top + baseline, x_2byte_buffer, 1);
                    i = 1;
                    gidx++;
                  }
@@ -875,18 +1015,33 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
 
                    if (relative_compose)
                      {
-                       pcm = PER_CHAR_METRIC (font, buf + i);
-                       if (- pcm->descent >= 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]))))
                          {
-                           /* Draw above the current glyphs.  */
-                           y_offset = highest + pcm->descent;
-                           highest += pcm->ascent + pcm->descent;
+                           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 if (pcm->ascent <= 0)
+                       else
                          {
-                           /* Draw beneath the current glyphs.  */
-                           y_offset = lowest - pcm->ascent;
-                           lowest -= pcm->ascent + pcm->descent;
+                           /* 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)
@@ -901,7 +1056,7 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
                        gref = gref / 3 + (gref == 4) * 2;
                        nref = nref / 3 + (nref == 4) * 2;
 
-                       pcm = PER_CHAR_METRIC (font, buf + i);
+                       pcm = PER_CHAR_METRIC (font, x_2byte_buffer + i);
                        bottom = ((gref == 0 ? highest : gref == 1 ? 0
                                   : gref == 2 ? lowest
                                   : (highest + lowest) / 2)
@@ -919,25 +1074,11 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
                      }
                    XDrawString16 (FRAME_X_DISPLAY (f), window, gc,
                                   left + x_offset, top + baseline - y_offset,
-                                  buf + i, 1);
+                                  x_2byte_buffer + i, 1);
                  }
              }
-           else if (background_filled)
-             XDrawString16 (FRAME_X_DISPLAY (f), window, gc,
-                            left, top + baseline, buf, len);
-           else
-             XDrawImageString16 (FRAME_X_DISPLAY (f), window, gc,
-                                 left, top + baseline, 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);
+           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.  */
@@ -952,31 +1093,33 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
              }
 #endif
          }
-       else
+       if (!font)
          {
-           /* There's no appropriate font for this glyph.  Just show
-               rectangles.  */
+           /* Show rectangles to indicate that we found no font.  */
+           int limit = cmpcharp ? 1 : len;
 
-           if (cmpcharp)
-             XDrawRectangle
-               (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
-                left, top + 1,
-                pixel_width - 2, f->output_data.x->line_height - 3);
-           else
+           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))
+         {
+           /* Show ??? to indicate that we found a font of
+               inappropriate size.  */
+           int limit = cmpcharp ? 1 : len;
+
+           for (i = 0; i < limit; i++)
              {
-               int left_offset;
-               int left_skip_step = (FONT_WIDTH (f->output_data.x->font)
-                                     * CHARSET_WIDTH (charset));
-
-               for (left_offset = 0; left_offset < pixel_width;
-                    left_offset += left_skip_step)
-                 XDrawRectangle
-                   (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
-                    left + left_offset, top + 1,
-                    left_skip_step - 2, f->output_data.x->line_height - 3);
+               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);
              }
          }
-       
+
        /* 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.  */
@@ -987,17 +1130,17 @@ dumpglyphs (f, left, top, gp, n, hl, just_foreground, cmpcharp)
             on the default font of this frame.  */
          int underline_position = f->output_data.x->font_baseline + 1;
 
-         if (underline_position >= f->output_data.x->line_height)
-           underline_position = f->output_data.x->line_height - 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 + underline_position, pixel_width, 1);
+                           left, top + underline_position, run_width, 1);
        }
 
        if (!cmpcharp)
-         left += pixel_width;
+         left += run_width;
       }
     }
 
@@ -1043,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;
@@ -1089,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;
 {
@@ -1131,7 +1274,7 @@ XTclear_end_of_line (first_unused)
   UNBLOCK_INPUT;
 }
 
-static
+static void
 XTclear_frame ()
 {
   int mask;
@@ -1367,6 +1510,7 @@ timeval_subtract (result, x, y)
   return x.tv_sec < y.tv_sec;
 }
 
+void
 XTflash (f)
      struct frame *f;
 {
@@ -1494,6 +1638,7 @@ XTflash (f)
 
 #define XRINGBELL XBell (FRAME_X_DISPLAY (selected_frame), 0)
 
+void
 XTring_bell ()
 {
   if (FRAME_X_DISPLAY (selected_frame) == 0)
@@ -1516,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;
@@ -1524,7 +1669,7 @@ XTinsert_glyphs (start, len)
   abort ();
 }
 
-static
+static void
 XTdelete_glyphs (n)
      register int n;
 {
@@ -1536,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;
 {
@@ -1567,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;
 {
@@ -2149,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)
@@ -2249,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;
@@ -2302,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);
 
@@ -2409,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;
@@ -2551,6 +2698,7 @@ clear_mouse_face (dpyinfo)
 /* 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;
 {
@@ -2602,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
     {
@@ -2648,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;
 
@@ -2655,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))
@@ -2715,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)
@@ -2730,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)
@@ -3417,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;
 {
@@ -3453,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
@@ -3703,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]
@@ -3803,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. */
@@ -3864,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:
@@ -3887,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
@@ -3943,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;
 
@@ -3963,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.  */
@@ -3976,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
@@ -4041,6 +4210,10 @@ XTread_socket (sd, bufp, numchars, expected)
 #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,
@@ -4060,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
@@ -4271,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
@@ -4300,63 +4472,31 @@ XTread_socket (sd, bufp, numchars, expected)
                    }
 #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;
 
@@ -4537,12 +4677,27 @@ x_draw_box (f, x, y)
   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);
 }
 
@@ -4748,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;
@@ -4755,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)
@@ -4769,6 +4929,7 @@ 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;
@@ -4791,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;
 {
@@ -4878,6 +5040,147 @@ x_text_icon (f, icon_name)
   return 0;
 }
 \f
+#define X_ERROR_MESSAGE_SIZE 200
+
+/* If non-nil, this should be a string.
+   It means catch X errors  and store the error message in this string.  */
+
+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;
+     XErrorEvent *error;
+{
+  XGetErrorText (display, error->error_code,
+                XSTRING (x_error_message_string)->data,
+                X_ERROR_MESSAGE_SIZE);
+}
+
+/* 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.
+
+   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.
+
+   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.
+
+   Calling x_uncatch_errors resumes the normal error handling.  */
+
+void x_check_errors ();
+static Lisp_Object x_catch_errors_unwind ();
+
+int
+x_catch_errors (dpy)
+     Display *dpy;
+{
+  int count = specpdl_ptr - specpdl;
+
+  /* Make sure any errors from previous requests have been dealt with.  */
+  XSync (dpy, False);
+
+  record_unwind_protect (x_catch_errors_unwind, x_error_message_string);
+
+  x_error_message_string = make_uninit_string (X_ERROR_MESSAGE_SIZE);
+  XSTRING (x_error_message_string)->data[0] = 0;
+
+  return count;
+}
+
+/* Unbind the binding that we made to check for X errors.  */
+
+static Lisp_Object
+x_catch_errors_unwind (old_val)
+     Lisp_Object old_val;
+{
+  x_error_message_string = old_val;
+  return Qnil;
+}
+
+/* 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.  */
+
+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);
+}
+
+/* Nonzero if we had any X protocol errors
+   since we did x_catch_errors on DPY.  */
+
+int
+x_had_errors_p (dpy)
+     Display *dpy;
+{
+  /* Make sure to catch any errors incurred so far.  */
+  XSync (dpy, False);
+
+  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.
+   Don't need to do anything, because the write which caused the 
+   SIGPIPE will fail, causing Xlib to invoke the X IO error handler,
+   which will do the appropriate cleanup for us. */
+   
+static SIGTYPE
+x_connection_signal (signalnum)        /* If we don't have an argument, */
+     int signalnum;            /* some compilers complain in signal calls. */
+{
+#ifdef USG
+  /* USG systems forget handlers when they are used;
+     must reestablish each time */
+  signal (signalnum, x_connection_signal);
+#endif /* USG */
+}
+\f
 /* Handling X errors.  */
 
 /* Handle the loss of connection to display DISPLAY.  */
@@ -4892,9 +5195,9 @@ x_connection_closed (display, error_message)
 
   /* Indicate that this display is dead.  */
 
-  #ifdef USE_X_TOOLKIT
+#ifdef USE_X_TOOLKIT
   XtCloseDisplay (display);
-  #endif
+#endif
 
   dpyinfo->display = 0;
 
@@ -4966,138 +5269,35 @@ x_error_quitter (display, error)
   x_connection_closed (display, buf1);
 }
 
-/* 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.  */
+/* This is the first-level handler for X protocol errors.
+   It calls x_error_quitter or x_error_catcher.  */
 
 static int
-x_io_error_quitter (display)
+x_error_handler (display, error)
      Display *display;
+     XErrorEvent *error;
 {
-  char buf[256];
+  char buf[256], buf1[356];
 
-  sprintf (buf, "Connection lost to X server `%s'", DisplayString (display));
-  x_connection_closed (display, buf);
-}
-\f
-/* Handle SIGPIPE, which can happen when the connection to a server
-   simply goes away.  SIGPIPE is handled by x_connection_signal.
-   Don't need to do anything, because the write which caused the 
-   SIGPIPE will fail, causing Xlib to invoke the X IO error handler,
-   which will do the appropriate cleanup for us. */
-   
-static SIGTYPE
-x_connection_signal (signalnum)        /* If we don't have an argument, */
-     int signalnum;            /* some compilers complain in signal calls. */
-{
-#ifdef USG
-  /* USG systems forget handlers when they are used;
-     must reestablish each time */
-  signal (signalnum, x_connection_signal);
-#endif /* USG */
+  if (! NILP (x_error_message_string))
+    x_error_catcher (display, error);
+  else
+    x_error_quitter (display, error);
 }
-\f
-/* A buffer for storing X error messages.  */
-static char *x_caught_error_message;
-#define X_CAUGHT_ERROR_MESSAGE_SIZE 200
 
-/* 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.  */
+/* 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.  */
 
 static int
-x_error_catcher (display, error)
+x_io_error_quitter (display)
      Display *display;
-     XErrorEvent *error;
-{
-  XGetErrorText (display, error->error_code,
-                x_caught_error_message, X_CAUGHT_ERROR_MESSAGE_SIZE);
-}
-
-
-/* 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.
-
-   After calling this function, X protocol errors no longer cause
-   Emacs to exit; instead, they are recorded in x_cfc_error_message.
-
-   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.
-
-   Calling x_uncatch_errors resumes the normal error handling.  */
-
-void x_catch_errors (), x_check_errors (), x_uncatch_errors ();
-
-void
-x_catch_errors (dpy)
-     Display *dpy;
-{
-  /* Make sure any errors from previous requests have been dealt with.  */
-  XSync (dpy, False);
-
-  /* Set up the error buffer.  */
-  x_caught_error_message
-    = (char*) xmalloc (X_CAUGHT_ERROR_MESSAGE_SIZE);
-  x_caught_error_message[0] = '\0';
-
-  /* Install our little error handler.  */
-  XSetErrorHandler (x_error_catcher);
-}
-
-/* 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.  */
-
-void
-x_check_errors (dpy, format)
-     Display *dpy;
-     char *format;
 {
-  /* Make sure to catch any errors incurred so far.  */
-  XSync (dpy, False);
-
-  if (x_caught_error_message[0])
-    {
-      char buf[X_CAUGHT_ERROR_MESSAGE_SIZE + 56];
-
-      sprintf (buf, format, x_caught_error_message);
-      x_uncatch_errors (dpy);
-      error (buf);
-    }
-}
-
-/* Nonzero if we had any X protocol errors since we did x_catch_errors.  */
-
-int
-x_had_errors_p (dpy)
-     Display *dpy;
-{
-  /* Make sure to catch any errors incurred so far.  */
-  XSync (dpy, False);
-
-  return x_caught_error_message[0] != 0;
-}
-
-/* Stop catching X protocol errors and let them make Emacs die.  */
-
-void
-x_uncatch_errors (dpy)
-     Display *dpy;
-{
-  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.  */
 
@@ -5129,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)
@@ -5154,8 +5357,8 @@ x_new_font (f, 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 font that fits the pattern.
-   The return value shows which font we chose.  */
+   pattern; in that case, we choose some fontset that fits the pattern.
+   The return value shows which fontset we chose.  */
 
 Lisp_Object
 x_new_fontset (f, fontsetname)
@@ -5169,6 +5372,11 @@ x_new_fontset (f, fontsetname)
   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])
@@ -5183,7 +5391,7 @@ x_new_fontset (f, fontsetname)
 
   /* 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),
+  FS_LOAD_FONT (f, FRAME_X_FONT_TABLE (f),
                CHARSET_ASCII, XSTRING (result)->data, fontset);
 
   return build_string (fontsetname);
@@ -5192,6 +5400,7 @@ x_new_fontset (f, fontsetname)
 /* Calculate the absolute position in frame F
    from its current recorded position values and gravity.  */
 
+void
 x_calc_absolute_position (f)
      struct frame *f;
 {
@@ -5200,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
@@ -5207,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-window, to-window.  */
+                                this_window,
+                                f->output_data.x->parent_desc,
 
-                            /* From-position, to-position.  */
-                            0, 0, &win_x, &win_y,
+                                /* From-position, to-position.  */
+                                0, 0, &win_x, &win_y,
 
-                            /* Child of win.  */
-                            &child);
+                                /* Child of win.  */
+                                &child);
+         if (x_had_errors_p (FRAME_X_DISPLAY (f)))
+           {
+             Window newroot, newparent = 0xdeadbeef;
+             Window *newchildren;
+             int nchildren;
+
+             if (! XQueryTree (FRAME_X_DISPLAY (f), this_window, &newroot,
+                               &newparent, &newchildren, &nchildren))
+               break;
+
+             XFree (newchildren);
+
+             f->output_data.x->parent_desc = newparent;
+           }
+         else
+           break;
+       }
+
+      x_uncatch_errors (FRAME_X_DISPLAY (f), count);
       UNBLOCK_INPUT;
     }
 
@@ -5253,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;
@@ -5276,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),
@@ -5301,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;
@@ -5427,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;
 {
@@ -5442,6 +5688,7 @@ x_focus_on_frame (f)
 #endif /* ! 0 */
 }
 
+void
 x_unfocus_frame (f)
      struct frame *f;
 {
@@ -5455,6 +5702,7 @@ x_unfocus_frame (f)
 
 /* Raise frame F.  */
 
+void
 x_raise_frame (f)
      struct frame *f;
 {
@@ -5473,6 +5721,7 @@ x_raise_frame (f)
 
 /* Lower frame F.  */
 
+void
 x_lower_frame (f)
      struct frame *f;
 {
@@ -5509,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;
 
@@ -5557,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)
@@ -5583,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.
@@ -5601,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;
 {
@@ -5683,6 +5970,7 @@ x_make_frame_invisible (f)
 
 /* Change window state from mapped to iconified. */
 
+void
 x_iconify_frame (f)
      struct frame *f;
 {
@@ -5791,6 +6079,7 @@ x_iconify_frame (f)
 \f
 /* Destroy the X window of frame F.  */
 
+void
 x_destroy_window (f)
      struct frame *f;
 {
@@ -5826,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)
@@ -5844,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;
@@ -5857,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;
@@ -6000,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;
@@ -6019,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;
@@ -6068,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;
@@ -6111,26 +6409,37 @@ x_list_fonts (f, pattern, size, maxnames)
      int size;
      int maxnames;
 {
-  Lisp_Object list, newlist, key;
+  Lisp_Object list = Qnil, patterns, newlist = Qnil, key, tem, second_best;
   Display *dpy = f != NULL ? FRAME_X_DISPLAY (f) : x_display_list->display;
 
-  key = Fcons (pattern, make_number (maxnames));
+  patterns = Fassoc (pattern, Valternate_fontname_alist);
+  if (NILP (patterns))
+    patterns = Fcons (pattern, Qnil);
 
-  if (f == NULL)
-    list = Qnil;
-  else
-    /* See if we cached the result for this particular query.  */
-    list = Fassoc (key,
-                  XCONS (FRAME_X_DISPLAY_INFO (f)->name_list_element)->cdr);
+  /* We try at least 10 fonts because X server will return auto-scaled
+     fonts at the head.  */
+  if (maxnames < 10) maxnames = 10;
 
-  if (!NILP (list))
-    list = XCONS (list)->cdr;
-  else
+  for (; CONSP (patterns); patterns = XCONS (patterns)->cdr)
     {
-      /* At first, put PATTERN in the cache.  */
       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;
@@ -6138,7 +6447,6 @@ x_list_fonts (f, pattern, size, maxnames)
       if (names)
        {
          int i;
-         Lisp_Object tem;
 
          /* Make a list of all the fonts we got back.
             Store that in the font cache for the display.  */
@@ -6148,9 +6456,10 @@ x_list_fonts (f, pattern, size, maxnames)
              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 of no use.  Let's ignore it.  */
+               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++ == '-')
                  {
@@ -6166,11 +6475,11 @@ x_list_fonts (f, pattern, size, maxnames)
                  if (NILP (Fassoc (tem, list)))
                    {
                      if (STRINGP (Vx_pixel_size_width_font_regexp)
-                         && (fast_string_match_ignore_case
-                             (Vx_pixel_size_width_font_regexp, names[i])
+                         && ((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.  */
+                         width of this font.  */
                        list = Fcons (Fcons (tem, make_number (width)), list);
                      else
                        /* For the moment, width is not known.  */
@@ -6181,31 +6490,35 @@ x_list_fonts (f, pattern, size, maxnames)
          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);
-    }
 
-  if (NILP (list))
-    return Qnil;
+    label_cached:
+      if (NILP (list)) continue; /* Try the remaining alternatives.  */
 
-  newlist = Qnil;
+      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;
 
-  /* Make a list of the fonts that have the right width.  */
-  for (; CONSP (list); list = XCONS (list)->cdr)
-    {
-      Lisp_Object tem = XCONS (list)->car;
-      int keeper;
+         tem = XCONS (list)->car;
+
+         if (!CONSP (tem) || NILP (XCONS (tem)->car))
+           continue;
+         if (!size)
+           {
+             newlist = Fcons (XCONS (tem)->car, newlist);
+             continue;
+           }
 
-      if (!CONSP (tem) || NILP (XCONS (tem)->car))
-       continue;
-      if (!size)
-       keeper = 1;
-      else
-       {
          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;
@@ -6215,16 +6528,47 @@ x_list_fonts (f, pattern, size, maxnames)
 
              if (thisinfo)
                {
-                 XCONS (tem)->cdr =  make_number (thisinfo->max_bounds.width);
+                 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);
            }
-         keeper = XINT (XCONS (tem)->cdr) == size;
+
+         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;
        }
-      if (keeper)
-       newlist = Fcons (XCONS (tem)->car, newlist);
     }
 
   return newlist;
@@ -6270,13 +6614,18 @@ x_load_font (f, fontname, size)
     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 = XSTRING (XCONS (font_names)->car)->data;
+      fontname = (char *) XSTRING (XCONS (font_names)->car)->data;
 
     BLOCK_INPUT;
     font = (XFontStruct *) XLoadQueryFont (FRAME_X_DISPLAY (f), fontname);
     UNBLOCK_INPUT;
-    if (!font || (size && font->max_bounds.width != size))
+    if (!font)
       return NULL;
 
     /* Do we need to create the table?  */
@@ -6342,22 +6691,47 @@ x_load_font (f, fontname, size)
       fontp->full_name = fontp->name;
 
     fontp->size = font->max_bounds.width;
-    fontp->height = font->ascent + font->descent;
+    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 (0x20..0x7F, 0xA0..0xFF, 0x2020..0x7F7F,
-       0xA0A0..0xFFFF, 0x20A0..0x7FFF, or 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 -1.  */
+       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 */
-              : -1)            /* 0x20..0xFF (can't decide) */
+              : FONT_ENCODING_NOT_DECIDED) /* 0x20..0xFF */
            : 1)                /* 0xA0..0xFF */
         /* 2-byte font */
         : (font->min_byte1 < 0x80
@@ -6365,13 +6739,13 @@ x_load_font (f, fontname, size)
               ? (font->min_char_or_byte2 < 0x80
                  ? (font->max_char_or_byte2 < 0x80
                     ? 0                /* 0x2020..0x7F7F */
-                    : -1)      /* 0x2020..0x7FFF (can't decide) */
+                    : FONT_ENCODING_NOT_DECIDED) /* 0x2020..0x7FFF */
                  : 3)          /* 0x20A0..0x7FFF */
-              : -1)            /* 0x20??..0xA0?? (can't decide) */
+              : FONT_ENCODING_NOT_DECIDED) /* 0x20??..0xA0?? */
            : (font->min_char_or_byte2 < 0x80
               ? (font->max_char_or_byte2 < 0x80
                  ? 2           /* 0xA020..0xFF7F */
-                 : -1)         /* 0xA020..0xFFFF (can't decide) */
+                 : FONT_ENCODING_NOT_DECIDED) /* 0xA020..0xFFFF */
               : 1)));          /* 0xA0A0..0xFFFF */
 
     fontp->baseline_offset
@@ -6380,6 +6754,9 @@ x_load_font (f, fontname, size)
     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++;
@@ -6581,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);
@@ -6678,6 +7055,8 @@ x_term_init (display_name, xrm_option, resource_name)
     = 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;
 
@@ -6685,7 +7064,9 @@ x_term_init (display_name, xrm_option, resource_name)
   dpyinfo->connection = connection;
 
   {
-    char null_bits[] = { 0x00 };
+    char null_bits[1];
+
+    null_bits[0] = 0x00;
 
     dpyinfo->null_pixel
       = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window, 
@@ -6716,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 *);
@@ -6729,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;
@@ -6802,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;
@@ -6850,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. */
@@ -6864,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;