(enum fringe_bitmap_type): Define here.
[bpt/emacs.git] / src / xterm.c
index 2a700b1..f6566c1 100644 (file)
@@ -1,5 +1,5 @@
 /* X Communication module for terminals which understand the X protocol.
-   Copyright (C) 1989, 93, 94, 95, 96, 1997, 1998, 1999, 2000, 2001
+   Copyright (C) 1989, 93, 94, 95, 96, 1997, 1998, 1999, 2000, 2001, 2002
    Free Software Foundation, Inc.
 
 This file is part of GNU Emacs.
@@ -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
@@ -155,11 +161,11 @@ extern void _XEditResCheckMessages ();
 #define BETWEEN(X, LOWER, UPPER)  ((X) >= (LOWER) && (X) < (UPPER))
 
 \f
-/* Bitmaps for truncated lines.  */
+/* Fringe bitmaps.  */
 
-enum bitmap_type
+enum fringe_bitmap_type
 {
-  NO_BITMAP,
+  NO_FRINGE_BITMAP,
   LEFT_TRUNCATION_BITMAP,
   RIGHT_TRUNCATION_BITMAP,
   OVERLAY_ARROW_BITMAP,
@@ -172,9 +178,17 @@ enum bitmap_type
    `indicate-empty-lines' is non-nil.  */
 
 #define zv_width 8
-#define zv_height 8
+#define zv_height 72
+#define zv_period 3
 static unsigned char zv_bits[] = {
-   0x00, 0x00, 0x1e, 0x1e, 0x1e, 0x1e, 0x00, 0x00};
+  0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00,
+  0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00,
+  0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00,
+  0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00,
+  0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00,
+  0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00,
+  0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00,
+  0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00};
 
 /* An arrow like this: `<-'.  */
 
@@ -230,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;
@@ -245,6 +259,13 @@ static Lisp_Object previous_help_echo;
 
 static int any_help_event_p;
 
+/* Non-zero means autoselect window with the mouse cursor.  */
+
+int mouse_autoselect_window;
+
+/* Last window where we saw the mouse.  Used by mouse-autoselect-window.  */
+static Lisp_Object last_window;
+
 /* Non-zero means draw block and hollow cursor as wide as the glyph
    under it.  For example, if a block cursor is over a tab, it will be
    drawn as wide as that tab on the display.  */
@@ -274,8 +295,6 @@ Lisp_Object x_display_name_list;
 
 extern struct frame *updating_frame;
 
-extern int waiting_for_input;
-
 /* This is a frame waiting to be auto-raised, within XTread_socket.  */
 
 struct frame *pending_autoraise_frame;
@@ -286,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.  */
 
@@ -367,15 +386,22 @@ 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;
 
 /* A mask of extra modifier bits to put into every keyboard char.  */
 
-extern int extra_keyboard_modifiers;
+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 *));
@@ -411,7 +437,8 @@ static int fast_find_string_pos P_ ((struct window *, int, Lisp_Object,
 static void set_output_cursor P_ ((struct cursor_pos *));
 static struct glyph *x_y_to_hpos_vpos P_ ((struct window *, int, int,
                                           int *, int *, int *, int));
-static void note_mode_line_highlight P_ ((struct window *, int, int));
+static void note_mode_line_or_margin_highlight P_ ((struct window *, int,
+                                                   int, int));
 static void note_mouse_highlight P_ ((struct frame *, int, int));
 static void note_tool_bar_highlight P_ ((struct frame *f, int, int));
 static void x_handle_tool_bar_click P_ ((struct frame *, XButtonEvent *));
@@ -446,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));
@@ -463,14 +503,15 @@ 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_bitmap P_ ((struct window *, struct glyph_row *, 
-                              enum bitmap_type));
+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 *,
                               GC, int));
 static int x_phys_cursor_in_rect_p P_ ((struct window *, XRectangle *));
-static void x_draw_row_bitmaps P_ ((struct window *, struct glyph_row *));
-static void notice_overwritten_cursor P_ ((struct window *, int, int));
+static void x_draw_row_fringe_bitmaps P_ ((struct window *, struct glyph_row *));
+static void notice_overwritten_cursor P_ ((struct window *, enum glyph_row_area,
+                                          int, int, int, int));
 static void x_flush P_ ((struct frame *f));
 static void x_update_begin P_ ((struct frame *));
 static void x_update_window_begin P_ ((struct window *));
@@ -483,6 +524,14 @@ static void x_scroll_bar_report_motion P_ ((struct frame **, Lisp_Object *,
                                            enum scroll_bar_part *,
                                            Lisp_Object *, 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.  */
 
@@ -510,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
 /***********************************************************************
@@ -522,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;
@@ -568,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
@@ -593,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);
 
@@ -615,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;
@@ -648,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
@@ -659,15 +708,15 @@ x_draw_vertical_border (w)
       int x0, x1, y0, y1;
 
       window_box_edges (w, -1, &x0, &y0, &x1, &y1);
-      x1 += FRAME_X_RIGHT_FLAGS_AREA_WIDTH (f);
+      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
@@ -687,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;
@@ -696,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)
@@ -709,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;
 }
 
@@ -758,7 +807,7 @@ XTframe_up_to_date (f)
 
 
 /* Draw truncation mark bitmaps, continuation mark bitmaps, overlay
-   arrow bitmaps, or clear the areas where they would be displayed
+   arrow bitmaps, or clear the fringes if no bitmaps are required
    before DESIRED_ROW is made current.  The window being updated is
    found in updated_window.  This function It is called from
    update_window_line only if it is known that there are differences
@@ -771,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_bitmaps (w, desired_row);
+      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,
@@ -801,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);
@@ -813,22 +862,24 @@ x_after_update_window_line (desired_row)
 }
 
 
-/* Draw the bitmap WHICH in one of the areas to the left or right of
+/* Draw the bitmap WHICH in one of the left or right fringes of
    window W.  ROW is the glyph row for which to display the bitmap; it
    determines the vertical position at which the bitmap has to be
    drawn.  */
 
 static void
-x_draw_bitmap (w, row, which)
+x_draw_fringe_bitmap (w, row, which, left_p)
      struct window *w;
      struct glyph_row *row;
-     enum bitmap_type which;
+     enum fringe_bitmap_type which;
+     int left_p;
 {
   struct frame *f = XFRAME (WINDOW_FRAME (w));
   Display *display = FRAME_X_DISPLAY (f);
   Window window = FRAME_X_WINDOW (f);
   int x, y, wd, h, dy;
-  unsigned char *bits;
+  int b1, b2;
+  unsigned char *bits = NULL;
   Pixmap pixmap;
   GC gc = f->output_data.x->normal_gc;
   struct face *face;
@@ -837,93 +888,151 @@ x_draw_bitmap (w, row, which)
   /* Must clip because of partially visible lines.  */
   x_clip_to_row (w, row, gc, 1);
 
+  /* Convert row to frame coordinates.  */
+  y = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
+
   switch (which)
     {
+    case NO_FRINGE_BITMAP:
+      wd = 0;
+      h = 0;
+      break;
+
     case LEFT_TRUNCATION_BITMAP:
       wd = left_width;
       h = left_height;
       bits = left_bits;
-      x = (WINDOW_TO_FRAME_PIXEL_X (w, 0)
-          - wd
-          - (FRAME_X_LEFT_FLAGS_AREA_WIDTH (f) - wd) / 2);
       break;
-      
+
     case OVERLAY_ARROW_BITMAP:
-      wd = left_width;
-      h = left_height;
+      wd = ov_width;
+      h = ov_height;
       bits = ov_bits;
-      x = (WINDOW_TO_FRAME_PIXEL_X (w, 0)
-          - wd
-          - (FRAME_X_LEFT_FLAGS_AREA_WIDTH (f) - wd) / 2);
       break;
-      
+
     case RIGHT_TRUNCATION_BITMAP:
       wd = right_width;
       h = right_height;
       bits = right_bits;
-      x = window_box_right (w, -1);
-      x += (FRAME_X_RIGHT_FLAGS_AREA_WIDTH (f) - wd) / 2;
       break;
 
     case CONTINUED_LINE_BITMAP:
-      wd = right_width;
-      h = right_height;
+      wd = continued_width;
+      h = continued_height;
       bits = continued_bits;
-      x = window_box_right (w, -1);
-      x += (FRAME_X_RIGHT_FLAGS_AREA_WIDTH (f) - wd) / 2;
       break;
-      
+
     case CONTINUATION_LINE_BITMAP:
       wd = continuation_width;
       h = continuation_height;
       bits = continuation_bits;
-      x = (WINDOW_TO_FRAME_PIXEL_X (w, 0)
-          - wd
-          - (FRAME_X_LEFT_FLAGS_AREA_WIDTH (f) - wd) / 2);
       break;
 
     case ZV_LINE_BITMAP:
       wd = zv_width;
-      h = zv_height;
-      bits = zv_bits;
-      x = (WINDOW_TO_FRAME_PIXEL_X (w, 0)
-          - wd
-          - (FRAME_X_LEFT_FLAGS_AREA_WIDTH (f) - wd) / 2);
+      h = zv_height - (y % zv_period);
+      bits = zv_bits + (y % zv_period);
       break;
 
     default:
       abort ();
     }
 
-  /* Convert to frame coordinates.  Set dy to the offset in the row to
-     start drawing the bitmap.  */
-  y = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
+  /* Clip bitmap if too high.  */
+  if (h > row->height)
+    h = row->height;
+
+  /* Set dy to the offset in the row to start drawing the bitmap.  */
   dy = (row->height - h) / 2;
 
-  /* Draw the bitmap.  I believe these small pixmaps can be cached
-     by the server.  */
-  face = FACE_FROM_ID (f, BITMAP_AREA_FACE_ID);
-  pixmap = XCreatePixmapFromBitmapData (display, window, bits, wd, h,
-                                       face->foreground,
-                                       face->background, depth);
-  XCopyArea (display, pixmap, window, gc, 0, 0, wd, h, x, y + dy);
-  XFreePixmap (display, pixmap);
+  face = FACE_FROM_ID (f, FRINGE_FACE_ID);
+  PREPARE_FACE_FOR_DISPLAY (f, face);
+
+  /* Clear left fringe if no bitmap to draw or if bitmap doesn't fill
+     the fringe.  */
+  b1 = b2 = -1;
+  if (left_p)
+    {
+      if (wd > FRAME_X_LEFT_FRINGE_WIDTH (f))
+       wd = FRAME_X_LEFT_FRINGE_WIDTH (f);
+      x = (WINDOW_TO_FRAME_PIXEL_X (w, 0)
+          - wd
+          - (FRAME_X_LEFT_FRINGE_WIDTH (f) - wd) / 2);
+      if (wd < FRAME_X_LEFT_FRINGE_WIDTH (f) || row->height > h)
+       {
+         /* If W has a vertical border to its left, don't draw over it.  */
+         int border = ((XFASTINT (w->left) > 0
+                        && !FRAME_HAS_VERTICAL_SCROLL_BARS (f))
+                       ? 1 : 0);
+         b1 = (window_box_left (w, -1)
+               - FRAME_X_LEFT_FRINGE_WIDTH (f)
+               + border);
+         b2 = (FRAME_X_LEFT_FRINGE_WIDTH (f) - border);
+       }
+    }
+  else
+    {
+      if (wd > FRAME_X_RIGHT_FRINGE_WIDTH (f))
+       wd = FRAME_X_RIGHT_FRINGE_WIDTH (f);
+      x = (window_box_right (w, -1)
+          + (FRAME_X_RIGHT_FRINGE_WIDTH (f) - wd) / 2);
+      /* Clear right fringe if no bitmap to draw of if bitmap doesn't fill
+        the fringe.  */
+      if (wd < FRAME_X_RIGHT_FRINGE_WIDTH (f) || row->height > h)
+       {
+         b1 = window_box_right (w, -1);
+         b2 = FRAME_X_RIGHT_FRINGE_WIDTH (f);
+       }
+    }
+
+  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
+        FillSolid in x_draw_glyph_string_background.  */
+      if (face->stipple)
+       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,
+                                                      row->y)),
+                     b2,
+                     row->visible_height);
+      if (!face->stipple)
+       XSetForeground (display, face->gc, face->foreground);
+    }
+
+  if (which != NO_FRINGE_BITMAP)
+    {
+      /* Draw the bitmap.  I believe these small pixmaps can be cached
+        by the server.  */
+      pixmap = XCreatePixmapFromBitmapData (display, window, bits, wd, h,
+                                           face->foreground,
+                                           face->background, depth);
+      XCopyArea (display, pixmap, window, gc, 0, 0, wd, h, x, y + dy);
+      XFreePixmap (display, pixmap);
+    }
+
   XSetClipMask (display, gc, None);
 }
 
 
-/* Draw flags bitmaps for glyph row ROW on window W.  Call this
+/* Draw fringe bitmaps for glyph row ROW on window W.  Call this
    function with input blocked.  */
 
 static void
-x_draw_row_bitmaps (w, row)
+x_draw_row_fringe_bitmaps (w, row)
      struct window *w;
      struct glyph_row *row;
 {
   struct frame *f = XFRAME (w->frame);
-  enum bitmap_type bitmap;
-  struct face *face;
-  int header_line_height = -1;
+  enum fringe_bitmap_type bitmap;
 
   xassert (interrupt_input_blocked);
 
@@ -932,103 +1041,37 @@ x_draw_row_bitmaps (w, row)
   if (row->visible_height <= 0)
     return;
 
-  face = FACE_FROM_ID (f, BITMAP_AREA_FACE_ID);
-  PREPARE_FACE_FOR_DISPLAY (f, face);
-
-  /* Decide which bitmap to draw at the left side.  */
-  if (row->overlay_arrow_p)
-    bitmap = OVERLAY_ARROW_BITMAP;
-  else if (row->truncated_on_left_p)
-    bitmap = LEFT_TRUNCATION_BITMAP;
-  else if (MATRIX_ROW_CONTINUATION_LINE_P (row))
-    bitmap = CONTINUATION_LINE_BITMAP;
-  else if (row->indicate_empty_line_p)
-    bitmap = ZV_LINE_BITMAP;
-  else
-    bitmap = NO_BITMAP;
-
-  /* Clear flags area if no bitmap to draw or if bitmap doesn't fill
-     the flags area.  */
-  if (bitmap == NO_BITMAP
-      || FRAME_FLAGS_BITMAP_WIDTH (f) < FRAME_X_LEFT_FLAGS_AREA_WIDTH (f)
-      || row->height > FRAME_FLAGS_BITMAP_HEIGHT (f))
-    {
-      /* If W has a vertical border to its left, don't draw over it.  */
-      int border = ((XFASTINT (w->left) > 0
-                    && !FRAME_HAS_VERTICAL_SCROLL_BARS (f))
-                   ? 1 : 0);
-      int left = window_box_left (w, -1);
-
-      if (header_line_height < 0)
-       header_line_height = WINDOW_DISPLAY_HEADER_LINE_HEIGHT (w);
-      
-      /* In case the same realized face is used for bitmap areas and
-        for something displayed in the text (e.g. face `region' on
-        mono-displays, the fill style may have been changed to
-        FillSolid in x_draw_glyph_string_background.  */
-      if (face->stipple)
-       XSetFillStyle (FRAME_X_DISPLAY (f), face->gc, FillOpaqueStippled);
+  if (FRAME_X_LEFT_FRINGE_WIDTH (f) != 0)
+    {
+      /* Decide which bitmap to draw in the left fringe.  */
+      if (row->overlay_arrow_p)
+       bitmap = OVERLAY_ARROW_BITMAP;
+      else if (row->truncated_on_left_p)
+       bitmap = LEFT_TRUNCATION_BITMAP;
+      else if (MATRIX_ROW_CONTINUATION_LINE_P (row))
+       bitmap = CONTINUATION_LINE_BITMAP;
+      else if (row->indicate_empty_line_p)
+       bitmap = ZV_LINE_BITMAP;
       else
-       XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->background);
-      
-      XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
-                     face->gc,
-                     (left
-                      - FRAME_X_LEFT_FLAGS_AREA_WIDTH (f)
-                      + border),
-                     WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
-                                                      row->y)),
-                     FRAME_X_LEFT_FLAGS_AREA_WIDTH (f) - border,
-                     row->visible_height);
-      if (!face->stipple)
-       XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->foreground);
-    }
+       bitmap = NO_FRINGE_BITMAP;
 
-  /* Draw the left bitmap.  */
-  if (bitmap != NO_BITMAP)
-    x_draw_bitmap (w, row, bitmap);
-
-  /* Decide which bitmap to draw at the right side.  */
-  if (row->truncated_on_right_p)
-    bitmap = RIGHT_TRUNCATION_BITMAP;
-  else if (row->continued_p)
-    bitmap = CONTINUED_LINE_BITMAP;
-  else
-    bitmap = NO_BITMAP;
+      x_draw_fringe_bitmap (w, row, bitmap, 1);
+    }
 
-  /* Clear flags area if no bitmap to draw of if bitmap doesn't fill
-     the flags area.  */
-  if (bitmap == NO_BITMAP
-      || FRAME_FLAGS_BITMAP_WIDTH (f) < FRAME_X_RIGHT_FLAGS_AREA_WIDTH (f)
-      || row->height > FRAME_FLAGS_BITMAP_HEIGHT (f))
+  if (FRAME_X_RIGHT_FRINGE_WIDTH (f) != 0)
     {
-      int right = window_box_right (w, -1);
-
-      if (header_line_height < 0)
-       header_line_height = WINDOW_DISPLAY_HEADER_LINE_HEIGHT (w);
-
-      /* In case the same realized face is used for bitmap areas and
-        for something displayed in the text (e.g. face `region' on
-        mono-displays, the fill style may have been changed to
-        FillSolid in x_draw_glyph_string_background.  */
-      if (face->stipple)
-       XSetFillStyle (FRAME_X_DISPLAY (f), face->gc, FillOpaqueStippled);
+      /* Decide which bitmap to draw in the right fringe.  */
+      if (row->truncated_on_right_p)
+       bitmap = RIGHT_TRUNCATION_BITMAP;
+      else if (row->continued_p)
+       bitmap = CONTINUED_LINE_BITMAP;
+      else if (row->indicate_empty_line_p && FRAME_X_LEFT_FRINGE_WIDTH (f) == 0)
+       bitmap = ZV_LINE_BITMAP;
       else
-       XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->background);
-      XFillRectangle (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
-                     face->gc,
-                     right,
-                     WINDOW_TO_FRAME_PIXEL_Y (w, max (header_line_height,
-                                                      row->y)),
-                     FRAME_X_RIGHT_FLAGS_AREA_WIDTH (f),
-                     row->visible_height);
-      if (!face->stipple)
-       XSetForeground (FRAME_X_DISPLAY (f), face->gc, face->foreground);
-    }
+       bitmap = NO_FRINGE_BITMAP;
 
-  /* Draw the right bitmap.  */
-  if (bitmap != NO_BITMAP)
-    x_draw_bitmap (w, row, bitmap);
+      x_draw_fringe_bitmap (w, row, bitmap, 0);
+    }
 }
 
 \f
@@ -1075,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
@@ -1123,7 +1166,8 @@ static struct face *x_get_glyph_face_and_encoding P_ ((struct frame *,
                                                       XChar2b *,
                                                       int *));
 static struct face *x_get_char_face_and_encoding P_ ((struct frame *, int,
-                                                     int, XChar2b *, int));
+                                                     int, XChar2b *, int,
+                                                     int));
 static XCharStruct *x_per_char_metric P_ ((XFontStruct *, XChar2b *));
 static void x_encode_char P_ ((int, XChar2b *, struct font_info *));
 static void x_append_glyph P_ ((struct it *));
@@ -1229,6 +1273,7 @@ x_encode_char (c, char2b, font_info)
        {
          ccl->reg[0] = charset;
          ccl->reg[1] = char2b->byte2;
+         ccl->reg[2] = -1;
        }
       else
        {
@@ -1236,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 */
@@ -1251,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;
     }
@@ -1264,15 +1309,17 @@ x_encode_char (c, char2b, font_info)
 
 /* Get face and two-byte form of character C in face FACE_ID on frame
    F.  The encoding of C is returned in *CHAR2B.  MULTIBYTE_P non-zero
-   means we want to display multibyte text.  Value is a pointer to a
-   realized face that is ready for display.  */
+   means we want to display multibyte text.  DISPLAY_P non-zero means
+   make sure that X resources for the face returned are allocated.
+   Value is a pointer to a realized face that is ready for display if
+   DISPLAY_P is non-zero.  */
 
 static INLINE struct face *
-x_get_char_face_and_encoding (f, c, face_id, char2b, multibyte_p)
+x_get_char_face_and_encoding (f, c, face_id, char2b, multibyte_p, display_p)
      struct frame *f;
      int c, face_id;
      XChar2b *char2b;
-     int multibyte_p;
+     int multibyte_p, display_p;
 {
   struct face *face = FACE_FROM_ID (f, face_id);
 
@@ -1294,7 +1341,7 @@ x_get_char_face_and_encoding (f, c, face_id, char2b, multibyte_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);
@@ -1314,9 +1361,12 @@ x_get_char_face_and_encoding (f, c, face_id, char2b, multibyte_p)
     }
 
   /* Make sure X resources of the face are allocated.  */
-  xassert (face != NULL);
-  PREPARE_FACE_FOR_DISPLAY (f, face);
-  
+  if (display_p)
+    {
+      xassert (face != NULL);
+      PREPARE_FACE_FOR_DISPLAY (f, face);
+    }
+
   return face;
 }
 
@@ -1357,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);
@@ -1388,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
@@ -1397,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])
     {
@@ -1422,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
@@ -1431,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])
     {
@@ -1503,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)
@@ -1511,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)
@@ -1519,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])
        {
@@ -1548,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;
@@ -1563,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])
     {
@@ -1592,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
@@ -1602,12 +1652,12 @@ 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.
 
-   5. `:relative-height FACTOR' specifies that the height of the the
+   5. `:relative-height FACTOR' specifies that the height of the
    stretch should be FACTOR times the height of the characters having
    the glyph property.
 
@@ -1640,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);
@@ -1658,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)
        {
@@ -1680,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)
@@ -1691,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),
@@ -1725,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);
 }
 
@@ -1822,11 +1872,11 @@ 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,
-                                   it->multibyte_p);
+                                   it->multibyte_p, 0);
       font = face->font;
 
       /* When no suitable font found, use the default font.  */
@@ -1883,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;
@@ -1904,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)
            {
@@ -1913,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
@@ -1933,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)
            {
@@ -1952,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
@@ -2011,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);
        }
@@ -2053,12 +2103,12 @@ 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);
       x_get_char_face_and_encoding (it->f, it->char_to_display,
-                                   it->face_id, &char2b, it->multibyte_p);
+                                   it->face_id, &char2b, it->multibyte_p, 0);
       font = face->font;
 
       /* When no suitable font found, use the default font.  */
@@ -2118,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)
@@ -2143,10 +2193,10 @@ 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);
+                                           it->multibyte_p, 0);
              font = face->font;
              if (font == NULL)
                {
@@ -2284,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);
     }
@@ -2311,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);
@@ -2344,7 +2394,7 @@ x_estimate_mode_line_height (f, face_id)
              height += 2 * face->box_line_width;
          }
       }
-  
+
   return height;
 }
 
@@ -2514,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,
@@ -2670,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;
 
@@ -2683,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
@@ -2700,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;
     }
 
@@ -2729,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;
 }
 
@@ -2743,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;
@@ -2792,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;
 
@@ -2802,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)
@@ -2885,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;
@@ -2926,7 +2976,7 @@ x_get_glyph_overhangs (glyph, f, left, right)
      int *left, *right;
 {
   *left = *right = 0;
-  
+
   if (glyph->type == CHAR_GLYPH)
     {
       XFontStruct *font;
@@ -2959,7 +3009,7 @@ x_left_overwritten (s)
      struct glyph_string *s;
 {
   int k;
-    
+
   if (s->left_overhang)
     {
       int x = 0, i;
@@ -3021,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;
 
@@ -3184,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);
+       }
     }
 }
 
@@ -3219,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);
+       }
     }
 }
 
@@ -3246,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
@@ -3389,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",
@@ -3405,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
@@ -3413,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;
 }
@@ -3476,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);
     }
@@ -3532,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.
@@ -3572,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;
@@ -3585,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
@@ -3602,7 +3671,7 @@ x_alloc_nearest_color_1 (dpy, cmap, color)
   if (rc)
     register_color (color->pixel);
 #endif /* DEBUG_X_COLORS */
-  
+
   return rc;
 }
 
@@ -3751,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);
@@ -3761,7 +3830,7 @@ x_alloc_lighter_color (f, display, cmap, pixel, factor, delta)
        success_p = 1;
       *pixel = new.pixel;
     }
-  
+
   return success_p;
 }
 
@@ -3772,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;
@@ -3812,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;
@@ -3836,12 +3905,13 @@ x_setup_relief_colors (s)
   if (s->face->use_box_color_for_shadows_p)
     color = s->face->box_color;
   else if (s->first_glyph->type == IMAGE_GLYPH
+          && s->img->pixmap
           && !IMAGE_BACKGROUND_TRANSPARENT (s->img, s->f, 0))
     color = IMAGE_BACKGROUND (s->img, s->f, 0);
   else
     {
       XGCValues xgcv;
-      
+
       /* Get the background color of the face.  */
       XGetGCValues (s->display, s->gc, GCBackground, &xgcv);
       color = xgcv.background;
@@ -3871,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
@@ -3903,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)
@@ -3931,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);
@@ -3952,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,
@@ -3978,11 +4048,11 @@ x_draw_glyph_string_box (s)
   if (s->row->full_width_p
       && !s->w->pseudo_window_p)
     {
-      last_x += FRAME_X_RIGHT_FLAGS_AREA_WIDTH (s->f);
+      last_x += FRAME_X_RIGHT_FRINGE_WIDTH (s->f);
       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
@@ -4061,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;
@@ -4083,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
@@ -4091,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
@@ -4112,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
@@ -4120,16 +4194,16 @@ 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)
     {
-      thick = tool_bar_button_relief > 0 ? tool_bar_button_relief : 3;
+      thick = tool_bar_button_relief >= 0 ? tool_bar_button_relief : DEFAULT_TOOL_BAR_BUTTON_RELIEF;
       raised_p = s->hl == DRAW_IMAGE_RAISED;
     }
   else
@@ -4137,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);
@@ -4199,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
@@ -4207,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
@@ -4238,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      +-------------------------
@@ -4264,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.  */
@@ -4279,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
@@ -4294,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);
@@ -4321,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;
     }
 
@@ -4380,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.  */
@@ -4404,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;
 }
 
@@ -4497,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;
@@ -4505,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);
@@ -4538,7 +4617,7 @@ x_draw_glyph_string (s)
              XSetForeground (s->display, s->gc, xgcv.foreground);
            }
        }
-  
+
       /* Draw strike-through.  */
       if (s->face->strike_through_p)
        {
@@ -4558,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);
 }
@@ -4574,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
@@ -4593,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);
@@ -4622,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.  */
@@ -4633,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
@@ -4650,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);
@@ -4659,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
@@ -4683,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
@@ -4714,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;
 }
@@ -4737,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;
@@ -4756,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;
 
@@ -4774,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;
@@ -4801,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;
 }
 
@@ -4819,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
@@ -4831,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.  */
@@ -4912,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
@@ -4945,7 +5024,7 @@ x_set_glyph_string_background_width (s, start, last_x)
        int this_face_id = FACE_FOR_CHAR (XFRAME (w->frame), base_face, c); \
        faces[n] = FACE_FROM_ID (XFRAME (w->frame), this_face_id);        \
        x_get_char_face_and_encoding (XFRAME (w->frame), c,               \
-                                     this_face_id, char2b + n, 1);       \
+                                     this_face_id, char2b + n, 1, 1);    \
       }                                                                          \
                                                                          \
     /* Make glyph_strings for each glyph sequence that is drawable by    \
@@ -4968,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.
@@ -5037,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;
@@ -5064,9 +5143,8 @@ x_draw_glyphs (w, x, row, area, start, end, hl, overlaps_p)
   if (row->full_width_p)
     {
       /* X is relative to the left edge of W, without scroll bars
-        or flag areas.  */
+        or fringes.  */
       struct frame *f = XFRAME (w->frame);
-      /* int width = FRAME_FLAGS_AREA_WIDTH (f);  */
       int window_left_x = WINDOW_LEFT_MARGIN (w) * CANON_X_UNIT (f);
 
       x += window_left_x;
@@ -5119,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)
@@ -5188,22 +5266,28 @@ x_draw_glyphs (w, x, row, area, start, end, hl, overlaps_p)
   for (s = head; s; s = s->next)
     x_draw_glyph_string (s);
 
-  if (area == TEXT_AREA && !row->full_width_p)
+  if (area == TEXT_AREA
+      && !row->full_width_p
+      /* When drawing overlapping rows, only the glyph strings'
+        foreground is drawn, which doesn't erase a cursor
+        completely. */
+      && !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 (!row->full_width_p && XFASTINT (w->left_margin_width) != 0)
+
+      if (XFASTINT (w->left_margin_width) != 0)
        {
          int left_area_width = window_box_width (w, LEFT_MARGIN_AREA);
          x0 -= left_area_width;
          x1 -= left_area_width;
        }
 
-      notice_overwritten_cursor (w, x0, x1);
+      notice_overwritten_cursor (w, area, x0, x1,
+                                row->y, MATRIX_ROW_BOTTOM_Y (row));
     }
 
   /* Value is the x-position up to which drawn, relative to AREA of W.
@@ -5216,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;
 }
 
@@ -5230,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)
@@ -5264,7 +5348,7 @@ x_fix_overlapping_area (w, row, area)
          ++i;
        }
     }
-  
+
   UNBLOCK_INPUT;
 }
 
@@ -5284,7 +5368,7 @@ x_write_glyphs (start, len)
 
   xassert (updated_window && updated_row);
   BLOCK_INPUT;
-  
+
   /* Write glyphs.  */
 
   hpos = start - updated_row->glyphs[updated_area];
@@ -5293,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;
@@ -5347,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;
@@ -5397,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);
@@ -5422,13 +5514,16 @@ 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, output_cursor.x, -1);
+    notice_overwritten_cursor (w, updated_area,
+                              output_cursor.x, -1,
+                              updated_row->y,
+                              MATRIX_ROW_BOTTOM_Y (updated_row));
 
   from_x = output_cursor.x;
-     
+
   /* Translate to frame coordinates.  */
   if (updated_row->full_width_p)
     {
@@ -5440,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)
     {
@@ -5514,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;
@@ -5598,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));
@@ -5652,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));
@@ -5674,7 +5769,7 @@ void
 XTring_bell ()
 {
   struct frame *f = SELECTED_FRAME ();
-  
+
   if (FRAME_X_DISPLAY (f))
     {
 #if defined (HAVE_TIMEVAL) && defined (HAVE_SELECT)
@@ -5732,11 +5827,11 @@ x_scroll_run (w, run)
   int x, y, width, height, from_y, to_y, bottom_y;
 
   /* Get frame-relative bounding box of the text display area of W,
-     without mode lines.  Include in this box the flags areas to the
-     left and right of W.  */
+     without mode lines.  Include in this box the left and right
+     fringe of W.  */
   window_box (w, -1, &x, &y, &width, &height);
-  width += FRAME_X_FLAGS_AREA_WIDTH (f);
-  x -= FRAME_X_LEFT_FLAGS_AREA_WIDTH (f);
+  width += FRAME_X_FRINGE_WIDTH (f);
+  x -= FRAME_X_LEFT_FRINGE_WIDTH (f);
 
   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->current_y);
   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, run->desired_y);
@@ -5762,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);
@@ -5773,7 +5868,7 @@ x_scroll_run (w, run)
             x, from_y,
             width, height,
             x, to_y);
-  
+
   UNBLOCK_INPUT;
 }
 
@@ -5782,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
@@ -5877,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))
@@ -5888,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);
     }
 
@@ -5936,7 +6031,7 @@ expose_area (w, row, r, area)
          x += first->pixel_width;
          ++first;
        }
-      
+
       /* Find the last one.  */
       last = first;
       first_x = x;
@@ -5946,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,
@@ -5955,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
@@ -5968,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);
@@ -5980,7 +6075,7 @@ expose_line (w, row, r)
        expose_area (w, row, r, TEXT_AREA);
       if (row->used[RIGHT_MARGIN_AREA])
        expose_area (w, row, r, RIGHT_MARGIN_AREA);
-      x_draw_row_bitmaps (w, row);
+      x_draw_row_fringe_bitmaps (w, row);
     }
 
   return row->mouse_face_p;
@@ -6011,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
@@ -6052,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));
 
@@ -6070,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;
        }
@@ -6103,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);
@@ -6127,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;
@@ -6139,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)
@@ -6156,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;
@@ -6242,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
@@ -6410,12 +6666,28 @@ x_x_to_emacs_modifiers (dpyinfo, state)
      struct x_display_info *dpyinfo;
      unsigned int state;
 {
+  EMACS_UINT mod_meta = meta_modifier;
+  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);
+  if (! EQ (tem, Qnil)) mod_meta = XUINT (tem);
+  tem = Fget (Vx_hyper_keysym, Qmodifier_value);
+  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)
-         | ((state & dpyinfo->meta_mod_mask)  ? meta_modifier  : 0)
-         | ((state & dpyinfo->alt_mod_mask)   ? alt_modifier  : 0)
-         | ((state & dpyinfo->super_mod_mask) ? super_modifier  : 0)
-         | ((state & dpyinfo->hyper_mod_mask) ? hyper_modifier  : 0));
+            | ((state & ControlMask)                   ? ctrl_modifier : 0)
+            | ((state & dpyinfo->meta_mod_mask)                ? mod_meta      : 0)
+            | ((state & dpyinfo->alt_mod_mask)         ? mod_alt       : 0)
+            | ((state & dpyinfo->super_mod_mask)       ? mod_super     : 0)
+            | ((state & dpyinfo->hyper_mod_mask)       ? mod_hyper     : 0));
 }
 
 static unsigned int
@@ -6423,12 +6695,29 @@ x_emacs_to_x_modifiers (dpyinfo, state)
      struct x_display_info *dpyinfo;
      unsigned int state;
 {
-  return (  ((state & alt_modifier)    ? dpyinfo->alt_mod_mask   : 0)
-         | ((state & super_modifier)   ? dpyinfo->super_mod_mask : 0)
-         | ((state & hyper_modifier)   ? dpyinfo->hyper_mod_mask : 0)
-         | ((state & shift_modifier)   ? ShiftMask        : 0)
-         | ((state & ctrl_modifier)    ? ControlMask      : 0)
-         | ((state & meta_modifier)    ? dpyinfo->meta_mod_mask  : 0));
+  EMACS_UINT mod_meta = meta_modifier;
+  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);
+  if (! EQ (tem, Qnil)) mod_meta = XUINT (tem);
+  tem = Fget (Vx_hyper_keysym, Qmodifier_value);
+  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)
+            | ((state & shift_modifier)        ? ShiftMask        : 0)
+            | ((state & ctrl_modifier) ? ControlMask      : 0)
+            | ((state & mod_meta)      ? dpyinfo->meta_mod_mask  : 0));
 }
 
 /* Convert a keysym to its name.  */
@@ -6554,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),
@@ -6612,11 +6901,6 @@ note_mouse_movement (frame, event)
     }
 }
 
-/* This is used for debugging, to turn off note_mouse_highlight.  */
-
- int disable_mouse_highlight;
-
-
 \f
 /************************************************************************
                              Mouse Face
@@ -6696,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;
     }
@@ -6733,78 +7017,52 @@ frame_to_window_pixel_xy (w, x, y)
 }
 
 
-/* Take proper action when mouse has moved to the mode or header line of
-   window W, x-position X.  MODE_LINE_P non-zero means mouse is on the
-   mode line.  X is relative to the start of the text 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.  */
+/* Take proper action when mouse has moved to the mode or header line
+   or marginal area of window W, x-position X and y-position Y.  Area
+   is 1, 3, 6 or 7 for the mode line, header line, left and right
+   marginal area respectively.  X is relative to the start of the text
+   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_highlight (w, x, mode_line_p)
+note_mode_line_or_margin_highlight (w, x, y, portion)
      struct window *w;
-     int x, mode_line_p;
+     int 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 charpos;
+  Lisp_Object string, help, map, pos;
 
-  if (mode_line_p)
-    row = MATRIX_MODE_LINE_ROW (w->current_matrix);
-  else
-    row = MATRIX_HEADER_LINE_ROW (w->current_matrix);
-
-  if (row->enabled_p)
-    {
-      struct glyph *glyph, *end;
-      Lisp_Object help, map;
-      int x0;
-      
-      /* Find the glyph under X.  */
-      glyph = row->glyphs[TEXT_AREA];
-      end = glyph + row->used[TEXT_AREA];
-      x0 = - (FRAME_LEFT_SCROLL_BAR_WIDTH (f) * CANON_X_UNIT (f)
-             + FRAME_X_LEFT_FLAGS_AREA_WIDTH (f));
-      
-      while (glyph < end
-            && x >= x0 + glyph->pixel_width)
-       {
-         x0 += glyph->pixel_width;
-         ++glyph;
-       }
+  if (portion == 1 || portion == 3)
+    string = mode_line_string (w, x, y, portion == 1, &charpos);
+   else
+     string = marginal_area_string (w, x, y, portion, &charpos);
 
-      if (glyph < end
-         && STRINGP (glyph->object)
-         && XSTRING (glyph->object)->intervals
-         && glyph->charpos >= 0
-         && glyph->charpos < XSTRING (glyph->object)->size)
-       {
-         /* 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.  */
-         help = Fget_text_property (make_number (glyph->charpos),
-                                    Qhelp_echo, glyph->object);
-         if (!NILP (help))
-           {
-             help_echo = help;
-             XSETWINDOW (help_echo_window, w);
-             help_echo_object = glyph->object;
-             help_echo_pos = glyph->charpos;
-           }
+  if (STRINGP (string))
+    {
+      pos = make_number (charpos);
 
-         /* Change the mouse pointer according to what is under X/Y.  */
-         map = Fget_text_property (make_number (glyph->charpos),
-                                   Qlocal_map, glyph->object);
-         if (KEYMAPP (map))
-           cursor = f->output_data.x->nontext_cursor;
-         else
-           {
-             map = Fget_text_property (make_number (glyph->charpos),
-                                       Qkeymap, glyph->object);
-             if (KEYMAPP (map))
-               cursor = f->output_data.x->nontext_cursor;
-           }
+      /* 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.  */
+      help = Fget_text_property (pos, Qhelp_echo, string);
+      if (!NILP (help))
+       {
+         help_echo = help;
+         XSETWINDOW (help_echo_window, w);
+         help_echo_object = string;
+         help_echo_pos = charpos;
        }
+
+     /* Change the mouse pointer according to what is under X/Y.  */
+      map = Fget_text_property (pos, Qlocal_map, string);
+      if (!KEYMAPP (map))
+       map = Fget_text_property (pos, Qkeymap, string);
+      if (KEYMAPP (map))
+       cursor = f->output_data.x->nontext_cursor;
     }
 
   XDefineCursor (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f), cursor);
@@ -6829,12 +7087,12 @@ 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
 
-  if (disable_mouse_highlight
+  if (NILP (Vmouse_highlight)
       || !f->glyphs_initialized_p)
     return;
 
@@ -6874,13 +7132,13 @@ note_mouse_highlight (f, x, y)
       return;
     }
 
-  /* Mouse is on the mode or header line?  */
-  if (portion == 1 || portion == 3)
+  /* Mouse is on the mode, header line or margin?  */
+  if (portion == 1 || portion == 3 || portion == 6 || portion == 7)
     {
-      note_mode_line_highlight (w, x, portion == 1);
+      note_mode_line_or_margin_highlight (w, x, y, portion);
       return;
     }
-  
+
   if (portion == 2)
     cursor = f->output_data.x->horizontal_drag_cursor;
   else
@@ -6989,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.  */
@@ -7022,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,
@@ -7032,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);
@@ -7056,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,
@@ -7074,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);
@@ -7084,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);
@@ -7093,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,
@@ -7118,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),
@@ -7129,7 +7389,7 @@ note_mouse_highlight (f, x, y)
                {
                  Lisp_Object before = Foverlay_start (overlay);
                  Lisp_Object after = Foverlay_end (overlay);
-                 Lisp_Object ignore;
+                 int ignore;
 
                  /* Note that we might not be able to find position
                     BEFORE in the glyph matrix if the overlay is
@@ -7142,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,
@@ -7153,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);
@@ -7187,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);
@@ -7220,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;
@@ -7230,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);
 }
@@ -7308,13 +7569,13 @@ 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;
 }
 
 
 /* Handle mouse button event on the tool-bar of frame F, at
-   frame-relative coordinates X/Y.  EVENT_TYPE is either ButtionPress
+   frame-relative coordinates X/Y.  EVENT_TYPE is either ButtonPress
    or ButtonRelase.  */
 
 static void
@@ -7329,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)
@@ -7339,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.  */
@@ -7415,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
@@ -7426,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))
@@ -7436,29 +7697,29 @@ 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.
+
+  /* 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;
   help_echo_pos = -1;
@@ -7479,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
@@ -7512,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.  */
@@ -7589,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;
@@ -7644,9 +7905,9 @@ fast_find_position (w, pos, hpos, vpos, x, y, stop)
 #endif /* not 0 */
 
 
-/* Find the position of the the glyph for position POS in OBJECT in
-   window W's current matrix, and return in *X/*Y the pixel
-   coordinates, and return in *HPOS/*VPOS the column/row of the glyph.
+/* Find the position of the glyph for position POS in OBJECT in
+   window W's current matrix, and return in *X*Y the pixel
+   coordinates, and return in *HPOS*VPOS the column/row of the glyph.
 
    RIGHT_P non-zero means return the position of the right edge of the
    glyph, RIGHT_P zero means return the left edge position.
@@ -7717,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;
     }
@@ -7740,6 +8001,8 @@ show_mouse_face (dpyinfo, draw)
   if (/* If window is in the process of being destroyed, don't bother
         to do anything.  */
       w->current_matrix != NULL
+      /* Don't update mouse highlight if hidden */
+      && (draw != DRAW_MOUSE_FACE || !dpyinfo->mouse_face_hidden)
       /* Recognize when we are called to operate on rows that don't exist
         anymore.  This can happen when a window is split.  */
       && dpyinfo->mouse_face_end_row < w->current_matrix->nrows)
@@ -7749,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;
@@ -7773,10 +8036,11 @@ 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 = draw == DRAW_MOUSE_FACE || DRAW_IMAGE_RAISED;
+             row->mouse_face_p
+               = draw == DRAW_MOUSE_FACE || draw == DRAW_IMAGE_RAISED;
            }
        }
 
@@ -7809,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);
@@ -7888,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)
                {
@@ -8098,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
@@ -8107,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)
@@ -8116,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;
@@ -8148,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)
@@ -8172,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))
@@ -8211,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;
     }
@@ -8243,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.  */
 
@@ -8259,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
@@ -8271,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,
@@ -8285,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";
@@ -8299,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);
@@ -8311,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.  */
@@ -8336,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;
@@ -8357,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);
@@ -8394,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]);
@@ -8424,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)
@@ -8461,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;
@@ -8478,34 +8752,13 @@ xm_scroll_callback (widget, client_data, call_data)
        XtVaGetValues (widget, XmNsliderSize, &slider_size, NULL);
        UNBLOCK_INPUT;
 
-       /* At the max position of the scroll bar, do a line-wise
-          movement.  Without doing anything, we would be called with
-          the same cs->value again and again.  If we want to make
-          sure that we can reach the end of the buffer, we have to do
-          something.
-
-          Implementation note: setting bar->dragging always to
-          cs->value gives a smoother movement at the max position.
-          Setting it to nil when doing line-wise movement gives
-          a better slider behavior. */
-       
-       if (cs->value + slider_size == XM_SB_MAX
-           || (dragging_down_p
-               && last_scroll_bar_part == scroll_bar_down_arrow))
-         {
-           part = scroll_bar_down_arrow;
-           bar->dragging = Qnil;
-         }
-       else
-         {
-           whole = XM_SB_RANGE;
-           portion = min (cs->value - XM_SB_MIN, XM_SB_MAX - slider_size);
-           part = scroll_bar_handle;
-           bar->dragging = make_number (cs->value);
-         }
+       whole = XM_SB_RANGE - slider_size;
+       portion = min (cs->value - XM_SB_MIN, whole);
+       part = scroll_bar_handle;
+       bar->dragging = make_number (cs->value);
       }
       break;
-      
+
     case XmCR_VALUE_CHANGED:
       break;
     };
@@ -8519,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
@@ -8567,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.  */
 
@@ -8577,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;
 
@@ -8602,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;
@@ -8618,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;
@@ -8639,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);
 
@@ -8665,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);
 
@@ -8673,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
@@ -8684,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)
     {
@@ -8768,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);
@@ -8791,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;
@@ -8805,7 +9159,27 @@ x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
   Widget widget = SCROLL_BAR_X_WIDGET (FRAME_X_DISPLAY (f), bar);
   float top, shown;
 
-  if (whole == 0)
+  BLOCK_INPUT;
+
+#ifdef USE_MOTIF
+
+  /* We use an estimate of 30 chars per line rather than the real
+     `portion' value.  This has the disadvantage that the thumb size
+     is not very representative, but it makes our life a lot easier.
+     Otherwise, we have to constantly adjust the thumb size, which
+     we can't always do quickly enough: while dragging, the size of
+     the thumb might prevent the user from dragging the thumb all the
+     way to the end.  but Motif and some versions of Xaw3d don't allow
+     updating the thumb size while dragging.  Also, even if we can update
+     its size, the update will often happen too late.
+     If you don't believe it, check out revision 1.650 of xterm.c to see
+     what hoops we were going through and the still poor behavior we got.  */
+  portion = XFASTINT (XWINDOW (bar->window)->height) * 30;
+  /* When the thumb is at the bottom, position == whole.
+     So we need to increase `whole' to make space for the thumb.  */
+  whole += portion;
+
+  if (whole <= 0)
     top = 0, shown = 1;
   else
     {
@@ -8813,48 +9187,37 @@ x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
       shown = (float) portion / whole;
     }
 
-  BLOCK_INPUT;
-
-#ifdef USE_MOTIF
-  {
-    int size, value;
+  if (NILP (bar->dragging))
+    {
+      int size, value;
 
-    /* Slider size.  Must be in the range [1 .. MAX - MIN] where MAX
-       is the scroll bar's maximum and MIN is the scroll bar's minimum
-       value.  */
-    size = shown * XM_SB_RANGE;
-    size = min (size, XM_SB_RANGE);
-    size = max (size, 1);
+      /* Slider size.  Must be in the range [1 .. MAX - MIN] where MAX
+         is the scroll bar's maximum and MIN is the scroll bar's minimum
+        value.  */
+      size = shown * XM_SB_RANGE;
+      size = min (size, XM_SB_RANGE);
+      size = max (size, 1);
 
-    /* Position.  Must be in the range [MIN .. MAX - SLIDER_SIZE].  */
-    value = top * XM_SB_RANGE;
-    value = min (value, XM_SB_MAX - size);
-    value = max (value, XM_SB_MIN);
+      /* Position.  Must be in the range [MIN .. MAX - SLIDER_SIZE].  */
+      value = top * XM_SB_RANGE;
+      value = min (value, XM_SB_MAX - size);
+      value = max (value, XM_SB_MIN);
 
-    if (NILP (bar->dragging))
       XmScrollBarSetValues (widget, value, size, 0, 0, False);
-    else if (last_scroll_bar_part == scroll_bar_down_arrow)
-      /* This has the negative side effect that the slider value is
-        not what it would be if we scrolled here using line-wise or
-        page-wise movement.  */
-      XmScrollBarSetValues (widget, value, XM_SB_RANGE - value, 0, 0, False);
-    else
-      {
-       /* If currently dragging, only update the slider size.
-          This reduces flicker effects.  */
-       int old_value, old_size, increment, page_increment;
-       
-       XmScrollBarGetValues (widget, &old_value, &old_size,
-                             &increment, &page_increment);
-       XmScrollBarSetValues (widget, old_value,
-                             min (size, XM_SB_RANGE - old_value),
-                             0, 0, False);
-      }
-  }
+    }
 #else /* !USE_MOTIF i.e. use Xaw */
-  {
-    float old_top, old_shown;
-    Dimension height;
+
+  if (whole == 0)
+    top = 0, shown = 1;
+  else
+    {
+      top = (float) position / whole;
+      shown = (float) portion / whole;
+    }
+
+  {
+    float old_top, old_shown;
+    Dimension height;
     XtVaGetValues (widget,
                   XtNtopOfThumb, &old_top,
                   XtNshown, &old_shown,
@@ -8881,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)
              {
@@ -8895,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;
@@ -8909,6 +9272,7 @@ x_set_toolkit_scroll_bar_thumb (bar, portion, position, whole)
 
   UNBLOCK_INPUT;
 }
+#endif /* not USE_GTK */
 
 #endif /* USE_TOOLKIT_SCROLL_BARS */
 
@@ -8917,10 +9281,10 @@ 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
+   WIDTH and HEIGHT are the pixel coordinates and dimensions of the
    scroll bar. */
 
 static struct scroll_bar *
@@ -8945,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);
@@ -8997,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,
@@ -9004,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));
@@ -9015,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
@@ -9138,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;
 
@@ -9189,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))
     {
@@ -9209,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;
@@ -9227,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)
@@ -9262,7 +9650,7 @@ XTset_vertical_scroll_bar (w, portion, whole, position)
        }
 
       /* Clear areas not covered by the scroll bar because it's not as
-        wide as the area reserved for it .  This makes sure a
+        wide as the area reserved for it.  This makes sure a
         previous mode line display is cleared after C-x 2 C-x 1, for
         example.  */
       {
@@ -9279,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;
@@ -9292,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.  */
@@ -9300,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;
     }
 
@@ -9464,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)
@@ -9487,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
@@ -9530,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))
@@ -9540,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
@@ -9557,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
@@ -9694,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.  */
 
@@ -9809,11 +10155,13 @@ x_stop_queuing_selection_requests (display)
 \f
 /* The main X event-reading loop - XTread_socket.  */
 
+#if 0
 /* Time stamp of enter window event.  This is only used by XTread_socket,
    but we have to put it out here, since static variables within functions
    sometimes don't work.  */
 
 static Time enter_timestamp;
+#endif
 
 /* This holds the state XLookupString needs to implement dead keys
    and other tricks known as "compose processing".  _X Window System_
@@ -9821,7 +10169,7 @@ static Time enter_timestamp;
    me that letting the compiler initialize it to zeros will work okay.
 
    This must be defined outside of XTread_socket, for the same reasons
-   given for enter_time stamp, above.  */
+   given for enter_timestamp, above.  */
 
 static XComposeStatus compose_status;
 
@@ -9852,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++;                                                   \
@@ -9865,137 +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.
 
-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;
-  struct frame *f;
-  int event_found = 0;
-  struct x_display_info *dpyinfo;
-  struct coding_system coding;
+   Returns non-zero if the event was filtered, caller shall not process
+   this event further.
+   Returns zero if event is wasn't filtered.  */
 
-  if (interrupt_input_blocked)
-    {
-      interrupt_input_pending = 1;
-      return -1;
-    }
+#ifdef HAVE_X_I18N
+static int
+x_filter_event (dpyinfo, event)
+     struct x_display_info *dpyinfo;
+     XEvent *event;
+{
+  /* 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.  */
 
-  interrupt_input_pending = 0;
-  BLOCK_INPUT;
+  struct frame *f1 = x_any_window_to_frame (dpyinfo,
+                                            event->xclient.window);
 
-  /* So people can tell when we have read the available input.  */
-  input_signal_count++;
+  return XFilterEvent (event, f1 ? FRAME_X_WINDOW (f1) : None);
+}
+#endif
 
-  if (numchars <= 0)
-    abort ();                  /* Don't think this happens.  */
+#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;
 
-  ++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;
+/* 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;
 
-  /* 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 (current_numcharsp)
     {
-#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) */
+#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 ());
 
-#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
+  if (current_finish == X_EVENT_GOTO_OUT || current_finish == X_EVENT_DROP)
+    return GDK_FILTER_REMOVE;
 
-      /* 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);
-       }
+  return GDK_FILTER_CONTINUE;
+}
+#endif /* USE_GTK */
 
-      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;
+/* Handles the XEvent EVENT on display DPYINFO.
 
-         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);
+   *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)
+    {
+    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));
+                /* 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
@@ -10009,1045 +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 */
-#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 (numchars > 0)
-                         {
-                           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;
-                     }
-                 }
+                /* 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
+#ifdef HAVE_X_SM
+                    && ! 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
+                  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;
-
-           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;
+      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;
+        }
+      goto OTHER;
+      break;
 
-           case Expose:
-             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);
-               }
-             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;
-
-           case NoExpose:              /* This occurs when an XCopyArea's
-                                          source area was completely
-                                          available.  */
-             break;
+      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 NoExpose:             /* This occurs when an XCopyArea's
+                                   source area was completely
+                                   available.  */
+      break;
 
-                 /* wait_reading_process_input will notice this and update
-                    the frame's display structures.  */
-                 SET_FRAME_GARBAGED (f);
+    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)
+        {
+          /* 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;
+
+    case KeyPress:
+
+#if defined (USE_X_TOOLKIT) || defined (USE_GTK)
+      /* Dispatch KeyPress events when in menu.  */
+      if (popup_activated ())
+        goto OTHER;
+#endif
 
-                 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;
+      f = x_any_window_to_frame (dpyinfo, event.xkey.window);
 
-           case KeyPress:
-             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 faily 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 */
-                               ))
-                       {
-                         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 ();
-               }
+                             /* 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)
+#endif
+                             ))
+                {
+                  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;
-             }
-
-           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);
-
-                 /* 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;
-                   }
-               }
+        /* 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;
+      }
 
-#ifdef HAVE_X_I18N
-             if (f && FRAME_XIC (f))
-               XSetICFocus (FRAME_XIC (f));
-#endif
+    case FocusIn:
+      {
+        int n;
 
-             goto OTHER;
+        n = x_detect_focus_change (dpyinfo, &event, bufp, numchars);
+        if (n > 0)
+          {
+            bufp += n, count += n, numchars -= 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;
-                   }
+      goto OTHER;
 
-                 /* 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;
-                   }
+    case LeaveNotify:
+      {
+        int 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 (dpyinfo->x_focus_event_frame != 0
-                         && f == dpyinfo->x_focus_frame)
-                       x_new_focus_frame (dpyinfo, 0);
-                   }
-#endif
-               }
-             goto OTHER;
+        n = x_detect_focus_change (dpyinfo, &event, bufp, numchars);
+        if (n > 0)
+          {
+            bufp += n, count += n, numchars -= n;
+          }
+      }
 
-           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 = 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;
+            }
+
+        }
+      goto OTHER;
+
+    case FocusOut:
+      {
+        int n;
 
-#ifdef HAVE_X_I18N
-             if (f && FRAME_XIC (f))
-               XUnsetICFocus (FRAME_XIC (f));
-#endif
+        n = x_detect_focus_change (dpyinfo, &event, bufp, numchars);
+        if (n > 0)
+          {
+            bufp += n, count += n, numchars -= n;
+          }
+      }
 
-             goto OTHER;
+      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 (f)
-                 note_mouse_movement (f, &event.xmotion);
-               else
-                 {
+    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);
+            struct scroll_bar *bar
+              = x_window_to_scroll_bar (event.xmotion.window);
 
-                   if (bar)
-                     x_scroll_bar_note_movement (bar, &event);
+            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;
-             }
+            /* 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)
-               {
+    case ConfigureNotify:
+      f = x_top_window_to_frame (dpyinfo, event.xconfigure.window);
+      if (f)
+        {
 #ifndef USE_X_TOOLKIT
-                 int rows = PIXEL_TO_CHAR_HEIGHT (f, event.xconfigure.height);
-                 int columns = PIXEL_TO_CHAR_WIDTH (f, event.xconfigure.width);
-                 
-                 /* 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);
-                   }
+#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
 
-                 f->output_data.x->pixel_width = event.xconfigure.width;
-                 f->output_data.x->pixel_height = event.xconfigure.height;
-
-                 /* 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);
+          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 (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
-                   xic_set_statusarea (f);
+          if (FRAME_XIC (f) && (FRAME_XIC_STYLE (f) & XIMStatusArea))
+            xic_set_statusarea (f);
 #endif
 
-                 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;
-                   }
+          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 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);
+
+#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;
+          }
+
+#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 */
-               }
-             goto OTHER;
+        else
+          goto OTHER;
+#endif /* USE_X_TOOLKIT || USE_GTK */
+      }
+      break;
 
-           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;
+    case CirculateNotify:
+      goto OTHER;
 
-                       x = event.xbutton.x;
-                       y = event.xbutton.y;
+    case CirculateRequest:
+      goto OTHER;
 
-                       /* 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;
-                         }
-                     }
+    case VisibilityNotify:
+      goto OTHER;
 
-                   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);
+    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;
 
-                   if (bar)
-                     x_scroll_bar_handle_click (bar, &event, &emacs_event);
-#endif /* not USE_TOOLKIT_SCROLL_BARS */
-                 }
+    default:
+    OTHER:
+#ifdef USE_X_TOOLKIT
+    BLOCK_INPUT;
+    if (*finish != X_EVENT_DROP)
+      XtDispatchEvent (&event);
+    UNBLOCK_INPUT;
+#endif /* USE_X_TOOLKIT */
+    break;
+    }
 
-               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);
-                 }
+  goto ret;
 
-               if (numchars >= 1 && emacs_event.kind != no_event)
-                 {
-                   bcopy (&emacs_event, bufp, sizeof (struct input_event));
-                   bufp++;
-                   count++;
-                   numchars--;
-                 }
+ out:
+  *finish = X_EVENT_GOTO_OUT;
 
-#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;
-                 }
+ ret:
+  *bufp_r = bufp;
+  *numcharsp = numchars;
+  *eventp = event;
 
-#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;
+  return count;
+}
 
-           case CirculateNotify:
-             goto OTHER;
-             
-           case CirculateRequest:
-             goto OTHER;
 
-           case VisibilityNotify:
-             goto OTHER;
+/* 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.
 
-           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;
+   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;
 
-           default:
-           OTHER:
-#ifdef USE_X_TOOLKIT
-             BLOCK_INPUT;
-             XtDispatchEvent (&event);
-             UNBLOCK_INPUT;
-#endif /* USE_X_TOOLKIT */
-             break;
-           }
+  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);
        }
+
+#ifdef HAVE_X_SM
+      BLOCK_INPUT;
+      count += x_session_check_input (bufp, &numchars);
+      UNBLOCK_INPUT;
+#endif
+
+#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;
+
+      while (gtk_events_pending ())
+        {
+          static int nr = 0;
+          current_count = count;
+          current_numcharsp = &numchars;
+          current_bufp = &bufp;
+
+          gtk_main_iteration ();
+
+          count = current_count;
+          current_bufp = 0;
+          current_numcharsp = 0;
+
+          if (current_finish == X_EVENT_GOTO_OUT)
+            goto out;
+        }
+
+#else /* not USE_GTK */
+      while (XPending (dpyinfo->display))
+       {
+          int finish;
+
+         XNextEvent (dpyinfo->display, &event);
+
+#ifdef HAVE_X_I18N
+          /* Filter events for the current X input method.  */
+          if (x_filter_event (dpyinfo, &event))
+            break;
+#endif
+         event_found = 1;
+
+          count += handle_one_xevent (dpyinfo,
+                                      &event,
+                                      &bufp,
+                                      &numchars,
+                                      &finish);
+
+          if (finish == X_EVENT_GOTO_OUT)
+            goto out;
+        }
+#endif /* USE_GTK */
     }
 
  out:;
@@ -11095,23 +11786,49 @@ XTread_socket (sd, bufp, numchars, expected)
                             Text Cursor
  ***********************************************************************/
 
-/* Notice if the text cursor of window W has been overwritten by a
-   drawing operation that outputs N glyphs starting at START_X and
-   ending at END_X in the line given by output_cursor.vpos.
-   Coordinates are area-relative.  END_X < 0 means all the rest
-   of the line after START_X has been written.  */
+/* Notice when the text cursor of window W has been completely
+   overwritten by a drawing operation that outputs glyphs in AREA
+   starting at X0 and ending at X1 in the line starting at Y0 and
+   ending at Y1.  X coordinates are area-relative.  X1 < 0 means all
+   the rest of the line after X0 has been written.  Y coordinates
+   are window-relative.  */
 
 static void
-notice_overwritten_cursor (w, start_x, end_x)
+notice_overwritten_cursor (w, area, x0, x1, y0, y1)
      struct window *w;
-     int start_x, end_x;
+     enum glyph_row_area area;
+     int x0, y0, x1, y1;
 {
-  if (updated_area == TEXT_AREA
-      && w->phys_cursor_on_p
-      && output_cursor.vpos == w->phys_cursor.vpos
-      && start_x <= w->phys_cursor.x
-      && end_x > 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;
+       }
+    }
 }
 
 
@@ -11147,8 +11864,8 @@ x_clip_to_row (w, row, gc, whole_line_p)
      the rectangle to the left and increase its width.  */
   if (whole_line_p)
     {
-      clip_rect.x -= FRAME_X_LEFT_FLAGS_AREA_WIDTH (f);
-      clip_rect.width += FRAME_X_FLAGS_AREA_WIDTH (f);
+      clip_rect.x -= FRAME_X_LEFT_FRINGE_WIDTH (f);
+      clip_rect.width += FRAME_X_FRINGE_WIDTH (f);
     }
 
   XSetClipRectangles (FRAME_X_DISPLAY (f), gc, 0, 0, &clip_rect, 1, Unsorted);
@@ -11191,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;
@@ -11217,20 +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;
-  GC gc;
-  int x;
-  unsigned long mask;
-  XGCValues xgcv;
-  Display *dpy;
-  Window window;
-      
+
   /* 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.  */
@@ -11249,14 +11962,24 @@ x_draw_bar_cursor (w, row, width)
     }
   else
     {
-      xgcv.background = f->output_data.x->cursor_pixel;
-      xgcv.foreground = f->output_data.x->cursor_pixel;
+      Display *dpy = FRAME_X_DISPLAY (f);
+      Window window = FRAME_X_WINDOW (f);
+      GC gc = FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc;
+      unsigned long mask = GCForeground | GCBackground | GCGraphicsExposures;
+      struct face *face = FACE_FROM_ID (f, cursor_glyph->face_id);
+      XGCValues xgcv;
+
+      /* If the glyph's background equals the color we normally draw
+        the bar cursor in, the bar cursor in its normal color is
+        invisible.  Use the glyph's foreground color instead in this
+        case, on the assumption that the glyph's colors are chosen so
+        that the glyph is legible.  */
+      if (face->background == f->output_data.x->cursor_pixel)
+       xgcv.background = xgcv.foreground = face->foreground;
+      else
+       xgcv.background = xgcv.foreground = f->output_data.x->cursor_pixel;
       xgcv.graphics_exposures = 0;
-      mask = GCForeground | GCBackground | GCGraphicsExposures;
-      dpy = FRAME_X_DISPLAY (f);
-      window = FRAME_X_WINDOW (f);
-      gc = FRAME_X_DISPLAY_INFO (f)->scratch_cursor_gc;
-  
+
       if (gc)
        XChangeGC (dpy, gc, mask, &xgcv);
       else
@@ -11264,17 +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;
-  
-      x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, w->phys_cursor.x);
+       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,
-                     x,
-                     WINDOW_TO_FRAME_PIXEL_Y (w, w->phys_cursor.y),
-                     min (cursor_glyph->pixel_width, 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);
     }
 }
@@ -11308,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))
@@ -11351,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)
@@ -11362,7 +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
@@ -11370,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)
@@ -11398,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,
@@ -11407,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;
@@ -11429,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)
     {
@@ -11462,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
@@ -11484,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)
     {
@@ -11495,52 +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 if (w->cursor_off_p)
-       new_cursor_type = NO_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);
-       }
-    }
+  /* 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,
@@ -11549,16 +12248,21 @@ x_display_and_set_cursor (w, on, hpos, vpos, x, y)
       && (!on
          || w->phys_cursor.x != x
          || w->phys_cursor.y != y
-         || new_cursor_type != w->phys_cursor_type))
+         || new_cursor_type != w->phys_cursor_type
+         || ((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;
@@ -11579,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))
@@ -11626,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);
 }
@@ -11738,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)
@@ -11774,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);
 }
 
@@ -11798,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;
 }
@@ -11817,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;
 }
 
@@ -11833,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
@@ -11847,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.  */
@@ -11856,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.
@@ -11883,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.  */
@@ -11929,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
@@ -11954,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.  */
@@ -12002,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);
@@ -12094,7 +12807,9 @@ x_new_font (f, fontname)
   f->output_data.x->font = (XFontStruct *) (fontp->font);
   f->output_data.x->baseline_offset = fontp->baseline_offset;
   f->output_data.x->fontset = -1;
-  
+
+  x_compute_fringe_widths (f, 1);
+
   /* Compute the scroll bar width in character columns.  */
   if (f->scroll_bar_pixel_width > 0)
     {
@@ -12154,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.  */
@@ -12166,12 +12881,96 @@ 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);
 }
 
+/* Compute actual fringe widths */
+
+void
+x_compute_fringe_widths (f, redraw)
+     struct frame *f;
+     int redraw;
+{
+  int o_left = f->output_data.x->left_fringe_width;
+  int o_right = f->output_data.x->right_fringe_width;
+  int o_cols = f->output_data.x->fringe_cols;
+
+  Lisp_Object left_fringe = Fassq (Qleft_fringe, f->param_alist);
+  Lisp_Object right_fringe = Fassq (Qright_fringe, f->param_alist);
+  int left_fringe_width, right_fringe_width;
+
+  if (!NILP (left_fringe))
+    left_fringe = Fcdr (left_fringe);
+  if (!NILP (right_fringe))
+    right_fringe = Fcdr (right_fringe);
+
+  left_fringe_width = ((NILP (left_fringe) || !INTEGERP (left_fringe)) ? 8 :
+                      XINT (left_fringe));
+  right_fringe_width = ((NILP (right_fringe) || !INTEGERP (right_fringe)) ? 8 :
+                       XINT (right_fringe));
+
+  if (left_fringe_width || right_fringe_width)
+    {
+      int left_wid = left_fringe_width >= 0 ? left_fringe_width : -left_fringe_width;
+      int right_wid = right_fringe_width >= 0 ? right_fringe_width : -right_fringe_width;
+      int conf_wid = left_wid + right_wid;
+      int font_wid = FONT_WIDTH (f->output_data.x->font);
+      int cols = (left_wid + right_wid + font_wid-1) / font_wid;
+      int real_wid = cols * font_wid;
+      if (left_wid && right_wid)
+       {
+         if (left_fringe_width < 0)
+           {
+             /* Left fringe width is fixed, adjust right fringe if necessary */
+             f->output_data.x->left_fringe_width = left_wid;
+             f->output_data.x->right_fringe_width = real_wid - left_wid;
+           }
+         else if (right_fringe_width < 0)
+           {
+             /* Right fringe width is fixed, adjust left fringe if necessary */
+             f->output_data.x->left_fringe_width = real_wid - right_wid;
+             f->output_data.x->right_fringe_width = right_wid;
+           }
+         else
+           {
+             /* Adjust both fringes with an equal amount.
+                Note that we are doing integer arithmetic here, so don't
+                lose a pixel if the total width is an odd number.  */
+             int fill = real_wid - conf_wid;
+             f->output_data.x->left_fringe_width = left_wid + fill/2;
+             f->output_data.x->right_fringe_width = right_wid + fill - fill/2;
+           }
+       }
+      else if (left_fringe_width)
+       {
+         f->output_data.x->left_fringe_width = real_wid;
+         f->output_data.x->right_fringe_width = 0;
+       }
+      else
+       {
+         f->output_data.x->left_fringe_width = 0;
+         f->output_data.x->right_fringe_width = real_wid;
+       }
+      f->output_data.x->fringe_cols = cols;
+      f->output_data.x->fringes_extra = real_wid;
+    }
+  else
+    {
+      f->output_data.x->left_fringe_width = 0;
+      f->output_data.x->right_fringe_width = 0;
+      f->output_data.x->fringe_cols = 0;
+      f->output_data.x->fringes_extra = 0;
+    }
+
+  if (redraw && FRAME_VISIBLE_P (f))
+    if (o_left != f->output_data.x->left_fringe_width ||
+       o_right != f->output_data.x->right_fringe_width ||
+       o_cols != f->output_data.x->fringe_cols)
+      redraw_frame (f);
+}
 \f
 /***********************************************************************
                           X Input Methods
@@ -12193,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)
     {
@@ -12210,7 +13009,7 @@ xim_destroy_callback (xim, client_data, call_data)
            }
        }
     }
-  
+
   /* No need to call XCloseIM.  */
   dpyinfo->xim = NULL;
   XFree (dpyinfo->xim_styles);
@@ -12219,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.  */
 
@@ -12238,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 */
@@ -12265,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.  */
 
@@ -12281,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
@@ -12294,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)
              {
@@ -12308,7 +13111,7 @@ xim_instantiate_callback (display, client_data, call_data)
                  }
              }
        }
-      
+
       UNBLOCK_INPUT;
     }
 }
@@ -12330,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;
@@ -12348,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 */
@@ -12396,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.
@@ -12470,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
 
@@ -12481,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.  */
@@ -12531,16 +13330,119 @@ 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;
 }
 
+/* Check if we need to resize the frame due to a fullscreen request.
+   If so needed, resize the frame. */
+static void
+x_check_fullscreen (f)
+     struct frame *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
+         x_check_fullscreen_move. */
+      if (f->width != width || f->height != height)
+        {
+          change_frame_size (f, height, width, 0, 1, 0);
+          SET_FRAME_GARBAGED (f);
+          cancel_mouse_face (f);
+
+          /* Wait for the change of frame size to occur */
+          f->output_data.x->want_fullscreen |= FULLSCREEN_WAIT;
+
+        }
+    }
+}
+
+/* If frame parameters are set after the frame is mapped, we need to move
+   the window.  This is done in xfns.c.
+   Some window managers moves the window to the right position, some
+   moves the outer window manager window to the specified position.
+   Here we check that we are in the right spot.  If not, make a second
+   move, assuming we are dealing with the second kind of window manager. */
+static void
+x_check_fullscreen_move (f)
+     struct frame *f;
+{
+  if (f->output_data.x->want_fullscreen & FULLSCREEN_MOVE_WAIT)
+  {
+    int expect_top = f->output_data.x->top_pos;
+    int expect_left = f->output_data.x->left_pos;
+
+    if (f->output_data.x->want_fullscreen & FULLSCREEN_HEIGHT)
+      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);
+
+    /* Just do this once */
+    f->output_data.x->want_fullscreen &= ~FULLSCREEN_MOVE_WAIT;
+  }
+}
+
+
+/* Calculate fullscreen size.  Return in *TOP_POS and *LEFT_POS the
+   wanted positions of the WM window (not emacs window).
+   Return in *WIDTH and *HEIGHT the wanted width and height of Emacs
+   window (FRAME_X_WINDOW).
+ */
+void
+x_fullscreen_adjust (f, width, height, top_pos, left_pos)
+     struct frame *f;
+     int *width;
+     int *height;
+     int *top_pos;
+     int *left_pos;
+{
+  int newwidth = f->width, newheight = f->height;
+
+  *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)
+        - f->output_data.x->y_pixels_diff;
+      newheight = PIXEL_TO_CHAR_HEIGHT (f, ph);
+      *top_pos = 0;
+    }
+
+  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)
+        - f->output_data.x->x_pixels_diff;
+      newwidth = PIXEL_TO_CHAR_WIDTH (f, pw);
+      *left_pos = 0;
+    }
+
+  *width = newwidth;
+  *height = newheight;
+}
+
 
 /* Change the size of frame F's X window to COLS/ROWS in the case F
    doesn't have a widget.  If CHANGE_GRAVITY is 1, we change to
@@ -12562,8 +13464,9 @@ x_set_window_size_1 (f, change_gravity, cols, rows)
        : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
        ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
        : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.x->font)));
-  f->output_data.x->flags_areas_extra
-    = FRAME_FLAGS_AREA_WIDTH (f);
+
+  x_compute_fringe_widths (f, 0);
+
   pixelwidth = CHAR_TO_PIXEL_WIDTH (f, cols);
   pixelheight = CHAR_TO_PIXEL_HEIGHT (f, rows);
 
@@ -12614,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
@@ -12630,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);
@@ -12727,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;
     }
@@ -12746,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;
     }
@@ -12810,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
@@ -12857,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
@@ -12920,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;
   }
@@ -12936,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)
@@ -12961,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,
@@ -12995,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
@@ -13034,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))
@@ -13126,6 +14052,8 @@ x_free_frame_resources (f)
      struct frame *f;
 {
   struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
+  Lisp_Object bar;
+  struct scroll_bar *b;
 
   BLOCK_INPUT;
 
@@ -13135,23 +14063,52 @@ x_free_frame_resources (f)
     {
       if (f->output_data.x->icon_desc)
        XDestroyWindow (FRAME_X_DISPLAY (f), f->output_data.x->icon_desc);
-      
+
+#ifdef USE_X_TOOLKIT
+      /* Explicitly destroy the scroll bars of the frame.  Without
+        this, we get "BadDrawable" errors from the toolkit later on,
+        presumably from expose events generated for the disappearing
+        toolkit scroll bars.  */
+      for (bar = FRAME_SCROLL_BARS (f); !NILP (bar); bar = b->next)
+       {
+         b = XSCROLL_BAR (bar);
+         x_scroll_bar_remove (b);
+       }
+#endif
+
 #ifdef HAVE_X_I18N
       if (FRAME_XIC (f))
        free_frame_xic (f);
 #endif
-      
-      if (FRAME_X_WINDOW (f))
-       XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
-      
+
 #ifdef USE_X_TOOLKIT
       if (f->output_data.x->widget)
        {
          XtDestroyWidget (f->output_data.x->widget);
          f->output_data.x->widget = NULL;
        }
+      /* Tooltips don't have widgets, only a simple X window, even if
+        we are using a toolkit.  */
+      else if (FRAME_X_WINDOW (f))
+       XDestroyWindow (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f));
+
       free_frame_menubar (f);
-#endif /* USE_X_TOOLKIT */
+#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 */
 
       unload_color (f, f->output_data.x->foreground_pixel);
       unload_color (f, f->output_data.x->background_pixel);
@@ -13159,7 +14116,7 @@ x_free_frame_resources (f)
       unload_color (f, f->output_data.x->cursor_foreground_pixel);
       unload_color (f, f->output_data.x->border_pixel);
       unload_color (f, f->output_data.x->mouse_pixel);
-      
+
       if (f->output_data.x->scroll_bar_background_pixel != -1)
        unload_color (f, f->output_data.x->scroll_bar_background_pixel);
       if (f->output_data.x->scroll_bar_foreground_pixel != -1)
@@ -13178,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));
     }
@@ -13188,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)
@@ -13234,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;
@@ -13248,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 */;
@@ -13378,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 */
 
@@ -13409,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)
@@ -13442,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);
 
@@ -13454,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;
@@ -13554,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
@@ -13597,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
@@ -13622,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
@@ -13637,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)
                {
@@ -13657,7 +14632,7 @@ x_list_fonts (f, pattern, size, maxnames)
                    }
                }
            }
-         
+
          if (!try_XLoadQueryFont)
            {
              BLOCK_INPUT;
@@ -13698,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
@@ -13757,7 +14732,7 @@ x_list_fonts (f, pattern, size, maxnames)
     }
 
   return newlist;
-}  
+}
 
 
 #if GLYPH_DEBUG
@@ -13776,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;
 
@@ -13822,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);
       }
@@ -13878,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);
     }
 
@@ -13898,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));
@@ -13970,7 +14945,7 @@ x_load_font (f, fontname, size)
 
        XFree (name);
       }
-    
+
     if (full_name != 0)
       fontp->full_name = full_name;
     else
@@ -14051,10 +15026,10 @@ x_load_font (f, fontname, size)
 
     /* Set global flag fonts_changed_p to non-zero if the font loaded
        has a character with a smaller width than any other character
-       before, or if the font loaded has a smalle>r height than any
+       before, or if the font loaded has a smaller height than any
        other font loaded before.  If this happens, it will make a
        glyph matrix reallocation necessary.  */
-    fonts_changed_p = x_compute_min_glyph_bounds (f);
+    fonts_changed_p |= x_compute_min_glyph_bounds (f);
     UNBLOCK_INPUT;
     return fontp;
   }
@@ -14102,7 +15077,7 @@ x_find_ccl_program (fontp)
                  >= 0)))
        break;
     }
-  
+
   if (! NILP (list))
     {
       struct ccl_program *ccl
@@ -14147,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;
 
@@ -14210,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:
@@ -14231,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.  */
@@ -14246,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)
@@ -14268,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;
@@ -14303,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);
@@ -14315,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);
@@ -14365,6 +15408,7 @@ x_term_init (display_name, xrm_option, resource_name)
   dpyinfo->mouse_face_overlay = Qnil;
   dpyinfo->mouse_face_mouse_x = dpyinfo->mouse_face_mouse_y = 0;
   dpyinfo->mouse_face_defer = 0;
+  dpyinfo->mouse_face_hidden = 0;
   dpyinfo->x_focus_frame = 0;
   dpyinfo->x_focus_event_frame = 0;
   dpyinfo->x_highlight_frame = 0;
@@ -14381,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);
@@ -14399,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
@@ -14424,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
@@ -14451,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);
 
@@ -14466,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);
   }
@@ -14484,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)
@@ -14516,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;
@@ -14542,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;
@@ -14609,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);
@@ -14672,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);
 
@@ -14680,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,
@@ -14702,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
@@ -14716,9 +15764,13 @@ 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);
+
+#ifdef HAVE_X_SM
+  x_session_initialize ();
+#endif
 }
 
 
@@ -14737,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;
 
@@ -14750,6 +15807,10 @@ syms_of_xterm ()
   staticpro (&previous_help_echo);
   help_echo_pos = -1;
 
+  DEFVAR_BOOL ("mouse-autoselect-window", &mouse_autoselect_window,
+    doc: /* *Non-nil means autoselect window with mouse pointer.  */);
+  mouse_autoselect_window = 0;
+
   DEFVAR_BOOL ("x-stretch-cursor", &x_stretch_cursor_p,
     doc: /* *Non-nil means draw block cursor as wide as the glyph under it.
 For example, if a block cursor is over a tab, it will be drawn as
@@ -14759,7 +15820,7 @@ wide as that tab on the display.  */);
   DEFVAR_BOOL ("x-use-underline-position-properties",
               &x_use_underline_position_properties,
      doc: /* *Non-nil means make use of UNDERLINE_POSITION font properties.
-Nil means ignore them.  If you encounter fonts with bogus
+nil means ignore them.  If you encounter fonts with bogus
 UNDERLINE_POSITION font properties, for example 7x13 on XFree prior
 to 4.1, set this to nil.  */);
   x_use_underline_position_properties = 1;
@@ -14773,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
@@ -14782,6 +15845,51 @@ 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));
+  Qhyper = intern ("hyper");
+  Fput (Qhyper, Qmodifier_value, make_number (hyper_modifier));
+  Qmeta = intern ("meta");
+  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'.
+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 */