(enum fringe_bitmap_type): Define here.
[bpt/emacs.git] / src / xterm.c
index aae8114..f6566c1 100644 (file)
@@ -97,17 +97,23 @@ Boston, MA 02111-1307, USA.  */
 #include <unistd.h>
 #endif
 
+#ifdef USE_GTK
+#include "gtkutil.h"
+#endif
+
 #ifdef USE_LUCID
-extern int xlwmenu_window_p (Widget w, Window window);
+extern int xlwmenu_window_p P_ ((Widget w, Window window));
 extern void xlwmenu_redisplay P_ ((Widget));
 #endif
 
-#ifdef USE_X_TOOLKIT
+#if defined (USE_X_TOOLKIT) || defined (USE_GTK)
 
 extern void free_frame_menubar P_ ((struct frame *));
 extern struct frame *x_menubar_window_to_frame P_ ((struct x_display_info *,
                                                    int));
+#endif
 
+#ifdef USE_X_TOOLKIT
 #if (XtSpecificationRelease >= 5) && !defined(NO_EDITRES)
 #define HACK_EDITRES
 extern void _XEditResCheckMessages ();
@@ -138,7 +144,7 @@ extern void _XEditResCheckMessages ();
 
 #endif /* USE_X_TOOLKIT */
 
-#ifndef USE_X_TOOLKIT
+#if ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
 #define x_any_window_to_frame x_window_to_frame
 #define x_top_window_to_frame x_window_to_frame
 #endif
@@ -238,7 +244,7 @@ Lisp_Object Vx_toolkit_scroll_bars;
 
 /* If a string, XTread_socket generates an event to display that string.
    (The display is done in read_char.)  */
-   
+
 static Lisp_Object help_echo;
 static Lisp_Object help_echo_window;
 static Lisp_Object help_echo_object;
@@ -299,7 +305,7 @@ XtAppContext Xt_app_con;
 static String Xt_default_resources[] = {0};
 #endif /* USE_X_TOOLKIT */
 
-/* Nominal cursor position -- where to draw output.  
+/* Nominal cursor position -- where to draw output.
    HPOS and VPOS are window relative glyph matrix coordinates.
    X and Y are window relative pixel coordinates.  */
 
@@ -380,7 +386,7 @@ extern Lisp_Object Vcommand_line_args, Vsystem_name;
 
 extern Lisp_Object Vx_no_window_manager;
 
-extern Lisp_Object Qface, Qmouse_face;
+extern Lisp_Object Qface, Qmouse_face, Qeql;
 
 extern int errno;
 
@@ -391,9 +397,11 @@ extern EMACS_INT extra_keyboard_modifiers;
 /* The keysyms to use for the various modifiers.  */
 
 Lisp_Object Vx_alt_keysym, Vx_hyper_keysym, Vx_meta_keysym, Vx_super_keysym;
+Lisp_Object Vx_keysym_table;
 static Lisp_Object Qalt, Qhyper, Qmeta, Qsuper, Qmodifier_value;
 
 static Lisp_Object Qvendor_specific_keysyms;
+static Lisp_Object Qlatin_1, Qutf_8;
 
 extern XrmDatabase x_load_resources P_ ((Display *, char *, char *, char *));
 extern Lisp_Object x_icon_type P_ ((struct frame *));
@@ -465,14 +473,27 @@ static void x_clear_cursor P_ ((struct window *));
 static void frame_highlight P_ ((struct frame *));
 static void frame_unhighlight P_ ((struct frame *));
 static void x_new_focus_frame P_ ((struct x_display_info *, struct frame *));
+static int  x_focus_changed P_ ((int,
+                                 int,
+                                 struct x_display_info *,
+                                 struct frame *,
+                                 struct input_event *,
+                                 int));
+static int  x_detect_focus_change P_ ((struct x_display_info *,
+                                       XEvent *,
+                                       struct input_event *,
+                                       int));
 static void XTframe_rehighlight P_ ((struct frame *));
 static void x_frame_rehighlight P_ ((struct x_display_info *));
 static void x_draw_hollow_cursor P_ ((struct window *, struct glyph_row *));
-static void x_draw_bar_cursor P_ ((struct window *, struct glyph_row *, int));
+static void x_draw_bar_cursor P_ ((struct window *, struct glyph_row *, int,
+                                  enum text_cursor_kinds));
 static int x_intersect_rectangles P_ ((XRectangle *, XRectangle *,
                                       XRectangle *));
 static void expose_frame P_ ((struct frame *, int, int, int, int));
 static int expose_window_tree P_ ((struct window *, XRectangle *));
+static void expose_overlaps P_ ((struct window *, struct glyph_row *,
+                                struct glyph_row *));
 static int expose_window P_ ((struct window *, XRectangle *));
 static void expose_area P_ ((struct window *, struct glyph_row *,
                             XRectangle *, enum glyph_row_area));
@@ -482,7 +503,7 @@ static void x_update_cursor_in_window_tree P_ ((struct window *, int));
 static void x_update_window_cursor P_ ((struct window *, int));
 static void x_erase_phys_cursor P_ ((struct window *));
 void x_display_and_set_cursor P_ ((struct window *, int, int, int, int, int));
-static void x_draw_fringe_bitmap P_ ((struct window *, struct glyph_row *, 
+static void x_draw_fringe_bitmap P_ ((struct window *, struct glyph_row *,
                                      enum fringe_bitmap_type, int left_p));
 
 static void x_clip_to_row P_ ((struct window *, struct glyph_row *,
@@ -505,6 +526,12 @@ static void x_scroll_bar_report_motion P_ ((struct frame **, Lisp_Object *,
                                            unsigned long *));
 static void x_check_fullscreen P_ ((struct frame *));
 static void x_check_fullscreen_move P_ ((struct frame *));
+static int handle_one_xevent P_ ((struct x_display_info *,
+                                  XEvent *,
+                                  struct input_event **,
+                                  int *,
+                                  int *));
+
 
 /* Flush display of frame F, or of all frames if F is null.  */
 
@@ -532,7 +559,7 @@ x_flush (f)
    XTread_socket calls XPending.  Removing XFlush improves
    performance.  */
 
-#define XFlush(DISPLAY)        (void) 0 
+#define XFlush(DISPLAY)        (void) 0
 
 \f
 /***********************************************************************
@@ -544,7 +571,7 @@ x_flush (f)
 /* This is a function useful for recording debugging information about
    the sequence of occurrences in this file.  */
 
-struct record 
+struct record
 {
   char *locus;
   int type;
@@ -590,7 +617,7 @@ x_display_info_for_display (dpy)
 /***********************************************************************
                    Starting and ending an update
  ***********************************************************************/
-                                                                       
+
 /* Start an update of frame F.  This function is installed as a hook
    for update_begin, i.e. it is called when update_begin is called.
    This function is called prior to calls to x_update_window_begin for
@@ -615,7 +642,7 @@ x_update_window_begin (w)
 {
   struct frame *f = XFRAME (WINDOW_FRAME (w));
   struct x_display_info *display_info = FRAME_X_DISPLAY_INFO (f);
-  
+
   updated_window = w;
   set_output_cursor (&w->cursor);
 
@@ -637,7 +664,7 @@ x_update_window_begin (w)
         flag set.  So, rows containing mouse-face glyphs are never
         scrolled, and we don't have to switch the mouse highlight off
         here to prevent it from being scrolled.  */
-      
+
       /* Can we tell that this update does not affect the window
         where the mouse highlight is?  If so, no need to turn off.
         Likewise, don't do anything if the frame is garbaged;
@@ -670,7 +697,7 @@ x_draw_vertical_border (w)
      struct window *w;
 {
   struct frame *f = XFRAME (WINDOW_FRAME (w));
-  
+
   /* Redraw borders between horizontally adjacent windows.  Don't
      do it for frames with vertical scroll bars because either the
      right scroll bar of a window, or the left scroll bar of its
@@ -683,13 +710,13 @@ x_draw_vertical_border (w)
       window_box_edges (w, -1, &x0, &y0, &x1, &y1);
       x1 += FRAME_X_RIGHT_FRINGE_WIDTH (f);
       y1 -= 1;
-      
-      XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), 
+
+      XDrawLine (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                 f->output_data.x->normal_gc, x1, y0, x1, y1);
     }
 }
-   
-   
+
+
 /* End update of window W (which is equal to updated_window).
 
    Draw vertical borders between horizontally adjacent windows, and
@@ -709,7 +736,7 @@ x_update_window_end (w, cursor_on_p, mouse_face_overwritten_p)
      int cursor_on_p, mouse_face_overwritten_p;
 {
   struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (XFRAME (w->frame));
-      
+
   if (!w->pseudo_window_p)
     {
       BLOCK_INPUT;
@@ -718,11 +745,11 @@ x_update_window_end (w, cursor_on_p, mouse_face_overwritten_p)
        x_display_and_set_cursor (w, 1, output_cursor.hpos,
                                  output_cursor.vpos,
                                  output_cursor.x, output_cursor.y);
-      
+
       x_draw_vertical_border (w);
       UNBLOCK_INPUT;
     }
-  
+
   /* If a row with mouse-face was overwritten, arrange for
      XTframe_up_to_date to redisplay the mouse highlight.  */
   if (mouse_face_overwritten_p)
@@ -731,7 +758,7 @@ x_update_window_end (w, cursor_on_p, mouse_face_overwritten_p)
       dpyinfo->mouse_face_end_row = dpyinfo->mouse_face_end_col = -1;
       dpyinfo->mouse_face_window = Qnil;
     }
-      
+
   updated_window = NULL;
 }
 
@@ -793,16 +820,16 @@ x_after_update_window_line (desired_row)
   struct window *w = updated_window;
   struct frame *f;
   int width, height;
-  
+
   xassert (w);
-  
+
   if (!desired_row->mode_line_p && !w->pseudo_window_p)
     {
       BLOCK_INPUT;
       x_draw_row_fringe_bitmaps (w, desired_row);
       UNBLOCK_INPUT;
     }
-      
+
   /* When a window has disappeared, make sure that no rest of
      full-width rows stays visible in the internal border.  Could
      check here if updated_window is the leftmost/rightmost window,
@@ -823,7 +850,7 @@ x_after_update_window_line (desired_row)
       if (WINDOWP (f->tool_bar_window)
          && w == XWINDOW (f->tool_bar_window))
        y -= width;
-      
+
       BLOCK_INPUT;
       x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                    0, y, width, height, False);
@@ -876,13 +903,13 @@ x_draw_fringe_bitmap (w, row, which, left_p)
       h = left_height;
       bits = left_bits;
       break;
-      
+
     case OVERLAY_ARROW_BITMAP:
       wd = ov_width;
       h = ov_height;
       bits = ov_bits;
       break;
-      
+
     case RIGHT_TRUNCATION_BITMAP:
       wd = right_width;
       h = right_height;
@@ -894,7 +921,7 @@ x_draw_fringe_bitmap (w, row, which, left_p)
       h = continued_height;
       bits = continued_bits;
       break;
-      
+
     case CONTINUATION_LINE_BITMAP:
       wd = continuation_width;
       h = continuation_height;
@@ -961,7 +988,7 @@ x_draw_fringe_bitmap (w, row, which, left_p)
   if (b1 >= 0)
     {
       int header_line_height = WINDOW_DISPLAY_HEADER_LINE_HEIGHT (w);
-      
+
       /* In case the same realized face is used for fringes and
         for something displayed in the text (e.g. face `region' on
         mono-displays, the fill style may have been changed to
@@ -970,7 +997,7 @@ x_draw_fringe_bitmap (w, row, which, left_p)
        XSetFillStyle (display, face->gc, FillOpaqueStippled);
       else
        XSetForeground (display, face->gc, face->background);
-      
+
       XFillRectangle (display, window, face->gc,
                      b1,
                      WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
@@ -991,7 +1018,7 @@ x_draw_fringe_bitmap (w, row, which, left_p)
       XCopyArea (display, pixmap, window, gc, 0, 0, wd, h, x, y + dy);
       XFreePixmap (display, pixmap);
     }
-  
+
   XSetClipMask (display, gc, None);
 }
 
@@ -1091,7 +1118,7 @@ set_output_cursor (cursor)
 
    HPOS and VPOS are column/row positions in a window glyph matrix.  X
    and Y are window text area relative pixel positions.
-   
+
    If this is done during an update, updated_window will contain the
    window that is being updated and the position is the future output
    cursor position for that window.  If updated_window is null, use
@@ -1246,6 +1273,7 @@ x_encode_char (c, char2b, font_info)
        {
          ccl->reg[0] = charset;
          ccl->reg[1] = char2b->byte2;
+         ccl->reg[2] = -1;
        }
       else
        {
@@ -1253,9 +1281,9 @@ x_encode_char (c, char2b, font_info)
          ccl->reg[1] = char2b->byte1;
          ccl->reg[2] = char2b->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 */
@@ -1268,11 +1296,11 @@ x_encode_char (c, char2b, font_info)
       /* Fixed encoding scheme.  See fontset.h for the meaning of the
         encoding numbers.  */
       int enc = font_info->encoding[charset];
-      
+
       if ((enc == 1 || enc == 2)
          && CHARSET_DIMENSION (charset) == 2)
        char2b->byte1 |= 0x80;
-      
+
       if (enc == 1 || enc == 3)
        char2b->byte2 |= 0x80;
     }
@@ -1313,7 +1341,7 @@ x_get_char_face_and_encoding (f, c, face_id, char2b, multibyte_p, display_p)
   else
     {
       int c1, c2, charset;
-      
+
       /* Split characters into bytes.  If c2 is -1 afterwards, C is
         really a one-byte character so that byte1 is zero.  */
       SPLIT_CHAR (c, charset, c1, c2);
@@ -1338,7 +1366,7 @@ x_get_char_face_and_encoding (f, c, face_id, char2b, multibyte_p, display_p)
       xassert (face != NULL);
       PREPARE_FACE_FOR_DISPLAY (f, face);
     }
-  
+
   return face;
 }
 
@@ -1379,7 +1407,7 @@ x_get_glyph_face_and_encoding (f, glyph, char2b, two_byte_p)
   else
     {
       int c1, c2, charset;
-      
+
       /* Split characters into bytes.  If c2 is -1 afterwards, C is
         really a one-byte character so that byte1 is zero.  */
       SPLIT_CHAR (glyph->u.ch, charset, c1, c2);
@@ -1410,7 +1438,7 @@ x_get_glyph_face_and_encoding (f, glyph, char2b, two_byte_p)
 }
 
 
-/* Store one glyph for IT->char_to_display in IT->glyph_row.  
+/* Store one glyph for IT->char_to_display in IT->glyph_row.
    Called from x_produce_glyphs when IT->glyph_row is non-null.  */
 
 static INLINE void
@@ -1419,10 +1447,10 @@ x_append_glyph (it)
 {
   struct glyph *glyph;
   enum glyph_row_area area = it->area;
-  
+
   xassert (it->glyph_row);
   xassert (it->char_to_display != '\n' && it->char_to_display != '\t');
-  
+
   glyph = it->glyph_row->glyphs[area] + it->glyph_row->used[area];
   if (glyph < it->glyph_row->glyphs[area + 1])
     {
@@ -1444,7 +1472,7 @@ x_append_glyph (it)
     }
 }
 
-/* Store one glyph for the composition IT->cmp_id in IT->glyph_row.  
+/* Store one glyph for the composition IT->cmp_id in IT->glyph_row.
    Called from x_produce_glyphs when IT->glyph_row is non-null.  */
 
 static INLINE void
@@ -1453,9 +1481,9 @@ x_append_composite_glyph (it)
 {
   struct glyph *glyph;
   enum glyph_row_area area = it->area;
-  
+
   xassert (it->glyph_row);
-  
+
   glyph = it->glyph_row->glyphs[area] + it->glyph_row->used[area];
   if (glyph < it->glyph_row->glyphs[area + 1])
     {
@@ -1525,7 +1553,7 @@ x_produce_image_glyph (it)
   it->pixel_width = img->width + 2 * img->hmargin;
 
   it->nglyphs = 1;
-  
+
   if (face->box != FACE_NO_BOX)
     {
       if (face->box_line_width > 0)
@@ -1533,7 +1561,7 @@ x_produce_image_glyph (it)
          it->ascent += face->box_line_width;
          it->descent += face->box_line_width;
        }
-      
+
       if (it->start_of_box_run_p)
        it->pixel_width += abs (face->box_line_width);
       if (it->end_of_box_run_p)
@@ -1541,12 +1569,12 @@ x_produce_image_glyph (it)
     }
 
   take_vertical_position_into_account (it);
-  
+
   if (it->glyph_row)
     {
       struct glyph *glyph;
       enum glyph_row_area area = it->area;
-      
+
       glyph = it->glyph_row->glyphs[area] + it->glyph_row->used[area];
       if (glyph < it->glyph_row->glyphs[area + 1])
        {
@@ -1570,10 +1598,10 @@ x_produce_image_glyph (it)
 
 
 /* Append a stretch glyph to IT->glyph_row.  OBJECT is the source
-   of the glyph, WIDTH and HEIGHT are the width and height of the 
-   stretch.  ASCENT is the percentage/100 of HEIGHT to use for the 
+   of the glyph, WIDTH and HEIGHT are the width and height of the
+   stretch.  ASCENT is the percentage/100 of HEIGHT to use for the
    ascent of the glyph (0 <= ASCENT <= 1).  */
-  
+
 static void
 x_append_stretch_glyph (it, object, width, height, ascent)
      struct it *it;
@@ -1585,7 +1613,7 @@ x_append_stretch_glyph (it, object, width, height, ascent)
   enum glyph_row_area area = it->area;
 
   xassert (ascent >= 0 && ascent <= 1);
-  
+
   glyph = it->glyph_row->glyphs[area] + it->glyph_row->used[area];
   if (glyph < it->glyph_row->glyphs[area + 1])
     {
@@ -1614,7 +1642,7 @@ x_append_stretch_glyph (it, object, width, height, ascent)
    being recognized:
 
    1. `:width WIDTH' specifies that the space should be WIDTH *
-   canonical char width wide.  WIDTH may be an integer or floating 
+   canonical char width wide.  WIDTH may be an integer or floating
    point number.
 
    2. `:relative-width FACTOR' specifies that the width of the stretch
@@ -1624,7 +1652,7 @@ x_append_stretch_glyph (it, object, width, height, ascent)
    3. `:align-to HPOS' specifies that the space should be wide enough
    to reach HPOS, a value in canonical character units.
 
-   Exactly one of the above pairs must be present.  
+   Exactly one of the above pairs must be present.
 
    4. `:height HEIGHT' specifies that the height of the stretch produced
    should be HEIGHT, measured in canonical character units.
@@ -1662,7 +1690,7 @@ x_produce_stretch_glyph (it)
   XFontStruct *font = face->font ? face->font : FRAME_FONT (it->f);
 
   PREPARE_FACE_FOR_DISPLAY (it->f, face);
-  
+
   /* List should start with `space'.  */
   xassert (CONSP (it->object) && EQ (XCAR (it->object), Qspace));
   plist = XCDR (it->object);
@@ -1680,7 +1708,7 @@ x_produce_stretch_glyph (it)
         property.  */
       struct it it2;
       unsigned char *p = BYTE_POS_ADDR (IT_BYTEPOS (*it));
-      
+
       it2 = *it;
       if (it->multibyte_p)
        {
@@ -1702,7 +1730,7 @@ x_produce_stretch_glyph (it)
   else
     /* Nothing specified -> width defaults to canonical char width.  */
     width = CANON_X_UNIT (it->f);
-  
+
   /* Compute height.  */
   if (prop = Fplist_get (plist, QCheight),
       NUMVAL (prop) > 0)
@@ -1713,7 +1741,7 @@ x_produce_stretch_glyph (it)
   else
     height = FONT_HEIGHT (font);
 
-  /* Compute percentage of height used for ascent.  If 
+  /* Compute percentage of height used for ascent.  If
      `:ascent ASCENT' is present and valid, use that.  Otherwise,
      derive the ascent from the font in use.  */
   if (prop = Fplist_get (plist, QCascent),
@@ -1747,13 +1775,13 @@ x_produce_stretch_glyph (it)
          it->ascent += face->box_line_width;
          it->descent += face->box_line_width;
        }
-      
+
       if (it->start_of_box_run_p)
        it->pixel_width += abs (face->box_line_width);
       if (it->end_of_box_run_p)
        it->pixel_width += abs (face->box_line_width);
     }
-  
+
   take_vertical_position_into_account (it);
 }
 
@@ -1844,7 +1872,7 @@ x_produce_glyphs (it)
              face = FACE_FROM_ID (it->f, it->face_id);
            }
        }
-      
+
       /* Get font to use.  Encode IT->char_to_display.  */
       x_get_char_face_and_encoding (it->f, it->char_to_display,
                                    it->face_id, &char2b,
@@ -1905,7 +1933,7 @@ x_produce_glyphs (it)
          if (face->box != FACE_NO_BOX)
            {
              int thick = face->box_line_width;
-             
+
              if (thick > 0)
                {
                  it->ascent += thick;
@@ -1926,7 +1954,7 @@ x_produce_glyphs (it)
            it->ascent += 2;
 
          take_vertical_position_into_account (it);
-  
+
          /* If we have to actually produce glyphs, do it.  */
          if (it->glyph_row)
            {
@@ -1935,7 +1963,7 @@ x_produce_glyphs (it)
                  /* Translate a space with a `space-width' property
                     into a stretch glyph.  */
                  double ascent = (double) font->ascent / FONT_HEIGHT (font);
-                 x_append_stretch_glyph (it, it->object, it->pixel_width, 
+                 x_append_stretch_glyph (it, it->object, it->pixel_width,
                                          it->ascent + it->descent, ascent);
                }
              else
@@ -1955,7 +1983,7 @@ x_produce_glyphs (it)
          it->nglyphs = 0;
          it->ascent = it->phys_ascent = font->ascent + boff;
          it->descent = it->phys_descent = font->descent - boff;
-      
+
          if (face->box != FACE_NO_BOX
              && face->box_line_width > 0)
            {
@@ -1974,20 +2002,20 @@ x_produce_glyphs (it)
             tab stop after that.  */
          if (next_tab_x - x < CANON_X_UNIT (it->f))
            next_tab_x += tab_width;
-      
+
          it->pixel_width = next_tab_x - x;
          it->nglyphs = 1;
          it->ascent = it->phys_ascent = font->ascent + boff;
          it->descent = it->phys_descent = font->descent - boff;
-         
+
          if (it->glyph_row)
            {
              double ascent = (double) it->ascent / (it->ascent + it->descent);
-             x_append_stretch_glyph (it, it->object, it->pixel_width, 
+             x_append_stretch_glyph (it, it->object, it->pixel_width,
                                      it->ascent + it->descent, ascent);
            }
        }
-      else 
+      else
        {
          /* A multi-byte character.  Assume that the display width of the
             character is the width of the character multiplied by the
@@ -2033,20 +2061,20 @@ x_produce_glyphs (it)
                }
              else
                thick = - thick;
-         
+
              if (it->start_of_box_run_p)
                it->pixel_width += thick;
              if (it->end_of_box_run_p)
                it->pixel_width += thick;
            }
-  
+
          /* If face has an overline, add the height of the overline
             (1 pixel) and a 1 pixel margin to the character height.  */
          if (face->overline_p)
            it->ascent += 2;
 
          take_vertical_position_into_account (it);
-  
+
          if (it->glyph_row)
            x_append_glyph (it);
        }
@@ -2075,7 +2103,7 @@ x_produce_glyphs (it)
        {
          it->char_to_display = unibyte_char_to_multibyte (it->c);
        }
-      
+
       /* Get face and font to use.  Encode IT->char_to_display.  */
       it->face_id = FACE_FOR_CHAR (it->f, face, it->char_to_display);
       face = FACE_FROM_ID (it->f, it->face_id);
@@ -2140,12 +2168,12 @@ x_produce_glyphs (it)
              ascent = font->ascent;
              descent = font->descent;
            }
-         
+
          rightmost = width;
          lowest = - descent + boff;
          highest = ascent + boff;
          leftmost = 0;
-         
+
          if (font_info
              && font_info->default_ascent
              && CHAR_TABLE_P (Vuse_default_ascent)
@@ -2165,7 +2193,7 @@ x_produce_glyphs (it)
              int left, right, btm, top;
              int ch = COMPOSITION_GLYPH (cmp, i);
              int face_id = FACE_FOR_CHAR (it->f, face, ch);
-             
+
              face = FACE_FROM_ID (it->f, face_id);
              x_get_char_face_and_encoding (it->f, ch, face->id, &char2b,
                                            it->multibyte_p, 0);
@@ -2306,20 +2334,20 @@ x_produce_glyphs (it)
            }
          else
            thick = - thick;
-         
+
          if (it->start_of_box_run_p)
            it->pixel_width += thick;
          if (it->end_of_box_run_p)
            it->pixel_width += thick;
        }
-  
+
       /* If face has an overline, add the height of the overline
         (1 pixel) and a 1 pixel margin to the character height.  */
       if (face->overline_p)
        it->ascent += 2;
 
       take_vertical_position_into_account (it);
-  
+
       if (it->glyph_row)
        x_append_composite_glyph (it);
     }
@@ -2333,9 +2361,9 @@ x_produce_glyphs (it)
   xassert (it->ascent >= 0 && it->descent >= 0);
   if (it->area == TEXT_AREA)
     it->current_x += it->pixel_width;
-  
+
   it->descent += it->extra_line_spacing;
-  
+
   it->max_ascent = max (it->max_ascent, it->ascent);
   it->max_descent = max (it->max_descent, it->descent);
   it->max_phys_ascent = max (it->max_phys_ascent, it->phys_ascent);
@@ -2366,7 +2394,7 @@ x_estimate_mode_line_height (f, face_id)
              height += 2 * face->box_line_width;
          }
       }
-  
+
   return height;
 }
 
@@ -2536,7 +2564,7 @@ static int x_fill_glyph_string P_ ((struct glyph_string *, int, int, int,
 static void x_init_glyph_string P_ ((struct glyph_string *,
                                        XChar2b *, struct window *,
                                        struct glyph_row *,
-                                       enum glyph_row_area, int, 
+                                       enum glyph_row_area, int,
                                        enum draw_glyphs_face));
 static int x_draw_glyphs P_ ((struct window *, int , struct glyph_row *,
                              enum glyph_row_area, int, int,
@@ -2692,11 +2720,11 @@ x_set_cursor_gc (s)
 
 
 /* Set up S->gc of glyph string S for drawing text in mouse face.  */
-   
+
 static void
 x_set_mouse_face_gc (s)
      struct glyph_string *s;
-{     
+{
   int face_id;
   struct face *face;
 
@@ -2705,7 +2733,7 @@ x_set_mouse_face_gc (s)
   face = FACE_FROM_ID (s->f, face_id);
   if (face == NULL)
     face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
-  
+
   if (s->first_glyph->type == CHAR_GLYPH)
     face_id = FACE_FOR_CHAR (s->f, face, s->first_glyph->u.ch);
   else
@@ -2722,21 +2750,21 @@ x_set_mouse_face_gc (s)
         but font FONT.  */
       XGCValues xgcv;
       unsigned long mask;
-      
+
       xgcv.background = s->face->background;
       xgcv.foreground = s->face->foreground;
       IF_DEBUG (x_check_font (s->f, s->font));
       xgcv.font = s->font->fid;
       xgcv.graphics_exposures = False;
       mask = GCForeground | GCBackground | GCFont | GCGraphicsExposures;
-      
+
       if (FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc)
        XChangeGC (s->display, FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc,
                   mask, &xgcv);
       else
        FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc
          = XCreateGC (s->display, s->window, mask, &xgcv);
-      
+
       s->gc = FRAME_X_DISPLAY_INFO (s->f)->scratch_cursor_gc;
     }
 
@@ -2751,7 +2779,7 @@ x_set_mouse_face_gc (s)
 static INLINE void
 x_set_mode_line_face_gc (s)
      struct glyph_string *s;
-{     
+{
   s->gc = s->face->gc;
 }
 
@@ -2765,7 +2793,7 @@ x_set_glyph_string_gc (s)
      struct glyph_string *s;
 {
   PREPARE_FACE_FOR_DISPLAY (s->f, s->face);
-  
+
   if (s->hl == DRAW_NORMAL_TEXT)
     {
       s->gc = s->face->gc;
@@ -2814,7 +2842,7 @@ x_get_glyph_string_clip_rect (s, r)
     {
       /* Draw full-width.  X coordinates are relative to S->w->left.  */
       int canon_x = CANON_X_UNIT (s->f);
-      
+
       r->x = WINDOW_LEFT_MARGIN (s->w) * canon_x;
       r->width = XFASTINT (s->w->width) * canon_x;
 
@@ -2824,9 +2852,9 @@ x_get_glyph_string_clip_rect (s, r)
          if (FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (s->f))
            r->x -= width;
        }
-      
+
       r->x += FRAME_INTERNAL_BORDER_WIDTH (s->f);
-      
+
       /* Unless displaying a mode or menu bar line, which are always
         fully visible, clip to the visible part of the row.  */
       if (s->w->pseudo_window_p)
@@ -2907,7 +2935,7 @@ x_compute_glyph_string_overhangs (s)
 /* Compute overhangs and x-positions for glyph string S and its
    predecessors, or successors.  X is the starting x-position for S.
    BACKWARD_P non-zero means process predecessors.  */
-   
+
 static void
 x_compute_overhangs_and_x (s, x, backward_p)
      struct glyph_string *s;
@@ -2948,7 +2976,7 @@ x_get_glyph_overhangs (glyph, f, left, right)
      int *left, *right;
 {
   *left = *right = 0;
-  
+
   if (glyph->type == CHAR_GLYPH)
     {
       XFontStruct *font;
@@ -2981,7 +3009,7 @@ x_left_overwritten (s)
      struct glyph_string *s;
 {
   int k;
-    
+
   if (s->left_overhang)
     {
       int x = 0, i;
@@ -3043,7 +3071,7 @@ x_right_overwritten (s)
       struct glyph *glyphs = s->row->glyphs[s->area];
       int first = (s->first_glyph - glyphs) + (s->cmp ? 1 : s->nchars);
       int end = s->row->used[s->area];
-      
+
       for (i = first; i < end && s->right_overhang > x; ++i)
        x += glyphs[i].pixel_width;
 
@@ -3206,6 +3234,18 @@ x_draw_glyph_string_foreground (s)
            XDrawImageString (s->display, s->window, s->gc, x,
                              s->ybase - boff, char1b, s->nchars);
        }
+
+      if (s->face->overstrike)
+       {
+         /* For overstriking (to simulate bold-face), draw the
+            characters again shifted to the right by one pixel.  */
+         if (s->two_byte_p)
+           XDrawString16 (s->display, s->window, s->gc, x + 1,
+                          s->ybase - boff, s->char2b, s->nchars);
+         else
+           XDrawString (s->display, s->window, s->gc, x + 1,
+                        s->ybase - boff, char1b, s->nchars);
+       }
     }
 }
 
@@ -3241,10 +3281,17 @@ x_draw_composite_glyph_string_foreground (s)
   else
     {
       for (i = 0; i < s->nchars; i++, ++s->gidx)
-       XDrawString16 (s->display, s->window, s->gc,
-                      x + s->cmp->offsets[s->gidx * 2],
-                      s->ybase - s->cmp->offsets[s->gidx * 2 + 1],
-                      s->char2b + i, 1);
+       {
+         XDrawString16 (s->display, s->window, s->gc,
+                        x + s->cmp->offsets[s->gidx * 2],
+                        s->ybase - s->cmp->offsets[s->gidx * 2 + 1],
+                        s->char2b + i, 1);
+         if (s->face->overstrike)
+           XDrawString16 (s->display, s->window, s->gc,
+                          x + s->cmp->offsets[s->gidx * 2] + 1,
+                          s->ybase - s->cmp->offsets[s->gidx * 2 + 1],
+                          s->char2b + i, 1);
+       }
     }
 }
 
@@ -3268,9 +3315,9 @@ x_frame_of_widget (widget)
   struct x_display_info *dpyinfo;
   Lisp_Object tail;
   struct frame *f;
-  
+
   dpyinfo = x_display_info_for_display (XtDisplay (widget));
-  
+
   /* Find the top-level shell of the widget.  Note that this function
      can be called when the widget is not yet realized, so XtWindow
      (widget) == 0.  That's the reason we can't simply use
@@ -3411,7 +3458,7 @@ cvt_string_to_pixel (dpy, args, nargs, from, to, closure_ret)
     {
       String params[1];
       Cardinal nparams = 1;
-      
+
       params[0] = color_name;
       XtAppWarningMsg (XtDisplayToApplicationContext (dpy),
                       "badValue", "cvt_string_to_pixel",
@@ -3427,7 +3474,7 @@ cvt_string_to_pixel (dpy, args, nargs, from, to, closure_ret)
          to->size = sizeof (Pixel);
          return False;
        }
-      
+
       *(Pixel *) to->addr = pixel;
     }
   else
@@ -3435,7 +3482,7 @@ cvt_string_to_pixel (dpy, args, nargs, from, to, closure_ret)
       cvt_string_to_pixel_value = pixel;
       to->addr = (XtPointer) &cvt_string_to_pixel_value;
     }
-  
+
   to->size = sizeof (Pixel);
   return True;
 }
@@ -3498,16 +3545,16 @@ x_color_cells (dpy, ncells)
     {
       Screen *screen = dpyinfo->screen;
       int i;
-      
+
       dpyinfo->ncolor_cells
        = XDisplayCells (dpy, XScreenNumberOfScreen (screen));
       dpyinfo->color_cells
        = (XColor *) xmalloc (dpyinfo->ncolor_cells
                              * sizeof *dpyinfo->color_cells);
-      
+
       for (i = 0; i < dpyinfo->ncolor_cells; ++i)
        dpyinfo->color_cells[i].pixel = i;
-      
+
       XQueryColors (dpy, dpyinfo->cmap,
                    dpyinfo->color_cells, dpyinfo->ncolor_cells);
     }
@@ -3554,7 +3601,7 @@ x_query_color (f, color)
 {
   x_query_colors (f, color, 1);
 }
-     
+
 
 /* Allocate the color COLOR->pixel on DISPLAY, colormap CMAP.  If an
    exact match can't be allocated, try the nearest color available.
@@ -3594,7 +3641,7 @@ x_alloc_nearest_color_1 (dpy, cmap, color)
              nearest_delta = delta;
            }
        }
-      
+
       color->red   = cells[nearest].red;
       color->green = cells[nearest].green;
       color->blue  = cells[nearest].blue;
@@ -3607,7 +3654,7 @@ x_alloc_nearest_color_1 (dpy, cmap, color)
          change in the colormap, so clear the color cache.  */
       struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
       XColor *cached_color;
-      
+
       if (dpyinfo->color_cells
          && (cached_color = &dpyinfo->color_cells[color->pixel],
              (cached_color->red != color->red
@@ -3624,7 +3671,7 @@ x_alloc_nearest_color_1 (dpy, cmap, color)
   if (rc)
     register_color (color->pixel);
 #endif /* DEBUG_X_COLORS */
-  
+
   return rc;
 }
 
@@ -3773,7 +3820,7 @@ x_alloc_lighter_color (f, display, cmap, pixel, factor, delta)
          /* If we end up with the same color as before, try adding
             delta to the RGB values.  */
          x_free_colors (f, &new.pixel, 1);
-         
+
          new.red = min (0xffff, delta + color.red);
          new.green = min (0xffff, delta + color.green);
          new.blue = min (0xffff, delta + color.blue);
@@ -3783,7 +3830,7 @@ x_alloc_lighter_color (f, display, cmap, pixel, factor, delta)
        success_p = 1;
       *pixel = new.pixel;
     }
-  
+
   return success_p;
 }
 
@@ -3794,7 +3841,7 @@ x_alloc_lighter_color (f, display, cmap, pixel, factor, delta)
    DELTA lighter or darker than the relief's background which is found
    in S->f->output_data.x->relief_background.  If such a color cannot
    be allocated, use DEFAULT_PIXEL, instead.  */
-   
+
 static void
 x_setup_relief_color (f, relief, factor, delta, default_pixel)
      struct frame *f;
@@ -3834,7 +3881,7 @@ x_setup_relief_color (f, relief, factor, delta, default_pixel)
       relief->allocated_p = 1;
       xgcv.foreground = relief->pixel = pixel;
     }
-  
+
   if (relief->gc == 0)
     {
       xgcv.stipple = dpyinfo->gray;
@@ -3864,7 +3911,7 @@ x_setup_relief_colors (s)
   else
     {
       XGCValues xgcv;
-      
+
       /* Get the background color of the face.  */
       XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
       color = xgcv.background;
@@ -3894,14 +3941,14 @@ static void
 x_draw_relief_rect (f, left_x, top_y, right_x, bottom_y, width,
                    raised_p, left_p, right_p, clip_rect)
      struct frame *f;
-     int left_x, top_y, right_x, bottom_y, left_p, right_p, raised_p;
+     int left_x, top_y, right_x, bottom_y, width, left_p, right_p, raised_p;
      XRectangle *clip_rect;
 {
   Display *dpy = FRAME_X_DISPLAY (f);
   Window window = FRAME_X_WINDOW (f);
   int i;
   GC gc;
-  
+
   if (raised_p)
     gc = f->output_data.x->white_relief.gc;
   else
@@ -3926,13 +3973,13 @@ x_draw_relief_rect (f, left_x, top_y, right_x, bottom_y, width,
   else
     gc = f->output_data.x->white_relief.gc;
   XSetClipRectangles (dpy, gc, 0, 0, clip_rect, 1, Unsorted);
-  
+
   /* Bottom.  */
   for (i = 0; i < width; ++i)
     XDrawLine (dpy, window, gc,
               left_x + i * left_p, bottom_y - i,
               right_x + 1 - i * right_p, bottom_y - i);
-  
+
   /* Right.  */
   if (right_p)
     for (i = 0; i < width; ++i)
@@ -3954,15 +4001,15 @@ static void
 x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
                 left_p, right_p, clip_rect)
      struct glyph_string *s;
-     int left_x, top_y, right_x, bottom_y, left_p, right_p;
+     int left_x, top_y, right_x, bottom_y, width, left_p, right_p;
      XRectangle *clip_rect;
 {
   XGCValues xgcv;
-  
+
   XGetGCValues (s->display, s->gc, GCForeground, &xgcv);
   XSetForeground (s->display, s->gc, s->face->box_color);
   XSetClipRectangles (s->display, s->gc, 0, 0, clip_rect, 1, Unsorted);
-  
+
   /* Top.  */
   XFillRectangle (s->display, s->window, s->gc,
                  left_x, top_y, right_x - left_x + 1, width);
@@ -3975,7 +4022,7 @@ x_draw_box_rect (s, left_x, top_y, right_x, bottom_y, width,
   /* Bottom.  */
   XFillRectangle (s->display, s->window, s->gc,
                  left_x, bottom_y - width + 1, right_x - left_x + 1, width);
-  
+
   /* Right.  */
   if (right_p)
     XFillRectangle (s->display, s->window, s->gc,
@@ -4005,7 +4052,7 @@ x_draw_glyph_string_box (s)
       if (FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (s->f))
        last_x += FRAME_SCROLL_BAR_WIDTH (s->f) * CANON_X_UNIT (s->f);
     }
-  
+
   /* The glyph that may have a right box line.  */
   last_glyph = (s->cmp || s->img
                ? s->first_glyph
@@ -4084,7 +4131,7 @@ x_draw_image_foreground (s)
          xgcv.clip_y_origin = y;
          xgcv.function = GXcopy;
          XChangeGC (s->display, s->gc, mask, &xgcv);
-         
+
          x_get_glyph_string_clip_rect (s, &clip_rect);
          image_rect.x = x;
          image_rect.y = y;
@@ -4106,7 +4153,7 @@ x_draw_image_foreground (s)
          if (x_intersect_rectangles (&clip_rect, &image_rect, &r))
            XCopyArea (s->display, s->img->pixmap, s->window, s->gc,
                       r.x - x, r.y - y, r.width, r.height, r.x, r.y);
-         
+
          /* When the image has a mask, we can expect that at
             least part of a mouse highlight or a block cursor will
             be visible.  If the image doesn't have a mask, make
@@ -4114,8 +4161,12 @@ x_draw_image_foreground (s)
             the image.  I believe it's looking better if we do
             nothing here for mouse-face.  */
          if (s->hl == DRAW_CURSOR)
-           XDrawRectangle (s->display, s->window, s->gc, x, y,
-                           s->img->width - 1, s->img->height - 1);
+           {
+             int r = s->img->relief;
+             if (r < 0) r = -r;
+             XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
+                             s->img->width + r*2 - 1, s->img->height + r*2 - 1);
+           }
        }
     }
   else
@@ -4135,7 +4186,7 @@ x_draw_image_relief (s)
   XRectangle r;
   int x;
   int y = s->ybase - image_ascent (s->img, s->face);
-  
+
   /* If first glyph of S has a left box line, start drawing it to the
      right of that line.  */
   if (s->face->box != FACE_NO_BOX
@@ -4143,12 +4194,12 @@ x_draw_image_relief (s)
     x = s->x + abs (s->face->box_line_width);
   else
     x = s->x;
-  
+
   /* If there is a margin around the image, adjust x- and y-position
      by that margin.  */
   x += s->img->hmargin;
   y += s->img->vmargin;
-  
+
   if (s->hl == DRAW_IMAGE_SUNKEN
       || s->hl == DRAW_IMAGE_RAISED)
     {
@@ -4160,12 +4211,12 @@ x_draw_image_relief (s)
       thick = abs (s->img->relief);
       raised_p = s->img->relief > 0;
     }
-  
+
   x0 = x - thick;
   y0 = y - thick;
   x1 = x + s->img->width + thick - 1;
   y1 = y + s->img->height + thick - 1;
-  
+
   x_setup_relief_colors (s);
   x_get_glyph_string_clip_rect (s, &r);
   x_draw_relief_rect (s->f, x0, y0, x1, y1, thick, raised_p, 1, 1, &r);
@@ -4222,7 +4273,7 @@ x_draw_image_foreground_1 (s, pixmap)
        {
          XCopyArea (s->display, s->img->pixmap, pixmap, s->gc,
                     0, 0, s->img->width, s->img->height, x, y);
-         
+
          /* When the image has a mask, we can expect that at
             least part of a mouse highlight or a block cursor will
             be visible.  If the image doesn't have a mask, make
@@ -4230,8 +4281,12 @@ x_draw_image_foreground_1 (s, pixmap)
             the image.  I believe it's looking better if we do
             nothing here for mouse-face.  */
          if (s->hl == DRAW_CURSOR)
-           XDrawRectangle (s->display, pixmap, s->gc, x, y,
-                           s->img->width - 1, s->img->height - 1);
+           {
+             int r = s->img->relief;
+             if (r < 0) r = -r;
+             XDrawRectangle (s->display, s->window, s->gc, x - r, y - r,
+                             s->img->width + r*2 - 1, s->img->height + r*2 - 1);
+           }
        }
     }
   else
@@ -4261,7 +4316,7 @@ x_draw_glyph_string_bg_rect (s, x, y, w, h)
 }
 
 
-/* Draw image glyph string S.  
+/* Draw image glyph string S.
 
             s->y
    s->x      +-------------------------
@@ -4287,6 +4342,7 @@ x_draw_image_glyph_string (s)
 
   height = s->height - 2 * box_line_vwidth;
 
+
   /* Fill background with face under the image.  Do it only if row is
      taller than image or if image has a clip mask to reduce
      flickering.  */
@@ -4302,9 +4358,9 @@ x_draw_image_glyph_string (s)
        x = s->x + box_line_hwidth;
       else
        x = s->x;
-      
+
       y = s->y + box_line_vwidth;
-      
+
       if (s->img->mask)
        {
          /* Create a pixmap as large as the glyph string.  Fill it
@@ -4317,7 +4373,7 @@ x_draw_image_glyph_string (s)
          pixmap = XCreatePixmap (s->display, s->window,
                                  s->background_width,
                                  s->height, depth);
-         
+
          /* Don't clip in the following because we're working on the
             pixmap.  */
          XSetClipMask (s->display, s->gc, None);
@@ -4344,7 +4400,7 @@ x_draw_image_glyph_string (s)
        }
       else
        x_draw_glyph_string_bg_rect (s, x, y, s->background_width, height);
-      
+
       s->background_filled_p = 1;
     }
 
@@ -4403,10 +4459,10 @@ x_draw_stretch_glyph_string (s)
            }
          else
            gc = s->face->gc;
-  
+
          x_get_glyph_string_clip_rect (s, &r);
          XSetClipRectangles (s->display, gc, 0, 0, &r, 1, Unsorted);
-         
+
          if (s->face->stipple)
            {
              /* Fill background with a stipple pattern.  */
@@ -4427,7 +4483,7 @@ x_draw_stretch_glyph_string (s)
   else if (!s->background_filled_p)
     x_draw_glyph_string_bg_rect (s, s->x, s->y, s->background_width,
                                 s->height);
-  
+
   s->background_filled_p = 1;
 }
 
@@ -4520,7 +4576,7 @@ x_draw_glyph_string (s)
 
             ROUND ((maximum descent) / 2), with
             ROUND(x) = floor (x + 0.5)  */
-         
+
          if (x_use_underline_position_properties
              && XGetFontProperty (s->font, XA_UNDERLINE_POSITION, &tem))
            y = s->ybase + (long) tem;
@@ -4528,7 +4584,7 @@ x_draw_glyph_string (s)
            y = s->ybase + (s->face->font->max_bounds.descent + 1) / 2;
          else
            y = s->y + s->height - h;
-      
+
          if (s->face->underline_defaulted_p)
            XFillRectangle (s->display, s->window, s->gc,
                            s->x, y, s->width, h);
@@ -4561,7 +4617,7 @@ x_draw_glyph_string (s)
              XSetForeground (s->display, s->gc, xgcv.foreground);
            }
        }
-  
+
       /* Draw strike-through.  */
       if (s->face->strike_through_p)
        {
@@ -4581,12 +4637,12 @@ x_draw_glyph_string (s)
              XSetForeground (s->display, s->gc, xgcv.foreground);
            }
        }
-  
+
       /* Draw relief if not yet drawn.  */
       if (!relief_drawn_p && s->face->box != FACE_NO_BOX)
        x_draw_glyph_string_box (s);
     }
-  
+
   /* Reset clipping.  */
   XSetClipMask (s->display, s->gc, None);
 }
@@ -4597,7 +4653,7 @@ static int x_fill_composite_glyph_string P_ ((struct glyph_string *,
 
 
 /* Fill glyph string S with composition components specified by S->cmp.
-   
+
    FACES is an array of faces for all components of this composition.
    S->gidx is the index of the first component for S.
    OVERLAPS_P non-zero means S should draw the foreground only, and
@@ -4616,7 +4672,7 @@ x_fill_composite_glyph_string (s, faces, overlaps_p)
   xassert (s);
 
   s->for_overlaps_p = overlaps_p;
-  
+
   s->face = faces[s->gidx];
   s->font = s->face->font;
   s->font_info = FONT_INFO_FROM_ID (s->f, s->face->font_info_id);
@@ -4645,7 +4701,7 @@ x_fill_composite_glyph_string (s, faces, overlaps_p)
 
   /* Adjust base line for subscript/superscript text.  */
   s->ybase += s->first_glyph->voffset;
-  
+
   xassert (s->face && s->face->gc);
 
   /* This glyph string must always be drawn with 16-bit functions.  */
@@ -4656,7 +4712,7 @@ x_fill_composite_glyph_string (s, faces, overlaps_p)
 
 
 /* Fill glyph string S from a sequence of character glyphs.
-   
+
    FACE_ID is the face id of the string.  START is the index of the
    first glyph to consider, END is the index of the last + 1.
    OVERLAPS_P non-zero means S should draw the foreground only, and
@@ -4673,7 +4729,7 @@ x_fill_glyph_string (s, face_id, start, end, overlaps_p)
   struct glyph *glyph, *last;
   int voffset;
   int glyph_not_available_p;
-  
+
   xassert (s->f == XFRAME (s->w->frame));
   xassert (s->nchars == 0);
   xassert (start >= 0 && end > start);
@@ -4682,7 +4738,7 @@ x_fill_glyph_string (s, face_id, start, end, overlaps_p)
   glyph = s->row->glyphs[s->area] + start;
   last = s->row->glyphs[s->area] + end;
   voffset = glyph->voffset;
-  
+
   glyph_not_available_p = glyph->glyph_not_available_p;
 
   while (glyph < last
@@ -4706,7 +4762,7 @@ x_fill_glyph_string (s, face_id, start, end, overlaps_p)
 
   s->font = s->face->font;
   s->font_info = FONT_INFO_FROM_ID (s->f, s->face->font_info_id);
-  
+
   /* If the specified font could not be loaded, use the frame's font,
      but record the fact that we couldn't load it in
      S->font_not_found_p so that we can draw rectangles for the
@@ -4737,7 +4793,7 @@ x_fill_image_glyph_string (s)
   s->face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
   s->font = s->face->font;
   s->width = s->first_glyph->pixel_width;
-  
+
   /* Adjust base line for subscript/superscript text.  */
   s->ybase += s->first_glyph->voffset;
 }
@@ -4760,9 +4816,9 @@ x_fill_stretch_glyph_string (s, row, area, start, end)
 {
   struct glyph *glyph, *last;
   int voffset, face_id;
-  
+
   xassert (s->first_glyph->type == STRETCH_GLYPH);
-  
+
   glyph = s->row->glyphs[s->area] + start;
   last = s->row->glyphs[s->area] + end;
   face_id = glyph->face_id;
@@ -4779,7 +4835,7 @@ x_fill_stretch_glyph_string (s, row, area, start, end)
        && glyph->face_id == face_id);
        ++glyph)
     s->width += glyph->pixel_width;
-  
+
   /* Adjust base line for subscript/superscript text.  */
   s->ybase += voffset;
 
@@ -4797,7 +4853,7 @@ x_fill_stretch_glyph_string (s, row, area, start, end)
    and area within the row from which S is constructed.  START is the
    index of the first glyph structure covered by S.  HL is a
    face-override for drawing S.  */
-   
+
 static void
 x_init_glyph_string (s, char2b, w, row, area, start, hl)
      struct glyph_string *s;
@@ -4824,7 +4880,7 @@ x_init_glyph_string (s, char2b, w, row, area, start, hl)
   /* Display the internal border below the tool-bar window.  */
   if (s->w == XWINDOW (s->f->tool_bar_window))
     s->y -= s->f->output_data.x->internal_border_width;
-  
+
   s->ybase = s->y + row->ascent;
 }
 
@@ -4842,7 +4898,7 @@ x_set_glyph_string_background_width (s, start, last_x)
   /* If the face of this glyph string has to be drawn to the end of
      the drawing area, set S->extends_to_end_of_line_p.  */
   struct face *default_face = FACE_FROM_ID (s->f, DEFAULT_FACE_ID);
-  
+
   if (start == s->row->used[s->area]
       && s->area == TEXT_AREA
       && ((s->hl == DRAW_NORMAL_TEXT
@@ -4854,7 +4910,7 @@ x_set_glyph_string_background_width (s, start, last_x)
          || ((s->hl == DRAW_IMAGE_RAISED || s->hl == DRAW_IMAGE_SUNKEN)
              && s->row->fill_line_p)))
       s->extends_to_end_of_line_p = 1;
-  
+
   /* If S extends its face to the end of the line, set its
      background_width to the distance to the right edge of the drawing
      area.  */
@@ -4935,7 +4991,7 @@ x_set_glyph_string_background_width (s, start, last_x)
                                           OVERLAPS_P);                    \
        }                                                                  \
      while (0)
-     
+
 
 /* Add a glyph string for a composite sequence to the list of strings
    between HEAD and TAIL.  START is the index of the first glyph in
@@ -4991,7 +5047,7 @@ x_set_glyph_string_background_width (s, start, last_x)
     ++START;                                                             \
     s = first_s;                                                         \
   } while (0)
-    
+
 
 /* Build a list of glyph strings between HEAD and TAIL for the glyphs
    of AREA of glyph row ROW on window W between indices START and END.
@@ -5060,7 +5116,7 @@ x_set_glyph_string_background_width (s, start, last_x)
    and clip to the physical height of ROW.
 
    Value is the x-position reached, relative to AREA of W.  */
-     
+
 static int
 x_draw_glyphs (w, x, row, area, start, end, hl, overlaps_p)
      struct window *w;
@@ -5141,7 +5197,7 @@ x_draw_glyphs (w, x, row, area, start, end, hl, overlaps_p)
       /* Prepend glyph strings for glyphs in front of the first glyph
         string that are overwritten because of the first glyph
         string's left overhang.  The background of all strings
-        prepended must be drawn because the first glyph string 
+        prepended must be drawn because the first glyph string
         draws over it.  */
       i = x_left_overwritten (head);
       if (i >= 0)
@@ -5219,10 +5275,10 @@ x_draw_glyphs (w, x, row, area, start, end, hl, overlaps_p)
     {
       int x0 = head ? head->x : x;
       int x1 = tail ? tail->x + tail->background_width : x;
-      
+
       x0 = FRAME_TO_WINDOW_PIXEL_X (w, x0);
       x1 = FRAME_TO_WINDOW_PIXEL_X (w, x1);
-      
+
       if (XFASTINT (w->left_margin_width) != 0)
        {
          int left_area_width = window_box_width (w, LEFT_MARGIN_AREA);
@@ -5244,7 +5300,7 @@ x_draw_glyphs (w, x, row, area, start, end, hl, overlaps_p)
       if (area > TEXT_AREA)
        x_reached -= window_box_width (w, TEXT_AREA);
     }
-  
+
   return x_reached;
 }
 
@@ -5258,9 +5314,9 @@ x_fix_overlapping_area (w, row, area)
      enum glyph_row_area area;
 {
   int i, x;
-  
+
   BLOCK_INPUT;
-  
+
   if (area == LEFT_MARGIN_AREA)
     x = 0;
   else if (area == TEXT_AREA)
@@ -5292,7 +5348,7 @@ x_fix_overlapping_area (w, row, area)
          ++i;
        }
     }
-  
+
   UNBLOCK_INPUT;
 }
 
@@ -5312,7 +5368,7 @@ x_write_glyphs (start, len)
 
   xassert (updated_window && updated_row);
   BLOCK_INPUT;
-  
+
   /* Write glyphs.  */
 
   hpos = start - updated_row->glyphs[updated_area];
@@ -5321,8 +5377,16 @@ x_write_glyphs (start, len)
                     hpos, hpos + len,
                     DRAW_NORMAL_TEXT, 0);
 
+  /* Invalidate old phys cursor if the glyph at its hpos is redrawn.  */
+  if (updated_area == TEXT_AREA
+      && updated_window->phys_cursor_on_p
+      && updated_window->phys_cursor.vpos == output_cursor.vpos
+      && updated_window->phys_cursor.hpos >= hpos
+      && updated_window->phys_cursor.hpos < hpos + len)
+    updated_window->phys_cursor_on_p = 0;
+
   UNBLOCK_INPUT;
-  
+
   /* Advance the output cursor.  */
   output_cursor.hpos += len;
   output_cursor.x = x;
@@ -5375,7 +5439,7 @@ x_insert_glyphs (start, len)
   hpos = start - row->glyphs[updated_area];
   x_draw_glyphs (w, output_cursor.x, row, updated_area, hpos, hpos + len,
                 DRAW_NORMAL_TEXT, 0);
-  
+
   /* Advance the output cursor.  */
   output_cursor.hpos += len;
   output_cursor.x += shift_by_width;
@@ -5425,10 +5489,10 @@ x_clear_end_of_line (to_x)
   struct window *w = updated_window;
   int max_x, min_y, max_y;
   int from_x, from_y, to_y;
-  
+
   xassert (updated_window && updated_row);
   f = XFRAME (w->frame);
-  
+
   if (updated_row->full_width_p)
     {
       max_x = XFASTINT (w->width) * CANON_X_UNIT (f);
@@ -5450,7 +5514,7 @@ x_clear_end_of_line (to_x)
     to_x = min (to_x, max_x);
 
   to_y = min (max_y, output_cursor.y + updated_row->height);
-  
+
   /* Notice if the cursor will be cleared by this operation.  */
   if (!updated_row->full_width_p)
     notice_overwritten_cursor (w, updated_area,
@@ -5459,7 +5523,7 @@ x_clear_end_of_line (to_x)
                               MATRIX_ROW_BOTTOM_Y (updated_row));
 
   from_x = output_cursor.x;
-     
+
   /* Translate to frame coordinates.  */
   if (updated_row->full_width_p)
     {
@@ -5471,11 +5535,11 @@ x_clear_end_of_line (to_x)
       from_x = WINDOW_AREA_TO_FRAME_PIXEL_X (w, updated_area, from_x);
       to_x = WINDOW_AREA_TO_FRAME_PIXEL_X (w, updated_area, to_x);
     }
-  
+
   min_y = WINDOW_DISPLAY_HEADER_LINE_HEIGHT (w);
   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, max (min_y, output_cursor.y));
   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, to_y);
-  
+
   /* Prevent inadvertently clearing to end of the X window.  */
   if (to_x > from_x && to_y > from_y)
     {
@@ -5545,7 +5609,7 @@ timeval_subtract (result, x, y)
       y.tv_usec -= 1000000 * nsec;
       y.tv_sec += nsec;
     }
-  
+
   if (x.tv_usec - y.tv_usec > 1000000)
     {
       int nsec = (y.tv_usec - x.tv_usec) / 1000000;
@@ -5629,7 +5693,7 @@ XTflash (f)
                          width, flash_height);
        }
       else
-       /* If it is short, flash it all.  */ 
+       /* If it is short, flash it all.  */
        XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
                        flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
                        width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
@@ -5683,7 +5747,7 @@ XTflash (f)
                          width, flash_height);
        }
       else
-       /* If it is short, flash it all.  */ 
+       /* If it is short, flash it all.  */
        XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), gc,
                        flash_left, FRAME_INTERNAL_BORDER_WIDTH (f),
                        width, height - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
@@ -5705,7 +5769,7 @@ void
 XTring_bell ()
 {
   struct frame *f = SELECTED_FRAME ();
-  
+
   if (FRAME_X_DISPLAY (f))
     {
 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
@@ -5793,7 +5857,7 @@ x_scroll_run (w, run)
     }
 
   BLOCK_INPUT;
-  
+
   /* Cursor off.  Will be switched on again in x_update_window_end.  */
   updated_window = w;
   x_clear_cursor (w);
@@ -5804,7 +5868,7 @@ x_scroll_run (w, run)
             x, from_y,
             width, height,
             x, to_y);
-  
+
   UNBLOCK_INPUT;
 }
 
@@ -5813,7 +5877,7 @@ x_scroll_run (w, run)
 /***********************************************************************
                           Exposure Events
  ***********************************************************************/
-                                                                       
+
 /* Redisplay an exposed area of frame F.  X and Y are the upper-left
    corner of the exposed rectangle.  W and H are width and height of
    the exposed area.  All are pixel values.  W or H zero means redraw
@@ -5908,7 +5972,7 @@ expose_window_tree (w, r)
 {
   struct frame *f = XFRAME (w->frame);
   int mouse_face_overwritten_p = 0;
-  
+
   while (w && !FRAME_GARBAGED_P (f))
     {
       if (!NILP (w->hchild))
@@ -5919,7 +5983,7 @@ expose_window_tree (w, r)
          |= expose_window_tree (XWINDOW (w->vchild), r);
       else
        mouse_face_overwritten_p |= expose_window (w, r);
-      
+
       w = NILP (w->next) ? NULL : XWINDOW (w->next);
     }
 
@@ -5967,7 +6031,7 @@ expose_area (w, row, r, area)
          x += first->pixel_width;
          ++first;
        }
-      
+
       /* Find the last one.  */
       last = first;
       first_x = x;
@@ -5977,7 +6041,7 @@ expose_area (w, row, r, area)
          x += last->pixel_width;
          ++last;
        }
-      
+
       /* Repaint.  */
       if (last > first)
        x_draw_glyphs (w, first_x - start_x, row, area,
@@ -5986,7 +6050,7 @@ expose_area (w, row, r, area)
                       DRAW_NORMAL_TEXT, 0);
     }
 }
-      
+
 
 /* Redraw the parts of the glyph row ROW on window W intersecting
    rectangle R.  R is in window-relative coordinates.  Value is
@@ -5999,7 +6063,7 @@ expose_line (w, row, r)
      XRectangle *r;
 {
   xassert (row->enabled_p);
-  
+
   if (row->mode_line_p || w->pseudo_window_p)
     x_draw_glyphs (w, 0, row, TEXT_AREA, 0, row->used[TEXT_AREA],
                   DRAW_NORMAL_TEXT, 0);
@@ -6042,6 +6106,39 @@ x_phys_cursor_in_rect_p (w, r)
 }
 
 
+/* Redraw those parts of glyphs rows during expose event handling that
+   overlap other rows.  Redrawing of an exposed line writes over parts
+   of lines overlapping that exposed line; this function fixes that.
+
+   W is the window being exposed.  FIRST_OVERLAPPING_ROW is the first
+   row in W's current matrix that is exposed and overlaps other rows.
+   LAST_OVERLAPPING_ROW is the last such row.  */
+
+static void
+expose_overlaps (w, first_overlapping_row, last_overlapping_row)
+     struct window *w;
+     struct glyph_row *first_overlapping_row;
+     struct glyph_row *last_overlapping_row;
+{
+  struct glyph_row *row;
+
+  for (row = first_overlapping_row; row <= last_overlapping_row; ++row)
+    if (row->overlapping_p)
+      {
+       xassert (row->enabled_p && !row->mode_line_p);
+
+       if (row->used[LEFT_MARGIN_AREA])
+         x_fix_overlapping_area (w, row, LEFT_MARGIN_AREA);
+
+       if (row->used[TEXT_AREA])
+         x_fix_overlapping_area (w, row, TEXT_AREA);
+
+       if (row->used[RIGHT_MARGIN_AREA])
+         x_fix_overlapping_area (w, row, RIGHT_MARGIN_AREA);
+      }
+}
+
+
 /* Redraw the part of window W intersection rectangle FR.  Pixel
    coordinates in FR are frame-relative.  Call this function with
    input blocked.  Value is non-zero if the exposure overwrites
@@ -6083,7 +6180,8 @@ expose_window (w, fr)
       int yb = window_text_bottom_y (w);
       struct glyph_row *row;
       int cursor_cleared_p;
-  
+      struct glyph_row *first_overlapping_row, *last_overlapping_row;
+
       TRACE ((stderr, "expose_window (%d, %d, %d, %d)\n",
              r.x, r.y, r.width, r.height));
 
@@ -6101,23 +6199,31 @@ expose_window (w, fr)
       else
        cursor_cleared_p = 0;
 
-      /* Find the first row intersecting the rectangle R.  */
+      /* Update lines intersecting rectangle R.  */
+      first_overlapping_row = last_overlapping_row = NULL;
       for (row = w->current_matrix->rows;
           row->enabled_p;
           ++row)
        {
          int y0 = row->y;
          int y1 = MATRIX_ROW_BOTTOM_Y (row);
-         
+
          if ((y0 >= r.y && y0 < r.y + r.height)
              || (y1 > r.y && y1 < r.y + r.height)
              || (r.y >= y0 && r.y < y1)
              || (r.y + r.height > y0 && r.y + r.height < y1))
            {
+             if (row->overlapping_p)
+               {
+                 if (first_overlapping_row == NULL)
+                   first_overlapping_row = row;
+                 last_overlapping_row = row;
+               }
+
              if (expose_line (w, row, &r))
                mouse_face_overwritten_p = 1;
            }
-             
+
          if (y1 >= yb)
            break;
        }
@@ -6134,9 +6240,13 @@ expose_window (w, fr)
 
       if (!w->pseudo_window_p)
        {
+         /* Fix the display of overlapping rows.  */
+         if (first_overlapping_row)
+           expose_overlaps (w, first_overlapping_row, last_overlapping_row);
+
          /* Draw border between windows.  */
          x_draw_vertical_border (w);
-      
+
          /* Turn the cursor on again.  */
          if (cursor_cleared_p)
            x_update_window_cursor (w, 1);
@@ -6158,7 +6268,7 @@ x_intersect_rectangles (r1, r2, result)
   XRectangle *left, *right;
   XRectangle *upper, *lower;
   int intersection_p = 0;
-  
+
   /* Rearrange so that R1 is the left-most rectangle.  */
   if (r1->x < r2->x)
     left = r1, right = r2;
@@ -6170,7 +6280,7 @@ x_intersect_rectangles (r1, r2, result)
   if (right->x <= left->x + left->width)
     {
       result->x = right->x;
-      
+
       /* The right end of the intersection is the minimum of the
         the right ends of left and right.  */
       result->width = (min (left->x + left->width, right->x + right->width)
@@ -6187,10 +6297,10 @@ x_intersect_rectangles (r1, r2, result)
       if (lower->y <= upper->y + upper->height)
        {
          result->y = lower->y;
-         
+
          /* The lower end of the intersection is the minimum of the lower
             ends of upper and lower.  */
-         result->height = (min (lower->y + lower->height, 
+         result->height = (min (lower->y + lower->height,
                                 upper->y + upper->height)
                            - result->y);
          intersection_p = 1;
@@ -6273,6 +6383,121 @@ x_new_focus_frame (dpyinfo, frame)
   x_frame_rehighlight (dpyinfo);
 }
 
+/* Handle FocusIn and FocusOut state changes for FRAME.
+   If FRAME has focus and there exists more than one frame, puts
+   a FOCUS_IN_EVENT into BUFP.
+   Returns number of events inserted into BUFP. */
+
+static int
+x_focus_changed (type, state, dpyinfo, frame, bufp, numchars)
+     int type;
+     int state;
+     struct x_display_info *dpyinfo;
+     struct frame *frame;
+     struct input_event *bufp;
+     int numchars;
+{
+  int nr_events = 0;
+
+  if (type == FocusIn)
+    {
+      if (dpyinfo->x_focus_event_frame != frame)
+        {
+          x_new_focus_frame (dpyinfo, frame);
+          dpyinfo->x_focus_event_frame = frame;
+
+          /* Don't stop displaying the initial startup message
+             for a switch-frame event we don't need.  */
+          if (numchars > 0
+              && GC_NILP (Vterminal_frame)
+              && GC_CONSP (Vframe_list)
+              && !GC_NILP (XCDR (Vframe_list)))
+            {
+              bufp->kind = FOCUS_IN_EVENT;
+              XSETFRAME (bufp->frame_or_window, frame);
+              bufp->arg = Qnil;
+              ++bufp;
+              numchars--;
+              ++nr_events;
+            }
+        }
+
+      frame->output_data.x->focus_state |= state;
+
+#ifdef HAVE_X_I18N
+      if (FRAME_XIC (frame))
+        XSetICFocus (FRAME_XIC (frame));
+#endif
+    }
+  else if (type == FocusOut)
+    {
+      frame->output_data.x->focus_state &= ~state;
+
+      if (dpyinfo->x_focus_event_frame == frame)
+        {
+          dpyinfo->x_focus_event_frame = 0;
+          x_new_focus_frame (dpyinfo, 0);
+        }
+
+#ifdef HAVE_X_I18N
+      if (FRAME_XIC (frame))
+        XUnsetICFocus (FRAME_XIC (frame));
+#endif
+    }
+
+  return nr_events;
+}
+
+/* The focus may have changed.  Figure out if it is a real focus change,
+   by checking both FocusIn/Out and Enter/LeaveNotify events.
+
+   Returns number of events inserted into BUFP. */
+
+static int
+x_detect_focus_change (dpyinfo, event, bufp, numchars)
+     struct x_display_info *dpyinfo;
+     XEvent *event;
+     struct input_event *bufp;
+     int numchars;
+{
+  struct frame *frame;
+  int nr_events = 0;
+
+  frame = x_any_window_to_frame (dpyinfo, event->xany.window);
+  if (! frame) return nr_events;
+
+  switch (event->type)
+    {
+    case EnterNotify:
+    case LeaveNotify:
+      if (event->xcrossing.detail != NotifyInferior
+          && event->xcrossing.focus
+          && ! (frame->output_data.x->focus_state & FOCUS_EXPLICIT))
+        nr_events = x_focus_changed ((event->type == EnterNotify
+                                      ? FocusIn : FocusOut),
+                                     FOCUS_IMPLICIT,
+                                     dpyinfo,
+                                     frame,
+                                     bufp,
+                                     numchars);
+      break;
+
+    case FocusIn:
+    case FocusOut:
+      nr_events = x_focus_changed (event->type,
+                                   (event->xfocus.detail == NotifyPointer
+                                    ? FOCUS_IMPLICIT : FOCUS_EXPLICIT),
+                                   dpyinfo,
+                                   frame,
+                                   bufp,
+                                   numchars);
+      break;
+    }
+
+  return nr_events;
+}
+
+
 /* Handle an event saying the mouse has moved out of an Emacs frame.  */
 
 void
@@ -6446,7 +6671,7 @@ x_x_to_emacs_modifiers (dpyinfo, state)
   EMACS_UINT mod_hyper = hyper_modifier;
   EMACS_UINT mod_super = super_modifier;
   Lisp_Object tem;
-  
+
   tem = Fget (Vx_alt_keysym, Qmodifier_value);
   if (! EQ (tem, Qnil)) mod_alt = XUINT (tem);
   tem = Fget (Vx_meta_keysym, Qmodifier_value);
@@ -6455,7 +6680,7 @@ x_x_to_emacs_modifiers (dpyinfo, state)
   if (! EQ (tem, Qnil)) mod_hyper = XUINT (tem);
   tem = Fget (Vx_super_keysym, Qmodifier_value);
   if (! EQ (tem, Qnil)) mod_super = XUINT (tem);
-  
+
 
   return (  ((state & (ShiftMask | dpyinfo->shift_lock_mask)) ? shift_modifier : 0)
             | ((state & ControlMask)                   ? ctrl_modifier : 0)
@@ -6474,9 +6699,9 @@ x_emacs_to_x_modifiers (dpyinfo, state)
   EMACS_UINT mod_alt  = alt_modifier;
   EMACS_UINT mod_hyper = hyper_modifier;
   EMACS_UINT mod_super = super_modifier;
-  
+
   Lisp_Object tem;
-  
+
   tem = Fget (Vx_alt_keysym, Qmodifier_value);
   if (! EQ (tem, Qnil)) mod_alt = XUINT (tem);
   tem = Fget (Vx_meta_keysym, Qmodifier_value);
@@ -6485,8 +6710,8 @@ x_emacs_to_x_modifiers (dpyinfo, state)
   if (! EQ (tem, Qnil)) mod_hyper = XUINT (tem);
   tem = Fget (Vx_super_keysym, Qmodifier_value);
   if (! EQ (tem, Qnil)) mod_super = XUINT (tem);
-  
-  
+
+
   return (  ((state & mod_alt)         ? dpyinfo->alt_mod_mask   : 0)
             | ((state & mod_super)     ? dpyinfo->super_mod_mask : 0)
             | ((state & mod_hyper)     ? dpyinfo->hyper_mod_mask : 0)
@@ -6618,9 +6843,9 @@ construct_mouse_click (result, event, f)
      XButtonEvent *event;
      struct frame *f;
 {
-  /* Make the event type no_event; we'll change that when we decide
+  /* Make the event type NO_EVENT; we'll change that when we decide
      otherwise.  */
-  result->kind = mouse_click;
+  result->kind = MOUSE_CLICK_EVENT;
   result->code = event->button - Button1;
   result->timestamp = event->time;
   result->modifiers = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
@@ -6755,7 +6980,7 @@ x_y_to_hpos_vpos (w, x, y, hpos, vpos, area, buffer_only_p)
          else if (!buffer_only_p || BUFFERP (glyph->object))
            break;
        }
-      
+
       x0 += glyph->pixel_width;
       ++glyph;
     }
@@ -6799,7 +7024,7 @@ frame_to_window_pixel_xy (w, x, y)
    display area of W, so the width of bitmap areas and scroll bars
    must be subtracted to get a position relative to the start of the
    mode line.  */
+
 static void
 note_mode_line_or_margin_highlight (w, x, y, portion)
      struct window *w;
@@ -6808,8 +7033,7 @@ note_mode_line_or_margin_highlight (w, x, y, portion)
   struct frame *f = XFRAME (w->frame);
   struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
   Cursor cursor = dpyinfo->vertical_scroll_bar_cursor;
-  struct glyph_row *row;
-  int i, area, charpos;
+  int charpos;
   Lisp_Object string, help, map, pos;
 
   if (portion == 1 || portion == 3)
@@ -6820,7 +7044,7 @@ note_mode_line_or_margin_highlight (w, x, y, portion)
   if (STRINGP (string))
     {
       pos = make_number (charpos);
-      
+
       /* If we're on a string with `help-echo' text property, arrange
         for the help to be displayed.  This is done by setting the
         global variable help_echo to the help string.  */
@@ -6840,7 +7064,7 @@ note_mode_line_or_margin_highlight (w, x, y, portion)
       if (KEYMAPP (map))
        cursor = f->output_data.x->nontext_cursor;
     }
-  
+
   XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
 }
 
@@ -6863,7 +7087,7 @@ note_mouse_highlight (f, x, y)
   struct buffer *b;
 
   /* When a menu is active, don't highlight because this looks odd.  */
-#ifdef USE_X_TOOLKIT
+#if defined (USE_X_TOOLKIT) || defined (USE_GTK)
   if (popup_activated ())
     return;
 #endif
@@ -6914,7 +7138,7 @@ note_mouse_highlight (f, x, y)
       note_mode_line_or_margin_highlight (w, x, y, portion);
       return;
     }
-  
+
   if (portion == 2)
     cursor = f->output_data.x->horizontal_drag_cursor;
   else
@@ -7023,13 +7247,13 @@ note_mouse_highlight (f, x, y)
              if (!NILP (mouse_face))
                overlay = overlay_vec[i];
            }
-         
+
          /* If we're actually highlighting the same overlay as
             before, there's no need to do that again.  */
          if (!NILP (overlay)
              && EQ (overlay, dpyinfo->mouse_face_overlay))
            goto check_help_echo;
-           
+
          dpyinfo->mouse_face_overlay = overlay;
 
          /* Clear the display of the old active region, if any.  */
@@ -7056,7 +7280,7 @@ note_mouse_highlight (f, x, y)
                                  &dpyinfo->mouse_face_beg_row,
                                  &dpyinfo->mouse_face_beg_x,
                                  &dpyinfo->mouse_face_beg_y, Qnil);
-                      
+
              dpyinfo->mouse_face_past_end
                = !fast_find_position (w, XFASTINT (after),
                                       &dpyinfo->mouse_face_end_col,
@@ -7066,7 +7290,8 @@ note_mouse_highlight (f, x, y)
              dpyinfo->mouse_face_window = window;
              dpyinfo->mouse_face_face_id
                = face_at_buffer_position (w, pos, 0, 0,
-                                          &ignore, pos + 1, 1);
+                                          &ignore, pos + 1,
+                                          !dpyinfo->mouse_face_hidden);
 
              /* Display it as active.  */
              show_mouse_face (dpyinfo, DRAW_MOUSE_FACE);
@@ -7090,7 +7315,7 @@ note_mouse_highlight (f, x, y)
              after
                = Fnext_single_property_change (position, Qmouse_face,
                                                object, end);
-               
+
              /* Record this as the current active region.  */
              fast_find_position (w, XFASTINT (before),
                                  &dpyinfo->mouse_face_beg_col,
@@ -7108,7 +7333,8 @@ note_mouse_highlight (f, x, y)
              if (BUFFERP (object))
                dpyinfo->mouse_face_face_id
                  = face_at_buffer_position (w, pos, 0, 0,
-                                            &ignore, pos + 1, 1);
+                                            &ignore, pos + 1,
+                                            !dpyinfo->mouse_face_hidden);
 
              /* Display it as active.  */
              show_mouse_face (dpyinfo, DRAW_MOUSE_FACE);
@@ -7118,7 +7344,7 @@ note_mouse_highlight (f, x, y)
            {
              Lisp_Object b, e;
              int ignore;
-               
+
              b = Fprevious_single_property_change (make_number (pos + 1),
                                                    Qmouse_face,
                                                    object, Qnil);
@@ -7127,7 +7353,7 @@ note_mouse_highlight (f, x, y)
              if (NILP (b))
                b = make_number (0);
              if (NILP (e))
-               e = make_number (XSTRING (object)->size - 1);
+               e = make_number (SCHARS (object) - 1);
              fast_find_string_pos (w, XINT (b), object,
                                    &dpyinfo->mouse_face_beg_col,
                                    &dpyinfo->mouse_face_beg_row,
@@ -7152,7 +7378,7 @@ note_mouse_highlight (f, x, y)
                 the text ``under'' it might have.  */
              struct glyph_row *r = MATRIX_ROW (w->current_matrix, vpos);
              int start = MATRIX_ROW_START_CHARPOS (r);
-             
+
              pos = string_buffer_position (w, object, start);
              if (pos > 0)
                mouse_face = get_char_property_and_overlay (make_number (pos),
@@ -7176,7 +7402,7 @@ note_mouse_highlight (f, x, y)
                                      &dpyinfo->mouse_face_beg_x,
                                      &dpyinfo->mouse_face_beg_y,
                                      object);
-                      
+
                  dpyinfo->mouse_face_past_end
                    = !fast_find_position (w, XFASTINT (after),
                                           &dpyinfo->mouse_face_end_col,
@@ -7187,7 +7413,8 @@ note_mouse_highlight (f, x, y)
                  dpyinfo->mouse_face_window = window;
                  dpyinfo->mouse_face_face_id
                    = face_at_buffer_position (w, pos, 0, 0,
-                                              &ignore, pos + 1, 1);
+                                              &ignore, pos + 1,
+                                              !dpyinfo->mouse_face_hidden);
 
                  /* Display it as active.  */
                  show_mouse_face (dpyinfo, DRAW_MOUSE_FACE);
@@ -7221,11 +7448,11 @@ note_mouse_highlight (f, x, y)
          {
            Lisp_Object object = glyph->object;
            int charpos = glyph->charpos;
-             
+
            /* Try text properties.  */
            if (STRINGP (object)
                && charpos >= 0
-               && charpos < XSTRING (object)->size)
+               && charpos < SCHARS (object))
              {
                help = Fget_text_property (make_number (charpos),
                                           Qhelp_echo, object);
@@ -7254,7 +7481,7 @@ note_mouse_highlight (f, x, y)
                     && charpos < ZV)
              help = Fget_text_property (make_number (charpos), Qhelp_echo,
                                         object);
-           
+
            if (!NILP (help))
              {
                help_echo = help;
@@ -7264,14 +7491,14 @@ note_mouse_highlight (f, x, y)
              }
          }
       }
-         
+
       BEGV = obegv;
       ZV = ozv;
       current_buffer = obuf;
     }
 
  set_cursor:
-  
+
   if (cursor != None)
     XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
 }
@@ -7342,7 +7569,7 @@ x_tool_bar_item (f, x, y, glyph, hpos, vpos, prop_idx)
          || *hpos < dpyinfo->mouse_face_end_col
          || dpyinfo->mouse_face_past_end))
     return 0;
-  
+
   return 1;
 }
 
@@ -7363,7 +7590,7 @@ x_handle_tool_bar_click (f, button_event)
   Lisp_Object enabled_p;
   int x = button_event->x;
   int y = button_event->y;
-  
+
   /* If not on the highlighted tool-bar item, return.  */
   frame_to_window_pixel_xy (w, &x, &y);
   if (x_tool_bar_item (f, x, y, &glyph, &hpos, &vpos, &prop_idx) != 0)
@@ -7373,7 +7600,7 @@ x_handle_tool_bar_click (f, button_event)
   enabled_p = AREF (f->tool_bar_items, prop_idx + TOOL_BAR_ITEM_ENABLED_P);
   if (NILP (enabled_p))
     return;
-  
+
   if (button_event->type == ButtonPress)
     {
       /* Show item in pressed state.  */
@@ -7449,7 +7676,7 @@ note_tool_bar_highlight (f, x, y)
     goto set_help_echo;
 
   clear_mouse_face (dpyinfo);
-  
+
   /* Mouse is down, but on different tool-bar item?  */
   mouse_down_p = (dpyinfo->grabbed
                  && f == last_mouse_frame
@@ -7460,7 +7687,7 @@ note_tool_bar_highlight (f, x, y)
 
   dpyinfo->mouse_face_image_state = DRAW_NORMAL_TEXT;
   draw = mouse_down_p ? DRAW_IMAGE_SUNKEN : DRAW_IMAGE_RAISED;
-  
+
   /* If tool-bar item is not enabled, don't highlight it.  */
   enabled_p = AREF (f->tool_bar_items, prop_idx + TOOL_BAR_ITEM_ENABLED_P);
   if (!NILP (enabled_p))
@@ -7470,28 +7697,28 @@ note_tool_bar_highlight (f, x, y)
       row = MATRIX_ROW (w->current_matrix, vpos);
       for (i = x = 0; i < hpos; ++i)
        x += row->glyphs[TEXT_AREA][i].pixel_width;
-      
+
       /* Record this as the current active region.  */
       dpyinfo->mouse_face_beg_col = hpos;
       dpyinfo->mouse_face_beg_row = vpos;
       dpyinfo->mouse_face_beg_x = x;
       dpyinfo->mouse_face_beg_y = row->y;
       dpyinfo->mouse_face_past_end = 0;
-      
+
       dpyinfo->mouse_face_end_col = hpos + 1;
       dpyinfo->mouse_face_end_row = vpos;
       dpyinfo->mouse_face_end_x = x + glyph->pixel_width;
       dpyinfo->mouse_face_end_y = row->y;
       dpyinfo->mouse_face_window = window;
       dpyinfo->mouse_face_face_id = TOOL_BAR_FACE_ID;
-      
+
       /* Display it as active.  */
       show_mouse_face (dpyinfo, draw);
       dpyinfo->mouse_face_image_state = draw;
     }
-      
+
  set_help_echo:
-  
+
   /* Set help_echo to a help string to display for this tool-bar item.
      XTread_socket does the rest.  */
   help_echo_object = help_echo_window = Qnil;
@@ -7513,7 +7740,7 @@ note_tool_bar_highlight (f, x, y)
 #if 0 /* This is a version of fast_find_position that's more correct
         in the presence of hscrolling, for example.  I didn't install
         it right away because the problem fixed is minor, it failed
-        in 20.x as well, and I think it's too risky to install 
+        in 20.x as well, and I think it's too risky to install
         so near the release of 21.1.  2001-09-25 gerd.  */
 
 static int
@@ -7546,10 +7773,10 @@ fast_find_position (w, charpos, hpos, vpos, x, y, stop)
   *x = row->x;
   *y = row->y;
   *vpos = MATRIX_ROW_VPOS (row, w->current_matrix);
-  
+
   glyph = row->glyphs[TEXT_AREA];
   end = glyph + row->used[TEXT_AREA];
-  
+
   /* Skip over glyphs not having an object at the start of the row.
      These are special glyphs like truncation marks on terminal
      frames.  */
@@ -7623,11 +7850,11 @@ fast_find_position (w, pos, hpos, vpos, x, y, stop)
 
       if (row->y + row->height >= yb)
        break;
-      
+
       ++row;
       ++row_vpos;
     }
-  
+
   /* Find the right column within BEST_ROW.  */
   lastcol = 0;
   current_x = best_row->x;
@@ -7751,7 +7978,7 @@ fast_find_string_pos (w, pos, object, hpos, vpos, x, y, right_p)
          *x += best_glyph->pixel_width;
          ++*hpos;
        }
-      
+
       *y = best_row->y;
       *vpos = best_row - w->current_matrix->rows;
     }
@@ -7785,7 +8012,7 @@ show_mouse_face (dpyinfo, draw)
 
       first = MATRIX_ROW (w->current_matrix, dpyinfo->mouse_face_beg_row);
       last = MATRIX_ROW (w->current_matrix, dpyinfo->mouse_face_end_row);
-      
+
       for (row = first; row <= last && row->enabled_p; ++row)
        {
          int start_hpos, end_hpos, start_x;
@@ -7809,7 +8036,7 @@ show_mouse_face (dpyinfo, draw)
 
          if (end_hpos > start_hpos)
            {
-             x_draw_glyphs (w, start_x, row, TEXT_AREA, 
+             x_draw_glyphs (w, start_x, row, TEXT_AREA,
                             start_hpos, end_hpos, draw, 0);
 
              row->mouse_face_p
@@ -7846,7 +8073,7 @@ clear_mouse_face (dpyinfo)
      struct x_display_info *dpyinfo;
 {
   int cleared = 0;
-  
+
   if (!NILP (dpyinfo->mouse_face_window))
     {
       show_mouse_face (dpyinfo, DRAW_NORMAL_TEXT);
@@ -7925,14 +8152,14 @@ glyph_rect (f, x, y, rect)
       struct glyph_row *end = r + w->current_matrix->nrows - 1;
 
       frame_to_window_pixel_xy (w, &x, &y);
-      
+
       for (; !found && r < end && r->enabled_p; ++r)
        if (r->y >= y)
          {
            struct glyph *g = r->glyphs[TEXT_AREA];
            struct glyph *end = g + r->used[TEXT_AREA];
            int gx;
-             
+
            for (gx = r->x; !found && g < end; gx += g->pixel_width, ++g)
              if (gx >= x)
                {
@@ -8135,7 +8362,7 @@ XTmouse_position (fp, insist, bar_window, part, x, y, time)
 
            int width, height, gx, gy;
            XRectangle rect;
-           
+
            if (glyph_rect (f1, win_x, win_y, &rect))
              last_mouse_glyph = rect;
            else
@@ -8144,7 +8371,7 @@ XTmouse_position (fp, insist, bar_window, part, x, y, time)
                height = FRAME_SMALLEST_FONT_HEIGHT (f1);
                gx = win_x;
                gy = win_y;
-             
+
                /* Arrange for the division in PIXEL_TO_CHAR_COL etc. to
                   round down even for negative values.  */
                if (gx < 0)
@@ -8153,7 +8380,7 @@ XTmouse_position (fp, insist, bar_window, part, x, y, time)
                  gy -= height - 1;
                gx = (gx + width - 1) / width * width;
                gy = (gy + height - 1) / height * height;
-           
+
                last_mouse_glyph.width  = width;
                last_mouse_glyph.height = height;
                last_mouse_glyph.x = gx;
@@ -8185,7 +8412,7 @@ static void
 x_process_timeouts (timer)
      struct atimer *timer;
 {
-  if (toolkit_scroll_bar_interaction || popup_activated_flag)
+  if (toolkit_scroll_bar_interaction || popup_activated ())
     {
       BLOCK_INPUT;
       while (XtAppPending (Xt_app_con) & XtIMTimer)
@@ -8209,6 +8436,10 @@ x_window_to_scroll_bar (window_id)
 {
   Lisp_Object tail;
 
+#ifdef USE_GTK
+  window_id = (Window) xg_get_scroll_id_for_window (window_id);
+#endif /* USE_GTK */
+
   for (tail = Vframe_list;
        XGCTYPE (tail) == Lisp_Cons;
        tail = XCDR (tail))
@@ -8248,14 +8479,14 @@ x_window_to_menu_bar (window)
      Window window;
 {
   Lisp_Object tail;
-  
+
   for (tail = Vframe_list;
        XGCTYPE (tail) == Lisp_Cons;
        tail = XCDR (tail))
     {
       Lisp_Object frame = XCAR (tail);
       Widget menu_bar = XFRAME (frame)->output_data.x->menubar_widget;
-      
+
       if (menu_bar && xlwmenu_window_p (menu_bar, window))
        return menu_bar;
     }
@@ -8280,10 +8511,6 @@ static void x_set_toolkit_scroll_bar_thumb P_ ((struct scroll_bar *,
                                                int, int, int));
 
 
-/* Id of action hook installed for scroll bars.  */
-
-static XtActionHookId action_hook_id;
-
 /* Lisp window being scrolled.  Set when starting to interact with
    a toolkit scroll bar, reset to nil when ending the interaction.  */
 
@@ -8296,6 +8523,11 @@ static int last_scroll_bar_part;
 /* Whether this is an Xaw with arrow-scrollbars.  This should imply
    that movements of 1/20 of the screen size are mapped to up/down.  */
 
+#ifndef USE_GTK
+/* Id of action hook installed for scroll bars.  */
+
+static XtActionHookId action_hook_id;
+
 static Boolean xaw3d_arrow_scroll;
 
 /* Whether the drag scrolling maintains the mouse at the top of the
@@ -8308,7 +8540,7 @@ static Boolean xaw3d_pick_top;
 /* Action hook installed via XtAppAddActionHook when toolkit scroll
    bars are used..  The hook is responsible for detecting when
    the user ends an interaction with the scroll bar, and generates
-   a `end-scroll' scroll_bar_click' event if so.  */
+   a `end-scroll' SCROLL_BAR_CLICK_EVENT' event if so.  */
 
 static void
 xt_action_hook (widget, client_data, action_name, event, params,
@@ -8322,7 +8554,7 @@ xt_action_hook (widget, client_data, action_name, event, params,
 {
   int scroll_bar_p;
   char *end_action;
-  
+
 #ifdef USE_MOTIF
   scroll_bar_p = XmIsScrollBar (widget);
   end_action = "Release";
@@ -8336,7 +8568,7 @@ xt_action_hook (widget, client_data, action_name, event, params,
       && WINDOWP (window_being_scrolled))
     {
       struct window *w;
-      
+
       x_send_scroll_bar_event (window_being_scrolled,
                               scroll_bar_end_scroll, 0, 0);
       w = XWINDOW (window_being_scrolled);
@@ -8348,6 +8580,7 @@ xt_action_hook (widget, client_data, action_name, event, params,
       toolkit_scroll_bar_interaction = 0;
     }
 }
+#endif /* not USE_GTK */
 
 /* A vector of windows used for communication between
    x_send_scroll_bar_event and x_scroll_bar_to_input_event.  */
@@ -8373,7 +8606,7 @@ x_send_scroll_bar_event (window, part, portion, whole)
   int i;
 
   BLOCK_INPUT;
-  
+
   /* Construct a ClientMessage event to send to the frame.  */
   ev->type = ClientMessage;
   ev->message_type = FRAME_X_DISPLAY_INFO (f)->Xatom_Scrollbar;
@@ -8394,7 +8627,7 @@ x_send_scroll_bar_event (window, part, portion, whole)
       int new_size = max (10, 2 * scroll_bar_windows_size);
       size_t nbytes = new_size * sizeof *scroll_bar_windows;
       size_t old_nbytes = scroll_bar_windows_size * sizeof *scroll_bar_windows;
-      
+
       scroll_bar_windows = (struct window **) xrealloc (scroll_bar_windows,
                                                        nbytes);
       bzero (&scroll_bar_windows[i], nbytes - old_nbytes);
@@ -8431,17 +8664,21 @@ x_scroll_bar_to_input_event (event, ievent)
   Lisp_Object window;
   struct frame *f;
   struct window *w;
-  
+
   w = scroll_bar_windows[ev->data.l[0]];
   scroll_bar_windows[ev->data.l[0]] = NULL;
 
   XSETWINDOW (window, w);
   f = XFRAME (w->frame);
-  
-  ievent->kind = scroll_bar_click;
+
+  ievent->kind = SCROLL_BAR_CLICK_EVENT;
   ievent->frame_or_window = window;
   ievent->arg = Qnil;
+#ifdef USE_GTK
+  ievent->timestamp = CurrentTime;
+#else
   ievent->timestamp = XtLastTimestampProcessed (FRAME_X_DISPLAY (f));
+#endif
   ievent->part = ev->data.l[1];
   ievent->code = ev->data.l[2];
   ievent->x = make_number ((int) ev->data.l[3]);
@@ -8461,7 +8698,7 @@ x_scroll_bar_to_input_event (event, ievent)
 
 /* Scroll bar callback for Motif scroll bars.  WIDGET is the scroll
    bar widget.  CLIENT_DATA is a pointer to the scroll_bar structure.
-   CALL_DATA is a pointer a a XmScrollBarCallbackStruct.  */
+   CALL_DATA is a pointer to a XmScrollBarCallbackStruct.  */
 
 static void
 xm_scroll_callback (widget, client_data, call_data)
@@ -8498,7 +8735,7 @@ xm_scroll_callback (widget, client_data, call_data)
       bar->dragging = Qnil;
       part = scroll_bar_to_top;
       break;
-      
+
     case XmCR_TO_BOTTOM:
       bar->dragging = Qnil;
       part = scroll_bar_to_bottom;
@@ -8521,7 +8758,7 @@ xm_scroll_callback (widget, client_data, call_data)
        bar->dragging = make_number (cs->value);
       }
       break;
-      
+
     case XmCR_VALUE_CHANGED:
       break;
     };
@@ -8535,8 +8772,80 @@ xm_scroll_callback (widget, client_data, call_data)
 }
 
 
-#else /* !USE_MOTIF, i.e. Xaw.  */
+#else /* !USE_MOTIF, i.e. Xaw or GTK */
+#ifdef USE_GTK
+/* Scroll bar callback for Gtk scroll bars.  WIDGET is the scroll
+   bar adjustment widget.  DATA is a pointer to the scroll_bar structure. */
+
+static void
+xg_scroll_callback (widget, data)
+     GtkWidget *widget;
+     gpointer data;
+{
+  struct scroll_bar *bar = (struct scroll_bar *) data;
+  gdouble previous;
+  gdouble position;
+  gdouble *p;
+  int diff;
+
+  int part = -1, whole = 0, portion = 0;
+  GtkAdjustment *adj = GTK_ADJUSTMENT (widget);
+
+  if (xg_ignore_gtk_scrollbar) return;
+
+  position = gtk_adjustment_get_value (adj);
+
+  p = g_object_get_data (G_OBJECT (widget), XG_LAST_SB_DATA);
+  if (! p)
+    {
+      p = (gdouble*) xmalloc (sizeof (gdouble));
+      *p = XG_SB_MIN;
+      g_object_set_data (G_OBJECT (widget), XG_LAST_SB_DATA, p);
+    }
+
+  previous = *p;
+  *p = position;
+
+  diff = (int) (position - previous);
+
+  if (diff == (int) adj->step_increment)
+    {
+      part = scroll_bar_down_arrow;
+      bar->dragging = Qnil;
+    }
+  else if (-diff == (int) adj->step_increment)
+    {
+      part = scroll_bar_up_arrow;
+      bar->dragging = Qnil;
+    }
+  else if (diff == (int) adj->page_increment)
+    {
+      part = scroll_bar_below_handle;
+      bar->dragging = Qnil;
+    }
+  else if (-diff == (int) adj->page_increment)
+    {
+      part = scroll_bar_above_handle;
+      bar->dragging = Qnil;
+    }
+  else
+    {
+      part = scroll_bar_handle;
+      whole = adj->upper - adj->page_size;
+      portion = min (position, whole);
+      bar->dragging = make_number (portion);
+    }
+
+  if (part >= 0)
+    {
+      xg_ignore_next_thumb = 1;
+      window_being_scrolled = bar->window;
+      last_scroll_bar_part = part;
+      x_send_scroll_bar_event (bar->window, part, portion, whole);
+    }
+}
 
+#else /* not USE_GTK */
 
 /* Xaw scroll bar callback.  Invoked when the thumb is dragged.
    WIDGET is the scroll bar widget.  CLIENT_DATA is a pointer to the
@@ -8583,7 +8892,7 @@ xaw_jump_callback (widget, client_data, call_data)
    i.e. line or page up or down.  WIDGET is the Xaw scroll bar
    widget.  CLIENT_DATA is a pointer to the scroll_bar structure for
    the scroll bar.  CALL_DATA is an integer specifying the action that
-   has taken place.  It's magnitude is in the range 0..height of the
+   has taken place.  Its magnitude is in the range 0..height of the
    scroll bar.  Negative values mean scroll towards buffer start.
    Values < height of scroll bar mean line-wise movement.  */
 
@@ -8593,7 +8902,8 @@ xaw_scroll_callback (widget, client_data, call_data)
      XtPointer client_data, call_data;
 {
   struct scroll_bar *bar = (struct scroll_bar *) client_data;
-  int position = (int) call_data;
+  /* The position really is stored cast to a pointer.  */
+  int position = (long) call_data;
   Dimension height;
   int part;
 
@@ -8618,13 +8928,30 @@ xaw_scroll_callback (widget, client_data, call_data)
   x_send_scroll_bar_event (bar->window, part, position, height);
 }
 
-
+#endif /* not USE_GTK */
 #endif /* not USE_MOTIF */
 
+#define SCROLL_BAR_NAME "verticalScrollBar"
 
 /* Create the widget for scroll bar BAR on frame F.  Record the widget
    and X window of the scroll bar in BAR.  */
 
+#ifdef USE_GTK
+static void
+x_create_toolkit_scroll_bar (f, bar)
+     struct frame *f;
+     struct scroll_bar *bar;
+{
+  char *scroll_bar_name = SCROLL_BAR_NAME;
+
+  BLOCK_INPUT;
+  xg_create_scroll_bar (f, bar, G_CALLBACK (xg_scroll_callback),
+                        scroll_bar_name);
+  UNBLOCK_INPUT;
+}
+
+#else /* not USE_GTK */
+
 static void
 x_create_toolkit_scroll_bar (f, bar)
      struct frame *f;
@@ -8634,7 +8961,7 @@ x_create_toolkit_scroll_bar (f, bar)
   Widget widget;
   Arg av[20];
   int ac = 0;
-  char *scroll_bar_name = "verticalScrollBar";
+  char *scroll_bar_name = SCROLL_BAR_NAME;
   unsigned long pixel;
 
   BLOCK_INPUT;
@@ -8655,14 +8982,14 @@ x_create_toolkit_scroll_bar (f, bar)
       XtSetArg (av[ac], XmNforeground, pixel);
       ++ac;
     }
-  
+
   pixel = f->output_data.x->scroll_bar_background_pixel;
   if (pixel != -1)
     {
       XtSetArg (av[ac], XmNbackground, pixel);
       ++ac;
     }
-  
+
   widget = XmCreateScrollBar (f->output_data.x->edit_widget,
                              scroll_bar_name, av, ac);
 
@@ -8681,7 +9008,7 @@ x_create_toolkit_scroll_bar (f, bar)
                 (XtPointer) bar);
   XtAddCallback (widget, XmNtoTopCallback, xm_scroll_callback,
                 (XtPointer) bar);
-  
+
   /* Realize the widget.  Only after that is the X window created.  */
   XtRealizeWidget (widget);
 
@@ -8689,9 +9016,9 @@ x_create_toolkit_scroll_bar (f, bar)
      And I'm wondering why it hasn't an arrow cursor by default.  */
   XDefineCursor (XtDisplay (widget), XtWindow (widget),
                 f->output_data.x->nontext_cursor);
-  
+
 #else /* !USE_MOTIF i.e. use Xaw */
-  
+
   /* Set resources.  Create the widget.  The background of the
      Xaw3d scroll bar widget is a little bit light for my taste.
      We don't alter it here to let users change it according
@@ -8700,14 +9027,14 @@ x_create_toolkit_scroll_bar (f, bar)
   XtSetArg (av[ac], XtNorientation, XtorientVertical); ++ac;
   /* For smoother scrolling with Xaw3d   -sm */
   /* XtSetArg (av[ac], XtNpickTop, True); ++ac; */
-  
+
   pixel = f->output_data.x->scroll_bar_foreground_pixel;
   if (pixel != -1)
     {
       XtSetArg (av[ac], XtNforeground, pixel);
       ++ac;
     }
-  
+
   pixel = f->output_data.x->scroll_bar_background_pixel;
   if (pixel != -1)
     {
@@ -8784,22 +9111,22 @@ x_create_toolkit_scroll_bar (f, bar)
        XtVaSetValues (widget, XtNcursorName, "top_left_arrow", NULL);
       }
   }
-  
+
   /* Define callbacks.  */
   XtAddCallback (widget, XtNjumpProc, xaw_jump_callback, (XtPointer) bar);
   XtAddCallback (widget, XtNscrollProc, xaw_scroll_callback,
                 (XtPointer) bar);
-  
+
   /* Realize the widget.  Only after that is the X window created.  */
   XtRealizeWidget (widget);
-  
+
 #endif /* !USE_MOTIF */
 
-  /* Install an action hook that let's us detect when the user
+  /* Install an action hook that lets us detect when the user
      finishes interacting with a scroll bar.  */
   if (action_hook_id == 0)
     action_hook_id = XtAppAddActionHook (Xt_app_con, xt_action_hook, 0);
-  
+
   /* Remember X window and widget in the scroll bar vector.  */
   SET_SCROLL_BAR_X_WIDGET (bar, widget);
   xwindow = XtWindow (widget);
@@ -8807,11 +9134,22 @@ x_create_toolkit_scroll_bar (f, bar)
 
   UNBLOCK_INPUT;
 }
+#endif /* not USE_GTK */
 
 
 /* Set the thumb size and position of scroll bar BAR.  We are currently
    displaying PORTION out of a whole WHOLE, and our position POSITION.  */
 
+#ifdef USE_GTK
+static void
+x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
+     struct scroll_bar *bar;
+     int portion, position, whole;
+{
+  xg_set_toolkit_scroll_bar_thumb (bar, portion, position, whole);
+}
+
+#else /* not USE_GTK */
 static void
 x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
      struct scroll_bar *bar;
@@ -8864,7 +9202,7 @@ x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
       value = top * XM_SB_RANGE;
       value = min (value, XM_SB_MAX - size);
       value = max (value, XM_SB_MIN);
-      
+
       XmScrollBarSetValues (widget, value, size, 0, 0, False);
     }
 #else /* !USE_MOTIF i.e. use Xaw */
@@ -8906,7 +9244,7 @@ x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
 #ifdef HAVE_XAW3D
            ScrollbarWidget sb = (ScrollbarWidget) widget;
            int scroll_mode = 0;
-           
+
            /* `scroll_mode' only exists with Xaw3d + ARROW_SCROLLBAR.  */
            if (xaw3d_arrow_scroll)
              {
@@ -8920,9 +9258,9 @@ x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
            /* Try to make the scrolling a tad smoother.  */
            if (!xaw3d_pick_top)
              shown = min (shown, old_shown);
-           
+
            XawScrollbarSetThumb (widget, top, shown);
-           
+
 #ifdef HAVE_XAW3D
            if (xaw3d_arrow_scroll && scroll_mode == 2)
              sb->scrollbar.scroll_mode = scroll_mode;
@@ -8934,6 +9272,7 @@ x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
 
   UNBLOCK_INPUT;
 }
+#endif /* not USE_GTK */
 
 #endif /* USE_TOOLKIT_SCROLL_BARS */
 
@@ -8942,7 +9281,7 @@ x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
 /************************************************************************
                         Scroll bars, general
  ************************************************************************/
-                                                                        
+
 /* Create a scroll bar and return the scroll bar vector for it.  W is
    the Emacs window on which to create the scroll bar. TOP, LEFT,
    WIDTH and HEIGHT are the pixel coordinates and dimensions of the
@@ -8970,7 +9309,7 @@ x_scroll_bar_create (w, top, left, width, height)
     a.background_pixel = f->output_data.x->scroll_bar_background_pixel;
     if (a.background_pixel == -1)
       a.background_pixel = f->output_data.x->background_pixel;
-    
+
     a.event_mask = (ButtonPressMask | ButtonReleaseMask
                    | ButtonMotionMask | PointerMotionHintMask
                    | ExposureMask);
@@ -9022,6 +9361,15 @@ x_scroll_bar_create (w, top, left, width, height)
   /* Map the window/widget.  */
 #ifdef USE_TOOLKIT_SCROLL_BARS
   {
+#ifdef USE_GTK
+    xg_update_scrollbar_pos (f,
+                             SCROLL_BAR_X_WINDOW (bar),
+                             top,
+                             left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
+                             width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
+                             max (height, 1));
+    xg_show_scroll_bar (SCROLL_BAR_X_WINDOW (bar));
+#else /* not USE_GTK */
     Widget scroll_bar = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
     XtConfigureWidget (scroll_bar,
                       left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
@@ -9029,6 +9377,7 @@ x_scroll_bar_create (w, top, left, width, height)
                       width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
                       max (height, 1), 0);
     XtMapWidget (scroll_bar);
+#endif /* not USE_GTK */
     }
 #else /* not USE_TOOLKIT_SCROLL_BARS */
   XMapRaised (FRAME_X_DISPLAY (f), SCROLL_BAR_X_WINDOW (bar));
@@ -9040,7 +9389,7 @@ x_scroll_bar_create (w, top, left, width, height)
 
 
 /* Draw BAR's handle in the proper position.
-   
+
    If the handle is already drawn from START to END, don't bother
    redrawing it, unless REBUILD is non-zero; in that case, always
    redraw it.  (REBUILD is handy for drawing the handle after expose
@@ -9163,11 +9512,15 @@ x_scroll_bar_remove (bar)
   BLOCK_INPUT;
 
 #ifdef USE_TOOLKIT_SCROLL_BARS
+#ifdef USE_GTK
+  xg_remove_scroll_bar (f, SCROLL_BAR_X_WINDOW (bar));
+#else /* not USE_GTK */
   XtDestroyWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar));
+#endif /* not USE_GTK */
 #else
   XDestroyWindow (FRAME_X_DISPLAY (f), SCROLL_BAR_X_WINDOW (bar));
 #endif
-  
+
   /* Disassociate this scroll bar from its window.  */
   XWINDOW (bar->window)->vertical_scroll_bar = Qnil;
 
@@ -9214,16 +9567,16 @@ XTset_vertical_scroll_bar (w, portion, whole, position)
   /* Compute the left edge of the scroll bar.  */
 #ifdef USE_TOOLKIT_SCROLL_BARS
   if (FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
-    sb_left = left + width - sb_width - (width - sb_width) / 2; 
+    sb_left = left + width - sb_width - (width - sb_width) / 2;
   else
     sb_left = left + (width - sb_width) / 2;
 #else
   if (FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
-    sb_left = left + width - sb_width; 
+    sb_left = left + width - sb_width;
   else
     sb_left = left;
 #endif
-  
+
   /* Does the scroll bar exist yet?  */
   if (NILP (w->vertical_scroll_bar))
     {
@@ -9234,14 +9587,14 @@ XTset_vertical_scroll_bar (w, portion, whole, position)
                        left, top, width, height, False);
          UNBLOCK_INPUT;
        }
-      
+
       bar = x_scroll_bar_create (w, top, sb_left, sb_width, height);
     }
   else
     {
       /* It may just need to be moved and resized.  */
       unsigned int mask = 0;
-      
+
       bar = XSCROLL_BAR (w->vertical_scroll_bar);
 
       BLOCK_INPUT;
@@ -9252,27 +9605,37 @@ XTset_vertical_scroll_bar (w, portion, whole, position)
        mask |= CWY;
       if (sb_width != XINT (bar->width))
        mask |= CWWidth;
-      if (height != XINT (bar->height))        
+      if (height != XINT (bar->height))
        mask |= CWHeight;
-      
+
 #ifdef USE_TOOLKIT_SCROLL_BARS
 
+#ifdef USE_GTK
+      if (mask)
+        xg_update_scrollbar_pos (f,
+                                 SCROLL_BAR_X_WINDOW (bar),
+                                 top,
+                                 sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
+                                 sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
+                                 max (height, 1));
+#else /* not USE_GTK */
+
       /* Since toolkit scroll bars are smaller than the space reserved
-        for them on the frame, we have to clear "under" them.  */
+         for them on the frame, we have to clear "under" them.  */
       if (width > 0 && height > 0)
-       x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
-                     left, top, width, height, False);
-
+        x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
+                          left, top, width, height, False);
       /* Move/size the scroll bar widget.  */
       if (mask)
-       XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
-                          sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
-                          top,
-                          sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
-                          max (height, 1), 0);
+          XtConfigureWidget (SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar),
+                             sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
+                             top,
+                             sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
+                             max (height, 1), 0);
 
+#endif /* not USE_GTK */
 #else /* not USE_TOOLKIT_SCROLL_BARS */
-  
+
       /* Clear areas not covered by the scroll bar because of
         VERTICAL_SCROLL_BAR_WIDTH_TRIM.  */
       if (VERTICAL_SCROLL_BAR_WIDTH_TRIM)
@@ -9304,12 +9667,12 @@ XTset_vertical_scroll_bar (w, portion, whole, position)
                            left, top, rest, height, False);
          }
       }
-      
+
       /* Move/size the scroll bar window.  */
       if (mask)
        {
          XWindowChanges wc;
-         
+
          wc.x = sb_left + VERTICAL_SCROLL_BAR_WIDTH_TRIM;
          wc.y = top;
          wc.width = sb_width - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2;
@@ -9317,7 +9680,7 @@ XTset_vertical_scroll_bar (w, portion, whole, position)
          XConfigureWindow (FRAME_X_DISPLAY (f), SCROLL_BAR_X_WINDOW (bar),
                            mask, &wc);
        }
-  
+
 #endif /* not USE_TOOLKIT_SCROLL_BARS */
 
       /* Remember new settings.  */
@@ -9325,7 +9688,7 @@ XTset_vertical_scroll_bar (w, portion, whole, position)
       XSETINT (bar->top, top);
       XSETINT (bar->width, sb_width);
       XSETINT (bar->height, height);
-      
+
       UNBLOCK_INPUT;
     }
 
@@ -9489,19 +9852,18 @@ x_scroll_bar_expose (bar, event)
                  0, 0,
                  XINT (bar->width) - 1 - width_trim - width_trim,
                  XINT (bar->height) - 1);
-    
+
   UNBLOCK_INPUT;
 
 #endif /* not USE_TOOLKIT_SCROLL_BARS */
 }
 
 /* Handle a mouse click on the scroll bar BAR.  If *EMACS_EVENT's kind
-   is set to something other than no_event, it is enqueued.
+   is set to something other than NO_EVENT, it is enqueued.
 
    This may be called from a signal handler, so we have to ignore GC
    mark bits.  */
 
-#ifndef USE_TOOLKIT_SCROLL_BARS
 
 static void
 x_scroll_bar_handle_click (bar, event, emacs_event)
@@ -9512,10 +9874,10 @@ x_scroll_bar_handle_click (bar, event, emacs_event)
   if (! GC_WINDOWP (bar->window))
     abort ();
 
-  emacs_event->kind = scroll_bar_click;
+  emacs_event->kind = SCROLL_BAR_CLICK_EVENT;
   emacs_event->code = event->xbutton.button - Button1;
   emacs_event->modifiers
-    = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO 
+    = (x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO
                               (XFRAME (WINDOW_FRAME (XWINDOW (bar->window)))),
                               event->xbutton.state)
        | (event->type == ButtonRelease
@@ -9555,6 +9917,7 @@ x_scroll_bar_handle_click (bar, event, emacs_event)
       XSETINT (bar->dragging, y - XINT (bar->start));
 #endif
 
+#ifndef USE_TOOLKIT_SCROLL_BARS
     /* If the user has released the handle, set it to its final position.  */
     if (event->type == ButtonRelease
        && ! NILP (bar->dragging))
@@ -9565,6 +9928,7 @@ x_scroll_bar_handle_click (bar, event, emacs_event)
        x_scroll_bar_set_handle (bar, new_start, new_end, 0);
        bar->dragging = Qnil;
       }
+#endif
 
     /* Same deal here as the other #if 0.  */
 #if 0
@@ -9582,6 +9946,8 @@ x_scroll_bar_handle_click (bar, event, emacs_event)
   }
 }
 
+#ifndef USE_TOOLKIT_SCROLL_BARS
+
 /* Handle some mouse motion while someone is dragging the scroll bar.
 
    This may be called from a signal handler, so we have to ignore GC
@@ -9719,51 +10085,6 @@ x_scroll_bar_clear (f)
 #endif /* not USE_TOOLKIT_SCROLL_BARS */
 }
 
-/* This processes Expose events from the menu-bar specific X event
-   loop in xmenu.c.  This allows to redisplay the frame if necessary
-   when handling menu-bar or pop-up items.  */
-
-int
-process_expose_from_menu (event)
-     XEvent event;
-{
-  FRAME_PTR f;
-  struct x_display_info *dpyinfo;
-  int frame_exposed_p = 0;
-
-  BLOCK_INPUT;
-
-  dpyinfo = x_display_info_for_display (event.xexpose.display);
-  f = x_window_to_frame (dpyinfo, event.xexpose.window);
-  if (f)
-    {
-      if (f->async_visible == 0)
-       {
-         f->async_visible = 1;
-         f->async_iconified = 0;
-         f->output_data.x->has_been_visible = 1;
-         SET_FRAME_GARBAGED (f);
-       }
-      else
-       {
-         expose_frame (x_window_to_frame (dpyinfo, event.xexpose.window),
-                       event.xexpose.x, event.xexpose.y,
-                       event.xexpose.width, event.xexpose.height);
-         frame_exposed_p = 1;
-       }
-    }
-  else
-    {
-      struct scroll_bar *bar
-       = x_window_to_scroll_bar (event.xexpose.window);
-
-      if (bar)
-       x_scroll_bar_expose (bar, &event);
-    }
-
-  UNBLOCK_INPUT;
-  return frame_exposed_p;
-}
 \f
 /* Define a queue to save up SelectionRequest events for later handling.  */
 
@@ -9879,7 +10200,7 @@ static struct x_display_info *next_noop_dpyinfo;
          bcopy (&event, f->output_data.x->saved_menu_event, size);     \
          if (numchars >= 1)                                            \
            {                                                           \
-             bufp->kind = menu_bar_activate_event;                     \
+             bufp->kind = MENU_BAR_ACTIVATE_EVENT;                     \
              XSETFRAME (bufp->frame_or_window, f);                     \
              bufp->arg = Qnil;                                         \
              bufp++;                                                   \
@@ -9892,143 +10213,132 @@ static struct x_display_info *next_noop_dpyinfo;
 #define SET_SAVED_BUTTON_EVENT SET_SAVED_MENU_EVENT (sizeof (XButtonEvent))
 #define SET_SAVED_KEY_EVENT    SET_SAVED_MENU_EVENT (sizeof (XKeyEvent))
 
-/* Read events coming from the X server.
-   This routine is called by the SIGIO handler.
-   We return as soon as there are no more events to be read.
 
-   Events representing keys are stored in buffer BUFP,
-   which can hold up to NUMCHARS characters.
-   We return the number of characters stored into the buffer,
-   thus pretending to be `read'.
+enum
+{
+  X_EVENT_NORMAL,
+  X_EVENT_GOTO_OUT,
+  X_EVENT_DROP
+};
 
-   EXPECTED is nonzero if the caller knows input is available.  */
+/* Filter events for the current X input method.
+   DPYINFO is the display this event is for.
+   EVENT is the X event to filter.
 
+   Returns non-zero if the event was filtered, caller shall not process
+   this event further.
+   Returns zero if event is wasn't filtered.  */
+
+#ifdef HAVE_X_I18N
 static int
-XTread_socket (sd, bufp, numchars, expected)
-     register int sd;
-     /* register */ struct input_event *bufp;
-     /* register */ int numchars;
-     int expected;
+x_filter_event (dpyinfo, event)
+     struct x_display_info *dpyinfo;
+     XEvent *event;
 {
-  int count = 0;
-  int nbytes = 0;
-  XEvent event;
-  struct frame *f;
-  int event_found = 0;
-  struct x_display_info *dpyinfo;
-  struct coding_system coding;
+  /* XFilterEvent returns non-zero if the input method has
+   consumed the event.  We pass the frame's X window to
+   XFilterEvent because that's the one for which the IC
+   was created.  */
 
-  if (interrupt_input_blocked)
+  struct frame *f1 = x_any_window_to_frame (dpyinfo,
+                                            event->xclient.window);
+
+  return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
+}
+#endif
+
+#ifdef USE_GTK
+static struct x_display_info *current_dpyinfo;
+static struct input_event **current_bufp;
+static int *current_numcharsp;
+static int current_count;
+static int current_finish;
+
+/* This is the filter function invoked by the GTK event loop.
+   It is invoked before the XEvent is translated to a GdkEvent,
+   so we have a chanse to act on the event before GTK. */
+static GdkFilterReturn
+event_handler_gdk (gxev, ev, data)
+     GdkXEvent *gxev;
+     GdkEvent *ev;
+     gpointer data;
+{
+  XEvent *xev = (XEvent*)gxev;
+
+  if (current_numcharsp)
     {
-      interrupt_input_pending = 1;
-      return -1;
+#ifdef HAVE_X_I18N
+      /* Filter events for the current X input method.
+         GTK calls XFilterEvent but not for key press and release,
+         so we do it here.  */
+      if (xev->type == KeyPress || xev->type == KeyRelease)
+        if (x_filter_event (current_dpyinfo, xev))
+          return GDK_FILTER_REMOVE;
+#endif
+      current_count += handle_one_xevent (current_dpyinfo,
+                                          xev,
+                                          current_bufp,
+                                          current_numcharsp,
+                                          &current_finish);
     }
+  else
+    current_finish = x_dispatch_event (xev, GDK_DISPLAY ());
 
-  interrupt_input_pending = 0;
-  BLOCK_INPUT;
+  if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
+    return GDK_FILTER_REMOVE;
 
-  /* So people can tell when we have read the available input.  */
-  input_signal_count++;
+  return GDK_FILTER_CONTINUE;
+}
+#endif /* USE_GTK */
 
-  if (numchars <= 0)
-    abort ();                  /* Don't think this happens.  */
 
-  ++handling_signal;
-  
-  /* The input should be decoded if it is from XIM.  Currently the
-     locale of XIM is the same as that of the system.  So, we can use
-     Vlocale_coding_system which is initialized properly at Emacs
-     startup time.  */
-  setup_coding_system (Vlocale_coding_system, &coding);
-  coding.src_multibyte = 0;
-  coding.dst_multibyte = 1;
-  /* The input is converted to events, thus we can't handle
-     composition.  Anyway, there's no XIM that gives us composition
-     information.  */
-  coding.composing = COMPOSITION_DISABLED;
+/* Handles the XEvent EVENT on display DPYINFO.
 
-  /* Find the display we are supposed to read input for.
-     It's the one communicating on descriptor SD.  */
-  for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
+   *FINISH is X_EVENT_GOTO_OUT if caller should stop reading events.
+   *FINISH is zero if caller should continue reading events.
+   *FINISH is X_EVENT_DROP if event should not be passed to the toolkit.
+
+   Events representing keys are stored in buffer *BUFP_R,
+   which can hold up to *NUMCHARSP characters.
+   We return the number of characters stored into the buffer. */
+
+static int
+handle_one_xevent (dpyinfo, eventp, bufp_r, numcharsp, finish)
+     struct x_display_info *dpyinfo;
+     XEvent *eventp;
+     /* register */ struct input_event **bufp_r;
+     /* register */ int *numcharsp;
+     int *finish;
+{
+  int count = 0;
+  int nbytes = 0;
+  struct frame *f;
+  struct coding_system coding;
+  struct input_event *bufp = *bufp_r;
+  int numchars = *numcharsp;
+  XEvent event = *eventp;
+
+  *finish = X_EVENT_NORMAL;
+
+  switch (event.type)
     {
-#if 0 /* This ought to be unnecessary; let's verify it.  */
-#ifdef FIOSNBIO
-      /* If available, Xlib uses FIOSNBIO to make the socket
-        non-blocking, and then looks for EWOULDBLOCK.  If O_NDELAY is set,
-        FIOSNBIO is ignored, and instead of signaling EWOULDBLOCK,
-        a read returns 0, which Xlib interprets as equivalent to EPIPE.  */
-      fcntl (dpyinfo->connection, F_SETFL, 0);
-#endif /* ! defined (FIOSNBIO) */
-#endif
-
-#if 0 /* This code can't be made to work, with multiple displays,
-        and appears not to be used on any system any more.
-        Also keyboard.c doesn't turn O_NDELAY on and off
-        for X connections.  */
-#ifndef SIGIO
-#ifndef HAVE_SELECT
-      if (! (fcntl (dpyinfo->connection, F_GETFL, 0) & O_NDELAY))
-       {
-         extern int read_alarm_should_throw;
-         read_alarm_should_throw = 1;
-         XPeekEvent (dpyinfo->display, &event);
-         read_alarm_should_throw = 0;
-       }
-#endif /* HAVE_SELECT */
-#endif /* SIGIO */
-#endif
-
-      /* For debugging, this gives a way to fake an I/O error.  */
-      if (dpyinfo == XTread_socket_fake_io_error)
-       {
-         XTread_socket_fake_io_error = 0;
-         x_io_error_quitter (dpyinfo->display);
-       }
-
-#ifdef HAVE_X_SM
-      BLOCK_INPUT;
-      count += x_session_check_input (bufp, &numchars);
-      UNBLOCK_INPUT;
-#endif
-
-      while (XPending (dpyinfo->display))
-       {
-         XNextEvent (dpyinfo->display, &event);
-
-#ifdef HAVE_X_I18N
-         {
-           /* Filter events for the current X input method.
-              XFilterEvent returns non-zero if the input method has
-              consumed the event.  We pass the frame's X window to
-              XFilterEvent because that's the one for which the IC
-              was created.  */
-           struct frame *f1 = x_any_window_to_frame (dpyinfo,
-                                                     event.xclient.window);
-           if (XFilterEvent (&event, f1 ? FRAME_X_WINDOW (f1) : None))
-             break;
-         }
-#endif
-         event_found = 1;
-
-         switch (event.type)
-           {
-           case ClientMessage:
-             {
-               if (event.xclient.message_type
-                   == dpyinfo->Xatom_wm_protocols
-                   && event.xclient.format == 32)
-                 {
-                   if (event.xclient.data.l[0]
-                       == dpyinfo->Xatom_wm_take_focus)
-                     {
-                       /* 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 && FRAME_XIC (f))
-                         XSetICFocus (FRAME_XIC (f));
+    case ClientMessage:
+      {
+        if (event.xclient.message_type
+            == dpyinfo->Xatom_wm_protocols
+            && event.xclient.format == 32)
+          {
+            if (event.xclient.data.l[0]
+                == dpyinfo->Xatom_wm_take_focus)
+              {
+                /* 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 && FRAME_XIC (f))
+                  XSetICFocus (FRAME_XIC (f));
 #endif
 #if 0 /* Emacs sets WM hints whose `input' field is `true'.  This
         instructs the WM to set the input focus automatically for
@@ -10042,1114 +10352,1393 @@ XTread_socket (sd, bufp, numchars, expected)
         below are temporally close (on a fast machine), the call
         below can generate additional FocusIn events which confuse
         Emacs.  */
-                       
-                       /* 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)
-                         {
-                           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,
-                                           /* The ICCCM says this is
-                                              the only valid choice.  */
-                                           RevertToParent,
-                                           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 */
+
+                /* 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)
+                  {
+                    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,
+                                    /* The ICCCM says this is
+                                       the only valid choice.  */
+                                    RevertToParent,
+                                    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 */
 #endif /* 0 */
-                     }
-                   else if (event.xclient.data.l[0]
-                            == dpyinfo->Xatom_wm_save_yourself)
-                     {
-                       /* Save state modify the WM_COMMAND property to
-                          something which can reinstate us.  This notifies
-                          the session manager, who's looking for such a
-                          PropertyNotify.  Can restart processing when
-                          a keyboard or mouse event arrives.  */
-                        /* If we have a session manager, don't set this.
-                           KDE will then start two Emacsen, one for the
-                           session manager and one for this. */
-                       if (numchars > 0
+              }
+            else if (event.xclient.data.l[0]
+                     == dpyinfo->Xatom_wm_save_yourself)
+              {
+                /* Save state modify the WM_COMMAND property to
+                   something which can reinstate us.  This notifies
+                   the session manager, who's looking for such a
+                   PropertyNotify.  Can restart processing when
+                   a keyboard or mouse event arrives.  */
+                /* If we have a session manager, don't set this.
+                   KDE will then start two Emacsen, one for the
+                   session manager and one for this. */
+                if (numchars > 0
 #ifdef HAVE_X_SM
-                            && ! x_session_have_connection ()
+                    && ! x_session_have_connection ()
 #endif
-                            )
-                         {
-                           f = x_top_window_to_frame (dpyinfo,
-                                                      event.xclient.window);
-                           /* This is just so we only give real data once
-                              for a single Emacs process.  */
-                           if (f == SELECTED_FRAME ())
-                             XSetCommand (FRAME_X_DISPLAY (f),
-                                          event.xclient.window,
-                                          initial_argv, initial_argc);
-                           else if (f)
-                             XSetCommand (FRAME_X_DISPLAY (f),
-                                          event.xclient.window,
-                                          0, 0);
-                         }
-                     }
-                   else if (event.xclient.data.l[0]
-                            == dpyinfo->Xatom_wm_delete_window)
-                     {
-                       struct frame *f
-                         = x_any_window_to_frame (dpyinfo,
-                                                  event.xclient.window);
-
-                       if (f)
-                         {
-                           if (numchars == 0)
-                             abort ();
-
-                           bufp->kind = delete_window_event;
-                           XSETFRAME (bufp->frame_or_window, f);
-                           bufp->arg = Qnil;
-                           bufp++;
-
-                           count += 1;
-                           numchars -= 1;
-                         }
-                     }
-                 }
-               else if (event.xclient.message_type
-                        == dpyinfo->Xatom_wm_configure_denied)
-                 {
-                 }
-               else if (event.xclient.message_type
-                        == dpyinfo->Xatom_wm_window_moved)
-                 {
-                   int new_x, new_y;
-                   struct frame *f
-                     = x_window_to_frame (dpyinfo, event.xclient.window);
-
-                   new_x = event.xclient.data.s[0];
-                   new_y = event.xclient.data.s[1];
-
-                   if (f)
-                     {
-                       f->output_data.x->left_pos = new_x;
-                       f->output_data.x->top_pos = new_y;
-                     }
-                 }
+                    )
+                  {
+                    f = x_top_window_to_frame (dpyinfo,
+                                               event.xclient.window);
+                    /* This is just so we only give real data once
+                       for a single Emacs process.  */
+                    if (f == SELECTED_FRAME ())
+                      XSetCommand (FRAME_X_DISPLAY (f),
+                                   event.xclient.window,
+                                   initial_argv, initial_argc);
+                    else if (f)
+                      XSetCommand (FRAME_X_DISPLAY (f),
+                                   event.xclient.window,
+                                   0, 0);
+                  }
+              }
+            else if (event.xclient.data.l[0]
+                     == dpyinfo->Xatom_wm_delete_window)
+              {
+                struct frame *f
+                  = x_any_window_to_frame (dpyinfo,
+                                           event.xclient.window);
+
+                if (f)
+                  {
+                    if (numchars == 0)
+                      abort ();
+
+                    bufp->kind = DELETE_WINDOW_EVENT;
+                    XSETFRAME (bufp->frame_or_window, f);
+                    bufp->arg = Qnil;
+                    bufp++;
+
+                    count += 1;
+                    numchars -= 1;
+                  }
+                else
+                  goto OTHER; /* May be a dialog that is to be removed  */
+              }
+          }
+        else if (event.xclient.message_type
+                 == dpyinfo->Xatom_wm_configure_denied)
+          {
+          }
+        else if (event.xclient.message_type
+                 == dpyinfo->Xatom_wm_window_moved)
+          {
+            int new_x, new_y;
+            struct frame *f
+              = x_window_to_frame (dpyinfo, event.xclient.window);
+
+            new_x = event.xclient.data.s[0];
+            new_y = event.xclient.data.s[1];
+
+            if (f)
+              {
+                f->output_data.x->left_pos = new_x;
+                f->output_data.x->top_pos = new_y;
+              }
+          }
 #ifdef HACK_EDITRES
-               else if (event.xclient.message_type
-                        == dpyinfo->Xatom_editres)
-                 {
-                   struct frame *f
-                     = x_any_window_to_frame (dpyinfo, event.xclient.window);
-                   _XEditResCheckMessages (f->output_data.x->widget, NULL,
-                                           &event, NULL);
-                 }
+        else if (event.xclient.message_type
+                 == dpyinfo->Xatom_editres)
+          {
+            struct frame *f
+              = x_any_window_to_frame (dpyinfo, event.xclient.window);
+            _XEditResCheckMessages (f->output_data.x->widget, NULL,
+                                    &event, NULL);
+          }
 #endif /* HACK_EDITRES */
-               else if ((event.xclient.message_type
-                         == dpyinfo->Xatom_DONE)
-                        || (event.xclient.message_type
-                            == dpyinfo->Xatom_PAGE))
-                 {
-                   /* Ghostview job completed.  Kill it.  We could
-                      reply with "Next" if we received "Page", but we
-                      currently never do because we are interested in
-                      images, only, which should have 1 page.  */
-                   Pixmap pixmap = (Pixmap) event.xclient.data.l[1];
-                   struct frame *f
-                     = x_window_to_frame (dpyinfo, event.xclient.window);
-                   x_kill_gs_process (pixmap, f);
-                   expose_frame (f, 0, 0, 0, 0);
-                 }
+        else if ((event.xclient.message_type
+                  == dpyinfo->Xatom_DONE)
+                 || (event.xclient.message_type
+                     == dpyinfo->Xatom_PAGE))
+          {
+            /* Ghostview job completed.  Kill it.  We could
+               reply with "Next" if we received "Page", but we
+               currently never do because we are interested in
+               images, only, which should have 1 page.  */
+            Pixmap pixmap = (Pixmap) event.xclient.data.l[1];
+            struct frame *f
+              = x_window_to_frame (dpyinfo, event.xclient.window);
+            x_kill_gs_process (pixmap, f);
+            expose_frame (f, 0, 0, 0, 0);
+          }
 #ifdef USE_TOOLKIT_SCROLL_BARS
-               /* Scroll bar callbacks send a ClientMessage from which
-                  we construct an input_event.  */
-               else if (event.xclient.message_type
-                        == dpyinfo->Xatom_Scrollbar)
-                 {
-                   x_scroll_bar_to_input_event (&event, bufp);
-                   ++bufp, ++count, --numchars;
-                   goto out;
-                 }
+        /* Scroll bar callbacks send a ClientMessage from which
+           we construct an input_event.  */
+        else if (event.xclient.message_type
+                 == dpyinfo->Xatom_Scrollbar)
+          {
+            x_scroll_bar_to_input_event (&event, bufp);
+            ++bufp, ++count, --numchars;
+            goto out;
+          }
 #endif /* USE_TOOLKIT_SCROLL_BARS */
-               else
-                 goto OTHER;
-             }
-             break;
+        else
+          goto OTHER;
+      }
+      break;
 
-           case SelectionNotify:
+    case SelectionNotify:
 #ifdef USE_X_TOOLKIT
-             if (! x_window_to_frame (dpyinfo, event.xselection.requestor))
-               goto OTHER;
+      if (! x_window_to_frame (dpyinfo, event.xselection.requestor))
+        goto OTHER;
 #endif /* not USE_X_TOOLKIT */
-             x_handle_selection_notify (&event.xselection);
-             break;
+      x_handle_selection_notify (&event.xselection);
+      break;
 
-           case SelectionClear:        /* Someone has grabbed ownership.  */
+    case SelectionClear:       /* Someone has grabbed ownership.  */
 #ifdef USE_X_TOOLKIT
-             if (! x_window_to_frame (dpyinfo, event.xselectionclear.window))
-               goto OTHER;
+      if (! x_window_to_frame (dpyinfo, event.xselectionclear.window))
+        goto OTHER;
 #endif /* USE_X_TOOLKIT */
-             {
-               XSelectionClearEvent *eventp = (XSelectionClearEvent *) &event;
+      {
+        XSelectionClearEvent *eventp = (XSelectionClearEvent *) &event;
 
-               if (numchars == 0)
-                 abort ();
+        if (numchars == 0)
+          abort ();
 
-               bufp->kind = selection_clear_event;
-               SELECTION_EVENT_DISPLAY (bufp) = eventp->display;
-               SELECTION_EVENT_SELECTION (bufp) = eventp->selection;
-               SELECTION_EVENT_TIME (bufp) = eventp->time;
-               bufp->frame_or_window = Qnil;
-               bufp->arg = Qnil;
-               bufp++;
+        bufp->kind = SELECTION_CLEAR_EVENT;
+        SELECTION_EVENT_DISPLAY (bufp) = eventp->display;
+        SELECTION_EVENT_SELECTION (bufp) = eventp->selection;
+        SELECTION_EVENT_TIME (bufp) = eventp->time;
+        bufp->frame_or_window = Qnil;
+        bufp->arg = Qnil;
+        bufp++;
 
-               count += 1;
-               numchars -= 1;
-             }
-             break;
+        count += 1;
+        numchars -= 1;
+      }
+      break;
 
-           case SelectionRequest:      /* Someone wants our selection.  */
+    case SelectionRequest:     /* Someone wants our selection.  */
 #ifdef USE_X_TOOLKIT
-             if (!x_window_to_frame (dpyinfo, event.xselectionrequest.owner))
-               goto OTHER;
+      if (!x_window_to_frame (dpyinfo, event.xselectionrequest.owner))
+        goto OTHER;
 #endif /* USE_X_TOOLKIT */
-             if (x_queue_selection_requests)
-               x_queue_event (x_window_to_frame (dpyinfo, event.xselectionrequest.owner),
-                              &event);
-             else
-               {
-                 XSelectionRequestEvent *eventp
-                   = (XSelectionRequestEvent *) &event;
-
-                 if (numchars == 0)
-                   abort ();
-
-                 bufp->kind = selection_request_event;
-                 SELECTION_EVENT_DISPLAY (bufp) = eventp->display;
-                 SELECTION_EVENT_REQUESTOR (bufp) = eventp->requestor;
-                 SELECTION_EVENT_SELECTION (bufp) = eventp->selection;
-                 SELECTION_EVENT_TARGET (bufp) = eventp->target;
-                 SELECTION_EVENT_PROPERTY (bufp) = eventp->property;
-                 SELECTION_EVENT_TIME (bufp) = eventp->time;
-                 bufp->frame_or_window = Qnil;
-                 bufp->arg = Qnil;
-                 bufp++;
-
-                 count += 1;
-                 numchars -= 1;
-               }
-             break;
+      if (x_queue_selection_requests)
+        x_queue_event (x_window_to_frame (dpyinfo, event.xselectionrequest.owner),
+                       &event);
+      else
+        {
+          XSelectionRequestEvent *eventp
+            = (XSelectionRequestEvent *) &event;
+
+          if (numchars == 0)
+            abort ();
+
+          bufp->kind = SELECTION_REQUEST_EVENT;
+          SELECTION_EVENT_DISPLAY (bufp) = eventp->display;
+          SELECTION_EVENT_REQUESTOR (bufp) = eventp->requestor;
+          SELECTION_EVENT_SELECTION (bufp) = eventp->selection;
+          SELECTION_EVENT_TARGET (bufp) = eventp->target;
+          SELECTION_EVENT_PROPERTY (bufp) = eventp->property;
+          SELECTION_EVENT_TIME (bufp) = eventp->time;
+          bufp->frame_or_window = Qnil;
+          bufp->arg = Qnil;
+          bufp++;
+
+          count += 1;
+          numchars -= 1;
+        }
+      break;
 
-           case PropertyNotify:
+    case PropertyNotify:
 #if 0 /* This is plain wrong.  In the case that we are waiting for a
         PropertyNotify used as an ACK in incremental selection
         transfer, the property will be on the receiver's window.  */
 #if defined USE_X_TOOLKIT
-             if (!x_any_window_to_frame (dpyinfo, event.xproperty.window))
-               goto OTHER;
+      if (!x_any_window_to_frame (dpyinfo, event.xproperty.window))
+        goto OTHER;
 #endif
 #endif
-             x_handle_property_notify (&event.xproperty);
-             goto OTHER;
+      x_handle_property_notify (&event.xproperty);
+      goto OTHER;
 
-           case ReparentNotify:
-             f = x_top_window_to_frame (dpyinfo, event.xreparent.window);
-             if (f)
-               {
-                 int x, y;
-                 f->output_data.x->parent_desc = event.xreparent.parent;
-                 x_real_positions (f, &x, &y);
-                 f->output_data.x->left_pos = x;
-                 f->output_data.x->top_pos = y;
-               }
-             break;
-
-           case Expose:
-             f = x_window_to_frame (dpyinfo, event.xexpose.window);
-             if (f)
-               {
-                  x_check_fullscreen (f);
+    case ReparentNotify:
+      f = x_top_window_to_frame (dpyinfo, event.xreparent.window);
+      if (f)
+        {
+          int x, y;
+          f->output_data.x->parent_desc = event.xreparent.parent;
+          x_real_positions (f, &x, &y);
+          f->output_data.x->left_pos = x;
+          f->output_data.x->top_pos = y;
+        }
+      goto OTHER;
+      break;
 
-                 if (f->async_visible == 0)
-                   {
-                     f->async_visible = 1;
-                     f->async_iconified = 0;
-                     f->output_data.x->has_been_visible = 1;
-                     SET_FRAME_GARBAGED (f);
-                   }
-                 else
-                   expose_frame (x_window_to_frame (dpyinfo,
-                                                    event.xexpose.window),
-                                 event.xexpose.x, event.xexpose.y,
-                                 event.xexpose.width, event.xexpose.height);
-               }
-             else
-               {
+    case Expose:
+      f = x_window_to_frame (dpyinfo, event.xexpose.window);
+      if (f)
+        {
+          x_check_fullscreen (f);
+
+          if (f->async_visible == 0)
+            {
+              f->async_visible = 1;
+              f->async_iconified = 0;
+              f->output_data.x->has_been_visible = 1;
+              SET_FRAME_GARBAGED (f);
+            }
+          else
+            expose_frame (x_window_to_frame (dpyinfo,
+                                             event.xexpose.window),
+                          event.xexpose.x, event.xexpose.y,
+                          event.xexpose.width, event.xexpose.height);
+        }
+      else
+        {
 #ifndef USE_TOOLKIT_SCROLL_BARS
-                 struct scroll_bar *bar;
+          struct scroll_bar *bar;
 #endif
 #if defined USE_LUCID
-                 /* Submenus of the Lucid menu bar aren't widgets
-                    themselves, so there's no way to dispatch events
-                    to them.  Recognize this case separately.  */
-                 {
-                   Widget widget
-                     = x_window_to_menu_bar (event.xexpose.window);
-                   if (widget)
-                     xlwmenu_redisplay (widget);
-                 }
+          /* Submenus of the Lucid menu bar aren't widgets
+             themselves, so there's no way to dispatch events
+             to them.  Recognize this case separately.  */
+          {
+            Widget widget
+              = x_window_to_menu_bar (event.xexpose.window);
+            if (widget)
+              xlwmenu_redisplay (widget);
+          }
 #endif /* USE_LUCID */
 
 #ifdef USE_TOOLKIT_SCROLL_BARS
-                 /* Dispatch event to the widget.  */
-                 goto OTHER;
+          /* Dispatch event to the widget.  */
+          goto OTHER;
 #else /* not USE_TOOLKIT_SCROLL_BARS */
-                 bar = x_window_to_scroll_bar (event.xexpose.window);
+          bar = x_window_to_scroll_bar (event.xexpose.window);
 
-                 if (bar)
-                   x_scroll_bar_expose (bar, &event);
+          if (bar)
+            x_scroll_bar_expose (bar, &event);
 #ifdef USE_X_TOOLKIT
-                 else
-                   goto OTHER;
+          else
+            goto OTHER;
 #endif /* USE_X_TOOLKIT */
 #endif /* not USE_TOOLKIT_SCROLL_BARS */
-               }
-             break;
+        }
+      break;
 
-           case GraphicsExpose:        /* This occurs when an XCopyArea's
-                                          source area was obscured or not
-                                          available.  */
-             f = x_window_to_frame (dpyinfo, event.xgraphicsexpose.drawable);
-             if (f)
-               {
-                 expose_frame (f,
-                               event.xgraphicsexpose.x, event.xgraphicsexpose.y,
-                               event.xgraphicsexpose.width,
-                               event.xgraphicsexpose.height);
-               }
+    case GraphicsExpose:       /* This occurs when an XCopyArea's
+                                   source area was obscured or not
+                                   available.  */
+      f = x_window_to_frame (dpyinfo, event.xgraphicsexpose.drawable);
+      if (f)
+        {
+          expose_frame (f,
+                        event.xgraphicsexpose.x, event.xgraphicsexpose.y,
+                        event.xgraphicsexpose.width,
+                        event.xgraphicsexpose.height);
+        }
 #ifdef USE_X_TOOLKIT
-             else
-               goto OTHER;
+      else
+        goto OTHER;
 #endif /* USE_X_TOOLKIT */
-             break;
+      break;
 
-           case NoExpose:              /* This occurs when an XCopyArea's
-                                          source area was completely
-                                          available.  */
-             break;
+    case NoExpose:             /* This occurs when an XCopyArea's
+                                   source area was completely
+                                   available.  */
+      break;
 
-           case UnmapNotify:
-             /* Redo the mouse-highlight after the tooltip has gone.  */
-             if (event.xmap.window == tip_window)
-               {
-                 tip_window = 0;
-                 redo_mouse_highlight ();
-               }
-             
-             f = x_top_window_to_frame (dpyinfo, event.xunmap.window);
-             if (f)            /* F may no longer exist if
-                                  the frame was deleted.  */
-               {
-                 /* While a frame is unmapped, display generation is
-                    disabled; you don't want to spend time updating a
-                    display that won't ever be seen.  */
-                 f->async_visible = 0;
-                 /* 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.
-                    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;
-
-                     bufp->kind = iconify_event;
-                     XSETFRAME (bufp->frame_or_window, f);
-                     bufp->arg = Qnil;
-                     bufp++;
-                     count++;
-                     numchars--;
-                   }
-               }
-             goto OTHER;
-
-           case MapNotify:
-             if (event.xmap.window == tip_window)
-               /* The tooltip has been drawn already.  Avoid
-                  the SET_FRAME_GARBAGED below.  */
-               goto OTHER;
-             
-             /* We use x_top_window_to_frame because map events can
-                come for sub-windows and they don't mean that the
-                frame is visible.  */
-             f = x_top_window_to_frame (dpyinfo, event.xmap.window);
-             if (f)
-               {
-                 f->async_visible = 1;
-                 f->async_iconified = 0;
-                 f->output_data.x->has_been_visible = 1;
+    case UnmapNotify:
+      /* Redo the mouse-highlight after the tooltip has gone.  */
+      if (event.xmap.window == tip_window)
+        {
+          tip_window = 0;
+          redo_mouse_highlight ();
+        }
 
-                 /* wait_reading_process_input will notice this and update
-                    the frame's display structures.  */
-                 SET_FRAME_GARBAGED (f);
+      f = x_top_window_to_frame (dpyinfo, event.xunmap.window);
+      if (f)           /* F may no longer exist if
+                           the frame was deleted.  */
+        {
+          /* While a frame is unmapped, display generation is
+             disabled; you don't want to spend time updating a
+             display that won't ever be seen.  */
+          f->async_visible = 0;
+          /* 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.
+             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;
+
+              bufp->kind = ICONIFY_EVENT;
+              XSETFRAME (bufp->frame_or_window, f);
+              bufp->arg = Qnil;
+              bufp++;
+              count++;
+              numchars--;
+            }
+        }
+      goto OTHER;
+
+    case MapNotify:
+      if (event.xmap.window == tip_window)
+        /* The tooltip has been drawn already.  Avoid
+           the SET_FRAME_GARBAGED below.  */
+        goto OTHER;
+
+      /* We use x_top_window_to_frame because map events can
+         come for sub-windows and they don't mean that the
+         frame is visible.  */
+      f = x_top_window_to_frame (dpyinfo, event.xmap.window);
+      if (f)
+        {
+          /* wait_reading_process_input will notice this and update
+             the frame's display structures.
+             If we where iconified, we should not set garbaged,
+             because that stops redrawing on Expose events.  This looks
+             bad if we are called from a recursive event loop
+             (x_dispatch_event), for example when a dialog is up.  */
+          if (! f->async_iconified)
+            SET_FRAME_GARBAGED (f);
+
+          f->async_visible = 1;
+          f->async_iconified = 0;
+          f->output_data.x->has_been_visible = 1;
+
+          if (f->iconified)
+            {
+              bufp->kind = DEICONIFY_EVENT;
+              XSETFRAME (bufp->frame_or_window, f);
+              bufp->arg = Qnil;
+              bufp++;
+              count++;
+              numchars--;
+            }
+          else if (! NILP (Vframe_list)
+                   && ! NILP (XCDR (Vframe_list)))
+            /* Force a redisplay sooner or later
+               to update the frame titles
+               in case this is the second frame.  */
+            record_asynch_buffer_change ();
+        }
+      goto OTHER;
 
-                 if (f->iconified)
-                   {
-                     bufp->kind = deiconify_event;
-                     XSETFRAME (bufp->frame_or_window, f);
-                     bufp->arg = Qnil;
-                     bufp++;
-                     count++;
-                     numchars--;
-                   }
-                 else if (! NILP (Vframe_list)
-                          && ! NILP (XCDR (Vframe_list)))
-                   /* Force a redisplay sooner or later
-                      to update the frame titles
-                      in case this is the second frame.  */
-                   record_asynch_buffer_change ();
-               }
-             goto OTHER;
+    case KeyPress:
 
-           case KeyPress:
-             f = x_any_window_to_frame (dpyinfo, event.xkey.window);
+#if defined (USE_X_TOOLKIT) || defined (USE_GTK)
+      /* Dispatch KeyPress events when in menu.  */
+      if (popup_activated ())
+        goto OTHER;
+#endif
 
-             if (!dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
-               {
-                 dpyinfo->mouse_face_hidden = 1;
-                 clear_mouse_face (dpyinfo);
-               }
+      f = x_any_window_to_frame (dpyinfo, event.xkey.window);
+
+      if (!dpyinfo->mouse_face_hidden && INTEGERP (Vmouse_highlight))
+        {
+          dpyinfo->mouse_face_hidden = 1;
+          clear_mouse_face (dpyinfo);
+        }
 
 #if defined USE_MOTIF && defined USE_TOOLKIT_SCROLL_BARS
-             if (f == 0)
-               {
-                 /* Scroll bars consume key events, but we want
-                    the keys to go to the scroll bar's frame.  */
-                 Widget widget = XtWindowToWidget (dpyinfo->display,
-                                                   event.xkey.window);
-                 if (widget && XmIsScrollBar (widget))
-                   {
-                     widget = XtParent (widget);
-                     f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
-                   }
-               }
+      if (f == 0)
+        {
+          /* Scroll bars consume key events, but we want
+             the keys to go to the scroll bar's frame.  */
+          Widget widget = XtWindowToWidget (dpyinfo->display,
+                                            event.xkey.window);
+          if (widget && XmIsScrollBar (widget))
+            {
+              widget = XtParent (widget);
+              f = x_any_window_to_frame (dpyinfo, XtWindow (widget));
+            }
+        }
 #endif /* USE_MOTIF and USE_TOOLKIT_SCROLL_BARS */
 
-             if (f != 0)
-               {
-                 KeySym keysym, orig_keysym;
-                 /* al%imercury@uunet.uu.net says that making this 81
-                    instead of 80 fixed a bug whereby meta chars made
-                    his Emacs hang.
-
-                    It seems that some version of XmbLookupString has
-                    a bug of not returning XBufferOverflow in
-                    status_return even if the input is too long to
-                    fit in 81 bytes.  So, we must prepare sufficient
-                    bytes for copy_buffer.  513 bytes (256 chars for
-                    two-byte character set) seems to be a fairly good
-                    approximation.  -- 2000.8.10 handa@etl.go.jp  */
-                 unsigned char copy_buffer[513];
-                 unsigned char *copy_bufptr = copy_buffer;
-                 int copy_bufsiz = sizeof (copy_buffer);
-                 int modifiers;
-
-                 event.xkey.state
-                   |= x_emacs_to_x_modifiers (FRAME_X_DISPLAY_INFO (f),
-                                              extra_keyboard_modifiers);
-                 modifiers = event.xkey.state;
-
-                 /* This will have to go some day...  */
-
-                 /* make_lispy_event turns chars into control chars.
-                    Don't do it here because XLookupString is too eager.  */
-                 event.xkey.state &= ~ControlMask;
-                 event.xkey.state &= ~(dpyinfo->meta_mod_mask
-                                       | dpyinfo->super_mod_mask
-                                       | 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));
+      if (f != 0)
+        {
+          KeySym keysym, orig_keysym;
+          /* al%imercury@uunet.uu.net says that making this 81
+             instead of 80 fixed a bug whereby meta chars made
+             his Emacs hang.
+
+             It seems that some version of XmbLookupString has
+             a bug of not returning XBufferOverflow in
+             status_return even if the input is too long to
+             fit in 81 bytes.  So, we must prepare sufficient
+             bytes for copy_buffer.  513 bytes (256 chars for
+             two-byte character set) seems to be a fairly good
+             approximation.  -- 2000.8.10 handa@etl.go.jp  */
+          unsigned char copy_buffer[513];
+          unsigned char *copy_bufptr = copy_buffer;
+          int copy_bufsiz = sizeof (copy_buffer);
+          int modifiers;
+          Lisp_Object coding_system = Qlatin_1;
+
+          event.xkey.state
+            |= x_emacs_to_x_modifiers (FRAME_X_DISPLAY_INFO (f),
+                                       extra_keyboard_modifiers);
+          modifiers = event.xkey.state;
+
+          /* This will have to go some day...  */
+
+          /* make_lispy_event turns chars into control chars.
+             Don't do it here because XLookupString is too eager.  */
+          event.xkey.state &= ~ControlMask;
+          event.xkey.state &= ~(dpyinfo->meta_mod_mask
+                                | dpyinfo->super_mod_mask
+                                | 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))
-                   {
-                     Status status_return;
-
-                     nbytes = XmbLookupString (FRAME_XIC (f),
-                                               &event.xkey, copy_bufptr,
-                                               copy_bufsiz, &keysym,
-                                               &status_return);
-                     if (status_return == XBufferOverflow)
-                       {
-                         copy_bufsiz = nbytes + 1;
-                         copy_bufptr = (char *) alloca (copy_bufsiz);
-                         nbytes = XmbLookupString (FRAME_XIC (f),
-                                                   &event.xkey, copy_bufptr,
-                                                   copy_bufsiz, &keysym,
-                                                   &status_return);
-                       }
-
-                     if (status_return == XLookupNone)
-                       break;
-                     else if (status_return == XLookupChars)
-                       {
-                         keysym = NoSymbol;
-                         modifiers = 0;
-                       }
-                     else if (status_return != XLookupKeySym
-                              && status_return != XLookupBoth)
-                       abort ();
-                   }
-                 else
-                   nbytes = XLookupString (&event.xkey, copy_bufptr,
-                                           copy_bufsiz, &keysym,
-                                           &compose_status);
-#else
-                 nbytes = XLookupString (&event.xkey, copy_bufptr,
-                                         copy_bufsiz, &keysym,
-                                         &compose_status);
+          if (FRAME_XIC (f))
+            {
+              Status status_return;
+
+              coding_system = Vlocale_coding_system;
+              nbytes = XmbLookupString (FRAME_XIC (f),
+                                        &event.xkey, copy_bufptr,
+                                        copy_bufsiz, &keysym,
+                                        &status_return);
+              if (status_return == XBufferOverflow)
+                {
+                  copy_bufsiz = nbytes + 1;
+                  copy_bufptr = (char *) alloca (copy_bufsiz);
+                  nbytes = XmbLookupString (FRAME_XIC (f),
+                                            &event.xkey, copy_bufptr,
+                                            copy_bufsiz, &keysym,
+                                            &status_return);
+                }
+              /* Xutf8LookupString is a new but already deprecated interface.  -stef  */
+#if 0 && defined X_HAVE_UTF8_STRING
+              else if (status_return == XLookupKeySym)
+                {  /* Try again but with utf-8.  */
+                  coding_system = Qutf_8;
+                  nbytes = Xutf8LookupString (FRAME_XIC (f),
+                                              &event.xkey, copy_bufptr,
+                                              copy_bufsiz, &keysym,
+                                              &status_return);
+                  if (status_return == XBufferOverflow)
+                    {
+                      copy_bufsiz = nbytes + 1;
+                      copy_bufptr = (char *) alloca (copy_bufsiz);
+                      nbytes = Xutf8LookupString (FRAME_XIC (f),
+                                                  &event.xkey,
+                                                  copy_bufptr,
+                                                  copy_bufsiz, &keysym,
+                                                  &status_return);
+                    }
+                }
 #endif
 
-                 orig_keysym = keysym;
+              if (status_return == XLookupNone)
+                break;
+              else if (status_return == XLookupChars)
+                {
+                  keysym = NoSymbol;
+                  modifiers = 0;
+                }
+              else if (status_return != XLookupKeySym
+                       && status_return != XLookupBoth)
+                abort ();
+            }
+          else
+            nbytes = XLookupString (&event.xkey, copy_bufptr,
+                                    copy_bufsiz, &keysym,
+                                    &compose_status);
+#else
+          nbytes = XLookupString (&event.xkey, copy_bufptr,
+                                  copy_bufsiz, &keysym,
+                                  &compose_status);
+#endif
 
-                 if (numchars > 1)
-                   {
-                     if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
-                          || keysym == XK_Delete
+          orig_keysym = keysym;
+
+          if (numchars > 1)
+            {
+              Lisp_Object c;
+
+              /* First deal with keysyms which have defined
+                 translations to characters.  */
+              if (keysym >= 32 && keysym < 128)
+                /* Avoid explicitly decoding each ASCII character.  */
+                {
+                  bufp->kind = ASCII_KEYSTROKE_EVENT;
+                  bufp->code = keysym;
+                  XSETFRAME (bufp->frame_or_window, f);
+                  bufp->arg = Qnil;
+                  bufp->modifiers
+                    = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
+                                              modifiers);
+                  bufp->timestamp = event.xkey.time;
+                  bufp++;
+                  count++;
+                  numchars--;
+                }
+              /* Now non-ASCII.  */
+              else if (HASH_TABLE_P (Vx_keysym_table)
+                       && (NATNUMP (c = Fgethash (make_number (keysym),
+                                                  Vx_keysym_table,
+                                                  Qnil))))
+                {
+                  bufp->kind = (SINGLE_BYTE_CHAR_P (XFASTINT (c))
+                                ? ASCII_KEYSTROKE_EVENT
+                                : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
+                  bufp->code = XFASTINT (c);
+                  XSETFRAME (bufp->frame_or_window, f);
+                  bufp->arg = Qnil;
+                  bufp->modifiers
+                    = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
+                                              modifiers);
+                  bufp->timestamp = event.xkey.time;
+                  bufp++;
+                  count++;
+                  numchars--;
+                }
+              /* Random non-modifier sorts of keysyms.  */
+              else if (((keysym >= XK_BackSpace && keysym <= XK_Escape)
+                        || keysym == XK_Delete
 #ifdef XK_ISO_Left_Tab
-                          || (keysym >= XK_ISO_Left_Tab && keysym <= XK_ISO_Enter)
+                        || (keysym >= XK_ISO_Left_Tab
+                            && keysym <= XK_ISO_Enter)
 #endif
-                          || (keysym >= XK_Kanji && keysym <= XK_Eisu_toggle)
-                          || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
-                          || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
+                        || IsCursorKey (keysym) /* 0xff50 <= x < 0xff60 */
+                        || IsMiscFunctionKey (keysym) /* 0xff60 <= x < VARIES */
 #ifdef HPUX
-                          /* This recognizes the "extended function keys".
-                             It seems there's no cleaner way.
-                             Test IsModifierKey to avoid handling mode_switch
-                             incorrectly.  */
-                          || ((unsigned) (keysym) >= XK_Select
-                              && (unsigned)(keysym) < XK_KP_Space)
+                        /* This recognizes the "extended function
+                           keys".  It seems there's no cleaner way.
+                           Test IsModifierKey to avoid handling
+                           mode_switch incorrectly.  */
+                        || ((unsigned) (keysym) >= XK_Select
+                            && (unsigned)(keysym) < XK_KP_Space)
 #endif
 #ifdef XK_dead_circumflex
-                          || orig_keysym == XK_dead_circumflex
+                        || orig_keysym == XK_dead_circumflex
 #endif
 #ifdef XK_dead_grave
-                          || orig_keysym == XK_dead_grave
+                        || orig_keysym == XK_dead_grave
 #endif
 #ifdef XK_dead_tilde
-                          || orig_keysym == XK_dead_tilde
+                        || orig_keysym == XK_dead_tilde
 #endif
 #ifdef XK_dead_diaeresis
-                          || orig_keysym == XK_dead_diaeresis
+                        || orig_keysym == XK_dead_diaeresis
 #endif
 #ifdef XK_dead_macron
-                          || orig_keysym == XK_dead_macron
+                        || orig_keysym == XK_dead_macron
 #endif
 #ifdef XK_dead_degree
-                          || orig_keysym == XK_dead_degree
+                        || orig_keysym == XK_dead_degree
 #endif
 #ifdef XK_dead_acute
-                          || orig_keysym == XK_dead_acute
+                        || orig_keysym == XK_dead_acute
 #endif
 #ifdef XK_dead_cedilla
-                          || orig_keysym == XK_dead_cedilla
+                        || orig_keysym == XK_dead_cedilla
 #endif
 #ifdef XK_dead_breve
-                          || orig_keysym == XK_dead_breve
+                        || orig_keysym == XK_dead_breve
 #endif
 #ifdef XK_dead_ogonek
-                          || orig_keysym == XK_dead_ogonek
+                        || orig_keysym == XK_dead_ogonek
 #endif
 #ifdef XK_dead_caron
-                          || orig_keysym == XK_dead_caron
+                        || orig_keysym == XK_dead_caron
 #endif
 #ifdef XK_dead_doubleacute
-                          || orig_keysym == XK_dead_doubleacute
+                        || orig_keysym == XK_dead_doubleacute
 #endif
 #ifdef XK_dead_abovedot
-                          || orig_keysym == XK_dead_abovedot
+                        || orig_keysym == XK_dead_abovedot
 #endif
-                          || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
-                          || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
-                          /* Any "vendor-specific" key is ok.  */
-                          || (orig_keysym & (1 << 28))
-                          || (keysym != NoSymbol && nbytes == 0))
-                         && ! (IsModifierKey (orig_keysym)
+                        || IsKeypadKey (keysym) /* 0xff80 <= x < 0xffbe */
+                        || IsFunctionKey (keysym) /* 0xffbe <= x < 0xffe1 */
+                        /* Any "vendor-specific" key is ok.  */
+                        || (orig_keysym & (1 << 28))
+                        || (keysym != NoSymbol && nbytes == 0))
+                       && ! (IsModifierKey (orig_keysym)
 #ifndef HAVE_X11R5
 #ifdef XK_Mode_switch
-                               || ((unsigned)(orig_keysym) == XK_Mode_switch)
+                             || ((unsigned)(orig_keysym) == XK_Mode_switch)
 #endif
 #ifdef XK_Num_Lock
-                               || ((unsigned)(orig_keysym) == XK_Num_Lock)
+                             || ((unsigned)(orig_keysym) == XK_Num_Lock)
 #endif
 #endif /* not HAVE_X11R5 */
-                               /* The symbols from XK_ISO_Lock to
-                                  XK_ISO_Last_Group_Lock doesn't have real
-                                  modifiers but should be treated similarly
-                                  to Mode_switch by Emacs. */
+                             /* The symbols from XK_ISO_Lock
+                                to XK_ISO_Last_Group_Lock
+                                don't have real modifiers but
+                                should be treated similarly to
+                                Mode_switch by Emacs. */
 #if defined XK_ISO_Lock && defined XK_ISO_Last_Group_Lock
-                               || ((unsigned)(orig_keysym) >=  XK_ISO_Lock
-                                   && (unsigned)(orig_keysym) <= XK_ISO_Last_Group_Lock)
+                             || ((unsigned)(orig_keysym)
+                                 >=  XK_ISO_Lock
+                                 && (unsigned)(orig_keysym)
+                                 <= XK_ISO_Last_Group_Lock)
 #endif
-                               ))
-                       {
-                         if (temp_index == sizeof temp_buffer / sizeof (short))
-                           temp_index = 0;
-                         temp_buffer[temp_index++] = keysym;
-                         bufp->kind = non_ascii_keystroke;
-                         bufp->code = keysym;
-                         XSETFRAME (bufp->frame_or_window, f);
-                         bufp->arg = Qnil;
-                         bufp->modifiers
-                           = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
-                                                     modifiers);
-                         bufp->timestamp = event.xkey.time;
-                         bufp++;
-                         count++;
-                         numchars--;
-                       }
-                     else if (numchars > nbytes)
-                       {
-                         register int i;
-                         register int c;
-                         int nchars, len;
-
-                         for (i = 0; i < nbytes; i++)
-                           {
-                             if (temp_index == (sizeof temp_buffer
-                                                / sizeof (short)))
-                               temp_index = 0;
-                             temp_buffer[temp_index++] = copy_bufptr[i];
-                           }
-
-                         if (/* If the event is not from XIM, */
-                             event.xkey.keycode != 0
-                             /* or the current locale doesn't request
-                                decoding of the intup data, ... */
-                             || coding.type == coding_type_raw_text
-                             || coding.type == coding_type_no_conversion)
-                           {
-                             /* ... we can use the input data as is.  */
-                             nchars = nbytes;
-                           }
-                         else
-                           { 
-                             /* We have to decode the input data.  */
-                             int require;
-                             unsigned char *p;
-
-                             require = decoding_buffer_size (&coding, nbytes);
-                             p = (unsigned char *) alloca (require);
-                             coding.mode |= CODING_MODE_LAST_BLOCK;
-                             decode_coding (&coding, copy_bufptr, p,
-                                            nbytes, require);
-                             nbytes = coding.produced;
-                             nchars = coding.produced_char;
-                             copy_bufptr = p;
-                           }
-
-                         /* Convert the input data to a sequence of
-                            character events.  */
-                         for (i = 0; i < nbytes; i += len)
-                           {
-                             if (nchars == nbytes)
-                               c = copy_bufptr[i], len = 1;
-                             else
-                               c = STRING_CHAR_AND_LENGTH (copy_bufptr + i,
-                                                           nbytes - i, len);
-                             
-                             bufp->kind = (SINGLE_BYTE_CHAR_P (c)
-                                           ? ascii_keystroke
-                                           : multibyte_char_keystroke);
-                             bufp->code = c;
-                             XSETFRAME (bufp->frame_or_window, f);
-                             bufp->arg = Qnil;
-                             bufp->modifiers
-                               = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
-                                                         modifiers);
-                             bufp->timestamp = event.xkey.time;
-                             bufp++;
-                           }
-
-                         count += nchars;
-                         numchars -= nchars;
-
-                         if (keysym == NoSymbol)
-                           break;
-                       }
-                     else
-                       abort ();
-                   }
-                 else
-                   abort ();
-               }
+                             ))
+                {
+                  if (temp_index == sizeof temp_buffer / sizeof (short))
+                    temp_index = 0;
+                  temp_buffer[temp_index++] = keysym;
+                  /* make_lispy_event will convert this to a symbolic
+                     key.  */
+                  bufp->kind = NON_ASCII_KEYSTROKE_EVENT;
+                  bufp->code = keysym;
+                  XSETFRAME (bufp->frame_or_window, f);
+                  bufp->arg = Qnil;
+                  bufp->modifiers
+                    = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
+                                              modifiers);
+                  bufp->timestamp = event.xkey.time;
+                  bufp++;
+                  count++;
+                  numchars--;
+                }
+              else if (numchars > nbytes)
+                {      /* Raw bytes, not keysym.  */
+                  register int i;
+                  register int c;
+                  int nchars, len;
+
+                  /* The input should be decoded with `coding_system'
+                     which depends on which X*LookupString function
+                     we used just above and the locale.  */
+                  setup_coding_system (coding_system, &coding);
+                  coding.src_multibyte = 0;
+                  coding.dst_multibyte = 1;
+                  /* The input is converted to events, thus we can't
+                     handle composition.  Anyway, there's no XIM that
+                     gives us composition information.  */
+                  coding.composing = COMPOSITION_DISABLED;
+
+                  for (i = 0; i < nbytes; i++)
+                    {
+                      if (temp_index == (sizeof temp_buffer
+                                         / sizeof (short)))
+                        temp_index = 0;
+                      temp_buffer[temp_index++] = copy_bufptr[i];
+                    }
+
+                  {
+                    /* Decode the input data.  */
+                    int require;
+                    unsigned char *p;
+
+                    require = decoding_buffer_size (&coding, nbytes);
+                    p = (unsigned char *) alloca (require);
+                    coding.mode |= CODING_MODE_LAST_BLOCK;
+                    /* We explicitely disable composition
+                       handling because key data should
+                       not contain any composition
+                       sequence.  */
+                    coding.composing = COMPOSITION_DISABLED;
+                    decode_coding (&coding, copy_bufptr, p,
+                                   nbytes, require);
+                    nbytes = coding.produced;
+                    nchars = coding.produced_char;
+                    copy_bufptr = p;
+                  }
+
+                  /* Convert the input data to a sequence of
+                     character events.  */
+                  for (i = 0; i < nbytes; i += len)
+                    {
+                      if (nchars == nbytes)
+                        c = copy_bufptr[i], len = 1;
+                      else
+                        c = STRING_CHAR_AND_LENGTH (copy_bufptr + i,
+                                                    nbytes - i, len);
+
+                      bufp->kind = (SINGLE_BYTE_CHAR_P (c)
+                                    ? ASCII_KEYSTROKE_EVENT
+                                    : MULTIBYTE_CHAR_KEYSTROKE_EVENT);
+                      bufp->code = c;
+                      XSETFRAME (bufp->frame_or_window, f);
+                      bufp->arg = Qnil;
+                      bufp->modifiers
+                        = x_x_to_emacs_modifiers (FRAME_X_DISPLAY_INFO (f),
+                                                  modifiers);
+                      bufp->timestamp = event.xkey.time;
+                      bufp++;
+                    }
+
+                  count += nchars;
+                  numchars -= nchars;
+
+                  if (keysym == NoSymbol)
+                    break;
+                }
+              else
+                abort ();
+            }
+          else
+            abort ();
+        }
 #ifdef HAVE_X_I18N
-             /* Don't dispatch this event since XtDispatchEvent calls
-                XFilterEvent, and two calls in a row may freeze the
-                client.  */
-             break;
+      /* Don't dispatch this event since XtDispatchEvent calls
+         XFilterEvent, and two calls in a row may freeze the
+         client.  */
+      break;
 #else
-             goto OTHER;
+      goto OTHER;
 #endif
 
-           case KeyRelease:
+    case KeyRelease:
 #ifdef HAVE_X_I18N
-             /* Don't dispatch this event since XtDispatchEvent calls
-                XFilterEvent, and two calls in a row may freeze the
-                client.  */
-             break;
+      /* Don't dispatch this event since XtDispatchEvent calls
+         XFilterEvent, and two calls in a row may freeze the
+         client.  */
+      break;
 #else
-             goto OTHER;
+      goto OTHER;
 #endif
 
-             /* Here's a possible interpretation of the whole
-                FocusIn-EnterNotify FocusOut-LeaveNotify mess.  If
-                you get a FocusIn event, you have to get a FocusOut
-                event before you relinquish the focus.  If you
-                haven't received a FocusIn event, then a mere
-                LeaveNotify is enough to free you.  */
+    case EnterNotify:
+      {
+        int n;
 
-           case EnterNotify:
-             {
-               f = x_any_window_to_frame (dpyinfo, event.xcrossing.window);
+        n = x_detect_focus_change (dpyinfo, &event, bufp, numchars);
+        if (n > 0)
+          {
+            bufp += n, count += n, numchars -= n;
+          }
+
+        f = x_any_window_to_frame (dpyinfo, event.xcrossing.window);
 
 #if 0
-               if (event.xcrossing.focus)
-                 {
-                   /* Avoid nasty pop/raise loops.  */
-                   if (f && (!(f->auto_raise)
-                             || !(f->auto_lower)
-                             || (event.xcrossing.time - enter_timestamp) > 500))
-                     {
-                       x_new_focus_frame (dpyinfo, f);
-                       enter_timestamp = event.xcrossing.time;
-                     }
-                 }
-               else if (f == dpyinfo->x_focus_frame)
-                 x_new_focus_frame (dpyinfo, 0);
+        if (event.xcrossing.focus)
+          {
+            /* Avoid nasty pop/raise loops.  */
+            if (f && (!(f->auto_raise)
+                      || !(f->auto_lower)
+                      || (event.xcrossing.time - enter_timestamp) > 500))
+              {
+                x_new_focus_frame (dpyinfo, f);
+                enter_timestamp = event.xcrossing.time;
+              }
+          }
+        else if (f == dpyinfo->x_focus_frame)
+          x_new_focus_frame (dpyinfo, 0);
 #endif
 
-               /* EnterNotify counts as mouse movement,
-                  so update things that depend on mouse position.  */
-               if (f && !f->output_data.x->hourglass_p)
-                 note_mouse_movement (f, &event.xmotion);
-               goto OTHER;
-             }
+        /* EnterNotify counts as mouse movement,
+           so update things that depend on mouse position.  */
+        if (f && !f->output_data.x->hourglass_p)
+          note_mouse_movement (f, &event.xmotion);
+        goto OTHER;
+      }
 
-           case FocusIn:
-             f = x_any_window_to_frame (dpyinfo, event.xfocus.window);
-             if (event.xfocus.detail != NotifyPointer)
-               dpyinfo->x_focus_event_frame = f;
-             if (f)
-               {
-                 x_new_focus_frame (dpyinfo, f);
+    case FocusIn:
+      {
+        int n;
 
-                 /* Don't stop displaying the initial startup message
-                    for a switch-frame event we don't need.  */
-                 if (GC_NILP (Vterminal_frame)
-                     && GC_CONSP (Vframe_list)
-                     && !GC_NILP (XCDR (Vframe_list)))
-                   {
-                     bufp->kind = FOCUS_IN_EVENT;
-                     XSETFRAME (bufp->frame_or_window, f);
-                     bufp->arg = Qnil;
-                     ++bufp, ++count, --numchars;
-                   }
-               }
+        n = x_detect_focus_change (dpyinfo, &event, bufp, numchars);
+        if (n > 0)
+          {
+            bufp += n, count += n, numchars -= n;
+          }
+      }
 
-#ifdef HAVE_X_I18N
-             if (f && FRAME_XIC (f))
-               XSetICFocus (FRAME_XIC (f));
-#endif
+      goto OTHER;
 
-             goto OTHER;
+    case LeaveNotify:
+      {
+        int n;
 
-           case LeaveNotify:
-             f = x_top_window_to_frame (dpyinfo, event.xcrossing.window);
-             if (f)
-               {
-                 if (f == dpyinfo->mouse_face_mouse_frame)
-                   {
-                     /* If we move outside the frame, then we're
-                        certainly no longer on any text in the frame.  */
-                     clear_mouse_face (dpyinfo);
-                     dpyinfo->mouse_face_mouse_frame = 0;
-                   }
+        n = x_detect_focus_change (dpyinfo, &event, bufp, numchars);
+        if (n > 0)
+          {
+            bufp += n, count += n, numchars -= n;
+          }
+      }
 
-                 /* Generate a nil HELP_EVENT to cancel a help-echo.
-                    Do it only if there's something to cancel.
-                    Otherwise, the startup message is cleared when
-                    the mouse leaves the frame.  */
-                 if (any_help_event_p)
-                   {
-                     Lisp_Object frame;
-                     int n;
-
-                     XSETFRAME (frame, f);
-                     help_echo = Qnil;
-                     n = gen_help_event (bufp, numchars,
-                                         Qnil, frame, Qnil, Qnil, 0);
-                     bufp += n, count += n, numchars -= n;
-                   }
+      f = x_top_window_to_frame (dpyinfo, event.xcrossing.window);
+      if (f)
+        {
+          if (f == dpyinfo->mouse_face_mouse_frame)
+            {
+              /* If we move outside the frame, then we're
+                 certainly no longer on any text in the frame.  */
+              clear_mouse_face (dpyinfo);
+              dpyinfo->mouse_face_mouse_frame = 0;
+            }
+
+          /* Generate a nil HELP_EVENT to cancel a help-echo.
+             Do it only if there's something to cancel.
+             Otherwise, the startup message is cleared when
+             the mouse leaves the frame.  */
+          if (any_help_event_p)
+            {
+              Lisp_Object frame;
+              int n;
+
+              XSETFRAME (frame, f);
+              help_echo = Qnil;
+              n = gen_help_event (bufp, numchars,
+                                  Qnil, frame, Qnil, Qnil, 0);
+              bufp += n, count += n, numchars -= n;
+            }
 
-#if 0
-                 if (event.xcrossing.focus)
-                   x_mouse_leave (dpyinfo);
-                 else
-                   {
-                     if (f == dpyinfo->x_focus_event_frame)
-                       dpyinfo->x_focus_event_frame = 0;
-                     if (f == dpyinfo->x_focus_frame)
-                       x_new_focus_frame (dpyinfo, 0);
-                   }
+        }
+      goto OTHER;
+
+    case FocusOut:
+      {
+        int n;
+
+        n = x_detect_focus_change (dpyinfo, &event, bufp, numchars);
+        if (n > 0)
+          {
+            bufp += n, count += n, numchars -= n;
+          }
+      }
+
+      goto OTHER;
+
+    case MotionNotify:
+      {
+        previous_help_echo = help_echo;
+        help_echo = help_echo_object = help_echo_window = Qnil;
+        help_echo_pos = -1;
+
+        if (dpyinfo->grabbed && last_mouse_frame
+            && FRAME_LIVE_P (last_mouse_frame))
+          f = last_mouse_frame;
+        else
+          f = x_window_to_frame (dpyinfo, event.xmotion.window);
+
+        if (dpyinfo->mouse_face_hidden)
+          {
+            dpyinfo->mouse_face_hidden = 0;
+            clear_mouse_face (dpyinfo);
+          }
+
+        if (f)
+          {
+
+            /* Generate SELECT_WINDOW_EVENTs when needed.  */
+            if (mouse_autoselect_window)
+              {
+                Lisp_Object window;
+                int area;
+
+                window = window_from_coordinates (f,
+                                                  event.xmotion.x, event.xmotion.y,
+                                                  &area, 0);
+
+                /* Window will be selected only when it is not selected now and
+                   last mouse movement event was not in it.  Minibuffer window
+                   will be selected iff it is active.  */
+                if (WINDOWP(window)
+                    && !EQ (window, last_window)
+                    && !EQ (window, selected_window)
+                    && numchars > 0)
+                  {
+                    bufp->kind = SELECT_WINDOW_EVENT;
+                    bufp->frame_or_window = window;
+                    bufp->arg = Qnil;
+                    ++bufp, ++count, --numchars;
+                  }
+
+                last_window=window;
+              }
+            note_mouse_movement (f, &event.xmotion);
+          }
+        else
+          {
+#ifndef USE_TOOLKIT_SCROLL_BARS
+            struct scroll_bar *bar
+              = x_window_to_scroll_bar (event.xmotion.window);
+
+            if (bar)
+              x_scroll_bar_note_movement (bar, &event);
+#endif /* USE_TOOLKIT_SCROLL_BARS */
+
+            /* If we move outside the frame, then we're
+               certainly no longer on any text in the frame.  */
+            clear_mouse_face (dpyinfo);
+          }
+
+        /* If the contents of the global variable help_echo
+           has changed, generate a HELP_EVENT.  */
+        if (!NILP (help_echo)
+            || !NILP (previous_help_echo))
+          {
+            Lisp_Object frame;
+            int n;
+
+            if (f)
+              XSETFRAME (frame, f);
+            else
+              frame = Qnil;
+
+            any_help_event_p = 1;
+            n = gen_help_event (bufp, numchars, help_echo, frame,
+                                help_echo_window, help_echo_object,
+                                help_echo_pos);
+            bufp += n, count += n, numchars -= n;
+          }
+
+        goto OTHER;
+      }
+
+    case ConfigureNotify:
+      f = x_top_window_to_frame (dpyinfo, event.xconfigure.window);
+      if (f)
+        {
+#ifndef USE_X_TOOLKIT
+#ifdef USE_GTK
+          xg_resize_widgets (f, event.xconfigure.width,
+                             event.xconfigure.height);
+#else /* not USE_GTK */
+          /* If there is a pending resize for fullscreen, don't
+             do this one, the right one will come later.
+             The toolkit version doesn't seem to need this, but we
+             need to reset it below.  */
+          int dont_resize =
+            ((f->output_data.x->want_fullscreen & FULLSCREEN_WAIT)
+             && FRAME_NEW_WIDTH (f) != 0);
+          int rows = PIXEL_TO_CHAR_HEIGHT (f, event.xconfigure.height);
+          int columns = PIXEL_TO_CHAR_WIDTH (f, event.xconfigure.width);
+          if (dont_resize)
+            goto OTHER;
+
+          /* In the toolkit version, change_frame_size
+             is called by the code that handles resizing
+             of the EmacsFrame widget.  */
+
+          /* Even if the number of character rows and columns has
+             not changed, the font size may have changed, so we need
+             to check the pixel dimensions as well.  */
+          if (columns != f->width
+              || rows != f->height
+              || event.xconfigure.width != f->output_data.x->pixel_width
+              || event.xconfigure.height != f->output_data.x->pixel_height)
+            {
+              change_frame_size (f, rows, columns, 0, 1, 0);
+              SET_FRAME_GARBAGED (f);
+              cancel_mouse_face (f);
+            }
+#endif /* not USE_GTK */
 #endif
-               }
-             goto OTHER;
 
-           case FocusOut:
-             f = x_any_window_to_frame (dpyinfo, event.xfocus.window);
-             if (event.xfocus.detail != NotifyPointer
-                 && f == dpyinfo->x_focus_event_frame)
-               dpyinfo->x_focus_event_frame = 0;
-             if (f && f == dpyinfo->x_focus_frame)
-               x_new_focus_frame (dpyinfo, 0);
+          f->output_data.x->pixel_width = event.xconfigure.width;
+          f->output_data.x->pixel_height = event.xconfigure.height;
 
+#ifdef USE_GTK
+          /* GTK creates windows but doesn't map them.
+             Only get real positions and check fullscreen when mapped. */
+          if (FRAME_GTK_OUTER_WIDGET (f)
+              && GTK_WIDGET_MAPPED (FRAME_GTK_OUTER_WIDGET (f)))
+            {
+#endif
+          /* What we have now is the position of Emacs's own window.
+             Convert that to the position of the window manager window.  */
+          x_real_positions (f, &f->output_data.x->left_pos,
+                            &f->output_data.x->top_pos);
+
+          x_check_fullscreen_move (f);
+          if (f->output_data.x->want_fullscreen & FULLSCREEN_WAIT)
+            f->output_data.x->want_fullscreen &=
+              ~(FULLSCREEN_WAIT|FULLSCREEN_BOTH);
+#ifdef USE_GTK
+            }
+#endif
 #ifdef HAVE_X_I18N
-             if (f && FRAME_XIC (f))
-               XUnsetICFocus (FRAME_XIC (f));
+          if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
+            xic_set_statusarea (f);
 #endif
 
-             goto OTHER;
+          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);
+            }
+        }
+      goto OTHER;
 
-           case MotionNotify:
-             {
-               previous_help_echo = help_echo;
-               help_echo = help_echo_object = help_echo_window = Qnil;
-               help_echo_pos = -1;
-               
-               if (dpyinfo->grabbed && last_mouse_frame
-                   && FRAME_LIVE_P (last_mouse_frame))
-                 f = last_mouse_frame;
-               else
-                 f = x_window_to_frame (dpyinfo, event.xmotion.window);
-
-               if (dpyinfo->mouse_face_hidden)
-                 {
-                   dpyinfo->mouse_face_hidden = 0;
-                   clear_mouse_face (dpyinfo);
-                 }
+    case ButtonRelease:
+    case ButtonPress:
+      {
+        /* If we decide we want to generate an event to be seen
+           by the rest of Emacs, we put it here.  */
+        struct input_event emacs_event;
+        int tool_bar_p = 0;
+
+        emacs_event.kind = NO_EVENT;
+        bzero (&compose_status, sizeof (compose_status));
+
+        if (dpyinfo->grabbed
+            && last_mouse_frame
+            && FRAME_LIVE_P (last_mouse_frame))
+          f = last_mouse_frame;
+        else
+          f = x_window_to_frame (dpyinfo, event.xbutton.window);
+
+        if (f)
+          {
+            /* Is this in the tool-bar?  */
+            if (WINDOWP (f->tool_bar_window)
+                && XFASTINT (XWINDOW (f->tool_bar_window)->height))
+              {
+                Lisp_Object window;
+                int p, x, y;
+
+                x = event.xbutton.x;
+                y = event.xbutton.y;
+
+                /* Set x and y.  */
+                window = window_from_coordinates (f, x, y, &p, 1);
+                if (EQ (window, f->tool_bar_window))
+                  {
+                    x_handle_tool_bar_click (f, &event.xbutton);
+                    tool_bar_p = 1;
+                  }
+              }
+
+            if (!tool_bar_p)
+              if (!dpyinfo->x_focus_frame
+                  || f == dpyinfo->x_focus_frame)
+                {
+#if defined (USE_X_TOOLKIT) || defined (USE_GTK)
+                  if (! popup_activated ())
+#endif
+                    construct_mouse_click (&emacs_event, &event, f);
+                }
+          }
+        else
+          {
+            struct scroll_bar *bar
+              = x_window_to_scroll_bar (event.xbutton.window);
 
-               if (f)
-                 {
+#ifdef USE_TOOLKIT_SCROLL_BARS
+            /* Make the "Ctrl-Mouse-2 splits window" work for toolkit
+               scroll bars.  */
+            if (bar && event.xbutton.state & ControlMask)
+              {
+                x_scroll_bar_handle_click (bar, &event, &emacs_event);
+                *finish = X_EVENT_DROP;
+              }
+#else /* not USE_TOOLKIT_SCROLL_BARS */
+            if (bar)
+              x_scroll_bar_handle_click (bar, &event, &emacs_event);
+#endif /* not USE_TOOLKIT_SCROLL_BARS */
+          }
+
+        if (event.type == ButtonPress)
+          {
+            dpyinfo->grabbed |= (1 << event.xbutton.button);
+            last_mouse_frame = f;
+            /* Ignore any mouse motion that happened
+               before this event; any subsequent mouse-movement
+               Emacs events should reflect only motion after
+               the ButtonPress.  */
+            if (f != 0)
+              f->mouse_moved = 0;
+
+            if (!tool_bar_p)
+              last_tool_bar_item = -1;
+          }
+        else
+          dpyinfo->grabbed &= ~(1 << event.xbutton.button);
+
+        if (numchars >= 1 && emacs_event.kind != NO_EVENT)
+          {
+            bcopy (&emacs_event, bufp, sizeof (struct input_event));
+            bufp++;
+            count++;
+            numchars--;
+          }
+
+#if defined (USE_X_TOOLKIT) || defined (USE_GTK)
+        f = x_menubar_window_to_frame (dpyinfo, event.xbutton.window);
+        /* For a down-event in the menu bar,
+           don't pass it to Xt right now.
+           Instead, save it away
+           and we will pass it to Xt from kbd_buffer_get_event.
+           That way, we can run some Lisp code first.  */
+        if (
+#ifdef USE_GTK
+            ! popup_activated ()
+            &&
+#endif
+            f && event.type == ButtonPress
+            /* Verify the event is really within the menu bar
+               and not just sent to it due to grabbing.  */
+            && event.xbutton.x >= 0
+            && event.xbutton.x < f->output_data.x->pixel_width
+            && event.xbutton.y >= 0
+            && event.xbutton.y < f->output_data.x->menubar_height
+            && event.xbutton.same_screen)
+          {
+            SET_SAVED_BUTTON_EVENT;
+            XSETFRAME (last_mouse_press_frame, f);
+#ifdef USE_GTK
+            *finish = X_EVENT_DROP;
+#endif
+          }
+        else if (event.type == ButtonPress)
+          {
+            last_mouse_press_frame = Qnil;
+            goto OTHER;
+          }
 
-                   /* Generate SELECT_WINDOW_EVENTs when needed.  */
-                   if (mouse_autoselect_window)
-                     {
-                       Lisp_Object window;
-                       int area;
-
-                       window = window_from_coordinates (f,
-                                                         event.xmotion.x, event.xmotion.y,
-                                                         &area, 0);
-
-                       /* Window will be selected only when it is not selected now and
-                          last mouse movement event was not in it.  Minibuffer window
-                          will be selected iff it is active.  */
-                       if (WINDOWP(window)
-                           && !EQ (window, last_window)
-                           && !EQ (window, selected_window)
-                           && numchars > 0)
-                         {
-                           bufp->kind = SELECT_WINDOW_EVENT;
-                           bufp->frame_or_window = window;
-                           bufp->arg = Qnil;
-                           ++bufp, ++count, --numchars;
-                         }
+#ifdef USE_MOTIF /* This should do not harm for Lucid,
+                   but I am trying to be cautious.  */
+        else if (event.type == ButtonRelease)
+          {
+            if (!NILP (last_mouse_press_frame))
+              {
+                f = XFRAME (last_mouse_press_frame);
+                if (f->output_data.x)
+                  SET_SAVED_BUTTON_EVENT;
+              }
+            else
+              goto OTHER;
+          }
+#endif /* USE_MOTIF */
+        else
+          goto OTHER;
+#endif /* USE_X_TOOLKIT || USE_GTK */
+      }
+      break;
 
-                       last_window=window;
-                     }
-                   note_mouse_movement (f, &event.xmotion);
-                 }
-               else
-                 {
-#ifndef USE_TOOLKIT_SCROLL_BARS
-                   struct scroll_bar *bar
-                     = x_window_to_scroll_bar (event.xmotion.window);
+    case CirculateNotify:
+      goto OTHER;
 
-                   if (bar)
-                     x_scroll_bar_note_movement (bar, &event);
-#endif /* USE_TOOLKIT_SCROLL_BARS */
+    case CirculateRequest:
+      goto OTHER;
 
-                   /* If we move outside the frame, then we're
-                      certainly no longer on any text in the frame.  */
-                   clear_mouse_face (dpyinfo);
-                 }
+    case VisibilityNotify:
+      goto OTHER;
 
-               /* If the contents of the global variable help_echo
-                  has changed, generate a HELP_EVENT.  */
-               if (!NILP (help_echo)
-                   || !NILP (previous_help_echo))
-                 {
-                   Lisp_Object frame;
-                   int n;
-
-                   if (f)
-                     XSETFRAME (frame, f);
-                   else
-                     frame = Qnil;
-
-                   any_help_event_p = 1;
-                   n = gen_help_event (bufp, numchars, help_echo, frame,
-                                       help_echo_window, help_echo_object,
-                                       help_echo_pos);
-                   bufp += n, count += n, numchars -= n;
-                 }
-               
-               goto OTHER;
-             }
+    case MappingNotify:
+      /* Someone has changed the keyboard mapping - update the
+         local cache.  */
+      switch (event.xmapping.request)
+        {
+        case MappingModifier:
+          x_find_modifier_meanings (dpyinfo);
+          /* This is meant to fall through.  */
+        case MappingKeyboard:
+          XRefreshKeyboardMapping (&event.xmapping);
+        }
+      goto OTHER;
 
-           case ConfigureNotify:
-             f = x_top_window_to_frame (dpyinfo, event.xconfigure.window);
-             if (f)
-               {
-#ifndef USE_X_TOOLKIT
-                  /* If there is a pending resize for fullscreen, don't
-                     do this one, the right one will come later.
-                    The toolkit version doesn't seem to need this, but we
-                    need to reset it below.  */
-                  int dont_resize =
-                    ((f->output_data.x->want_fullscreen & FULLSCREEN_WAIT)
-                     && FRAME_NEW_WIDTH (f) != 0);
-                 int rows = PIXEL_TO_CHAR_HEIGHT (f, event.xconfigure.height);
-                 int columns = PIXEL_TO_CHAR_WIDTH (f, event.xconfigure.width);
-                  if (dont_resize)
-                    goto OTHER;
-                 
-                 /* In the toolkit version, change_frame_size
-                    is called by the code that handles resizing
-                    of the EmacsFrame widget.  */
-
-                 /* Even if the number of character rows and columns has
-                    not changed, the font size may have changed, so we need
-                    to check the pixel dimensions as well.  */
-                 if (columns != f->width
-                     || rows != f->height
-                     || event.xconfigure.width != f->output_data.x->pixel_width
-                     || event.xconfigure.height != f->output_data.x->pixel_height)
-                   {
-                     change_frame_size (f, rows, columns, 0, 1, 0);
-                     SET_FRAME_GARBAGED (f);
-                     cancel_mouse_face (f);
-                   }
-#endif
+    default:
+    OTHER:
+#ifdef USE_X_TOOLKIT
+    BLOCK_INPUT;
+    if (*finish != X_EVENT_DROP)
+      XtDispatchEvent (&event);
+    UNBLOCK_INPUT;
+#endif /* USE_X_TOOLKIT */
+    break;
+    }
 
-                 f->output_data.x->pixel_width = event.xconfigure.width;
-                 f->output_data.x->pixel_height = event.xconfigure.height;
+  goto ret;
 
-                 /* What we have now is the position of Emacs's own window.
-                    Convert that to the position of the window manager window.  */
-                 x_real_positions (f, &f->output_data.x->left_pos,
-                                   &f->output_data.x->top_pos);
+ out:
+  *finish = X_EVENT_GOTO_OUT;
 
-                  x_check_fullscreen_move(f);
-                  if (f->output_data.x->want_fullscreen & FULLSCREEN_WAIT)
-                    f->output_data.x->want_fullscreen &=
-                      ~(FULLSCREEN_WAIT|FULLSCREEN_BOTH);
-#ifdef HAVE_X_I18N
-                 if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
-                   xic_set_statusarea (f);
-#endif
+ ret:
+  *bufp_r = bufp;
+  *numcharsp = numchars;
+  *eventp = event;
 
-                 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 /* USE_MOTIF */
-               }
-             goto OTHER;
+  return count;
+}
 
-           case ButtonPress:
-           case ButtonRelease:
-             {
-               /* If we decide we want to generate an event to be seen
-                  by the rest of Emacs, we put it here.  */
-               struct input_event emacs_event;
-               int tool_bar_p = 0;
-               
-               emacs_event.kind = no_event;
-               bzero (&compose_status, sizeof (compose_status));
-
-               if (dpyinfo->grabbed
-                   && last_mouse_frame
-                   && FRAME_LIVE_P (last_mouse_frame))
-                 f = last_mouse_frame;
-               else
-                 f = x_window_to_frame (dpyinfo, event.xbutton.window);
-
-               if (f)
-                 {
-                   /* Is this in the tool-bar?  */
-                   if (WINDOWP (f->tool_bar_window)
-                       && XFASTINT (XWINDOW (f->tool_bar_window)->height))
-                     {
-                       Lisp_Object window;
-                       int p, x, y;
 
-                       x = event.xbutton.x;
-                       y = event.xbutton.y;
+/* Handles the XEvent EVENT on display DISPLAY.
+   This is used for event loops outside the normal event handling,
+   i.e. looping while a popup menu or a dialog is posted.
+
+   Returns the value handle_one_xevent sets in the finish argument.  */
+int
+x_dispatch_event (event, display)
+     XEvent *event;
+     Display *display;
+{
+  struct x_display_info *dpyinfo;
+  struct input_event bufp[10];
+  struct input_event *bufpp = bufp;
+  int numchars = 10;
+  int finish = X_EVENT_NORMAL;
+
+  for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
+    if (dpyinfo->display == display)
+      break;
+
+  if (dpyinfo)
+    {
+      int i, events;
+      events = handle_one_xevent (dpyinfo,
+                                  event,
+                                  &bufpp,
+                                  &numchars,
+                                  &finish);
+      for (i = 0; i < events; ++i)
+        kbd_buffer_store_event (&bufp[i]);
+    }
+
+  return finish;
+}
+
+
+/* Read events coming from the X server.
+   This routine is called by the SIGIO handler.
+   We return as soon as there are no more events to be read.
+
+   Events representing keys are stored in buffer BUFP,
+   which can hold up to NUMCHARS characters.
+   We return the number of characters stored into the buffer,
+   thus pretending to be `read'.
+
+   EXPECTED is nonzero if the caller knows input is available.  */
+
+static int
+XTread_socket (sd, bufp, numchars, expected)
+     register int sd;
+     /* register */ struct input_event *bufp;
+     /* register */ int numchars;
+     int expected;
+{
+  int count = 0;
+  int nbytes = 0;
+  XEvent event;
+  int event_found = 0;
+  struct x_display_info *dpyinfo;
+
+  if (interrupt_input_blocked)
+    {
+      interrupt_input_pending = 1;
+      return -1;
+    }
+
+  interrupt_input_pending = 0;
+  BLOCK_INPUT;
+
+  /* So people can tell when we have read the available input.  */
+  input_signal_count++;
+
+  if (numchars <= 0)
+    abort ();                  /* Don't think this happens.  */
+
+  ++handling_signal;
+
+  /* Find the display we are supposed to read input for.
+     It's the one communicating on descriptor SD.  */
+  for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
+    {
+#if 0 /* This ought to be unnecessary; let's verify it.  */
+#ifdef FIOSNBIO
+      /* If available, Xlib uses FIOSNBIO to make the socket
+        non-blocking, and then looks for EWOULDBLOCK.  If O_NDELAY is set,
+        FIOSNBIO is ignored, and instead of signaling EWOULDBLOCK,
+        a read returns 0, which Xlib interprets as equivalent to EPIPE.  */
+      fcntl (dpyinfo->connection, F_SETFL, 0);
+#endif /* ! defined (FIOSNBIO) */
+#endif
+
+#if 0 /* This code can't be made to work, with multiple displays,
+        and appears not to be used on any system any more.
+        Also keyboard.c doesn't turn O_NDELAY on and off
+        for X connections.  */
+#ifndef SIGIO
+#ifndef HAVE_SELECT
+      if (! (fcntl (dpyinfo->connection, F_GETFL, 0) & O_NDELAY))
+       {
+         extern int read_alarm_should_throw;
+         read_alarm_should_throw = 1;
+         XPeekEvent (dpyinfo->display, &event);
+         read_alarm_should_throw = 0;
+       }
+#endif /* HAVE_SELECT */
+#endif /* SIGIO */
+#endif
+
+      /* For debugging, this gives a way to fake an I/O error.  */
+      if (dpyinfo == XTread_socket_fake_io_error)
+       {
+         XTread_socket_fake_io_error = 0;
+         x_io_error_quitter (dpyinfo->display);
+       }
 
-                       /* Set x and y.  */
-                       window = window_from_coordinates (f, x, y, &p, 1);
-                       if (EQ (window, f->tool_bar_window))
-                         {
-                           x_handle_tool_bar_click (f, &event.xbutton);
-                           tool_bar_p = 1;
-                         }
-                     }
+#ifdef HAVE_X_SM
+      BLOCK_INPUT;
+      count += x_session_check_input (bufp, &numchars);
+      UNBLOCK_INPUT;
+#endif
 
-                   if (!tool_bar_p)
-                     if (!dpyinfo->x_focus_frame
-                         || f == dpyinfo->x_focus_frame)
-                       construct_mouse_click (&emacs_event, &event, f);
-                 }
-               else
-                 {
-#ifndef USE_TOOLKIT_SCROLL_BARS
-                   struct scroll_bar *bar
-                     = x_window_to_scroll_bar (event.xbutton.window);
+#ifdef USE_GTK
+      /* For GTK we must use the GTK event loop.  But XEvents gets passed
+         to our filter function above, and then to the big event switch.
+         We use a bunch of globals to communicate with our filter function,
+         that is kind of ugly, but it works. */
+      current_dpyinfo = dpyinfo;
 
-                   if (bar)
-                     x_scroll_bar_handle_click (bar, &event, &emacs_event);
-#endif /* not USE_TOOLKIT_SCROLL_BARS */
-                 }
+      while (gtk_events_pending ())
+        {
+          static int nr = 0;
+          current_count = count;
+          current_numcharsp = &numchars;
+          current_bufp = &bufp;
 
-               if (event.type == ButtonPress)
-                 {
-                   dpyinfo->grabbed |= (1 << event.xbutton.button);
-                   last_mouse_frame = f;
-                   /* Ignore any mouse motion that happened
-                      before this event; any subsequent mouse-movement
-                      Emacs events should reflect only motion after
-                      the ButtonPress.  */
-                   if (f != 0)
-                     f->mouse_moved = 0;
-                   
-                   if (!tool_bar_p)
-                     last_tool_bar_item = -1;
-                 }
-               else
-                 {
-                   dpyinfo->grabbed &= ~(1 << event.xbutton.button);
-                 }
+          gtk_main_iteration ();
 
-               if (numchars >= 1 && emacs_event.kind != no_event)
-                 {
-                   bcopy (&emacs_event, bufp, sizeof (struct input_event));
-                   bufp++;
-                   count++;
-                   numchars--;
-                 }
+          count = current_count;
+          current_bufp = 0;
+          current_numcharsp = 0;
 
-#ifdef USE_X_TOOLKIT
-               f = x_menubar_window_to_frame (dpyinfo, event.xbutton.window);
-               /* For a down-event in the menu bar,
-                  don't pass it to Xt right now.
-                  Instead, save it away
-                  and we will pass it to Xt from kbd_buffer_get_event.
-                  That way, we can run some Lisp code first.  */
-               if (f && event.type == ButtonPress
-                   /* Verify the event is really within the menu bar
-                      and not just sent to it due to grabbing.  */
-                   && event.xbutton.x >= 0
-                   && event.xbutton.x < f->output_data.x->pixel_width
-                   && event.xbutton.y >= 0
-                   && event.xbutton.y < f->output_data.x->menubar_height
-                   && event.xbutton.same_screen)
-                 {
-                   SET_SAVED_BUTTON_EVENT;
-                   XSETFRAME (last_mouse_press_frame, f);
-                 }
-               else if (event.type == ButtonPress)
-                 {
-                   last_mouse_press_frame = Qnil;
-                   goto OTHER;
-                 }
+          if (current_finish == X_EVENT_GOTO_OUT)
+            goto out;
+        }
 
-#ifdef USE_MOTIF /* This should do not harm for Lucid,
-                   but I am trying to be cautious.  */
-               else if (event.type == ButtonRelease)
-                 {
-                   if (!NILP (last_mouse_press_frame))
-                     {
-                       f = XFRAME (last_mouse_press_frame);
-                       if (f->output_data.x)
-                         SET_SAVED_BUTTON_EVENT;
-                     }
-                   else
-                     goto OTHER;
-                 }
-#endif /* USE_MOTIF */
-               else
-                 goto OTHER;
-#endif /* USE_X_TOOLKIT */
-             }
-             break;
+#else /* not USE_GTK */
+      while (XPending (dpyinfo->display))
+       {
+          int finish;
 
-           case CirculateNotify:
-             goto OTHER;
-             
-           case CirculateRequest:
-             goto OTHER;
+         XNextEvent (dpyinfo->display, &event);
 
-           case VisibilityNotify:
-             goto OTHER;
+#ifdef HAVE_X_I18N
+          /* Filter events for the current X input method.  */
+          if (x_filter_event (dpyinfo, &event))
+            break;
+#endif
+         event_found = 1;
 
-           case MappingNotify:
-             /* Someone has changed the keyboard mapping - update the
-                local cache.  */
-             switch (event.xmapping.request)
-               {
-               case MappingModifier:
-                 x_find_modifier_meanings (dpyinfo);
-                 /* This is meant to fall through.  */
-               case MappingKeyboard:
-                 XRefreshKeyboardMapping (&event.xmapping);
-               }
-             goto OTHER;
+          count += handle_one_xevent (dpyinfo,
+                                      &event,
+                                      &bufp,
+                                      &numchars,
+                                      &finish);
 
-           default:
-           OTHER:
-#ifdef USE_X_TOOLKIT
-             BLOCK_INPUT;
-             XtDispatchEvent (&event);
-             UNBLOCK_INPUT;
-#endif /* USE_X_TOOLKIT */
-             break;
-           }
-       }
+          if (finish == X_EVENT_GOTO_OUT)
+            goto out;
+        }
+#endif /* USE_GTK */
     }
 
  out:;
@@ -11210,13 +11799,36 @@ notice_overwritten_cursor (w, area, x0, x1, y0, y1)
      enum glyph_row_area area;
      int x0, y0, x1, y1;
 {
-  if (area == TEXT_AREA
-      && w->phys_cursor_on_p
-      && y0 <= w->phys_cursor.y
-      && y1 >= w->phys_cursor.y + w->phys_cursor_height
-      && x0 <= w->phys_cursor.x
-      && (x1 < 0 || x1 > w->phys_cursor.x))
-    w->phys_cursor_on_p = 0;
+  if (area == TEXT_AREA && w->phys_cursor_on_p)
+    {
+      int cx0 = w->phys_cursor.x;
+      int cx1 = cx0 + w->phys_cursor_width;
+      int cy0 = w->phys_cursor.y;
+      int cy1 = cy0 + w->phys_cursor_height;
+
+      if (x0 <= cx0 && (x1 < 0 || x1 >= cx1))
+       {
+         /* The cursor image will be completely removed from the
+            screen if the output area intersects the cursor area in
+            y-direction.  When we draw in [y0 y1[, and some part of
+            the cursor is at y < y0, that part must have been drawn
+            before.  When scrolling, the cursor is erased before
+            actually scrolling, so we don't come here.  When not
+            scrolling, the rows above the old cursor row must have
+            changed, and in this case these rows must have written
+            over the cursor image.
+
+            Likewise if part of the cursor is below y1, with the
+            exception of the cursor being in the first blank row at
+            the buffer and window end because update_text_area
+            doesn't draw that row.  (Except when it does, but
+            that's handled in update_text_area.)  */
+
+         if (((y0 >= cy0 && y0 < cy1) || (y1 > cy0 && y1 < cy1))
+             && w->current_matrix->rows[w->phys_cursor.vpos].displays_text_p)
+           w->phys_cursor_on_p = 0;
+       }
+    }
 }
 
 
@@ -11296,7 +11908,8 @@ x_draw_hollow_cursor (w, row)
   if (cursor_glyph->type == STRETCH_GLYPH
       && !x_stretch_cursor_p)
     wd = min (CANON_X_UNIT (f), wd);
-  
+  w->phys_cursor_width = wd;
+
   /* The foreground of cursor_gc is typically the same as the normal
      background color, which can cause the cursor box to be invisible.  */
   xgcv.foreground = f->output_data.x->cursor_pixel;
@@ -11322,14 +11935,15 @@ x_draw_hollow_cursor (w, row)
    --gerd.  */
 
 static void
-x_draw_bar_cursor (w, row, width)
+x_draw_bar_cursor (w, row, width, kind)
      struct window *w;
      struct glyph_row *row;
      int width;
+     enum text_cursor_kinds kind;
 {
   struct frame *f = XFRAME (w->frame);
   struct glyph *cursor_glyph;
-      
+
   /* If cursor is out of bounds, don't draw garbage.  This can happen
      in mini-buffer windows when switching between echo area glyphs
      and mini-buffer.  */
@@ -11365,7 +11979,7 @@ x_draw_bar_cursor (w, row, width)
       else
        xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
       xgcv.graphics_exposures = 0;
-  
+
       if (gc)
        XChangeGC (dpy, gc, mask, &xgcv);
       else
@@ -11373,16 +11987,27 @@ x_draw_bar_cursor (w, row, width)
          gc = XCreateGC (dpy, window, mask, &xgcv);
          FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc = gc;
        }
-  
+
       if (width < 0)
-       width = f->output_data.x->cursor_width;
+       width = FRAME_CURSOR_WIDTH (f);
       width = min (cursor_glyph->pixel_width, width);
-  
+
+      w->phys_cursor_width = width;
       x_clip_to_row (w, row, gc, 0);
-      XFillRectangle (dpy, window, gc,
-                     WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
-                     WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
-                     width, row->height);
+
+      if (kind == BAR_CURSOR)
+         XFillRectangle (dpy, window, gc,
+                         WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
+                         WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
+                         width, row->height);
+      else
+         XFillRectangle (dpy, window, gc,
+                         WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x),
+                         WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y +
+                                                  row->height - width),
+                         cursor_glyph->pixel_width,
+                         width);
+
       XSetClipMask (dpy, gc, None);
     }
 }
@@ -11416,16 +12041,20 @@ x_draw_phys_cursor_glyph (w, row, hl)
   if (w->phys_cursor.hpos < row->used[TEXT_AREA])
     {
       int on_p = w->phys_cursor_on_p;
-      
-      x_draw_glyphs (w, w->phys_cursor.x, row, TEXT_AREA,
-                    w->phys_cursor.hpos, w->phys_cursor.hpos + 1,
-                    hl, 0);
+      int x1;
+
+      x1 = x_draw_glyphs (w, w->phys_cursor.x, row, TEXT_AREA,
+                         w->phys_cursor.hpos, w->phys_cursor.hpos + 1,
+                         hl, 0);
       w->phys_cursor_on_p = on_p;
 
+      if (hl == DRAW_CURSOR)
+       w->phys_cursor_width = x1 - w->phys_cursor.x;
+
       /* When we erase the cursor, and ROW is overlapped by other
         rows, make sure that these overlapping parts of other rows
         are redrawn.  */
-      if (hl == DRAW_NORMAL_TEXT && row->overlapped_p)
+      else if (hl == DRAW_NORMAL_TEXT && row->overlapped_p)
        {
          if (row > w->current_matrix->rows
              && MATRIX_ROW_OVERLAPS_SUCC_P (row - 1))
@@ -11459,7 +12088,7 @@ x_erase_phys_cursor (w)
      screen.  */
   if (w->phys_cursor_type == NO_CURSOR)
     goto mark_cursor_off;
-          
+
   /* VPOS >= active_glyphs->nrows means that window has been resized.
      Don't bother to erase the cursor.  */
   if (vpos >= active_glyphs->nrows)
@@ -11470,13 +12099,13 @@ x_erase_phys_cursor (w)
   cursor_row = MATRIX_ROW (active_glyphs, vpos);
   if (!cursor_row->enabled_p)
     goto mark_cursor_off;
-  
+
   /* If row is completely invisible, don't attempt to delete a cursor which
      isn't there.  This can happen if cursor is at top of a window, and
      we switch to a buffer with a header line in that window.  */
   if (cursor_row->visible_height <= 0)
     goto mark_cursor_off;
-  
+
   /* This can happen when the new row is shorter than the old one.
      In this case, either x_draw_glyphs or clear_end_of_line
      should have cleared the cursor.  Note that we wouldn't be
@@ -11484,7 +12113,7 @@ x_erase_phys_cursor (w)
      cursor glyph at hand.  */
   if (w->phys_cursor.hpos >= cursor_row->used[TEXT_AREA])
     goto mark_cursor_off;
-        
+
   /* If the cursor is in the mouse face area, redisplay that when
      we clear the cursor.  */
   if (! NILP (dpyinfo->mouse_face_window)
@@ -11512,7 +12141,7 @@ x_erase_phys_cursor (w)
        goto mark_cursor_off;
 
       x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
-      
+
       x_clear_area (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
                    x,
                    WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
@@ -11521,7 +12150,7 @@ x_erase_phys_cursor (w)
                    cursor_row->visible_height,
                    False);
     }
-  
+
   /* Erase the cursor by redrawing the character underneath it.  */
   if (mouse_face_here_p)
     hl = DRAW_MOUSE_FACE;
@@ -11543,7 +12172,7 @@ cursor_in_mouse_face_p (w)
 {
   struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (XFRAME (w->frame));
   int in_mouse_face = 0;
-  
+
   if (WINDOWP (dpyinfo->mouse_face_window)
       && XWINDOW (dpyinfo->mouse_face_window) == w)
     {
@@ -11576,10 +12205,10 @@ x_display_and_set_cursor (w, on, hpos, vpos, x, y)
   struct frame *f = XFRAME (w->frame);
   int new_cursor_type;
   int new_cursor_width;
+  int active_cursor;
   struct glyph_matrix *current_glyphs;
   struct glyph_row *glyph_row;
   struct glyph *glyph;
-  int cursor_non_selected;
 
   /* This is pointless on invisible frames, and dangerous on garbaged
      windows and frames; in the latter case, the frame or window may
@@ -11598,8 +12227,8 @@ x_display_and_set_cursor (w, on, hpos, vpos, x, y)
   current_glyphs = w->current_matrix;
   glyph_row = MATRIX_ROW (current_glyphs, vpos);
   glyph = glyph_row->glyphs[TEXT_AREA] + hpos;
-  
-  /* If cursor row is not enabled, we don't really know where to 
+
+  /* If cursor row is not enabled, we don't really know where to
      display the cursor.  */
   if (!glyph_row->enabled_p)
     {
@@ -11609,59 +12238,8 @@ x_display_and_set_cursor (w, on, hpos, vpos, x, y)
 
   xassert (interrupt_input_blocked);
 
-  /* Set new_cursor_type to the cursor we want to be displayed.  In a
-     mini-buffer window, we want the cursor only to appear if we are
-     reading input from this window.  For the selected window, we want
-     the cursor type given by the frame parameter.  If explicitly
-     marked off, draw no cursor.  In all other cases, we want a hollow
-     box cursor.  */
-  cursor_non_selected 
-    = !NILP (Fbuffer_local_value (Qcursor_in_non_selected_windows,
-                                 w->buffer));
-  new_cursor_width = -1;
-  if (cursor_in_echo_area
-      && FRAME_HAS_MINIBUF_P (f)
-      && EQ (FRAME_MINIBUF_WINDOW (f), echo_area_window))
-    {
-      if (w == XWINDOW (echo_area_window))
-       new_cursor_type = FRAME_DESIRED_CURSOR (f);
-      else if (cursor_non_selected)
-       new_cursor_type = HOLLOW_BOX_CURSOR;
-      else
-       new_cursor_type = NO_CURSOR;
-    }
-  else
-    {
-      if (f != FRAME_X_DISPLAY_INFO (f)->x_highlight_frame
-         || w != XWINDOW (f->selected_window))
-       {
-         if ((MINI_WINDOW_P (w) && minibuf_level == 0)
-             || !cursor_non_selected
-             || NILP (XBUFFER (w->buffer)->cursor_type))
-           new_cursor_type = NO_CURSOR;
-         else
-           new_cursor_type = HOLLOW_BOX_CURSOR;
-       }
-      else
-       {
-         struct buffer *b = XBUFFER (w->buffer);
-
-         if (EQ (b->cursor_type, Qt))
-           new_cursor_type = FRAME_DESIRED_CURSOR (f);
-         else
-           new_cursor_type = x_specified_cursor_type (b->cursor_type, 
-                                                      &new_cursor_width);
-         if (w->cursor_off_p)
-           {
-             if (new_cursor_type == FILLED_BOX_CURSOR)
-               new_cursor_type = HOLLOW_BOX_CURSOR;
-             else if (new_cursor_type == BAR_CURSOR && new_cursor_width > 1)
-               new_cursor_width = 1;
-             else
-               new_cursor_type = NO_CURSOR;
-           }
-       }
-    }
+  /* Set new_cursor_type to the cursor we want to be displayed.  */
+  new_cursor_type = get_window_cursor_type (w, &new_cursor_width, &active_cursor);
 
   /* If cursor is currently being shown and we don't want it to be or
      it is in the wrong place, or the cursor type is not what we want,
@@ -11671,17 +12249,20 @@ x_display_and_set_cursor (w, on, hpos, vpos, x, y)
          || w->phys_cursor.x != x
          || w->phys_cursor.y != y
          || new_cursor_type != w->phys_cursor_type
-         || (new_cursor_type == BAR_CURSOR
+         || ((new_cursor_type == BAR_CURSOR || new_cursor_type == HBAR_CURSOR)
              && new_cursor_width != w->phys_cursor_width)))
     x_erase_phys_cursor (w);
 
-  /* If the cursor is now invisible and we want it to be visible,
-     display it.  */
-  if (on && !w->phys_cursor_on_p)
+  /* Don't check phys_cursor_on_p here because that flag is only set
+     to zero in some cases where we know that the cursor has been
+     completely erased, to avoid the extra work of erasing the cursor
+     twice.  In other words, phys_cursor_on_p can be 1 and the cursor
+     still not be visible, or it has only been partly erased.  */
+  if (on)
     {
       w->phys_cursor_ascent = glyph_row->ascent;
       w->phys_cursor_height = glyph_row->height;
-      
+
       /* Set phys_cursor_.* before x_draw_.* is called because some
         of them may need the information.  */
       w->phys_cursor.x = x;
@@ -11689,7 +12270,6 @@ x_display_and_set_cursor (w, on, hpos, vpos, x, y)
       w->phys_cursor.hpos = hpos;
       w->phys_cursor.vpos = vpos;
       w->phys_cursor_type = new_cursor_type;
-      w->phys_cursor_width = new_cursor_width;
       w->phys_cursor_on_p = 1;
 
       switch (new_cursor_type)
@@ -11703,16 +12283,21 @@ x_display_and_set_cursor (w, on, hpos, vpos, x, y)
          break;
 
        case BAR_CURSOR:
-         x_draw_bar_cursor (w, glyph_row, new_cursor_width);
+         x_draw_bar_cursor (w, glyph_row, new_cursor_width, BAR_CURSOR);
+         break;
+
+       case HBAR_CURSOR:
+         x_draw_bar_cursor (w, glyph_row, new_cursor_width, HBAR_CURSOR);
          break;
 
        case NO_CURSOR:
+         w->phys_cursor_width = 0;
          break;
 
        default:
          abort ();
        }
-      
+
 #ifdef HAVE_X_I18N
       if (w == XWINDOW (f->selected_window))
        if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMPreeditPosition))
@@ -11750,6 +12335,7 @@ x_display_cursor (w, on, hpos, vpos, x, y)
 void
 x_update_cursor (f, on_p)
      struct frame *f;
+     int on_p;
 {
   x_update_cursor_in_window_tree (XWINDOW (f->root_window), on_p);
 }
@@ -11862,15 +12448,10 @@ x_text_icon (f, icon_name)
     text.encoding = XA_STRING;
     text.format = 8;
     text.nitems = strlen (icon_name);
-#ifdef USE_X_TOOLKIT
-    XSetWMIconName (FRAME_X_DISPLAY (f), XtWindow (f->output_data.x->widget),
-                   &text);
-#else /* not USE_X_TOOLKIT */
-    XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), &text);
-#endif /* not USE_X_TOOLKIT */
+    XSetWMIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), &text);
   }
 #else /* not HAVE_X11R4 */
-  XSetIconName (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), icon_name);
+  XSetIconName (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f), icon_name);
 #endif /* not HAVE_X11R4 */
 
   if (f->output_data.x->icon_bitmap > 0)
@@ -11898,7 +12479,7 @@ x_error_catcher (display, error)
      XErrorEvent *error;
 {
   XGetErrorText (display, error->error_code,
-                XSTRING (x_error_message_string)->data,
+                SDATA (x_error_message_string),
                 X_ERROR_MESSAGE_SIZE);
 }
 
@@ -11922,15 +12503,17 @@ int
 x_catch_errors (dpy)
      Display *dpy;
 {
-  int count = specpdl_ptr - specpdl;
+  int count = SPECPDL_INDEX ();
 
   /* 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);
+  record_unwind_protect (x_catch_errors_unwind,
+                        Fcons (make_save_value (dpy, 0),
+                               x_error_message_string));
 
   x_error_message_string = make_uninit_string (X_ERROR_MESSAGE_SIZE);
-  XSTRING (x_error_message_string)->data[0] = 0;
+  SSET (x_error_message_string, 0, 0);
 
   return count;
 }
@@ -11941,7 +12524,13 @@ static Lisp_Object
 x_catch_errors_unwind (old_val)
      Lisp_Object old_val;
 {
-  x_error_message_string = old_val;
+  Lisp_Object first;
+
+  first = XCAR (old_val);
+
+  XSync (XSAVE_VALUE (first)->pointer, False);
+
+  x_error_message_string = XCDR (old_val);
   return Qnil;
 }
 
@@ -11957,8 +12546,8 @@ x_check_errors (dpy, 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);
+  if (SREF (x_error_message_string, 0))
+    error (format, SDATA (x_error_message_string));
 }
 
 /* Nonzero if we had any X protocol errors
@@ -11971,7 +12560,7 @@ x_had_errors_p (dpy)
   /* Make sure to catch any errors incurred so far.  */
   XSync (dpy, False);
 
-  return XSTRING (x_error_message_string)->data[0] != 0;
+  return SREF (x_error_message_string, 0) != 0;
 }
 
 /* Forget about any errors we have had, since we did x_catch_errors on DPY.  */
@@ -11980,7 +12569,7 @@ void
 x_clear_errors (dpy)
      Display *dpy;
 {
-  XSTRING (x_error_message_string)->data[0] = 0;
+  SSET (x_error_message_string, 0, 0);
 }
 
 /* Stop catching X protocol errors and let them make Emacs die.
@@ -12007,10 +12596,10 @@ x_trace_wire ()
 \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 
+   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.  */
@@ -12053,17 +12642,17 @@ x_connection_closed (dpy, error_message)
   struct x_display_info *dpyinfo = x_display_info_for_display (dpy);
   Lisp_Object frame, tail;
   int count;
-  
+
   error_msg = (char *) alloca (strlen (error_message) + 1);
   strcpy (error_msg, error_message);
   handling_signal = 0;
-  
+
   /* Prevent being called recursively because of an error condition
      below.  Otherwise, we might end up with printing ``can't find per
      display information'' in the recursive call instead of printing
      the original message here.  */
   count = x_catch_errors (dpy);
-  
+
   /* We have to close the display to inform Xt that it doesn't
      exist anymore.  If we don't, Xt will continue to wait for
      events from the display.  As a consequence, a sequence of
@@ -12078,7 +12667,7 @@ x_connection_closed (dpy, error_message)
      Closing the display is reported to lead to a bus error on
      OpenWindows in certain situations.  I suspect that is a bug
      in OpenWindows.  I don't know how to cicumvent it here.  */
-  
+
 #ifdef USE_X_TOOLKIT
   /* If DPYINFO is null, this means we didn't open the display
      in the first place, so don't try to close it.  */
@@ -12126,7 +12715,7 @@ x_connection_closed (dpy, error_message)
     x_delete_display (dpyinfo);
 
   x_uncatch_errors (dpy, count);
-  
+
   if (x_display_list == 0)
     {
       fprintf (stderr, "%s\n", error_msg);
@@ -12280,7 +12869,7 @@ x_new_fontset (f, fontsetname)
        to do.  */
     return fontset_name (fontset);
 
-  result = x_new_font (f, (XSTRING (fontset_ascii (fontset))->data));
+  result = x_new_font (f, (SDATA (fontset_ascii (fontset))));
 
   if (!STRINGP (result))
     /* Can't load ASCII font.  */
@@ -12292,9 +12881,9 @@ x_new_fontset (f, fontsetname)
 #ifdef HAVE_X_I18N
   if (FRAME_XIC (f)
       && (FRAME_XIC_STYLE (f) & (XIMPreeditPosition | XIMStatusArea)))
-    xic_set_xfontset (f, XSTRING (fontset_ascii (fontset))->data);
+    xic_set_xfontset (f, SDATA (fontset_ascii (fontset)));
 #endif
-  
+
   return build_string (fontsetname);
 }
 
@@ -12403,9 +12992,9 @@ xim_destroy_callback (xim, client_data, call_data)
 {
   struct x_display_info *dpyinfo = (struct x_display_info *) client_data;
   Lisp_Object frame, tail;
-  
+
   BLOCK_INPUT;
-  
+
   /* No need to call XDestroyIC.. */
   FOR_EACH_FRAME (tail, frame)
     {
@@ -12420,7 +13009,7 @@ xim_destroy_callback (xim, client_data, call_data)
            }
        }
     }
-  
+
   /* No need to call XCloseIM.  */
   dpyinfo->xim = NULL;
   XFree (dpyinfo->xim_styles);
@@ -12429,6 +13018,11 @@ xim_destroy_callback (xim, client_data, call_data)
 
 #endif /* HAVE_X11R6 */
 
+#ifdef HAVE_X11R6
+/* This isn't prototyped in OSF 5.0 or 5.1a.  */
+extern char *XSetIMValues P_ ((XIM, ...));
+#endif
+
 /* Open the connection to the XIM server on display DPYINFO.
    RESOURCE_NAME is the resource name Emacs uses.  */
 
@@ -12448,18 +13042,17 @@ xim_open_dpy (dpyinfo, resource_name)
 #ifdef HAVE_X11R6
       XIMCallback destroy;
 #endif
-      
+
       /* Get supported styles and XIM values.  */
       XGetIMValues (xim, XNQueryInputStyle, &dpyinfo->xim_styles, NULL);
-      
+
 #ifdef HAVE_X11R6
       destroy.callback = xim_destroy_callback;
       destroy.client_data = (XPointer)dpyinfo;
-      /* This isn't prototyped in OSF 5.0.  */
       XSetIMValues (xim, XNDestroyCallback, &destroy, NULL);
 #endif
     }
-  
+
 #else /* not USE_XIM */
   dpyinfo->xim = NULL;
 #endif /* not USE_XIM */
@@ -12475,7 +13068,7 @@ struct xim_inst_t
 };
 
 /* XIM instantiate callback function, which is called whenever an XIM
-   server is available.  DISPLAY is teh display of the XIM.
+   server is available.  DISPLAY is the display of the XIM.
    CLIENT_DATA contains a pointer to an xim_inst_t structure created
    when the callback was registered.  */
 
@@ -12491,7 +13084,7 @@ xim_instantiate_callback (display, client_data, call_data)
   /* We don't support multiple XIM connections. */
   if (dpyinfo->xim)
     return;
-  
+
   xim_open_dpy (dpyinfo, xim_inst->resource_name);
 
   /* Create XIC for the existing frames on the same display, as long
@@ -12504,7 +13097,7 @@ xim_instantiate_callback (display, client_data, call_data)
       FOR_EACH_FRAME (tail, frame)
        {
          struct frame *f = XFRAME (frame);
-         
+
          if (FRAME_X_DISPLAY_INFO (f) == xim_inst->dpyinfo)
            if (FRAME_XIC (f) == NULL)
              {
@@ -12518,7 +13111,7 @@ xim_instantiate_callback (display, client_data, call_data)
                  }
              }
        }
-      
+
       UNBLOCK_INPUT;
     }
 }
@@ -12540,7 +13133,7 @@ xim_initialize (dpyinfo, resource_name)
 #ifdef HAVE_X11R6_XIM
   struct xim_inst_t *xim_inst;
   int len;
-  
+
   dpyinfo->xim = NULL;
   xim_inst = (struct xim_inst_t *) xmalloc (sizeof (struct xim_inst_t));
   xim_inst->dpyinfo = dpyinfo;
@@ -12558,7 +13151,7 @@ xim_initialize (dpyinfo, resource_name)
   dpyinfo->xim = NULL;
   xim_open_dpy (dpyinfo, resource_name);
 #endif /* not HAVE_X11R6_XIM */
-  
+
 #else /* not USE_XIM */
   dpyinfo->xim = NULL;
 #endif /* not USE_XIM */
@@ -12606,11 +13199,7 @@ x_calc_absolute_position (f)
   if (! ((flags & XNegative) || (flags & YNegative)))
     return;
 
-#ifdef USE_X_TOOLKIT
-  this_window = XtWindow (f->output_data.x->widget);
-#else
-  this_window = FRAME_X_WINDOW (f);
-#endif
+  this_window = FRAME_OUTER_WINDOW (f);
 
   /* Find the position of the outside upper-left corner of
      the inner window, with respect to the outer window.
@@ -12680,7 +13269,7 @@ x_calc_absolute_position (f)
 
        It's not obvious where the initial small difference comes from.
        2000-12-01, gerd.  */
-    
+
     XtVaGetValues (f->output_data.x->column_widget, XtNheight, &height, NULL);
 #endif
 
@@ -12691,7 +13280,7 @@ x_calc_absolute_position (f)
                                 - height
                                 + f->output_data.x->top_pos);
   }
-  
+
   /* The left_pos and top_pos
      are now relative to the top and left screen edges,
      so the flags should correspond.  */
@@ -12741,13 +13330,8 @@ x_set_offset (f, xoff, yoff, change_gravity)
     }
 #endif
 
-#ifdef USE_X_TOOLKIT
-  XMoveWindow (FRAME_X_DISPLAY (f), XtWindow (f->output_data.x->widget),
-              modified_left, modified_top);
-#else /* not USE_X_TOOLKIT */
-  XMoveWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
-              modified_left, modified_top);
-#endif /* not USE_X_TOOLKIT */
+  XMoveWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f),
+               modified_left, modified_top);
   UNBLOCK_INPUT;
 }
 
@@ -12760,12 +13344,12 @@ x_check_fullscreen (f)
   if (f->output_data.x->want_fullscreen & FULLSCREEN_BOTH)
     {
       int width, height, ign;
-                      
+
       x_real_positions (f, &f->output_data.x->left_pos,
                         &f->output_data.x->top_pos);
 
       x_fullscreen_adjust (f, &width, &height, &ign, &ign);
-                  
+
       /* We do not need to move the window, it shall be taken care of
          when setting WM manager hints.
          If the frame is visible already, the position is checked by
@@ -12778,7 +13362,7 @@ x_check_fullscreen (f)
 
           /* Wait for the change of frame size to occur */
           f->output_data.x->want_fullscreen |= FULLSCREEN_WAIT;
-          
+
         }
     }
 }
@@ -12802,7 +13386,7 @@ x_check_fullscreen_move (f)
       expect_top = 0;
     if (f->output_data.x->want_fullscreen & FULLSCREEN_WIDTH)
       expect_left = 0;
-    
+
     if (expect_top != f->output_data.x->top_pos
         || expect_left != f->output_data.x->left_pos)
       x_set_offset (f, expect_left, expect_top, 1);
@@ -12830,11 +13414,11 @@ x_fullscreen_adjust (f, width, height, top_pos, left_pos)
 
   *top_pos = f->output_data.x->top_pos;
   *left_pos = f->output_data.x->left_pos;
-  
+
   if (f->output_data.x->want_fullscreen & FULLSCREEN_HEIGHT)
     {
       int ph;
-      
+
       ph = FRAME_X_DISPLAY_INFO (f)->height;
       newheight = PIXEL_TO_CHAR_HEIGHT (f, ph);
       ph = CHAR_TO_PIXEL_HEIGHT (f, newheight)
@@ -12846,7 +13430,7 @@ x_fullscreen_adjust (f, width, height, top_pos, left_pos)
   if (f->output_data.x->want_fullscreen & FULLSCREEN_WIDTH)
     {
       int pw;
-      
+
       pw = FRAME_X_DISPLAY_INFO (f)->width;
       newwidth = PIXEL_TO_CHAR_WIDTH (f, pw);
       pw = CHAR_TO_PIXEL_WIDTH (f, newwidth)
@@ -12933,8 +13517,13 @@ x_set_window_size (f, change_gravity, cols, rows)
 {
   BLOCK_INPUT;
 
-#ifdef USE_X_TOOLKIT
-  
+#ifdef USE_GTK
+  if (FRAME_GTK_WIDGET (f))
+    xg_frame_set_char_size (f, cols, rows);
+  else
+    x_set_window_size_1 (f, change_gravity, cols, rows);
+#elif USE_X_TOOLKIT
+
   if (f->output_data.x->widget != NULL)
     {
       /* The x and y position of the widget is clobbered by the
@@ -12949,18 +13538,18 @@ x_set_window_size (f, change_gravity, cols, rows)
     }
   else
     x_set_window_size_1 (f, change_gravity, cols, rows);
-  
+
 #else /* not USE_X_TOOLKIT */
-  
+
   x_set_window_size_1 (f, change_gravity, cols, rows);
-  
+
 #endif /* not USE_X_TOOLKIT */
 
   /* If cursor was outside the new size, mark it as off.  */
   mark_window_cursors_off (XWINDOW (f->root_window));
 
   /* Clear out any recollection of where the mouse highlighting was,
-     since it might be in a place that's outside the new frame size. 
+     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.  */
   cancel_mouse_face (f);
@@ -13046,11 +13635,7 @@ x_raise_frame (f)
   if (f->async_visible)
     {
       BLOCK_INPUT;
-#ifdef USE_X_TOOLKIT
-      XRaiseWindow (FRAME_X_DISPLAY (f), XtWindow (f->output_data.x->widget));
-#else /* not USE_X_TOOLKIT */
-      XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
-#endif /* not USE_X_TOOLKIT */
+      XRaiseWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
       XFlush (FRAME_X_DISPLAY (f));
       UNBLOCK_INPUT;
     }
@@ -13065,11 +13650,7 @@ x_lower_frame (f)
   if (f->async_visible)
     {
       BLOCK_INPUT;
-#ifdef USE_X_TOOLKIT
-      XLowerWindow (FRAME_X_DISPLAY (f), XtWindow (f->output_data.x->widget));
-#else /* not USE_X_TOOLKIT */
-      XLowerWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
-#endif /* not USE_X_TOOLKIT */
+      XLowerWindow (FRAME_X_DISPLAY (f), FRAME_OUTER_WINDOW (f));
       XFlush (FRAME_X_DISPLAY (f));
       UNBLOCK_INPUT;
     }
@@ -13129,7 +13710,12 @@ x_make_frame_visible (f)
       /* This was XtPopup, but that did nothing for an iconified frame.  */
       XtMapWidget (f->output_data.x->widget);
 #else /* not USE_X_TOOLKIT */
+#ifdef USE_GTK
+      gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
+      gtk_window_deiconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
+#else
       XMapRaised (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
+#endif /* not USE_GTK */
 #endif /* not USE_X_TOOLKIT */
 #if 0 /* This seems to bring back scroll bars in the wrong places
         if the window configuration has changed.  They seem
@@ -13176,7 +13762,7 @@ x_make_frame_visible (f)
        Drawable rootw;
        int x, y;
        unsigned int width, height, border, depth;
-       
+
        BLOCK_INPUT;
 
        /* On some window managers (such as FVWM) moving an existing
@@ -13239,7 +13825,7 @@ x_make_frame_visible (f)
        FreeBSD, Linux and Solaris.  It turns out that, for some
        unknown reason, the call to XtMapWidget is completely ignored.
        Mapping the widget a second time works.  */
-    
+
     if (!FRAME_VISIBLE_P (f) && --retry_count > 0)
       goto retry;
   }
@@ -13255,12 +13841,8 @@ x_make_frame_invisible (f)
 {
   Window window;
 
-#ifdef USE_X_TOOLKIT
   /* Use the frame's outermost window, not the one we normally draw on.  */
-  window = XtWindow (f->output_data.x->widget);
-#else /* not USE_X_TOOLKIT */
-  window = FRAME_X_WINDOW (f);
-#endif /* not USE_X_TOOLKIT */
+  window = FRAME_OUTER_WINDOW (f);
 
   /* Don't keep the highlight on an invisible frame.  */
   if (FRAME_X_DISPLAY_INFO (f)->x_highlight_frame == f)
@@ -13280,6 +13862,14 @@ x_make_frame_invisible (f)
      by hand again (they have already done that once for this window.)  */
   x_wm_set_size_hint (f, (long) 0, 1);
 
+#ifdef USE_GTK
+  if (FRAME_GTK_OUTER_WIDGET (f))
+    {
+      gtk_widget_hide (FRAME_GTK_OUTER_WIDGET (f));
+      goto out;
+    }
+#endif
+
 #ifdef HAVE_X11R4
 
   if (! XWithdrawWindow (FRAME_X_DISPLAY (f), window,
@@ -13314,6 +13904,7 @@ x_make_frame_invisible (f)
   XUnmapWindow (FRAME_X_DISPLAY (f), window);
 #endif /* ! defined (HAVE_X11R4) */
 
+ out:
   /* We can't distinguish this from iconification
      just by the event that we get from the server.
      So we can't win using the usual strategy of letting
@@ -13353,6 +13944,22 @@ x_iconify_frame (f)
   if (!NILP (type))
     x_bitmap_icon (f, type);
 
+#ifdef USE_GTK
+  if (FRAME_GTK_OUTER_WIDGET (f))
+    {
+      if (! FRAME_VISIBLE_P (f))
+        gtk_widget_show_all (FRAME_GTK_OUTER_WIDGET (f));
+
+      gtk_window_iconify (GTK_WINDOW (FRAME_GTK_OUTER_WIDGET (f)));
+      f->iconified = 1;
+      f->visible = 1;
+      f->async_iconified = 1;
+      f->async_visible = 0;
+      UNBLOCK_INPUT;
+      return;
+    }
+#endif
+
 #ifdef USE_X_TOOLKIT
 
   if (! FRAME_VISIBLE_P (f))
@@ -13487,6 +14094,18 @@ x_free_frame_resources (f)
 
       free_frame_menubar (f);
 #else  /* !USE_X_TOOLKIT */
+
+#ifdef USE_GTK
+      /* In the GTK version, tooltips are normal X
+         frames.  We must check and free both types. */
+      if (FRAME_GTK_OUTER_WIDGET (f))
+        {
+          gtk_widget_destroy (FRAME_GTK_OUTER_WIDGET (f));
+          FRAME_X_WINDOW (f) = 0; /* Set to avoid XDestroyWindow below */
+          FRAME_GTK_OUTER_WIDGET (f) = 0;
+        }
+#endif /* USE_GTK */
+
       if (FRAME_X_WINDOW (f))
        XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
 #endif /* !USE_X_TOOLKIT */
@@ -13516,7 +14135,7 @@ x_free_frame_resources (f)
 
       if (FRAME_FACE_CACHE (f))
        free_frame_faces (f);
-      
+
       x_free_gcs (f);
       XFlush (FRAME_X_DISPLAY (f));
     }
@@ -13526,7 +14145,7 @@ x_free_frame_resources (f)
 
   xfree (f->output_data.x);
   f->output_data.x = NULL;
-  
+
   if (f == dpyinfo->x_focus_frame)
     dpyinfo->x_focus_frame = 0;
   if (f == dpyinfo->x_focus_event_frame)
@@ -13572,8 +14191,10 @@ x_destroy_window (f)
    FLAGS is the flags word to use--or 0 meaning preserve the flags
    that the window now has.
    If USER_POSITION is nonzero, we set the USPosition
-   flag (this is useful when FLAGS is 0).  */
+   flag (this is useful when FLAGS is 0).
+   The GTK version is in gtkutils.c  */
 
+#ifndef USE_GTK
 void
 x_wm_set_size_hint (f, flags, user_position)
      struct frame *f;
@@ -13586,10 +14207,9 @@ x_wm_set_size_hint (f, flags, user_position)
   Arg al[2];
   int ac = 0;
   Dimension widget_width, widget_height;
-  Window window = XtWindow (f->output_data.x->widget);
-#else /* not USE_X_TOOLKIT */
-  Window window = FRAME_X_WINDOW (f);
-#endif /* not USE_X_TOOLKIT */
+#endif
+
+  Window window = FRAME_OUTER_WINDOW (f);
 
   /* Setting PMaxSize caused various problems.  */
   size_hints.flags = PResizeInc | PMinSize /* | PMaxSize */;
@@ -13716,6 +14336,7 @@ x_wm_set_size_hint (f, flags, user_position)
   XSetNormalHints (FRAME_X_DISPLAY (f), window, &size_hints);
 #endif
 }
+#endif /* not USE_GTK */
 
 /* Used for IconicState or NormalState */
 
@@ -13747,7 +14368,7 @@ x_wm_set_icon_pixmap (f, pixmap_id)
   Pixmap icon_pixmap;
 
 #ifndef USE_X_TOOLKIT
-  Window window = FRAME_X_WINDOW (f);
+  Window window = FRAME_OUTER_WINDOW (f);
 #endif
 
   if (pixmap_id > 0)
@@ -13780,7 +14401,7 @@ x_wm_set_icon_pixmap (f, pixmap_id)
   }
 
 #else /* not USE_X_TOOLKIT */
-  
+
   f->output_data.x->wm_hints.flags |= IconPixmapHint;
   XSetWMHints (FRAME_X_DISPLAY (f), window, &f->output_data.x->wm_hints);
 
@@ -13792,11 +14413,7 @@ x_wm_set_icon_position (f, icon_x, icon_y)
      struct frame *f;
      int icon_x, icon_y;
 {
-#ifdef USE_X_TOOLKIT
-  Window window = XtWindow (f->output_data.x->widget);
-#else
-  Window window = FRAME_X_WINDOW (f);
-#endif
+  Window window = FRAME_OUTER_WINDOW (f);
 
   f->output_data.x->wm_hints.flags |= IconPositionHint;
   f->output_data.x->wm_hints.icon_x = icon_x;
@@ -13892,7 +14509,7 @@ x_list_fonts (f, pattern, size, maxnames)
          XFontStruct *font;
          unsigned long value;
 
-         font = XLoadQueryFont (dpy, XSTRING (pattern)->data);
+         font = XLoadQueryFont (dpy, SDATA (pattern));
          if (x_had_errors_p (dpy))
            {
              /* This error is perhaps due to insufficient memory on X
@@ -13935,8 +14552,28 @@ x_list_fonts (f, pattern, size, maxnames)
        {
          /* We try at least 10 fonts because XListFonts will return
             auto-scaled fonts at the head.  */
-         names = XListFonts (dpy, XSTRING (pattern)->data, max (maxnames, 10),
-                             &num_fonts);
+          if (maxnames < 0)
+            {
+              int limit;
+
+              for (limit = 500;;)
+                {
+                  names = XListFonts (dpy, SDATA (pattern), limit, &num_fonts);
+                  if (num_fonts == limit)
+                    {
+                      BLOCK_INPUT;
+                      XFreeFontNames (names);
+                      UNBLOCK_INPUT;
+                      limit *= 2;
+                    }
+                  else
+                    break;
+                }
+            }
+          else
+            names = XListFonts (dpy, SDATA (pattern), max (maxnames, 10),
+                                &num_fonts);
+
          if (x_had_errors_p (dpy))
            {
              /* This error is perhaps due to insufficient memory on X
@@ -13960,7 +14597,7 @@ x_list_fonts (f, pattern, size, maxnames)
              int width = 0;
              char *p = names[i];
              int average_width = -1, dashes = 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
@@ -13975,7 +14612,7 @@ x_list_fonts (f, pattern, size, maxnames)
                    else if (dashes == 12) /* AVERAGE_WIDTH field */
                      average_width = atoi (p);
                  }
-             
+
              if (allow_scalable_fonts_p
                  || dashes < 14 || average_width != 0)
                {
@@ -13995,7 +14632,7 @@ x_list_fonts (f, pattern, size, maxnames)
                    }
                }
            }
-         
+
          if (!try_XLoadQueryFont)
            {
              BLOCK_INPUT;
@@ -14036,7 +14673,7 @@ x_list_fonts (f, pattern, size, maxnames)
              BLOCK_INPUT;
              count = x_catch_errors (dpy);
              thisinfo = XLoadQueryFont (dpy,
-                                        XSTRING (XCAR (tem))->data);
+                                        SDATA (XCAR (tem)));
              if (x_had_errors_p (dpy))
                {
                  /* This error is perhaps due to insufficient memory on X
@@ -14095,7 +14732,7 @@ x_list_fonts (f, pattern, size, maxnames)
     }
 
   return newlist;
-}  
+}
 
 
 #if GLYPH_DEBUG
@@ -14114,7 +14751,7 @@ x_check_font (f, font)
   xassert (font != NULL);
 
   for (i = 0; i < dpyinfo->n_fonts; i++)
-    if (dpyinfo->font_table[i].name 
+    if (dpyinfo->font_table[i].name
        && font == dpyinfo->font_table[i].font)
       break;
 
@@ -14160,20 +14797,20 @@ x_compute_min_glyph_bounds (f)
   XFontStruct *font;
   int old_width = dpyinfo->smallest_char_width;
   int old_height = dpyinfo->smallest_font_height;
-  
+
   dpyinfo->smallest_font_height = 100000;
   dpyinfo->smallest_char_width = 100000;
-  
+
   for (i = 0; i < dpyinfo->n_fonts; ++i)
     if (dpyinfo->font_table[i].name)
       {
        struct font_info *fontp = dpyinfo->font_table + i;
        int w, h;
-       
+
        font = (XFontStruct *) fontp->font;
        xassert (font != (XFontStruct *) ~0);
        x_font_min_bounds (font, &w, &h);
-       
+
        dpyinfo->smallest_font_height = min (dpyinfo->smallest_font_height, h);
        dpyinfo->smallest_char_width = min (dpyinfo->smallest_char_width, w);
       }
@@ -14216,9 +14853,9 @@ x_load_font (f, fontname, size)
        for (tail = font_names; CONSP (tail); tail = XCDR (tail))
          if (dpyinfo->font_table[i].name
              && (!strcmp (dpyinfo->font_table[i].name,
-                          XSTRING (XCAR (tail))->data)
+                          SDATA (XCAR (tail)))
                  || !strcmp (dpyinfo->font_table[i].full_name,
-                             XSTRING (XCAR (tail))->data)))
+                             SDATA (XCAR (tail)))))
            return (dpyinfo->font_table + i);
     }
 
@@ -14236,7 +14873,7 @@ x_load_font (f, fontname, size)
        a bug of not finding a font even if the font surely exists and
        is loadable by XLoadQueryFont.  */
     if (size > 0 && !NILP (font_names))
-      fontname = (char *) XSTRING (XCAR (font_names))->data;
+      fontname = (char *) SDATA (XCAR (font_names));
 
     BLOCK_INPUT;
     count = x_catch_errors (FRAME_X_DISPLAY (f));
@@ -14308,7 +14945,7 @@ x_load_font (f, fontname, size)
 
        XFree (name);
       }
-    
+
     if (full_name != 0)
       fontp->full_name = full_name;
     else
@@ -14440,7 +15077,7 @@ x_find_ccl_program (fontp)
                  >= 0)))
        break;
     }
-  
+
   if (! NILP (list))
     {
       struct ccl_program *ccl
@@ -14485,10 +15122,10 @@ static int x_initialized;
    the screen number from the server number.  */
 static int
 same_x_server (name1, name2)
-     char *name1, *name2;
+     const char *name1, *name2;
 {
   int seen_colon = 0;
-  unsigned char *system_name = XSTRING (Vsystem_name)->data;
+  const unsigned char *system_name = SDATA (Vsystem_name);
   int system_name_length = strlen (system_name);
   int length_until_period = 0;
 
@@ -14548,6 +15185,71 @@ x_term_init (display_name, xrm_option, resource_name)
       x_initialized = 1;
     }
 
+#ifdef USE_GTK
+  {
+#define NUM_ARGV 10
+    int argc;
+    char *argv[NUM_ARGV];
+    char **argv2 = argv;
+    GdkAtom atom;
+
+    /* GTK 2.0 can only handle one display, GTK 2.2 can handle more
+       than one, but this remains to be implemented.  */
+    if (x_initialized > 1)
+      return 0;
+
+    x_initialized++;
+
+    for (argc = 0; argc < NUM_ARGV; ++argc)
+      argv[argc] = 0;
+
+    argc = 0;
+    argv[argc++] = initial_argv[0];
+
+    if (! NILP (display_name))
+      {
+        argv[argc++] = "--display";
+        argv[argc++] = SDATA (display_name);
+      }
+
+    argv[argc++] = "--name";
+    argv[argc++] = resource_name;
+
+#ifdef HAVE_X11R5
+    XSetLocaleModifiers ("");
+#endif
+
+    gtk_init (&argc, &argv2);
+
+    /* gtk_init does set_locale.  We must fix locale after calling it.  */
+    fixup_locale ();
+    xg_initialize ();
+
+    dpy = GDK_DISPLAY ();
+
+    /* NULL window -> events for all windows go to our function */
+    gdk_window_add_filter (NULL, event_handler_gdk, NULL);
+
+    /* Load our own gtkrc if it exists.  */
+    {
+      struct gcpro gcpro1, gcpro2;
+      char *file = "~/.emacs.d/gtkrc";
+      Lisp_Object s, abs_file;
+
+      GCPRO2 (str, abs_file);
+      s = make_string (file, strlen (file));
+      abs_file = Fexpand_file_name(s, Qnil);
+
+      if (! NILP (abs_file) && Ffile_readable_p (abs_file))
+        gtk_rc_parse (SDATA (abs_file));
+
+      UNGCPRO;
+    }
+
+    XSetErrorHandler (x_error_handler);
+    XSetIOErrorHandler (x_io_error_quitter);
+  }
+#else /* not USE_GTK */
 #ifdef USE_X_TOOLKIT
   /* weiner@footloose.sps.mot.com reports that this causes
      errors with X11R5:
@@ -14569,10 +15271,12 @@ x_term_init (display_name, xrm_option, resource_name)
        argv[argc++] = "-xrm";
        argv[argc++] = xrm_option;
       }
-    dpy = XtOpenDisplay (Xt_app_con, XSTRING (display_name)->data,
+    turn_on_atimers (0);
+    dpy = XtOpenDisplay (Xt_app_con, SDATA (display_name),
                         resource_name, EMACS_CLASS,
                         emacs_options, XtNumber (emacs_options),
                         &argc, argv);
+    turn_on_atimers (1);
 
 #ifdef HAVE_X11XTR6
     /* I think this is to compensate for XtSetLanguageProc.  */
@@ -14584,8 +15288,9 @@ x_term_init (display_name, xrm_option, resource_name)
 #ifdef HAVE_X11R5
   XSetLocaleModifiers ("");
 #endif
-  dpy = XOpenDisplay (XSTRING (display_name)->data);
+  dpy = XOpenDisplay (SDATA (display_name));
 #endif /* not USE_X_TOOLKIT */
+#endif /* not USE_GTK*/
 
   /* Detect failure.  */
   if (dpy == 0)
@@ -14606,8 +15311,8 @@ x_term_init (display_name, xrm_option, resource_name)
 
     for (share = x_display_list, tail = x_display_name_list; share;
         share = share->next, tail = XCDR (tail))
-      if (same_x_server (XSTRING (XCAR (XCAR (tail)))->data,
-                        XSTRING (display_name)->data))
+      if (same_x_server (SDATA (XCAR (XCAR (tail))),
+                        SDATA (display_name)))
        break;
     if (share)
       dpyinfo->kboard = share->kboard;
@@ -14641,7 +15346,7 @@ x_term_init (display_name, xrm_option, resource_name)
   dpyinfo->next = x_display_list;
   x_display_list = dpyinfo;
 
-  /* Put it on x_display_name_list as well, to keep them parallel.  */ 
+  /* Put it on x_display_name_list as well, to keep them parallel.  */
   x_display_name_list = Fcons (Fcons (display_name, Qnil),
                               x_display_name_list);
   dpyinfo->name_list_element = XCAR (x_display_name_list);
@@ -14653,11 +15358,11 @@ x_term_init (display_name, xrm_option, resource_name)
 #endif /* ! 0 */
 
   dpyinfo->x_id_name
-    = (char *) xmalloc (STRING_BYTES (XSTRING (Vinvocation_name))
-                       + STRING_BYTES (XSTRING (Vsystem_name))
+    = (char *) xmalloc (SBYTES (Vinvocation_name)
+                       + SBYTES (Vsystem_name)
                        + 2);
   sprintf (dpyinfo->x_id_name, "%s@%s",
-          XSTRING (Vinvocation_name)->data, XSTRING (Vsystem_name)->data);
+          SDATA (Vinvocation_name), SDATA (Vsystem_name));
 
   /* Figure out which modifier bits mean what.  */
   x_find_modifier_meanings (dpyinfo);
@@ -14720,15 +15425,15 @@ x_term_init (display_name, xrm_option, resource_name)
                                          build_string ("PrivateColormap"),
                                          Qnil, Qnil);
          if (STRINGP (value)
-             && (!strcmp (XSTRING (value)->data, "true")
-                 || !strcmp (XSTRING (value)->data, "on")))
+             && (!strcmp (SDATA (value), "true")
+                 || !strcmp (SDATA (value), "on")))
            dpyinfo->cmap = XCopyColormapAndFree (dpyinfo->display, dpyinfo->cmap);
        }
     }
   else
     dpyinfo->cmap = XCreateColormap (dpyinfo->display, dpyinfo->root_window,
                                     dpyinfo->visual, AllocNone);
-      
+
   {
     int screen_number = XScreenNumberOfScreen (dpyinfo->screen);
     double pixels = DisplayHeight (dpyinfo->display, screen_number);
@@ -14738,7 +15443,7 @@ x_term_init (display_name, xrm_option, resource_name)
     mm = DisplayWidthMM (dpyinfo->display, screen_number);
     dpyinfo->resx = pixels * 25.4 / mm;
   }
-  
+
   dpyinfo->Xatom_wm_protocols
     = XInternAtom (dpyinfo->display, "WM_PROTOCOLS", False);
   dpyinfo->Xatom_wm_take_focus
@@ -14763,6 +15468,8 @@ x_term_init (display_name, xrm_option, resource_name)
     = XInternAtom (dpyinfo->display, "TEXT", False);
   dpyinfo->Xatom_COMPOUND_TEXT
     = XInternAtom (dpyinfo->display, "COMPOUND_TEXT", False);
+  dpyinfo->Xatom_UTF8_STRING
+    = XInternAtom (dpyinfo->display, "UTF8_STRING", False);
   dpyinfo->Xatom_DELETE
     = XInternAtom (dpyinfo->display, "DELETE", False);
   dpyinfo->Xatom_MULTIPLE
@@ -14790,7 +15497,7 @@ x_term_init (display_name, xrm_option, resource_name)
   /* Ghostscript support.  */
   dpyinfo->Xatom_PAGE = XInternAtom (dpyinfo->display, "PAGE", False);
   dpyinfo->Xatom_DONE = XInternAtom (dpyinfo->display, "DONE", False);
-  
+
   dpyinfo->Xatom_Scrollbar = XInternAtom (dpyinfo->display, "SCROLLBAR",
                                          False);
 
@@ -14805,7 +15512,7 @@ x_term_init (display_name, xrm_option, resource_name)
     null_bits[0] = 0x00;
 
     dpyinfo->null_pixel
-      = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window, 
+      = XCreatePixmapFromBitmapData (dpyinfo->display, dpyinfo->root_window,
                                     null_bits, 1, 1, (long) 0, (long) 0,
                                     1);
   }
@@ -14823,7 +15530,7 @@ x_term_init (display_name, xrm_option, resource_name)
 #ifdef HAVE_X_I18N
   xim_initialize (dpyinfo, resource_name);
 #endif
-  
+
 #ifdef subprocesses
   /* This is only needed for distinguishing keyboard and process input.  */
   if (connection != 0)
@@ -14855,7 +15562,7 @@ x_term_init (display_name, xrm_option, resource_name)
     XrmValue d, fr, to;
     Font font;
     int count;
-    
+
     d.addr = (XPointer)&dpy;
     d.size = sizeof (Display *);
     fr.addr = XtDefaultFont;
@@ -14881,11 +15588,11 @@ x_term_init (display_name, xrm_option, resource_name)
                                    build_string ("Synchronous"),
                                    Qnil, Qnil);
     if (STRINGP (value)
-       && (!strcmp (XSTRING (value)->data, "true")
-           || !strcmp (XSTRING (value)->data, "on")))
+       && (!strcmp (SDATA (value), "true")
+           || !strcmp (SDATA (value), "on")))
       XSynchronize (dpyinfo->display, True);
   }
-  
+
   UNBLOCK_INPUT;
 
   return dpyinfo;
@@ -14948,7 +15655,7 @@ x_delete_display (dpyinfo)
   if (dpyinfo->xim)
     xim_close_dpy (dpyinfo);
 #endif
-  
+
   xfree (dpyinfo->font_table);
   xfree (dpyinfo->x_id_name);
   xfree (dpyinfo->color_cells);
@@ -15011,7 +15718,7 @@ x_initialize ()
   x_noop_count = 0;
   last_tool_bar_item = -1;
   any_help_event_p = 0;
-  
+
   /* Try to use interrupt input; if we can't, then start polling.  */
   Fset_input_mode (Qt, Qnil, Qt, Qnil);
 
@@ -15019,7 +15726,7 @@ x_initialize ()
   XtToolkitInitialize ();
 
   Xt_app_con = XtCreateApplicationContext ();
-  
+
   /* Register a converter from strings to pixels, which uses
      Emacs' color allocation infrastructure.  */
   XtAppSetTypeConverter (Xt_app_con,
@@ -15041,10 +15748,12 @@ x_initialize ()
     start_atimer (ATIMER_CONTINUOUS, interval, x_process_timeouts, 0);
   }
 #endif
-  
+
 #ifdef USE_TOOLKIT_SCROLL_BARS
+#ifndef USE_GTK
   xaw3d_arrow_scroll = False;
   xaw3d_pick_top = True;
+#endif
 #endif
 
   /* Note that there is no real way portable across R3/R4 to get the
@@ -15055,7 +15764,7 @@ x_initialize ()
   /* Disable Window Change signals;  they are handled by X events.  */
 #ifdef SIGWINCH
   signal (SIGWINCH, SIG_DFL);
-#endif /* ! defined (SIGWINCH) */
+#endif /* SIGWINCH */
 
   signal (SIGPIPE, x_connection_signal);
 
@@ -15080,6 +15789,11 @@ syms_of_xterm ()
   staticpro (&Qvendor_specific_keysyms);
   Qvendor_specific_keysyms = intern ("vendor-specific-keysyms");
 
+  staticpro (&Qutf_8);
+  Qutf_8 = intern ("utf-8");
+  staticpro (&Qlatin_1);
+  Qlatin_1 = intern ("latin-1");
+
   staticpro (&last_mouse_press_frame);
   last_mouse_press_frame = Qnil;
 
@@ -15120,6 +15834,8 @@ Otherwise, value is a symbol describing the X toolkit.  */);
   Vx_toolkit_scroll_bars = intern ("motif");
 #elif defined HAVE_XAW3D
   Vx_toolkit_scroll_bars = intern ("xaw3d");
+#elif USE_GTK
+  Vx_toolkit_scroll_bars = intern ("gtk");
 #else
   Vx_toolkit_scroll_bars = intern ("xaw");
 #endif
@@ -15129,7 +15845,7 @@ Otherwise, value is a symbol describing the X toolkit.  */);
 
   staticpro (&last_mouse_motion_frame);
   last_mouse_motion_frame = Qnil;
-  
+
   Qmodifier_value = intern ("modifier-value");
   Qalt = intern ("alt");
   Fput (Qalt, Qmodifier_value, make_number (alt_modifier));
@@ -15139,28 +15855,28 @@ Otherwise, value is a symbol describing the X toolkit.  */);
   Fput (Qmeta, Qmodifier_value, make_number (meta_modifier));
   Qsuper = intern ("super");
   Fput (Qsuper, Qmodifier_value, make_number (super_modifier));
-  
+
   DEFVAR_LISP ("x-alt-keysym", &Vx_alt_keysym,
     doc: /* Which keys Emacs uses for the alt modifier.
 This should be one of the symbols `alt', `hyper', `meta', `super'.
 For example, `alt' means use the Alt_L and Alt_R keysyms.  The default
 is nil, which is the same as `alt'.  */);
   Vx_alt_keysym = Qnil;
-  
+
   DEFVAR_LISP ("x-hyper-keysym", &Vx_hyper_keysym,
     doc: /* Which keys Emacs uses for the hyper modifier.
 This should be one of the symbols `alt', `hyper', `meta', `super'.
 For example, `hyper' means use the Hyper_L and Hyper_R keysyms.  The
 default is nil, which is the same as `hyper'.  */);
   Vx_hyper_keysym = Qnil;
-  
+
   DEFVAR_LISP ("x-meta-keysym", &Vx_meta_keysym,
     doc: /* Which keys Emacs uses for the meta modifier.
 This should be one of the symbols `alt', `hyper', `meta', `super'.
 For example, `meta' means use the Meta_L and Meta_R keysyms.  The
 default is nil, which is the same as `meta'.  */);
   Vx_meta_keysym = Qnil;
-  
+
   DEFVAR_LISP ("x-super-keysym", &Vx_super_keysym,
     doc: /* Which keys Emacs uses for the super modifier.
 This should be one of the symbols `alt', `hyper', `meta', `super'.
@@ -15168,6 +15884,12 @@ For example, `super' means use the Super_L and Super_R keysyms.  The
 default is nil, which is the same as `super'.  */);
   Vx_super_keysym = Qnil;
 
+  DEFVAR_LISP ("x-keysym-table", &Vx_keysym_table,
+    doc: /* Hash table of character codes indexed by X keysym codes.  */);
+  Vx_keysym_table = make_hash_table (Qeql, make_number (900),
+                                    make_float (DEFAULT_REHASH_SIZE),
+                                    make_float (DEFAULT_REHASH_THRESHOLD),
+                                    Qnil, Qnil, Qnil);
 }
 
 #endif /* HAVE_X_WINDOWS */