(Qbar, Qhbar, Qbox, Qhollow, Vblink_cursor_alist):
[bpt/emacs.git] / src / xdisp.c
index 45b179a..e7656d4 100644 (file)
@@ -1,5 +1,5 @@
 /* Display generation from window structure and buffer text.
-   Copyright (C) 1985, 86, 87, 88, 93, 94, 95, 97, 98, 99, 2000, 2001
+   Copyright (C) 1985, 86, 87, 88, 93, 94, 95, 97, 98, 99, 2000, 2001, 2002
    Free Software Foundation, Inc.
 
 This file is part of GNU Emacs.
@@ -33,8 +33,8 @@ Boston, MA 02111-1307, USA.  */
    you as part of the interpreter's command loop or as the result of
    calling Lisp functions like `sit-for'.  The C function `redisplay'
    in xdisp.c is the only entry into the inner redisplay code.  (Or,
-   let's say almost---see the the description of direct update
-   operations, below.).
+   let's say almost---see the description of direct update
+   operations, below.)
 
    The following diagram shows how redisplay code is invoked.  As you
    can see, Lisp calls redisplay and vice versa.  Under window systems
@@ -47,12 +47,12 @@ Boston, MA 02111-1307, USA.  */
    you will encounter bugs which are very hard to explain.
 
             (Direct functions, see below)
-             direct_output_for_insert, 
+             direct_output_for_insert,
              direct_forward_char (dispnew.c)
          +---------------------------------+
           |                                 |
          |                                 V
-   +--------------+   redisplay()   +----------------+
+   +--------------+   redisplay     +----------------+
    | Lisp machine |---------------->| Redisplay code |<--+
    +--------------+   (xdisp.c)     +----------------+   |
          ^                                  |           |
@@ -88,7 +88,7 @@ Boston, MA 02111-1307, USA.  */
 
    Direct operations.
 
-   You will find a lot of of redisplay optimizations when you start
+   You will find a lot of redisplay optimizations when you start
    looking at the innards of redisplay.  The overall goal of all these
    optimizations is to make redisplay fast because it is done
    frequently.
@@ -106,7 +106,7 @@ Boston, MA 02111-1307, USA.  */
    `direct_output_for_insert' and `direct_output_forward_char' in
    dispnew.c.
 
-   
+
    Desired matrices.
 
    Desired matrices are always built per Emacs window.  The function
@@ -123,11 +123,10 @@ Boston, MA 02111-1307, USA.  */
    interface functions taking a iterator structure (struct it)
    argument.
 
-   Iteration over things to be be displayed is then simple.  It is
-   started by initializing an iterator with a call to init_iterator
-   (or init_string_iterator for that matter).  Calls to
-   get_next_display_element fill the iterator structure with relevant
-   information about the next thing to display.  Calls to
+   Iteration over things to be displayed is then simple.  It is
+   started by initializing an iterator with a call to init_iterator.
+   Calls to get_next_display_element fill the iterator structure with
+   relevant information about the next thing to display.  Calls to
    set_iterator_to_next move the iterator to the next thing.
 
    Besides this, an iterator also contains information about the
@@ -195,13 +194,13 @@ Boston, MA 02111-1307, USA.  */
 #ifdef WINDOWSNT
 #include "w32term.h"
 #endif
-#ifdef macintosh
+#ifdef MAC_OS
 #include "macterm.h"
 #endif
 
 #define INFINITY 10000000
 
-#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) || defined (macintosh)
+#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) || defined (MAC_OS)
 extern void set_frame_menubar P_ ((struct frame *f, int, int));
 extern int pending_menu_activation;
 #endif
@@ -212,6 +211,7 @@ extern int command_loop_level;
 extern int minibuffer_auto_raise;
 
 extern Lisp_Object Qface;
+extern Lisp_Object Qmode_line, Qmode_line_inactive, Qheader_line;
 
 extern Lisp_Object Voverriding_local_map;
 extern Lisp_Object Voverriding_local_map_menu_flag;
@@ -221,12 +221,20 @@ Lisp_Object Qoverriding_local_map, Qoverriding_terminal_local_map;
 Lisp_Object Qwindow_scroll_functions, Vwindow_scroll_functions;
 Lisp_Object Qredisplay_end_trigger_functions;
 Lisp_Object Qinhibit_point_motion_hooks;
-Lisp_Object QCeval, Qwhen, QCfile, QCdata;
+Lisp_Object QCeval, Qwhen, QCfile, QCdata, QCpropertize;
 Lisp_Object Qfontified;
 Lisp_Object Qgrow_only;
 Lisp_Object Qinhibit_eval_during_redisplay;
 Lisp_Object Qbuffer_position, Qposition, Qobject;
 
+/* Cursor shapes */
+Lisp_Object Qbar, Qhbar, Qbox, Qhollow;
+
+Lisp_Object Qrisky_local_variable;
+
+/* Holds the list (error).  */
+Lisp_Object list_of_error;
+
 /* Functions called to fontify regions of text.  */
 
 Lisp_Object Vfontification_functions;
@@ -243,7 +251,7 @@ Lisp_Object Vtool_bar_button_margin;
 
 /* Thickness of shadow to draw around tool bar buttons.  */
 
-int tool_bar_button_relief;
+EMACS_INT tool_bar_button_relief;
 
 /* Non-zero means automatically resize tool-bars so that all tool-bar
    items are visible, and no blank lines remain.  */
@@ -261,7 +269,7 @@ int inhibit_eval_during_redisplay;
 /* Names of text properties relevant for redisplay.  */
 
 Lisp_Object Qdisplay, Qrelative_width, Qalign_to;
-extern Lisp_Object Qface, Qinvisible, Qimage, Qwidth;
+extern Lisp_Object Qface, Qinvisible, Qwidth;
 
 /* Symbols used in text property values.  */
 
@@ -292,6 +300,12 @@ int noninteractive_need_newline;
 
 static int message_log_need_newline;
 
+/* Three markers that message_dolog uses.
+   It could allocate them itself, but that causes trouble
+   in handling memory-full errors.  */
+static Lisp_Object message_dolog_marker1;
+static Lisp_Object message_dolog_marker2;
+static Lisp_Object message_dolog_marker3;
 \f
 /* The buffer position of the first character appearing entirely or
    partially on the line of the selected window which contains the
@@ -328,7 +342,7 @@ int truncate_partial_width_windows;
 /* A flag to control how to display unibyte 8-bit character.  */
 
 int unibyte_display_via_language_environment;
+
 /* Nonzero means we have more than one non-mini-buffer-only frame.
    Not guaranteed to be accurate except while parsing
    frame-title-format.  */
@@ -378,19 +392,19 @@ int highlight_nonselected_windows;
 /* If cursor motion alone moves point off frame, try scrolling this
    many lines up or down if that will bring it back.  */
 
-static int scroll_step;
+static EMACS_INT scroll_step;
 
-/* Non-0 means scroll just far enough to bring point back on the
+/* Nonzero means scroll just far enough to bring point back on the
    screen, when appropriate.  */
 
-static int scroll_conservatively;
+static EMACS_INT scroll_conservatively;
 
 /* Recenter the window whenever point gets within this many lines of
    the top or bottom of the window.  This value is translated into a
    pixel value by multiplying it with CANON_Y_UNIT, which means that
    there is really a fixed pixel height scroll margin.  */
 
-int scroll_margin;
+EMACS_INT scroll_margin;
 
 /* Number of windows showing the buffer of the selected window (or
    another buffer with the same base buffer).  keyboard.c refers to
@@ -418,7 +432,6 @@ Lisp_Object minibuf_prompt;
    of the line that contains the prompt.  */
 
 int minibuf_prompt_width;
-int minibuf_prompt_pixel_width;
 
 /* This is the window where the echo area message was displayed.  It
    is always a mini-buffer window, but it may not be the same window
@@ -438,15 +451,19 @@ Lisp_Object Vmessage_stack;
 
 int message_enable_multibyte;
 
-/* True if we should redraw the mode lines on the next redisplay.  */
+/* Nonzero if we should redraw the mode lines on the next redisplay.  */
 
 int update_mode_lines;
 
 /* Nonzero if window sizes or contents have changed since last
-   redisplay that finished */
+   redisplay that finished */
 
 int windows_or_buffers_changed;
 
+/* Nonzero means a frame's cursor type has been changed.  */
+
+int cursor_type_changed;
+
 /* Nonzero after display_mode_line if %l was used and it displayed a
    line number.  */
 
@@ -456,9 +473,9 @@ int line_number_displayed;
 
 Lisp_Object Vline_number_display_limit;
 
-/* line width to consider when repostioning for line number display */
+/* Line width to consider when repositioning for line number display.  */
 
-static int line_number_display_limit_width;
+static EMACS_INT line_number_display_limit_width;
 
 /* Number of lines to keep in the message log buffer.  t means
    infinite.  nil means don't log at all.  */
@@ -517,7 +534,18 @@ static int message_cleared_p;
 /* Non-zero means we want a hollow cursor in windows that are not
    selected.  Zero means there's no cursor in such windows.  */
 
-int cursor_in_non_selected_windows;
+Lisp_Object Vcursor_in_non_selected_windows;
+Lisp_Object Qcursor_in_non_selected_windows;
+
+/* Specifies the desired cursor-type to use to show the blinking
+   cursor off state and cursor shown in non-selected windows.
+   t means to use the default.  */
+
+Lisp_Object Valternate_cursor_type;
+Lisp_Object Qalternate_cursor_type;
+
+/* How to blink the default frame cursor off.  */
+Lisp_Object Vblink_cursor_alist;
 
 /* A scratch glyph row with contents used for generating truncation
    glyphs.  Also used in direct_output_for_insert.  */
@@ -541,7 +569,7 @@ int help_echo_showing_p;
 int current_mode_line_height, current_header_line_height;
 
 /* The maximum distance to look ahead for text properties.  Values
-   that are too small let us call compute_char_face and similar 
+   that are too small let us call compute_char_face and similar
    functions too often which is expensive.  Values that are too large
    let us call compute_char_face and alike too often because we
    might not be interested in text properties that far away.  */
@@ -570,12 +598,19 @@ int trace_move;
 #else
 #define TRACE_MOVE(x)  (void) 0
 #endif
+
 /* Non-zero means automatically scroll windows horizontally to make
    point visible.  */
 
 int automatic_hscrolling_p;
 
+/* How close to the margin can point get before the window is scrolled
+   horizontally.  */
+EMACS_INT hscroll_margin;
+
+/* How much to scroll horizontally when point is inside the above margin.  */
+Lisp_Object Vhscroll_step;
+
 /* A list of symbols, one for each supported image type.  */
 
 Lisp_Object Vimage_types;
@@ -587,6 +622,10 @@ Lisp_Object Vimage_types;
 
 Lisp_Object Vresize_mini_windows;
 
+/* Buffer being redisplayed -- for redisplay_window_error.  */
+
+struct buffer *displayed_buffer;
+
 /* Value returned from text property handlers (see below).  */
 
 enum prop_handled
@@ -655,7 +694,7 @@ enum move_it_result
   /* Move within a line ended at the end of a line that must be
      continued.  */
   MOVE_LINE_CONTINUED,
-  
+
   /* Move within a line ended at the end of a line that would
      be displayed truncated.  */
   MOVE_LINE_TRUNCATED,
@@ -664,6 +703,28 @@ enum move_it_result
   MOVE_NEWLINE_OR_CR
 };
 
+/* This counter is used to clear the face cache every once in a while
+   in redisplay_internal.  It is incremented for each redisplay.
+   Every CLEAR_FACE_CACHE_COUNT full redisplays, the face cache is
+   cleared.  */
+
+#define CLEAR_FACE_CACHE_COUNT 500
+static int clear_face_cache_count;
+
+/* Record the previous terminal frame we displayed.  */
+
+static struct frame *previous_terminal_frame;
+
+/* Non-zero while redisplay_internal is in progress.  */
+
+int redisplaying_p;
+
+/* Non-zero means don't free realized faces.  Bound while freeing
+   realized faces is dangerous because glyph matrices might still
+   reference them.  */
+
+int inhibit_free_realized_faces;
+Lisp_Object Qinhibit_free_realized_faces;
 
 \f
 /* Function prototypes.  */
@@ -687,7 +748,7 @@ static struct text_pos run_window_scroll_functions P_ ((Lisp_Object,
 static void reconsider_clip_changes P_ ((struct window *, struct buffer *));
 static int text_outside_line_unchanged_p P_ ((struct window *, int, int));
 static void store_frame_title_char P_ ((char));
-static int store_frame_title P_ ((unsigned char *, int, int));
+static int store_frame_title P_ ((const unsigned char *, int, int));
 static void x_consider_frame_title P_ ((Lisp_Object));
 static void handle_stop P_ ((struct it *));
 static int tool_bar_lines_needed P_ ((struct frame *));
@@ -706,7 +767,7 @@ static int display_echo_area P_ ((struct window *));
 static int display_echo_area_1 P_ ((EMACS_INT, Lisp_Object, EMACS_INT, EMACS_INT));
 static int resize_mini_window_1 P_ ((EMACS_INT, Lisp_Object, EMACS_INT, EMACS_INT));
 static Lisp_Object unwind_redisplay P_ ((Lisp_Object));
-static int string_char_and_length P_ ((unsigned char *, int, int *));
+static int string_char_and_length P_ ((const unsigned char *, int, int *));
 static struct text_pos display_prop_end P_ ((struct it *, Lisp_Object,
                                             struct text_pos));
 static int compute_window_start_on_continuation_line P_ ((struct window *));
@@ -716,7 +777,7 @@ static struct glyph_row *get_overlay_arrow_glyph_row P_ ((struct window *));
 static void extend_face_to_end_of_line P_ ((struct it *));
 static int append_space P_ ((struct it *, int));
 static int make_cursor_line_fully_visible P_ ((struct window *));
-static int try_scrolling P_ ((Lisp_Object, int, int, int, int));
+static int try_scrolling P_ ((Lisp_Object, int, EMACS_INT, EMACS_INT, int));
 static int try_cursor_movement P_ ((Lisp_Object, struct text_pos, int *));
 static int trailing_whitespace_p P_ ((int));
 static int message_log_check_duplicate P_ ((int, int, int, int));
@@ -727,13 +788,17 @@ static void redisplay_internal P_ ((int));
 static int echo_area_display P_ ((int));
 static void redisplay_windows P_ ((Lisp_Object));
 static void redisplay_window P_ ((Lisp_Object, int));
+static Lisp_Object redisplay_window_error ();
+static Lisp_Object redisplay_window_0 P_ ((Lisp_Object));
+static Lisp_Object redisplay_window_1 P_ ((Lisp_Object));
 static void update_menu_bar P_ ((struct frame *, int));
 static int try_window_reusing_current_matrix P_ ((struct window *));
 static int try_window_id P_ ((struct window *));
 static int display_line P_ ((struct it *));
 static int display_mode_lines P_ ((struct window *));
 static int display_mode_line P_ ((struct window *, enum face_id, Lisp_Object));
-static int display_mode_element P_ ((struct it *, int, int, int, Lisp_Object));
+static int display_mode_element P_ ((struct it *, int, int, int, Lisp_Object, Lisp_Object, int));
+static int store_mode_line_string P_ ((char *, Lisp_Object, int, int, int, Lisp_Object));
 static char *decode_mode_spec P_ ((struct window *, int, int, int, int *));
 static void display_menu_bar P_ ((struct window *));
 static int display_count_lines P_ ((int, int, int, int, int *));
@@ -821,7 +886,7 @@ window_text_bottom_y (w)
 
 
 /* Return the pixel width of display area AREA of window W.  AREA < 0
-   means return the total width of W, not including bitmap areas to
+   means return the total width of W, not including fringes to
    the left and right of the window.  */
 
 INLINE int
@@ -831,11 +896,11 @@ window_box_width (w, area)
 {
   struct frame *f = XFRAME (w->frame);
   int width = XFASTINT (w->width);
-  
+
   if (!w->pseudo_window_p)
     {
-      width -= FRAME_SCROLL_BAR_WIDTH (f) + FRAME_FLAGS_AREA_COLS (f);
-      
+      width -= FRAME_SCROLL_BAR_WIDTH (f) + FRAME_FRINGE_COLS (f);
+
       if (area == TEXT_AREA)
        {
          if (INTEGERP (w->left_margin_width))
@@ -856,7 +921,7 @@ window_box_width (w, area)
 
 
 /* Return the pixel height of the display area of window W, not
-   including mode lines of W, if any..  */
+   including mode lines of W, if any.  */
 
 INLINE int
 window_box_height (w)
@@ -866,7 +931,7 @@ window_box_height (w)
   int height = XFASTINT (w->height) * CANON_Y_UNIT (f);
 
   xassert (height >= 0);
-  
+
   /* Note: the code below that determines the mode-line/header-line
      height is essentially the same as that contained in the macro
      CURRENT_{MODE,HEADER}_LINE_HEIGHT, except that it checks whether
@@ -882,7 +947,7 @@ window_box_height (w)
       if (ml_row && ml_row->mode_line_p)
        height -= ml_row->height;
       else
-       height -= estimate_mode_line_height (f, MODE_LINE_FACE_ID);
+       height -= estimate_mode_line_height (f, CURRENT_MODE_LINE_FACE_ID (w));
     }
 
   if (WINDOW_WANTS_HEADER_LINE_P (w))
@@ -897,14 +962,15 @@ window_box_height (w)
        height -= estimate_mode_line_height (f, HEADER_LINE_FACE_ID);
     }
 
-  return height;
+  /* With a very small font and a mode-line that's taller than
+     default, we might end up with a negative height.  */
+  return max (0, height);
 }
 
 
 /* Return the frame-relative coordinate of the left edge of display
    area AREA of window W.  AREA < 0 means return the left edge of the
-   whole window, to the right of any bitmap area at the left side of
-   W.  */
+   whole window, to the right of the left fringe of W.  */
 
 INLINE int
 window_box_left (w, area)
@@ -917,8 +983,8 @@ window_box_left (w, area)
   if (!w->pseudo_window_p)
     {
       x += (WINDOW_LEFT_MARGIN (w) * CANON_X_UNIT (f)
-           + FRAME_LEFT_FLAGS_AREA_WIDTH (f));
-      
+           + FRAME_LEFT_FRINGE_WIDTH (f));
+
       if (area == TEXT_AREA)
        x += window_box_width (w, LEFT_MARGIN_AREA);
       else if (area == RIGHT_MARGIN_AREA)
@@ -927,13 +993,12 @@ window_box_left (w, area)
     }
 
   return x;
-}     
+}
 
 
 /* Return the frame-relative coordinate of the right edge of display
    area AREA of window W.  AREA < 0 means return the left edge of the
-   whole window, to the left of any bitmap area at the right side of
-   W.  */
+   whole window, to the left of the right fringe of W.  */
 
 INLINE int
 window_box_right (w, area)
@@ -941,12 +1006,12 @@ window_box_right (w, area)
      int area;
 {
   return window_box_left (w, area) + window_box_width (w, area);
-}     
-     
+}
+
 
 /* Get the bounding box of the display area AREA of window W, without
    mode lines, in frame-relative coordinates.  AREA < 0 means the
-   whole window, not including bitmap areas to the left and right of
+   whole window, not including the left and right fringes of
    the window.  Return in *BOX_X and *BOX_Y the frame-relative pixel
    coordinates of the upper-left corner of the box.  Return in
    *BOX_WIDTH, and *BOX_HEIGHT the pixel width and height of the box.  */
@@ -958,7 +1023,7 @@ window_box (w, area, box_x, box_y, box_width, box_height)
      int *box_x, *box_y, *box_width, *box_height;
 {
   struct frame *f = XFRAME (w->frame);
-  
+
   *box_width = window_box_width (w, area);
   *box_height = window_box_height (w);
   *box_x = window_box_left (w, area);
@@ -970,8 +1035,8 @@ window_box (w, area, box_x, box_y, box_width, box_height)
 
 
 /* Get the bounding box of the display area AREA of window W, without
-   mode lines.  AREA < 0 means the whole window, not including bitmap
-   areas to the left and right of the window.  Return in *TOP_LEFT_X
+   mode lines.  AREA < 0 means the whole window, not including the
+   left and right fringe of the window.  Return in *TOP_LEFT_X
    and TOP_LEFT_Y the frame-relative pixel coordinates of the
    upper-left corner of the box.  Return in *BOTTOM_RIGHT_X, and
    *BOTTOM_RIGHT_Y the coordinates of the bottom-right corner of the
@@ -1005,7 +1070,7 @@ line_bottom_y (it)
 {
   int line_height = it->max_ascent + it->max_descent;
   int line_top_y = it->current_y;
-  
+
   if (line_height == 0)
     {
       if (last_height)
@@ -1020,7 +1085,7 @@ line_bottom_y (it)
       else
        {
          struct glyph_row *row = it->glyph_row;
-         
+
          /* Use the default character height.  */
          it->glyph_row = NULL;
          it->what = IT_CHARACTER;
@@ -1059,15 +1124,15 @@ pos_visible_p (w, charpos, fully, exact_mode_line_heights_p)
 
   *fully = visible_p = 0;
   SET_TEXT_POS_FROM_MARKER (top, w->start);
-  
+
   /* Compute exact mode line heights, if requested.  */
   if (exact_mode_line_heights_p)
     {
       if (WINDOW_WANTS_MODELINE_P (w))
        current_mode_line_height
-         = display_mode_line (w, MODE_LINE_FACE_ID,
+         = display_mode_line (w, CURRENT_MODE_LINE_FACE_ID (w),
                               current_buffer->mode_line_format);
-  
+
       if (WINDOW_WANTS_HEADER_LINE_P (w))
        current_header_line_height
          = display_mode_line (w, HEADER_LINE_FACE_ID,
@@ -1084,7 +1149,7 @@ pos_visible_p (w, charpos, fully, exact_mode_line_heights_p)
       int top_y = it.current_y;
       int bottom_y = line_bottom_y (&it);
       int window_top_y = WINDOW_DISPLAY_HEADER_LINE_HEIGHT (w);
-      
+
       if (top_y < window_top_y)
        visible_p = bottom_y > window_top_y;
       else if (top_y < it.last_visible_y)
@@ -1119,7 +1184,7 @@ pos_visible_p (w, charpos, fully, exact_mode_line_heights_p)
 
 static INLINE int
 string_char_and_length (str, maxlen, len)
-     unsigned char *str;
+     const unsigned char *str;
      int maxlen, *len;
 {
   int c;
@@ -1149,8 +1214,8 @@ string_pos_nchars_ahead (pos, string, nchars)
 
   if (STRING_MULTIBYTE (string))
     {
-      int rest = STRING_BYTES (XSTRING (string)) - BYTEPOS (pos);
-      unsigned char *p = XSTRING (string)->data + BYTEPOS (pos);
+      int rest = SBYTES (string) - BYTEPOS (pos);
+      const unsigned char *p = SDATA (string) + BYTEPOS (pos);
       int len;
 
       while (nchars--)
@@ -1230,7 +1295,7 @@ number_of_chars (s, multibyte_p)
      int multibyte_p;
 {
   int nchars;
-  
+
   if (multibyte_p)
     {
       int rest = strlen (s), len;
@@ -1248,7 +1313,7 @@ number_of_chars (s, multibyte_p)
   return nchars;
 }
 
-     
+
 /* Compute byte position NEWPOS->bytepos corresponding to
    NEWPOS->charpos.  POS is a known position in string STRING.
    NEWPOS->charpos must be >= POS.charpos.  */
@@ -1260,7 +1325,7 @@ compute_string_pos (newpos, pos, string)
 {
   xassert (STRINGP (string));
   xassert (CHARPOS (*newpos) >= CHARPOS (pos));
-  
+
   if (STRING_MULTIBYTE (string))
     *newpos = string_pos_nchars_ahead (pos, string,
                                       CHARPOS (*newpos) - CHARPOS (pos));
@@ -1293,22 +1358,24 @@ safe_eval (sexpr)
      Lisp_Object sexpr;
 {
   Lisp_Object val;
-  
+
   if (inhibit_eval_during_redisplay)
     val = Qnil;
   else
     {
-      int count = BINDING_STACK_SIZE ();
+      int count = SPECPDL_INDEX ();
       struct gcpro gcpro1;
 
       GCPRO1 (sexpr);
       specbind (Qinhibit_redisplay, Qt);
-      val = internal_condition_case_1 (Feval, sexpr, Qerror,
+      /* Use Qt to ensure debugger does not run,
+        so there is no possibility of wanting to redisplay.  */
+      val = internal_condition_case_1 (Feval, sexpr, Qt,
                                       safe_eval_handler);
       UNGCPRO;
       val = unbind_to (count, val);
     }
-  
+
   return val;
 }
 
@@ -1323,18 +1390,20 @@ safe_call (nargs, args)
      Lisp_Object *args;
 {
   Lisp_Object val;
-  
+
   if (inhibit_eval_during_redisplay)
     val = Qnil;
   else
     {
-      int count = BINDING_STACK_SIZE ();
+      int count = SPECPDL_INDEX ();
       struct gcpro gcpro1;
 
       GCPRO1 (args[0]);
       gcpro1.nvars = nargs;
       specbind (Qinhibit_redisplay, Qt);
-      val = internal_condition_case_2 (Ffuncall, nargs, args, Qerror,
+      /* Use Qt to ensure debugger does not run,
+        so there is no possibility of wanting to redisplay.  */
+      val = internal_condition_case_2 (Ffuncall, nargs, args, Qt,
                                       safe_eval_handler);
       UNGCPRO;
       val = unbind_to (count, val);
@@ -1443,13 +1512,14 @@ check_window_end (w)
    will produce glyphs in that row.
 
    BASE_FACE_ID is the id of a base face to use.  It must be one of
-   DEFAULT_FACE_ID for normal text, MODE_LINE_FACE_ID or
-   HEADER_LINE_FACE_ID for displaying mode lines, or TOOL_BAR_FACE_ID for
-   displaying the tool-bar.
-   
-   If ROW is null and BASE_FACE_ID is equal to MODE_LINE_FACE_ID or
-   HEADER_LINE_FACE_ID, the iterator will be initialized to use the
-   corresponding mode line glyph row of the desired matrix of W.  */
+   DEFAULT_FACE_ID for normal text, MODE_LINE_FACE_ID,
+   MODE_LINE_INACTIVE_FACE_ID, or HEADER_LINE_FACE_ID for displaying
+   mode lines, or TOOL_BAR_FACE_ID for displaying the tool-bar.
+
+   If ROW is null and BASE_FACE_ID is equal to MODE_LINE_FACE_ID,
+   MODE_LINE_INACTIVE_FACE_ID, or HEADER_LINE_FACE_ID, the iterator
+   will be initialized to use the corresponding mode line glyph row of
+   the desired matrix of W.  */
 
 void
 init_iterator (it, w, charpos, bytepos, row, base_face_id)
@@ -1468,8 +1538,9 @@ init_iterator (it, w, charpos, bytepos, row, base_face_id)
 
   /* If face attributes have been changed since the last redisplay,
      free realized faces now because they depend on face definitions
-     that might have changed.  */
-  if (face_change_count)
+     that might have changed.  Don't free faces while there might be 
+     desired matrices pending which reference these faces.  */
+  if (face_change_count && !inhibit_free_realized_faces)
     {
       face_change_count = 0;
       free_all_realized_faces (Qnil);
@@ -1479,12 +1550,13 @@ init_iterator (it, w, charpos, bytepos, row, base_face_id)
      appropriate.  */
   if (row == NULL)
     {
-      if (base_face_id == MODE_LINE_FACE_ID)
+      if (base_face_id == MODE_LINE_FACE_ID
+         || base_face_id == MODE_LINE_INACTIVE_FACE_ID)
        row = MATRIX_MODE_LINE_ROW (w->desired_matrix);
       else if (base_face_id == HEADER_LINE_FACE_ID)
        row = MATRIX_HEADER_LINE_ROW (w->desired_matrix);
     }
-  
+
   /* Clear IT.  */
   bzero (it, sizeof *it);
   it->current.overlay_string_index = -1;
@@ -1522,7 +1594,7 @@ init_iterator (it, w, charpos, bytepos, row, base_face_id)
   /* Current value of the `space-width', and 'height' properties.  */
   it->space_width = Qnil;
   it->font_height = Qnil;
-  
+
   /* Are control characters displayed as `^C'?  */
   it->ctl_arrow_p = !NILP (current_buffer->ctl_arrow);
 
@@ -1531,7 +1603,7 @@ init_iterator (it, w, charpos, bytepos, row, base_face_id)
      invisible.  */
   it->selective = (INTEGERP (current_buffer->selective_display)
                   ? XFASTINT (current_buffer->selective_display)
-                  : (!NILP (current_buffer->selective_display) 
+                  : (!NILP (current_buffer->selective_display)
                      ? -1 : 0));
   it->selective_display_ellipsis_p
     = !NILP (current_buffer->selective_display_ellipses);
@@ -1553,15 +1625,15 @@ init_iterator (it, w, charpos, bytepos, row, base_face_id)
      -1 to indicate no region.  */
   if (highlight_region_p
       /* Maybe highlight only in selected window.  */
-      && (/* Either show region everywhere.  */ 
+      && (/* Either show region everywhere.  */
          highlight_nonselected_windows
          /* Or show region in the selected window.  */
          || w == XWINDOW (selected_window)
          /* Or show the region if we are in the mini-buffer and W is
             the window the mini-buffer refers to.  */
          || (MINI_WINDOW_P (XWINDOW (selected_window))
-             && WINDOWP (Vminibuf_scroll_window)
-             && w == XWINDOW (Vminibuf_scroll_window))))
+             && WINDOWP (minibuf_selected_window)
+             && w == XWINDOW (minibuf_selected_window))))
     {
       int charpos = marker_position (current_buffer->mark);
       it->region_beg_charpos = min (PT, charpos);
@@ -1593,7 +1665,7 @@ init_iterator (it, w, charpos, bytepos, row, base_face_id)
        || !NILP (current_buffer->truncate_lines));
 
   /* Get dimensions of truncation and continuation glyphs.  These are
-     displayed as bitmaps under X, so we don't need them for such
+     displayed as fringe bitmaps under X, so we don't need them for such
      frames.  */
   if (!FRAME_WINDOW_P (it->f))
     {
@@ -1612,7 +1684,7 @@ init_iterator (it, w, charpos, bytepos, row, base_face_id)
          it->continuation_pixel_width = it->pixel_width;
        }
 
-      /* Reset these values to zero becaue the produce_special_glyphs
+      /* Reset these values to zero because the produce_special_glyphs
         above has changed them.  */
       it->pixel_width = it->ascent = it->descent = 0;
       it->phys_ascent = it->phys_descent = 0;
@@ -1669,7 +1741,7 @@ init_iterator (it, w, charpos, bytepos, row, base_face_id)
   if (base_face_id != DEFAULT_FACE_ID)
     {
       struct face *face;
-      
+
       it->face_id = base_face_id;
 
       /* If we have a boxed mode line, make the first character appear
@@ -1686,7 +1758,7 @@ init_iterator (it, w, charpos, bytepos, row, base_face_id)
       it->end_charpos = ZV;
       it->face_id = -1;
       IT_CHARPOS (*it) = charpos;
-      
+
       /* Compute byte position if not specified.  */
       if (bytepos < charpos)
        IT_BYTEPOS (*it) = CHAR_TO_BYTE (charpos);
@@ -1696,7 +1768,7 @@ init_iterator (it, w, charpos, bytepos, row, base_face_id)
       /* Compute faces etc.  */
       reseat (it, it->current.pos, 1);
     }
-  
+
   CHECK_IT (it);
 }
 
@@ -1719,7 +1791,7 @@ start_display (it, w, pos)
     {
       int start_at_line_beg_p;
       int first_y = it->current_y;
-  
+
       /* If window start is not at a line start, skip forward to POS to
         get the correct continuation lines width.  */
       start_at_line_beg_p = (CHARPOS (pos) == BEGV
@@ -1743,7 +1815,7 @@ start_display (it, w, pos)
                  set_iterator_to_next (it, 1);
                  move_it_in_display_line_to (it, -1, -1, 0);
                }
-             
+
              it->continuation_lines_width += it->current_x;
            }
 
@@ -1752,7 +1824,7 @@ start_display (it, w, pos)
             fields in the iterator structure.  */
          it->max_ascent = it->max_descent = 0;
          it->max_phys_ascent = it->max_phys_descent = 0;
-      
+
          it->current_y = first_y;
          it->vpos = 0;
          it->current_x = it->hpos = 0;
@@ -1762,7 +1834,7 @@ start_display (it, w, pos)
 #if 0 /* Don't assert the following because start_display is sometimes
          called intentionally with a window start that is not at a
         line start.  Please leave this code in as a comment.  */
-  
+
   /* Window start should be on a line start, now.  */
   xassert (it->continuation_lines_width
           || IT_CHARPOS (it) == BEGV
@@ -1782,7 +1854,7 @@ in_ellipses_for_invisible_text_p (pos, w)
   Lisp_Object prop, window;
   int ellipses_p = 0;
   int charpos = CHARPOS (pos->pos);
-  
+
   /* If POS specifies a position in a display vector, this might
      be for an ellipsis displayed for invisible text.  We won't
      get the iterator set up for delivering that ellipsis unless
@@ -1818,7 +1890,7 @@ init_from_display_pos (it, w, pos)
 {
   int charpos = CHARPOS (pos->pos), bytepos = BYTEPOS (pos->pos);
   int i, overlay_strings_with_newlines = 0;
-  
+
   /* If POS specifies a position in a display vector, this might
      be for an ellipsis displayed for invisible text.  We won't
      get the iterator set up for delivering that ellipsis unless
@@ -1828,7 +1900,7 @@ init_from_display_pos (it, w, pos)
       --charpos;
       bytepos = 0;
     }
-    
+
   /* Keep in mind: the call to reseat in init_iterator skips invisible
      text, so we might end up at a position different from POS.  This
      is only a problem when POS is a row start after a newline and an
@@ -1842,9 +1914,9 @@ init_from_display_pos (it, w, pos)
 
   for (i = 0; i < it->n_overlay_strings; ++i)
     {
-      char *s = XSTRING (it->overlay_strings[i])->data;
-      char *e = s + STRING_BYTES (XSTRING (it->overlay_strings[i]));
-      
+      const char *s = SDATA (it->overlay_strings[i]);
+      const char *e = s + SBYTES (it->overlay_strings[i]);
+
       while (s < e && *s != '\n')
        ++s;
 
@@ -1867,7 +1939,7 @@ init_from_display_pos (it, w, pos)
         correct the overlay string index.  */
       if (it->method == next_element_from_image)
        pop_it (it);
-      
+
       /* We already have the first chunk of overlay strings in
         IT->overlay_strings.  Load more until the one for
         pos->overlay_string_index is in IT->overlay_strings.  */
@@ -1881,7 +1953,7 @@ init_from_display_pos (it, w, pos)
              it->current.overlay_string_index += OVERLAY_STRING_CHUNK_SIZE;
            }
        }
-      
+
       it->current.overlay_string_index = pos->overlay_string_index;
       relative_index = (it->current.overlay_string_index
                        % OVERLAY_STRING_CHUNK_SIZE);
@@ -1890,7 +1962,7 @@ init_from_display_pos (it, w, pos)
       it->current.string_pos = pos->string_pos;
       it->method = next_element_from_string;
     }
-  
+
 #if 0 /* This is bogus because POS not having an overlay string
         position does not mean it's after the string.  Example: A
         line starting with a before-string and initialization of IT
@@ -1909,7 +1981,7 @@ init_from_display_pos (it, w, pos)
        it->overlay_strings_at_end_processed_p = 1;
     }
 #endif /* 0 */
-  
+
   if (CHARPOS (pos->string_pos) >= 0)
     {
       /* Recorded position is not in an overlay string, but in another
@@ -1928,7 +2000,7 @@ init_from_display_pos (it, w, pos)
       xassert (it->dpvec && it->current.dpvec_index == 0);
       it->current.dpvec_index = pos->dpvec_index;
     }
-  
+
   CHECK_IT (it);
   return !overlay_strings_with_newlines;
 }
@@ -1948,7 +2020,7 @@ init_to_row_start (it, w, row)
   CHECK_IT (it);
 }
 
-     
+
 /* Initialize IT for stepping through current_buffer in window W
    starting in the line following ROW, i.e. starting at ROW->end.
    Value is zero if there are overlay strings with newlines at ROW's
@@ -1961,7 +2033,7 @@ init_to_row_end (it, w, row)
      struct glyph_row *row;
 {
   int success = 0;
-  
+
   if (init_from_display_pos (it, w, &row->end))
     {
       if (row->continued_p)
@@ -1970,7 +2042,7 @@ init_to_row_end (it, w, row)
       CHECK_IT (it);
       success = 1;
     }
-  
+
   return success;
 }
 
@@ -1999,7 +2071,7 @@ handle_stop (it)
   do
     {
       handled = HANDLED_NORMALLY;
-      
+
       /* Call text property handlers.  */
       for (p = it_props; p->handler; ++p)
        {
@@ -2023,7 +2095,7 @@ handle_stop (it)
          /* Handle overlay changes.  */
          if (handle_overlay_change_p)
            handled = handle_overlay_change (it);
-      
+
          /* Determine where to stop next.  */
          if (handled == HANDLED_NORMALLY)
            compute_stop_pos (it);
@@ -2045,7 +2117,7 @@ compute_stop_pos (it)
 
   /* If nowhere else, stop at the end.  */
   it->stop_charpos = it->end_charpos;
-  
+
   if (STRINGP (it->string))
     {
       /* Strings are usually short, so don't limit the search for
@@ -2075,7 +2147,7 @@ compute_stop_pos (it)
          else if (IT_CHARPOS (*it) < it->region_end_charpos)
            it->stop_charpos = min (it->stop_charpos, it->region_end_charpos);
        }
-      
+
       /* Set up variables for computing the stop position from text
          property changes.  */
       XSETBUFFER (object, current_buffer);
@@ -2112,7 +2184,7 @@ compute_stop_pos (it)
              if (!EQ (values_here[p->idx], new_value))
                break;
            }
-         
+
          if (p->handler)
            break;
        }
@@ -2205,12 +2277,12 @@ handle_fontified_prop (it)
          prop = Fget_char_property (pos, Qfontified, Qnil),
          NILP (prop)))
     {
-      int count = BINDING_STACK_SIZE ();
+      int count = SPECPDL_INDEX ();
       Lisp_Object val;
 
       val = Vfontification_functions;
       specbind (Qfontification_functions, Qnil);
-  
+
       if (!CONSP (val) || EQ (XCAR (val), Qlambda))
        safe_call1 (val, pos);
       else
@@ -2220,11 +2292,11 @@ handle_fontified_prop (it)
 
          globals = Qnil;
          GCPRO2 (val, globals);
-         
+
          for (; CONSP (val); val = XCDR (val))
            {
              fn = XCAR (val);
-             
+
              if (EQ (fn, Qt))
                {
                  /* A value of t indicates this hook has a local
@@ -2274,7 +2346,7 @@ handle_face_prop (it)
      struct it *it;
 {
   int new_face_id, next_stop;
-  
+
   if (!STRINGP (it->string))
     {
       new_face_id
@@ -2286,17 +2358,17 @@ handle_face_prop (it)
                                   (IT_CHARPOS (*it)
                                    + TEXT_PROP_DISTANCE_LIMIT),
                                   0);
-      
+
       /* Is this a start of a run of characters with box face?
         Caveat: this can be called for a freshly initialized
-        iterator; face_id is -1 is this case.  We know that the new
+        iterator; face_id is -1 in this case.  We know that the new
         face will not change until limit, i.e. if the new face has a
         box, all characters up to limit will have one.  But, as
         usual, we don't know whether limit is really the end.  */
       if (new_face_id != it->face_id)
        {
          struct face *new_face = FACE_FROM_ID (it->f, new_face_id);
-         
+
          /* If new face has a box but old face has not, this is
             the start of a run of characters with box, i.e. it has
             a shadow on the left side.  The value of face_id of the
@@ -2319,14 +2391,14 @@ handle_face_prop (it)
        bufpos = IT_CHARPOS (*it);
       else
        bufpos = 0;
-      
+
       /* For strings from a buffer, i.e. overlay strings or strings
         from a `display' property, use the face at IT's current
         buffer position as the base face to merge with, so that
         overlay strings appear in the same face as surrounding
         text, unless they specify their own faces.  */
       base_face_id = underlying_face_id (it);
-      
+
       new_face_id = face_at_string_position (it->w,
                                             it->string,
                                             IT_STRING_CHARPOS (*it),
@@ -2335,15 +2407,15 @@ handle_face_prop (it)
                                             it->region_end_charpos,
                                             &next_stop,
                                             base_face_id, 0);
-      
+
 #if 0 /* This shouldn't be neccessary.  Let's check it.  */
       /* If IT is used to display a mode line we would really like to
         use the mode line face instead of the frame's default face.  */
       if (it->glyph_row == MATRIX_MODE_LINE_ROW (it->w->desired_matrix)
          && new_face_id == DEFAULT_FACE_ID)
-       new_face_id = MODE_LINE_FACE_ID;
+       new_face_id = CURRENT_MODE_LINE_FACE_ID (it->w);
 #endif
-      
+
       /* Is this a start of a run of characters with box?  Caveat:
         this can be called for a freshly allocated iterator; face_id
         is -1 is this case.  We know that the new face will not
@@ -2355,7 +2427,7 @@ handle_face_prop (it)
        {
          struct face *new_face = FACE_FROM_ID (it->f, new_face_id);
          struct face *old_face = FACE_FROM_ID (it->f, it->face_id);
-         
+
          /* If new face has a box but old face hasn't, this is the
             start of a run of characters with box, i.e. it has a
             shadow on the left side.  */
@@ -2364,7 +2436,7 @@ handle_face_prop (it)
          it->face_box_p = new_face->box != FACE_NO_BOX;
        }
     }
-  
+
   it->face_id = new_face_id;
   return HANDLED_NORMALLY;
 }
@@ -2405,15 +2477,15 @@ face_before_or_after_it_pos (it, before_p)
   struct text_pos pos;
 
   xassert (it->s == NULL);
-    
+
   if (STRINGP (it->string))
     {
       int bufpos, base_face_id;
-      
+
       /* No face change past the end of the string (for the case
         we are padding with spaces).  No face change before the
         string start.  */
-      if (IT_STRING_CHARPOS (*it) >= XSTRING (it->string)->size
+      if (IT_STRING_CHARPOS (*it) >= SCHARS (it->string)
          || (IT_STRING_CHARPOS (*it) == 0 && before_p))
        return it->face_id;
 
@@ -2449,11 +2521,11 @@ face_before_or_after_it_pos (it, before_p)
         suitable for unibyte text if IT->string is unibyte.  */
       if (STRING_MULTIBYTE (it->string))
        {
-         unsigned char *p = XSTRING (it->string)->data + BYTEPOS (pos);
-         int rest = STRING_BYTES (XSTRING (it->string)) - BYTEPOS (pos);
+         const unsigned char *p = SDATA (it->string) + BYTEPOS (pos);
+         int rest = SBYTES (it->string) - BYTEPOS (pos);
          int c, len;
          struct face *face = FACE_FROM_ID (it->f, face_id);
-      
+
          c = string_char_and_length (p, rest, &len);
          face_id = FACE_FOR_CHAR (it->f, face, c);
        }
@@ -2463,10 +2535,10 @@ face_before_or_after_it_pos (it, before_p)
       if ((IT_CHARPOS (*it) >= ZV && !before_p)
          || (IT_CHARPOS (*it) <= BEGV && before_p))
        return it->face_id;
-      
+
       limit = IT_CHARPOS (*it) + TEXT_PROP_DISTANCE_LIMIT;
       pos = it->current.pos;
-      
+
       if (before_p)
        DEC_TEXT_POS (pos, it->multibyte_p);
       else
@@ -2478,7 +2550,7 @@ face_before_or_after_it_pos (it, before_p)
          else
            INC_TEXT_POS (pos, it->multibyte_p);
        }
-      
+
       /* Determine face for CHARSET_ASCII, or unibyte.  */
       face_id = face_at_buffer_position (it->w,
                                         CHARPOS (pos),
@@ -2492,12 +2564,12 @@ face_before_or_after_it_pos (it, before_p)
         suitable for unibyte text if current_buffer is unibyte.  */
       if (it->multibyte_p)
        {
-         int c = FETCH_MULTIBYTE_CHAR (CHARPOS (pos));
+         int c = FETCH_MULTIBYTE_CHAR (BYTEPOS (pos));
          struct face *face = FACE_FROM_ID (it->f, face_id);
          face_id = FACE_FOR_CHAR (it->f, face, c);
        }
     }
-  
+
   return face_id;
 }
 
@@ -2531,15 +2603,15 @@ handle_invisible_prop (it)
          && IT_STRING_CHARPOS (*it) < it->end_charpos)
        {
          handled = HANDLED_RECOMPUTE_PROPS;
-         
+
          /* Get the position at which the next change of the
             invisible text property can be found in IT->string.
             Value will be nil if the property value is the same for
             all the rest of IT->string.  */
-         XSETINT (limit, XSTRING (it->string)->size);
+         XSETINT (limit, SCHARS (it->string));
          end_charpos = Fnext_single_property_change (charpos, Qinvisible,
-                                                 it->string, limit);
-         
+                                                     it->string, limit);
+
          /* Text at current position is invisible.  The next
             change in the property is at position end_charpos.
             Move IT's current position to that position.  */
@@ -2565,9 +2637,8 @@ handle_invisible_prop (it)
                }
              else
                {
-                 struct Lisp_String *s = XSTRING (it->string);
-                 IT_STRING_CHARPOS (*it) = s->size;
-                 IT_STRING_BYTEPOS (*it) = STRING_BYTES (s);
+                 IT_STRING_CHARPOS (*it) = SCHARS (it->string);
+                 IT_STRING_BYTEPOS (*it) = SBYTES (it->string);
                }
            }
        }
@@ -2592,7 +2663,7 @@ handle_invisible_prop (it)
          int display_ellipsis_p = invis_p == 2;
 
          handled = HANDLED_RECOMPUTE_PROPS;
-         
+
          /* Loop skipping over invisible text.  The loop is left at
             ZV or with IT on the first char being visible again.  */
          do
@@ -2622,7 +2693,7 @@ handle_invisible_prop (it)
                  prop = Fget_char_property (pos, Qinvisible, it->window);
                  invis_p = TEXT_PROP_MEANS_INVISIBLE (prop);
                }
-             
+
              /* If we ended up on invisible text, proceed to
                 skip starting with next_stop.  */
              if (invis_p)
@@ -2633,7 +2704,7 @@ handle_invisible_prop (it)
          /* The position newpos is now either ZV or on visible text.  */
          IT_CHARPOS (*it) = newpos;
          IT_BYTEPOS (*it) = CHAR_TO_BYTE (newpos);
-         
+
          /* If there are before-strings at the start of invisible
             text, and the text is invisible because of a text
             property, arrange to show before-strings because 20.x did
@@ -2661,25 +2732,25 @@ static void
 setup_for_ellipsis (it)
      struct it *it;
 {
-  if (it->dp 
+  if (it->dp
       && VECTORP (DISP_INVIS_VECTOR (it->dp)))
     {
       struct Lisp_Vector *v = XVECTOR (DISP_INVIS_VECTOR (it->dp));
       it->dpvec = v->contents;
       it->dpend = v->contents + v->size;
     }
-  else 
+  else
     {
       /* Default `...'.  */
       it->dpvec = default_invis_vector;
       it->dpend = default_invis_vector + 3;
     }
-  
+
   /* The ellipsis display does not replace the display of the
      character at the new position.  Indicate this by setting
      IT->dpvec_char_len to zero.  */
   it->dpvec_char_len = 0;
-  
+
   it->current.dpvec_index = 0;
   it->method = next_element_from_display_vector;
 }
@@ -2799,7 +2870,7 @@ display_prop_end (it, object, start_pos)
    If PROP is a `space' or `image' sub-property, set *POSITION to the
    end position of the `display' property.
 
-   Value is non-zero something was found which replaces the display
+   Value is non-zero if something was found which replaces the display
    of buffer or string text.  */
 
 static int
@@ -2816,7 +2887,7 @@ handle_single_display_prop (it, prop, object, position,
   Lisp_Object form;
 
   /* If PROP is a list of the form `(when FORM . VALUE)', FORM is
-     evaluated.  If the result is nil, VALUE is ignored. */
+     evaluated.  If the result is nil, VALUE is ignored.  */
   form = Qt;
   if (CONSP (prop) && EQ (XCAR (prop), Qwhen))
     {
@@ -2829,7 +2900,7 @@ handle_single_display_prop (it, prop, object, position,
 
   if (!NILP (form) && !EQ (form, Qt))
     {
-      int count = BINDING_STACK_SIZE ();
+      int count = SPECPDL_INDEX ();
       struct gcpro gcpro1;
 
       /* Bind `object' to the object having the `display' property, a
@@ -2846,7 +2917,7 @@ handle_single_display_prop (it, prop, object, position,
       UNGCPRO;
       unbind_to (count, Qnil);
     }
-  
+
   if (NILP (form))
     return 0;
 
@@ -2856,7 +2927,7 @@ handle_single_display_prop (it, prop, object, position,
     {
       if (FRAME_TERMCAP_P (it->f) || FRAME_MSDOS_P (it->f))
        return 0;
-      
+
       /* `(height HEIGHT)'.  */
       it->font_height = XCAR (XCDR (prop));
       if (!NILP (it->font_height))
@@ -2890,7 +2961,7 @@ handle_single_display_prop (it, prop, object, position,
            {
              /* Value is a multiple of the canonical char height.  */
              struct face *face;
-             
+
              face = FACE_FROM_ID (it->f, DEFAULT_FACE_ID);
              new_height = (XFLOATINT (it->font_height)
                            * XINT (face->lface[LFACE_HEIGHT_INDEX]));
@@ -2900,16 +2971,16 @@ handle_single_display_prop (it, prop, object, position,
              /* Evaluate IT->font_height with `height' bound to the
                 current specified height to get the new height.  */
              Lisp_Object value;
-             int count = BINDING_STACK_SIZE ();
-             
+             int count = SPECPDL_INDEX ();
+
              specbind (Qheight, face->lface[LFACE_HEIGHT_INDEX]);
              value = safe_eval (it->font_height);
              unbind_to (count, Qnil);
-             
+
              if (NUMBERP (value))
                new_height = XFLOATINT (value);
            }
-         
+
          if (new_height > 0)
            it->face_id = face_with_height (it->f, it->face_id, new_height);
        }
@@ -2921,7 +2992,7 @@ handle_single_display_prop (it, prop, object, position,
       /* `(space_width WIDTH)'.  */
       if (FRAME_TERMCAP_P (it->f) || FRAME_MSDOS_P (it->f))
        return 0;
-      
+
       value = XCAR (XCDR (prop));
       if (NUMBERP (value) && XFLOATINT (value) > 0)
        it->space_width = value;
@@ -2933,7 +3004,7 @@ handle_single_display_prop (it, prop, object, position,
       /* `(raise FACTOR)'.  */
       if (FRAME_TERMCAP_P (it->f) || FRAME_MSDOS_P (it->f))
        return 0;
-      
+
 #ifdef HAVE_WINDOW_SYSTEM
       value = XCAR (XCDR (prop));
       if (NUMBERP (value))
@@ -2947,7 +3018,7 @@ handle_single_display_prop (it, prop, object, position,
   else if (!it->string_from_display_prop_p)
     {
       /* `((margin left-margin) VALUE)' or `((margin right-margin)
-        VALUE) or `((margin nil) VALUE)' or VALUE. */
+        VALUE) or `((margin nil) VALUE)' or VALUE.  */
       Lisp_Object location, value;
       struct text_pos start_pos;
       int valid_p;
@@ -2966,7 +3037,7 @@ handle_single_display_prop (it, prop, object, position,
       if (CONSP (prop) && CONSP (XCAR (prop)))
        {
          Lisp_Object tem;
-         
+
          value = XCDR (prop);
          if (CONSP (value))
            value = XCAR (value);
@@ -2997,7 +3068,7 @@ handle_single_display_prop (it, prop, object, position,
 #else /* not HAVE_WINDOW_SYSTEM */
       valid_p = STRINGP (value);
 #endif /* not HAVE_WINDOW_SYSTEM */
-      
+
       if ((EQ (location, Qleft_margin)
           || EQ (location, Qright_margin)
           || NILP (location))
@@ -3005,26 +3076,25 @@ handle_single_display_prop (it, prop, object, position,
          && !display_replaced_before_p)
        {
          replaces_text_display_p = 1;
-         
+
          /* Save current settings of IT so that we can restore them
             when we are finished with the glyph property value.  */
          push_it (it);
-         
+
          if (NILP (location))
            it->area = TEXT_AREA;
          else if (EQ (location, Qleft_margin))
            it->area = LEFT_MARGIN_AREA;
          else
            it->area = RIGHT_MARGIN_AREA;
-         
+
          if (STRINGP (value))
            {
              it->string = value;
              it->multibyte_p = STRING_MULTIBYTE (it->string);
              it->current.overlay_string_index = -1;
              IT_STRING_CHARPOS (*it) = IT_STRING_BYTEPOS (*it) = 0;
-             it->end_charpos = it->string_nchars
-               = XSTRING (it->string)->size;
+             it->end_charpos = it->string_nchars = SCHARS (it->string);
              it->method = next_element_from_string;
              it->stop_charpos = 0;
              it->string_from_display_prop_p = 1;
@@ -3047,7 +3117,7 @@ handle_single_display_prop (it, prop, object, position,
              it->position = start_pos;
              it->object = NILP (object) ? it->w->buffer : object;
              it->method = next_element_from_image;
-             
+
              /* Say that we haven't consumed the characters with
                 `display' property yet.  The call to pop_it in
                 set_iterator_to_next will clean this up.  */
@@ -3098,7 +3168,7 @@ single_display_prop_intangible_p (prop)
          || EQ (XCAR (prop), Qright_margin))
        return 0;
     }
-  
+
   return CONSP (prop) && EQ (XCAR (prop), Qimage);
 }
 
@@ -3145,7 +3215,7 @@ single_display_prop_string_p (prop, string)
 {
   if (EQ (string, prop))
     return 1;
-  
+
   /* Skip over `when FORM'.  */
   if (CONSP (prop) && EQ (XCAR (prop), Qwhen))
     {
@@ -3167,7 +3237,7 @@ single_display_prop_string_p (prop, string)
        if (!CONSP (prop))
          return 0;
       }
-  
+
   return CONSP (prop) && EQ (XCAR (prop), string);
 }
 
@@ -3352,7 +3422,7 @@ handle_overlay_change (it)
    overlay strings to display, IT->string and
    IT->current.overlay_string_index are set appropriately here.
    Otherwise IT->string is set to nil.  */
-   
+
 static void
 next_overlay_string (it)
      struct it *it;
@@ -3364,7 +3434,7 @@ next_overlay_string (it)
         they were before overlay strings were processed, and
         continue to deliver from current_buffer.  */
       int display_ellipsis_p = it->stack[it->sp - 1].display_ellipsis_p;
-      
+
       pop_it (it);
       xassert (it->stop_charpos >= BEGV
               && it->stop_charpos <= it->end_charpos);
@@ -3392,7 +3462,7 @@ next_overlay_string (it)
         where we must load IT->overlay_strings with more strings, do
         it.  */
       int i = it->current.overlay_string_index % OVERLAY_STRING_CHUNK_SIZE;
-  
+
       if (it->current.overlay_string_index && i == 0)
        load_overlay_strings (it, 0);
 
@@ -3404,7 +3474,7 @@ next_overlay_string (it)
       it->method = next_element_from_string;
       it->stop_charpos = 0;
     }
-  
+
   CHECK_IT (it);
 }
 
@@ -3415,7 +3485,7 @@ next_overlay_string (it)
 
    1. All after-strings come in front of before-strings, except
    when they come from the same overlay.
-   
+
    2. Within after-strings, strings are sorted so that overlay strings
    from overlays with higher priorities come first.
 
@@ -3424,7 +3494,7 @@ next_overlay_string (it)
 
    Value is analogous to strcmp.  */
 
-  
+
 static int
 compare_overlay_entries (e1, e2)
      void *e1, *e2;
@@ -3476,7 +3546,7 @@ compare_overlay_entries (e1, e2)
    front of before-string strings.  Within before and after-strings,
    strings are sorted by overlay priority.  See also function
    compare_overlay_entries.  */
-   
+
 static void
 load_overlay_strings (it, charpos)
      struct it *it;
@@ -3529,7 +3599,7 @@ load_overlay_strings (it, charpos)
       xassert (OVERLAYP (overlay));
       start = OVERLAY_POSITION (OVERLAY_START (overlay));
       end = OVERLAY_POSITION (OVERLAY_END (overlay));
-      
+
       if (end < charpos)
        break;
 
@@ -3537,7 +3607,7 @@ load_overlay_strings (it, charpos)
         position.  */
       if (end != charpos && start != charpos)
        continue;
-      
+
       /* Skip this overlay if it doesn't apply to IT->w.  */
       window = Foverlay_get (overlay, Qwindow);
       if (WINDOWP (window) && XWINDOW (window) != it->w)
@@ -3552,16 +3622,16 @@ load_overlay_strings (it, charpos)
       /* If overlay has a non-empty before-string, record it.  */
       if ((start == charpos || (end == charpos && invis_p))
          && (str = Foverlay_get (overlay, Qbefore_string), STRINGP (str))
-         && XSTRING (str)->size)
+         && SCHARS (str))
        RECORD_OVERLAY_STRING (overlay, str, 0);
-      
+
       /* If overlay has a non-empty after-string, record it.  */
       if ((end == charpos || (start == charpos && invis_p))
          && (str = Foverlay_get (overlay, Qafter_string), STRINGP (str))
-         && XSTRING (str)->size)
+         && SCHARS (str))
        RECORD_OVERLAY_STRING (overlay, str, 1);
     }
-      
+
   /* Process overlays after the overlay center.  */
   for (ov = current_buffer->overlays_after; CONSP (ov); ov = XCDR (ov))
     {
@@ -3572,7 +3642,7 @@ load_overlay_strings (it, charpos)
 
       if (start > charpos)
        break;
-      
+
       /* Skip this overlay if it doesn't start or end at IT's current
         position.  */
       if (end != charpos && start != charpos)
@@ -3582,7 +3652,7 @@ load_overlay_strings (it, charpos)
       window = Foverlay_get (overlay, Qwindow);
       if (WINDOWP (window) && XWINDOW (window) != it->w)
        continue;
-      
+
       /* If the text ``under'' the overlay is invisible, it has a zero
         dimension, and both before- and after-strings apply.  */
       invisible = Foverlay_get (overlay, Qinvisible);
@@ -3591,18 +3661,18 @@ load_overlay_strings (it, charpos)
       /* If overlay has a non-empty before-string, record it.  */
       if ((start == charpos || (end == charpos && invis_p))
          && (str = Foverlay_get (overlay, Qbefore_string), STRINGP (str))
-         && XSTRING (str)->size)
+         && SCHARS (str))
        RECORD_OVERLAY_STRING (overlay, str, 0);
-                              
+
       /* If overlay has a non-empty after-string, record it.  */
       if ((end == charpos || (start == charpos && invis_p))
          && (str = Foverlay_get (overlay, Qafter_string), STRINGP (str))
-         && XSTRING (str)->size)
+         && SCHARS (str))
        RECORD_OVERLAY_STRING (overlay, str, 1);
     }
 
 #undef RECORD_OVERLAY_STRING
-   
+
   /* Sort entries.  */
   if (n > 1)
     qsort (entries, n, sizeof *entries, compare_overlay_entries);
@@ -3651,7 +3721,7 @@ get_overlay_strings (it, charpos)
         strings.  */
       compute_stop_pos (it);
       xassert (it->face_id >= 0);
-      
+
       /* Save IT's settings.  They are restored after all overlay
         strings have been processed.  */
       xassert (it->sp == 0);
@@ -3662,9 +3732,9 @@ get_overlay_strings (it, charpos)
       IT_STRING_CHARPOS (*it) = IT_STRING_BYTEPOS (*it) = 0;
       it->string = it->overlay_strings[0];
       it->stop_charpos = 0;
-      it->end_charpos = XSTRING (it->string)->size;
-      it->multibyte_p = STRING_MULTIBYTE (it->string);
       xassert (STRINGP (it->string));
+      it->end_charpos = SCHARS (it->string);
+      it->multibyte_p = STRING_MULTIBYTE (it->string);
       it->method = next_element_from_string;
     }
   else
@@ -3696,7 +3766,7 @@ push_it (it)
      struct it *it;
 {
   struct iterator_stack_entry *p;
-  
+
   xassert (it->sp < 2);
   p = it->stack + it->sp;
 
@@ -3729,7 +3799,7 @@ pop_it (it)
      struct it *it;
 {
   struct iterator_stack_entry *p;
-  
+
   xassert (it->sp > 0);
   --it->sp;
   p = it->stack + it->sp;
@@ -3765,12 +3835,12 @@ back_to_previous_line_start (it)
 
 
 /* Move IT to the next line start.
-   
+
    Value is non-zero if a newline was found.  Set *SKIPPED_P to 1 if
    we skipped over part of the text (as opposed to moving the iterator
    continuously over the text).  Otherwise, don't change the value
    of *SKIPPED_P.
-   
+
    Newlines may come from buffer text, overlay strings, or strings
    displayed via the `display' property.  That's the reason we can't
    simply use find_next_newline_no_quit.
@@ -3815,14 +3885,14 @@ forward_to_next_line_start (it, skipped_p)
        n += STRINGP (it->string) ? 0 : 1)
     {
       if (!get_next_display_element (it))
-       break;
+       return 0;
       newline_found_p = it->what == IT_CHARACTER && it->c == '\n';
       set_iterator_to_next (it, 0);
     }
 
   /* If we didn't find a newline near enough, see if we can use a
      short-cut.  */
-  if (n == MAX_NEWLINE_DISTANCE)
+  if (!newline_found_p)
     {
       int start = IT_CHARPOS (*it);
       int limit = find_next_newline_no_quit (start, 1);
@@ -3886,9 +3956,9 @@ back_to_previous_visible_line_start (it)
         are invisible.  */
       if (it->selective > 0
          && indented_beyond_p (IT_CHARPOS (*it), IT_BYTEPOS (*it),
-                               it->selective))
+                               (double) it->selective)) /* iftc */
        visible_p = 0;
-      else 
+      else
        {
          Lisp_Object prop;
 
@@ -3946,7 +4016,7 @@ reseat_at_next_visible_line_start (it, on_newline_p)
   if (it->selective > 0)
     while (IT_CHARPOS (*it) < ZV
           && indented_beyond_p (IT_CHARPOS (*it), IT_BYTEPOS (*it),
-                                it->selective))
+                                (double) it->selective)) /* iftc */
       {
        xassert (FETCH_BYTE (IT_BYTEPOS (*it) - 1) == '\n');
        newline_found_p = forward_to_next_line_start (it, &skipped_p);
@@ -3972,7 +4042,7 @@ reseat_at_next_visible_line_start (it, on_newline_p)
     }
   else if (skipped_p)
     reseat (it, it->current.pos, 0);
-  
+
   CHECK_IT (it);
 }
 
@@ -4045,7 +4115,7 @@ reseat_1 (it, pos, set_stop_p)
 /* Set up IT for displaying a string, starting at CHARPOS in window W.
    If S is non-null, it is a C string to iterate over.  Otherwise,
    STRING gives a Lisp string to iterate over.
-   
+
    If PRECISION > 0, don't return more then PRECISION number of
    characters from the string.
 
@@ -4079,18 +4149,18 @@ reseat_to_string (it, s, string, charpos, precision, field_width, multibyte)
   it->current.overlay_string_index = -1;
   it->current.dpvec_index = -1;
   xassert (charpos >= 0);
-  
+
   /* If STRING is specified, use its multibyteness, otherwise use the
      setting of MULTIBYTE, if specified.  */
   if (multibyte >= 0)
     it->multibyte_p = multibyte > 0;
-  
+
   if (s == NULL)
     {
       xassert (STRINGP (string));
       it->string = string;
       it->s = NULL;
-      it->end_charpos = it->string_nchars = XSTRING (string)->size;
+      it->end_charpos = it->string_nchars = SCHARS (string);
       it->method = next_element_from_string;
       it->current.string_pos = string_pos (charpos, string);
     }
@@ -4112,7 +4182,7 @@ reseat_to_string (it, s, string, charpos, precision, field_width, multibyte)
          IT_CHARPOS (*it) = IT_BYTEPOS (*it) = charpos;
          it->end_charpos = it->string_nchars = strlen (s);
        }
-      
+
       it->method = next_element_from_c_string;
     }
 
@@ -4204,14 +4274,22 @@ get_next_display_element (it)
             the translation.  This could easily be changed but I
             don't believe that it is worth doing.
 
-            Non-printable multibyte characters are also translated
-            octal form.  */
-         else if ((it->c < ' '
+            If it->multibyte_p is nonzero, eight-bit characters and
+            non-printable multibyte characters are also translated to
+            octal form.
+
+            If it->multibyte_p is zero, eight-bit characters that
+            don't have corresponding multibyte char code are also
+            translated to octal form.  */
+         else if (((it->c < ' ' || it->c == 127)
                    && (it->area != TEXT_AREA
                        || (it->c != '\n' && it->c != '\t')))
-                  || (it->c >= 127
-                      && it->len == 1)
-                  || !CHAR_PRINTABLE_P (it->c))
+                  || (it->multibyte_p
+                      ? ((it->c >= 127
+                          && it->len == 1)
+                         || !CHAR_PRINTABLE_P (it->c))
+                      : (it->c >= 128
+                         && it->c == unibyte_char_to_multibyte (it->c))))
            {
              /* IT->c is a control character which must be displayed
                 either as '\003' or as `^C' where the '\\' and '^'
@@ -4282,11 +4360,11 @@ get_next_display_element (it)
                      XSETINT (it->ctl_chars[i * 4], escape_glyph);
                      /* Insert three more glyphs into IT->ctl_chars for
                         the octal display of the character.  */
-                     g = FAST_MAKE_GLYPH (((str[i] >> 6) & 7) + '0', 0); 
+                     g = FAST_MAKE_GLYPH (((str[i] >> 6) & 7) + '0', 0);
                      XSETINT (it->ctl_chars[i * 4 + 1], g);
-                     g = FAST_MAKE_GLYPH (((str[i] >> 3) & 7) + '0', 0); 
+                     g = FAST_MAKE_GLYPH (((str[i] >> 3) & 7) + '0', 0);
                      XSETINT (it->ctl_chars[i * 4 + 2], g);
-                     g = FAST_MAKE_GLYPH ((str[i] & 7) + '0', 0); 
+                     g = FAST_MAKE_GLYPH ((str[i] & 7) + '0', 0);
                      XSETINT (it->ctl_chars[i * 4 + 3], g);
                    }
 
@@ -4357,7 +4435,7 @@ set_iterator_to_next (it, reseat_p)
      with box.  Reset them at the start of this function because
      moving the iterator to a new position might set them.  */
   it->start_of_box_run_p = it->end_of_box_run_p = 0;
-  
+
   if (it->method == next_element_from_buffer)
     {
       /* The current display element of IT is a character from
@@ -4407,7 +4485,7 @@ set_iterator_to_next (it, reseat_p)
       /* Restore face of the iterator to what they were before the
          display vector entry (these entries may contain faces).  */
       it->face_id = it->saved_face_id;
-      
+
       if (it->dpvec + it->current.dpvec_index == it->dpend)
        {
          if (it->s)
@@ -4436,14 +4514,14 @@ set_iterator_to_next (it, reseat_p)
       xassert (it->s == NULL && STRINGP (it->string));
       IT_STRING_BYTEPOS (*it) += it->len;
       IT_STRING_CHARPOS (*it) += 1;
-      
+
     consider_string_end:
 
       if (it->current.overlay_string_index >= 0)
        {
          /* IT->string is an overlay string.  Advance to the
             next, if there is one.  */
-         if (IT_STRING_CHARPOS (*it) >= XSTRING (it->string)->size)
+         if (IT_STRING_CHARPOS (*it) >= SCHARS (it->string))
            next_overlay_string (it);
        }
       else
@@ -4452,7 +4530,7 @@ set_iterator_to_next (it, reseat_p)
             its end, and there is something on IT->stack, proceed
             with what is on the stack.  This can be either another
             string, this time an overlay string, or a buffer.  */
-         if (IT_STRING_CHARPOS (*it) == XSTRING (it->string)->size
+         if (IT_STRING_CHARPOS (*it) == SCHARS (it->string)
              && it->sp > 0)
            {
              pop_it (it);
@@ -4504,7 +4582,7 @@ next_element_from_display_vector (it)
   /* Remember the current face id in case glyphs specify faces.
      IT's face is restored in set_iterator_to_next.  */
   it->saved_face_id = it->face_id;
-  
+
   if (INTEGERP (*it->dpvec)
       && GLYPH_CHAR_VALID_P (XFASTINT (*it->dpvec)))
     {
@@ -4570,22 +4648,21 @@ next_element_from_string (it)
       /* Get the next character from an overlay string.  In overlay
         strings, There is no field width or padding with spaces to
         do.  */
-      if (IT_STRING_CHARPOS (*it) >= XSTRING (it->string)->size)
+      if (IT_STRING_CHARPOS (*it) >= SCHARS (it->string))
        {
          it->what = IT_EOB;
          return 0;
        }
       else if (STRING_MULTIBYTE (it->string))
        {
-         int remaining = (STRING_BYTES (XSTRING (it->string))
-                          - IT_STRING_BYTEPOS (*it));
-         unsigned char *s = (XSTRING (it->string)->data
-                             + IT_STRING_BYTEPOS (*it));
+         int remaining = SBYTES (it->string) - IT_STRING_BYTEPOS (*it);
+         const unsigned char *s = (SDATA (it->string)
+                                   + IT_STRING_BYTEPOS (*it));
          it->c = string_char_and_length (s, remaining, &it->len);
        }
       else
        {
-         it->c = XSTRING (it->string)->data[IT_STRING_BYTEPOS (*it)];
+         it->c = SREF (it->string, IT_STRING_BYTEPOS (*it));
          it->len = 1;
        }
     }
@@ -4608,15 +4685,14 @@ next_element_from_string (it)
        }
       else if (STRING_MULTIBYTE (it->string))
        {
-         int maxlen = (STRING_BYTES (XSTRING (it->string))
-                       - IT_STRING_BYTEPOS (*it));
-         unsigned char *s = (XSTRING (it->string)->data
-                             + IT_STRING_BYTEPOS (*it));
+         int maxlen = SBYTES (it->string) - IT_STRING_BYTEPOS (*it);
+         const unsigned char *s = (SDATA (it->string)
+                                   + IT_STRING_BYTEPOS (*it));
          it->c = string_char_and_length (s, maxlen, &it->len);
        }
       else
        {
-         it->c = XSTRING (it->string)->data[IT_STRING_BYTEPOS (*it)];
+         it->c = SREF (it->string, IT_STRING_BYTEPOS (*it));
          it->len = 1;
        }
     }
@@ -4643,12 +4719,12 @@ next_element_from_c_string (it)
      struct it *it;
 {
   int success_p = 1;
-  
+
   xassert (it->s);
   it->what = IT_CHARACTER;
   BYTEPOS (it->position) = CHARPOS (it->position) = 0;
   it->object = Qnil;
-  
+
   /* IT's position can be greater IT->string_nchars in case a field
      width or precision has been specified when the iterator was
      initialized.  */
@@ -4675,7 +4751,7 @@ next_element_from_c_string (it)
     }
   else
     it->c = it->s[IT_BYTEPOS (*it)], it->len = 1;
-  
+
   return success_p;
 }
 
@@ -4723,7 +4799,7 @@ next_element_from_ellipsis (it)
       reseat_at_next_visible_line_start (it, 1);
       it->face_before_selective_p = 1;
     }
-  
+
   return get_next_display_element (it);
 }
 
@@ -4731,7 +4807,7 @@ next_element_from_ellipsis (it)
 /* Deliver an image display element.  The iterator IT is already
    filled with image information (done in handle_display_prop).  Value
    is always 1.  */
-  
+
 
 static int
 next_element_from_image (it)
@@ -4776,7 +4852,7 @@ next_element_from_buffer (it)
       if (IT_CHARPOS (*it) >= it->end_charpos)
        {
          int overlay_strings_follow_p;
-         
+
          /* End of the game, except when overlay strings follow that
             haven't been returned yet.  */
          if (it->overlay_strings_at_end_processed_p)
@@ -4843,7 +4919,7 @@ next_element_from_buffer (it)
                  && IT_CHARPOS (*it) + 1 < ZV
                  && indented_beyond_p (IT_CHARPOS (*it) + 1,
                                        IT_BYTEPOS (*it) + 1,
-                                       it->selective))
+                                       (double) it->selective)) /* iftc */
                {
                  success_p = next_element_from_ellipsis (it);
                  it->dpvec_char_len = -1;
@@ -4865,7 +4941,7 @@ next_element_from_buffer (it)
   return success_p;
 }
 
-     
+
 /* Run the redisplay end trigger hook for IT.  */
 
 static void
@@ -4888,7 +4964,7 @@ run_redisplay_end_trigger_hook (it)
      them again, even if they get an error.  */
   it->w->redisplay_end_trigger = Qnil;
   Frun_hook_with_args (3, args);
-  
+
   /* Notice if it changed the face of the character we are on.  */
   handle_face_prop (it);
 }
@@ -4918,28 +4994,28 @@ next_element_from_composition (it)
 /* Move iterator IT to a specified buffer or X position within one
    line on the display without producing glyphs.
 
-   Begin to skip at IT's current position.  Skip to TO_CHARPOS or TO_X
-   whichever is reached first.
+   OP should be a bit mask including some or all of these bits:
+    MOVE_TO_X: Stop on reaching x-position TO_X.
+    MOVE_TO_POS: Stop on reaching buffer or string position TO_CHARPOS.
+   Regardless of OP's value, stop in reaching the end of the display line.
 
-   TO_CHARPOS <= 0 means no TO_CHARPOS is specified.
+   TO_X is normally a value 0 <= TO_X <= IT->last_visible_x.
+   This means, in particular, that TO_X includes window's horizontal
+   scroll amount.
 
-   TO_X < 0 means that no TO_X is specified.  TO_X is normally a value
-   0 <= TO_X <= IT->last_visible_x.  This means in particular, that
-   TO_X includes the amount by which a window is horizontally
-   scrolled.
-
-   Value is
+   The return value has several possible values that
+   say what condition caused the scan to stop:
 
    MOVE_POS_MATCH_OR_ZV
      - when TO_POS or ZV was reached.
-       
+
    MOVE_X_REACHED
      -when TO_X was reached before TO_POS or ZV were reached.
-       
+
    MOVE_LINE_CONTINUED
      - when we reached the end of the display area and the line must
      be continued.
-                          
+
    MOVE_LINE_TRUNCATED
      - when we reached the end of the display area and the line is
      truncated.
@@ -4963,7 +5039,7 @@ move_it_in_display_line_to (it, to_charpos, to_x, op)
   while (1)
     {
       int x, i, ascent = 0, descent = 0;
-      
+
       /* Stop when ZV or TO_CHARPOS reached.  */
       if (!get_next_display_element (it)
          || ((op & MOVE_TO_POS) != 0
@@ -4973,13 +5049,13 @@ move_it_in_display_line_to (it, to_charpos, to_x, op)
          result = MOVE_POS_MATCH_OR_ZV;
          break;
        }
-         
+
       /* The call to produce_glyphs will get the metrics of the
         display element IT is loaded with.  We record in x the
         x-position before this display element in case it does not
         fit on the line.  */
       x = it->current_x;
-      
+
       /* Remember the line height so far in case the next element doesn't
         fit on the line.  */
       if (!it->truncate_lines_p)
@@ -4987,7 +5063,7 @@ move_it_in_display_line_to (it, to_charpos, to_x, op)
          ascent = it->max_ascent;
          descent = it->max_descent;
        }
-      
+
       PRODUCE_GLYPHS (it);
 
       if (it->area != TEXT_AREA)
@@ -5020,7 +5096,7 @@ move_it_in_display_line_to (it, to_charpos, to_x, op)
             glyphs have the same width.  */
          int single_glyph_width = it->pixel_width / it->nglyphs;
          int new_x;
-         
+
          for (i = 0; i < it->nglyphs; ++i, x = new_x)
            {
              new_x = x + single_glyph_width;
@@ -5058,7 +5134,7 @@ move_it_in_display_line_to (it, to_charpos, to_x, op)
                      it->max_ascent = ascent;
                      it->max_descent = descent;
                    }
-                 
+
                  TRACE_MOVE ((stderr, "move_it_in: continued at %d\n",
                               IT_CHARPOS (*it)));
                  result = MOVE_LINE_CONTINUED;
@@ -5072,7 +5148,7 @@ move_it_in_display_line_to (it, to_charpos, to_x, op)
                }
              else
                {
-                 /* Glyph is completely off the left margin of the display 
+                 /* Glyph is completely off the left margin of the display
                     area.  Nothing to do.  */
                }
            }
@@ -5090,18 +5166,18 @@ move_it_in_display_line_to (it, to_charpos, to_x, op)
          result = MOVE_X_REACHED;
          break;
        }
-  
+
       /* Is this a line end?  If yes, we're done.  */
       if (ITERATOR_AT_END_OF_LINE_P (it))
        {
          result = MOVE_NEWLINE_OR_CR;
          break;
        }
-      
+
       /* The current display element has been consumed.  Advance
         to the next.  */
       set_iterator_to_next (it, 1);
-      
+
       /* Stop if lines are truncated and IT's current x-position is
         past the right edge of the window now.  */
       if (it->truncate_lines_p
@@ -5119,10 +5195,13 @@ move_it_in_display_line_to (it, to_charpos, to_x, op)
 }
 
 
-/* Move IT forward to a specified buffer position TO_CHARPOS, TO_X,
-   TO_Y, TO_VPOS.  OP is a bit-mask that specifies where to stop.  See
-   the description of enum move_operation_enum.
-   
+/* Move IT forward until it satisfies one or more of the criteria in
+   TO_CHARPOS, TO_X, TO_Y, and TO_VPOS.
+
+   OP is a bit-mask that specifies where to stop, and in particular,
+   which of those four position arguments makes a difference.  See the
+   description of enum move_operation_enum.
+
    If TO_CHARPOS is in invisible text, e.g. a truncated part of a
    screen line, this function will set IT to the next position >
    TO_CHARPOS.  */
@@ -5162,7 +5241,7 @@ move_it_to (it, to_charpos, to_x, to_y, to_vpos, op)
                  reached = 2;
                  break;
                }
-             
+
              skip = move_it_in_display_line_to (it, to_charpos, to_x, op);
 
              if (skip == MOVE_POS_MATCH_OR_ZV || it->vpos == to_vpos)
@@ -5186,7 +5265,7 @@ move_it_to (it, to_charpos, to_x, to_y, to_vpos, op)
       else if (op & MOVE_TO_Y)
        {
          struct it it_backup;
-         
+
          /* TO_Y specified means stop at TO_X in the line containing
             TO_Y---or at TO_CHARPOS if this is reached first.  The
             problem is that we can't really tell whether the line
@@ -5211,7 +5290,7 @@ move_it_to (it, to_charpos, to_x, to_y, to_vpos, op)
              reached = 5;
              break;
            }
-         
+
          /* If TO_X was reached, we would like to know whether TO_Y
             is in the line.  This can only be said if we know the
             total line height which requires us to scan the rest of
@@ -5228,7 +5307,7 @@ move_it_to (it, to_charpos, to_x, to_y, to_vpos, op)
          /* Now, decide whether TO_Y is in this line.  */
          line_height = it->max_ascent + it->max_descent;
          TRACE_MOVE ((stderr, "move_it: line_height = %d\n", line_height));
-         
+
          if (to_y >= it->current_y
              && to_y < it->current_y + line_height)
            {
@@ -5291,7 +5370,7 @@ move_it_to (it, to_charpos, to_x, to_y, to_vpos, op)
       last_max_ascent = it->max_ascent;
       it->max_ascent = it->max_descent = 0;
     }
-  
+
  out:
 
   TRACE_MOVE ((stderr, "move_it_to: reached %d\n", reached));
@@ -5311,10 +5390,10 @@ move_it_vertically_backward (it, dy)
      struct it *it;
      int dy;
 {
-  int nlines, h, line_height;
-  struct it it2;
+  int nlines, h;
+  struct it it2, it3;
   int start_pos = IT_CHARPOS (*it);
-  
+
   xassert (dy >= 0);
 
   /* Estimate how many newlines we must move back.  */
@@ -5342,8 +5421,8 @@ move_it_vertically_backward (it, dy)
   move_it_to (&it2, start_pos, -1, -1, it2.vpos + 1,
              MOVE_TO_POS | MOVE_TO_VPOS);
   xassert (IT_CHARPOS (*it) >= BEGV);
-  line_height = it2.max_ascent + it2.max_descent;
-  
+  it3 = it2;
+
   move_it_to (&it2, start_pos, -1, -1, -1, MOVE_TO_POS);
   xassert (IT_CHARPOS (*it) >= BEGV);
   h = it2.current_y - it->current_y;
@@ -5352,7 +5431,7 @@ move_it_vertically_backward (it, dy)
   /* Correct IT's y and vpos position.  */
   it->vpos -= nlines;
   it->current_y -= h;
-  
+
   if (dy == 0)
     {
       /* DY == 0 means move to the start of the screen line.  The
@@ -5366,19 +5445,47 @@ move_it_vertically_backward (it, dy)
       /* The y-position we try to reach.  Note that h has been
          subtracted in front of the if-statement.  */
       int target_y = it->current_y + h - dy;
+      int y0 = it3.current_y;
+      int y1 = line_bottom_y (&it3);
+      int line_height = y1 - y0;
 
       /* If we did not reach target_y, try to move further backward if
         we can.  If we moved too far backward, try to move forward.  */
       if (target_y < it->current_y
+         /* This is heuristic.  In a window that's 3 lines high, with
+            a line height of 13 pixels each, recentering with point
+            on the bottom line will try to move -39/2 = 19 pixels
+            backward.  Try to avoid moving into the first line.  */
+         && it->current_y - target_y > line_height / 3 * 2
          && IT_CHARPOS (*it) > BEGV)
        {
+         TRACE_MOVE ((stderr, "  not far enough -> move_vert %d\n",
+                      target_y - it->current_y));
          move_it_vertically (it, target_y - it->current_y);
          xassert (IT_CHARPOS (*it) >= BEGV);
        }
       else if (target_y >= it->current_y + line_height
               && IT_CHARPOS (*it) < ZV)
        {
-         move_it_vertically (it, target_y - (it->current_y + line_height));
+         /* Should move forward by at least one line, maybe more.
+
+            Note: Calling move_it_by_lines can be expensive on
+            terminal frames, where compute_motion is used (via
+            vmotion) to do the job, when there are very long lines
+            and truncate-lines is nil.  That's the reason for
+            treating terminal frames specially here.  */
+
+         if (!FRAME_WINDOW_P (it->f))
+           move_it_vertically (it, target_y - (it->current_y + line_height));
+         else
+           {
+             do
+               {
+                 move_it_by_lines (it, 1, 1);
+               }
+             while (target_y >= line_bottom_y (it) && IT_CHARPOS (*it) < ZV);
+           }
+
          xassert (IT_CHARPOS (*it) >= BEGV);
        }
     }
@@ -5389,7 +5496,7 @@ move_it_vertically_backward (it, dy)
    move backwards.  DY = 0 means move to start of screen line.  At the
    end, IT will be on the start of a screen line.  */
 
-void 
+void
 move_it_vertically (it, dy)
     struct it *it;
     int dy;
@@ -5419,7 +5526,7 @@ move_it_past_eol (it)
      struct it *it;
 {
   enum move_it_result rc;
-  
+
   rc = move_it_in_display_line_to (it, Z, 0, MOVE_TO_POS);
   if (rc == MOVE_NEWLINE_OR_CR)
     set_iterator_to_next (it, 0);
@@ -5439,7 +5546,7 @@ invisible_text_between_p (it, start_charpos, end_charpos)
 {
   Lisp_Object prop, limit;
   int invisible_found_p;
-  
+
   xassert (it != NULL && start_charpos <= end_charpos);
 
   /* Is text at START invisible?  */
@@ -5476,11 +5583,11 @@ move_it_by_lines (it, dvpos, need_y_p)
      int dvpos, need_y_p;
 {
   struct position pos;
-  
+
   if (!FRAME_WINDOW_P (it->f))
     {
       struct text_pos textpos;
-      
+
       /* We can use vmotion on frames without proportional fonts.  */
       pos = *vmotion (IT_CHARPOS (*it), dvpos, it->w);
       SET_TEXT_POS (textpos, pos.bufpos, pos.bytepos);
@@ -5500,11 +5607,11 @@ move_it_by_lines (it, dvpos, need_y_p)
     {
       struct it it2;
       int start_charpos, i;
-      
+
       /* Start at the beginning of the screen line containing IT's
         position.  */
       move_it_vertically_backward (it, 0);
-      
+
       /* Go back -DVPOS visible lines and reseat the iterator there.  */
       start_charpos = IT_CHARPOS (*it);
       for (i = -dvpos; i && IT_CHARPOS (*it) > BEGV; --i)
@@ -5559,16 +5666,16 @@ add_to_log (format, arg1, arg2)
 
   fmt = msg = Qnil;
   GCPRO4 (fmt, msg, arg1, arg2);
-  
+
   args[0] = fmt = build_string (format);
   args[1] = arg1;
   args[2] = arg2;
   msg = Fformat (3, args);
 
-  len = STRING_BYTES (XSTRING (msg)) + 1;
+  len = SBYTES (msg) + 1;
   buffer = (char *) alloca (len);
-  bcopy (XSTRING (msg)->data, buffer, len);
-  
+  bcopy (SDATA (msg), buffer, len);
+
   message_dolog (buffer, len - 1, 1, 0);
   UNGCPRO;
 }
@@ -5592,9 +5699,12 @@ message_log_maybe_newline ()
 
 void
 message_dolog (m, nbytes, nlflag, multibyte)
-     char *m;
+     const char *m;
      int nbytes, nlflag, multibyte;
 {
+  if (!NILP (Vmemory_full))
+    return;
+
   if (!NILP (Vmessage_log_max))
     {
       struct buffer *oldbuf;
@@ -5603,17 +5713,20 @@ message_dolog (m, nbytes, nlflag, multibyte)
       int point_at_end = 0;
       int zv_at_end = 0;
       Lisp_Object old_deactivate_mark, tem;
-      struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
+      struct gcpro gcpro1;
 
       old_deactivate_mark = Vdeactivate_mark;
       oldbuf = current_buffer;
       Fset_buffer (Fget_buffer_create (Vmessages_buffer_name));
       current_buffer->undo_list = Qt;
 
-      oldpoint = Fpoint_marker ();
-      oldbegv = Fpoint_min_marker ();
-      oldzv = Fpoint_max_marker ();
-      GCPRO4 (oldpoint, oldbegv, oldzv, old_deactivate_mark);
+      oldpoint = message_dolog_marker1;
+      set_marker_restricted (oldpoint, make_number (PT), Qnil);
+      oldbegv = message_dolog_marker2;
+      set_marker_restricted (oldbegv, make_number (BEGV), Qnil);
+      oldzv = message_dolog_marker3;
+      set_marker_restricted (oldzv, make_number (ZV), Qnil);
+      GCPRO1 (old_deactivate_mark);
 
       if (PT == Z)
        point_at_end = 1;
@@ -5633,7 +5746,7 @@ message_dolog (m, nbytes, nlflag, multibyte)
        {
          int i, c, char_bytes;
          unsigned char work[1];
-         
+
          /* Convert a multibyte string to single-byte
             for the *Message* buffer.  */
          for (i = 0; i < nbytes; i += nbytes)
@@ -5672,6 +5785,8 @@ message_dolog (m, nbytes, nlflag, multibyte)
          this_bol = PT;
          this_bol_byte = PT_BYTE;
 
+         /* See if this line duplicates the previous one.
+            If so, combine duplicates.  */
          if (this_bol > BEG)
            {
              scan_newline (PT, PT_BYTE, BEG, BEG_BYTE, -2, 0);
@@ -5699,6 +5814,10 @@ message_dolog (m, nbytes, nlflag, multibyte)
                }
            }
 
+         /* If we have more than the desired maximum number of lines
+            in the *Messages* buffer now, delete the oldest ones.
+            This is safe because we don't have undo in this buffer.  */
+
          if (NATNUMP (Vmessage_log_max))
            {
              scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
@@ -5729,9 +5848,9 @@ message_dolog (m, nbytes, nlflag, multibyte)
                          XMARKER (oldpoint)->bytepos);
 
       UNGCPRO;
-      free_marker (oldpoint);
-      free_marker (oldbegv);
-      free_marker (oldzv);
+      unchain_marker (oldpoint);
+      unchain_marker (oldbegv);
+      unchain_marker (oldzv);
 
       tem = Fget_buffer_window (Fcurrent_buffer (), Qt);
       set_buffer_internal (oldbuf);
@@ -5794,7 +5913,7 @@ message_log_check_duplicate (prev_bol, prev_bol_byte, this_bol, this_bol_byte)
 
 void
 message2 (m, nbytes, multibyte)
-     char *m;
+     const char *m;
      int nbytes;
      int multibyte;
 {
@@ -5810,7 +5929,7 @@ message2 (m, nbytes, multibyte)
 
 void
 message2_nolog (m, nbytes, multibyte)
-     char *m;
+     const char *m;
      int nbytes;
 {
   struct frame *sf = SELECTED_FRAME ();
@@ -5830,7 +5949,7 @@ message2_nolog (m, nbytes, multibyte)
   /* A null message buffer means that the frame hasn't really been
      initialized yet.  Error messages get reported properly by
      cmd_error, so this must be just an informative message; toss it.  */
-  else if (INTERACTIVE 
+  else if (INTERACTIVE
           && sf->glyphs_initialized_p
           && FRAME_MESSAGE_BUF (sf))
     {
@@ -5879,11 +5998,11 @@ message3 (m, nbytes, multibyte)
   struct gcpro gcpro1;
 
   GCPRO1 (m);
-  
+
   /* First flush out any partial line written with print.  */
   message_log_maybe_newline ();
   if (STRINGP (m))
-    message_dolog (XSTRING (m)->data, nbytes, 1, multibyte);
+    message_dolog (SDATA (m), nbytes, 1, multibyte);
   message3_nolog (m, nbytes, multibyte);
 
   UNGCPRO;
@@ -5906,7 +6025,7 @@ message3_nolog (m, nbytes, multibyte)
        putc ('\n', stderr);
       noninteractive_need_newline = 0;
       if (STRINGP (m))
-       fwrite (XSTRING (m)->data, nbytes, 1, stderr);
+       fwrite (SDATA (m), nbytes, 1, stderr);
       if (cursor_in_echo_area == 0)
        fprintf (stderr, "\n");
       fflush (stderr);
@@ -5914,7 +6033,7 @@ message3_nolog (m, nbytes, multibyte)
   /* A null message buffer means that the frame hasn't really been
      initialized yet.  Error messages get reported properly by
      cmd_error, so this must be just an informative message; toss it.  */
-  else if (INTERACTIVE 
+  else if (INTERACTIVE
           && sf->glyphs_initialized_p
           && FRAME_MESSAGE_BUF (sf))
     {
@@ -5933,7 +6052,7 @@ message3_nolog (m, nbytes, multibyte)
          && !FRAME_VISIBLE_P (f))
        Fmake_frame_visible (frame);
 
-      if (STRINGP (m) && XSTRING (m)->size)
+      if (STRINGP (m) && SCHARS (m) > 0)
        {
          set_message (NULL, m, nbytes, multibyte);
          if (minibuffer_auto_raise)
@@ -5985,6 +6104,8 @@ message_with_string (m, string, log)
      Lisp_Object string;
      int log;
 {
+  CHECK_STRING (string);
+
   if (noninteractive)
     {
       if (m)
@@ -5992,7 +6113,7 @@ message_with_string (m, string, log)
          if (noninteractive_need_newline)
            putc ('\n', stderr);
          noninteractive_need_newline = 0;
-         fprintf (stderr, m, XSTRING (string)->data);
+         fprintf (stderr, m, SDATA (string));
          if (cursor_in_echo_area == 0)
            fprintf (stderr, "\n");
          fflush (stderr);
@@ -6016,19 +6137,22 @@ message_with_string (m, string, log)
         cmd_error, so this must be just an informative message; toss it.  */
       if (FRAME_MESSAGE_BUF (f))
        {
-         int len;
-         char *a[1];
-         a[0] = (char *) XSTRING (string)->data;
+         Lisp_Object args[2], message;
+         struct gcpro gcpro1, gcpro2;
 
-         len = doprnt (FRAME_MESSAGE_BUF (f),
-                       FRAME_MESSAGE_BUF_SIZE (f), m, (char *)0, 3, a);
+         args[0] = build_string (m);
+         args[1] = message = string;
+         GCPRO2 (args[0], message);
+         gcpro1.nvars = 2;
+
+         message = Fformat (2, args);
 
          if (log)
-           message2 (FRAME_MESSAGE_BUF (f), len,
-                     STRING_MULTIBYTE (string));
+           message3 (message, SBYTES (message), STRING_MULTIBYTE (message));
          else
-           message2_nolog (FRAME_MESSAGE_BUF (f), len,
-                           STRING_MULTIBYTE (string));
+           message3_nolog (message, SBYTES (message), STRING_MULTIBYTE (message));
+
+         UNGCPRO;
 
          /* Print should start at the beginning of the message
             buffer next time.  */
@@ -6135,14 +6259,14 @@ update_echo_area ()
     {
       Lisp_Object string;
       string = Fcurrent_message ();
-      message3 (string, XSTRING (string)->size, 
+      message3 (string, SBYTES (string),
                !NILP (current_buffer->enable_multibyte_characters));
     }
 }
 
 
-/* Make sure echo area buffers in echo_buffers[] are life.  If they
-   aren't, make new ones.  */
+/* Make sure echo area buffers in `echo_buffers' are live.
+   If they aren't, make new ones.  */
 
 static void
 ensure_echo_area_buffers ()
@@ -6183,7 +6307,7 @@ ensure_echo_area_buffers ()
    that the current message becomes the last displayed one, make
    choose a suitable buffer for echo_area_buffer[0], and clear it.
 
-   Value is what FN returns. */
+   Value is what FN returns.  */
 
 static int
 with_echo_area_buffer (w, which, fn, a1, a2, a3, a4)
@@ -6196,13 +6320,13 @@ with_echo_area_buffer (w, which, fn, a1, a2, a3, a4)
 {
   Lisp_Object buffer;
   int this_one, the_other, clear_buffer_p, rc;
-  int count = BINDING_STACK_SIZE ();
+  int count = SPECPDL_INDEX ();
 
-  /* If buffers aren't life, make new ones.  */
+  /* If buffers aren't live, make new ones.  */
   ensure_echo_area_buffers ();
 
   clear_buffer_p = 0;
-  
+
   if (which == 0)
     this_one = 0, the_other = 1;
   else if (which > 0)
@@ -6211,7 +6335,7 @@ with_echo_area_buffer (w, which, fn, a1, a2, a3, a4)
     {
       this_one = 0, the_other = 1;
       clear_buffer_p = 1;
-      
+
       /* We need a fresh one in case the current echo buffer equals
         the one containing the last displayed echo area message.  */
       if (!NILP (echo_area_buffer[this_one])
@@ -6289,14 +6413,14 @@ with_echo_area_buffer_unwind_data (w)
      Vwith_echo_area_save_vector.  */
   vector = Vwith_echo_area_save_vector;
   Vwith_echo_area_save_vector = Qnil;
-  
+
   if (NILP (vector))
     vector = Fmake_vector (make_number (7), Qnil);
-  
+
   XSETBUFFER (AREF (vector, i), current_buffer); ++i;
   AREF (vector, i) = Vdeactivate_mark, ++i;
   AREF (vector, i) = make_number (windows_or_buffers_changed), ++i;
-  
+
   if (w)
     {
       XSETWINDOW (AREF (vector, i), w); ++i;
@@ -6331,12 +6455,12 @@ unwind_with_echo_area_buffer (vector)
     {
       struct window *w;
       Lisp_Object buffer, charpos, bytepos;
-      
+
       w = XWINDOW (AREF (vector, 3));
       buffer = AREF (vector, 4);
       charpos = AREF (vector, 5);
       bytepos = AREF (vector, 6);
-      
+
       w->buffer = buffer;
       set_marker_both (w->pointm, buffer,
                       XFASTINT (charpos), XFASTINT (bytepos));
@@ -6361,18 +6485,19 @@ setup_echo_area_for_printing (multibyte_p)
       /* A message has been output since the last time we printed.
         Choose a fresh echo area buffer.  */
       if (EQ (echo_area_buffer[1], echo_buffer[0]))
-       echo_area_buffer[0] = echo_buffer[1]; 
+       echo_area_buffer[0] = echo_buffer[1];
       else
        echo_area_buffer[0] = echo_buffer[0];
 
       /* Switch to that buffer and clear it.  */
       set_buffer_internal (XBUFFER (echo_area_buffer[0]));
       current_buffer->truncate_lines = Qnil;
-      
+
       if (Z > BEG)
        {
-         int count = BINDING_STACK_SIZE ();
+         int count = SPECPDL_INDEX ();
          specbind (Qinhibit_read_only, Qt);
+         /* Note that undo recording is always disabled.  */
          del_range (BEG, Z);
          unbind_to (count, Qnil);
        }
@@ -6400,11 +6525,11 @@ setup_echo_area_for_printing (multibyte_p)
       if (NILP (echo_area_buffer[0]))
        {
          if (EQ (echo_area_buffer[1], echo_buffer[0]))
-           echo_area_buffer[0] = echo_buffer[1]; 
+           echo_area_buffer[0] = echo_buffer[1];
          else
            echo_area_buffer[0] = echo_buffer[0];
        }
-      
+
       if (current_buffer != XBUFFER (echo_area_buffer[0]))
        {
          /* Someone switched buffers between print requests.  */
@@ -6439,7 +6564,7 @@ display_echo_area (w)
      with_echo_area_buffer will sets it to an empty buffer.  */
   i = display_last_displayed_message_p ? 1 : 0;
   no_message_p = NILP (echo_area_buffer[i]);
-  
+
   window_height_changed_p
     = with_echo_area_buffer (w, display_last_displayed_message_p,
                             display_echo_area_1,
@@ -6502,7 +6627,7 @@ resize_echo_area_exactly ()
        resize_exactly = Qt;
       else
        resize_exactly = Qnil;
-      
+
       resized_p = with_echo_area_buffer (w, 0, resize_mini_window_1,
                                         (EMACS_INT) w, resize_exactly, 0, 0);
       if (resized_p)
@@ -6534,7 +6659,7 @@ resize_mini_window_1 (a1, exactly, a3, a4)
 /* Resize mini-window W to fit the size of its contents.  EXACT:P
    means size the window exactly to the size needed.  Otherwise, it's
    only enlarged until W's buffer is empty.  Value is non-zero if
-   the window height has been changed. */
+   the window height has been changed.  */
 
 int
 resize_mini_window (w, exact_p)
@@ -6554,12 +6679,12 @@ resize_mini_window (w, exact_p)
      functions with safe_call which binds inhibit-redisplay to t.  */
   if (!NILP (Vinhibit_redisplay))
     return 0;
-  
+
   /* Nil means don't try to resize.  */
   if (NILP (Vresize_mini_windows)
       || (FRAME_X_P (f) && f->output_data.x == NULL))
     return 0;
-  
+
   if (!FRAME_MINIBUF_ONLY_P (f))
     {
       struct it it;
@@ -6585,11 +6710,11 @@ resize_mini_window (w, exact_p)
        max_height = XINT (Vmax_mini_window_height);
       else
        max_height = total_height / 4;
-      
-      /* Correct that max. height if it's bogus. */
+
+      /* Correct that max. height if it's bogus.  */
       max_height = max (1, max_height);
       max_height = min (total_height, max_height);
-      
+
       /* Find out the height of the text in the window.  */
       if (it.truncate_lines_p)
        height = 1;
@@ -6604,7 +6729,7 @@ resize_mini_window (w, exact_p)
          height -= it.extra_line_spacing;
          height = (height + unit - 1) / unit;
        }
-      
+
       /* Compute a suitable window start.  */
       if (height > max_height)
        {
@@ -6637,7 +6762,7 @@ resize_mini_window (w, exact_p)
              window_height_changed_p = XFASTINT (w->height) != old_height;
            }
        }
-      else 
+      else
        {
          /* Always resize to exact size needed.  */
          if (height > XFASTINT (w->height))
@@ -6658,7 +6783,7 @@ resize_mini_window (w, exact_p)
                  freeze_window_starts (f, 1);
                  grow_mini_window (w, height - XFASTINT (w->height));
                }
-             
+
              window_height_changed_p = XFASTINT (w->height) != old_height;
            }
        }
@@ -6688,7 +6813,7 @@ current_message ()
       if (NILP (msg))
        echo_area_buffer[0] = Qnil;
     }
-  
+
   return msg;
 }
 
@@ -6700,7 +6825,7 @@ current_message_1 (a1, a2, a3, a4)
      EMACS_INT a3, a4;
 {
   Lisp_Object *msg = (Lisp_Object *) a1;
-  
+
   if (Z > BEG)
     *msg = make_buffer_string (BEG, Z, 1);
   else
@@ -6741,11 +6866,11 @@ void
 restore_message ()
 {
   Lisp_Object msg;
-  
+
   xassert (CONSP (Vmessage_stack));
   msg = XCAR (Vmessage_stack);
   if (STRINGP (msg))
-    message3_nolog (msg, STRING_BYTES (XSTRING (msg)), STRING_MULTIBYTE (msg));
+    message3_nolog (msg, SBYTES (msg), STRING_MULTIBYTE (msg));
   else
     message3_nolog (msg, 0, 0);
 }
@@ -6825,14 +6950,14 @@ truncate_message_1 (nchars, a2, a3, a4)
 
 void
 set_message (s, string, nbytes, multibyte_p)
-     char *s;
+     const char *s;
      Lisp_Object string;
      int nbytes;
 {
   message_enable_multibyte
     = ((s && multibyte_p)
        || (STRINGP (string) && STRING_MULTIBYTE (string)));
-  
+
   with_echo_area_buffer (0, -1, set_message_1,
                         (EMACS_INT) s, string, nbytes, multibyte_p);
   message_buf_print = 0;
@@ -6851,29 +6976,29 @@ set_message_1 (a1, a2, nbytes, multibyte_p)
      Lisp_Object a2;
      EMACS_INT nbytes, multibyte_p;
 {
-  char *s = (char *) a1;
+  const char *s = (const char *) a1;
   Lisp_Object string = a2;
-  
+
   xassert (BEG == Z);
-  
+
   /* Change multibyteness of the echo buffer appropriately.  */
   if (message_enable_multibyte
       != !NILP (current_buffer->enable_multibyte_characters))
     Fset_buffer_multibyte (message_enable_multibyte ? Qt : Qnil);
 
   current_buffer->truncate_lines = message_truncate_lines ? Qt : Qnil;
-  
+
   /* Insert new message at BEG.  */
   TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
 
   if (STRINGP (string))
     {
       int nchars;
-      
+
       if (nbytes == 0)
-       nbytes = XSTRING (string)->size_byte;
+       nbytes = SBYTES (string);
       nchars = string_byte_to_char (string, nbytes);
-      
+
       /* This function takes care of single/multibyte conversion.  We
          just have to ensure that the echo area buffer has the right
          setting of enable_multibyte_characters.  */
@@ -6883,13 +7008,13 @@ set_message_1 (a1, a2, nbytes, multibyte_p)
     {
       if (nbytes == 0)
        nbytes = strlen (s);
-      
+
       if (multibyte_p && NILP (current_buffer->enable_multibyte_characters))
        {
          /* Convert from multi-byte to single-byte.  */
          int i, c, n;
          unsigned char work[1];
-         
+
          /* Convert a multibyte string to single-byte.  */
          for (i = 0; i < nbytes; i += n)
            {
@@ -6905,9 +7030,9 @@ set_message_1 (a1, a2, nbytes, multibyte_p)
        {
          /* Convert from single-byte to multi-byte.  */
          int i, c, n;
-         unsigned char *msg = (unsigned char *) s;
+         const unsigned char *msg = (const unsigned char *) s;
          unsigned char str[MAX_MULTIBYTE_LENGTH];
-      
+
          /* Convert a single-byte string to multibyte.  */
          for (i = 0; i < nbytes; i++)
            {
@@ -6937,10 +7062,10 @@ clear_message (current_p, last_displayed_p)
       echo_area_buffer[0] = Qnil;
       message_cleared_p = 1;
     }
-  
+
   if (last_displayed_p)
     echo_area_buffer[1] = Qnil;
-  
+
   message_buf_print = 0;
 }
 
@@ -6959,20 +7084,26 @@ clear_garbaged_frames ()
   if (frame_garbaged)
     {
       Lisp_Object tail, frame;
-      
+      int changed_count = 0;
+
       FOR_EACH_FRAME (tail, frame)
        {
          struct frame *f = XFRAME (frame);
-         
+
          if (FRAME_VISIBLE_P (f) && FRAME_GARBAGED_P (f))
            {
+             if (f->resized_p)
+               Fredraw_frame (frame);
              clear_current_matrices (f);
+             changed_count++;
              f->garbaged = 0;
+             f->resized_p = 0;
            }
        }
 
       frame_garbaged = 0;
-      ++windows_or_buffers_changed;
+      if (changed_count)
+       ++windows_or_buffers_changed;
     }
 }
 
@@ -7000,12 +7131,12 @@ echo_area_display (update_frame_p)
     return 0;
 
 /* The terminal frame is used as the first Emacs frame on the Mac OS.  */
-#ifndef macintosh
+#ifndef MAC_OS8
 #ifdef HAVE_WINDOW_SYSTEM
   /* When Emacs starts, selected_frame may be a visible terminal
      frame, even if we run under a window system.  If we let this
      through, a message would be displayed on the terminal.  */
-  if (EQ (selected_frame, Vterminal_frame) 
+  if (EQ (selected_frame, Vterminal_frame)
       && !NILP (Vwindow_system))
     return 0;
 #endif /* HAVE_WINDOW_SYSTEM */
@@ -7036,7 +7167,7 @@ echo_area_display (update_frame_p)
             garbaged.  This looks odd, so we prevent it here.  */
          if (!display_completed)
            n = redisplay_mode_lines (FRAME_ROOT_WINDOW (f), 0);
-           
+
          if (window_height_changed_p
              /* Don't do this if Emacs is shutting down.  Redisplay
                 needs to run hooks.  */
@@ -7045,7 +7176,7 @@ echo_area_display (update_frame_p)
              /* Must update other windows.  Likewise as in other
                 cases, don't let this update be interrupted by
                 pending input.  */
-             int count = BINDING_STACK_SIZE ();
+             int count = SPECPDL_INDEX ();
              specbind (Qredisplay_dont_pause, Qt);
              windows_or_buffers_changed = 1;
              redisplay_internal (0);
@@ -7074,7 +7205,7 @@ echo_area_display (update_frame_p)
 
   /* Last displayed message is now the current message.  */
   echo_area_buffer[1] = echo_area_buffer[0];
-      
+
   /* Prevent redisplay optimization in redisplay_internal by resetting
      this_line_start_pos.  This is done because the mini-buffer now
      displays the message instead of its buffer text.  */
@@ -7091,7 +7222,8 @@ echo_area_display (update_frame_p)
  ***********************************************************************/
 
 
-#ifdef HAVE_WINDOW_SYSTEM
+/* The frame title buffering code is also used by Fformat_mode_line.
+   So it is not conditioned by HAVE_WINDOW_SYSTEM.  */
 
 /* A buffer for constructing frame titles in it; allocated from the
    heap in init_xdisp and resized as needed in store_frame_title_char.  */
@@ -7136,7 +7268,7 @@ store_frame_title_char (c)
 
 static int
 store_frame_title (str, field_width, precision)
-     unsigned char *str;
+     const unsigned char *str;
      int field_width, precision;
 {
   int n = 0;
@@ -7159,6 +7291,7 @@ store_frame_title (str, field_width, precision)
   return n;
 }
 
+#ifdef HAVE_WINDOW_SYSTEM
 
 /* Set the title of FRAME, if it has changed.  The title format is
    Vicon_title_format if FRAME is iconified, otherwise it is
@@ -7183,11 +7316,13 @@ x_consider_frame_title (frame)
 
       for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
        {
-         struct frame *tf = XFRAME (XCAR (tail));
+         Lisp_Object other_frame = XCAR (tail);
+         struct frame *tf = XFRAME (other_frame);
 
-         if (tf != f 
+         if (tf != f
              && FRAME_KBOARD (tf) == FRAME_KBOARD (f)
              && !FRAME_MINIBUF_ONLY_P (tf)
+             && !EQ (other_frame, tip_frame)
              && (FRAME_VISIBLE_P (tf) || FRAME_ICONIFIED_P (tf)))
            break;
        }
@@ -7199,33 +7334,28 @@ x_consider_frame_title (frame)
         frame_title_ptr so that display_mode_element will output into it;
         then display the title.  */
       obuf = current_buffer;
-      Fset_buffer (XWINDOW (f->selected_window)->buffer);
+      set_buffer_internal_1 (XBUFFER (XWINDOW (f->selected_window)->buffer));
       fmt = FRAME_ICONIFIED_P (f) ? Vicon_title_format : Vframe_title_format;
       frame_title_ptr = frame_title_buf;
       init_iterator (&it, XWINDOW (f->selected_window), -1, -1,
                     NULL, DEFAULT_FACE_ID);
-      display_mode_element (&it, 0, -1, -1, fmt);
+      display_mode_element (&it, 0, -1, -1, fmt, Qnil, 0);
       len = frame_title_ptr - frame_title_buf;
       frame_title_ptr = NULL;
-      set_buffer_internal (obuf);
+      set_buffer_internal_1 (obuf);
 
       /* Set the title only if it's changed.  This avoids consing in
         the common case where it hasn't.  (If it turns out that we've
         already wasted too much time by walking through the list with
         display_mode_element, then we might need to optimize at a
         higher level than this.)  */
-      if (! STRINGP (f->name) 
-         || STRING_BYTES (XSTRING (f->name)) != len
-         || bcmp (frame_title_buf, XSTRING (f->name)->data, len) != 0)
+      if (! STRINGP (f->name)
+         || SBYTES (f->name) != len
+         || bcmp (frame_title_buf, SDATA (f->name), len) != 0)
        x_implicitly_set_name (f, make_string (frame_title_buf, len), Qnil);
     }
 }
 
-#else /* not HAVE_WINDOW_SYSTEM */
-
-#define frame_title_ptr ((char *)0)
-#define store_frame_title(str, mincol, maxcol) 0
-
 #endif /* not HAVE_WINDOW_SYSTEM */
 
 
@@ -7247,7 +7377,7 @@ prepare_menu_bars ()
   struct frame *f;
   Lisp_Object tooltip_frame;
 
-#ifdef HAVE_X_WINDOWS
+#ifdef HAVE_WINDOW_SYSTEM
   tooltip_frame = tip_frame;
 #else
   tooltip_frame = Qnil;
@@ -7273,13 +7403,13 @@ prepare_menu_bars ()
 
   /* Update the menu bar item lists, if appropriate.  This has to be
      done before any actual redisplay or generation of display lines.  */
-  all_windows = (update_mode_lines 
+  all_windows = (update_mode_lines
                 || buffer_shared > 1
                 || windows_or_buffers_changed);
   if (all_windows)
     {
       Lisp_Object tail, frame;
-      int count = BINDING_STACK_SIZE ();
+      int count = SPECPDL_INDEX ();
 
       record_unwind_protect (Fset_match_data, Fmatch_data (Qnil, Qnil));
 
@@ -7290,18 +7420,18 @@ prepare_menu_bars ()
          /* Ignore tooltip frame.  */
          if (EQ (frame, tooltip_frame))
            continue;
-         
+
          /* If a window on this frame changed size, report that to
             the user and clear the size-change flag.  */
          if (FRAME_WINDOW_SIZES_CHANGED (f))
            {
              Lisp_Object functions;
-             
+
              /* Clear flag first in case we get an error below.  */
              FRAME_WINDOW_SIZES_CHANGED (f) = 0;
              functions = Vwindow_size_change_functions;
              GCPRO2 (tail, functions);
-             
+
              while (CONSP (functions))
                {
                  call1 (XCAR (functions), frame);
@@ -7309,7 +7439,7 @@ prepare_menu_bars ()
                }
              UNGCPRO;
            }
-         
+
          GCPRO1 (tail);
          update_menu_bar (f, 0);
 #ifdef HAVE_WINDOW_SYSTEM
@@ -7359,14 +7489,20 @@ update_menu_bar (f, save_match_data)
 
   window = FRAME_SELECTED_WINDOW (f);
   w = XWINDOW (window);
-  
+
+#if 0 /* The if statement below this if statement used to include the
+         condition !NILP (w->update_mode_line), rather than using
+         update_mode_lines directly, and this if statement may have
+         been added to make that condition work.  Now the if
+         statement below matches its comment, this isn't needed.  */
   if (update_mode_lines)
     w->update_mode_line = Qt;
+#endif
 
   if (FRAME_WINDOW_P (f)
       ?
-#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) || defined (macintosh)
-      FRAME_EXTERNAL_MENU_BAR (f) 
+#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) || defined (MAC_OS)
+      FRAME_EXTERNAL_MENU_BAR (f)
 #else
       FRAME_MENU_BAR_LINES (f) > 0
 #endif
@@ -7380,7 +7516,9 @@ update_menu_bar (f, save_match_data)
         the rest of the redisplay algorithm is about the same as
         windows_or_buffers_changed anyway.  */
       if (windows_or_buffers_changed
-         || !NILP (w->update_mode_line)
+         /* This used to test w->update_mode_line, but we believe
+            there is no need to recompute the menu in that case.  */
+         || update_mode_lines
          || ((BUF_SAVE_MODIFF (XBUFFER (w->buffer))
               < BUF_MODIFF (XBUFFER (w->buffer)))
              != !NILP (w->last_had_star))
@@ -7389,7 +7527,7 @@ update_menu_bar (f, save_match_data)
              != !NILP (w->region_showing)))
        {
          struct buffer *prev = current_buffer;
-         int count = BINDING_STACK_SIZE ();
+         int count = SPECPDL_INDEX ();
 
          specbind (Qinhibit_menubar_update, Qt);
 
@@ -7404,19 +7542,19 @@ update_menu_bar (f, save_match_data)
 
          /* Run the Lucid hook.  */
          safe_run_hooks (Qactivate_menubar_hook);
-         
+
          /* If it has changed current-menubar from previous value,
             really recompute the menu-bar from the value.  */
          if (! NILP (Vlucid_menu_bar_dirty_flag))
            call0 (Qrecompute_lucid_menubar);
-         
+
          safe_run_hooks (Qmenu_bar_update_hook);
          FRAME_MENU_BAR_ITEMS (f) = menu_bar_items (FRAME_MENU_BAR_ITEMS (f));
-         
+
          /* Redisplay the menu bar in case we changed it.  */
-#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) || defined (macintosh)
+#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) || defined (MAC_OS)
          if (FRAME_WINDOW_P (f)
-#if defined (macintosh)
+#if defined (MAC_OS)
               /* All frames on Mac OS share the same menubar.  So only the
                  selected frame should be allowed to set it.  */
               && f == SELECTED_FRAME ()
@@ -7465,7 +7603,7 @@ update_tool_bar (f, save_match_data)
 
       window = FRAME_SELECTED_WINDOW (f);
       w = XWINDOW (window);
-  
+
       /* If the user has switched buffers or windows, we need to
         recompute to reflect the new bindings.  But we'll
         recompute when update_mode_lines is set too; that means
@@ -7483,7 +7621,7 @@ update_tool_bar (f, save_match_data)
              != !NILP (w->region_showing)))
        {
          struct buffer *prev = current_buffer;
-         int count = BINDING_STACK_SIZE ();
+         int count = SPECPDL_INDEX ();
 
          /* Set current_buffer to the buffer of the selected
             window of the frame, so that we get the right local
@@ -7504,7 +7642,7 @@ update_tool_bar (f, save_match_data)
          /* Build desired tool-bar items from keymaps.  */
          f->tool_bar_items
            = tool_bar_items (f->tool_bar_items, &f->n_tool_bar_items);
-         
+
          /* Redisplay the tool-bar in case we changed it.  */
          w->update_mode_line = Qt;
 
@@ -7532,15 +7670,15 @@ build_desired_tool_bar_string (f)
 
   /* Prepare F->desired_tool_bar_string.  If we can reuse it, do so.
      Otherwise, make a new string.  */
-  
+
   /* The size of the string we might be able to reuse.  */
   size = (STRINGP (f->desired_tool_bar_string)
-         ? XSTRING (f->desired_tool_bar_string)->size
+         ? SCHARS (f->desired_tool_bar_string)
          : 0);
 
   /* We need one space in the string for each image.  */
   size_needed = f->n_tool_bar_items;
-  
+
   /* Reuse f->desired_tool_bar_string, if possible.  */
   if (size < size_needed || NILP (f->desired_tool_bar_string))
     f->desired_tool_bar_string = Fmake_string (make_number (size_needed),
@@ -7577,7 +7715,7 @@ build_desired_tool_bar_string (f)
            idx = (selected_p
                   ? TOOL_BAR_IMAGE_DISABLED_SELECTED
                   : TOOL_BAR_IMAGE_DISABLED_DESELECTED);
-         
+
          xassert (ASIZE (image) >= idx);
          image = AREF (image, idx);
        }
@@ -7592,7 +7730,7 @@ build_desired_tool_bar_string (f)
       plist = Fcopy_sequence (XCDR (image));
 
       /* Compute margin and relief to draw.  */
-      relief = (tool_bar_button_relief > 0
+      relief = (tool_bar_button_relief >= 0
                ? tool_bar_button_relief
                : DEFAULT_TOOL_BAR_BUTTON_RELIEF);
       hmargin = vmargin = relief;
@@ -7608,12 +7746,12 @@ build_desired_tool_bar_string (f)
          if (INTEGERP (XCAR (Vtool_bar_button_margin))
              && XINT (XCAR (Vtool_bar_button_margin)) > 0)
            hmargin += XFASTINT (XCAR (Vtool_bar_button_margin));
-         
+
          if (INTEGERP (XCDR (Vtool_bar_button_margin))
              && XINT (XCDR (Vtool_bar_button_margin)) > 0)
            vmargin += XFASTINT (XCDR (Vtool_bar_button_margin));
        }
-      
+
       if (auto_raise_tool_bar_buttons_p)
        {
          /* Add a `:relief' property to the image spec if the item is
@@ -7648,13 +7786,13 @@ build_desired_tool_bar_string (f)
                                Fcons (make_number (hmargin),
                                       make_number (vmargin)));
        }
-         
+
       /* If button is not enabled, and we don't have special images
         for the disabled state, make the image appear disabled by
         applying an appropriate algorithm to it.  */
       if (!enabled_p && idx < 0)
        plist = Fplist_put (plist, QCconversion, Qdisabled);
-      
+
       /* Put a `display' text property on the string for the image to
         display.  Put a `menu-item' property on the string that gives
         the start of this item's properties in the tool-bar items
@@ -7667,7 +7805,7 @@ build_desired_tool_bar_string (f)
          string.  The string can be longer than needed when we reuse a
          previous string.  */
       if (i + 1 == f->n_tool_bar_items)
-       end = XSTRING (f->desired_tool_bar_string)->size;
+       end = SCHARS (f->desired_tool_bar_string);
       else
        end = i + 1;
       Fadd_text_properties (make_number (i), make_number (end),
@@ -7688,14 +7826,14 @@ display_tool_bar_line (it)
   struct glyph_row *row = it->glyph_row;
   int max_x = it->last_visible_x;
   struct glyph *last;
-  
+
   prepare_desired_row (row);
   row->y = it->current_y;
 
   /* Note that this isn't made use of if the face hasn't a box,
      so there's no need to check the face here.  */
   it->start_of_box_run_p = 1;
-  
+
   while (it->current_x < max_x)
     {
       int x_before, x, n_glyphs_before, i, nglyphs;
@@ -7715,7 +7853,7 @@ display_tool_bar_line (it)
       while (i < nglyphs)
        {
          struct glyph *glyph = row->glyphs[TEXT_AREA] + n_glyphs_before + i;
-         
+
          if (x + glyph->pixel_width > max_x)
            {
              /* Glyph doesn't fit on line.  */
@@ -7745,14 +7883,14 @@ display_tool_bar_line (it)
   if (last == row->glyphs[TEXT_AREA])
     last->left_box_line_p = 1;
   compute_line_metrics (it);
-  
+
   /* If line is empty, make it occupy the rest of the tool-bar.  */
   if (!row->displays_text_p)
     {
       row->height = row->phys_height = it->last_visible_y - row->y;
       row->ascent = row->phys_ascent = 0;
     }
-  
+
   row->full_width_p = 1;
   row->continued_p = 0;
   row->truncated_on_left_p = 0;
@@ -7774,7 +7912,7 @@ tool_bar_lines_needed (f)
 {
   struct window *w = XWINDOW (f->tool_bar_window);
   struct it it;
-  
+
   /* Initialize an iterator for iteration over
      F->desired_tool_bar_string in the tool-bar window of frame F.  */
   init_iterator (&it, w, -1, -1, w->desired_matrix->rows, TOOL_BAR_FACE_ID);
@@ -7806,9 +7944,9 @@ DEFUN ("tool-bar-lines-needed", Ftool_bar_lines_needed, Stool_bar_lines_needed,
   if (NILP (frame))
     frame = selected_frame;
   else
-    CHECK_FRAME (frame, 0);
+    CHECK_FRAME (frame);
   f = XFRAME (frame);
-  
+
   if (WINDOWP (f->tool_bar_window)
       || (w = XWINDOW (f->tool_bar_window),
          XFASTINT (w->height) > 0))
@@ -7836,7 +7974,7 @@ redisplay_tool_bar (f)
   struct it it;
   struct glyph_row *row;
   int change_height_p = 0;
-  
+
   /* If frame hasn't a tool-bar window or if it is zero-height, don't
      do anything.  This means you must start with tool-bar-lines
      non-zero to get the auto-sizing effect.  Or in other words, you
@@ -7873,7 +8011,7 @@ redisplay_tool_bar (f)
         height.  */
       if (IT_STRING_CHARPOS (it) < it.end_charpos)
        change_height_p = 1;
-      
+
       /* If there are blank lines at the end, except for a partially
         visible blank line at the end that is smaller than
         CANON_Y_UNIT, change the tool-bar's height.  */
@@ -7897,7 +8035,7 @@ redisplay_tool_bar (f)
          extern Lisp_Object Qtool_bar_lines;
          Lisp_Object frame;
          int old_height = XFASTINT (w->height);
-         
+
          XSETFRAME (frame, f);
          clear_glyph_matrix (w->desired_matrix);
          Fmodify_frame_parameters (frame,
@@ -7926,11 +8064,18 @@ tool_bar_item_info (f, glyph, prop_idx)
 {
   Lisp_Object prop;
   int success_p;
-  
+  int charpos;
+
+  /* This function can be called asynchronously, which means we must
+     exclude any possibility that Fget_text_property signals an
+     error.  */
+  charpos = min (SCHARS (f->current_tool_bar_string), glyph->charpos);
+  charpos = max (0, charpos);
+
   /* Get the text property `menu-item' at pos. The value of that
      property is the start index of this item's properties in
      F->tool_bar_items.  */
-  prop = Fget_text_property (make_number (glyph->charpos),
+  prop = Fget_text_property (make_number (charpos),
                             Qmenu_item, f->current_tool_bar_string);
   if (INTEGERP (prop))
     {
@@ -7942,7 +8087,7 @@ tool_bar_item_info (f, glyph, prop_idx)
 
   return success_p;
 }
-  
+
 #endif /* HAVE_WINDOW_SYSTEM */
 
 
@@ -7965,18 +8110,39 @@ hscroll_window_tree (window)
      Lisp_Object window;
 {
   int hscrolled_p = 0;
-  
+  int hscroll_relative_p = FLOATP (Vhscroll_step);
+  int hscroll_step_abs = 0;
+  double hscroll_step_rel = 0;
+
+  if (hscroll_relative_p)
+    {
+      hscroll_step_rel = XFLOAT_DATA (Vhscroll_step);
+      if (hscroll_step_rel < 0)
+       {
+         hscroll_relative_p = 0;
+         hscroll_step_abs = 0;
+       }
+    }
+  else if (INTEGERP (Vhscroll_step))
+    {
+      hscroll_step_abs = XINT (Vhscroll_step);
+      if (hscroll_step_abs < 0)
+       hscroll_step_abs = 0;
+    }
+  else
+    hscroll_step_abs = 0;
+
   while (WINDOWP (window))
     {
       struct window *w = XWINDOW (window);
-      
+
       if (WINDOWP (w->hchild))
        hscrolled_p |= hscroll_window_tree (w->hchild);
       else if (WINDOWP (w->vchild))
        hscrolled_p |= hscroll_window_tree (w->vchild);
       else if (w->cursor.vpos >= 0)
        {
-         int hscroll_margin, text_area_x, text_area_y;
+         int h_margin, text_area_x, text_area_y;
          int text_area_width, text_area_height;
          struct glyph_row *current_cursor_row
            = MATRIX_ROW (w->current_matrix, w->cursor.vpos);
@@ -7991,24 +8157,24 @@ hscroll_window_tree (window)
                      &text_area_width, &text_area_height);
 
          /* Scroll when cursor is inside this scroll margin.  */
-         /* Shouldn't we export this `5' for customization ?  -stef  */
-         hscroll_margin = 5 * CANON_X_UNIT (XFRAME (w->frame));
-         
+         h_margin = hscroll_margin * CANON_X_UNIT (XFRAME (w->frame));
+
          if ((XFASTINT (w->hscroll)
-              && w->cursor.x < hscroll_margin)
+              && w->cursor.x <= h_margin)
              || (cursor_row->enabled_p
                  && cursor_row->truncated_on_right_p
-                 && (w->cursor.x > text_area_width - hscroll_margin)))
+                 && (w->cursor.x >= text_area_width - h_margin)))
            {
              struct it it;
              int hscroll;
              struct buffer *saved_current_buffer;
              int pt;
+             int wanted_x;
 
              /* Find point in a display of infinite width.  */
              saved_current_buffer = current_buffer;
              current_buffer = XBUFFER (w->buffer);
-             
+
              if (w == XWINDOW (selected_window))
                pt = BUF_PT (current_buffer);
              else
@@ -8025,9 +8191,33 @@ hscroll_window_tree (window)
              move_it_in_display_line_to (&it, pt, -1, MOVE_TO_POS);
              current_buffer = saved_current_buffer;
 
-             /* Center cursor in window.  */
-             hscroll = (max (0, it.current_x - text_area_width / 2)
-                        / CANON_X_UNIT (it.f));
+             /* Position cursor in window.  */
+             if (!hscroll_relative_p && hscroll_step_abs == 0)
+               hscroll = max (0, it.current_x - text_area_width / 2)
+                         / CANON_X_UNIT (it.f);
+             else if (w->cursor.x >= text_area_width - h_margin)
+               {
+                 if (hscroll_relative_p)
+                   wanted_x = text_area_width * (1 - hscroll_step_rel)
+                              - h_margin;
+                 else
+                   wanted_x = text_area_width
+                              - hscroll_step_abs * CANON_X_UNIT (it.f)
+                              - h_margin;
+                 hscroll
+                   = max (0, it.current_x - wanted_x) / CANON_X_UNIT (it.f);
+               }
+             else
+               {
+                 if (hscroll_relative_p)
+                   wanted_x = text_area_width * hscroll_step_rel
+                              + h_margin;
+                 else
+                   wanted_x = hscroll_step_abs * CANON_X_UNIT (it.f)
+                              + h_margin;
+                 hscroll
+                   = max (0, it.current_x - wanted_x) / CANON_X_UNIT (it.f);
+               }
              hscroll = max (hscroll, XFASTINT (w->min_hscroll));
 
              /* Don't call Fset_window_hscroll if value hasn't
@@ -8061,7 +8251,7 @@ hscroll_windows (window)
      Lisp_Object window;
 {
   int hscrolled_p;
-  
+
   if (automatic_hscrolling_p)
     {
       hscrolled_p = hscroll_window_tree (window);
@@ -8101,7 +8291,7 @@ int debug_delta, debug_delta_bytes;
 /* Values of window_end_pos and window_end_vpos at the end of
    try_window_id.  */
 
-int debug_end_pos, debug_end_vpos;
+EMACS_INT debug_end_pos, debug_end_vpos;
 
 /* Append a string to W->desired_matrix->method.  FMT is a printf
    format string.  A1...A9 are a supplement for a variable-length
@@ -8126,7 +8316,7 @@ debug_method_add (w, fmt, a1, a2, a3, a4, a5, a6, a7, a8, a9)
       method[len] = '|';
       --remaining, ++len;
     }
-  
+
   strncpy (method + len, buffer, remaining);
 
   if (trace_redisplay_p)
@@ -8134,7 +8324,7 @@ debug_method_add (w, fmt, a1, a2, a3, a4, a5, a6, a7, a8, a9)
             w,
             ((BUFFERP (w->buffer)
               && STRINGP (XBUFFER (w->buffer)->name))
-             ? (char *) XSTRING (XBUFFER (w->buffer)->name)->data
+             ? (char *) SDATA (XBUFFER (w->buffer)->name)
              : "no buffer"),
             buffer);
 }
@@ -8142,23 +8332,6 @@ debug_method_add (w, fmt, a1, a2, a3, a4, a5, a6, a7, a8, a9)
 #endif /* GLYPH_DEBUG */
 
 
-/* This counter is used to clear the face cache every once in a while
-   in redisplay_internal.  It is incremented for each redisplay.
-   Every CLEAR_FACE_CACHE_COUNT full redisplays, the face cache is
-   cleared.  */
-
-#define CLEAR_FACE_CACHE_COUNT 10000
-static int clear_face_cache_count;
-
-/* Record the previous terminal frame we displayed.  */
-
-static struct frame *previous_terminal_frame;
-
-/* Non-zero while redisplay_internal is in progress.  */
-
-int redisplaying_p;
-
-
 /* Value is non-zero if all changes in window W, which displays
    current_buffer, are in the text between START and END.  START is a
    buffer position, END is given as a distance from Z.  Used in
@@ -8170,7 +8343,7 @@ text_outside_line_unchanged_p (w, start, end)
      int start, end;
 {
   int unchanged_p = 1;
-  
+
   /* If text or overlays have changed, see where.  */
   if (XFASTINT (w->last_modified) < MODIFF
       || XFASTINT (w->last_overlay_modified) < OVERLAY_MODIFF)
@@ -8184,7 +8357,7 @@ text_outside_line_unchanged_p (w, start, end)
          && (BEG_UNCHANGED < start - 1
              || END_UNCHANGED < end))
        unchanged_p = 0;
-      
+
       /* If selective display, can't optimize if changes start at the
         beginning of the line.  */
       if (unchanged_p
@@ -8250,7 +8423,7 @@ check_point_in_composition (prev_buf, prev_pt, buf, pt)
       if (prev_pt == pt)
        /* Point didn't move.  */
        return 0;
-    
+
       if (prev_pt > BUF_BEGV (buf) && prev_pt < BUF_ZV (buf)
          && find_composition (prev_pt, -1, &start, &end, &prop, buffer)
          && COMPOSITION_VALID_P (start, end, prop)
@@ -8276,9 +8449,7 @@ reconsider_clip_changes (w, b)
      struct window *w;
      struct buffer *b;
 {
-  if (b->prevent_redisplay_optimizations_p)
-    b->clip_changed = 1;
-  else if (b->clip_changed
+  if (b->clip_changed
           && !NILP (w->window_end_valid)
           && w->current_matrix->buffer == b
           && w->current_matrix->zv == BUF_ZV (b)
@@ -8332,7 +8503,7 @@ redisplay_internal (preserve_echo_area)
   /* Non-zero means redisplay has to consider all windows on all
      frames.  Zero means, only selected_window is considered.  */
   int consider_all_windows_p;
-  
+
   TRACE ((stderr, "redisplay_internal %d\n", redisplaying_p));
 
   /* No redisplay if running in batch mode or frame is not yet fully
@@ -8364,10 +8535,11 @@ redisplay_internal (preserve_echo_area)
 
   /* Record a function that resets redisplaying_p to its old value
      when we leave this function.  */
-  count = BINDING_STACK_SIZE ();
+  count = SPECPDL_INDEX ();
   record_unwind_protect (unwind_redisplay, make_number (redisplaying_p));
   ++redisplaying_p;
-  
+  specbind (Qinhibit_free_realized_faces, Qnil);
+
  retry:
   pause = 0;
   reconsider_clip_changes (w, current_buffer);
@@ -8411,7 +8583,7 @@ redisplay_internal (preserve_echo_area)
     FOR_EACH_FRAME (tail, frame)
       {
        struct frame *f = XFRAME (frame);
-       
+
        FRAME_SAMPLE_VISIBILITY (f);
        if (FRAME_VISIBLE_P (f))
          ++number_of_visible_frames;
@@ -8447,15 +8619,17 @@ redisplay_internal (preserve_echo_area)
       && !(PT == XFASTINT (w->last_point)
           && XFASTINT (w->last_modified) >= MODIFF
           && XFASTINT (w->last_overlay_modified) >= OVERLAY_MODIFF)
-      && XFASTINT (w->column_number_displayed) != current_column ())
-    w->update_mode_line = Qt; 
+      && (XFASTINT (w->column_number_displayed)
+          != (int) current_column ()))  /* iftc */
+    w->update_mode_line = Qt;
 
   FRAME_SCROLL_BOTTOM_VPOS (XFRAME (w->frame)) = -1;
 
   /* The variable buffer_shared is set in redisplay_window and
      indicates that we redisplay a buffer in different windows.  See
      there.  */
-  consider_all_windows_p = update_mode_lines || buffer_shared > 1;
+  consider_all_windows_p = (update_mode_lines || buffer_shared > 1
+                           || cursor_type_changed);
 
   /* If specs for an arrow have changed, do thorough redisplay
      to ensure we remove any arrow that should no longer exist.  */
@@ -8485,7 +8659,7 @@ redisplay_internal (preserve_echo_area)
         the echo area.  */
       if (!display_last_displayed_message_p)
        message_cleared_p = 0;
-      
+
       if (fonts_changed_p)
        goto retry;
       else if (window_height_changed_p)
@@ -8493,7 +8667,7 @@ redisplay_internal (preserve_echo_area)
          consider_all_windows_p = 1;
          ++update_mode_lines;
          ++windows_or_buffers_changed;
-         
+
          /* If window configuration was changed, frames may have been
             marked garbaged.  Clear them or we will experience
             surprises wrt scrolling.  */
@@ -8513,14 +8687,14 @@ redisplay_internal (preserve_echo_area)
       consider_all_windows_p = 1;
       ++windows_or_buffers_changed;
       ++update_mode_lines;
-      
+
       /* If window configuration was changed, frames may have been
         marked garbaged.  Clear them or we will experience
         surprises wrt scrolling.  */
       if (frame_garbaged)
        clear_garbaged_frames ();
     }
-  
+
 
   /* If showing the region, and mark has changed, we must redisplay
      the whole window.  The assignment to this_line_start_pos prevents
@@ -8543,12 +8717,14 @@ redisplay_internal (preserve_echo_area)
       && CHARPOS (tlbufpos) > 0
       && NILP (w->update_mode_line)
       && !current_buffer->clip_changed
+      && !current_buffer->prevent_redisplay_optimizations_p
       && FRAME_VISIBLE_P (XFRAME (w->frame))
       && !FRAME_OBSCURED_P (XFRAME (w->frame))
       /* Make sure recorded data applies to current buffer, etc.  */
       && this_line_buffer == current_buffer
       && current_buffer == XBUFFER (w->buffer)
       && NILP (w->force_start)
+      && NILP (w->optional_new_start)
       /* Point must be on the line that we have info recorded about.  */
       && PT >= CHARPOS (tlbufpos)
       && PT <= Z - CHARPOS (tlendpos)
@@ -8602,7 +8778,7 @@ redisplay_internal (preserve_echo_area)
 
          /* If line contains point, is not continued,
              and ends at same distance from eob as before, we win */
-         if (w->cursor.vpos >= 0 
+         if (w->cursor.vpos >= 0
               /* Line is not continued, otherwise this_line_start_pos
                  would have been set to 0 in display_line.  */
              && CHARPOS (this_line_start_pos)
@@ -8619,7 +8795,7 @@ redisplay_internal (preserve_echo_area)
                  struct glyph_row *row
                    = MATRIX_ROW (w->current_matrix, this_line_vpos + 1);
                  int delta, delta_bytes;
-  
+
                  if (Z - CHARPOS (tlendpos) == ZV)
                    {
                      /* This line ends at end of (accessible part of)
@@ -8643,7 +8819,7 @@ redisplay_internal (preserve_echo_area)
                                     - BYTEPOS (tlendpos)
                                     - MATRIX_ROW_START_BYTEPOS (row));
                    }
-  
+
                  increment_matrix_positions (w->current_matrix,
                                              this_line_vpos + 1,
                                              w->current_matrix->nrows,
@@ -8662,7 +8838,7 @@ redisplay_internal (preserve_echo_area)
                       && this_line_vpos > 0)
                XSETINT (w->window_end_vpos, this_line_vpos - 1);
              w->window_end_valid = Qnil;
-             
+
              /* Update hint: No need to try to scroll in update_window.  */
              w->desired_matrix->no_scrolling_p = 1;
 
@@ -8686,7 +8862,7 @@ redisplay_internal (preserve_echo_area)
            {
              do_pending_window_change (1);
 
-             /* We used to always goto end_of_redisplay here, but this 
+             /* We used to always goto end_of_redisplay here, but this
                 isn't enough if we have a blinking cursor.  */
              if (w->cursor_off_p == w->last_cursor_off_p)
                goto end_of_redisplay;
@@ -8714,7 +8890,7 @@ redisplay_internal (preserve_echo_area)
          it.current_x = this_line_start_x;
          it.current_y = this_line_y;
          it.vpos = this_line_vpos;
-         
+
          /* The call to move_it_to stops in front of PT, but
             moves over before-strings.  */
          move_it_to (&it, PT, -1, -1, -1, MOVE_TO_POS);
@@ -8745,7 +8921,7 @@ redisplay_internal (preserve_echo_area)
   consider_all_windows_p |= buffer_shared > 1;
   ++clear_face_cache_count;
 
-  
+
   /* Build desired matrices, and update the display.  If
      consider_all_windows_p is non-zero, do it for all windows on all
      frames.  Otherwise do it for selected_window, only.  */
@@ -8771,9 +8947,15 @@ redisplay_internal (preserve_echo_area)
       FOR_EACH_FRAME (tail, frame)
        {
          struct frame *f = XFRAME (frame);
-         
+
          if (FRAME_WINDOW_P (f) || f == sf)
            {
+#ifdef HAVE_WINDOW_SYSTEM
+             if (clear_face_cache_count % 50 == 0
+                 && FRAME_WINDOW_P (f))
+               clear_image_cache (f, 0);
+#endif /* HAVE_WINDOW_SYSTEM */
+
              /* Mark all the scroll bars to be removed; we'll redeem
                 the ones we want when we redisplay their windows.  */
              if (condemn_scroll_bars_hook)
@@ -8790,7 +8972,7 @@ redisplay_internal (preserve_echo_area)
              /* If fonts changed, display again.  */
              if (fonts_changed_p)
                goto retry;
-             
+
              if (FRAME_VISIBLE_P (f) && !FRAME_OBSCURED_P (f))
                {
                  /* See if we have to hscroll.  */
@@ -8818,7 +9000,7 @@ redisplay_internal (preserve_echo_area)
                      bcopy (updated, p, nbytes);
                      size *= 2;
                    }
-                 
+
                  updated[n++] = f;
                }
            }
@@ -8840,11 +9022,16 @@ redisplay_internal (preserve_echo_area)
       Lisp_Object mini_window;
       struct frame *mini_frame;
 
-      redisplay_window (selected_window, 1);
-  
+      displayed_buffer = XBUFFER (XWINDOW (selected_window)->buffer);
+      /* Use list_of_error, not Qerror, so that
+        we catch only errors and don't run the debugger.  */
+      internal_condition_case_1 (redisplay_window_1, selected_window,
+                                list_of_error,
+                                redisplay_window_error);
+
       /* Compare desired and current matrices, perform output.  */
+      
     update:
-  
       /* If fonts changed, display again.  */
       if (fonts_changed_p)
        goto retry;
@@ -8860,7 +9047,7 @@ redisplay_internal (preserve_echo_area)
        {
          if (hscroll_windows (selected_window))
            goto retry;
-         
+
          XWINDOW (selected_window)->must_be_updated_p = 1;
          pause = update_frame (sf, 0, 0);
        }
@@ -8872,7 +9059,7 @@ redisplay_internal (preserve_echo_area)
         it here.  */
       mini_window = FRAME_MINIBUF_WINDOW (sf);
       mini_frame = XFRAME (WINDOW_FRAME (XWINDOW (mini_window)));
-       
+
       if (mini_frame != sf && FRAME_WINDOW_P (mini_frame))
        {
          XWINDOW (mini_window)->must_be_updated_p = 1;
@@ -8897,7 +9084,7 @@ redisplay_internal (preserve_echo_area)
          last_arrow_position = Qt;
          last_arrow_string = Qt;
        }
-      
+
       /* If we pause after scrolling, some rows in the current
         matrices of some windows are not valid.  */
       if (!WINDOW_FULL_WIDTH_P (w)
@@ -8911,16 +9098,17 @@ redisplay_internal (preserve_echo_area)
          /* This has already been done above if
             consider_all_windows_p is set.  */
          mark_window_display_accurate_1 (w, 1);
-         
+
          last_arrow_position = COERCE_MARKER (Voverlay_arrow_position);
          last_arrow_string = Voverlay_arrow_string;
-         
+
          if (frame_up_to_date_hook != 0)
            frame_up_to_date_hook (sf);
        }
 
       update_mode_lines = 0;
       windows_or_buffers_changed = 0;
+      cursor_type_changed = 0;
     }
 
   /* Start SIGIO interrupts coming again.  Having them off during the
@@ -8968,8 +9156,7 @@ redisplay_internal (preserve_echo_area)
   if (windows_or_buffers_changed && !pause)
     goto retry;
 
- end_of_redisplay:;
-
+ end_of_redisplay:
   unbind_to (count, Qnil);
 }
 
@@ -9005,8 +9192,9 @@ redisplay_preserve_echo_area (from_where)
 
 
 /* Function registered with record_unwind_protect in
-   redisplay_internal.  Clears the flag indicating that a redisplay is
-   in progress.  */
+   redisplay_internal.  Reset redisplaying_p to the value it had
+   before redisplay_internal was called, and clear
+   prevent_freeing_realized_faces_p.  */
 
 static Lisp_Object
 unwind_redisplay (old_redisplaying_p)
@@ -9030,7 +9218,7 @@ mark_window_display_accurate_1 (w, accurate_p)
   if (BUFFERP (w->buffer))
     {
       struct buffer *b = XBUFFER (w->buffer);
-         
+
       w->last_modified
        = make_number (accurate_p ? BUF_MODIFF (b) : 0);
       w->last_overlay_modified
@@ -9047,14 +9235,14 @@ mark_window_display_accurate_1 (w, accurate_p)
          BUF_OVERLAY_UNCHANGED_MODIFIED (b) = BUF_OVERLAY_MODIFF (b);
          BUF_BEG_UNCHANGED (b) = BUF_GPT (b) - BUF_BEG (b);
          BUF_END_UNCHANGED (b) = BUF_Z (b) - BUF_GPT (b);
-         
+
          w->current_matrix->buffer = b;
          w->current_matrix->begv = BUF_BEGV (b);
          w->current_matrix->zv = BUF_ZV (b);
-         
+
          w->last_cursor = w->cursor;
          w->last_cursor_off_p = w->cursor_off_p;
-         
+
          if (w == XWINDOW (selected_window))
            w->last_point = make_number (BUF_PT (b));
          else
@@ -9086,7 +9274,7 @@ mark_window_display_accurate (window, accurate_p)
      int accurate_p;
 {
   struct window *w;
-  
+
   for (; !NILP (window); window = w->next)
     {
       w = XWINDOW (window);
@@ -9107,7 +9295,7 @@ mark_window_display_accurate (window, accurate_p)
     {
       /* Force a thorough redisplay the next time by setting
         last_arrow_position and last_arrow_string to t, which is
-        unequal to any useful value of Voverlay_arrow_... */
+        unequal to any useful value of Voverlay_arrow_...  */
       last_arrow_position = Qt;
       last_arrow_string = Qt;
     }
@@ -9129,13 +9317,13 @@ disp_char_vector (dp, c)
 
   if (SINGLE_BYTE_CHAR_P (c))
     return (dp->contents[c]);
-  
+
   SPLIT_CHAR (c, code[0], code[1], code[2]);
   if (code[1] < 32)
     code[1] = -1;
   else if (code[2] < 32)
     code[2] = -1;
-  
+
   /* Here, the possible range of code[0] (== charset ID) is
      128..max_charset.  Since the top level char table contains data
      for multibyte characters after 256th element, we must increment
@@ -9149,7 +9337,7 @@ disp_char_vector (dp, c)
       if (!SUB_CHAR_TABLE_P (val))
        return (NILP (val) ? dp->defalt : val);
     }
-  
+
   /* Here, val is a sub char table.  We return the default value of
      it.  */
   return (dp->defalt);
@@ -9170,19 +9358,50 @@ redisplay_windows (window)
   while (!NILP (window))
     {
       struct window *w = XWINDOW (window);
-      
+
       if (!NILP (w->hchild))
        redisplay_windows (w->hchild);
       else if (!NILP (w->vchild))
        redisplay_windows (w->vchild);
       else
-       redisplay_window (window, 0);
+       {
+         displayed_buffer = XBUFFER (w->buffer);
+         /* Use list_of_error, not Qerror, so that
+            we catch only errors and don't run the debugger.  */
+         internal_condition_case_1 (redisplay_window_0, window,
+                                    list_of_error,
+                                    redisplay_window_error);
+       }
 
       window = w->next;
     }
 }
 
+static Lisp_Object
+redisplay_window_error ()
+{
+  displayed_buffer->display_error_modiff = BUF_MODIFF (displayed_buffer);
+  return Qnil;
+}
+
+static Lisp_Object
+redisplay_window_0 (window)
+     Lisp_Object window;
+{
+  if (displayed_buffer->display_error_modiff < BUF_MODIFF (displayed_buffer))
+    redisplay_window (window, 0);
+  return Qnil;
+}
 
+static Lisp_Object
+redisplay_window_1 (window)
+     Lisp_Object window;
+{
+  if (displayed_buffer->display_error_modiff < BUF_MODIFF (displayed_buffer))
+    redisplay_window (window, 1);
+  return Qnil;
+}
+\f
 /* Set cursor position of W.  PT is assumed to be displayed in ROW.
    DELTA is the number of bytes by which positions recorded in ROW
    differ from current buffer positions.  */
@@ -9232,17 +9451,17 @@ set_cursor_from_row (w, row, matrix, delta, delta_bytes, dy, dvpos)
          && row->x == 0)
        {
          this_line_buffer = XBUFFER (w->buffer);
-         
+
          CHARPOS (this_line_start_pos)
            = MATRIX_ROW_START_CHARPOS (row) + delta;
          BYTEPOS (this_line_start_pos)
            = MATRIX_ROW_START_BYTEPOS (row) + delta_bytes;
-         
+
          CHARPOS (this_line_end_pos)
            = Z - (MATRIX_ROW_END_CHARPOS (row) + delta);
          BYTEPOS (this_line_end_pos)
            = Z_BYTE - (MATRIX_ROW_END_BYTEPOS (row) + delta_bytes);
-         
+
          this_line_y = w->cursor.y;
          this_line_pixel_height = row->height;
          this_line_vpos = w->cursor.vpos;
@@ -9272,7 +9491,7 @@ run_window_scroll_functions (window, startp)
 
   if (!NILP (Vwindow_scroll_functions))
     {
-      run_hook_with_args_2 (Qwindow_scroll_functions, window, 
+      run_hook_with_args_2 (Qwindow_scroll_functions, window,
                            make_number (CHARPOS (startp)));
       SET_TEXT_POS_FROM_MARKER (startp, w->start);
       /* In case the hook functions switch buffers.  */
@@ -9284,10 +9503,12 @@ run_window_scroll_functions (window, startp)
 }
 
 
-/* Modify the desired matrix of window W and W->vscroll so that the
-   line containing the cursor is fully visible.  If this requires
-   larger matrices than are allocated, set fonts_changed_p and return
-   0.  */
+/* Make sure the line containing the cursor is fully visible.
+   A value of 1 means there is nothing to be done.
+   (Either the line is fully visible, or it cannot be made so,
+   or we cannot tell.)
+   A value of 0 means the caller should do scrolling
+   as if point had gone off the screen.  */
 
 static int
 make_cursor_line_fully_visible (w)
@@ -9296,17 +9517,16 @@ make_cursor_line_fully_visible (w)
   struct glyph_matrix *matrix;
   struct glyph_row *row;
   int window_height;
-  
+
   /* It's not always possible to find the cursor, e.g, when a window
      is full of overlay strings.  Don't do anything in that case.  */
   if (w->cursor.vpos < 0)
     return 1;
-  
+
   matrix = w->desired_matrix;
   row = MATRIX_ROW (matrix, w->cursor.vpos);
 
-  /* If the cursor row is not partially visible, there's nothing
-     to do.  */
+  /* If the cursor row is not partially visible, there's nothing to do.  */
   if (!MATRIX_ROW_PARTIALLY_VISIBLE_P (row))
     return 1;
 
@@ -9316,6 +9536,13 @@ make_cursor_line_fully_visible (w)
   if (row->height >= window_height)
     return 1;
 
+  return 0;
+
+#if 0
+  /* This code used to try to scroll the window just enough to make
+     the line visible.  It returned 0 to say that the caller should
+     allocate larger glyph matrices.  */
+
   if (MATRIX_ROW_PARTIALLY_VISIBLE_AT_TOP_P (w, row))
     {
       int dy = row->height - row->visible_height;
@@ -9330,7 +9557,7 @@ make_cursor_line_fully_visible (w)
       w->cursor.y += dy;
       shift_glyph_matrix (w, matrix, 0, matrix->nrows, dy);
     }
-  
+
   /* When we change the cursor y-position of the selected window,
      change this_line_y as well so that the display optimization for
      the cursor line of the selected window in redisplay_internal uses
@@ -9347,6 +9574,7 @@ make_cursor_line_fully_visible (w)
     }
 
   return 1;
+#endif /* 0 */
 }
 
 
@@ -9359,9 +9587,9 @@ make_cursor_line_fully_visible (w)
    Value is
 
    1   if scrolling succeeded
-    
+
    0   if scrolling didn't find point.
-   
+
    -1  if new fonts have been loaded so that we must interrupt
    redisplay, adjust glyph matrices, and try again.  */
 
@@ -9377,7 +9605,7 @@ try_scrolling (window, just_this_one_p, scroll_conservatively,
               scroll_step, temp_scroll_step)
      Lisp_Object window;
      int just_this_one_p;
-     int scroll_conservatively, scroll_step;
+     EMACS_INT scroll_conservatively, scroll_step;
      int temp_scroll_step;
 {
   struct window *w = XWINDOW (window);
@@ -9400,7 +9628,7 @@ try_scrolling (window, just_this_one_p, scroll_conservatively,
 #endif
 
   SET_TEXT_POS_FROM_MARKER (startp, w->start);
-  
+
   /* Compute scroll margin height in pixels.  We scroll when point is
      within this distance from the top or bottom of the window.  */
   if (scroll_margin > 0)
@@ -9442,7 +9670,8 @@ try_scrolling (window, just_this_one_p, scroll_conservatively,
   if (PT >= CHARPOS (scroll_margin_pos))
     {
       int y0;
-      
+
+    too_near_end:
       /* Point is in the scroll margin at the bottom of the window, or
         below.  Compute a new window start that makes point visible.  */
 
@@ -9452,17 +9681,15 @@ try_scrolling (window, just_this_one_p, scroll_conservatively,
       y0 = it.current_y;
       move_it_to (&it, PT, 0, it.last_visible_y, -1,
                  MOVE_TO_POS | MOVE_TO_X | MOVE_TO_Y);
-      
-      /* With a scroll_margin of 0, scroll_margin_pos is at the window
-        end, which is one line below the window.  The iterator's
-        current_y will be same as y0 in that case, but we have to
-        scroll a line to make PT visible.  That's the reason why 1 is
-        added below.  */
-      dy = 1 + it.current_y - y0;
-      
+
+      /* To make point visible, we have to move the window start
+        down so that the line the cursor is in is visible, which
+        means we have to add in the height of the cursor line.  */
+      dy = line_bottom_y (&it) - y0;
+
       if (dy > scroll_max)
        return SCROLLING_FAILED;
-      
+
       /* Move the window start down.  If scrolling conservatively,
         move it just enough down to make point visible.  If
         scroll_step is set, move it down by scroll_step.  */
@@ -9476,7 +9703,7 @@ try_scrolling (window, just_this_one_p, scroll_conservatively,
        amount_to_scroll = scroll_max;
       else
        {
-         aggressive = current_buffer->scroll_down_aggressively;
+         aggressive = current_buffer->scroll_up_aggressively;
          height = (WINDOW_DISPLAY_HEIGHT_NO_MODE_LINE (w)
                    - WINDOW_DISPLAY_HEADER_LINE_HEIGHT (w));
          if (NUMBERP (aggressive))
@@ -9506,7 +9733,7 @@ try_scrolling (window, just_this_one_p, scroll_conservatively,
          /* Point is in the scroll margin at the top of the window or
             above what is displayed in the window.  */
          int y0;
-         
+
          /* Compute the vertical distance from PT to the scroll
             margin position.  Give up if distance is greater than
             scroll_max.  */
@@ -9519,10 +9746,10 @@ try_scrolling (window, just_this_one_p, scroll_conservatively,
          dy = it.current_y - y0;
          if (dy > scroll_max)
            return SCROLLING_FAILED;
-         
+
          /* Compute new window start.  */
          start_display (&it, w, startp);
-         
+
          if (scroll_conservatively)
            amount_to_scroll =
              max (dy, CANON_Y_UNIT (f) * max (scroll_step, temp_scroll_step));
@@ -9530,7 +9757,7 @@ try_scrolling (window, just_this_one_p, scroll_conservatively,
            amount_to_scroll = scroll_max;
          else
            {
-             aggressive = current_buffer->scroll_up_aggressively;
+             aggressive = current_buffer->scroll_down_aggressively;
              height = (WINDOW_DISPLAY_HEIGHT_NO_MODE_LINE (w)
                        - WINDOW_DISPLAY_HEADER_LINE_HEIGHT (w));
              if (NUMBERP (aggressive))
@@ -9539,7 +9766,7 @@ try_scrolling (window, just_this_one_p, scroll_conservatively,
 
          if (amount_to_scroll <= 0)
            return SCROLLING_FAILED;
-         
+
          move_it_vertically (&it, - amount_to_scroll);
          startp = it.current.pos;
        }
@@ -9560,18 +9787,16 @@ try_scrolling (window, just_this_one_p, scroll_conservatively,
   else
     {
       /* Maybe forget recorded base line for line number display.  */
-      if (!just_this_one_p 
+      if (!just_this_one_p
          || current_buffer->clip_changed
          || BEG_UNCHANGED < CHARPOS (startp))
        w->base_line_number = Qnil;
-      
-      /* If cursor ends up on a partially visible line, shift display
-        lines up or down.  If that fails because we need larger
-        matrices, give up.  */
-      if (!make_cursor_line_fully_visible (w))
-       rc = SCROLLING_NEED_LARGER_MATRICES;
-      else
-       rc = SCROLLING_SUCCESS;
+
+      /* If cursor ends up on a partially visible line,
+        treat that as being off the bottom of the screen.  */
+      if (! make_cursor_line_fully_visible (w))
+       goto too_near_end;
+      rc = SCROLLING_SUCCESS;
     }
 
   return rc;
@@ -9596,7 +9821,7 @@ compute_window_start_on_continuation_line (w)
   SET_TEXT_POS_FROM_MARKER (start_pos, w->start);
 
   /* If window start is on a continuation line...  Window start may be
-     < BEGV in case there's invisible text at the start of the 
+     < BEGV in case there's invisible text at the start of the
      buffer (M-x rmail, for example).  */
   if (CHARPOS (start_pos) > BEGV
       && FETCH_BYTE (BYTEPOS (start_pos) - 1) != '\n')
@@ -9609,7 +9834,7 @@ compute_window_start_on_continuation_line (w)
        SET_TEXT_POS (start_pos, BEGV, BEGV_BYTE);
       else if (CHARPOS (start_pos) > ZV)
        SET_TEXT_POS (start_pos, ZV, ZV_BYTE);
-      
+
       /* Find the start of the continued line.  This should be fast
         because scan_buffer is fast (newline cache).  */
       row = w->desired_matrix->rows + (WINDOW_WANTS_HEADER_LINE_P (w) ? 1 : 0);
@@ -9623,7 +9848,7 @@ compute_window_start_on_continuation_line (w)
          < XFASTINT (w->height) * XFASTINT (w->width))
        {
          int min_distance, distance;
-         
+
          /* Move forward by display lines to find the new window
             start.  If window width was enlarged, the new start can
             be expected to be > the old start.  If window width was
@@ -9639,22 +9864,22 @@ compute_window_start_on_continuation_line (w)
              pos = it.current.pos;
              move_it_by_lines (&it, 1, 0);
            }
-         
+
          /* Set the window start there.  */
          SET_MARKER_FROM_TEXT_POS (w->start, pos);
          window_start_changed_p = 1;
        }
     }
-  
+
   return window_start_changed_p;
 }
 
 
-/* Try cursor movement in case text has not changes in window WINDOW,
+/* Try cursor movement in case text has not changed in window WINDOW,
    with window start STARTP.  Value is
 
    CURSOR_MOVEMENT_SUCCESS if successful
-   
+
    CURSOR_MOVEMENT_CANNOT_BE_USED if this method cannot be used
 
    CURSOR_MOVEMENT_MUST_SCROLL if we know we have to scroll the
@@ -9665,7 +9890,7 @@ compute_window_start_on_continuation_line (w)
    which case we have to abort this redisplay, and adjust matrices
    first.  */
 
-enum 
+enum
 {
   CURSOR_MOVEMENT_SUCCESS,
   CURSOR_MOVEMENT_CANNOT_BE_USED,
@@ -9682,8 +9907,8 @@ try_cursor_movement (window, startp, scroll_step)
   struct window *w = XWINDOW (window);
   struct frame *f = XFRAME (w->frame);
   int rc = CURSOR_MOVEMENT_CANNOT_BE_USED;
-  
-#ifdef GLYPH_DEBUG
+
+#if GLYPH_DEBUG
   if (inhibit_try_cursor_movement)
     return rc;
 #endif
@@ -9700,7 +9925,8 @@ try_cursor_movement (window, startp, scroll_step)
         cases.  */
       && !update_mode_lines
       && !windows_or_buffers_changed
-      /* Can't use this case if highlighting a region.  When a 
+      && !cursor_type_changed
+      /* Can't use this case if highlighting a region.  When a
          region exists, cursor movement has to do more than just
          set the cursor.  */
       && !(!NILP (Vtransient_mark_mode)
@@ -9758,7 +9984,7 @@ try_cursor_movement (window, startp, scroll_step)
        {
          int scroll_p = 0;
          int last_y = window_text_bottom_y (w) - this_scroll_margin;
-         
+
          if (PT > XFASTINT (w->last_point))
            {
              /* Point has moved forward.  */
@@ -9826,7 +10052,7 @@ try_cursor_movement (window, startp, scroll_step)
                     && MATRIX_ROW_END_CHARPOS (row) == PT
                     && !cursor_row_p (w, row))
                ++row;
-         
+
              /* If within the scroll margin, scroll.  */
              if (row->y < this_scroll_margin
                  && CHARPOS (startp) != BEGV)
@@ -9859,7 +10085,7 @@ try_cursor_movement (window, startp, scroll_step)
                  set_cursor_from_row (w, row, w->current_matrix, 0, 0, 0, 0);
                  try_window (window, startp);
                  if (!make_cursor_line_fully_visible (w))
-                   rc = CURSOR_MOVEMENT_NEED_LARGER_MATRICES;
+                   rc = CURSOR_MOVEMENT_MUST_SCROLL;
                  else
                    rc = CURSOR_MOVEMENT_SUCCESS;
                }
@@ -9896,9 +10122,13 @@ redisplay_window (window, just_this_one_p)
   struct it it;
   /* Record it now because it's overwritten.  */
   int current_matrix_up_to_date_p = 0;
+  /* This is less strict than current_matrix_up_to_date_p.
+     It indictes that the buffer contents and narrowing are unchanged.  */
+  int buffer_unchanged_p = 0;
   int temp_scroll_step = 0;
-  int count = BINDING_STACK_SIZE ();
+  int count = SPECPDL_INDEX ();
   int rc;
+  int centering_position;
 
   SET_TEXT_POS (lpoint, PT, PT_BYTE);
   opoint = lpoint;
@@ -9912,11 +10142,12 @@ redisplay_window (window, just_this_one_p)
   specbind (Qinhibit_point_motion_hooks, Qt);
 
   reconsider_clip_changes (w, buffer);
-    
-  /* Has the mode line to be updated?  */ 
+
+  /* Has the mode line to be updated?  */
   update_mode_line = (!NILP (w->update_mode_line)
                      || update_mode_lines
-                     || buffer->clip_changed);
+                     || buffer->clip_changed
+                     || buffer->prevent_redisplay_optimizations_p);
 
   if (MINI_WINDOW_P (w))
     {
@@ -9957,6 +10188,13 @@ redisplay_window (window, just_this_one_p)
   SET_TEXT_POS (opoint, PT, PT_BYTE);
 
   current_matrix_up_to_date_p
+    = (!NILP (w->window_end_valid)
+       && !current_buffer->clip_changed
+       && !current_buffer->prevent_redisplay_optimizations_p
+       && XFASTINT (w->last_modified) >= MODIFF
+       && XFASTINT (w->last_overlay_modified) >= OVERLAY_MODIFF);
+
+  buffer_unchanged_p
     = (!NILP (w->window_end_valid)
        && !current_buffer->clip_changed
        && XFASTINT (w->last_modified) >= MODIFF
@@ -9970,7 +10208,7 @@ redisplay_window (window, just_this_one_p)
         window start in case the window's width changed.  */
       if (XMARKER (w->start)->buffer == current_buffer)
        compute_window_start_on_continuation_line (w);
-      
+
       w->window_end_valid = Qnil;
     }
 
@@ -9988,8 +10226,9 @@ redisplay_window (window, just_this_one_p)
       && !(PT == XFASTINT (w->last_point)
           && XFASTINT (w->last_modified) >= MODIFF
           && XFASTINT (w->last_overlay_modified) >= OVERLAY_MODIFF)
-      && XFASTINT (w->column_number_displayed) != current_column ())
-    update_mode_line = 1; 
+      && (XFASTINT (w->column_number_displayed)
+          != (int) current_column ()))  /* iftc */
+    update_mode_line = 1;
 
   /* Count number of windows showing the selected buffer.  An indirect
      buffer counts as its base buffer.  */
@@ -10024,7 +10263,7 @@ redisplay_window (window, just_this_one_p)
          new_pt_byte = ZV_BYTE;
          set_marker_both (w->pointm, Qnil, ZV, ZV_BYTE);
        }
-      
+
       /* We don't use SET_PT so that the point-motion hooks don't run.  */
       TEMP_SET_PT_BOTH (new_pt, new_pt_byte);
     }
@@ -10078,8 +10317,7 @@ redisplay_window (window, just_this_one_p)
       w->window_end_valid = Qnil;
 
       /* Forget any recorded base line for line number display.  */
-      if (!current_matrix_up_to_date_p
-         || current_buffer->clip_changed)
+      if (!buffer_unchanged_p)
        w->base_line_number = Qnil;
 
       /* Redisplay the mode line.  Select the buffer properly for that.
@@ -10096,15 +10334,15 @@ redisplay_window (window, just_this_one_p)
          w->update_mode_line = Qt;
          startp = run_window_scroll_functions (window, startp);
        }
-      
+
       w->last_modified = make_number (0);
       w->last_overlay_modified = make_number (0);
       if (CHARPOS (startp) < BEGV)
        SET_TEXT_POS (startp, BEGV, BEGV_BYTE);
       else if (CHARPOS (startp) > ZV)
        SET_TEXT_POS (startp, ZV, ZV_BYTE);
-      
-      /* Redisplay, then check if cursor has been set during the 
+
+      /* Redisplay, then check if cursor has been set during the
         redisplay.  Give up if new fonts were loaded.  */
       if (!try_window (window, startp))
        {
@@ -10135,7 +10373,7 @@ redisplay_window (window, just_this_one_p)
            SET_TEXT_POS (lpoint, PT, PT_BYTE);
 
          set_cursor_from_row (w, row, w->desired_matrix, 0, 0, 0, 0);
-         
+
          /* If we are highlighting the region, then we just changed
             the region, so redisplay to show it.  */
          if (!NILP (Vtransient_mark_mode)
@@ -10148,7 +10386,44 @@ redisplay_window (window, just_this_one_p)
        }
 
       if (!make_cursor_line_fully_visible (w))
-       goto need_larger_matrices;
+       {
+         /* CVS rev. 1.761 had changed this to ``goto try_to_scroll''.
+
+            The intention of the fix -- AFAIU -- was to ensure that 
+            the cursor didn't end up on a partially visible last (or
+            first?) line when scrolling.
+
+
+            But that change causes havoc when scrolling backwards and
+            a partially visible first (or last?) line is present when
+            we reach the top of the buffer.  In effect, the text
+            already in the window is repeated (each line is appended
+            to the same or another lines in the window)...
+
+            I changed it back to ``goto need_larger_matrices'' which
+            in effect mean that we don't go through `try_scrolling'
+            when the cursor is already at the first line of the buffer,
+            and there is really only a few pixels [rather than lines]
+            to scroll backwards.  I guess move_it_by_lines etc. really
+            isn't the right device for doing that, ref. the code in
+            make_cursor_line_fully_visible which was also disabled by
+            CVS rev. 1.761.
+
+            But how do we know that we are already on the top line of
+            the window showing the first line in the buffer, so that
+            scrolling really wont help here?
+
+            I cannot find a simple fix for this (I tried various
+            approaches), but I prefer to an occasional partial line
+            rather than the visual messup, so I reverted this part of
+            the fix.
+
+            Someone will need to look into this when time allows.
+
+            -- 2002-08-22, Kim F. Storm  */
+
+         goto need_larger_matrices;
+       }
 #if GLYPH_DEBUG
       debug_method_add (w, "forced window start");
 #endif
@@ -10156,7 +10431,8 @@ redisplay_window (window, just_this_one_p)
     }
 
   /* Handle case where text has not changed, only point, and it has
-     not moved off the frame.  */
+     not moved off the frame, and we are not retrying after hscroll.
+     (current_matrix_up_to_date_p is nonzero when retrying.)  */
   if (current_matrix_up_to_date_p
       && (rc = try_cursor_movement (window, startp, &temp_scroll_step),
          rc != CURSOR_MOVEMENT_CANNOT_BE_USED))
@@ -10165,13 +10441,13 @@ redisplay_window (window, just_this_one_p)
        {
        case CURSOR_MOVEMENT_SUCCESS:
          goto done;
-         
+
        case CURSOR_MOVEMENT_NEED_LARGER_MATRICES:
          goto need_larger_matrices;
-         
+
        case CURSOR_MOVEMENT_MUST_SCROLL:
          goto try_to_scroll;
-         
+
        default:
          abort ();
        }
@@ -10187,7 +10463,7 @@ redisplay_window (window, just_this_one_p)
 #endif
       goto recenter;
     }
-  
+
   /* Try scrolling with try_window_id.  Value is > 0 if update has
      been done, it is -1 if we know that the same window start will
      not work.  It is 0 if unsuccessful for some other reason.  */
@@ -10217,7 +10493,7 @@ redisplay_window (window, just_this_one_p)
 #if GLYPH_DEBUG
       debug_method_add (w, "same window start");
 #endif
-      
+
       /* Try to redisplay starting at same place as before.
          If point has not moved off frame, accept the results.  */
       if (!current_matrix_up_to_date_p
@@ -10234,17 +10510,18 @@ redisplay_window (window, just_this_one_p)
 
       if (fonts_changed_p)
        goto need_larger_matrices;
-      
+
       if (w->cursor.vpos >= 0)
        {
-         if (!just_this_one_p 
+         if (!just_this_one_p
              || current_buffer->clip_changed
              || BEG_UNCHANGED < CHARPOS (startp))
            /* Forget any recorded base line for line number display.  */
            w->base_line_number = Qnil;
-         
+
          if (!make_cursor_line_fully_visible (w))
-           goto need_larger_matrices;
+           /* Drop through and scroll.  */
+           ;
          goto done;
        }
       else
@@ -10270,7 +10547,7 @@ redisplay_window (window, just_this_one_p)
        || NUMBERP (current_buffer->scroll_up_aggressively)
        || NUMBERP (current_buffer->scroll_down_aggressively))
       && !current_buffer->clip_changed
-      && CHARPOS (startp) >= BEGV 
+      && CHARPOS (startp) >= BEGV
       && CHARPOS (startp) <= ZV)
     {
       /* The function returns -1 if new fonts were loaded, 1 if
@@ -10283,13 +10560,13 @@ redisplay_window (window, just_this_one_p)
        {
        case SCROLLING_SUCCESS:
          goto done;
-         
+
        case SCROLLING_NEED_LARGER_MATRICES:
          goto need_larger_matrices;
-         
+
        case SCROLLING_FAILED:
          break;
-         
+
        default:
          abort ();
        }
@@ -10298,6 +10575,10 @@ redisplay_window (window, just_this_one_p)
   /* Finally, just choose place to start which centers point */
 
  recenter:
+  centering_position = window_box_height (w) / 2;
+
+ point_at_top:
+  /* Jump here with centering_position already set to 0.  */
 
 #if GLYPH_DEBUG
   debug_method_add (w, "recenter");
@@ -10306,14 +10587,13 @@ redisplay_window (window, just_this_one_p)
   /* w->vscroll = 0; */
 
   /* Forget any previously recorded base line for line number display.  */
-  if (!current_matrix_up_to_date_p
-      || current_buffer->clip_changed)
+  if (!buffer_unchanged_p)
     w->base_line_number = Qnil;
 
   /* Move backward half the height of the window.  */
   init_iterator (&it, w, PT, PT_BYTE, NULL, DEFAULT_FACE_ID);
   it.current_y = it.last_visible_y;
-  move_it_vertically_backward (&it, window_box_height (w) / 2);
+  move_it_vertically_backward (&it, centering_position);
   xassert (IT_CHARPOS (it) >= BEGV);
 
   /* The function move_it_vertically_backward may move over more
@@ -10330,7 +10610,7 @@ redisplay_window (window, just_this_one_p)
     }
 
   it.current_x = it.hpos = 0;
-  
+
   /* Set startp here explicitly in case that helps avoid an infinite loop
      in case the window-scroll-functions functions get errors.  */
   set_marker_both (w->start, Qnil, IT_CHARPOS (it), IT_BYTEPOS (it));
@@ -10341,6 +10621,7 @@ redisplay_window (window, just_this_one_p)
   /* Redisplay the window.  */
   if (!current_matrix_up_to_date_p
       || windows_or_buffers_changed
+      || cursor_type_changed
       /* Don't use try_window_reusing_current_matrix in this case
         because it can have changed the buffer.  */
       || !NILP (Vwindow_scroll_functions)
@@ -10392,9 +10673,15 @@ redisplay_window (window, just_this_one_p)
        ++row;
       set_cursor_from_row (w, row, w->current_matrix, 0, 0, 0, 0);
     }
-  
+
   if (!make_cursor_line_fully_visible (w))
-    goto need_larger_matrices;
+    {
+      /* If centering point failed to make the whole line visible,
+        put point at the top instead.  That has to make the whole line
+        visible, if it can be done.  */
+      centering_position = 0;
+      goto point_at_top;
+    }
 
  done:
 
@@ -10406,17 +10693,18 @@ redisplay_window (window, just_this_one_p)
   /* Display the mode line, if we must.  */
   if ((update_mode_line
        /* If window not full width, must redo its mode line
-         if (a) the window to its side is being redone and 
+         if (a) the window to its side is being redone and
          (b) we do a frame-based redisplay.  This is a consequence
          of how inverted lines are drawn in frame-based redisplay.  */
-       || (!just_this_one_p 
+       || (!just_this_one_p
           && !FRAME_WINDOW_P (f)
           && !WINDOW_FULL_WIDTH_P (w))
        /* Line number to display.  */
        || INTEGERP (w->base_line_pos)
        /* Column number is displayed and different from the one displayed.  */
        || (!NILP (w->column_number_displayed)
-          && XFASTINT (w->column_number_displayed) != current_column ()))
+          && (XFASTINT (w->column_number_displayed)
+               != (int) current_column ()))) /* iftc */
        /* This means that the window has a mode line.  */
        && (WINDOW_WANTS_MODELINE_P (w)
           || WINDOW_WANTS_HEADER_LINE_P (w)))
@@ -10432,7 +10720,7 @@ redisplay_window (window, just_this_one_p)
          MATRIX_MODE_LINE_ROW (w->current_matrix)->height
            = DESIRED_MODE_LINE_HEIGHT (w);
        }
-      
+
       /* If top line height has changed, arrange for a thorough
         immediate redisplay using the correct mode line height.  */
       if (WINDOW_WANTS_HEADER_LINE_P (w)
@@ -10455,7 +10743,7 @@ redisplay_window (window, just_this_one_p)
     }
 
  finish_menu_bars:
-  
+
   /* When we reach a frame's selected window, redo the frame's menu bar.  */
   if (update_mode_line
       && EQ (FRAME_SELECTED_WINDOW (f), window))
@@ -10464,7 +10752,7 @@ redisplay_window (window, just_this_one_p)
 
       if (FRAME_WINDOW_P (f))
        {
-#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) || defined (macintosh)
+#if defined (USE_X_TOOLKIT) || defined (HAVE_NTGUI) || defined (MAC_OS)
          redisplay_menu_p = FRAME_EXTERNAL_MENU_BAR (f);
 #else
          redisplay_menu_p = FRAME_MENU_BAR_LINES (f) > 0;
@@ -10509,9 +10797,9 @@ redisplay_window (window, just_this_one_p)
             moment, we'll pretend it is.  */
          end = (Z - XFASTINT (w->window_end_pos)) - BEGV;
 
-         if (end < start) 
+         if (end < start)
            end = start;
-         if (whole < (end - start)) 
+         if (whole < (end - start))
            whole = end - start;
        }
       else
@@ -10592,7 +10880,7 @@ try_window (window, pos)
       w->window_end_bytepos = 0;
       w->window_end_pos = w->window_end_vpos = make_number (0);
     }
-  
+
   /* But that is not valid info until redisplay finishes.  */
   w->window_end_valid = Qnil;
   return 1;
@@ -10624,7 +10912,7 @@ try_window_reusing_current_matrix (w)
   struct glyph_row *start_row;
   int start_vpos, min_y, max_y;
 
-#ifdef GLYPH_DEBUG
+#if GLYPH_DEBUG
   if (inhibit_try_window_reusing)
     return 0;
 #endif
@@ -10633,7 +10921,8 @@ try_window_reusing_current_matrix (w)
       !FRAME_WINDOW_P (f)
       /* Don't try to reuse the display if windows have been split
         or such.  */
-      || windows_or_buffers_changed)
+      || windows_or_buffers_changed
+      || cursor_type_changed)
     return 0;
 
   /* Can't do this if region may have changed.  */
@@ -10662,11 +10951,11 @@ try_window_reusing_current_matrix (w)
 
   /* Clear the desired matrix for the display below.  */
   clear_glyph_matrix (w->desired_matrix);
-  
+
   if (CHARPOS (new_start) <= CHARPOS (start))
     {
       int first_row_y;
-      
+
       /* Don't use this method if the display starts with an ellipsis
         displayed for invisible text.  It's not easy to handle that case
         below, and it's certainly not worth the effort since this is
@@ -10675,7 +10964,7 @@ try_window_reusing_current_matrix (w)
        return 0;
 
       IF_DEBUG (debug_method_add (w, "twu1"));
-      
+
       /* Display up to a row that can be reused.  The variable
         last_text_row is set to the last row displayed that displays
         text.  Note that it.vpos == 0 if or if not there is a
@@ -10684,7 +10973,7 @@ try_window_reusing_current_matrix (w)
       first_row_y = it.current_y;
       w->cursor.vpos = -1;
       last_text_row = last_reused_text_row = NULL;
-      
+
       while (it.current_y < it.last_visible_y
             && IT_CHARPOS (it) < CHARPOS (start)
             && !fonts_changed_p)
@@ -10698,12 +10987,12 @@ try_window_reusing_current_matrix (w)
        {
          /* IT.vpos always starts from 0; it counts text lines.  */
          nrows_scrolled = it.vpos;
-         
+
          /* Find PT if not already found in the lines displayed.  */
          if (w->cursor.vpos < 0)
            {
              int dy = it.current_y - first_row_y;
-             
+
              row = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
              row = row_containing_pos (w, PT, row, NULL, dy);
              if (row)
@@ -10742,7 +11031,7 @@ try_window_reusing_current_matrix (w)
                         start_vpos,
                         MATRIX_ROW_VPOS (bottom_row, w->current_matrix),
                         nrows_scrolled);
-         
+
          /* Disable lines that must be updated.  */
          for (i = 0; i < it.vpos; ++i)
            (start_row + i)->enabled_p = 0;
@@ -10761,7 +11050,7 @@ try_window_reusing_current_matrix (w)
                row->visible_height -= min_y - row->y;
              if (row->y + row->height > max_y)
                row->visible_height -= row->y + row->height - max_y;
-             
+
              it.current_y += row->height;
 
              if (MATRIX_ROW_DISPLAYS_TEXT_P (row))
@@ -10769,7 +11058,7 @@ try_window_reusing_current_matrix (w)
              if (MATRIX_ROW_BOTTOM_Y (row) >= it.last_visible_y)
                break;
            }
-         
+
          /* Disable lines in the current matrix which are now
             below the window.  */
          for (++row; row < bottom_row; ++row)
@@ -10809,7 +11098,7 @@ try_window_reusing_current_matrix (w)
 
       /* Update hint: don't try scrolling again in update_window.  */
       w->desired_matrix->no_scrolling_p = 1;
-      
+
 #if GLYPH_DEBUG
       debug_method_add (w, "try_window_reusing_current_matrix 1");
 #endif
@@ -10896,7 +11185,7 @@ try_window_reusing_current_matrix (w)
       run.desired_y = WINDOW_DISPLAY_HEADER_LINE_HEIGHT (w);
       run.height = it.last_visible_y - run.current_y;
       dy = run.current_y - run.desired_y;
-      
+
       if (run.height)
        {
          struct frame *f = XFRAME (WINDOW_FRAME (w));
@@ -10950,7 +11239,7 @@ try_window_reusing_current_matrix (w)
          w->window_end_vpos
            = make_number (XFASTINT (w->window_end_vpos) - nrows_scrolled);
        }
-      
+
       w->window_end_valid = Qnil;
       w->desired_matrix->no_scrolling_p = 1;
 
@@ -10959,7 +11248,7 @@ try_window_reusing_current_matrix (w)
 #endif
       return 1;
     }
-  
+
   return 0;
 }
 
@@ -11003,7 +11292,7 @@ find_last_row_displaying_text (matrix, it, start)
        break;
       ++row;
     }
-  
+
   return row_found;
 }
 
@@ -11048,7 +11337,7 @@ find_last_unchanged_at_beg_row (w)
       /* Stop if last visible row.  */
      if (MATRIX_ROW_BOTTOM_Y (row) >= yb)
        break;
-      
+
       ++row;
     }
 
@@ -11057,17 +11346,17 @@ find_last_unchanged_at_beg_row (w)
 
 
 /* Find the first glyph row in the current matrix of W that is not
-   affected by changes at the end of current_buffer since the 
+   affected by changes at the end of current_buffer since the
    time W's current matrix was built.
 
    Return in *DELTA the number of chars by which buffer positions in
    unchanged text at the end of current_buffer must be adjusted.
-   
+
    Return in *DELTA_BYTES the corresponding number of bytes.
 
    Value is null if no such row exists, i.e. all rows are affected by
    changes.  */
-   
+
 static struct glyph_row *
 find_first_unchanged_at_end_row (w, delta, delta_bytes)
      struct window *w;
@@ -11082,7 +11371,7 @@ find_first_unchanged_at_end_row (w, delta, delta_bytes)
      is not up to date.  */
   if (NILP (w->window_end_valid))
     abort ();
-  
+
   /* A value of window_end_pos >= END_UNCHANGED means that the window
      end is in the range of changed text.  If so, there is no
      unchanged row at the end of W's current matrix.  */
@@ -11091,8 +11380,8 @@ find_first_unchanged_at_end_row (w, delta, delta_bytes)
 
   /* Set row to the last row in W's current matrix displaying text.  */
   row = MATRIX_ROW (w->current_matrix, XFASTINT (w->window_end_vpos));
-  
-  /* If matrix is entirely empty, no unchanged row exists.  */ 
+
+  /* If matrix is entirely empty, no unchanged row exists.  */
   if (MATRIX_ROW_DISPLAYS_TEXT_P (row))
     {
       /* The value of row is the last glyph row in the matrix having a
@@ -11117,14 +11406,14 @@ find_first_unchanged_at_end_row (w, delta, delta_bytes)
         position.  */
       last_unchanged_pos = Z - END_UNCHANGED + BEG;
       last_unchanged_pos_old = last_unchanged_pos - *delta;
-      
+
       /* Search backward from ROW for a row displaying a line that
         starts at a minimum position >= last_unchanged_pos_old.  */
       for (; row > first_text_row; --row)
        {
          if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
            abort ();
-         
+
          if (MATRIX_ROW_START_CHARPOS (row) >= last_unchanged_pos_old)
            row_found = row;
        }
@@ -11132,7 +11421,7 @@ find_first_unchanged_at_end_row (w, delta, delta_bytes)
 
   if (row_found && !MATRIX_ROW_DISPLAYS_TEXT_P (row_found))
     abort ();
-  
+
   return row_found;
 }
 
@@ -11158,22 +11447,26 @@ sync_frame_with_window_matrix_rows (w)
 
   /* If W is a full-width window, glyph pointers in W's current matrix
      have, by definition, to be the same as glyph pointers in the
-     corresponding frame matrix.  */
+     corresponding frame matrix.  Note that frame matrices have no
+     marginal areas (see build_frame_matrix).  */
   window_row = w->current_matrix->rows;
   window_row_end = window_row + w->current_matrix->nrows;
   frame_row = f->current_matrix->rows + XFASTINT (w->top);
   while (window_row < window_row_end)
     {
-      int area;
-      
-      for (area = LEFT_MARGIN_AREA; area <= LAST_AREA; ++area)
-       frame_row->glyphs[area] = window_row->glyphs[area];
+      struct glyph *start = window_row->glyphs[LEFT_MARGIN_AREA];
+      struct glyph *end = window_row->glyphs[LAST_AREA];
+
+      frame_row->glyphs[LEFT_MARGIN_AREA] = start;
+      frame_row->glyphs[TEXT_AREA] = start;
+      frame_row->glyphs[RIGHT_MARGIN_AREA] = end;
+      frame_row->glyphs[LAST_AREA] = end;
 
       /* Disable frame rows whose corresponding window rows have
         been disabled in try_window_id.  */
       if (!window_row->enabled_p)
        frame_row->enabled_p = 0;
-      
+
       ++window_row, ++frame_row;
     }
 }
@@ -11197,12 +11490,12 @@ row_containing_pos (w, charpos, start, end, dy)
   /* If we happen to start on a header-line, skip that.  */
   if (row->mode_line_p)
     ++row;
-  
+
   if ((end && row >= end) || !row->enabled_p)
     return NULL;
-  
+
   last_y = window_text_bottom_y (w) - dy;
-      
+
   while ((end == NULL || row < end)
         && MATRIX_ROW_BOTTOM_Y (row) < last_y
         && (MATRIX_ROW_END_CHARPOS (row) < charpos
@@ -11214,7 +11507,7 @@ row_containing_pos (w, charpos, start, end, dy)
                 && !row->ends_at_zv_p
                 && !MATRIX_ROW_ENDS_IN_MIDDLE_OF_CHAR_P (row))))
     ++row;
-      
+
   /* Give up if CHARPOS not found.  */
   if ((end && row >= end)
       || charpos < MATRIX_ROW_START_CHARPOS (row)
@@ -11281,7 +11574,7 @@ try_window_id (w)
   struct text_pos start;
   int first_changed_charpos, last_changed_charpos;
 
-#ifdef GLYPH_DEBUG
+#if GLYPH_DEBUG
   if (inhibit_try_window_id)
     return 0;
 #endif
@@ -11296,22 +11589,24 @@ try_window_id (w)
 #else
 #define GIVE_UP(X) return 0
 #endif
-  
+
   SET_TEXT_POS_FROM_MARKER (start, w->start);
 
   /* Don't use this for mini-windows because these can show
      messages and mini-buffers, and we don't handle that here.  */
   if (MINI_WINDOW_P (w))
     GIVE_UP (1);
-  
+
   /* This flag is used to prevent redisplay optimizations.  */
-  if (windows_or_buffers_changed)
+  if (windows_or_buffers_changed || cursor_type_changed)
     GIVE_UP (2);
-  
-  /* Verify that narrowing has not changed.  This flag is also set to prevent
-     redisplay optimizations.  It would be nice to further
+
+  /* Verify that narrowing has not changed.
+     Also verify that we were not told to prevent redisplay optimizations.
+     It would be nice to further
      reduce the number of cases where this prevents try_window_id.  */
-  if (current_buffer->clip_changed)
+  if (current_buffer->clip_changed
+      || current_buffer->prevent_redisplay_optimizations_p)
     GIVE_UP (3);
 
   /* Window must either use window-based redisplay or be full width.  */
@@ -11327,15 +11622,15 @@ try_window_id (w)
   /* Another way to prevent redisplay optimizations.  */
   if (XFASTINT (w->last_modified) == 0)
     GIVE_UP (6);
-  
+
   /* Verify that window is not hscrolled.  */
   if (XFASTINT (w->hscroll) != 0)
     GIVE_UP (7);
-  
+
   /* Verify that display wasn't paused.  */
   if (NILP (w->window_end_valid))
     GIVE_UP (8);
-  
+
   /* Can't use this if highlighting a region because a cursor movement
      will do more than just set the cursor.  */
   if (!NILP (Vtransient_mark_mode)
@@ -11345,17 +11640,17 @@ try_window_id (w)
   /* Likewise if highlighting trailing whitespace.  */
   if (!NILP (Vshow_trailing_whitespace))
     GIVE_UP (11);
-  
+
   /* Likewise if showing a region.  */
   if (!NILP (w->region_showing))
     GIVE_UP (10);
-  
+
   /* Can use this if overlay arrow position and or string have changed.  */
   if (!EQ (last_arrow_position, COERCE_MARKER (Voverlay_arrow_position))
       || !EQ (last_arrow_string, Voverlay_arrow_string))
     GIVE_UP (12);
 
-  
+
   /* Make sure beg_unchanged and end_unchanged are up to date.  Do it
      only if buffer has really changed.  The reason is that the gap is
      initially at Z for freshly visited files.  The code below would
@@ -11395,7 +11690,7 @@ try_window_id (w)
       Z_BYTE_old = MATRIX_ROW_END_BYTEPOS (row) + w->window_end_bytepos;
       delta = Z - Z_old;
       delta_bytes = Z_BYTE - Z_BYTE_old;
-         
+
       /* Give up if PT is not in the window.  Note that it already has
         been checked at the start of try_window_id that PT is not in
         front of the window start.  */
@@ -11419,7 +11714,7 @@ try_window_id (w)
                                          MATRIX_ROW_VPOS (r1, current_matrix),
                                          delta, delta_bytes);
            }
-      
+
          /* Set the cursor.  */
          row = row_containing_pos (w, PT, r0, NULL, 0);
          set_cursor_from_row (w, row, current_matrix, 0, 0, 0, 0);
@@ -11466,7 +11761,7 @@ try_window_id (w)
     }
 
   /* Give up if window start is in the changed area.
-     
+
      The condition used to read
 
      (BEG_UNCHANGED + END_UNCHANGED != Z - BEG && ...)
@@ -11475,7 +11770,7 @@ try_window_id (w)
   if (CHARPOS (start) >= first_changed_charpos
       && CHARPOS (start) <= last_changed_charpos)
     GIVE_UP (15);
-  
+
   /* Check that window start agrees with the start of the first glyph
      row in its current matrix.  Check this after we know the window
      start is not in changed text, otherwise positions would not be
@@ -11514,7 +11809,7 @@ try_window_id (w)
       if (init_to_row_end (&it, w, last_unchanged_at_beg_row) == 0)
        GIVE_UP (18);
       start_pos = it.current.pos;
-      
+
       /* Start displaying new lines in the desired matrix at the same
         vpos we would use in the current matrix, i.e. below
         last_unchanged_at_beg_row.  */
@@ -11543,7 +11838,7 @@ try_window_id (w)
     = find_first_unchanged_at_end_row (w, &delta, &delta_bytes);
   IF_DEBUG (debug_delta = delta);
   IF_DEBUG (debug_delta_bytes = delta_bytes);
-  
+
   /* Set stop_pos to the buffer position up to which we will have to
      display new lines.  If first_unchanged_at_end_row != NULL, this
      is the buffer position of the start of the line displayed in that
@@ -11554,7 +11849,7 @@ try_window_id (w)
     {
       xassert (last_unchanged_at_beg_row == NULL
               || first_unchanged_at_end_row >= last_unchanged_at_beg_row);
-      
+
       /* If this is a continuation line, move forward to the next one
         that isn't.  Changes in lines above affect this line.
         Caution: this may move first_unchanged_at_end_row to a row
@@ -11583,22 +11878,22 @@ try_window_id (w)
 
 
 #if GLYPH_DEBUG
-  
+
   /* Either there is no unchanged row at the end, or the one we have
      now displays text.  This is a necessary condition for the window
      end pos calculation at the end of this function.  */
   xassert (first_unchanged_at_end_row == NULL
           || MATRIX_ROW_DISPLAYS_TEXT_P (first_unchanged_at_end_row));
-  
+
   debug_last_unchanged_at_beg_vpos
     = (last_unchanged_at_beg_row
        ? MATRIX_ROW_VPOS (last_unchanged_at_beg_row, current_matrix)
        : -1);
   debug_first_unchanged_at_end_vpos = first_unchanged_at_end_vpos;
-  
+
 #endif /* GLYPH_DEBUG != 0 */
 
-  
+
   /* Display new lines.  Set last_text_row to the last new line
      displayed which has text on it, i.e. might end up as being the
      line where the window_end_vpos is.  */
@@ -11680,17 +11975,17 @@ try_window_id (w)
          return -1;
        }
     }
-  
+
   /* Don't let the cursor end in the scroll margins.  */
   {
     int this_scroll_margin, cursor_height;
-    
+
     this_scroll_margin = max (0, scroll_margin);
     this_scroll_margin = min (this_scroll_margin,
                              XFASTINT (w->height) / 4);
     this_scroll_margin *= CANON_Y_UNIT (it.f);
     cursor_height = MATRIX_ROW (w->desired_matrix, w->cursor.vpos)->height;
-    
+
     if ((w->cursor.y < this_scroll_margin
         && CHARPOS (start) > BEGV)
        /* Don't take scroll margin into account at the bottom because
@@ -11709,7 +12004,7 @@ try_window_id (w)
   if (dy && run.height)
     {
       update_begin (f);
-         
+
       if (FRAME_WINDOW_P (f))
        {
          rif->update_window_begin_hook (w);
@@ -11727,7 +12022,7 @@ try_window_id (w)
          int end = (XFASTINT (w->top)
                     + (WINDOW_WANTS_HEADER_LINE_P (w) ? 1 : 0)
                     + window_internal_height (w));
-         
+
          /* Perform the operation on the screen.  */
          if (dvpos > 0)
            {
@@ -11761,10 +12056,10 @@ try_window_id (w)
              if (!scroll_region_ok)
                ins_del_lines (end + dvpos, -dvpos);
            }
-         
+
          set_terminal_window (0);
        }
-      
+
       update_end (f);
     }
 
@@ -11845,7 +12140,7 @@ try_window_id (w)
         get the right continuation_lines_width and current_x.  */
       it.continuation_lines_width = last_row->continuation_lines_width;
       it.hpos = it.current_x = 0;
-      
+
       /* Display the rest of the lines at the window end.  */
       it.glyph_row = MATRIX_ROW (desired_matrix, it.vpos);
       while (it.current_y < it.last_visible_y
@@ -11874,7 +12169,7 @@ try_window_id (w)
       row = find_last_row_displaying_text (w->current_matrix, &it,
                                           first_unchanged_at_end_row);
       xassert (row && MATRIX_ROW_DISPLAYS_TEXT_P (row));
-      
+
       w->window_end_pos = make_number (Z - MATRIX_ROW_END_CHARPOS (row));
       w->window_end_bytepos = Z_BYTE - MATRIX_ROW_END_BYTEPOS (row);
       w->window_end_vpos
@@ -12075,7 +12370,7 @@ dump_glyph_row (row, vpos, glyphs)
     {
       fprintf (stderr, "Row Start   End Used oEI><O\\CTZFesm     X    Y    W    H    V    A    P\n");
       fprintf (stderr, "=======================================================================\n");
-  
+
       fprintf (stderr, "%3d %5d %5d %4d %1.1d%1.1d%1.1d%1.1d%1.1d\
 %1.1d%1.1d%1.1d%1.1d%1.1d%1.1d%1.1d%1.1d  %4d %4d %4d %4d %4d %4d %4d\n",
               vpos,
@@ -12111,7 +12406,7 @@ dump_glyph_row (row, vpos, glyphs)
       fprintf (stderr, "%9d %5d\n", row->start.dpvec_index,
               row->end.dpvec_index);
     }
-  
+
   if (glyphs > 1)
     {
       int area;
@@ -12120,14 +12415,14 @@ dump_glyph_row (row, vpos, glyphs)
        {
          struct glyph *glyph = row->glyphs[area];
          struct glyph *glyph_end = glyph + row->used[area];
-      
+
          /* Glyph for a line end in text.  */
          if (area == TEXT_AREA && glyph == glyph_end && glyph->charpos > 0)
            ++glyph_end;
-      
+
          if (glyph < glyph_end)
            fprintf (stderr, "  Glyph    Type Pos   O W    Code C Face LR\n");
-      
+
          for (; glyph < glyph_end; ++glyph)
            dump_glyph (row, glyph, area);
        }
@@ -12151,7 +12446,7 @@ dump_glyph_row (row, vpos, glyphs)
              else
                s[i] = '.';
            }
-      
+
          s[i] = '\0';
          fprintf (stderr, "%3d: (%d) '%s'\n", vpos, row->enabled_p, s);
        }
@@ -12182,6 +12477,16 @@ glyphs in short form, otherwise show glyphs in long form.  */)
 }
 
 
+DEFUN ("dump-frame-glyph-matrix", Fdump_frame_glyph_matrix,
+       Sdump_frame_glyph_matrix, 0, 0, "", doc: /* */)
+     ()
+{
+  struct frame *f = XFRAME (selected_frame);
+  dump_glyph_matrix (f->current_matrix, 1);
+  return Qnil;
+}
+
+
 DEFUN ("dump-glyph-row", Fdump_glyph_row, Sdump_glyph_row, 1, 2, "",
        doc: /* Dump glyph row ROW to stderr.
 GLYPH 0 means don't dump glyphs.
@@ -12192,8 +12497,8 @@ GLYPH > 1 or omitted means dump glyphs in long form.  */)
 {
   struct glyph_matrix *matrix;
   int vpos;
-  
-  CHECK_NUMBER (row, 0);
+
+  CHECK_NUMBER (row);
   matrix = XWINDOW (selected_window)->current_matrix;
   vpos = XINT (row);
   if (vpos >= 0 && vpos < matrix->nrows)
@@ -12205,7 +12510,7 @@ GLYPH > 1 or omitted means dump glyphs in long form.  */)
 
 
 DEFUN ("dump-tool-bar-row", Fdump_tool_bar_row, Sdump_tool_bar_row, 1, 2, "",
-  doc: /* Dump glyph row ROW of the tool-bar of the current frame to stderr.
+       doc: /* Dump glyph row ROW of the tool-bar of the current frame to stderr.
 GLYPH 0 means don't dump glyphs.
 GLYPH 1 means dump glyphs in short form.
 GLYPH > 1 or omitted means dump glyphs in long form.  */)
@@ -12215,8 +12520,8 @@ GLYPH > 1 or omitted means dump glyphs in long form.  */)
   struct frame *sf = SELECTED_FRAME ();
   struct glyph_matrix *m = XWINDOW (sf->tool_bar_window)->current_matrix;
   int vpos;
-  
-  CHECK_NUMBER (row, 0);
+
+  CHECK_NUMBER (row);
   vpos = XINT (row);
   if (vpos >= 0 && vpos < m->nrows)
     dump_glyph_row (MATRIX_ROW (m, vpos), vpos,
@@ -12238,22 +12543,23 @@ With ARG, turn tracing on if and only if ARG is positive.  */)
       arg = Fprefix_numeric_value (arg);
       trace_redisplay_p = XINT (arg) > 0;
     }
-  
+
   return Qnil;
 }
 
 
 DEFUN ("trace-to-stderr", Ftrace_to_stderr, Strace_to_stderr, 1, MANY, "",
-       doc: /* Like `format', but print result to stderr.  */)
+       doc: /* Like `format', but print result to stderr.
+usage: (trace-to-stderr STRING &rest OBJECTS)  */)
      (nargs, args)
      int nargs;
      Lisp_Object *args;
 {
   Lisp_Object s = Fformat (nargs, args);
-  fprintf (stderr, "%s", XSTRING (s)->data);
+  fprintf (stderr, "%s", SDATA (s));
   return Qnil;
 }
-       
+
 #endif /* GLYPH_DEBUG */
 
 
@@ -12272,10 +12578,10 @@ get_overlay_arrow_glyph_row (w)
   struct frame *f = XFRAME (WINDOW_FRAME (w));
   struct buffer *buffer = XBUFFER (w->buffer);
   struct buffer *old = current_buffer;
-  unsigned char *arrow_string = XSTRING (Voverlay_arrow_string)->data;
-  int arrow_len = XSTRING (Voverlay_arrow_string)->size;
-  unsigned char *arrow_end = arrow_string + arrow_len;
-  unsigned char *p;
+  const unsigned char *arrow_string = SDATA (Voverlay_arrow_string);
+  int arrow_len = SCHARS (Voverlay_arrow_string);
+  const unsigned char *arrow_end = arrow_string + arrow_len;
+  const unsigned char *p;
   struct it it;
   int multibyte_p;
   int n_glyphs_before;
@@ -12290,14 +12596,14 @@ get_overlay_arrow_glyph_row (w)
   while (p < arrow_end)
     {
       Lisp_Object face, ilisp;
-      
+
       /* Get the next character.  */
       if (multibyte_p)
        it.c = string_char_and_length (p, arrow_len, &it.len);
       else
        it.c = *p, it.len = 1;
       p += it.len;
-      
+
       /* Get its face.  */
       ilisp = make_number (p - arrow_string);
       face = Fget_text_property (ilisp, Qface, Voverlay_arrow_string);
@@ -12316,7 +12622,7 @@ get_overlay_arrow_glyph_row (w)
          break;
        }
     }
-  
+
   set_buffer_temp (old);
   return it.glyph_row;
 }
@@ -12346,7 +12652,7 @@ insert_left_trunc_glyphs (it)
   CHARPOS (truncate_it.position) = BYTEPOS (truncate_it.position) = -1;
   truncate_it.object = make_number (0);
   produce_special_glyphs (&truncate_it, IT_TRUNCATION);
-  
+
   /* Overwrite glyphs from IT with truncation glyphs.  */
   from = truncate_it.glyph_row->glyphs[TEXT_AREA];
   end = from + truncate_it.glyph_row->used[TEXT_AREA];
@@ -12409,7 +12715,7 @@ compute_line_metrics (it)
          row->phys_ascent = it->max_phys_ascent;
          row->phys_height = it->max_phys_ascent + it->max_phys_descent;
        }
-      
+
       /* Compute the width of this line.  */
       row->pixel_width = row->x;
       for (i = 0; i < row->used[TEXT_AREA]; ++i)
@@ -12433,7 +12739,7 @@ compute_line_metrics (it)
 
       /* Compute how much of the line is visible.  */
       row->visible_height = row->height;
-      
+
       min_y = WINDOW_DISPLAY_HEADER_LINE_HEIGHT (it->w);
       max_y = WINDOW_DISPLAY_HEIGHT_NO_MODE_LINE (it->w);
 
@@ -12507,7 +12813,7 @@ append_space (it, default_face_p)
 
          saved_object = it->object;
          saved_pos = it->position;
-         
+
          it->what = IT_CHARACTER;
          bzero (&it->position, sizeof it->position);
          it->object = make_number (0);
@@ -12522,7 +12828,7 @@ append_space (it, default_face_p)
          it->face_id = FACE_FOR_CHAR (it->f, face, 0);
 
          PRODUCE_GLYPHS (it);
-         
+
          it->current_x = saved_x;
          it->object = saved_object;
          it->position = saved_pos;
@@ -12542,7 +12848,7 @@ append_space (it, default_face_p)
    to the end of the display line.  Called from display_line.
    If the glyph row is empty, add a space glyph to it so that we
    know the face to draw.  Set the glyph row flag fill_line_p.  */
-   
+
 static void
 extend_face_to_end_of_line (it)
      struct it *it;
@@ -12553,7 +12859,7 @@ extend_face_to_end_of_line (it)
   /* If line is already filled, do nothing.  */
   if (it->current_x >= it->last_visible_x)
     return;
-  
+
   /* Face extension extends the background and box of IT->face_id
      to the end of the line.  If the background equals the background
      of the frame, we don't have to do anything.  */
@@ -12561,7 +12867,7 @@ extend_face_to_end_of_line (it)
     face = FACE_FROM_ID (it->f, it->saved_face_id);
   else
     face = FACE_FROM_ID (f, it->face_id);
-  
+
   if (FRAME_WINDOW_P (f)
       && face->box == FACE_NO_BOX
       && face->background == FRAME_BACKGROUND_PIXEL (f)
@@ -12603,19 +12909,19 @@ extend_face_to_end_of_line (it)
 
       saved_object = it->object;
       saved_pos = it->position;
-  
+
       it->what = IT_CHARACTER;
       bzero (&it->position, sizeof it->position);
       it->object = make_number (0);
       it->c = ' ';
       it->len = 1;
       it->face_id = face->id;
-      
+
       PRODUCE_GLYPHS (it);
-      
+
       while (it->current_x <= it->last_visible_x)
        PRODUCE_GLYPHS (it);
-      
+
       /* Don't count these blanks really.  It would let us insert a left
         truncation glyph below and make us set the cursor on them, maybe.  */
       it->current_x = saved_x;
@@ -12659,7 +12965,7 @@ highlight_trailing_whitespace (f, row)
      struct glyph_row *row;
 {
   int used = row->used[TEXT_AREA];
-  
+
   if (used)
     {
       struct glyph *start = row->glyphs[TEXT_AREA];
@@ -12685,7 +12991,7 @@ highlight_trailing_whitespace (f, row)
          && trailing_whitespace_p (glyph->charpos))
        {
          int face_id = lookup_named_face (f, Qtrailing_whitespace, 0);
-         
+
          while (glyph >= start
                 && BUFFERP (glyph->object)
                 && (glyph->type == STRETCH_GLYPH
@@ -12706,7 +13012,7 @@ cursor_row_p (w, row)
      struct glyph_row *row;
 {
   int cursor_row_p = 1;
-  
+
   if (PT == MATRIX_ROW_END_CHARPOS (row))
     {
       /* If the row ends with a newline from a string, we don't want
@@ -12733,7 +13039,7 @@ cursor_row_p (w, row)
    for an overview of struct it.  Value is non-zero if
    IT->glyph_row displays text, as opposed to a line displaying ZV
    only.  */
-   
+
 static int
 display_line (it)
      struct it *it;
@@ -12808,7 +13114,7 @@ display_line (it)
                      || (minibuf_level && EQ (it->window, minibuf_window))))
                row->indicate_empty_line_p = 1;
            }
-         
+
          it->continuation_lines_width = 0;
          row->ends_at_zv_p = 1;
          break;
@@ -12828,7 +13134,7 @@ display_line (it)
          phys_ascent = it->max_phys_ascent;
          phys_descent = it->max_phys_descent;
        }
-      
+
       PRODUCE_GLYPHS (it);
 
       /* If this display element was in marginal areas, continue with
@@ -12857,7 +13163,7 @@ display_line (it)
       hpos_before = it->hpos;
       x_before = x;
 
-      if (/* Not a newline. */
+      if (/* Not a newline.  */
          nglyphs > 0
          /* Glyphs produced fit entirely in the line.  */
          && it->current_x < it->last_visible_x)
@@ -12875,7 +13181,7 @@ display_line (it)
        {
          int new_x;
          struct glyph *glyph;
-         
+
          for (i = 0; i < nglyphs; ++i, x = new_x)
            {
              glyph = row->glyphs[TEXT_AREA] + n_glyphs_before + i;
@@ -12890,7 +13196,7 @@ display_line (it)
                          && FRAME_WINDOW_P (it->f))))
                {
                  /* End of a continued line.  */
-                 
+
                  if (it->hpos == 0
                      || (new_x == it->last_visible_x
                          && FRAME_WINDOW_P (it->f)))
@@ -12913,17 +13219,17 @@ display_line (it)
                         This means the whole character doesn't fit
                         on the line.  */
                      row->used[TEXT_AREA] = n_glyphs_before;
-                 
+
                      /* Fill the rest of the row with continuation
                         glyphs like in 20.x.  */
                      while (row->glyphs[TEXT_AREA] + row->used[TEXT_AREA]
                             < row->glyphs[1 + TEXT_AREA])
                        produce_special_glyphs (it, IT_CONTINUATION);
-                     
+
                      row->continued_p = 1;
                      it->current_x = x_before;
                      it->continuation_lines_width += x_before;
-                     
+
                      /* Restore the height to what it was before the
                         element not fitting on the line.  */
                      it->max_ascent = ascent;
@@ -12950,20 +13256,20 @@ display_line (it)
                         the right edge of the window.  Restore
                         positions to values before the element.  */
                      row->used[TEXT_AREA] = n_glyphs_before + i;
-                 
+
                      /* Display continuation glyphs.  */
                      if (!FRAME_WINDOW_P (it->f))
                        produce_special_glyphs (it, IT_CONTINUATION);
                      row->continued_p = 1;
 
                      it->continuation_lines_width += x;
-                     
+
                      if (nglyphs > 1 && i > 0)
                        {
                          row->ends_in_middle_of_char_p = 1;
                          it->starts_in_middle_of_char_p = 1;
                        }
-                     
+
                      /* Restore the height to what it was before the
                         element not fitting on the line.  */
                      it->max_ascent = ascent;
@@ -12978,7 +13284,7 @@ display_line (it)
                {
                  /* Increment number of glyphs actually displayed.  */
                  ++it->hpos;
-                 
+
                  if (x < it->first_visible_x)
                    /* Glyph is partially visible, i.e. row starts at
                       negative X position.  */
@@ -12988,18 +13294,19 @@ display_line (it)
                {
                  /* Glyph is completely off the left margin of the
                     window.  This should not happen because of the
-                    move_it_in_display_line at the start of
-                    this function.  */
-                 abort ();
+                    move_it_in_display_line at the start of this
+                    function, unless the text display area of the
+                    window is empty.  */
+                 xassert (it->first_visible_x <= it->last_visible_x);
                }
            }
-         
+
          row->ascent = max (row->ascent, it->max_ascent);
          row->height = max (row->height, it->max_ascent + it->max_descent);
          row->phys_ascent = max (row->phys_ascent, it->max_phys_ascent);
          row->phys_height = max (row->phys_height,
                                  it->max_phys_ascent + it->max_phys_descent);
-         
+
          /* End of this display line if row is continued.  */
          if (row->continued_p)
            break;
@@ -13017,21 +13324,21 @@ display_line (it)
          /* Add a space at the end of the line that is used to
             display the cursor there.  */
          append_space (it, 0);
-         
+
          /* Extend the face to the end of the line.  */
          extend_face_to_end_of_line (it);
 
          /* Make sure we have the position.  */
          if (used_before == 0)
            row->glyphs[TEXT_AREA]->charpos = CHARPOS (it->position);
-         
+
          /* Consume the line end.  This skips over invisible lines.  */
          set_iterator_to_next (it, 1);
          it->continuation_lines_width = 0;
          break;
        }
 
-      /* Proceed with next display element.  Note that this skips 
+      /* Proceed with next display element.  Note that this skips
         over lines invisible because of selective display.  */
       set_iterator_to_next (it, 1);
 
@@ -13046,7 +13353,7 @@ display_line (it)
          if (!FRAME_WINDOW_P (it->f))
            {
              int i, n;
-             
+
              for (i = row->used[TEXT_AREA] - 1; i > 0; --i)
                if (!CHAR_GLYPH_PADDING_P (row->glyphs[TEXT_AREA][i]))
                  break;
@@ -13057,7 +13364,7 @@ display_line (it)
                  produce_special_glyphs (it, IT_TRUNCATION);
                }
            }
-         
+
          row->truncated_on_right_p = 1;
          it->continuation_lines_width = 0;
          reseat_at_next_visible_line_start (it, 0);
@@ -13089,7 +13396,7 @@ display_line (it)
       && STRINGP (Voverlay_arrow_string)
       && ! overlay_arrow_seen)
     {
-      /* Overlay arrow in window redisplay is a bitmap.  */
+      /* Overlay arrow in window redisplay is a fringe bitmap.  */
       if (!FRAME_WINDOW_P (it->f))
        {
          struct glyph_row *arrow_row = get_overlay_arrow_glyph_row (it->w);
@@ -13114,7 +13421,7 @@ display_line (it)
              row->used[TEXT_AREA] = p2 - row->glyphs[TEXT_AREA];
            }
        }
-      
+
       overlay_arrow_seen = 1;
       row->overlay_arrow_p = 1;
     }
@@ -13157,7 +13464,7 @@ display_line (it)
 
    The menu bar of X frames that don't have X toolkit support is
    displayed in a special window W->frame->menu_bar_window.
-   
+
    The menu bar of terminal frames is treated specially as far as
    glyph matrices are concerned.  Menu bar lines are not part of
    windows, so the update is done directly on the frame matrix rows
@@ -13181,7 +13488,7 @@ display_menu_bar (w)
   if (FRAME_X_P (f))
     return;
 #endif
-#ifdef macintosh
+#ifdef MAC_OS
   if (FRAME_MAC_P (f))
     return;
 #endif
@@ -13245,7 +13552,7 @@ display_menu_bar (w)
       /* Display the item, pad with one space.  */
       if (it.current_x < it.last_visible_x)
        display_string (NULL, string, Qnil, 0, 0, &it,
-                       XSTRING (string)->size + 1, 0, 0, -1);
+                       SCHARS (string) + 1, 0, 0, -1);
     }
 
   /* Fill out the line with spaces.  */
@@ -13273,11 +13580,11 @@ redisplay_mode_lines (window, force)
      int force;
 {
   int nwindows = 0;
-  
+
   while (!NILP (window))
     {
       struct window *w = XWINDOW (window);
-      
+
       if (WINDOWP (w->hchild))
        nwindows += redisplay_mode_lines (w->hchild, force);
       else if (WINDOWP (w->vchild))
@@ -13292,13 +13599,13 @@ redisplay_mode_lines (window, force)
          /* Set the window's buffer for the mode line display.  */
          SET_TEXT_POS (lpoint, PT, PT_BYTE);
          set_buffer_internal_1 (XBUFFER (w->buffer));
-         
+
          /* Point refers normally to the selected window.  For any
             other window, set up appropriate value.  */
          if (!EQ (window, selected_window))
            {
              struct text_pos pt;
-             
+
              SET_TEXT_POS_FROM_MARKER (pt, w->pointm);
              if (CHARPOS (pt) < BEGV)
                TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
@@ -13342,18 +13649,21 @@ display_mode_lines (w)
   selected_frame = w->frame;
   old_selected_window = selected_window;
   XSETWINDOW (selected_window, w);
-  
+
   /* These will be set while the mode line specs are processed.  */
   line_number_displayed = 0;
   w->column_number_displayed = Qnil;
 
   if (WINDOW_WANTS_MODELINE_P (w))
     {
-      display_mode_line (w, MODE_LINE_FACE_ID,
+      struct window *sel_w = XWINDOW (old_selected_window);
+
+      /* Select mode line face based on the real selected window.  */
+      display_mode_line (w, CURRENT_MODE_LINE_FACE_ID_3 (sel_w, sel_w, w),
                         current_buffer->mode_line_format);
       ++n;
     }
-  
+
   if (WINDOW_WANTS_HEADER_LINE_P (w))
     {
       display_mode_line (w, HEADER_LINE_FACE_ID,
@@ -13392,12 +13702,12 @@ display_mode_line (w, face_id, format)
      kboard-local variables in the mode_line_format will get the right
      values.  */
   push_frame_kboard (it.f);
-  display_mode_element (&it, 0, 0, 0, format);
+  display_mode_element (&it, 0, 0, 0, format, Qnil, 0);
   pop_frame_kboard ();
 
   /* Fill up with spaces.  */
   display_string (" ", Qnil, Qnil, 0, 0, &it, 10000, -1, -1, 0);
-  
+
   compute_line_metrics (&it);
   it.glyph_row->full_width_p = 1;
   it.glyph_row->mode_line_p = 1;
@@ -13418,6 +13728,17 @@ display_mode_line (w, face_id, format)
   return it.glyph_row->height;
 }
 
+/* Alist that caches the results of :propertize.
+   Each element is (PROPERTIZED-STRING . PROPERTY-LIST).  */
+Lisp_Object mode_line_proptrans_alist;
+
+/* List of strings making up the mode-line.  */
+Lisp_Object mode_line_string_list;
+
+/* Base face property when building propertized mode line string.  */
+static Lisp_Object mode_line_string_face;
+static Lisp_Object mode_line_string_face_prop;
+
 
 /* Contribute ELT to the mode line for window IT->w.  How it
    translates into text depends on its data type.
@@ -13430,18 +13751,28 @@ display_mode_line (w, face_id, format)
    FIELD_WIDTH is the number of characters the display of ELT should
    occupy in the mode line, and PRECISION is the maximum number of
    characters to display from ELT's representation.  See
-   display_string for details.  *
+   display_string for details.
+
+   Returns the hpos of the end of the text generated by ELT.
 
-   Returns the hpos of the end of the text generated by ELT.  */
+   PROPS is a property list to add to any string we encounter.
+
+   If RISKY is nonzero, remove (disregard) any properties in any string 
+   we encounter, and ignore :eval and :propertize.
+
+   If the global variable `frame_title_ptr' is non-NULL, then the output
+   is passed to `store_frame_title' instead of `display_string'.  */
 
 static int
-display_mode_element (it, depth, field_width, precision, elt)
+display_mode_element (it, depth, field_width, precision, elt, props, risky)
      struct it *it;
      int depth;
      int field_width, precision;
-     Lisp_Object elt;
+     Lisp_Object elt, props;
+     int risky;
 {
   int n = 0, field, prec;
+  int literal = 0;
 
  tail_recurse:
   if (depth > 10)
@@ -13455,20 +13786,89 @@ display_mode_element (it, depth, field_width, precision, elt)
       {
        /* A string: output it and check for %-constructs within it.  */
        unsigned char c;
-       unsigned char *this = XSTRING (elt)->data;
-       unsigned char *lisp_string = this;
+       const unsigned char *this, *lisp_string;
+
+       if (!NILP (props) || risky)
+         {
+           Lisp_Object oprops, aelt;
+           oprops = Ftext_properties_at (make_number (0), elt);
+
+           if (NILP (Fequal (props, oprops)) || risky)
+             {
+               /* If the starting string has properties,
+                  merge the specified ones onto the existing ones.  */
+               if (! NILP (oprops) && !risky)
+                 {
+                   Lisp_Object tem;
+
+                   oprops = Fcopy_sequence (oprops);
+                   tem = props;
+                   while (CONSP (tem))
+                     {
+                       oprops = Fplist_put (oprops, XCAR (tem),
+                                            XCAR (XCDR (tem)));
+                       tem = XCDR (XCDR (tem));
+                     }
+                   props = oprops;
+                 }
+
+               aelt = Fassoc (elt, mode_line_proptrans_alist);
+               if (! NILP (aelt) && !NILP (Fequal (props, XCDR (aelt))))
+                 {
+                   mode_line_proptrans_alist
+                     = Fcons (aelt, Fdelq (aelt, mode_line_proptrans_alist));
+                   elt = XCAR (aelt);
+                 }
+               else
+                 {
+                   Lisp_Object tem;
+
+                   elt = Fcopy_sequence (elt);
+                   Fset_text_properties (make_number (0), Flength (elt),
+                                         props, elt);
+                   /* Add this item to mode_line_proptrans_alist.  */
+                   mode_line_proptrans_alist
+                     = Fcons (Fcons (elt, props),
+                              mode_line_proptrans_alist);
+                   /* Truncate mode_line_proptrans_alist
+                      to at most 50 elements.  */
+                   tem = Fnthcdr (make_number (50),
+                                  mode_line_proptrans_alist);
+                   if (! NILP (tem))
+                     XSETCDR (tem, Qnil);
+                 }
+             }
+         }
+
+       this = SDATA (elt);
+       lisp_string = this;
+
+       if (literal)
+         {
+           prec = precision - n;
+           if (frame_title_ptr)
+             n += store_frame_title (SDATA (elt), -1, prec);
+           else if (!NILP (mode_line_string_list))
+             n += store_mode_line_string (NULL, elt, 1, 0, prec, Qnil);
+           else
+             n += display_string (NULL, elt, Qnil, 0, 0, it,
+                                  0, prec, 0, STRING_MULTIBYTE (elt));
+
+           break;
+         }
 
        while ((precision <= 0 || n < precision)
               && *this
               && (frame_title_ptr
+                  || !NILP (mode_line_string_list)
                   || it->current_x < it->last_visible_x))
          {
-           unsigned char *last = this;
+           const unsigned char *last = this;
 
            /* Advance to end of string or next format specifier.  */
            while ((c = *this++) != '\0' && c != '%')
              ;
-           
+
            if (this - 1 != last)
              {
                /* Output to end of string or up to '%'.  Field width
@@ -13479,9 +13879,18 @@ display_mode_element (it, depth, field_width, precision, elt)
                prec = chars_in_text (last, this - last);
                if (precision > 0 && prec > precision - n)
                  prec = precision - n;
-               
+
                if (frame_title_ptr)
                  n += store_frame_title (last, 0, prec);
+               else if (!NILP (mode_line_string_list))
+                 {
+                   int bytepos = last - lisp_string;
+                   int charpos = string_byte_to_char (elt, bytepos);
+                   n += store_mode_line_string (NULL,
+                                                Fsubstring (elt, make_number (charpos),
+                                                            make_number (charpos + prec)),
+                                                0, 0, 0, Qnil);
+                 }
                else
                  {
                    int bytepos = last - lisp_string;
@@ -13493,8 +13902,8 @@ display_mode_element (it, depth, field_width, precision, elt)
              }
            else /* c == '%' */
              {
-               unsigned char *percent_position = this;
-               
+               const unsigned char *percent_position = this;
+
                /* Get the specified minimum width.  Zero means
                   don't pad.  */
                field = 0;
@@ -13507,27 +13916,40 @@ display_mode_element (it, depth, field_width, precision, elt)
 
                /* Note that either PRECISION <= 0 or N < PRECISION.  */
                prec = precision - n;
-               
+
                if (c == 'M')
                  n += display_mode_element (it, depth, field, prec,
-                                            Vglobal_mode_string);
+                                            Vglobal_mode_string, props,
+                                            risky);
                else if (c != 0)
                  {
                    int multibyte;
-                   unsigned char *spec
+                   int bytepos, charpos;
+                   unsigned char *spec;
+
+                   bytepos = percent_position - lisp_string;
+                   charpos = (STRING_MULTIBYTE (elt)
+                              ? string_byte_to_char (elt, bytepos)
+                              : bytepos);
+
+                   spec
                      = decode_mode_spec (it->w, c, field, prec, &multibyte);
 
                    if (frame_title_ptr)
                      n += store_frame_title (spec, field, prec);
+                   else if (!NILP (mode_line_string_list))
+                     {
+                       int len = strlen (spec);
+                       Lisp_Object tem = make_string (spec, len);
+                       props = Ftext_properties_at (make_number (charpos), elt);
+                       /* Should only keep face property in props */
+                       n += store_mode_line_string (NULL, tem, 0, field, prec, props);
+                     }
                    else
                      {
-                       int nglyphs_before, bytepos, charpos, nwritten;
-                       
+                       int nglyphs_before, nwritten;
+
                        nglyphs_before = it->glyph_row->used[TEXT_AREA];
-                       bytepos = percent_position - XSTRING (elt)->data;
-                       charpos = (multibyte
-                                  ? string_byte_to_char (elt, bytepos)
-                                  : bytepos);
                        nwritten = display_string (spec, Qnil, elt,
                                                   charpos, 0, it,
                                                   field, prec, 0,
@@ -13548,11 +13970,13 @@ display_mode_element (it, depth, field_width, precision, elt)
                                glyph[i].object = elt;
                                glyph[i].charpos = charpos;
                              }
-                           
+
                            n += nwritten;
                          }
                      }
                  }
+               else /* c == 0 */
+                 break;
              }
          }
       }
@@ -13565,6 +13989,12 @@ display_mode_element (it, depth, field_width, precision, elt)
         literally.  */
       {
        register Lisp_Object tem;
+
+       /* If the variable is not marked as risky to set
+          then its contents are risky to use.  */
+       if (NILP (Fget (elt, Qrisky_local_variable)))
+         risky = 1;
+
        tem = Fboundp (elt);
        if (!NILP (tem))
          {
@@ -13572,15 +14002,9 @@ display_mode_element (it, depth, field_width, precision, elt)
            /* If value is a string, output that string literally:
               don't check for % within it.  */
            if (STRINGP (tem))
-             {
-               prec = precision - n;
-               if (frame_title_ptr)
-                 n += store_frame_title (XSTRING (tem)->data, -1, prec);
-               else
-                 n += display_string (NULL, tem, Qnil, 0, 0, it,
-                                      0, prec, 0, STRING_MULTIBYTE (tem));
-             }
-           else if (!EQ (tem, elt))
+             literal = 1;
+
+           if (!EQ (tem, elt))
              {
                /* Give up right away for nil or t.  */
                elt = tem;
@@ -13594,7 +14018,8 @@ display_mode_element (it, depth, field_width, precision, elt)
       {
        register Lisp_Object car, tem;
 
-       /* A cons cell: three distinct cases.
+       /* A cons cell: five distinct cases.
+          If first element is :eval or :propertize, do something special.
           If first element is a string or a cons, process all the elements
           and effectively concatenate them.
           If first element is a negative number, truncate displaying cdr to
@@ -13603,18 +14028,35 @@ display_mode_element (it, depth, field_width, precision, elt)
           If first element is a symbol, process the cadr or caddr recursively
           according to whether the symbol's value is non-nil or nil.  */
        car = XCAR (elt);
-       if (EQ (car, QCeval) && CONSP (XCDR (elt)))
+       if (EQ (car, QCeval))
          {
            /* An element of the form (:eval FORM) means evaluate FORM
               and use the result as mode line elements.  */
-           struct gcpro gcpro1;
-           Lisp_Object spec;
-
-           spec = safe_eval (XCAR (XCDR (elt)));
-           GCPRO1 (spec);
-           n += display_mode_element (it, depth, field_width - n,
-                                      precision - n, spec);
-           UNGCPRO;
+
+           if (risky)
+             break;
+
+           if (CONSP (XCDR (elt)))
+             {
+               Lisp_Object spec;
+               spec = safe_eval (XCAR (XCDR (elt)));
+               n += display_mode_element (it, depth, field_width - n,
+                                          precision - n, spec, props,
+                                          risky);
+             }
+         }
+       else if (EQ (car, QCpropertize))
+         {
+           /* An element of the form (:propertize ELT PROPS...)
+              means display ELT but applying properties PROPS.  */
+
+           if (risky)
+             break;
+
+           if (CONSP (XCDR (elt)))
+             n += display_mode_element (it, depth, field_width - n,
+                                        precision - n, XCAR (XCDR (elt)),
+                                        XCDR (XCDR (elt)), risky);
          }
        else if (SYMBOLP (car))
          {
@@ -13679,7 +14121,8 @@ display_mode_element (it, depth, field_width, precision, elt)
                   && (precision <= 0 || n < precision))
              {
                n += display_mode_element (it, depth, field_width - n,
-                                          precision - n, XCAR (elt));
+                                          precision - n, XCAR (elt),
+                                          props, risky);
                elt = XCDR (elt);
              }
          }
@@ -13690,6 +14133,8 @@ display_mode_element (it, depth, field_width, precision, elt)
     invalid:
       if (frame_title_ptr)
        n += store_frame_title ("*invalid*", 0, precision - n);
+      else if (!NILP (mode_line_string_list))
+       n += store_mode_line_string ("*invalid*", Qnil, 0, 0, precision - n, Qnil);
       else
        n += display_string ("*invalid*", Qnil, Qnil, 0, 0, it, 0,
                             precision - n, 0, 0);
@@ -13701,14 +14146,214 @@ display_mode_element (it, depth, field_width, precision, elt)
     {
       if (frame_title_ptr)
        n += store_frame_title ("", field_width - n, 0);
+      else if (!NILP (mode_line_string_list))
+       n += store_mode_line_string ("", Qnil, 0, field_width - n, 0, Qnil);
       else
        n += display_string ("", Qnil, Qnil, 0, 0, it, field_width - n,
                             0, 0, 0);
     }
-  
+
   return n;
 }
 
+/* Store a mode-line string element in mode_line_string_list.
+
+   If STRING is non-null, display that C string.  Otherwise, the Lisp
+   string LISP_STRING is displayed.
+
+   FIELD_WIDTH is the minimum number of output glyphs to produce.
+   If STRING has fewer characters than FIELD_WIDTH, pad to the right
+   with spaces.  FIELD_WIDTH <= 0 means don't pad.
+
+   PRECISION is the maximum number of characters to output from
+   STRING.  PRECISION <= 0  means don't truncate the string.
+
+   If COPY_STRING is non-zero, make a copy of LISP_STRING before adding
+   properties to the string.
+
+   PROPS are the properties to add to the string.  
+   The mode_line_string_face face property is always added to the string.
+ */
+
+static int store_mode_line_string (string, lisp_string, copy_string, field_width, precision, props)
+     char *string;
+     Lisp_Object lisp_string;
+     int copy_string;
+     int field_width;
+     int precision;
+     Lisp_Object props;
+{
+  int len;
+  int n = 0;
+
+  if (string != NULL)
+    {
+      len = strlen (string);
+      if (precision > 0 && len > precision)
+       len = precision;
+      lisp_string = make_string (string, len);
+      if (NILP (props))
+       props = mode_line_string_face_prop;
+      else if (!NILP (mode_line_string_face))
+       {
+         Lisp_Object face = Fplist_get (props, Qface);
+         props = Fcopy_sequence (props);
+         if (NILP (face))
+           face = mode_line_string_face;
+         else
+           face = Fcons (face, Fcons (mode_line_string_face, Qnil));
+         props = Fplist_put (props, Qface, face);
+       }
+      Fadd_text_properties (make_number (0), make_number (len),
+                           props, lisp_string);
+    }
+  else 
+    {
+      len = XFASTINT (Flength (lisp_string));
+      if (precision > 0 && len > precision)
+       {
+         len = precision;
+         lisp_string = Fsubstring (lisp_string, make_number (0), make_number (len));
+         precision = -1;
+       }
+      if (!NILP (mode_line_string_face))
+       {
+         Lisp_Object face;
+         if (NILP (props))
+           props = Ftext_properties_at (make_number (0), lisp_string);
+         face = Fplist_get (props, Qface);
+         if (NILP (face))
+           face = mode_line_string_face;
+         else
+           face = Fcons (face, Fcons (mode_line_string_face, Qnil));
+         props = Fcons (Qface, Fcons (face, Qnil));
+         if (copy_string)
+           lisp_string = Fcopy_sequence (lisp_string);
+       }
+      if (!NILP (props))
+       Fadd_text_properties (make_number (0), make_number (len),
+                             props, lisp_string);
+    }
+
+  if (len > 0)
+    {
+      mode_line_string_list = Fcons (lisp_string, mode_line_string_list);
+      n += len; 
+    }
+
+  if (field_width > len)
+    {
+      field_width -= len;
+      lisp_string = Fmake_string (make_number (field_width), make_number (' '));
+      if (!NILP (props))
+       Fadd_text_properties (make_number (0), make_number (field_width),
+                             props, lisp_string);
+      mode_line_string_list = Fcons (lisp_string, mode_line_string_list);
+      n += field_width; 
+    }
+
+  return n;
+}
+
+
+DEFUN ("format-mode-line", Fformat_mode_line, Sformat_mode_line,
+       0, 3, 0,
+       doc: /* Return the mode-line of selected window as a string.
+First optional arg FORMAT specifies a different format string (see
+`mode-line-format' for details) to use.  If FORMAT is t, return
+the buffer's header-line.  Second optional arg WINDOW specifies a
+different window to use as the context for the formatting.
+If third optional arg NO-PROPS is non-nil, string is not propertized.  */)
+     (format, window, no_props)
+     Lisp_Object format, window, no_props;
+{
+  struct it it;
+  int len;
+  struct window *w;
+  struct buffer *old_buffer = NULL;
+  enum face_id face_id = DEFAULT_FACE_ID;
+
+  if (NILP (window))
+    window = selected_window;
+  CHECK_WINDOW (window);
+  w = XWINDOW (window);
+  CHECK_BUFFER (w->buffer);
+
+  if (XBUFFER (w->buffer) != current_buffer)
+    {
+      old_buffer = current_buffer;
+      set_buffer_internal_1 (XBUFFER (w->buffer));
+    }
+
+  if (NILP (format) || EQ (format, Qt))
+    {
+      face_id = NILP (format)
+       ? CURRENT_MODE_LINE_FACE_ID (w) :
+       HEADER_LINE_FACE_ID;
+      format = NILP (format)
+       ? current_buffer->mode_line_format
+       : current_buffer->header_line_format;
+    }
+
+  init_iterator (&it, w, -1, -1, NULL, face_id);
+
+  if (NILP (no_props))
+    {
+      mode_line_string_face =
+       (face_id == MODE_LINE_FACE_ID ? Qmode_line :
+        face_id == MODE_LINE_INACTIVE_FACE_ID ? Qmode_line_inactive :
+        face_id == HEADER_LINE_FACE_ID ? Qheader_line : Qnil);
+
+      mode_line_string_face_prop =
+       NILP (mode_line_string_face) ? Qnil :
+       Fcons (Qface, Fcons (mode_line_string_face, Qnil));
+
+      /* We need a dummy last element in mode_line_string_list to
+        indicate we are building the propertized mode-line string.
+        Using mode_line_string_face_prop here GC protects it.  */
+      mode_line_string_list = 
+       Fcons (mode_line_string_face_prop, Qnil);
+      frame_title_ptr = NULL;
+    }
+  else
+    {
+      mode_line_string_face_prop = Qnil;
+      mode_line_string_list = Qnil;
+      frame_title_ptr = frame_title_buf;
+    }
+
+  push_frame_kboard (it.f);
+  display_mode_element (&it, 0, 0, 0, format, Qnil, 0);
+  pop_frame_kboard ();
+
+  if (old_buffer)
+    set_buffer_internal_1 (old_buffer);
+
+  if (NILP (no_props))
+    {
+      Lisp_Object str;
+      mode_line_string_list = Fnreverse (mode_line_string_list);
+      str = Fmapconcat (intern ("identity"), XCDR (mode_line_string_list),
+                       make_string ("", 0));
+      mode_line_string_face_prop = Qnil;
+      mode_line_string_list = Qnil;
+      return str;
+    }
+
+  len = frame_title_ptr - frame_title_buf;
+  if (len > 0 && frame_title_ptr[-1] == '-')
+    {
+      /* Mode lines typically ends with numerous dashes; reduce to two dashes.  */
+      while (frame_title_ptr > frame_title_buf && *--frame_title_ptr == '-')
+       ;
+      frame_title_ptr += 3;  /* restore last non-dash + two dashes */
+      if (len > frame_title_ptr - frame_title_buf)
+       len = frame_title_ptr - frame_title_buf;
+    }
+
+  frame_title_ptr = NULL;
+  return make_string (frame_title_buf, len);
+}
 
 /* Write a null-terminated, right justified decimal representation of
    the positive integer D to BUF using a minimal field width WIDTH.  */
@@ -13720,7 +14365,7 @@ pint2str (buf, width, d)
      register int d;
 {
   register char *p = buf;
-  
+
   if (d <= 0)
     *p++ = '0';
   else
@@ -13731,7 +14376,7 @@ pint2str (buf, width, d)
          d /= 10;
        }
     }
-  
+
   for (width -= (int) (p - buf); width > 0; --width)
     *p++ = ' ';
   *p-- = '\0';
@@ -13757,7 +14402,7 @@ decode_mode_spec_coding (coding_system, buf, eol_flag)
 {
   Lisp_Object val;
   int multibyte = !NILP (current_buffer->enable_multibyte_characters);
-  unsigned char *eol_str;
+  const unsigned char *eol_str;
   int eol_str_len;
   /* The EOL conversion we are using.  */
   Lisp_Object eoltype;
@@ -13797,20 +14442,21 @@ decode_mode_spec_coding (coding_system, buf, eol_flag)
                          ? eol_mnemonic_dos : eol_mnemonic_mac));
        }
     }
-  
+
   if (eol_flag)
     {
       /* Mention the EOL conversion if it is not the usual one.  */
       if (STRINGP (eoltype))
        {
-         eol_str = XSTRING (eoltype)->data;
-         eol_str_len = XSTRING (eoltype)->size;
+         eol_str = SDATA (eoltype);
+         eol_str_len = SBYTES (eoltype);
        }
       else if (INTEGERP (eoltype)
               && CHAR_VALID_P (XINT (eoltype), 0))
        {
-         eol_str = (unsigned char *) alloca (MAX_MULTIBYTE_LENGTH);
-         eol_str_len = CHAR_STRING (XINT (eoltype), eol_str);
+         unsigned char *tmp = (unsigned char *) alloca (MAX_MULTIBYTE_LENGTH);
+         eol_str_len = CHAR_STRING (XINT (eoltype), tmp);
+         eol_str = tmp;
        }
       else
        {
@@ -13873,7 +14519,7 @@ decode_mode_spec (w, c, field_width, precision, multibyte)
     case '%':
       return "%";
 
-    case '[': 
+    case '[':
       {
        int i;
        char *p;
@@ -13887,7 +14533,7 @@ decode_mode_spec (w, c, field_width, precision, multibyte)
        return decode_mode_spec_buf;
       }
 
-    case ']': 
+    case ']':
       {
        int i;
        char *p;
@@ -13906,6 +14552,8 @@ decode_mode_spec (w, c, field_width, precision, multibyte)
        register int i;
 
        /* Let lots_of_dashes be a string of infinite length.  */
+       if (!NILP (mode_line_string_list))
+         return "--";
        if (field_width <= 0
            || field_width > sizeof (lots_of_dashes))
          {
@@ -13918,13 +14566,13 @@ decode_mode_spec (w, c, field_width, precision, multibyte)
          return lots_of_dashes;
       }
 
-    case 'b': 
+    case 'b':
       obj = b->name;
       break;
 
     case 'c':
       {
-       int col = current_column ();
+       int col = (int) current_column (); /* iftc */
        w->column_number_displayed = make_number (col);
        pint2str (decode_mode_spec_buf, field_width, col);
        return decode_mode_spec_buf;
@@ -13933,12 +14581,12 @@ decode_mode_spec (w, c, field_width, precision, multibyte)
     case 'F':
       /* %F displays the frame name.  */
       if (!NILP (f->title))
-       return (char *) XSTRING (f->title)->data;
+       return (char *) SDATA (f->title);
       if (f->explicit_name || ! FRAME_WINDOW_P (f))
-       return (char *) XSTRING (f->name)->data;
+       return (char *) SDATA (f->name);
       return "Emacs";
 
-    case 'f': 
+    case 'f':
       obj = b->filename;
       break;
 
@@ -13950,7 +14598,7 @@ decode_mode_spec (w, c, field_width, precision, multibyte)
        int nlines, junk;
        int height = XFASTINT (w->height);
 
-       /* If we decided that this buffer isn't suitable for line numbers, 
+       /* If we decided that this buffer isn't suitable for line numbers,
           don't forget that too fast.  */
        if (EQ (w->base_line_pos, w->buffer))
          goto no_value;
@@ -14016,7 +14664,7 @@ decode_mode_spec (w, c, field_width, precision, multibyte)
                                          limit_byte,
                                          - (height * 2 + 30),
                                          &position);
-           /* If we couldn't find the lines we wanted within 
+           /* If we couldn't find the lines we wanted within
               line_number_display_limit_width chars per line,
               give up on line numbers for this window.  */
            if (position == limit_byte && limit == startpos - distance)
@@ -14054,7 +14702,7 @@ decode_mode_spec (w, c, field_width, precision, multibyte)
       }
       break;
 
-    case 'm': 
+    case 'm':
       obj = b->mode_name;
       break;
 
@@ -14181,7 +14829,7 @@ decode_mode_spec (w, c, field_width, precision, multibyte)
   if (STRINGP (obj))
     {
       *multibyte = STRING_MULTIBYTE (obj);
-      return (char *) XSTRING (obj)->data;
+      return (char *) SDATA (obj);
     }
   else
     return "";
@@ -14314,7 +14962,7 @@ display_count_lines (start, start_byte, limit_byte, count, byte_pos_ptr)
    If STRING has fewer characters than FIELD_WIDTH, pad to the right
    with spaces.  If STRING has more characters, more than FIELD_WIDTH
    glyphs will be produced.  FIELD_WIDTH <= 0 means don't pad.
-   
+
    PRECISION is the maximum number of characters to output from
    STRING.  PRECISION < 0  means don't truncate the string.
 
@@ -14360,7 +15008,7 @@ display_string (string, lisp_string, face_string, face_string_pos,
     {
       int endptr;
       struct face *face;
-      
+
       it->face_id
        = face_at_string_position (it->w, face_string, face_string_pos,
                                   0, it->region_beg_charpos,
@@ -14409,7 +15057,7 @@ display_string (string, lisp_string, face_string, face_string_pos,
       while (i < nglyphs)
        {
          struct glyph *glyph = row->glyphs[TEXT_AREA] + n_glyphs_before + i;
-         
+
          if (!it->truncate_lines_p
              && x + glyph->pixel_width > max_x)
            {
@@ -14504,7 +15152,7 @@ display_string (string, lisp_string, face_string, face_string_pos,
     }
 
   it->face_id = saved_face_id;
-  
+
   /* Value is number of columns displayed.  */
   return it->hpos - hpos_at_start;
 }
@@ -14525,7 +15173,7 @@ invisible_p (propval, list)
      Lisp_Object list;
 {
   register Lisp_Object tail, proptail;
-  
+
   for (tail = list; CONSP (tail); tail = XCDR (tail))
     {
       register Lisp_Object tem;
@@ -14535,7 +15183,7 @@ invisible_p (propval, list)
       if (CONSP (tem) && EQ (propval, XCAR (tem)))
        return NILP (XCDR (tem)) ? 1 : 2;
     }
-  
+
   if (CONSP (propval))
     {
       for (proptail = propval; CONSP (proptail); proptail = XCDR (proptail))
@@ -14553,11 +15201,204 @@ invisible_p (propval, list)
            }
        }
     }
-  
+
   return 0;
 }
 
 \f
+/***********************************************************************
+                            Cursor types
+ ***********************************************************************/
+
+/* Value is the internal representation of the specified cursor type
+   ARG.  If type is BAR_CURSOR, return in *WIDTH the specified width
+   of the bar cursor.  */
+
+enum text_cursor_kinds
+get_specified_cursor_type (arg, width)
+     Lisp_Object arg;
+     int *width;
+{
+  enum text_cursor_kinds type;
+  
+  if (NILP (arg))
+    return NO_CURSOR;
+
+  if (EQ (arg, Qbox))
+    return FILLED_BOX_CURSOR;
+
+  if (EQ (arg, Qhollow))
+    return HOLLOW_BOX_CURSOR;
+
+  if (EQ (arg, Qbar))
+    {
+      *width = 2;
+      return BAR_CURSOR;
+    }
+
+  if (CONSP (arg)
+      && EQ (XCAR (arg), Qbar)
+      && INTEGERP (XCDR (arg))
+      && XINT (XCDR (arg)) >= 0)
+    {
+      *width = XINT (XCDR (arg));
+      return BAR_CURSOR;
+    }
+
+  if (EQ (arg, Qhbar))
+    {
+      *width = 2;
+      return HBAR_CURSOR;
+    }
+
+  if (CONSP (arg)
+      && EQ (XCAR (arg), Qhbar)
+      && INTEGERP (XCDR (arg))
+      && XINT (XCDR (arg)) >= 0)
+    {
+      *width = XINT (XCDR (arg));
+      return HBAR_CURSOR;
+    }
+
+  /* Treat anything unknown as "hollow box cursor".
+     It was bad to signal an error; people have trouble fixing
+     .Xdefaults with Emacs, when it has something bad in it.  */
+  type = HOLLOW_BOX_CURSOR;
+
+  return type;
+}
+
+/* Set the default cursor types for specified frame.  */
+void
+set_frame_cursor_types (f, arg)
+     struct frame *f;
+     Lisp_Object arg;
+{
+  int width;
+  Lisp_Object tem;
+
+  FRAME_DESIRED_CURSOR (f) = get_specified_cursor_type (arg, &width);
+  FRAME_CURSOR_WIDTH (f) = width;
+
+  /* By default, set up the blink-off state depending on the on-state.  */
+
+  tem = Fassoc (arg, Vblink_cursor_alist);
+  if (!NILP (tem))
+    {
+      FRAME_BLINK_OFF_CURSOR (f)
+       = get_specified_cursor_type (XCDR (tem), &width);
+      FRAME_BLINK_OFF_CURSOR_WIDTH (f) = width;
+    }
+  else
+    FRAME_BLINK_OFF_CURSOR (f) = DEFAULT_CURSOR;
+}
+
+
+/* Return 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 or buffer local setting of
+   cursor-type.  If explicitly marked off, draw no cursor.  In all
+   other cases, we want a hollow box cursor.  */
+
+enum text_cursor_kinds
+get_window_cursor_type (w, width)
+     struct window *w;
+     int *width;
+{
+  struct frame *f = XFRAME (w->frame);
+  struct buffer *b = XBUFFER (w->buffer);
+  int cursor_type = DEFAULT_CURSOR;
+  Lisp_Object alt_cursor;
+  int non_selected = 0;
+
+  /* Echo area */
+  if (cursor_in_echo_area
+      && FRAME_HAS_MINIBUF_P (f)
+      && EQ (FRAME_MINIBUF_WINDOW (f), echo_area_window))
+    {
+      if (w == XWINDOW (echo_area_window))
+       {
+         *width = FRAME_CURSOR_WIDTH (f);
+         return FRAME_DESIRED_CURSOR (f);
+       }
+
+      non_selected = 1;
+    }
+
+  /* Nonselected window or nonselected frame.  */
+  else if (f != FRAME_X_DISPLAY_INFO (f)->x_highlight_frame
+      || w != XWINDOW (f->selected_window))
+    {
+      if (MINI_WINDOW_P (w) && minibuf_level == 0)
+       return NO_CURSOR;
+
+      non_selected = 1;
+    }
+
+  /* Never display a cursor in a window in which cursor-type is nil.  */
+  if (NILP (b->cursor_type))
+    return NO_CURSOR;
+
+  /* Use cursor-in-non-selected-windows for non-selected window or frame.  */
+  if (non_selected)
+    {
+      alt_cursor = Fbuffer_local_value (Qcursor_in_non_selected_windows, w->buffer);
+      return get_specified_cursor_type (alt_cursor, width);
+    }
+
+  /* Get the normal cursor type for this window.  */
+  if (EQ (b->cursor_type, Qt))
+    {
+      cursor_type = FRAME_DESIRED_CURSOR (f);
+      *width = FRAME_CURSOR_WIDTH (f);
+    }
+  else
+    cursor_type = get_specified_cursor_type (b->cursor_type, width);
+
+  /* Use normal cursor if not blinked off.  */
+  if (!w->cursor_off_p)
+    return cursor_type;
+
+  /* Cursor is blinked off, so determine how to "toggle" it.  */
+
+  /* First try to use alternate-cursor-type, unless it is t.  */
+  alt_cursor = Fbuffer_local_value (Qalternate_cursor_type, w->buffer);
+  if (!EQ (alt_cursor, Qt))
+    return get_specified_cursor_type (alt_cursor, width);
+
+  /* Then unless buffer's cursor-type is t (use default),
+     look for an entry matching normal cursor in blink-cursor-alist.  */
+  if (!EQ (b->cursor_type, Qt) &&
+      (alt_cursor = Fassoc (b->cursor_type, Vblink_cursor_alist), !NILP (alt_cursor)))
+    return get_specified_cursor_type (XCDR (alt_cursor), width);
+
+  /* Then see if frame has specified a specific blink off cursor type.  */
+  if (FRAME_BLINK_OFF_CURSOR (f) != DEFAULT_CURSOR)
+    {
+      *width = FRAME_BLINK_OFF_CURSOR_WIDTH (f);
+      return FRAME_BLINK_OFF_CURSOR (f);
+    }
+  
+  /* Finally perform built-in cursor blinking: 
+       filled box      <->   hollow box
+       wide [h]bar     <->   narrow [h]bar
+       narrow [h]bar   <->   no cursor
+       other type      <->   no cursor  */
+
+  if (cursor_type == FILLED_BOX_CURSOR)
+    return HOLLOW_BOX_CURSOR;
+
+  if ((cursor_type == BAR_CURSOR || cursor_type == HBAR_CURSOR) && *width > 1)
+    {
+      *width = 1;
+      return cursor_type;
+    }
+
+  return NO_CURSOR;
+}
+
+\f
 /***********************************************************************
                            Initialization
  ***********************************************************************/
@@ -14570,11 +15411,19 @@ syms_of_xdisp ()
 
   Vmessage_stack = Qnil;
   staticpro (&Vmessage_stack);
-  
+
   Qinhibit_redisplay = intern ("inhibit-redisplay");
   staticpro (&Qinhibit_redisplay);
 
+  message_dolog_marker1 = Fmake_marker ();
+  staticpro (&message_dolog_marker1);
+  message_dolog_marker2 = Fmake_marker ();
+  staticpro (&message_dolog_marker2);
+  message_dolog_marker3 = Fmake_marker ();
+  staticpro (&message_dolog_marker3);
+
 #if GLYPH_DEBUG
+  defsubr (&Sdump_frame_glyph_matrix);
   defsubr (&Sdump_glyph_matrix);
   defsubr (&Sdump_glyph_row);
   defsubr (&Sdump_tool_bar_row);
@@ -14584,6 +15433,7 @@ syms_of_xdisp ()
 #ifdef HAVE_WINDOW_SYSTEM
   defsubr (&Stool_bar_lines_needed);
 #endif
+  defsubr (&Sformat_mode_line);
 
   staticpro (&Qmenu_bar_update_hook);
   Qmenu_bar_update_hook = intern ("menu-bar-update-hook");
@@ -14599,7 +15449,7 @@ syms_of_xdisp ()
 
   staticpro (&Qredisplay_end_trigger_functions);
   Qredisplay_end_trigger_functions = intern ("redisplay-end-trigger-functions");
-  
+
   staticpro (&Qinhibit_point_motion_hooks);
   Qinhibit_point_motion_hooks = intern ("inhibit-point-motion-hooks");
 
@@ -14631,6 +15481,8 @@ syms_of_xdisp ()
   staticpro (&QCrelative_height);
   QCeval = intern (":eval");
   staticpro (&QCeval);
+  QCpropertize = intern (":propertize");
+  staticpro (&QCpropertize);
   Qwhen = intern ("when");
   staticpro (&Qwhen);
   QCfile = intern (":file");
@@ -14645,6 +15497,10 @@ syms_of_xdisp ()
   staticpro (&Qimage);
   Qmessage_truncate_lines = intern ("message-truncate-lines");
   staticpro (&Qmessage_truncate_lines);
+  Qcursor_in_non_selected_windows = intern ("cursor-in-non-selected-windows");
+  staticpro (&Qcursor_in_non_selected_windows);
+  Qalternate_cursor_type = intern ("alternate-cursor-type");
+  staticpro (&Qalternate_cursor_type);
   Qgrow_only = intern ("grow-only");
   staticpro (&Qgrow_only);
   Qinhibit_menubar_update = intern ("inhibit-menubar-update");
@@ -14657,12 +15513,27 @@ syms_of_xdisp ()
   staticpro (&Qbuffer_position);
   Qobject = intern ("object");
   staticpro (&Qobject);
+  Qbar = intern ("bar");
+  staticpro (&Qbar);
+  Qhbar = intern ("hbar");
+  staticpro (&Qhbar);
+  Qbox = intern ("box");
+  staticpro (&Qbox);
+  Qhollow = intern ("hollow");
+  staticpro (&Qhollow);
+  Qrisky_local_variable = intern ("risky-local-variable");
+  staticpro (&Qrisky_local_variable);
+  Qinhibit_free_realized_faces = intern ("inhibit-free-realized-faces");
+  staticpro (&Qinhibit_free_realized_faces);
+
+  list_of_error = Fcons (intern ("error"), Qnil);
+  staticpro (&list_of_error);
 
   last_arrow_position = Qnil;
   last_arrow_string = Qnil;
   staticpro (&last_arrow_position);
   staticpro (&last_arrow_string);
-  
+
   echo_buffer[0] = echo_buffer[1] = Qnil;
   staticpro (&echo_buffer[0]);
   staticpro (&echo_buffer[1]);
@@ -14673,7 +15544,13 @@ syms_of_xdisp ()
 
   Vmessages_buffer_name = build_string ("*Messages*");
   staticpro (&Vmessages_buffer_name);
-  
+
+  mode_line_proptrans_alist = Qnil;
+  staticpro (&mode_line_proptrans_alist);
+
+  mode_line_string_list = Qnil;
+  staticpro (&mode_line_string_list);
+
   DEFVAR_LISP ("show-trailing-whitespace", &Vshow_trailing_whitespace,
     doc: /* Non-nil means highlight trailing whitespace.
 The face used for trailing whitespace is `trailing-whitespace'.  */);
@@ -14729,9 +15606,7 @@ of the top or bottom of the window.  */);
   DEFVAR_BOOL ("mode-line-inverse-video", &mode_line_inverse_video,
     doc: /* nil means display the mode-line/header-line/menu-bar in the default face.
 Any other value means to use the appropriate face, `mode-line',
-`header-line', or `menu' respectively.
-
-This variable is deprecated; please change the above faces instead.  */);
+`header-line', or `menu' respectively.  */);
   mode_line_inverse_video = 1;
 
   DEFVAR_LISP ("line-number-display-limit", &Vline_number_display_limit,
@@ -14800,14 +15675,14 @@ Each function is called with two arguments, the window
 and its new display-start position.  Note that the value of `window-end'
 is not valid when these functions are called.  */);
   Vwindow_scroll_functions = Qnil;
-  
+
   DEFVAR_BOOL ("auto-resize-tool-bars", &auto_resize_tool_bars_p,
     doc: /* *Non-nil means automatically resize tool-bars.
 This increases a tool-bar's height if not all tool-bar items are visible.
 It decreases a tool-bar's height when it would display blank lines
 otherwise.  */);
   auto_resize_tool_bars_p = 1;
-  
+
   DEFVAR_BOOL ("auto-raise-tool-bar-buttons", &auto_raise_tool_bar_buttons_p,
     doc: /* *Non-nil means raise tool-bar buttons when the mouse moves over them.  */);
   auto_raise_tool_bar_buttons_p = 1;
@@ -14815,13 +15690,13 @@ otherwise.  */);
   DEFVAR_LISP ("tool-bar-button-margin", &Vtool_bar_button_margin,
     doc: /* *Margin around tool-bar buttons in pixels.
 If an integer, use that for both horizontal and vertical margins.
-Otherwise, value should be a pair of integers `(HORZ : VERT)' with
+Otherwise, value should be a pair of integers `(HORZ . VERT)' with
 HORZ specifying the horizontal margin, and VERT specifying the
 vertical margin.  */);
   Vtool_bar_button_margin = make_number (DEFAULT_TOOL_BAR_BUTTON_MARGIN);
 
   DEFVAR_INT ("tool-bar-button-relief", &tool_bar_button_relief,
-    doc: /* Relief thickness of tool-bar buttons.  */);
+    doc: /* *Relief thickness of tool-bar buttons.  */);
   tool_bar_button_relief = DEFAULT_TOOL_BAR_BUTTON_RELIEF;
 
   DEFVAR_LISP ("fontification-functions", &Vfontification_functions,
@@ -14856,21 +15731,57 @@ only, until their display becomes empty, at which point the windows
 go back to their normal size.  */);
   Vresize_mini_windows = Qgrow_only;
 
-  DEFVAR_BOOL ("cursor-in-non-selected-windows",
-              &cursor_in_non_selected_windows,
-    doc: /* *Non-nil means display a hollow cursor in non-selected windows.
-Nil means don't display a cursor there.  */);
-  cursor_in_non_selected_windows = 1;
-  
-  DEFVAR_BOOL ("automatic-hscrolling", &automatic_hscrolling_p,
+  DEFVAR_LISP ("cursor-in-non-selected-windows",
+              &Vcursor_in_non_selected_windows,
+    doc: /* *Cursor type to display in non-selected windows.
+t means to use hollow box cursor.  See `cursor-type' for other values.  */);
+  Vcursor_in_non_selected_windows = Qt;
+
+  DEFVAR_LISP ("alternate-cursor-type", &Valternate_cursor_type,
+    doc: /* *Cursor type displayed in the blinking cursor off state.
+t means to use default.  See `cursor-type' for other values.  */);
+  Valternate_cursor_type = Qt;
+
+  DEFVAR_LISP ("blink-cursor-alist", &Vblink_cursor_alist,
+    doc: /* Alist specifying how to blink the cursor off.
+Each element has the form (ON-STATE . OFF-STATE).  Whenever the
+`cursor-type' frame-parameter or variable equals ON-STATE,
+comparing using `equal', Emacs uses OFF-STATE to specify
+how to blink it off.  */);
+  Vblink_cursor_alist = Qnil;
+
+  DEFVAR_BOOL ("auto-hscroll-mode", &automatic_hscrolling_p,
     doc: /* *Non-nil means scroll the display automatically to make point visible.  */);
   automatic_hscrolling_p = 1;
-  
+
+  DEFVAR_INT ("hscroll-margin", &hscroll_margin,
+    doc: /* *How many columns away from the window edge point is allowed to get
+before automatic hscrolling will horizontally scroll the window.  */);
+  hscroll_margin = 5;
+
+  DEFVAR_LISP ("hscroll-step", &Vhscroll_step,
+    doc: /* *How many columns to scroll the window when point gets too close to the edge.
+When point is less than `automatic-hscroll-margin' columns from the window
+edge, automatic hscrolling will scroll the window by the amount of columns
+determined by this variable.  If its value is a positive integer, scroll that
+many columns.  If it's a positive floating-point number, it specifies the
+fraction of the window's width to scroll.  If it's nil or zero, point will be
+centered horizontally after the scroll.  Any other value, including negative
+numbers, are treated as if the value were zero.
+
+Automatic hscrolling always moves point outside the scroll margin, so if
+point was more than scroll step columns inside the margin, the window will
+scroll more than the value given by the scroll step.
+
+Note that the lower bound for automatic hscrolling specified by `scroll-left'
+and `scroll-right' overrides this variable's effect.  */);
+  Vhscroll_step = make_number (0);
+
   DEFVAR_LISP ("image-types", &Vimage_types,
     doc: /* List of supported image types.
 Each element of the list is a symbol for a supported image type.  */);
   Vimage_types = Qnil;
-  
+
   DEFVAR_BOOL ("message-truncate-lines", &message_truncate_lines,
     doc: /* If non-nil, messages are truncated instead of resizing the echo area.
 Bind this around calls to `message' to let it take effect.  */);
@@ -14880,7 +15791,7 @@ Bind this around calls to `message' to let it take effect.  */);
     doc: /* Normal hook run for clicks on menu bar, before displaying a submenu.
 Can be used to update submenus whose contents should vary.  */);
   Vmenu_bar_update_hook = Qnil;
-  
+
   DEFVAR_BOOL ("inhibit-menubar-update", &inhibit_menubar_update,
     doc: /* Non-nil means don't update menu bars.  Internal use only.  */);
   inhibit_menubar_update = 0;
@@ -14889,7 +15800,11 @@ Can be used to update submenus whose contents should vary.  */);
     doc: /* Non-nil means don't eval Lisp during redisplay.  */);
   inhibit_eval_during_redisplay = 0;
 
-#ifdef GLYPH_DEBUG
+  DEFVAR_BOOL ("inhibit-free-realized-faces", &inhibit_free_realized_faces,
+    doc: /* Non-nil means don't free realized faces.  Internal use only.  */);
+  inhibit_free_realized_faces = 0;
+
+#if GLYPH_DEBUG
   DEFVAR_BOOL ("inhibit-try-window-id", &inhibit_try_window_id,
               doc: /* Inhibit try_window_id display optimization.  */);
   inhibit_try_window_id = 0;
@@ -14939,21 +15854,20 @@ init_xdisp ()
       scratch_glyph_row.glyphs[TEXT_AREA + 1]
        = scratch_glyphs + MAX_SCRATCH_GLYPHS;
 
-      /* The default ellipsis glyphs `...'.  */ 
+      /* The default ellipsis glyphs `...'.  */
       for (i = 0; i < 3; ++i)
        default_invis_vector[i] = make_number ('.');
     }
 
-#ifdef HAVE_WINDOW_SYSTEM
   {
-    /* Allocate the buffer for frame titles.  */
+    /* Allocate the buffer for frame titles.
+       Also used for `format-mode-line'.  */
     int size = 100;
     frame_title_buf = (char *) xmalloc (size);
     frame_title_buf_end = frame_title_buf + size;
     frame_title_ptr = NULL;
   }
-#endif /* HAVE_WINDOW_SYSTEM */
-  
+
   help_echo_showing_p = 0;
 }