Initial incomplete version of tty menus. tty_menu_activate not done yet.
[bpt/emacs.git] / src / xdisp.c
index d3a1dfc..52163db 100644 (file)
@@ -383,11 +383,21 @@ static Lisp_Object Qline_height;
 #define IT_OVERFLOW_NEWLINE_INTO_FRINGE(it) 0
 #endif /* HAVE_WINDOW_SYSTEM */
 
-/* Test if the display element loaded in IT is a space or tab
-   character.  This is used to determine word wrapping.  */
-
-#define IT_DISPLAYING_WHITESPACE(it)                           \
-  (it->what == IT_CHARACTER && (it->c == ' ' || it->c == '\t'))
+/* Test if the display element loaded in IT, or the underlying buffer
+   or string character, is a space or a TAB character.  This is used
+   to determine where word wrapping can occur.  */
+
+#define IT_DISPLAYING_WHITESPACE(it)                                   \
+  ((it->what == IT_CHARACTER && (it->c == ' ' || it->c == '\t'))       \
+   || ((STRINGP (it->string)                                           \
+       && (SREF (it->string, IT_STRING_BYTEPOS (*it)) == ' '           \
+           || SREF (it->string, IT_STRING_BYTEPOS (*it)) == '\t'))     \
+       || (it->s                                                       \
+          && (it->s[IT_BYTEPOS (*it)] == ' '                           \
+              || it->s[IT_BYTEPOS (*it)] == '\t'))                     \
+       || (IT_BYTEPOS (*it) < ZV_BYTE                                  \
+          && (*BYTE_POS_ADDR (IT_BYTEPOS (*it)) == ' '                 \
+              || *BYTE_POS_ADDR (IT_BYTEPOS (*it)) == '\t'))))         \
 
 /* Name of the face used to highlight trailing whitespace.  */
 
@@ -839,6 +849,7 @@ static int try_cursor_movement (Lisp_Object, struct text_pos, int *);
 static int trailing_whitespace_p (ptrdiff_t);
 static intmax_t message_log_check_duplicate (ptrdiff_t, ptrdiff_t);
 static void push_it (struct it *, struct text_pos *);
+static void iterate_out_of_display_property (struct it *);
 static void pop_it (struct it *);
 static void sync_frame_with_window_matrix_rows (struct window *);
 static void select_frame_for_redisplay (Lisp_Object);
@@ -1265,6 +1276,11 @@ pos_visible_p (struct window *w, ptrdiff_t charpos, int *x, int *y,
     }
 
   SET_TEXT_POS_FROM_MARKER (top, w->start);
+  /* Scrolling a minibuffer window via scroll bar when the echo area
+     shows long text sometimes resets the minibuffer contents behind
+     our backs.  */
+  if (CHARPOS (top) > ZV)
+    SET_TEXT_POS (top, BEGV, BEGV_BYTE);
 
   /* Compute exact mode line heights.  */
   if (WINDOW_WANTS_MODELINE_P (w))
@@ -1298,8 +1314,8 @@ pos_visible_p (struct window *w, ptrdiff_t charpos, int *x, int *y,
         glyph.  */
       int top_x = it.current_x;
       int top_y = it.current_y;
-      enum it_method it_method = it.method;
       /* Calling line_bottom_y may change it.method, it.position, etc.  */
+      enum it_method it_method = it.method;
       int bottom_y = (last_height = 0, line_bottom_y (&it));
       int window_top_y = WINDOW_HEADER_LINE_HEIGHT (w);
 
@@ -1307,6 +1323,31 @@ pos_visible_p (struct window *w, ptrdiff_t charpos, int *x, int *y,
        visible_p = bottom_y > window_top_y;
       else if (top_y < it.last_visible_y)
        visible_p = 1;
+      if (bottom_y >= it.last_visible_y
+         && it.bidi_p && it.bidi_it.scan_dir == -1
+         && IT_CHARPOS (it) < charpos)
+       {
+         /* When the last line of the window is scanned backwards
+            under bidi iteration, we could be duped into thinking
+            that we have passed CHARPOS, when in fact move_it_to
+            simply stopped short of CHARPOS because it reached
+            last_visible_y.  To see if that's what happened, we call
+            move_it_to again with a slightly larger vertical limit,
+            and see if it actually moved vertically; if it did, we
+            didn't really reach CHARPOS, which is beyond window end.  */
+         struct it save_it = it;
+         /* Why 10? because we don't know how many canonical lines
+            will the height of the next line(s) be.  So we guess.  */
+         int ten_more_lines =
+           10 * FRAME_LINE_HEIGHT (XFRAME (WINDOW_FRAME (w)));
+
+         move_it_to (&it, charpos, -1, bottom_y + ten_more_lines, -1,
+                     MOVE_TO_POS | MOVE_TO_Y);
+         if (it.current_y > top_y)
+           visible_p = 0;
+
+         it = save_it;
+       }
       if (visible_p)
        {
          if (it_method == GET_FROM_DISPLAY_VECTOR)
@@ -1370,6 +1411,7 @@ pos_visible_p (struct window *w, ptrdiff_t charpos, int *x, int *y,
                  Lisp_Object startpos, endpos;
                  EMACS_INT start, end;
                  struct it it3;
+                 int it3_moved;
 
                  /* Find the first and the last buffer positions
                     covered by the display string.  */
@@ -1426,6 +1468,15 @@ pos_visible_p (struct window *w, ptrdiff_t charpos, int *x, int *y,
                     begins.  */
                  start_display (&it3, w, top);
                  move_it_to (&it3, -1, 0, top_y, -1, MOVE_TO_X | MOVE_TO_Y);
+                 /* If it3_moved stays zero after the 'while' loop
+                    below, that means we already were at a newline
+                    before the loop (e.g., the display string begins
+                    with a newline), so we don't need to (and cannot)
+                    inspect the glyphs of it3.glyph_row, because
+                    PRODUCE_GLYPHS will not produce anything for a
+                    newline, and thus it3.glyph_row stays at its
+                    stale content it got at top of the window.  */
+                 it3_moved = 0;
                  /* Finally, advance the iterator until we hit the
                     first display element whose character position is
                     CHARPOS, or until the first newline from the
@@ -1437,6 +1488,7 @@ pos_visible_p (struct window *w, ptrdiff_t charpos, int *x, int *y,
                      if (IT_CHARPOS (it3) == charpos
                          || ITERATOR_AT_END_OF_LINE_P (&it3))
                        break;
+                     it3_moved = 1;
                      set_iterator_to_next (&it3, 0);
                    }
                  top_x = it3.current_x - it3.pixel_width;
@@ -1447,7 +1499,8 @@ pos_visible_p (struct window *w, ptrdiff_t charpos, int *x, int *y,
                     display string, move back over the glyphs
                     produced from the string, until we find the
                     rightmost glyph not from the string.  */
-                 if (IT_CHARPOS (it3) != charpos && EQ (it3.object, string))
+                 if (it3_moved
+                     && IT_CHARPOS (it3) != charpos && EQ (it3.object, string))
                    {
                      struct glyph *g = it3.glyph_row->glyphs[TEXT_AREA]
                                        + it3.glyph_row->used[TEXT_AREA];
@@ -2753,9 +2806,12 @@ init_iterator (struct it *it, struct window *w,
   if (charpos >= BUF_BEG (current_buffer))
     {
       it->end_charpos = ZV;
-      it->face_id = -1;
       IT_CHARPOS (*it) = charpos;
 
+      /* We will rely on `reseat' to set this up properly, via
+        handle_face_prop.  */
+      it->face_id = it->base_face_id;
+
       /* Compute byte position if not specified.  */
       if (bytepos < charpos)
        IT_BYTEPOS (*it) = CHAR_TO_BYTE (charpos);
@@ -3108,7 +3164,15 @@ handle_stop (struct it *it)
                 overlays even if the actual buffer text is replaced.  */
              if (!handle_overlay_change_p
                  || it->sp > 1
-                 || !get_overlay_strings_1 (it, 0, 0))
+                 /* Don't call get_overlay_strings_1 if we already
+                    have overlay strings loaded, because doing so
+                    will load them again and push the iterator state
+                    onto the stack one more time, which is not
+                    expected by the rest of the code that processes
+                    overlay strings.  */
+                 || (it->current.overlay_string_index < 0
+                     ? !get_overlay_strings_1 (it, 0, 0)
+                     : 0))
                {
                  if (it->ellipsis_p)
                    setup_for_ellipsis (it, 0);
@@ -3673,7 +3737,9 @@ handle_face_prop (struct it *it)
             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);
+         base_face_id = it->string_from_prefix_prop_p
+           ? DEFAULT_FACE_ID
+           : underlying_face_id (it);
        }
 
       new_face_id = face_at_string_position (it->w,
@@ -4662,10 +4728,22 @@ handle_single_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
          if (!FRAME_WINDOW_P (it->f))
            /* If we return here, POSITION has been advanced
               across the text with this property.  */
-           return 0;
+           {
+             /* Synchronize the bidi iterator with POSITION.  This is
+                needed because we are not going to push the iterator
+                on behalf of this display property, so there will be
+                no pop_it call to do this synchronization for us.  */
+             if (it->bidi_p)
+               {
+                 it->position = *position;
+                 iterate_out_of_display_property (it);
+                 *position = it->position;
+               }
+             return 1;
+           }
        }
       else if (!frame_window_p)
-       return 0;
+       return 1;
 
 #ifdef HAVE_WINDOW_SYSTEM
       value = XCAR (XCDR (spec));
@@ -4673,7 +4751,15 @@ handle_single_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
          || !(fringe_bitmap = lookup_fringe_bitmap (value)))
        /* If we return here, POSITION has been advanced
           across the text with this property.  */
-       return 0;
+       {
+         if (it && it->bidi_p)
+           {
+             it->position = *position;
+             iterate_out_of_display_property (it);
+             *position = it->position;
+           }
+         return 1;
+       }
 
       if (it)
        {
@@ -4977,7 +5063,7 @@ string_buffer_position_lim (Lisp_Object string,
   Lisp_Object limit, prop, pos;
   int found = 0;
 
-  pos = make_number (from);
+  pos = make_number (max (from, BEGV));
 
   if (!back_p) /* looking forward */
     {
@@ -5156,6 +5242,12 @@ next_overlay_string (struct it *it)
       it->current.overlay_string_index = -1;
       it->n_overlay_strings = 0;
       it->overlay_strings_charpos = -1;
+      /* If there's an empty display string on the stack, pop the
+        stack, to resync the bidi iterator with IT's position.  Such
+        empty strings are pushed onto the stack in
+        get_overlay_strings_1.  */
+      if (it->sp > 0 && STRINGP (it->string) && !SCHARS (it->string))
+       pop_it (it);
 
       /* If we're at the end of the buffer, record that we have
         processed the overlay strings there already, so that
@@ -5458,8 +5550,15 @@ get_overlay_strings_1 (struct it *it, ptrdiff_t charpos, int compute_stop_p)
       xassert (!compute_stop_p || it->sp == 0);
 
       /* When called from handle_stop, there might be an empty display
-         string loaded.  In that case, don't bother saving it.  */
-      if (!STRINGP (it->string) || SCHARS (it->string))
+         string loaded.  In that case, don't bother saving it.  But
+         don't use this optimization with the bidi iterator, since we
+         need the corresponding pop_it call to resync the bidi
+         iterator's position with IT's position, after we are done
+         with the overlay strings.  (The corresponding call to pop_it
+         in case of an empty display string is in
+         next_overlay_string.)  */
+      if (!(!it->bidi_p
+           && STRINGP (it->string) && !SCHARS (it->string)))
        push_it (it, NULL);
 
       /* Set up IT to deliver display elements from the first overlay
@@ -5568,6 +5667,7 @@ push_it (struct it *it, struct text_pos *position)
   p->font_height = it->font_height;
   p->voffset = it->voffset;
   p->string_from_display_prop_p = it->string_from_display_prop_p;
+  p->string_from_prefix_prop_p = it->string_from_prefix_prop_p;
   p->display_ellipsis_p = 0;
   p->line_wrap = it->line_wrap;
   p->bidi_p = it->bidi_p;
@@ -5583,7 +5683,7 @@ push_it (struct it *it, struct text_pos *position)
 static void
 iterate_out_of_display_property (struct it *it)
 {
-  int buffer_p = BUFFERP (it->object);
+  int buffer_p = !STRINGP (it->string);
   ptrdiff_t eob = (buffer_p ? ZV : it->end_charpos);
   ptrdiff_t bob = (buffer_p ? BEGV : 0);
 
@@ -5677,6 +5777,7 @@ pop_it (struct it *it)
   it->font_height = p->font_height;
   it->voffset = p->voffset;
   it->string_from_display_prop_p = p->string_from_display_prop_p;
+  it->string_from_prefix_prop_p = p->string_from_prefix_prop_p;
   it->line_wrap = p->line_wrap;
   it->bidi_p = p->bidi_p;
   it->paragraph_embedding = p->paragraph_embedding;
@@ -6107,6 +6208,8 @@ reseat_1 (struct it *it, struct text_pos pos, int set_stop_p)
   it->multibyte_p = !NILP (BVAR (current_buffer, enable_multibyte_characters));
   it->sp = 0;
   it->string_from_display_prop_p = 0;
+  it->string_from_prefix_prop_p = 0;
+
   it->from_disp_prop_p = 0;
   it->face_before_selective_p = 0;
   if (it->bidi_p)
@@ -6747,6 +6850,16 @@ get_next_display_element (struct it *it)
               && FACE_FROM_ID (it->f, face_id)->box == FACE_NO_BOX);
        }
     }
+  /* If we reached the end of the object we've been iterating (e.g., a
+     display string or an overlay string), and there's something on
+     IT->stack, proceed with what's on the stack.  It doesn't make
+     sense to return zero if there's unprocessed stuff on the stack,
+     because otherwise that stuff will never be displayed.  */
+  if (!success_p && it->sp > 0)
+    {
+      set_iterator_to_next (it, 0);
+      success_p = get_next_display_element (it);
+    }
 
   /* Value is 0 if end of buffer or string reached.  */
   return success_p;
@@ -6928,7 +7041,7 @@ set_iterator_to_next (struct it *it, int reseat_p)
          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->dpvec + it->current.dpvec_index >= it->dpend)
        {
          int recheck_faces = it->ellipsis_p;
 
@@ -6966,6 +7079,26 @@ set_iterator_to_next (struct it *it, int reseat_p)
     case GET_FROM_STRING:
       /* Current display element is a character from a Lisp string.  */
       xassert (it->s == NULL && STRINGP (it->string));
+      /* Don't advance past string end.  These conditions are true
+        when set_iterator_to_next is called at the end of
+        get_next_display_element, in which case the Lisp string is
+        already exhausted, and all we want is pop the iterator
+        stack.  */
+      if (it->current.overlay_string_index >= 0)
+       {
+         /* This is an overlay string, so there's no padding with
+            spaces, and the number of characters in the string is
+            where the string ends.  */
+         if (IT_STRING_CHARPOS (*it) >= SCHARS (it->string))
+           goto consider_string_end;
+       }
+      else
+       {
+         /* Not an overlay string.  There could be padding, so test
+            against it->end_charpos . */
+         if (IT_STRING_CHARPOS (*it) >= it->end_charpos)
+           goto consider_string_end;
+       }
       if (it->cmp_it.id >= 0)
        {
          int i;
@@ -7352,7 +7485,7 @@ next_element_from_string (struct it *it)
   if (it->current.overlay_string_index >= 0)
     {
       /* Get the next character from an overlay string.  In overlay
-        strings, There is no field width or padding with spaces to
+        strings, there is no field width or padding with spaces to
         do.  */
       if (IT_STRING_CHARPOS (*it) >= SCHARS (it->string))
        {
@@ -8572,8 +8705,18 @@ move_it_to (struct it *it, ptrdiff_t to_charpos, int to_x, int to_y, int to_vpos
                {
                  /* If TO_Y is in this line and TO_X was reached
                     above, we scanned too far.  We have to restore
-                    IT's settings to the ones before skipping.  */
+                    IT's settings to the ones before skipping.  But
+                    keep the more accurate values of max_ascent and
+                    max_descent we've found while skipping the rest
+                    of the line, for the sake of callers, such as
+                    pos_visible_p, that need to know the line
+                    height.  */
+                 int max_ascent = it->max_ascent;
+                 int max_descent = it->max_descent;
+
                  RESTORE_IT (it, &it_backup, backup_data);
+                 it->max_ascent = max_ascent;
+                 it->max_descent = max_descent;
                  reached = 6;
                }
              else
@@ -8950,7 +9093,6 @@ move_it_by_lines (struct it *it, ptrdiff_t dvpos)
     {
       /* DVPOS == 0 means move to the start of the screen line.  */
       move_it_vertically_backward (it, 0);
-      xassert (it->current_x == 0 && it->hpos == 0);
       /* Let next call to line_bottom_y calculate real line height */
       last_height = 0;
     }
@@ -8958,7 +9100,20 @@ move_it_by_lines (struct it *it, ptrdiff_t dvpos)
     {
       move_it_to (it, -1, -1, -1, it->vpos + dvpos, MOVE_TO_VPOS);
       if (!IT_POS_VALID_AFTER_MOVE_P (it))
-       move_it_to (it, IT_CHARPOS (*it) + 1, -1, -1, -1, MOVE_TO_POS);
+       {
+         /* Only move to the next buffer position if we ended up in a
+            string from display property, not in an overlay string
+            (before-string or after-string).  That is because the
+            latter don't conceal the underlying buffer position, so
+            we can ask to move the iterator to the exact position we
+            are interested in.  Note that, even if we are already at
+            IT_CHARPOS (*it), the call below is not a no-op, as it
+            will detect that we are at the end of the string, pop the
+            iterator, and compute it->current_x and it->hpos
+            correctly.  */
+         move_it_to (it, IT_CHARPOS (*it) + it->string_from_display_prop_p,
+                     -1, -1, -1, MOVE_TO_POS);
+       }
     }
   else
     {
@@ -11014,7 +11169,7 @@ update_menu_bar (struct frame *f, int save_match_data, int hooks_run)
          || update_mode_lines
          || ((BUF_SAVE_MODIFF (XBUFFER (w->buffer))
               < BUF_MODIFF (XBUFFER (w->buffer)))
-             != !NILP (w->last_had_star))
+             != w->last_had_star)
          || ((!NILP (Vtransient_mark_mode)
               && !NILP (BVAR (XBUFFER (w->buffer), mark_active)))
              != !NILP (w->region_showing)))
@@ -11066,11 +11221,11 @@ update_menu_bar (struct frame *f, int save_match_data, int hooks_run)
          else
            /* On a terminal screen, the menu bar is an ordinary screen
               line, and this makes it get updated.  */
-           w->update_mode_line = Qt;
+           w->update_mode_line = 1;
 #else /* ! (USE_X_TOOLKIT || HAVE_NTGUI || HAVE_NS || USE_GTK) */
          /* In the non-toolkit version, the menu bar is an ordinary screen
             line, and this makes it get updated.  */
-         w->update_mode_line = Qt;
+         w->update_mode_line = 1;
 #endif /* ! (USE_X_TOOLKIT || HAVE_NTGUI || HAVE_NS || USE_GTK) */
 
          unbind_to (count, Qnil);
@@ -11208,11 +11363,11 @@ update_tool_bar (struct frame *f, int 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)
+         || w->update_mode_line
          || update_mode_lines
          || ((BUF_SAVE_MODIFF (XBUFFER (w->buffer))
               < BUF_MODIFF (XBUFFER (w->buffer)))
-             != !NILP (w->last_had_star))
+             != w->last_had_star)
          || ((!NILP (Vtransient_mark_mode)
               && !NILP (BVAR (XBUFFER (w->buffer), mark_active)))
              != !NILP (w->region_showing)))
@@ -11263,7 +11418,7 @@ update_tool_bar (struct frame *f, int save_match_data)
               BLOCK_INPUT;
               f->tool_bar_items = new_tool_bar;
               f->n_tool_bar_items = new_n_tool_bar;
-              w->update_mode_line = Qt;
+              w->update_mode_line = 1;
               UNBLOCK_INPUT;
             }
 
@@ -12673,6 +12828,9 @@ redisplay_internal (void)
      frames.  Zero means, only selected_window is considered.  */
   int consider_all_windows_p;
 
+  /* Non-zero means redisplay has to redisplay the miniwindow */
+  int update_miniwindow_p = 0;
+
   TRACE ((stderr, "redisplay_internal %d\n", redisplaying_p));
 
   /* No redisplay if running in batch mode or frame is not yet fully
@@ -12809,9 +12967,9 @@ redisplay_internal (void)
     update_mode_lines++;
 
   /* Detect case that we need to write or remove a star in the mode line.  */
-  if ((SAVE_MODIFF < MODIFF) != !NILP (w->last_had_star))
+  if ((SAVE_MODIFF < MODIFF) != w->last_had_star)
     {
-      w->update_mode_line = Qt;
+      w->update_mode_line = 1;
       if (buffer_shared > 1)
        update_mode_lines++;
     }
@@ -12828,7 +12986,7 @@ redisplay_internal (void)
           && XFASTINT (w->last_modified) >= MODIFF
           && XFASTINT (w->last_overlay_modified) >= OVERLAY_MODIFF)
       && (XFASTINT (w->column_number_displayed) != current_column ()))
-    w->update_mode_line = Qt;
+    w->update_mode_line = 1;
 
   unbind_to (count1, Qnil);
 
@@ -12859,6 +13017,10 @@ redisplay_internal (void)
          && !MINI_WINDOW_P (XWINDOW (selected_window))))
     {
       int window_height_changed_p = echo_area_display (0);
+
+      if (message_cleared_p)
+       update_miniwindow_p = 1;
+
       must_finish = 1;
 
       /* If we don't display the current message, don't clear the
@@ -12895,7 +13057,7 @@ redisplay_internal (void)
 /* FIXME: this causes all frames to be updated, which seems unnecessary
    since only the current frame needs to be considered.  This function needs
    to be rewritten with two variables, consider_all_windows and
-   consider_all_frames. */
+   consider_all_frames.  */
       consider_all_windows_p = 1;
       ++windows_or_buffers_changed;
       ++update_mode_lines;
@@ -12927,7 +13089,7 @@ redisplay_internal (void)
   tlendpos = this_line_end_pos;
   if (!consider_all_windows_p
       && CHARPOS (tlbufpos) > 0
-      && NILP (w->update_mode_line)
+      && !w->update_mode_line
       && !current_buffer->clip_changed
       && !current_buffer->prevent_redisplay_optimizations_p
       && FRAME_VISIBLE_P (XFRAME (w->frame))
@@ -12935,8 +13097,8 @@ redisplay_internal (void)
       /* 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)
+      && !w->force_start
+      && !w->optional_new_start
       /* Point must be on the line that we have info recorded about.  */
       && PT >= CHARPOS (tlbufpos)
       && PT <= Z - CHARPOS (tlendpos)
@@ -13081,7 +13243,8 @@ redisplay_internal (void)
         then we can't just move the cursor.  */
       else if (! (!NILP (Vtransient_mark_mode)
                  && !NILP (BVAR (current_buffer, mark_active)))
-              && (EQ (selected_window, BVAR (current_buffer, last_selected_window))
+              && (EQ (selected_window,
+                      BVAR (current_buffer, last_selected_window))
                   || highlight_nonselected_windows)
               && NILP (w->region_showing)
               && NILP (Vshow_trailing_whitespace)
@@ -13234,7 +13397,7 @@ redisplay_internal (void)
     }
   else if (FRAME_VISIBLE_P (sf) && !FRAME_OBSCURED_P (sf))
     {
-      Lisp_Object mini_window;
+      Lisp_Object mini_window = FRAME_MINIBUF_WINDOW (sf);
       struct frame *mini_frame;
 
       displayed_buffer = XBUFFER (XWINDOW (selected_window)->buffer);
@@ -13243,6 +13406,10 @@ redisplay_internal (void)
       internal_condition_case_1 (redisplay_window_1, selected_window,
                                 list_of_error,
                                 redisplay_window_error);
+      if (update_miniwindow_p)
+       internal_condition_case_1 (redisplay_window_1, mini_window,
+                                  list_of_error,
+                                  redisplay_window_error);
 
       /* Compare desired and current matrices, perform output.  */
 
@@ -13466,7 +13633,7 @@ mark_window_display_accurate_1 (struct window *w, int accurate_p)
       w->last_overlay_modified
        = make_number (accurate_p ? BUF_OVERLAY_MODIFF (b) : 0);
       w->last_had_star
-       = BUF_MODIFF (b) > BUF_SAVE_MODIFF (b) ? Qt : Qnil;
+       = BUF_MODIFF (b) > BUF_SAVE_MODIFF (b);
 
       if (accurate_p)
        {
@@ -13495,7 +13662,7 @@ mark_window_display_accurate_1 (struct window *w, int accurate_p)
   if (accurate_p)
     {
       w->window_end_valid = w->buffer;
-      w->update_mode_line = Qnil;
+      w->update_mode_line = 0;
     }
 }
 
@@ -13663,6 +13830,13 @@ set_cursor_from_row (struct window *w, struct glyph_row *row,
      comes from a text property, not from an overlay.  */
   int string_from_text_prop = 0;
 
+  /* Don't even try doing anything if called for a mode-line or
+     header-line row, since the rest of the code isn't prepared to
+     deal with such calamities.  */
+  xassert (!row->mode_line_p);
+  if (row->mode_line_p)
+    return 0;
+
   /* Skip over glyphs not having an object at the start and the end of
      the row.  These are special glyphs like truncation marks on
      terminal frames.  */
@@ -13785,16 +13959,31 @@ set_cursor_from_row (struct window *w, struct glyph_row *row,
 
            chprop = Fget_char_property (make_number (glyph_pos), Qcursor,
                                         glyph->object);
+           if (!NILP (chprop))
+             {
+               /* If the string came from a `display' text property,
+                  look up the buffer position of that property and
+                  use that position to update bpos_max, as if we
+                  actually saw such a position in one of the row's
+                  glyphs.  This helps with supporting integer values
+                  of `cursor' property on the display string in
+                  situations where most or all of the row's buffer
+                  text is completely covered by display properties,
+                  so that no glyph with valid buffer positions is
+                  ever seen in the row.  */
+               ptrdiff_t prop_pos =
+                 string_buffer_position_lim (glyph->object, pos_before,
+                                             pos_after, 0);
+
+               if (prop_pos >= pos_before)
+                 bpos_max = prop_pos - 1;
+             }
            if (INTEGERP (chprop))
              {
                bpos_covered = bpos_max + XINT (chprop);
                /* If the `cursor' property covers buffer positions up
                   to and including point, we should display cursor on
-                  this glyph.  Note that overlays and text properties
-                  with string values stop bidi reordering, so every
-                  buffer position to the left of the string is always
-                  smaller than any position to the right of the
-                  string.  Therefore, if a `cursor' property on one
+                  this glyph.  Note that, if a `cursor' property on one
                   of the string's characters has an integer value, we
                   will break out of the loop below _before_ we get to
                   the position match above.  IOW, integer values of
@@ -13854,6 +14043,15 @@ set_cursor_from_row (struct window *w, struct glyph_row *row,
 
            chprop = Fget_char_property (make_number (glyph_pos), Qcursor,
                                         glyph->object);
+           if (!NILP (chprop))
+             {
+               ptrdiff_t prop_pos =
+                 string_buffer_position_lim (glyph->object, pos_before,
+                                             pos_after, 0);
+
+               if (prop_pos >= pos_before)
+                 bpos_max = prop_pos - 1;
+             }
            if (INTEGERP (chprop))
              {
                bpos_covered = bpos_max + XINT (chprop);
@@ -13991,15 +14189,18 @@ set_cursor_from_row (struct window *w, struct glyph_row *row,
                      || pos <= tem)
                    {
                      /* If the string from which this glyph came is
-                        found in the buffer at point, then we've
-                        found the glyph we've been looking for.  If
-                        it comes from an overlay (tem == 0), and it
-                        has the `cursor' property on one of its
+                        found in the buffer at point, or at position
+                        that is closer to point than pos_after, then
+                        we've found the glyph we've been looking for.
+                        If it comes from an overlay (tem == 0), and
+                        it has the `cursor' property on one of its
                         glyphs, record that glyph as a candidate for
                         displaying the cursor.  (As in the
                         unidirectional version, we will display the
                         cursor on the last candidate we find.)  */
-                     if (tem == 0 || tem == pt_old)
+                     if (tem == 0
+                         || tem == pt_old
+                         || (tem - pt_old > 0 && tem < pos_after))
                        {
                          /* The glyphs from this string could have
                             been reordered.  Find the one with the
@@ -14037,7 +14238,8 @@ set_cursor_from_row (struct window *w, struct glyph_row *row,
                                }
                            }
 
-                         if (tem == pt_old)
+                         if (tem == pt_old
+                             || (tem - pt_old > 0 && tem < pos_after))
                            goto compute_x;
                        }
                      if (tem)
@@ -14855,6 +15057,8 @@ try_cursor_movement (Lisp_Object window, struct text_pos startp, int *scroll_ste
          else if (rc != CURSOR_MOVEMENT_SUCCESS
                   && !NILP (BVAR (XBUFFER (w->buffer), bidi_display_reordering)))
            {
+             struct glyph_row *row1;
+
              /* If rows are bidi-reordered and point moved, back up
                 until we find a row that does not belong to a
                 continuation line.  This is because we must consider
@@ -14865,24 +15069,28 @@ try_cursor_movement (Lisp_Object window, struct text_pos startp, int *scroll_ste
              /* FIXME: Revisit this when glyph ``spilling'' in
                 continuation lines' rows is implemented for
                 bidi-reordered rows.  */
-             while (MATRIX_ROW_CONTINUATION_LINE_P (row))
+             for (row1 = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
+                  MATRIX_ROW_CONTINUATION_LINE_P (row);
+                  --row)
                {
                  /* If we hit the beginning of the displayed portion
                     without finding the first row of a continued
                     line, give up.  */
-                 if (row <= w->current_matrix->rows)
+                 if (row <= row1)
                    {
                      rc = CURSOR_MOVEMENT_MUST_SCROLL;
                      break;
                    }
                  xassert (row->enabled_p);
-                 --row;
                }
            }
          if (must_scroll)
            ;
          else if (rc != CURSOR_MOVEMENT_SUCCESS
              && MATRIX_ROW_PARTIALLY_VISIBLE_P (w, row)
+             /* Make sure this isn't a header line by any chance, since
+                then MATRIX_ROW_PARTIALLY_VISIBLE_P might yield non-zero.  */
+             && !row->mode_line_p
              && make_cursor_line_fully_visible_p)
            {
              if (PT == MATRIX_ROW_END_CHARPOS (row)
@@ -15083,7 +15291,7 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
   reconsider_clip_changes (w, buffer);
 
   /* Has the mode line to be updated?  */
-  update_mode_line = (!NILP (w->update_mode_line)
+  update_mode_line = (w->update_mode_line
                      || update_mode_lines
                      || buffer->clip_changed
                      || buffer->prevent_redisplay_optimizations_p);
@@ -15255,32 +15463,31 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
 
   /* If someone specified a new starting point but did not insist,
      check whether it can be used.  */
-  if (!NILP (w->optional_new_start)
+  if (w->optional_new_start
       && CHARPOS (startp) >= BEGV
       && CHARPOS (startp) <= ZV)
     {
-      w->optional_new_start = Qnil;
+      w->optional_new_start = 0;
       start_display (&it, w, startp);
       move_it_to (&it, PT, 0, it.last_visible_y, -1,
                  MOVE_TO_POS | MOVE_TO_X | MOVE_TO_Y);
       if (IT_CHARPOS (it) == PT)
-       w->force_start = Qt;
+       w->force_start = 1;
       /* IT may overshoot PT if text at PT is invisible.  */
       else if (IT_CHARPOS (it) > PT && CHARPOS (startp) <= PT)
-       w->force_start = Qt;
+       w->force_start = 1;
     }
 
  force_start:
 
   /* Handle case where place to start displaying has been specified,
      unless the specified location is outside the accessible range.  */
-  if (!NILP (w->force_start)
-      || w->frozen_window_start_p)
+  if (w->force_start || w->frozen_window_start_p)
     {
       /* We set this later on if we have to adjust point.  */
       int new_vpos = -1;
 
-      w->force_start = Qnil;
+      w->force_start = 0;
       w->vscroll = 0;
       w->window_end_valid = Qnil;
 
@@ -15299,7 +15506,7 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
          || ! NILP (Vwindow_scroll_functions))
        {
          update_mode_line = 1;
-         w->update_mode_line = Qt;
+         w->update_mode_line = 1;
          startp = run_window_scroll_functions (window, startp);
        }
 
@@ -15317,7 +15524,7 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
         the scroll margin (bug#148) -- cyd  */
       if (!try_window (window, startp, 0))
        {
-         w->force_start = Qt;
+         w->force_start = 1;
          clear_glyph_matrix (w->desired_matrix);
          goto need_larger_matrices;
        }
@@ -15396,7 +15603,7 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
     }
   /* If current starting point was originally the beginning of a line
      but no longer is, find a new starting point.  */
-  else if (!NILP (w->start_at_line_beg)
+  else if (w->start_at_line_beg
           && !(CHARPOS (startp) <= BEGV
                || FETCH_BYTE (BYTEPOS (startp) - 1) == '\n'))
     {
@@ -15443,7 +15650,7 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
         new window start, since that would change the position under
         the mouse, resulting in an unwanted mouse-movement rather
         than a simple mouse-click.  */
-      if (NILP (w->start_at_line_beg)
+      if (!w->start_at_line_beg
          && NILP (do_mouse_tracking)
          && CHARPOS (startp) > BEGV
          && CHARPOS (startp) > BEG + beg_unchanged
@@ -15463,7 +15670,7 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
             See bug#9324.  */
          && pos_visible_p (w, PT, &d1, &d2, &d3, &d4, &d5, &d6))
        {
-         w->force_start = Qt;
+         w->force_start = 1;
          SET_TEXT_POS_FROM_MARKER (startp, w->start);
          goto force_start;
        }
@@ -15524,7 +15731,7 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
   if (!update_mode_line)
     {
       update_mode_line = 1;
-      w->update_mode_line = Qt;
+      w->update_mode_line = 1;
     }
 
   /* Try to scroll by specified few lines.  */
@@ -15593,7 +15800,7 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
             accessible region of the buffer.  This can happen when we
             have just switched to a different buffer and/or changed
             its restriction.  In that case, startp is initialized to
-            the character position 1 (BEG) because we did not yet
+            the character position 1 (BEGV) because we did not yet
             have chance to display the buffer even once.  */
          && BEGV <= CHARPOS (startp) && CHARPOS (startp) <= ZV)
        {
@@ -15602,7 +15809,7 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
 
          SAVE_IT (it1, it, it1data);
          start_display (&it1, w, startp);
-         move_it_vertically (&it1, margin);
+         move_it_vertically (&it1, margin * FRAME_LINE_HEIGHT (f));
          margin_pos = IT_CHARPOS (it1);
          RESTORE_IT (&it, &it, it1data);
        }
@@ -15779,9 +15986,8 @@ redisplay_window (Lisp_Object window, int just_this_one_p)
  done:
 
   SET_TEXT_POS_FROM_MARKER (startp, w->start);
-  w->start_at_line_beg = ((CHARPOS (startp) == BEGV
-                          || FETCH_BYTE (BYTEPOS (startp) - 1) == '\n')
-                         ? Qt : Qnil);
+  w->start_at_line_beg = (CHARPOS (startp) == BEGV
+                           || FETCH_BYTE (BYTEPOS (startp) - 1) == '\n');
 
   /* Display the mode line, if we must.  */
   if ((update_mode_line
@@ -15998,7 +16204,7 @@ try_window (Lisp_Object window, struct text_pos pos, int flags)
   /* If bottom moved off end of frame, change mode line percentage.  */
   if (XFASTINT (w->window_end_pos) <= 0
       && Z != IT_CHARPOS (it))
-    w->update_mode_line = Qt;
+    w->update_mode_line = 1;
 
   /* Set window_end_pos to the offset of the last character displayed
      on the window from the end of current_buffer.  Set
@@ -16313,7 +16519,10 @@ try_window_reusing_current_matrix (struct window *w)
           ++first_row_to_display)
        {
          if (PT >= MATRIX_ROW_START_CHARPOS (first_row_to_display)
-             && PT < MATRIX_ROW_END_CHARPOS (first_row_to_display))
+             && (PT < MATRIX_ROW_END_CHARPOS (first_row_to_display)
+                 || (PT == MATRIX_ROW_END_CHARPOS (first_row_to_display)
+                     && first_row_to_display->ends_at_zv_p
+                     && pt_row == NULL)))
            pt_row = first_row_to_display;
        }
 
@@ -16405,7 +16614,9 @@ try_window_reusing_current_matrix (struct window *w)
       if (pt_row)
        {
          for (row = MATRIX_ROW (w->current_matrix, w->cursor.vpos);
-              row < bottom_row && PT >= MATRIX_ROW_END_CHARPOS (row);
+              row < bottom_row
+                && PT >= MATRIX_ROW_END_CHARPOS (row)
+                && !row->ends_at_zv_p;
               row++)
            {
              w->cursor.vpos++;
@@ -16546,7 +16757,15 @@ find_last_unchanged_at_beg_row (struct window *w)
             continued.  */
          && !(MATRIX_ROW_END_CHARPOS (row) == first_changed_pos
               && (row->continued_p
-                  || row->exact_window_width_line_p)))
+                  || row->exact_window_width_line_p))
+         /* If ROW->end is beyond ZV, then ROW->end is outdated and
+            needs to be recomputed, so don't consider this row as
+            unchanged.  This happens when the last line was
+            bidi-reordered and was killed immediately before this
+            redisplay cycle.  In that case, ROW->end stores the
+            buffer position of the first visual-order character of
+            the killed text, which is now beyond ZV.  */
+         && CHARPOS (row->end.pos) <= ZV)
        row_found = row;
 
       /* Stop if last visible row.  */
@@ -18152,8 +18371,10 @@ append_space_for_newline (struct it *it, int default_face_p)
          it->c = it->char_to_display = ' ';
          it->len = 1;
 
+         /* If the default face was remapped, be sure to use the
+            remapped face for the appended newline. */
          if (default_face_p)
-           it->face_id = DEFAULT_FACE_ID;
+           it->face_id = lookup_basic_face (it->f, DEFAULT_FACE_ID);
          else if (it->face_before_selective_p)
            it->face_id = it->saved_face_id;
          face = FACE_FROM_ID (it->f, it->face_id);
@@ -18189,7 +18410,7 @@ append_space_for_newline (struct it *it, int default_face_p)
 static void
 extend_face_to_end_of_line (struct it *it)
 {
-  struct face *face;
+  struct face *face, *default_face;
   struct frame *f = it->f;
 
   /* If line is already filled, do nothing.  Non window-system frames
@@ -18203,6 +18424,9 @@ extend_face_to_end_of_line (struct it *it)
         && !it->glyph_row->continued_p))
     return;
 
+  /* The default face, possibly remapped. */
+  default_face = FACE_FROM_ID (f, lookup_basic_face (f, DEFAULT_FACE_ID));
+
   /* 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.  */
@@ -18240,7 +18464,7 @@ extend_face_to_end_of_line (struct it *it)
       if (it->glyph_row->used[TEXT_AREA] == 0)
        {
          it->glyph_row->glyphs[TEXT_AREA][0] = space_glyph;
-         it->glyph_row->glyphs[TEXT_AREA][0].face_id = it->face_id;
+         it->glyph_row->glyphs[TEXT_AREA][0].face_id = face->id;
          it->glyph_row->used[TEXT_AREA] = 1;
        }
 #ifdef HAVE_WINDOW_SYSTEM
@@ -18276,7 +18500,7 @@ extend_face_to_end_of_line (struct it *it)
                 face, to avoid painting the rest of the window with
                 the region face, if the region ends at ZV.  */
              if (it->glyph_row->ends_at_zv_p)
-               it->face_id = DEFAULT_FACE_ID;
+               it->face_id = default_face->id;
              else
                it->face_id = face->id;
              append_stretch_glyph (it, make_number (0), stretch_width,
@@ -18309,7 +18533,7 @@ extend_face_to_end_of_line (struct it *it)
         avoid painting the rest of the window with the region face,
         if the region ends at ZV.  */
       if (it->glyph_row->ends_at_zv_p)
-       it->face_id = DEFAULT_FACE_ID;
+       it->face_id = default_face->id;
       else
        it->face_id = face->id;
 
@@ -18442,9 +18666,11 @@ cursor_row_p (struct glyph_row *row)
       /* Suppose the row ends on a string.
         Unless the row is continued, that means it ends on a newline
         in the string.  If it's anything other than a display string
-        (e.g. a before-string from an overlay), we don't want the
+        (e.g., a before-string from an overlay), we don't want the
         cursor there.  (This heuristic seems to give the optimal
-        behavior for the various types of multi-line strings.)  */
+        behavior for the various types of multi-line strings.)
+        One exception: if the string has `cursor' property on one of
+        its characters, we _do_ want the cursor there.  */
       if (CHARPOS (row->end.string_pos) >= 0)
        {
          if (row->continued_p)
@@ -18466,6 +18692,25 @@ cursor_row_p (struct glyph_row *row)
                    result =
                      (!NILP (prop)
                       && display_prop_string_p (prop, glyph->object));
+                   /* If there's a `cursor' property on one of the
+                      string's characters, this row is a cursor row,
+                      even though this is not a display string.  */
+                   if (!result)
+                     {
+                       Lisp_Object s = glyph->object;
+
+                       for ( ; glyph >= beg && EQ (glyph->object, s); --glyph)
+                         {
+                           ptrdiff_t gpos = glyph->charpos;
+
+                           if (!NILP (Fget_char_property (make_number (gpos),
+                                                          Qcursor, s)))
+                             {
+                               result = 1;
+                               break;
+                             }
+                         }
+                     }
                    break;
                  }
            }
@@ -18504,7 +18749,7 @@ cursor_row_p (struct glyph_row *row)
    `line-prefix' and `wrap-prefix' properties.  */
 
 static int
-push_display_prop (struct it *it, Lisp_Object prop)
+push_prefix_prop (struct it *it, Lisp_Object prop)
 {
   struct text_pos pos =
     STRINGP (it->string) ? it->current.string_pos : it->current.pos;
@@ -18528,6 +18773,7 @@ push_display_prop (struct it *it, Lisp_Object prop)
        }
 
       it->string = prop;
+      it->string_from_prefix_prop_p = 1;
       it->multibyte_p = STRING_MULTIBYTE (it->string);
       it->current.overlay_string_index = -1;
       IT_STRING_CHARPOS (*it) = IT_STRING_BYTEPOS (*it) = 0;
@@ -18614,7 +18860,7 @@ handle_line_prefix (struct it *it)
       if (NILP (prefix))
        prefix = Vline_prefix;
     }
-  if (! NILP (prefix) && push_display_prop (it, prefix))
+  if (! NILP (prefix) && push_prefix_prop (it, prefix))
     {
       /* If the prefix is wider than the window, and we try to wrap
         it, it would acquire its own wrap prefix, and so on till the
@@ -18951,8 +19197,13 @@ display_line (struct it *it)
          /* A row that displays right-to-left text must always have
             its last face extended all the way to the end of line,
             even if this row ends in ZV, because we still write to
-            the screen left to right.  */
-         if (row->reversed_p)
+            the screen left to right.  We also need to extend the
+            last face if the default face is remapped to some
+            different face, otherwise the functions that clear
+            portions of the screen will clear with the default face's
+            background color.  */
+         if (row->reversed_p
+             || lookup_basic_face (it->f, DEFAULT_FACE_ID) != DEFAULT_FACE_ID)
            extend_face_to_end_of_line (it);
          break;
        }
@@ -19710,7 +19961,78 @@ display_menu_bar (struct window *w)
   compute_line_metrics (&it);
 }
 
+#ifdef HAVE_MENUS
+/* Display one menu item on a TTY, by overwriting the glyphs in the
+   desired glyph matrix with glyphs produced from the menu item text.
+   Called from term.c to display TTY drop-down menus one item at a
+   time.
+
+   ITEM_TEXT is the menu item text as a C string.
+
+   FACE_ID is the face ID to be used for this menu item.  FACE_ID
+   could specify one of 3 faces: a face for an enabled item, a face
+   for a disabled item, or a face for a selected item.
+
+   X and Y are coordinates of the first glyph in the desired matrix to
+   be overwritten by the menu item.  Since this is a TTY, Y is the
+   glyph row and X is the glyph number in the row, where to start
+   displaying the item.
+
+   SUBMENU non-zero means this menu item drops down a submenu, which
+   should be indicated by displaying a proper visual cue after the
+   item text.  */
 
+void
+display_tty_menu_item (const char *item_text, int face_id, int x, int y,
+                      int submenu)
+{
+  struct it it;
+  struct frame *f = SELECTED_FRAME ();
+  int saved_used, saved_truncated;
+  struct glyph_row *row;
+
+  xassert (FRAME_TERMCAP_P (f));
+
+  init_iterator (&it, w, -1, -1, f->desired_matrix->rows + y, MENU_FACE_ID);
+  it.first_visible_x = 0;
+  it.last_visible_x = FRAME_COLS (f);
+  row = it.glyph_row;
+  row->full_width_p = 1;
+
+  /* Arrange for the menu item glyphs to start at X and have the
+     desired face.  */
+  it.current_x = it.hpos = x;
+  saved_used = row->used[TEXT_AREA];
+  saved_truncated = row->truncated_on_right_p;
+  row->used[TEXT_AREA] = x - row->used[LEFT_MARGIN_AREA];
+  it.face_id = face_id;
+
+  /* FIXME: This should be controlled by a user option.  See the
+     comments in redisplay_tool_bar and display_mode_line about this.
+     Also, if paragraph_embedding could ever be R2L, changes will be
+     needed to avoid shifting to the right the row characters in
+     term.c:append_glyph.  */
+  it.paragraph_embedding = L2R;
+
+  if (submenu)
+    {
+      /* Indicate with ">" that there's a submenu.  */
+      display_string (item_text, Qnil, Qnil, 0, 0, &it,
+                     strlen (item_text), 0, FRAME_COLS (f) - 2, -1);
+      display_string (">", Qnil, Qnil, 0, 0, &it, 1, 0, 0, -1);
+    }
+  else
+    {
+      /* Display the menu item, pad with one space.  */
+      display_string (item_text, Qnil, Qnil, 0, 0, &it,
+                     strlen (item_text) + 1, 0, 0, -1);
+    }
+
+  row->used[TEXT_AREA] = saved_used;
+  row->truncated_on_right_p = saved_truncated;
+  row->hash - row_hash (row);
+}
+#endif /* HAVE_MENUS */
 \f
 /***********************************************************************
                              Mode Line
@@ -22745,7 +23067,7 @@ compute_overhangs_and_x (struct glyph_string *s, int x, int backward_p)
     ptrdiff_t cmp_id = (row)->glyphs[area][START].u.cmp.id;                \
     struct composition *cmp = composition_table[cmp_id];                   \
     XChar2b *char2b;                                                       \
-    struct glyph_string *first_s IF_LINT (= NULL);                         \
+    struct glyph_string *first_s = NULL;                                   \
     int n;                                                                 \
                                                                            \
     char2b = (XChar2b *) alloca ((sizeof *char2b) * cmp->glyph_len);       \
@@ -23971,7 +24293,7 @@ produce_glyphless_glyph (struct it *it, int for_no_font, Lisp_Object acronym)
          sprintf (buf, "%0*X", it->c < 0x10000 ? 4 : 6, it->c);
          str = buf;
        }
-      for (len = 0; str[len] && ASCII_BYTE_P (str[len]); len++)
+      for (len = 0; str[len] && ASCII_BYTE_P (str[len]) && len < 6; len++)
        code[len] = font->driver->encode_char (font, str[len]);
       upper_len = (len + 1) / 2;
       font->driver->text_extents (font, code, upper_len,
@@ -24407,7 +24729,7 @@ x_produce_glyphs (struct it *it)
          /* Initialize the bounding box.  */
          if (pcm)
            {
-             width = pcm->width;
+             width = cmp->glyph_len > 0 ? pcm->width : 0;
              ascent = pcm->ascent;
              descent = pcm->descent;
              lbearing = pcm->lbearing;
@@ -24415,7 +24737,7 @@ x_produce_glyphs (struct it *it)
            }
          else
            {
-             width = font->space_width;
+             width = cmp->glyph_len > 0 ? font->space_width : 0;
              ascent = FONT_BASE (font);
              descent = FONT_DESCENT (font);
              lbearing = 0;
@@ -24633,7 +24955,7 @@ x_produce_glyphs (struct it *it)
       if (it->descent < 0)
        it->descent = 0;
 
-      if (it->glyph_row)
+      if (it->glyph_row && cmp->glyph_len > 0)
        append_composite_glyph (it);
     }
   else if (it->what == IT_COMPOSITION)
@@ -25589,7 +25911,7 @@ draw_row_with_mouse_face (struct window *w, int start_x, struct glyph_row *row,
       return;
     }
 #endif
-#if defined (HAVE_GPM) || defined (MSDOS)
+#if defined (HAVE_GPM) || defined (MSDOS) || defined (WINDOWSNT)
   tty_draw_row_with_mouse_face (w, row, start_hpos, end_hpos, draw);
 #endif
 }
@@ -25822,12 +26144,14 @@ cursor_in_mouse_face_p (struct window *w)
 \f
 /* Find the glyph rows START_ROW and END_ROW of window W that display
    characters between buffer positions START_CHARPOS and END_CHARPOS
-   (excluding END_CHARPOS).  This is similar to row_containing_pos,
-   but is more accurate when bidi reordering makes buffer positions
-   change non-linearly with glyph rows.  */
+   (excluding END_CHARPOS).  DISP_STRING is a display string that
+   covers these buffer positions.  This is similar to
+   row_containing_pos, but is more accurate when bidi reordering makes
+   buffer positions change non-linearly with glyph rows.  */
 static void
 rows_from_pos_range (struct window *w,
                     ptrdiff_t start_charpos, ptrdiff_t end_charpos,
+                    Lisp_Object disp_string,
                     struct glyph_row **start, struct glyph_row **end)
 {
   struct glyph_row *first = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
@@ -25879,8 +26203,11 @@ rows_from_pos_range (struct window *w,
 
          while (g < e)
            {
-             if ((BUFFERP (g->object) || INTEGERP (g->object))
-                 && start_charpos <= g->charpos && g->charpos < end_charpos)
+             if (((BUFFERP (g->object) || INTEGERP (g->object))
+                  && start_charpos <= g->charpos && g->charpos < end_charpos)
+                 /* A glyph that comes from DISP_STRING is by
+                    definition to be highlighted.  */
+                 || EQ (g->object, disp_string))
                *start = row;
              g++;
            }
@@ -25899,14 +26226,15 @@ rows_from_pos_range (struct window *w,
   for ( ; row->enabled_p && MATRIX_ROW_BOTTOM_Y (row) <= last_y; row++)
     {
       struct glyph_row *next = row + 1;
+      ptrdiff_t next_start = MATRIX_ROW_START_CHARPOS (next);
 
       if (!next->enabled_p
          || next >= MATRIX_BOTTOM_TEXT_ROW (w->current_matrix, w)
          /* The first row >= START whose range of displayed characters
             does NOT intersect the range [START_CHARPOS..END_CHARPOS]
             is the row END + 1.  */
-         || (start_charpos < MATRIX_ROW_START_CHARPOS (next)
-             && end_charpos < MATRIX_ROW_START_CHARPOS (next))
+         || (start_charpos < next_start
+             && end_charpos < next_start)
          || ((start_charpos > MATRIX_ROW_END_CHARPOS (next)
               || (start_charpos == MATRIX_ROW_END_CHARPOS (next)
                   && !next->ends_at_zv_p
@@ -25925,12 +26253,29 @@ rows_from_pos_range (struct window *w,
             but none of the characters it displays are in the range, it is
             also END + 1. */
          struct glyph *g = next->glyphs[TEXT_AREA];
+         struct glyph *s = g;
          struct glyph *e = g + next->used[TEXT_AREA];
 
          while (g < e)
            {
-             if ((BUFFERP (g->object) || INTEGERP (g->object))
-                 && start_charpos <= g->charpos && g->charpos < end_charpos)
+             if (((BUFFERP (g->object) || INTEGERP (g->object))
+                  && ((start_charpos <= g->charpos && g->charpos < end_charpos)
+                      /* If the buffer position of the first glyph in
+                         the row is equal to END_CHARPOS, it means
+                         the last character to be highlighted is the
+                         newline of ROW, and we must consider NEXT as
+                         END, not END+1.  */
+                      || (((!next->reversed_p && g == s)
+                           || (next->reversed_p && g == e - 1))
+                          && (g->charpos == end_charpos
+                              /* Special case for when NEXT is an
+                                 empty line at ZV.  */
+                              || (g->charpos == -1
+                                  && !row->ends_at_zv_p
+                                  && next_start == end_charpos)))))
+                 /* A glyph that comes from DISP_STRING is by
+                    definition to be highlighted.  */
+                 || EQ (g->object, disp_string))
                break;
              g++;
            }
@@ -25939,6 +26284,13 @@ rows_from_pos_range (struct window *w,
              *end = row;
              break;
            }
+         /* The first row that ends at ZV must be the last to be
+            highlighted.  */
+         else if (next->ends_at_zv_p)
+           {
+             *end = next;
+             break;
+           }
        }
     }
 }
@@ -25974,7 +26326,7 @@ mouse_face_from_buffer_pos (Lisp_Object window,
   xassert (NILP (after_string) || STRINGP (after_string));
 
   /* Find the rows corresponding to START_CHARPOS and END_CHARPOS.  */
-  rows_from_pos_range (w, start_charpos, end_charpos, &r1, &r2);
+  rows_from_pos_range (w, start_charpos, end_charpos, disp_string, &r1, &r2);
   if (r1 == NULL)
     r1 = MATRIX_ROW (w->current_matrix, XFASTINT (w->window_end_vpos));
   /* If the before-string or display-string contains newlines,
@@ -26252,6 +26604,19 @@ mouse_face_from_buffer_pos (Lisp_Object window,
            }
          x += end->pixel_width;
        }
+      /* If we exited the above loop because we arrived at the last
+        glyph of the row, and its buffer position is still not in
+        range, it means the last character in range is the preceding
+        newline.  Bump the end column and x values to get past the
+        last glyph.  */
+      if (end == glyph
+         && BUFFERP (end->object)
+         && (end->charpos < start_charpos
+             || end->charpos >= end_charpos))
+       {
+         x += end->pixel_width;
+         ++end;
+       }
       hlinfo->mouse_face_end_x = x;
       hlinfo->mouse_face_end_col = end - r2->glyphs[TEXT_AREA];
     }
@@ -28149,14 +28514,14 @@ syms_of_xdisp (void)
 
 #ifdef HAVE_WINDOW_SYSTEM
   DEFVAR_BOOL ("x-stretch-cursor", x_stretch_cursor_p,
-    doc: /* *Non-nil means draw block cursor as wide as the glyph under it.
+    doc: /* Non-nil means draw block cursor as wide as the glyph under it.
 For example, if a block cursor is over a tab, it will be drawn as
 wide as that tab on the display.  */);
   x_stretch_cursor_p = 0;
 #endif
 
   DEFVAR_LISP ("show-trailing-whitespace", Vshow_trailing_whitespace,
-    doc: /* *Non-nil means highlight trailing whitespace.
+    doc: /* Non-nil means highlight trailing whitespace.
 The face used for trailing whitespace is `trailing-whitespace'.  */);
   Vshow_trailing_whitespace = Qnil;
 
@@ -28176,7 +28541,7 @@ A value of nil means no special handling of these characters.  */);
   Vnobreak_char_display = Qt;
 
   DEFVAR_LISP ("void-text-area-pointer", Vvoid_text_area_pointer,
-    doc: /* *The pointer shape to show in void text areas.
+    doc: /* The pointer shape to show in void text areas.
 A value of nil means to show the text pointer.  Other options are `arrow',
 `text', `hand', `vdrag', `hdrag', `modeline', and `hourglass'.  */);
   Vvoid_text_area_pointer = Qarrow;
@@ -28209,14 +28574,14 @@ where to display overlay arrows.  */);
     = Fcons (intern_c_string ("overlay-arrow-position"), Qnil);
 
   DEFVAR_INT ("scroll-step", emacs_scroll_step,
-    doc: /* *The number of lines to try scrolling a window by when point moves out.
+    doc: /* The number of lines to try scrolling a window by when point moves out.
 If that fails to bring point back on frame, point is centered instead.
 If this is zero, point is always centered after it moves off frame.
 If you want scrolling to always be a line at a time, you should set
 `scroll-conservatively' to a large value rather than set this to 1.  */);
 
   DEFVAR_INT ("scroll-conservatively", scroll_conservatively,
-    doc: /* *Scroll up to this many lines, to bring point back on screen.
+    doc: /* Scroll up to this many lines, to bring point back on screen.
 If point moves off-screen, redisplay will scroll by up to
 `scroll-conservatively' lines in order to bring point just barely
 onto the screen again.  If that cannot be done, then redisplay
@@ -28230,7 +28595,7 @@ A value of zero means always recenter point if it moves off screen.  */);
   scroll_conservatively = 0;
 
   DEFVAR_INT ("scroll-margin", scroll_margin,
-    doc: /* *Number of lines of margin at the top and bottom of a window.
+    doc: /* Number of lines of margin at the top and bottom of a window.
 Recenter the window whenever point gets within this many lines
 of the top or bottom of the window.  */);
   scroll_margin = 0;
@@ -28266,20 +28631,20 @@ Any other value means to use the appropriate face, `mode-line',
   mode_line_inverse_video = 1;
 
   DEFVAR_LISP ("line-number-display-limit", Vline_number_display_limit,
-    doc: /* *Maximum buffer size for which line number should be displayed.
+    doc: /* Maximum buffer size for which line number should be displayed.
 If the buffer is bigger than this, the line number does not appear
 in the mode line.  A value of nil means no limit.  */);
   Vline_number_display_limit = Qnil;
 
   DEFVAR_INT ("line-number-display-limit-width",
              line_number_display_limit_width,
-    doc: /* *Maximum line width (in characters) for line number display.
+    doc: /* Maximum line width (in characters) for line number display.
 If the average length of the lines near point is bigger than this, then the
 line number may be omitted from the mode line.  */);
   line_number_display_limit_width = 200;
 
   DEFVAR_BOOL ("highlight-nonselected-windows", highlight_nonselected_windows,
-    doc: /* *Non-nil means highlight region even in nonselected windows.  */);
+    doc: /* Non-nil means highlight region even in nonselected windows.  */);
   highlight_nonselected_windows = 0;
 
   DEFVAR_BOOL ("multiple-frames", multiple_frames,
@@ -28351,7 +28716,7 @@ See `set-window-redisplay-end-trigger'.  */);
   Vredisplay_end_trigger_functions = Qnil;
 
   DEFVAR_LISP ("mouse-autoselect-window", Vmouse_autoselect_window,
-     doc: /* *Non-nil means autoselect window with mouse pointer.
+     doc: /* Non-nil means autoselect window with mouse pointer.
 If nil, do not autoselect windows.
 A positive number means delay autoselection by that many seconds: a
 window is autoselected only after the mouse has remained in that
@@ -28371,7 +28736,7 @@ When customizing this variable make sure that the actual value of
   Vmouse_autoselect_window = Qnil;
 
   DEFVAR_LISP ("auto-resize-tool-bars", Vauto_resize_tool_bars,
-    doc: /* *Non-nil means automatically resize tool-bars.
+    doc: /* Non-nil means automatically resize tool-bars.
 This dynamically changes the tool-bar's height to the minimum height
 that is needed to make all tool-bar items visible.
 If value is `grow-only', the tool-bar's height is only increased
@@ -28379,15 +28744,15 @@ automatically; to decrease the tool-bar height, use \\[recenter].  */);
   Vauto_resize_tool_bars = Qt;
 
   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.  */);
+    doc: /* Non-nil means raise tool-bar buttons when the mouse moves over them.  */);
   auto_raise_tool_bar_buttons_p = 1;
 
   DEFVAR_BOOL ("make-cursor-line-fully-visible", make_cursor_line_fully_visible_p,
-    doc: /* *Non-nil means to scroll (recenter) cursor line if it is not fully visible.  */);
+    doc: /* Non-nil means to scroll (recenter) cursor line if it is not fully visible.  */);
   make_cursor_line_fully_visible_p = 1;
 
   DEFVAR_LISP ("tool-bar-border", Vtool_bar_border,
-    doc: /* *Border below tool-bar in pixels.
+    doc: /* Border below tool-bar in pixels.
 If an integer, use it as the height of the border.
 If it is one of `internal-border-width' or `border-width', use the
 value of the corresponding frame parameter.
@@ -28395,7 +28760,7 @@ Otherwise, no border is added below the tool-bar.  */);
   Vtool_bar_border = Qinternal_border_width;
 
   DEFVAR_LISP ("tool-bar-button-margin", Vtool_bar_button_margin,
-    doc: /* *Margin around tool-bar buttons in pixels.
+    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
 HORZ specifying the horizontal margin, and VERT specifying the
@@ -28403,7 +28768,7 @@ 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 ("tool-bar-style", Vtool_bar_style,
@@ -28418,7 +28783,7 @@ It can be one of
   Vtool_bar_style = Qnil;
 
   DEFVAR_INT ("tool-bar-max-label-size", tool_bar_max_label_size,
-    doc: /* *Maximum number of characters a label can have to be shown.
+    doc: /* Maximum number of characters a label can have to be shown.
 The tool bar style must also show labels for this to have any effect, see
 `tool-bar-style'.  */);
   tool_bar_max_label_size = DEFAULT_TOOL_BAR_LABEL_SIZE;
@@ -28433,7 +28798,7 @@ fontified regions the property `fontified'.  */);
 
   DEFVAR_BOOL ("unibyte-display-via-language-environment",
                unibyte_display_via_language_environment,
-    doc: /* *Non-nil means display unibyte text according to language environment.
+    doc: /* Non-nil means display unibyte text according to language environment.
 Specifically, this means that raw bytes in the range 160-255 decimal
 are displayed by converting them to the equivalent multibyte characters
 according to the current language environment.  As a result, they are
@@ -28444,7 +28809,7 @@ but does not change the fact they are interpreted as raw bytes.  */);
   unibyte_display_via_language_environment = 0;
 
   DEFVAR_LISP ("max-mini-window-height", Vmax_mini_window_height,
-    doc: /* *Maximum height for resizing mini-windows (the minibuffer and the echo area).
+    doc: /* Maximum height for resizing mini-windows (the minibuffer and the echo area).
 If a float, it specifies a fraction of the mini-window frame's height.
 If an integer, it specifies a number of lines.  */);
   Vmax_mini_window_height = make_float (0.25);
@@ -28478,12 +28843,12 @@ point visible.  */);
   DEFSYM (Qauto_hscroll_mode, "auto-hscroll-mode");
 
   DEFVAR_INT ("hscroll-margin", hscroll_margin,
-    doc: /* *How many columns away from the window edge point is allowed to get
+    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.
+    doc: /* How many columns to scroll the window when point gets too close to the edge.
 When point is less than `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
@@ -28570,7 +28935,7 @@ To add a prefix to continuation lines, use `wrap-prefix'.  */);
 #endif /* GLYPH_DEBUG */
 
   DEFVAR_INT ("overline-margin", overline_margin,
-              doc: /* *Space between overline and text, in pixels.
+              doc: /* Space between overline and text, in pixels.
 The default value is 2: the height of the overline (1 pixel) plus 1 pixel
 margin to the character height.  */);
   overline_margin = 2;
@@ -28591,7 +28956,7 @@ cursor shapes.  */);
   display_hourglass_p = 1;
 
   DEFVAR_LISP ("hourglass-delay", Vhourglass_delay,
-              doc: /* *Seconds to wait before displaying an hourglass pointer when Emacs is busy.  */);
+              doc: /* Seconds to wait before displaying an hourglass pointer when Emacs is busy.  */);
   Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
 
   hourglass_atimer = NULL;
@@ -28687,14 +29052,6 @@ init_xdisp (void)
 
 /* Platform-independent portion of hourglass implementation. */
 
-/* Return non-zero if hourglass timer has been started or hourglass is
-   shown.  */
-int
-hourglass_started (void)
-{
-  return hourglass_shown_p || hourglass_atimer != NULL;
-}
-
 /* Cancel a currently active hourglass timer, and start a new one.  */
 void
 start_hourglass (void)