(resize_mini_window): Don't resize while redisplaying.
[bpt/emacs.git] / src / xdisp.c
index c310622..6a56fe1 100644 (file)
@@ -226,6 +226,7 @@ Lisp_Object Qinhibit_point_motion_hooks;
 Lisp_Object QCeval, Qwhen, QCfile, QCdata;
 Lisp_Object Qfontified;
 Lisp_Object Qgrow_only;
+Lisp_Object Qinhibit_eval_during_redisplay;
 
 /* Functions called to fontify regions of text.  */
 
@@ -254,6 +255,10 @@ int auto_resize_tool_bars_p;
 
 Lisp_Object Vinhibit_redisplay, Qinhibit_redisplay;
 
+/* Non-zero means Lisp evaluation during redisplay is inhibited.  */
+
+int inhibit_eval_during_redisplay;
+
 /* Names of text properties relevant for redisplay.  */
 
 Lisp_Object Qdisplay, Qrelative_width, Qalign_to;
@@ -654,6 +659,7 @@ enum move_it_result
 \f
 /* Function prototypes.  */
 
+static void setup_for_ellipsis P_ ((struct it *));
 static void mark_window_display_accurate_1 P_ ((struct window *, int));
 static int single_display_prop_string_p P_ ((Lisp_Object, Lisp_Object));
 static int display_prop_string_p P_ ((Lisp_Object, Lisp_Object));
@@ -727,7 +733,7 @@ static int display_string P_ ((unsigned char *, Lisp_Object, Lisp_Object,
                               int, int, struct it *, int, int, int, int));
 static void compute_line_metrics P_ ((struct it *));
 static void run_redisplay_end_trigger_hook P_ ((struct it *));
-static int get_overlay_strings P_ ((struct it *));
+static int get_overlay_strings P_ ((struct it *, int));
 static void next_overlay_string P_ ((struct it *));
 static void reseat P_ ((struct it *, struct text_pos, int));
 static void reseat_1 P_ ((struct it *, struct text_pos, int));
@@ -741,7 +747,7 @@ static int next_element_from_buffer P_ ((struct it *));
 static int next_element_from_composition P_ ((struct it *));
 static int next_element_from_image P_ ((struct it *));
 static int next_element_from_stretch P_ ((struct it *));
-static void load_overlay_strings P_ ((struct it *));
+static void load_overlay_strings P_ ((struct it *, int));
 static void init_from_display_pos P_ ((struct it *, struct window *,
                                       struct display_pos *));
 static void reseat_to_string P_ ((struct it *, unsigned char *,
@@ -1278,15 +1284,24 @@ Lisp_Object
 safe_eval (sexpr)
      Lisp_Object sexpr;
 {
-  int count = BINDING_STACK_SIZE ();
-  struct gcpro gcpro1;
   Lisp_Object val;
+  
+  if (inhibit_eval_during_redisplay)
+    val = Qnil;
+  else
+    {
+      int count = BINDING_STACK_SIZE ();
+      struct gcpro gcpro1;
 
-  GCPRO1 (sexpr);
-  specbind (Qinhibit_redisplay, Qt);
-  val = internal_condition_case_1 (Feval, sexpr, Qerror, safe_eval_handler);
-  UNGCPRO;
-  return unbind_to (count, val);
+      GCPRO1 (sexpr);
+      specbind (Qinhibit_redisplay, Qt);
+      val = internal_condition_case_1 (Feval, sexpr, Qerror,
+                                      safe_eval_handler);
+      UNGCPRO;
+      val = unbind_to (count, val);
+    }
+  
+  return val;
 }
 
 
@@ -1298,17 +1313,25 @@ safe_call (nargs, args)
      int nargs;
      Lisp_Object *args;
 {
-  int count = BINDING_STACK_SIZE ();
   Lisp_Object val;
-  struct gcpro gcpro1;
+  
+  if (inhibit_eval_during_redisplay)
+    val = Qnil;
+  else
+    {
+      int count = BINDING_STACK_SIZE ();
+      struct gcpro gcpro1;
 
-  GCPRO1 (args[0]);
-  gcpro1.nvars = nargs;
-  specbind (Qinhibit_redisplay, Qt);
-  val = internal_condition_case_2 (Ffuncall, nargs, args, Qerror,
-                                  safe_eval_handler);
-  UNGCPRO;
-  return unbind_to (count, val);
+      GCPRO1 (args[0]);
+      gcpro1.nvars = nargs;
+      specbind (Qinhibit_redisplay, Qt);
+      val = internal_condition_case_2 (Ffuncall, nargs, args, Qerror,
+                                      safe_eval_handler);
+      UNGCPRO;
+      val = unbind_to (count, val);
+    }
+
+  return val;
 }
 
 
@@ -1826,7 +1849,7 @@ init_from_display_pos (it, w, pos)
          it->current.overlay_string_index = 0;
          while (n--)
            {
-             load_overlay_strings (it);
+             load_overlay_strings (it, 0);
              it->current.overlay_string_index += OVERLAY_STRING_CHUNK_SIZE;
            }
        }
@@ -2509,12 +2532,14 @@ handle_invisible_prop (it)
     }
   else
     {
-      int visible_p, newpos, next_stop;
-      Lisp_Object pos, prop;
+      int visible_p, newpos, next_stop, start_charpos;
+      Lisp_Object pos, prop, overlay;
 
       /* First of all, is there invisible text at this position?  */
+      start_charpos = IT_CHARPOS (*it);
       pos = make_number (IT_CHARPOS (*it));
-      prop = Fget_char_property (pos, Qinvisible, it->window);
+      prop = get_char_property_and_overlay (pos, Qinvisible, it->window,
+                                           &overlay);
       
       /* If we are on invisible text, skip over it.  */
       if (TEXT_PROP_MEANS_INVISIBLE (prop)
@@ -2563,36 +2588,25 @@ handle_invisible_prop (it)
                IT_CHARPOS (*it) = next_stop;
            }
          while (!visible_p);
-         
+
          /* The position newpos is now either ZV or on visible text.  */
          IT_CHARPOS (*it) = newpos;
          IT_BYTEPOS (*it) = CHAR_TO_BYTE (newpos);
          
-         /* Maybe return `...' next for the end of the invisible text.  */
-         if (display_ellipsis_p)
+         /* 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
+            it that way.  (If the text is invisible because of an
+            overlay property instead of a text property, this is
+            already handled in the overlay code.)  */
+         if (NILP (overlay)
+             && get_overlay_strings (it, start_charpos))
            {
-             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 
-               {
-                 /* 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;
+             handled = HANDLED_RECOMPUTE_PROPS;
+             it->stack[it->sp - 1].display_ellipsis_p = display_ellipsis_p;
            }
+         else if (display_ellipsis_p)
+           setup_for_ellipsis (it);
        }
     }
 
@@ -2600,6 +2614,36 @@ handle_invisible_prop (it)
 }
 
 
+/* Make iterator IT return `...' next.  */
+
+static void
+setup_for_ellipsis (it)
+     struct it *it;
+{
+  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 
+    {
+      /* 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;
+}
+
+
 \f
 /***********************************************************************
                            'display' property
@@ -2644,10 +2688,17 @@ handle_display_prop (it)
     return HANDLED_NORMALLY;
 
   if (CONSP (prop)
-      && CONSP (XCAR (prop))
-      && !EQ (Qmargin, XCAR (XCAR (prop))))
+      /* Simple properties.  */
+      && !EQ (XCAR (prop), Qimage)
+      && !EQ (XCAR (prop), Qspace)
+      && !EQ (XCAR (prop), Qwhen)
+      && !EQ (XCAR (prop), Qspace_width)
+      && !EQ (XCAR (prop), Qheight)
+      && !EQ (XCAR (prop), Qraise)
+      /* Marginal area specifications.  */
+      && !(CONSP (XCAR (prop)) && EQ (XCAR (XCAR (prop)), Qmargin))
+      && !NILP (XCAR (prop)))
     {
-      /* A list of sub-properties.  */
       for (; CONSP (prop); prop = XCDR (prop))
        {
          if (handle_single_display_prop (it, XCAR (prop), object,
@@ -3256,7 +3307,7 @@ static enum prop_handled
 handle_overlay_change (it)
      struct it *it;
 {
-  if (!STRINGP (it->string) && get_overlay_strings (it))
+  if (!STRINGP (it->string) && get_overlay_strings (it, 0))
     return HANDLED_RECOMPUTE_PROPS;
   else
     return HANDLED_NORMALLY;
@@ -3280,6 +3331,8 @@ next_overlay_string (it)
       /* No more overlay strings.  Restore IT's settings to what
         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);
@@ -3294,6 +3347,11 @@ next_overlay_string (it)
         next_element_from_buffer doesn't try it again.  */
       if (IT_CHARPOS (*it) >= it->end_charpos)
        it->overlay_strings_at_end_processed_p = 1;
+
+      /* If we have to display `...' for invisible text, set
+        the iterator up for that.  */
+      if (display_ellipsis_p)
+       setup_for_ellipsis (it);
     }
   else
     {
@@ -3304,7 +3362,7 @@ next_overlay_string (it)
       int i = it->current.overlay_string_index % OVERLAY_STRING_CHUNK_SIZE;
   
       if (it->current.overlay_string_index && i == 0)
-       load_overlay_strings (it);
+       load_overlay_strings (it, 0);
 
       /* Initialize IT to deliver display elements from the overlay
          string.  */
@@ -3364,8 +3422,8 @@ compare_overlay_entries (e1, e2)
 
 
 /* Load the vector IT->overlay_strings with overlay strings from IT's
-   current buffer position.  Set IT->n_overlays to the total number of
-   overlay strings found.  
+   current buffer position, or from CHARPOS if that is > 0.  Set
+   IT->n_overlays to the total number of overlay strings found.
 
    Overlay strings are processed OVERLAY_STRING_CHUNK_SIZE strings at
    a time.  On entry into load_overlay_strings,
@@ -3388,8 +3446,9 @@ compare_overlay_entries (e1, e2)
    compare_overlay_entries.  */
    
 static void
-load_overlay_strings (it)
+load_overlay_strings (it, charpos)
      struct it *it;
+     int charpos;
 {
   extern Lisp_Object Qafter_string, Qbefore_string, Qwindow, Qpriority;
   Lisp_Object ov, overlay, window, str, invisible;
@@ -3398,7 +3457,9 @@ load_overlay_strings (it)
   int n = 0, i, j, invis_p;
   struct overlay_entry *entries
     = (struct overlay_entry *) alloca (size * sizeof *entries);
-  int charpos = IT_CHARPOS (*it);
+
+  if (charpos <= 0)
+    charpos = IT_CHARPOS (*it);
 
   /* Append the overlay string STRING of overlay OVERLAY to vector
      `entries' which has size `size' and currently contains `n'
@@ -3530,12 +3591,13 @@ load_overlay_strings (it)
 
 
 /* Get the first chunk of overlay strings at IT's current buffer
-   position.  Value is non-zero if at least one overlay string was
-   found.   */
+   position, or at CHARPOS if that is > 0.  Value is non-zero if at
+   least one overlay string was found.  */
 
 static int
-get_overlay_strings (it)
+get_overlay_strings (it, charpos)
      struct it *it;
+     int charpos;
 {
   /* Get the first OVERLAY_STRING_CHUNK_SIZE overlay strings to
      process.  This fills IT->overlay_strings with strings, and sets
@@ -3545,7 +3607,7 @@ get_overlay_strings (it)
      when no overlay strings are found because a zero value would
      indicate a position in the first overlay string.  */
   it->current.overlay_string_index = 0;
-  load_overlay_strings (it);
+  load_overlay_strings (it, charpos);
 
   /* If we found overlay strings, set up IT to deliver display
      elements from the first one.  Otherwise set up IT to deliver
@@ -3566,8 +3628,9 @@ get_overlay_strings (it)
       /* Set up IT to deliver display elements from the first overlay
         string.  */
       IT_STRING_CHARPOS (*it) = IT_STRING_BYTEPOS (*it) = 0;
-      it->stop_charpos = 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->method = next_element_from_string;
@@ -3618,6 +3681,7 @@ push_it (it)
   p->font_height = it->font_height;
   p->voffset = it->voffset;
   p->string_from_display_prop_p = it->string_from_display_prop_p;
+  p->display_ellipsis_p = 0;
   ++it->sp;
 }
 
@@ -3985,9 +4049,7 @@ reseat_to_string (it, s, string, charpos, precision, field_width, multibyte)
   
   /* If STRING is specified, use its multibyteness, otherwise use the
      setting of MULTIBYTE, if specified.  */
-  if (STRINGP (string))
-    it->multibyte_p = STRING_MULTIBYTE (string);
-  else if (multibyte >= 0)
+  if (multibyte >= 0)
     it->multibyte_p = multibyte > 0;
   
   if (s == NULL)
@@ -4165,7 +4227,22 @@ get_next_display_element (it)
                  if (SINGLE_BYTE_CHAR_P (it->c))
                    str[0] = it->c, len = 1;
                  else
-                   len = CHAR_STRING (it->c, str);
+                   {
+                     len = CHAR_STRING_NO_SIGNAL (it->c, str);
+                     if (len < 0)
+                       {
+                         /* It's an invalid character, which
+                            shouldn't happen actually, but due to
+                            bugs it may happen.  Let's print the char
+                            as is, there's not much meaningful we can
+                            do with it.  */
+                         str[0] = it->c;
+                         str[1] = it->c >> 8;
+                         str[2] = it->c >> 16;
+                         str[3] = it->c >> 24;
+                         len = 4;
+                       }
+                   }
 
                  for (i = 0; i < len; i++)
                    {
@@ -4348,6 +4425,8 @@ set_iterator_to_next (it, reseat_p)
              pop_it (it);
              if (!STRINGP (it->string))
                it->method = next_element_from_buffer;
+             else
+               goto consider_string_end;
            }
        }
     }
@@ -4672,7 +4751,7 @@ next_element_from_buffer (it)
          else
            {
              it->overlay_strings_at_end_processed_p = 1;
-             overlay_strings_follow_p = get_overlay_strings (it);
+             overlay_strings_follow_p = get_overlay_strings (it, 0);
            }
 
          if (overlay_strings_follow_p)
@@ -5435,6 +5514,12 @@ add_to_log (format, arg1, arg2)
   int len;
   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
 
+  /* Do nothing if called asynchronously.  Inserting text into
+     a buffer may call after-change-functions and alike and
+     that would means running Lisp asynchronously.  */
+  if (handling_signal)
+    return;
+
   fmt = msg = Qnil;
   GCPRO4 (fmt, msg, arg1, arg2);
   
@@ -6110,6 +6195,11 @@ with_echo_area_buffer (w, which, fn, a1, a2, a3, a4)
 
   buffer = echo_area_buffer[this_one];
 
+  /* Don't get confused by reusing the buffer used for echoing
+     for a different purpose.  */
+  if (!echoing && EQ (buffer, echo_message_buffer))
+    cancel_echoing ();
+
   record_unwind_protect (unwind_with_echo_area_buffer,
                         with_echo_area_buffer_unwind_data (w));
 
@@ -6410,6 +6500,12 @@ resize_mini_window (w, exact_p)
 
   xassert (MINI_WINDOW_P (w));
 
+  /* Don't resize windows while redisplaying; it would confuse
+     redisplay functions when the size of the window they are
+     displaying changes from under them.  */
+  if (redisplaying_p)
+    return 0;
+  
   /* Nil means don't try to resize.  */
   if (NILP (Vresize_mini_windows)
       || (FRAME_X_P (f) && f->output_data.x == NULL))
@@ -9504,7 +9600,7 @@ try_cursor_movement (window, startp, scroll_step)
          || current_buffer != XMARKER (Voverlay_arrow_position)->buffer))
     {
       int this_scroll_margin;
-      struct glyph_row *row;
+      struct glyph_row *row = NULL;
 
 #if GLYPH_DEBUG
       debug_method_add (w, "cursor movement");
@@ -9719,6 +9815,8 @@ redisplay_window (window, just_this_one_p)
            blank_row (w, row, y);
          goto finish_scroll_bars;
        }
+
+      clear_glyph_matrix (w->desired_matrix);
     }
 
   /* Otherwise set up data on this window; select its buffer and point
@@ -9949,36 +10047,10 @@ redisplay_window (window, just_this_one_p)
       goto recenter;
     }
   
-  /* Try scrolling with try_window_id.  */
-  else if (/* Windows and buffers haven't changed.  */
-          !windows_or_buffers_changed
-          /* Window must be either use window-based redisplay or
-             be full width.  */
-          && (FRAME_WINDOW_P (f)
-              || (line_ins_del_ok && WINDOW_FULL_WIDTH_P (w)))
-          && !MINI_WINDOW_P (w)
-          /* Point is not known NOT to appear in window.  */
-          && PT >= CHARPOS (startp)
-          && XFASTINT (w->last_modified)
-          /* Window is not hscrolled.  */
-          && XFASTINT (w->hscroll) == 0
-          /* Selective display has not changed.  */
-          && !current_buffer->clip_changed
-          /* Current matrix is up to date.  */
-          && !NILP (w->window_end_valid)
-          /* Can't use this case if highlighting a region because
-             a cursor movement will do more than just set the cursor.  */
-          && !(!NILP (Vtransient_mark_mode)
-               && !NILP (current_buffer->mark_active))
-          && NILP (w->region_showing)
-          && NILP (Vshow_trailing_whitespace)
-          /* Overlay arrow position and string not changed.  */
-          && EQ (last_arrow_position, COERCE_MARKER (Voverlay_arrow_position))
-          && EQ (last_arrow_string, Voverlay_arrow_string)
-          /* 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.  */
-          && (tem = try_window_id (w)) != 0)
+  /* 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.  */
+  else if ((tem = try_window_id (w)) != 0)
     {
 #if GLYPH_DEBUG
       debug_method_add (w, "try_window_id %d", tem);
@@ -10089,7 +10161,7 @@ redisplay_window (window, just_this_one_p)
   /* 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, it.last_visible_y / 2);
+  move_it_vertically_backward (&it, window_box_height (w) / 2);
   xassert (IT_CHARPOS (it) >= BEGV);
 
   /* The function move_it_vertically_backward may move over more
@@ -10802,15 +10874,14 @@ find_last_row_displaying_text (matrix, it, start)
 
 
 /* Return the last row in the current matrix of W that is not affected
-   by changes at the start of current_buffer that occurred since the
-   last time W was redisplayed.  Value is null if no such row exists.
+   by changes at the start of current_buffer that occurred since W's
+   current matrix was built.  Value is null if no such row exists.
 
-   The global variable beg_unchanged has to contain the number of
-   bytes unchanged at the start of current_buffer.  BEG +
-   beg_unchanged is the buffer position of the first changed byte in
-   current_buffer.  Characters at positions < BEG + beg_unchanged are
-   at the same buffer positions as they were when the current matrix
-   was built.  */
+   BEG_UNCHANGED us the number of characters unchanged at the start of
+   current_buffer.  BEG + BEG_UNCHANGED is the buffer position of the
+   first changed character in current_buffer.  Characters at positions <
+   BEG + BEG_UNCHANGED are at the same buffer positions as they were
+   when the current matrix was built.  */
 
 static struct glyph_row *
 find_last_unchanged_at_beg_row (w)
@@ -10851,12 +10922,16 @@ 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 last
-   time the window was redisplayed.  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.  */
+   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)
@@ -10901,8 +10976,8 @@ find_first_unchanged_at_end_row (w, delta, delta_bytes)
 
       /* Set last_unchanged_pos to the buffer position of the last
         character in the buffer that has not been changed.  Z is the
-        index + 1 of the last byte in current_buffer, i.e. by
-        subtracting end_unchanged we get the index of the last
+        index + 1 of the last character in current_buffer, i.e. by
+        subtracting END_UNCHANGED we get the index of the last
         unchanged character, and we have to add BEG to get its buffer
         position.  */
       last_unchanged_pos = Z - END_UNCHANGED + BEG;
@@ -11049,8 +11124,6 @@ row_containing_pos (w, charpos, start, end)
 
    7. Update W's window end information.  */
 
-  /* Check that window end is what we expect it to be.  */
-
 static int
 try_window_id (w)
      struct window *w;
@@ -11070,15 +11143,78 @@ try_window_id (w)
   int first_unchanged_at_end_vpos = 0;
   struct glyph_row *last_text_row, *last_text_row_at_end;
   struct text_pos start;
+  int first_changed_charpos, last_changed_charpos;
 
+  /* This is handy for debugging.  */
+#if 0
+#define GIVE_UP(X)                                             \
+  do {                                                         \
+    fprintf (stderr, "try_window_id give up %d\n", (X));       \
+    return 0;                                                  \
+  } while (0)
+#else
+#define GIVE_UP(X) return 0
+#endif
+  
   SET_TEXT_POS_FROM_MARKER (start, w->start);
 
-  /* Check pre-conditions.  Window end must be valid, otherwise
-     the current matrix would not be up to date.  */
-  xassert (!NILP (w->window_end_valid));
-  xassert (FRAME_WINDOW_P (XFRAME (w->frame))
-          || (line_ins_del_ok && WINDOW_FULL_WIDTH_P (w)));
+  /* 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)
+    GIVE_UP (2);
+  
+  /* Verify that narrowing has not changed.  This flag is also set 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)
+    GIVE_UP (3);
+
+  /* Window must either use window-based redisplay or be full width.  */
+  if (!FRAME_WINDOW_P (f)
+      && (!line_ins_del_ok
+         || !WINDOW_FULL_WIDTH_P (w)))
+    GIVE_UP (4);
+
+  /* Give up if point is not known NOT to appear in W.  */
+  if (PT < CHARPOS (start))
+    GIVE_UP (5);
 
+  /* 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)
+      && !NILP (current_buffer->mark_active))
+    GIVE_UP (9);
+
+  /* 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
@@ -11093,73 +11229,119 @@ try_window_id (w)
        END_UNCHANGED = Z - GPT;
     }
 
+  /* The position of the first and last character that has been changed.  */
+  first_changed_charpos = BEG + BEG_UNCHANGED;
+  last_changed_charpos  = Z - END_UNCHANGED;
+
   /* If window starts after a line end, and the last change is in
      front of that newline, then changes don't affect the display.
      This case happens with stealth-fontification.  Note that although
      the display is unchanged, glyph positions in the matrix have to
      be adjusted, of course.  */
   row = MATRIX_ROW (w->current_matrix, XFASTINT (w->window_end_vpos));
-  if (CHARPOS (start) > BEGV
-      && Z - END_UNCHANGED < CHARPOS (start) - 1
-      && FETCH_BYTE (BYTEPOS (start) - 1) == '\n'
-      && PT < MATRIX_ROW_END_CHARPOS (row))
+  if (MATRIX_ROW_DISPLAYS_TEXT_P (row)
+      && ((last_changed_charpos < CHARPOS (start)
+          && CHARPOS (start) == BEGV)
+         || (last_changed_charpos < CHARPOS (start) - 1
+             && FETCH_BYTE (BYTEPOS (start) - 1) == '\n')))
+    {
+      int Z_old, delta, Z_BYTE_old, delta_bytes;
+      struct glyph_row *r0;
+
+      /* Compute how many chars/bytes have been added to or removed
+        from the buffer.  */
+      Z_old = MATRIX_ROW_END_CHARPOS (row) + XFASTINT (w->window_end_pos);
+      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.  */
+      if (PT >= MATRIX_ROW_END_CHARPOS (row) + delta)
+       GIVE_UP (13);
+
+      /* If window start is unchanged, we can reuse the whole matrix
+        as is, after adjusting glyph positions.  No need to compute
+        the window end again, since its offset from Z hasn't changed.  */
+      r0 = MATRIX_FIRST_TEXT_ROW (current_matrix);
+      if (CHARPOS (start) == MATRIX_ROW_START_CHARPOS (r0) + delta
+         && BYTEPOS (start) == MATRIX_ROW_START_BYTEPOS (r0) + delta_bytes)
+       {
+         /* Adjust positions in the glyph matrix.  */
+         if (delta || delta_bytes)
+           {
+             struct glyph_row *r1
+               = MATRIX_BOTTOM_TEXT_ROW (current_matrix, w);
+             increment_matrix_positions (w->current_matrix,
+                                         MATRIX_ROW_VPOS (r0, current_matrix),
+                                         MATRIX_ROW_VPOS (r1, current_matrix),
+                                         delta, delta_bytes);
+           }
+      
+         /* Set the cursor.  */
+         row = row_containing_pos (w, PT, r0, NULL);
+         set_cursor_from_row (w, row, current_matrix, 0, 0, 0, 0);
+         return 1;
+       }
+    }
+
+  /* Handle the case that changes are all below what is displayed in
+     the window, and that PT is in the window.  This shortcut cannot
+     be taken if ZV is visible in the window, and text has been added
+     there that is visible in the window.  */
+  if (first_changed_charpos >= MATRIX_ROW_END_CHARPOS (row)
+      /* ZV is not visible in the window, or there are no
+        changes at ZV, actually.  */
+      && (current_matrix->zv > MATRIX_ROW_END_CHARPOS (row)
+         || first_changed_charpos == last_changed_charpos))
     {
-      struct glyph_row *r0 = MATRIX_FIRST_TEXT_ROW (current_matrix);
-      int delta = CHARPOS (start) - MATRIX_ROW_START_CHARPOS (r0);
+      struct glyph_row *r0;
+
+      /* 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.  */
+      if (PT >= MATRIX_ROW_END_CHARPOS (row))
+       GIVE_UP (14);
 
-      if (delta)
+      /* If window start is unchanged, we can reuse the whole matrix
+        as is, without changing glyph positions since no text has
+        been added/removed in front of the window end.  */
+      r0 = MATRIX_FIRST_TEXT_ROW (current_matrix);
+      if (TEXT_POS_EQUAL_P (start, r0->start.pos))
        {
-         struct glyph_row *r1 = MATRIX_BOTTOM_TEXT_ROW (current_matrix, w);
-         int delta_bytes = BYTEPOS (start) - MATRIX_ROW_START_BYTEPOS (r0);
+         /* We have to compute the window end anew since text
+            can have been added/removed after it.  */
+         w->window_end_pos
+           = make_number (Z - MATRIX_ROW_END_CHARPOS (row));
+         w->window_end_bytepos
+           = Z_BYTE - MATRIX_ROW_END_BYTEPOS (row);
 
-         increment_matrix_positions (w->current_matrix,
-                                     MATRIX_ROW_VPOS (r0, current_matrix),
-                                     MATRIX_ROW_VPOS (r1, current_matrix),
-                                     delta, delta_bytes);
+         /* Set the cursor.  */
+         row = row_containing_pos (w, PT, r0, NULL);
+         set_cursor_from_row (w, row, current_matrix, 0, 0, 0, 0);
+         return 2;
        }
-      
-#if 0  /* If changes are all in front of the window start, the
-         distance of the last displayed glyph from Z hasn't
-         changed.  */
-      w->window_end_pos
-       = make_number (Z - MATRIX_ROW_END_CHARPOS (row));
-      w->window_end_bytepos
-       = Z_BYTE - MATRIX_ROW_END_BYTEPOS (row);
-#endif
-
-      row = row_containing_pos (w, PT, r0, NULL);
-      if (row == NULL)
-       return 0;
-      
-      set_cursor_from_row (w, row, w->current_matrix, 0, 0, 0, 0);
-      return 1;
     }
 
-  /* Return quickly if changes are all below what is displayed in the
-     window, and if PT is in the window.  */
-  if (BEG_UNCHANGED > MATRIX_ROW_END_CHARPOS (row)
-      && PT < MATRIX_ROW_END_CHARPOS (row))
-    {
-      /* We have to update window end positions because the buffer's
-        size has changed.  */
-      w->window_end_pos
-       = make_number (Z - MATRIX_ROW_END_CHARPOS (row));
-      w->window_end_bytepos
-       = Z_BYTE - MATRIX_ROW_END_BYTEPOS (row);
+  /* Give up if window start is in the changed area.
+     
+     The condition used to read
 
-      row = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
-      row = row_containing_pos (w, PT, row, NULL);
-      set_cursor_from_row (w, row, w->current_matrix, 0, 0, 0, 0);
-      return 2;
-    }
+     (BEG_UNCHANGED + END_UNCHANGED != Z - BEG && ...)
 
+     but why that was tested escapes me at the moment.  */
+  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
      comparable.  */
-  row = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
+  row = MATRIX_FIRST_TEXT_ROW (current_matrix);
   if (!TEXT_POS_EQUAL_P (start, row->start.pos))
-    return 0;
+    GIVE_UP (16);
 
   /* Compute the position at which we have to start displaying new
      lines.  Some of the lines at the top of the window might be
@@ -11179,7 +11361,7 @@ try_window_id (w)
        --last_unchanged_at_beg_row;
 
       if (MATRIX_ROW_ENDS_IN_MIDDLE_OF_CHAR_P (last_unchanged_at_beg_row))
-       return 0;
+       GIVE_UP (17);
       
       init_to_row_end (&it, w, last_unchanged_at_beg_row);
       start_pos = it.current.pos;
@@ -11248,7 +11430,7 @@ try_window_id (w)
        }
     }
   else if (last_unchanged_at_beg_row == NULL)
-    return 0;
+    GIVE_UP (18);
 
 
 #if GLYPH_DEBUG
@@ -11267,7 +11449,7 @@ try_window_id (w)
   
 #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.  */
@@ -11393,7 +11575,9 @@ try_window_id (w)
          int first_unchanged_at_end_vpos
            = MATRIX_ROW_VPOS (first_unchanged_at_end_row, w->current_matrix);
          int from = XFASTINT (w->top) + first_unchanged_at_end_vpos;
-         int end = XFASTINT (w->top) + window_internal_height (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)
@@ -11544,6 +11728,8 @@ try_window_id (w)
       w->window_end_bytepos = Z_BYTE - MATRIX_ROW_END_BYTEPOS (row);
       w->window_end_vpos
        = make_number (MATRIX_ROW_VPOS (row, w->current_matrix));
+      xassert (w->window_end_bytepos >= 0);
+      IF_DEBUG (debug_method_add (w, "A"));
     }
   else if (last_text_row_at_end)
     {
@@ -11553,6 +11739,8 @@ try_window_id (w)
        = Z_BYTE - MATRIX_ROW_END_BYTEPOS (last_text_row_at_end);
       w->window_end_vpos
        = make_number (MATRIX_ROW_VPOS (last_text_row_at_end, desired_matrix));
+      xassert (w->window_end_bytepos >= 0);
+      IF_DEBUG (debug_method_add (w, "B"));
     }
   else if (last_text_row)
     {
@@ -11565,6 +11753,7 @@ try_window_id (w)
        = Z_BYTE - MATRIX_ROW_END_BYTEPOS (last_text_row);
       w->window_end_vpos
        = make_number (MATRIX_ROW_VPOS (last_text_row, desired_matrix));
+      xassert (w->window_end_bytepos >= 0);
     }
   else if (first_unchanged_at_end_row == NULL
           && last_text_row == NULL
@@ -11572,17 +11761,30 @@ try_window_id (w)
     {
       /* Displayed to end of window, but no line containing text was
         displayed.  Lines were deleted at the end of the window.  */
-      int vpos;
-      int header_line_p = WINDOW_WANTS_HEADER_LINE_P (w) ? 1 : 0;
-
-      for (vpos = XFASTINT (w->window_end_vpos); vpos > 0; --vpos)
-       if ((w->desired_matrix->rows[vpos + header_line_p].enabled_p
-            && w->desired_matrix->rows[vpos + header_line_p].displays_text_p)
-           || (!w->desired_matrix->rows[vpos + header_line_p].enabled_p
-               && w->current_matrix->rows[vpos + header_line_p].displays_text_p))
-         break;
+      int first_vpos = WINDOW_WANTS_HEADER_LINE_P (w) ? 1 : 0;
+      int vpos = XFASTINT (w->window_end_vpos);
+      struct glyph_row *current_row = current_matrix->rows + vpos;
+      struct glyph_row *desired_row = desired_matrix->rows + vpos;
+
+      for (row = NULL;
+          row == NULL && vpos >= first_vpos;
+          --vpos, --current_row, --desired_row)
+       {
+         if (desired_row->enabled_p)
+           {
+             if (desired_row->displays_text_p)
+               row = desired_row;
+           }
+         else if (current_row->displays_text_p)
+           row  = current_row;
+       }
 
-      w->window_end_vpos = make_number (vpos);
+      xassert (row != NULL);
+      w->window_end_vpos = make_number (vpos + 1);
+      w->window_end_pos = make_number (Z - MATRIX_ROW_END_CHARPOS (row));
+      w->window_end_bytepos = Z_BYTE - MATRIX_ROW_END_BYTEPOS (row);
+      xassert (w->window_end_bytepos >= 0);
+      IF_DEBUG (debug_method_add (w, "C"));
     }
   else
     abort ();
@@ -11603,6 +11805,8 @@ try_window_id (w)
   w->window_end_valid = Qnil;
   w->desired_matrix->no_scrolling_p = 1;
   return 3;
+
+#undef GIVE_UP
 }
 
 
@@ -11729,7 +11933,7 @@ dump_glyph_row (matrix, vpos, glyphs)
       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%1.1d %4d %4d %4d %4d %4d %4d %4d\n",
+%1.1d%1.1d%1.1d%1.1d%1.1d%1.1d%1.1d%1.1d  %4d %4d %4d %4d %4d %4d %4d\n",
               row - matrix->rows,
               MATRIX_ROW_START_CHARPOS (row),
               MATRIX_ROW_END_CHARPOS (row),
@@ -11755,8 +11959,9 @@ dump_glyph_row (matrix, vpos, glyphs)
               row->visible_height,
               row->ascent,
               row->phys_ascent);
-      fprintf (stderr, "%9d %5d\n", row->start.overlay_string_index,
-              row->end.overlay_string_index);
+      fprintf (stderr, "%9d %5d\t%5d\n", row->start.overlay_string_index,
+              row->end.overlay_string_index,
+              row->continuation_lines_width);
       fprintf (stderr, "%9d %5d\n",
               CHARPOS (row->start.string_pos),
               CHARPOS (row->end.string_pos));
@@ -11865,12 +12070,20 @@ GLYPH > 1 or omitted means dump glyphs in long form.")
 }
 
 
-DEFUN ("trace-redisplay-toggle", Ftrace_redisplay_toggle,
-       Strace_redisplay_toggle, 0, 0, "",
-  "Toggle tracing of redisplay.")
-     ()
+DEFUN ("trace-redisplay", Ftrace_redisplay, Strace_redisplay, 0, 1, "P",
+  "Toggle tracing of redisplay.\n\
+With ARG, turn tracing on if and only if ARG is positive.")
+  (arg)
+     Lisp_Object arg;
 {
-  trace_redisplay_p = !trace_redisplay_p;
+  if (NILP (arg))
+    trace_redisplay_p = !trace_redisplay_p;
+  else
+    {
+      arg = Fprefix_numeric_value (arg);
+      trace_redisplay_p = XINT (arg) > 0;
+    }
+  
   return Qnil;
 }
 
@@ -12078,6 +12291,10 @@ compute_line_metrics (it)
   else
     {
       row->pixel_width = row->used[TEXT_AREA];
+      if (row->continued_p)
+       row->pixel_width -= it->continuation_pixel_width;
+      else if (row->truncated_on_right_p)
+       row->pixel_width -= it->truncation_pixel_width;
       row->ascent = row->phys_ascent = 0;
       row->height = row->phys_height = row->visible_height = 1;
     }
@@ -14212,7 +14429,7 @@ syms_of_xdisp ()
   defsubr (&Sdump_glyph_matrix);
   defsubr (&Sdump_glyph_row);
   defsubr (&Sdump_tool_bar_row);
-  defsubr (&Strace_redisplay_toggle);
+  defsubr (&Strace_redisplay);
   defsubr (&Strace_to_stderr);
 #endif
 #ifdef HAVE_WINDOW_SYSTEM
@@ -14283,6 +14500,8 @@ syms_of_xdisp ()
   staticpro (&Qgrow_only);
   Qinhibit_menubar_update = intern ("inhibit-menubar-update");
   staticpro (&Qinhibit_menubar_update);
+  Qinhibit_eval_during_redisplay = intern ("inhibit-eval-during-redisplay");
+  staticpro (&Qinhibit_eval_during_redisplay);
 
   last_arrow_position = Qnil;
   last_arrow_string = Qnil;
@@ -14511,6 +14730,10 @@ Can be used to update submenus whose contents should vary.");
   DEFVAR_BOOL ("inhibit-menubar-update", &inhibit_menubar_update,
     "Non-nil means don't update menu bars.  Internal use only.");
   inhibit_menubar_update = 0;
+
+  DEFVAR_BOOL ("inhibit-eval-during-redisplay", &inhibit_eval_during_redisplay,
+    "Non-nil means don't eval Lisp during redisplay.");
+  inhibit_eval_during_redisplay = 0;
 }