* lisp/mail/footnote.el (footnote-align-to-fn-text): New config var
[emacs.git] / src / dispnew.c
blob7fea867f660a255b86f5f1444e1faab9c5e316ba
1 /* Updating of data structures for redisplay.
3 Copyright (C) 1985-1988, 1993-1995, 1997-2017 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #include "sysstdio.h"
24 #include <stdlib.h>
25 #include <unistd.h>
27 #include "lisp.h"
28 #include "ptr-bounds.h"
29 #include "termchar.h"
30 /* cm.h must come after dispextern.h on Windows. */
31 #include "dispextern.h"
32 #include "cm.h"
33 #include "buffer.h"
34 #include "keyboard.h"
35 #include "frame.h"
36 #include "termhooks.h"
37 #include "window.h"
38 #include "commands.h"
39 #include "disptab.h"
40 #include "blockinput.h"
41 #include "syssignal.h"
42 #include "systime.h"
43 #include "tparam.h"
44 #include "xwidget.h"
46 #ifdef HAVE_WINDOW_SYSTEM
47 #include TERM_HEADER
48 #endif /* HAVE_WINDOW_SYSTEM */
50 #include <errno.h>
52 #include <fpending.h>
54 #ifdef WINDOWSNT
55 #include "w32.h"
56 #endif
58 /* Structure to pass dimensions around. Used for character bounding
59 boxes, glyph matrix dimensions and alike. */
61 struct dim
63 int width;
64 int height;
68 /* Function prototypes. */
70 static void update_frame_line (struct frame *, int, bool);
71 static int required_matrix_height (struct window *);
72 static int required_matrix_width (struct window *);
73 static void increment_row_positions (struct glyph_row *, ptrdiff_t, ptrdiff_t);
74 static void build_frame_matrix_from_window_tree (struct glyph_matrix *,
75 struct window *);
76 static void build_frame_matrix_from_leaf_window (struct glyph_matrix *,
77 struct window *);
78 static void adjust_decode_mode_spec_buffer (struct frame *);
79 static void fill_up_glyph_row_with_spaces (struct glyph_row *);
80 static void clear_window_matrices (struct window *, bool);
81 static void fill_up_glyph_row_area_with_spaces (struct glyph_row *, int);
82 static int scrolling_window (struct window *, bool);
83 static bool update_window_line (struct window *, int, bool *);
84 static void mirror_make_current (struct window *, int);
85 #ifdef GLYPH_DEBUG
86 static void check_matrix_pointers (struct glyph_matrix *,
87 struct glyph_matrix *);
88 #endif
89 static void mirror_line_dance (struct window *, int, int, int *, char *);
90 static bool update_window_tree (struct window *, bool);
91 static bool update_window (struct window *, bool);
92 static bool update_frame_1 (struct frame *, bool, bool, bool, bool);
93 static bool scrolling (struct frame *);
94 static void set_window_cursor_after_update (struct window *);
95 static void adjust_frame_glyphs_for_window_redisplay (struct frame *);
96 static void adjust_frame_glyphs_for_frame_redisplay (struct frame *);
97 static void set_window_update_flags (struct window *w, bool on_p);
99 /* True means last display completed. False means it was preempted. */
101 bool display_completed;
103 /* True means SIGWINCH happened when not safe. */
105 static bool delayed_size_change;
107 /* A glyph for a space. */
109 struct glyph space_glyph;
111 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
113 /* Counts of allocated structures. These counts serve to diagnose
114 memory leaks and double frees. */
116 static int glyph_matrix_count;
117 static int glyph_pool_count;
119 #endif /* GLYPH_DEBUG and ENABLE_CHECKING */
121 /* If non-null, the frame whose frame matrices are manipulated. If
122 null, window matrices are worked on. */
124 static struct frame *frame_matrix_frame;
126 /* Convert vpos and hpos from frame to window and vice versa.
127 This may only be used for terminal frames. */
129 #ifdef GLYPH_DEBUG
131 static int window_to_frame_vpos (struct window *, int);
132 static int window_to_frame_hpos (struct window *, int);
133 #define WINDOW_TO_FRAME_VPOS(W, VPOS) window_to_frame_vpos ((W), (VPOS))
134 #define WINDOW_TO_FRAME_HPOS(W, HPOS) window_to_frame_hpos ((W), (HPOS))
136 /* One element of the ring buffer containing redisplay history
137 information. */
139 struct redisplay_history
141 char trace[512 + 100];
144 /* The size of the history buffer. */
146 #define REDISPLAY_HISTORY_SIZE 30
148 /* The redisplay history buffer. */
150 static struct redisplay_history redisplay_history[REDISPLAY_HISTORY_SIZE];
152 /* Next free entry in redisplay_history. */
154 static int history_idx;
156 /* A tick that's incremented each time something is added to the
157 history. */
159 static uprintmax_t history_tick;
161 /* Add to the redisplay history how window W has been displayed.
162 MSG is a trace containing the information how W's glyph matrix
163 has been constructed. PAUSED_P means that the update
164 has been interrupted for pending input. */
166 static void
167 add_window_display_history (struct window *w, const char *msg, bool paused_p)
169 char *buf;
170 void *ptr = w;
172 if (history_idx >= REDISPLAY_HISTORY_SIZE)
173 history_idx = 0;
174 buf = redisplay_history[history_idx].trace;
175 ++history_idx;
177 snprintf (buf, sizeof redisplay_history[0].trace,
178 "%"pMu": window %p (%s)%s\n%s",
179 history_tick++,
180 ptr,
181 ((BUFFERP (w->contents)
182 && STRINGP (BVAR (XBUFFER (w->contents), name)))
183 ? SSDATA (BVAR (XBUFFER (w->contents), name))
184 : "???"),
185 paused_p ? " ***paused***" : "",
186 msg);
190 /* Add to the redisplay history that frame F has been displayed.
191 PAUSED_P means that the update has been interrupted for
192 pending input. */
194 static void
195 add_frame_display_history (struct frame *f, bool paused_p)
197 char *buf;
198 void *ptr = f;
200 if (history_idx >= REDISPLAY_HISTORY_SIZE)
201 history_idx = 0;
202 buf = redisplay_history[history_idx].trace;
203 ++history_idx;
205 sprintf (buf, "%"pMu": update frame %p%s",
206 history_tick++,
207 ptr, paused_p ? " ***paused***" : "");
211 DEFUN ("dump-redisplay-history", Fdump_redisplay_history,
212 Sdump_redisplay_history, 0, 0, "",
213 doc: /* Dump redisplay history to stderr. */)
214 (void)
216 int i;
218 for (i = history_idx - 1; i != history_idx; --i)
220 if (i < 0)
221 i = REDISPLAY_HISTORY_SIZE - 1;
222 fprintf (stderr, "%s\n", redisplay_history[i].trace);
225 return Qnil;
229 #else /* not GLYPH_DEBUG */
231 #define WINDOW_TO_FRAME_VPOS(W, VPOS) ((VPOS) + WINDOW_TOP_EDGE_LINE (W))
232 #define WINDOW_TO_FRAME_HPOS(W, HPOS) ((HPOS) + WINDOW_LEFT_EDGE_COL (W))
234 #endif /* GLYPH_DEBUG */
237 #if (defined PROFILING \
238 && (defined __FreeBSD__ || defined GNU_LINUX || defined __MINGW32__) \
239 && !HAVE___EXECUTABLE_START)
240 /* This function comes first in the Emacs executable and is used only
241 to estimate the text start for profiling. */
242 void
243 __executable_start (void)
245 emacs_abort ();
247 #endif
249 /***********************************************************************
250 Glyph Matrices
251 ***********************************************************************/
253 /* Allocate and return a glyph_matrix structure. POOL is the glyph
254 pool from which memory for the matrix should be allocated, or null
255 for window-based redisplay where no glyph pools are used. The
256 member `pool' of the glyph matrix structure returned is set to
257 POOL, the structure is otherwise zeroed. */
259 static struct glyph_matrix *
260 new_glyph_matrix (struct glyph_pool *pool)
262 struct glyph_matrix *result = xzalloc (sizeof *result);
264 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
265 /* Increment number of allocated matrices. This count is used
266 to detect memory leaks. */
267 ++glyph_matrix_count;
268 #endif
270 /* Set pool and return. */
271 result->pool = pool;
272 return result;
276 /* Free glyph matrix MATRIX. Passing in a null MATRIX is allowed.
278 If GLYPH_DEBUG and ENABLE_CHECKING are in effect, the global counter
279 glyph_matrix_count is decremented when a matrix is freed. If the count
280 gets negative, more structures were freed than allocated, i.e. one matrix
281 was freed more than once or a bogus pointer was passed to this function.
283 If MATRIX->pool is null, this means that the matrix manages its own
284 glyph memory---this is done for matrices on X frames. Freeing the
285 matrix also frees the glyph memory in this case. */
287 static void
288 free_glyph_matrix (struct glyph_matrix *matrix)
290 if (matrix)
292 int i;
294 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
295 /* Detect the case that more matrices are freed than were
296 allocated. */
297 --glyph_matrix_count;
298 eassert (glyph_matrix_count >= 0);
299 #endif
301 /* Free glyph memory if MATRIX owns it. */
302 if (matrix->pool == NULL)
303 for (i = 0; i < matrix->rows_allocated; ++i)
304 xfree (matrix->rows[i].glyphs[LEFT_MARGIN_AREA]);
306 /* Free row structures and the matrix itself. */
307 xfree (matrix->rows);
308 xfree (matrix);
313 /* Return the number of glyphs to reserve for a marginal area of
314 window W. TOTAL_GLYPHS is the number of glyphs in a complete
315 display line of window W. MARGIN gives the width of the marginal
316 area in canonical character units. */
318 static int
319 margin_glyphs_to_reserve (struct window *w, int total_glyphs, int margin)
321 if (margin > 0)
323 int width = w->total_cols;
324 double d = max (0, margin);
325 d = min (width / 2 - 1, d);
326 /* Since MARGIN is positive, we cannot possibly have less than
327 one glyph for the marginal area. */
328 return max (1, (int) ((double) total_glyphs / width * d));
330 return 0;
333 /* Return true if ROW's hash value is correct.
334 Optimized away if ENABLE_CHECKING is not defined. */
336 static bool
337 verify_row_hash (struct glyph_row *row)
339 return row->hash == row_hash (row);
342 /* Adjust glyph matrix MATRIX on window W or on a frame to changed
343 window sizes.
345 W is null if the function is called for a frame glyph matrix.
346 Otherwise it is the window MATRIX is a member of. X and Y are the
347 indices of the first column and row of MATRIX within the frame
348 matrix, if such a matrix exists. They are zero for purely
349 window-based redisplay. DIM is the needed size of the matrix.
351 In window-based redisplay, where no frame matrices exist, glyph
352 matrices manage their own glyph storage. Otherwise, they allocate
353 storage from a common frame glyph pool which can be found in
354 MATRIX->pool.
356 The reason for this memory management strategy is to avoid complete
357 frame redraws if possible. When we allocate from a common pool, a
358 change of the location or size of a sub-matrix within the pool
359 requires a complete redisplay of the frame because we cannot easily
360 make sure that the current matrices of all windows still agree with
361 what is displayed on the screen. While this is usually fast, it
362 leads to screen flickering. */
364 static void
365 adjust_glyph_matrix (struct window *w, struct glyph_matrix *matrix, int x, int y, struct dim dim)
367 int i;
368 int new_rows;
369 bool marginal_areas_changed_p = 0;
370 bool header_line_changed_p = 0;
371 bool header_line_p = 0;
372 int left = -1, right = -1;
373 int window_width = -1, window_height = -1;
375 /* See if W had a header line that has disappeared now, or vice versa.
376 Get W's size. */
377 if (w)
379 window_box (w, ANY_AREA, 0, 0, &window_width, &window_height);
381 header_line_p = window_wants_header_line (w);
382 header_line_changed_p = header_line_p != matrix->header_line_p;
384 matrix->header_line_p = header_line_p;
386 /* If POOL is null, MATRIX is a window matrix for window-based redisplay.
387 Do nothing if MATRIX' size, position, vscroll, and marginal areas
388 haven't changed. This optimization is important because preserving
389 the matrix means preventing redisplay. */
390 eassume (w != NULL || matrix->pool != NULL);
391 if (matrix->pool == NULL)
393 left = margin_glyphs_to_reserve (w, dim.width, w->left_margin_cols);
394 right = margin_glyphs_to_reserve (w, dim.width, w->right_margin_cols);
395 eassert (left >= 0 && right >= 0);
396 marginal_areas_changed_p = (left != matrix->left_margin_glyphs
397 || right != matrix->right_margin_glyphs);
399 if (!marginal_areas_changed_p
400 && !XFRAME (w->frame)->fonts_changed
401 && !header_line_changed_p
402 && matrix->window_pixel_left == WINDOW_LEFT_PIXEL_EDGE (w)
403 && matrix->window_pixel_top == WINDOW_TOP_PIXEL_EDGE (w)
404 && matrix->window_height == window_height
405 && matrix->window_vscroll == w->vscroll
406 && matrix->window_width == window_width)
407 return;
410 /* Enlarge MATRIX->rows if necessary. New rows are cleared. */
411 if (matrix->rows_allocated < dim.height)
413 int old_alloc = matrix->rows_allocated;
414 new_rows = dim.height - matrix->rows_allocated;
415 matrix->rows = xpalloc (matrix->rows, &matrix->rows_allocated,
416 new_rows, INT_MAX, sizeof *matrix->rows);
417 memset (matrix->rows + old_alloc, 0,
418 (matrix->rows_allocated - old_alloc) * sizeof *matrix->rows);
420 else
421 new_rows = 0;
423 /* If POOL is not null, MATRIX is a frame matrix or a window matrix
424 on a frame not using window-based redisplay. Set up pointers for
425 each row into the glyph pool. */
426 if (matrix->pool)
428 eassert (matrix->pool->glyphs);
430 if (w)
432 left = margin_glyphs_to_reserve (w, dim.width,
433 w->left_margin_cols);
434 right = margin_glyphs_to_reserve (w, dim.width,
435 w->right_margin_cols);
437 else
438 left = right = 0;
440 for (i = 0; i < dim.height; ++i)
442 struct glyph_row *row = &matrix->rows[i];
444 row->glyphs[LEFT_MARGIN_AREA]
445 = (matrix->pool->glyphs
446 + (y + i) * matrix->pool->ncolumns
447 + x);
449 if (w == NULL
450 || (row == matrix->rows + dim.height - 1
451 && window_wants_mode_line (w))
452 || (row == matrix->rows && matrix->header_line_p))
454 row->glyphs[TEXT_AREA]
455 = row->glyphs[LEFT_MARGIN_AREA];
456 row->glyphs[RIGHT_MARGIN_AREA]
457 = row->glyphs[TEXT_AREA] + dim.width;
458 row->glyphs[LAST_AREA]
459 = row->glyphs[RIGHT_MARGIN_AREA];
461 else
463 row->glyphs[TEXT_AREA]
464 = row->glyphs[LEFT_MARGIN_AREA] + left;
465 row->glyphs[RIGHT_MARGIN_AREA]
466 = row->glyphs[TEXT_AREA] + dim.width - left - right;
467 row->glyphs[LAST_AREA]
468 = row->glyphs[LEFT_MARGIN_AREA] + dim.width;
472 matrix->left_margin_glyphs = left;
473 matrix->right_margin_glyphs = right;
475 else
477 /* If MATRIX->pool is null, MATRIX is responsible for managing
478 its own memory. It is a window matrix for window-based redisplay.
479 Allocate glyph memory from the heap. */
480 if (dim.width > matrix->matrix_w
481 || new_rows
482 || header_line_changed_p
483 || marginal_areas_changed_p)
485 struct glyph_row *row = matrix->rows;
486 struct glyph_row *end = row + matrix->rows_allocated;
488 while (row < end)
490 row->glyphs[LEFT_MARGIN_AREA]
491 = xnrealloc (row->glyphs[LEFT_MARGIN_AREA],
492 dim.width, sizeof (struct glyph));
494 /* The mode line, if displayed, never has marginal areas. */
495 if ((row == matrix->rows + dim.height - 1
496 && !(w && window_wants_mode_line (w)))
497 || (row == matrix->rows && matrix->header_line_p))
499 row->glyphs[TEXT_AREA]
500 = row->glyphs[LEFT_MARGIN_AREA];
501 row->glyphs[RIGHT_MARGIN_AREA]
502 = row->glyphs[TEXT_AREA] + dim.width;
503 row->glyphs[LAST_AREA]
504 = row->glyphs[RIGHT_MARGIN_AREA];
506 else
508 row->glyphs[TEXT_AREA]
509 = row->glyphs[LEFT_MARGIN_AREA] + left;
510 row->glyphs[RIGHT_MARGIN_AREA]
511 = row->glyphs[TEXT_AREA] + dim.width - left - right;
512 row->glyphs[LAST_AREA]
513 = row->glyphs[LEFT_MARGIN_AREA] + dim.width;
515 ++row;
519 eassert (left >= 0 && right >= 0);
520 matrix->left_margin_glyphs = left;
521 matrix->right_margin_glyphs = right;
524 /* Number of rows to be used by MATRIX. */
525 matrix->nrows = dim.height;
526 eassert (matrix->nrows >= 0);
528 if (w)
530 if (matrix == w->current_matrix)
532 /* Mark rows in a current matrix of a window as not having
533 valid contents. It's important to not do this for
534 desired matrices. When Emacs starts, it may already be
535 building desired matrices when this function runs. */
536 if (window_width < 0)
537 window_width = window_box_width (w, -1);
539 /* Optimize the case that only the height has changed (C-x 2,
540 upper window). Invalidate all rows that are no longer part
541 of the window. */
542 if (!marginal_areas_changed_p
543 && !header_line_changed_p
544 && new_rows == 0
545 && dim.width == matrix->matrix_w
546 && matrix->window_pixel_left == WINDOW_LEFT_PIXEL_EDGE (w)
547 && matrix->window_pixel_top == WINDOW_TOP_PIXEL_EDGE (w)
548 && matrix->window_width == window_width)
550 /* Find the last row in the window. */
551 for (i = 0; i < matrix->nrows && matrix->rows[i].enabled_p; ++i)
552 if (MATRIX_ROW_BOTTOM_Y (matrix->rows + i) >= window_height)
554 ++i;
555 break;
558 /* Window end is invalid, if inside of the rows that
559 are invalidated below. */
560 if (w->window_end_vpos >= i)
561 w->window_end_valid = 0;
563 while (i < matrix->nrows)
564 matrix->rows[i++].enabled_p = false;
566 else
568 for (i = 0; i < matrix->nrows; ++i)
569 matrix->rows[i].enabled_p = false;
571 /* We've disabled the mode-line row, so force redrawing of
572 the mode line, if any, since otherwise it will remain
573 disabled in the current matrix, and expose events won't
574 redraw it. */
575 if (window_wants_mode_line (w))
576 w->update_mode_line = 1;
578 else if (matrix == w->desired_matrix)
580 /* Rows in desired matrices always have to be cleared;
581 redisplay expects this is the case when it runs, so it
582 had better be the case when we adjust matrices between
583 redisplays. */
584 for (i = 0; i < matrix->nrows; ++i)
585 matrix->rows[i].enabled_p = false;
590 /* Remember last values to be able to optimize frame redraws. */
591 matrix->matrix_x = x;
592 matrix->matrix_y = y;
593 matrix->matrix_w = dim.width;
594 matrix->matrix_h = dim.height;
596 /* Record the top y location and height of W at the time the matrix
597 was last adjusted. This is used to optimize redisplay above. */
598 if (w)
600 matrix->window_pixel_left = WINDOW_LEFT_PIXEL_EDGE (w);
601 matrix->window_pixel_top = WINDOW_TOP_PIXEL_EDGE (w);
602 matrix->window_height = window_height;
603 matrix->window_width = window_width;
604 matrix->window_vscroll = w->vscroll;
609 /* Reverse the contents of rows in MATRIX between START and END. The
610 contents of the row at END - 1 end up at START, END - 2 at START +
611 1 etc. This is part of the implementation of rotate_matrix (see
612 below). */
614 static void
615 reverse_rows (struct glyph_matrix *matrix, int start, int end)
617 int i, j;
619 for (i = start, j = end - 1; i < j; ++i, --j)
621 /* Non-ISO HP/UX compiler doesn't like auto struct
622 initialization. */
623 struct glyph_row temp;
624 temp = matrix->rows[i];
625 matrix->rows[i] = matrix->rows[j];
626 matrix->rows[j] = temp;
631 /* Rotate the contents of rows in MATRIX in the range FIRST .. LAST -
632 1 by BY positions. BY < 0 means rotate left, i.e. towards lower
633 indices. (Note: this does not copy glyphs, only glyph pointers in
634 row structures are moved around).
636 The algorithm used for rotating the vector was, I believe, first
637 described by Kernighan. See the vector R as consisting of two
638 sub-vectors AB, where A has length BY for BY >= 0. The result
639 after rotating is then BA. Reverse both sub-vectors to get ArBr
640 and reverse the result to get (ArBr)r which is BA. Similar for
641 rotating right. */
643 void
644 rotate_matrix (struct glyph_matrix *matrix, int first, int last, int by)
646 if (by < 0)
648 /* Up (rotate left, i.e. towards lower indices). */
649 by = -by;
650 reverse_rows (matrix, first, first + by);
651 reverse_rows (matrix, first + by, last);
652 reverse_rows (matrix, first, last);
654 else if (by > 0)
656 /* Down (rotate right, i.e. towards higher indices). */
657 reverse_rows (matrix, last - by, last);
658 reverse_rows (matrix, first, last - by);
659 reverse_rows (matrix, first, last);
664 /* Increment buffer positions in glyph rows of MATRIX. Do it for rows
665 with indices START <= index < END. Increment positions by DELTA/
666 DELTA_BYTES. */
668 void
669 increment_matrix_positions (struct glyph_matrix *matrix, int start, int end,
670 ptrdiff_t delta, ptrdiff_t delta_bytes)
672 /* Check that START and END are reasonable values. */
673 eassert (start >= 0 && start <= matrix->nrows);
674 eassert (end >= 0 && end <= matrix->nrows);
675 eassert (start <= end);
677 for (; start < end; ++start)
678 increment_row_positions (matrix->rows + start, delta, delta_bytes);
682 /* Clear the enable_p flags in a range of rows in glyph matrix MATRIX.
683 START and END are the row indices of the first and last + 1 row to clear. */
685 void
686 clear_glyph_matrix_rows (struct glyph_matrix *matrix, int start, int end)
688 eassert (start <= end);
689 eassert (start >= 0 && (start < matrix->nrows
690 /* matrix->nrows can be 0 for the initial frame. */
691 || (matrix->nrows == 0)));
692 eassert (end >= 0 && end <= matrix->nrows);
694 for (; start < end; ++start)
695 matrix->rows[start].enabled_p = false;
699 /* Clear MATRIX.
701 Empty all rows in MATRIX by clearing their enabled_p flags.
702 The function prepare_desired_row will eventually really clear a row
703 when it sees one with a false enabled_p flag.
705 Reset update hints to default values. The only update hint
706 currently present is the flag MATRIX->no_scrolling_p. */
708 void
709 clear_glyph_matrix (struct glyph_matrix *matrix)
711 if (matrix)
713 clear_glyph_matrix_rows (matrix, 0, matrix->nrows);
714 matrix->no_scrolling_p = 0;
719 /* Shift part of the glyph matrix MATRIX of window W up or down.
720 Increment y-positions in glyph rows between START and END by DY,
721 and recompute their visible height. */
723 void
724 shift_glyph_matrix (struct window *w, struct glyph_matrix *matrix, int start, int end, int dy)
726 int min_y, max_y;
728 eassert (start <= end);
729 eassert (start >= 0 && start < matrix->nrows);
730 eassert (end >= 0 && end <= matrix->nrows);
732 min_y = WINDOW_HEADER_LINE_HEIGHT (w);
733 max_y = WINDOW_BOX_HEIGHT_NO_MODE_LINE (w);
735 for (; start < end; ++start)
737 struct glyph_row *row = &matrix->rows[start];
739 row->y += dy;
740 row->visible_height = row->height;
742 if (row->y < min_y)
743 row->visible_height -= min_y - row->y;
744 if (row->y + row->height > max_y)
745 row->visible_height -= row->y + row->height - max_y;
746 if (row->fringe_bitmap_periodic_p)
747 row->redraw_fringe_bitmaps_p = 1;
752 /* Mark all rows in current matrices of frame F as invalid. Marking
753 invalid is done by setting enabled_p to zero for all rows in a
754 current matrix. */
756 void
757 clear_current_matrices (register struct frame *f)
759 /* Clear frame current matrix, if we have one. */
760 if (f->current_matrix)
761 clear_glyph_matrix (f->current_matrix);
763 #if defined (HAVE_X_WINDOWS) && ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
764 /* Clear the matrix of the menu bar window, if such a window exists.
765 The menu bar window is currently used to display menus on X when
766 no toolkit support is compiled in. */
767 if (WINDOWP (f->menu_bar_window))
768 clear_glyph_matrix (XWINDOW (f->menu_bar_window)->current_matrix);
769 #endif
771 #if defined (HAVE_WINDOW_SYSTEM) && ! defined (USE_GTK) && ! defined (HAVE_NS)
772 /* Clear the matrix of the tool-bar window, if any. */
773 if (WINDOWP (f->tool_bar_window))
774 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
775 #endif
777 /* Clear current window matrices. */
778 eassert (WINDOWP (FRAME_ROOT_WINDOW (f)));
779 clear_window_matrices (XWINDOW (FRAME_ROOT_WINDOW (f)), 0);
783 /* Clear out all display lines of F for a coming redisplay. */
785 void
786 clear_desired_matrices (register struct frame *f)
788 if (f->desired_matrix)
789 clear_glyph_matrix (f->desired_matrix);
791 #if defined (HAVE_X_WINDOWS) && ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
792 if (WINDOWP (f->menu_bar_window))
793 clear_glyph_matrix (XWINDOW (f->menu_bar_window)->desired_matrix);
794 #endif
796 #if defined (HAVE_WINDOW_SYSTEM) && ! defined (USE_GTK) && ! defined (HAVE_NS)
797 if (WINDOWP (f->tool_bar_window))
798 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->desired_matrix);
799 #endif
801 /* Do it for window matrices. */
802 eassert (WINDOWP (FRAME_ROOT_WINDOW (f)));
803 clear_window_matrices (XWINDOW (FRAME_ROOT_WINDOW (f)), 1);
807 /* Clear matrices in window tree rooted in W. If DESIRED_P,
808 clear desired matrices, otherwise clear current matrices. */
810 static void
811 clear_window_matrices (struct window *w, bool desired_p)
813 while (w)
815 if (WINDOWP (w->contents))
816 clear_window_matrices (XWINDOW (w->contents), desired_p);
817 else
819 if (desired_p)
820 clear_glyph_matrix (w->desired_matrix);
821 else
823 clear_glyph_matrix (w->current_matrix);
824 w->window_end_valid = 0;
828 w = NILP (w->next) ? 0 : XWINDOW (w->next);
834 /***********************************************************************
835 Glyph Rows
837 See dispextern.h for an overall explanation of glyph rows.
838 ***********************************************************************/
840 /* Clear glyph row ROW. NOTE: this code relies on the current
841 layout of `glyphs' and `used' fields of `struct glyph_row'. */
843 void
844 clear_glyph_row (struct glyph_row *row)
846 enum { off = offsetof (struct glyph_row, used) };
848 /* Zero everything except pointers in `glyphs'. */
849 memset (row->used, 0, sizeof *row - off);
853 /* Make ROW an empty, enabled row of canonical character height,
854 in window W starting at y-position Y. */
856 void
857 blank_row (struct window *w, struct glyph_row *row, int y)
859 int min_y, max_y;
861 min_y = WINDOW_HEADER_LINE_HEIGHT (w);
862 max_y = WINDOW_BOX_HEIGHT_NO_MODE_LINE (w);
864 clear_glyph_row (row);
865 row->y = y;
866 row->ascent = row->phys_ascent = 0;
867 row->height = row->phys_height = FRAME_LINE_HEIGHT (XFRAME (w->frame));
868 row->visible_height = row->height;
870 if (row->y < min_y)
871 row->visible_height -= min_y - row->y;
872 if (row->y + row->height > max_y)
873 row->visible_height -= row->y + row->height - max_y;
875 row->enabled_p = true;
879 /* Increment buffer positions in glyph row ROW. DELTA and DELTA_BYTES
880 are the amounts by which to change positions. Note that the first
881 glyph of the text area of a row can have a buffer position even if
882 the used count of the text area is zero. Such rows display line
883 ends. */
885 static void
886 increment_row_positions (struct glyph_row *row,
887 ptrdiff_t delta, ptrdiff_t delta_bytes)
889 int area, i;
891 /* Increment start and end positions. */
892 MATRIX_ROW_START_CHARPOS (row) += delta;
893 MATRIX_ROW_START_BYTEPOS (row) += delta_bytes;
894 MATRIX_ROW_END_CHARPOS (row) += delta;
895 MATRIX_ROW_END_BYTEPOS (row) += delta_bytes;
896 CHARPOS (row->start.pos) += delta;
897 BYTEPOS (row->start.pos) += delta_bytes;
898 CHARPOS (row->end.pos) += delta;
899 BYTEPOS (row->end.pos) += delta_bytes;
901 if (!row->enabled_p)
902 return;
904 /* Increment positions in glyphs. */
905 for (area = 0; area < LAST_AREA; ++area)
906 for (i = 0; i < row->used[area]; ++i)
907 if (BUFFERP (row->glyphs[area][i].object)
908 && row->glyphs[area][i].charpos > 0)
909 row->glyphs[area][i].charpos += delta;
911 /* Capture the case of rows displaying a line end. */
912 if (row->used[TEXT_AREA] == 0
913 && MATRIX_ROW_DISPLAYS_TEXT_P (row))
914 row->glyphs[TEXT_AREA]->charpos += delta;
918 #if 0
919 /* Swap glyphs between two glyph rows A and B. This exchanges glyph
920 contents, i.e. glyph structure contents are exchanged between A and
921 B without changing glyph pointers in A and B. */
923 static void
924 swap_glyphs_in_rows (struct glyph_row *a, struct glyph_row *b)
926 int area;
928 for (area = 0; area < LAST_AREA; ++area)
930 /* Number of glyphs to swap. */
931 int max_used = max (a->used[area], b->used[area]);
933 /* Start of glyphs in area of row A. */
934 struct glyph *glyph_a = a->glyphs[area];
936 /* End + 1 of glyphs in area of row A. */
937 struct glyph *glyph_a_end = a->glyphs[max_used];
939 /* Start of glyphs in area of row B. */
940 struct glyph *glyph_b = b->glyphs[area];
942 while (glyph_a < glyph_a_end)
944 /* Non-ISO HP/UX compiler doesn't like auto struct
945 initialization. */
946 struct glyph temp;
947 temp = *glyph_a;
948 *glyph_a = *glyph_b;
949 *glyph_b = temp;
950 ++glyph_a;
951 ++glyph_b;
956 #endif /* 0 */
958 /* Exchange pointers to glyph memory between glyph rows A and B. Also
959 exchange the used[] array and the hash values of the rows, because
960 these should all go together for the row's hash value to be
961 correct. */
963 static void
964 swap_glyph_pointers (struct glyph_row *a, struct glyph_row *b)
966 int i;
967 unsigned hash_tem = a->hash;
969 for (i = 0; i < LAST_AREA + 1; ++i)
971 struct glyph *temp = a->glyphs[i];
973 a->glyphs[i] = b->glyphs[i];
974 b->glyphs[i] = temp;
975 if (i < LAST_AREA)
977 short used_tem = a->used[i];
979 a->used[i] = b->used[i];
980 b->used[i] = used_tem;
983 a->hash = b->hash;
984 b->hash = hash_tem;
988 /* Copy glyph row structure FROM to glyph row structure TO, except that
989 glyph pointers, the `used' counts, and the hash values in the structures
990 are left unchanged. NOTE: this code relies on the current layout of
991 `glyphs', `used', `hash' and `x' fields of `struct glyph_row'. */
993 static void
994 copy_row_except_pointers (struct glyph_row *to, struct glyph_row *from)
996 enum { off = offsetof (struct glyph_row, x) };
998 memcpy (&to->x, &from->x, sizeof *to - off);
1002 /* Assign glyph row FROM to glyph row TO. This works like a structure
1003 assignment TO = FROM, except that glyph pointers are not copied but
1004 exchanged between TO and FROM. Pointers must be exchanged to avoid
1005 a memory leak. */
1007 static void
1008 assign_row (struct glyph_row *to, struct glyph_row *from)
1010 swap_glyph_pointers (to, from);
1011 copy_row_except_pointers (to, from);
1015 /* Test whether the glyph memory of the glyph row WINDOW_ROW, which is
1016 a row in a window matrix, is a slice of the glyph memory of the
1017 glyph row FRAME_ROW which is a row in a frame glyph matrix. Value
1018 is true if the glyph memory of WINDOW_ROW is part of the glyph
1019 memory of FRAME_ROW. */
1021 #ifdef GLYPH_DEBUG
1023 static bool
1024 glyph_row_slice_p (struct glyph_row *window_row, struct glyph_row *frame_row)
1026 struct glyph *window_glyph_start = window_row->glyphs[0];
1027 struct glyph *frame_glyph_start = frame_row->glyphs[0];
1028 struct glyph *frame_glyph_end = frame_row->glyphs[LAST_AREA];
1030 return (frame_glyph_start <= window_glyph_start
1031 && window_glyph_start < frame_glyph_end);
1034 #endif /* GLYPH_DEBUG */
1036 #if 0
1038 /* Find the row in the window glyph matrix WINDOW_MATRIX being a slice
1039 of ROW in the frame matrix FRAME_MATRIX. Value is null if no row
1040 in WINDOW_MATRIX is found satisfying the condition. */
1042 static struct glyph_row *
1043 find_glyph_row_slice (struct glyph_matrix *window_matrix,
1044 struct glyph_matrix *frame_matrix, int row)
1046 int i;
1048 eassert (row >= 0 && row < frame_matrix->nrows);
1050 for (i = 0; i < window_matrix->nrows; ++i)
1051 if (glyph_row_slice_p (window_matrix->rows + i,
1052 frame_matrix->rows + row))
1053 break;
1055 return i < window_matrix->nrows ? window_matrix->rows + i : 0;
1058 #endif /* 0 */
1060 /* Prepare ROW for display in windows W. Desired rows are cleared
1061 lazily, i.e. they are only marked as to be cleared by setting their
1062 enabled_p flag to zero. When a row is to be displayed, a prior
1063 call to this function really clears it. In addition, this function
1064 makes sure the marginal areas of ROW are in sync with the window's
1065 display margins. MODE_LINE_P non-zero means we are preparing a
1066 glyph row for header line or mode line. */
1068 void
1069 prepare_desired_row (struct window *w, struct glyph_row *row, bool mode_line_p)
1071 if (!row->enabled_p)
1073 bool rp = row->reversed_p;
1075 clear_glyph_row (row);
1076 row->enabled_p = true;
1077 row->reversed_p = rp;
1079 if (mode_line_p)
1081 /* Mode and header lines, if displayed, never have marginal
1082 areas. If we are called with MODE_LINE_P non-zero, we are
1083 displaying the mode/header line in this window, and so the
1084 marginal areas of this glyph row should be eliminated. This
1085 is needed when the mode/header line is switched on in a
1086 window that has display margins. */
1087 if (w->left_margin_cols > 0)
1088 row->glyphs[TEXT_AREA] = row->glyphs[LEFT_MARGIN_AREA];
1089 if (w->right_margin_cols > 0)
1090 row->glyphs[RIGHT_MARGIN_AREA] = row->glyphs[LAST_AREA];
1092 else
1094 /* The real number of glyphs reserved for the margins is
1095 recorded in the glyph matrix, and can be different from
1096 window's left_margin_cols and right_margin_cols; see
1097 margin_glyphs_to_reserve for when that happens. */
1098 int left = w->desired_matrix->left_margin_glyphs;
1099 int right = w->desired_matrix->right_margin_glyphs;
1101 /* Make sure the marginal areas of this row are in sync with
1102 what the window wants, when the row actually displays text
1103 and not header/mode line. */
1104 if (w->left_margin_cols > 0
1105 && (left != row->glyphs[TEXT_AREA] - row->glyphs[LEFT_MARGIN_AREA]))
1106 row->glyphs[TEXT_AREA] = row->glyphs[LEFT_MARGIN_AREA] + left;
1107 if (w->right_margin_cols > 0
1108 && (right != row->glyphs[LAST_AREA] - row->glyphs[RIGHT_MARGIN_AREA]))
1109 row->glyphs[RIGHT_MARGIN_AREA] = row->glyphs[LAST_AREA] - right;
1114 /* Return a hash code for glyph row ROW, which may
1115 be from current or desired matrix of frame F. */
1117 static unsigned
1118 line_hash_code (struct frame *f, struct glyph_row *row)
1120 unsigned hash = 0;
1122 if (row->enabled_p)
1124 struct glyph *glyph = row->glyphs[TEXT_AREA];
1125 struct glyph *end = glyph + row->used[TEXT_AREA];
1127 while (glyph < end)
1129 int c = glyph->u.ch;
1130 int face_id = glyph->face_id;
1131 if (FRAME_MUST_WRITE_SPACES (f))
1132 c -= SPACEGLYPH;
1133 hash = (((hash << 4) + (hash >> 24)) & 0x0fffffff) + c;
1134 hash = (((hash << 4) + (hash >> 24)) & 0x0fffffff) + face_id;
1135 ++glyph;
1138 if (hash == 0)
1139 hash = 1;
1142 return hash;
1146 /* Return the cost of drawing line VPOS in MATRIX, which may
1147 be current or desired matrix of frame F. The cost equals
1148 the number of characters in the line. If must_write_spaces
1149 is zero, leading and trailing spaces are ignored. */
1151 static int
1152 line_draw_cost (struct frame *f, struct glyph_matrix *matrix, int vpos)
1154 struct glyph_row *row = matrix->rows + vpos;
1155 struct glyph *beg = row->glyphs[TEXT_AREA];
1156 struct glyph *end = beg + row->used[TEXT_AREA];
1157 int len;
1158 Lisp_Object *glyph_table_base = GLYPH_TABLE_BASE;
1159 ptrdiff_t glyph_table_len = GLYPH_TABLE_LENGTH;
1161 /* Ignore trailing and leading spaces if we can. */
1162 if (!FRAME_MUST_WRITE_SPACES (f))
1164 /* Skip from the end over trailing spaces. */
1165 while (end > beg && CHAR_GLYPH_SPACE_P (*(end - 1)))
1166 --end;
1168 /* All blank line. */
1169 if (end == beg)
1170 return 0;
1172 /* Skip over leading spaces. */
1173 while (CHAR_GLYPH_SPACE_P (*beg))
1174 ++beg;
1177 /* If we don't have a glyph-table, each glyph is one character,
1178 so return the number of glyphs. */
1179 if (glyph_table_base == 0)
1180 len = end - beg;
1181 else
1183 /* Otherwise, scan the glyphs and accumulate their total length
1184 in LEN. */
1185 len = 0;
1186 while (beg < end)
1188 GLYPH g;
1190 SET_GLYPH_FROM_CHAR_GLYPH (g, *beg);
1192 if (GLYPH_INVALID_P (g)
1193 || GLYPH_SIMPLE_P (glyph_table_base, glyph_table_len, g))
1194 len += 1;
1195 else
1196 len += GLYPH_LENGTH (glyph_table_base, g);
1198 ++beg;
1202 return len;
1206 /* Return true if the glyph rows A and B have equal contents.
1207 MOUSE_FACE_P means compare the mouse_face_p flags of A and B, too. */
1209 static bool
1210 row_equal_p (struct glyph_row *a, struct glyph_row *b, bool mouse_face_p)
1212 eassert (verify_row_hash (a));
1213 eassert (verify_row_hash (b));
1215 if (a == b)
1216 return 1;
1217 else if (a->hash != b->hash)
1218 return 0;
1219 else
1221 struct glyph *a_glyph, *b_glyph, *a_end;
1222 int area;
1224 if (mouse_face_p && a->mouse_face_p != b->mouse_face_p)
1225 return 0;
1227 /* Compare glyphs. */
1228 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
1230 if (a->used[area] != b->used[area])
1231 return 0;
1233 a_glyph = a->glyphs[area];
1234 a_end = a_glyph + a->used[area];
1235 b_glyph = b->glyphs[area];
1237 while (a_glyph < a_end
1238 && GLYPH_EQUAL_P (a_glyph, b_glyph))
1239 ++a_glyph, ++b_glyph;
1241 if (a_glyph != a_end)
1242 return 0;
1245 if (a->fill_line_p != b->fill_line_p
1246 || a->cursor_in_fringe_p != b->cursor_in_fringe_p
1247 || a->left_fringe_bitmap != b->left_fringe_bitmap
1248 || a->left_fringe_face_id != b->left_fringe_face_id
1249 || a->left_fringe_offset != b->left_fringe_offset
1250 || a->right_fringe_bitmap != b->right_fringe_bitmap
1251 || a->right_fringe_face_id != b->right_fringe_face_id
1252 || a->right_fringe_offset != b->right_fringe_offset
1253 || a->fringe_bitmap_periodic_p != b->fringe_bitmap_periodic_p
1254 || a->overlay_arrow_bitmap != b->overlay_arrow_bitmap
1255 || a->exact_window_width_line_p != b->exact_window_width_line_p
1256 || a->overlapped_p != b->overlapped_p
1257 || (MATRIX_ROW_CONTINUATION_LINE_P (a)
1258 != MATRIX_ROW_CONTINUATION_LINE_P (b))
1259 || a->reversed_p != b->reversed_p
1260 /* Different partially visible characters on left margin. */
1261 || a->x != b->x
1262 /* Different height. */
1263 || a->ascent != b->ascent
1264 || a->phys_ascent != b->phys_ascent
1265 || a->phys_height != b->phys_height
1266 || a->visible_height != b->visible_height)
1267 return 0;
1270 return 1;
1275 /***********************************************************************
1276 Glyph Pool
1278 See dispextern.h for an overall explanation of glyph pools.
1279 ***********************************************************************/
1281 /* Allocate a glyph_pool structure. The structure returned is initialized
1282 with zeros. If GLYPH_DEBUG and ENABLE_CHECKING are in effect, the global
1283 variable glyph_pool_count is incremented for each pool allocated. */
1285 static struct glyph_pool *
1286 new_glyph_pool (void)
1288 struct glyph_pool *result = xzalloc (sizeof *result);
1290 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1291 /* For memory leak and double deletion checking. */
1292 ++glyph_pool_count;
1293 #endif
1295 return result;
1299 /* Free a glyph_pool structure POOL. The function may be called with
1300 a null POOL pointer. If GLYPH_DEBUG and ENABLE_CHECKING are in effect,
1301 global variable glyph_pool_count is decremented with every pool structure
1302 freed. If this count gets negative, more structures were freed than
1303 allocated, i.e. one structure must have been freed more than once or
1304 a bogus pointer was passed to free_glyph_pool. */
1306 static void
1307 free_glyph_pool (struct glyph_pool *pool)
1309 if (pool)
1311 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1312 /* More freed than allocated? */
1313 --glyph_pool_count;
1314 eassert (glyph_pool_count >= 0);
1315 #endif
1316 xfree (pool->glyphs);
1317 xfree (pool);
1322 /* Enlarge a glyph pool POOL. MATRIX_DIM gives the number of rows and
1323 columns we need. This function never shrinks a pool. The only
1324 case in which this would make sense, would be when a frame's size
1325 is changed from a large value to a smaller one. But, if someone
1326 does it once, we can expect that he will do it again.
1328 Return true if the pool changed in a way which makes
1329 re-adjusting window glyph matrices necessary. */
1331 static bool
1332 realloc_glyph_pool (struct glyph_pool *pool, struct dim matrix_dim)
1334 ptrdiff_t needed;
1335 bool changed_p;
1337 changed_p = (pool->glyphs == 0
1338 || matrix_dim.height != pool->nrows
1339 || matrix_dim.width != pool->ncolumns);
1341 /* Enlarge the glyph pool. */
1342 if (INT_MULTIPLY_WRAPV (matrix_dim.height, matrix_dim.width, &needed))
1343 memory_full (SIZE_MAX);
1344 if (needed > pool->nglyphs)
1346 ptrdiff_t old_nglyphs = pool->nglyphs;
1347 pool->glyphs = xpalloc (pool->glyphs, &pool->nglyphs,
1348 needed - old_nglyphs, -1, sizeof *pool->glyphs);
1349 memclear (pool->glyphs + old_nglyphs,
1350 (pool->nglyphs - old_nglyphs) * sizeof *pool->glyphs);
1353 /* Remember the number of rows and columns because (a) we use them
1354 to do sanity checks, and (b) the number of columns determines
1355 where rows in the frame matrix start---this must be available to
1356 determine pointers to rows of window sub-matrices. */
1357 pool->nrows = matrix_dim.height;
1358 pool->ncolumns = matrix_dim.width;
1360 return changed_p;
1365 /***********************************************************************
1366 Debug Code
1367 ***********************************************************************/
1369 #ifdef GLYPH_DEBUG
1372 /* Flush standard output. This is sometimes useful to call from the debugger.
1373 XXX Maybe this should be changed to flush the current terminal instead of
1374 stdout.
1377 void flush_stdout (void) EXTERNALLY_VISIBLE;
1379 void
1380 flush_stdout (void)
1382 fflush (stdout);
1386 /* Check that no glyph pointers have been lost in MATRIX. If a
1387 pointer has been lost, e.g. by using a structure assignment between
1388 rows, at least one pointer must occur more than once in the rows of
1389 MATRIX. */
1391 void
1392 check_matrix_pointer_lossage (struct glyph_matrix *matrix)
1394 int i, j;
1396 for (i = 0; i < matrix->nrows; ++i)
1397 for (j = 0; j < matrix->nrows; ++j)
1398 eassert (i == j
1399 || (matrix->rows[i].glyphs[TEXT_AREA]
1400 != matrix->rows[j].glyphs[TEXT_AREA]));
1404 /* Get a pointer to glyph row ROW in MATRIX, with bounds checks. */
1406 struct glyph_row *
1407 matrix_row (struct glyph_matrix *matrix, int row)
1409 eassert (matrix && matrix->rows);
1410 eassert (row >= 0 && row < matrix->nrows);
1412 /* That's really too slow for normal testing because this function
1413 is called almost everywhere. Although---it's still astonishingly
1414 fast, so it is valuable to have for debugging purposes. */
1415 #if 0
1416 check_matrix_pointer_lossage (matrix);
1417 #endif
1419 return matrix->rows + row;
1423 #if 0 /* This function makes invalid assumptions when text is
1424 partially invisible. But it might come handy for debugging
1425 nevertheless. */
1427 /* Check invariants that must hold for an up to date current matrix of
1428 window W. */
1430 static void
1431 check_matrix_invariants (struct window *w)
1433 struct glyph_matrix *matrix = w->current_matrix;
1434 int yb = window_text_bottom_y (w);
1435 struct glyph_row *row = matrix->rows;
1436 struct glyph_row *last_text_row = NULL;
1437 struct buffer *saved = current_buffer;
1438 struct buffer *buffer = XBUFFER (w->contents);
1439 int c;
1441 /* This can sometimes happen for a fresh window. */
1442 if (matrix->nrows < 2)
1443 return;
1445 set_buffer_temp (buffer);
1447 /* Note: last row is always reserved for the mode line. */
1448 while (MATRIX_ROW_DISPLAYS_TEXT_P (row)
1449 && MATRIX_ROW_BOTTOM_Y (row) < yb)
1451 struct glyph_row *next = row + 1;
1453 if (MATRIX_ROW_DISPLAYS_TEXT_P (row))
1454 last_text_row = row;
1456 /* Check that character and byte positions are in sync. */
1457 eassert (MATRIX_ROW_START_BYTEPOS (row)
1458 == CHAR_TO_BYTE (MATRIX_ROW_START_CHARPOS (row)));
1459 eassert (BYTEPOS (row->start.pos)
1460 == CHAR_TO_BYTE (CHARPOS (row->start.pos)));
1462 /* CHAR_TO_BYTE aborts when invoked for a position > Z. We can
1463 have such a position temporarily in case of a minibuffer
1464 displaying something like `[Sole completion]' at its end. */
1465 if (MATRIX_ROW_END_CHARPOS (row) < BUF_ZV (current_buffer))
1467 eassert (MATRIX_ROW_END_BYTEPOS (row)
1468 == CHAR_TO_BYTE (MATRIX_ROW_END_CHARPOS (row)));
1469 eassert (BYTEPOS (row->end.pos)
1470 == CHAR_TO_BYTE (CHARPOS (row->end.pos)));
1473 /* Check that end position of `row' is equal to start position
1474 of next row. */
1475 if (next->enabled_p && MATRIX_ROW_DISPLAYS_TEXT_P (next))
1477 eassert (MATRIX_ROW_END_CHARPOS (row)
1478 == MATRIX_ROW_START_CHARPOS (next));
1479 eassert (MATRIX_ROW_END_BYTEPOS (row)
1480 == MATRIX_ROW_START_BYTEPOS (next));
1481 eassert (CHARPOS (row->end.pos) == CHARPOS (next->start.pos));
1482 eassert (BYTEPOS (row->end.pos) == BYTEPOS (next->start.pos));
1484 row = next;
1487 eassert (w->current_matrix->nrows == w->desired_matrix->nrows);
1488 eassert (w->desired_matrix->rows != NULL);
1489 set_buffer_temp (saved);
1492 #endif /* 0 */
1494 #endif /* GLYPH_DEBUG */
1498 /**********************************************************************
1499 Allocating/ Adjusting Glyph Matrices
1500 **********************************************************************/
1502 /* Allocate glyph matrices over a window tree for a frame-based
1503 redisplay
1505 X and Y are column/row within the frame glyph matrix where
1506 sub-matrices for the window tree rooted at WINDOW must be
1507 allocated. DIM_ONLY_P means that the caller of this
1508 function is only interested in the result matrix dimension, and
1509 matrix adjustments should not be performed.
1511 The function returns the total width/height of the sub-matrices of
1512 the window tree. If called on a frame root window, the computation
1513 will take the mini-buffer window into account.
1515 *WINDOW_CHANGE_FLAGS is set to a bit mask with bits
1517 NEW_LEAF_MATRIX set if any window in the tree did not have a
1518 glyph matrices yet, and
1520 CHANGED_LEAF_MATRIX set if the dimension or location of a matrix of
1521 any window in the tree will be changed or have been changed (see
1522 DIM_ONLY_P)
1524 *WINDOW_CHANGE_FLAGS must be initialized by the caller of this
1525 function.
1527 Windows are arranged into chains of windows on the same level
1528 through the next fields of window structures. Such a level can be
1529 either a sequence of horizontally adjacent windows from left to
1530 right, or a sequence of vertically adjacent windows from top to
1531 bottom. Each window in a horizontal sequence can be either a leaf
1532 window or a vertical sequence; a window in a vertical sequence can
1533 be either a leaf or a horizontal sequence. All windows in a
1534 horizontal sequence have the same height, and all windows in a
1535 vertical sequence have the same width.
1537 This function uses, for historical reasons, a more general
1538 algorithm to determine glyph matrix dimensions that would be
1539 necessary.
1541 The matrix height of a horizontal sequence is determined by the
1542 maximum height of any matrix in the sequence. The matrix width of
1543 a horizontal sequence is computed by adding up matrix widths of
1544 windows in the sequence.
1546 |<------- result width ------->|
1547 +---------+----------+---------+ ---
1548 | | | | |
1549 | | | |
1550 +---------+ | | result height
1551 | +---------+
1552 | | |
1553 +----------+ ---
1555 The matrix width of a vertical sequence is the maximum matrix width
1556 of any window in the sequence. Its height is computed by adding up
1557 matrix heights of windows in the sequence.
1559 |<---- result width -->|
1560 +---------+ ---
1561 | | |
1562 | | |
1563 +---------+--+ |
1564 | | |
1565 | | result height
1567 +------------+---------+ |
1568 | | |
1569 | | |
1570 +------------+---------+ --- */
1572 /* Bit indicating that a new matrix will be allocated or has been
1573 allocated. */
1575 #define NEW_LEAF_MATRIX (1 << 0)
1577 /* Bit indicating that a matrix will or has changed its location or
1578 size. */
1580 #define CHANGED_LEAF_MATRIX (1 << 1)
1582 static struct dim
1583 allocate_matrices_for_frame_redisplay (Lisp_Object window, int x, int y,
1584 bool dim_only_p, int *window_change_flags)
1586 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (window)));
1587 int x0 = x, y0 = y;
1588 int wmax = 0, hmax = 0;
1589 struct dim total;
1590 struct dim dim;
1591 struct window *w;
1592 bool in_horz_combination_p;
1594 /* What combination is WINDOW part of? Compute this once since the
1595 result is the same for all windows in the `next' chain. The
1596 special case of a root window (parent equal to nil) is treated
1597 like a vertical combination because a root window's `next'
1598 points to the mini-buffer window, if any, which is arranged
1599 vertically below other windows. */
1600 in_horz_combination_p
1601 = (!NILP (XWINDOW (window)->parent)
1602 && WINDOW_HORIZONTAL_COMBINATION_P (XWINDOW (XWINDOW (window)->parent)));
1604 /* For WINDOW and all windows on the same level. */
1607 w = XWINDOW (window);
1609 /* Get the dimension of the window sub-matrix for W, depending
1610 on whether this is a combination or a leaf window. */
1611 if (WINDOWP (w->contents))
1612 dim = allocate_matrices_for_frame_redisplay (w->contents, x, y,
1613 dim_only_p,
1614 window_change_flags);
1615 else
1617 /* If not already done, allocate sub-matrix structures. */
1618 if (w->desired_matrix == NULL)
1620 w->desired_matrix = new_glyph_matrix (f->desired_pool);
1621 w->current_matrix = new_glyph_matrix (f->current_pool);
1622 *window_change_flags |= NEW_LEAF_MATRIX;
1625 /* Width and height MUST be chosen so that there are no
1626 holes in the frame matrix. */
1627 dim.width = required_matrix_width (w);
1628 dim.height = required_matrix_height (w);
1630 /* Will matrix be re-allocated? */
1631 if (x != w->desired_matrix->matrix_x
1632 || y != w->desired_matrix->matrix_y
1633 || dim.width != w->desired_matrix->matrix_w
1634 || dim.height != w->desired_matrix->matrix_h
1635 || (margin_glyphs_to_reserve (w, dim.width,
1636 w->left_margin_cols)
1637 != w->desired_matrix->left_margin_glyphs)
1638 || (margin_glyphs_to_reserve (w, dim.width,
1639 w->right_margin_cols)
1640 != w->desired_matrix->right_margin_glyphs))
1641 *window_change_flags |= CHANGED_LEAF_MATRIX;
1643 /* Actually change matrices, if allowed. Do not consider
1644 CHANGED_LEAF_MATRIX computed above here because the pool
1645 may have been changed which we don't know here. We trust
1646 that we only will be called with DIM_ONLY_P when
1647 necessary. */
1648 if (!dim_only_p)
1650 adjust_glyph_matrix (w, w->desired_matrix, x, y, dim);
1651 adjust_glyph_matrix (w, w->current_matrix, x, y, dim);
1655 /* If we are part of a horizontal combination, advance x for
1656 windows to the right of W; otherwise advance y for windows
1657 below W. */
1658 if (in_horz_combination_p)
1659 x += dim.width;
1660 else
1661 y += dim.height;
1663 /* Remember maximum glyph matrix dimensions. */
1664 wmax = max (wmax, dim.width);
1665 hmax = max (hmax, dim.height);
1667 /* Next window on same level. */
1668 window = w->next;
1670 while (!NILP (window));
1672 /* Set `total' to the total glyph matrix dimension of this window
1673 level. In a vertical combination, the width is the width of the
1674 widest window; the height is the y we finally reached, corrected
1675 by the y we started with. In a horizontal combination, the total
1676 height is the height of the tallest window, and the width is the
1677 x we finally reached, corrected by the x we started with. */
1678 if (in_horz_combination_p)
1680 total.width = x - x0;
1681 total.height = hmax;
1683 else
1685 total.width = wmax;
1686 total.height = y - y0;
1689 return total;
1693 /* Return the required height of glyph matrices for window W. */
1695 static int
1696 required_matrix_height (struct window *w)
1698 #ifdef HAVE_WINDOW_SYSTEM
1699 struct frame *f = XFRAME (w->frame);
1701 if (FRAME_WINDOW_P (f))
1703 /* https://lists.gnu.org/r/emacs-devel/2015-11/msg00194.html */
1704 int ch_height = max (FRAME_SMALLEST_FONT_HEIGHT (f), 1);
1705 int window_pixel_height = window_box_height (w) + eabs (w->vscroll);
1707 return (((window_pixel_height + ch_height - 1)
1708 / ch_height) * w->nrows_scale_factor
1709 /* One partially visible line at the top and
1710 bottom of the window. */
1712 /* 2 for header and mode line. */
1713 + 2);
1715 #endif /* HAVE_WINDOW_SYSTEM */
1717 return WINDOW_TOTAL_LINES (w);
1721 /* Return the required width of glyph matrices for window W. */
1723 static int
1724 required_matrix_width (struct window *w)
1726 #ifdef HAVE_WINDOW_SYSTEM
1727 struct frame *f = XFRAME (w->frame);
1728 if (FRAME_WINDOW_P (f))
1730 /* https://lists.gnu.org/r/emacs-devel/2015-11/msg00194.html */
1731 int ch_width = max (FRAME_SMALLEST_CHAR_WIDTH (f), 1);
1733 /* Compute number of glyphs needed in a glyph row. */
1734 return (((WINDOW_PIXEL_WIDTH (w) + ch_width - 1)
1735 / ch_width) * w->ncols_scale_factor
1736 /* 2 partially visible columns in the text area. */
1738 /* One partially visible column at the right
1739 edge of each marginal area. */
1740 + 1 + 1);
1742 #endif /* HAVE_WINDOW_SYSTEM */
1744 return w->total_cols;
1748 /* Allocate window matrices for window-based redisplay. W is the
1749 window whose matrices must be allocated/reallocated. */
1751 static void
1752 allocate_matrices_for_window_redisplay (struct window *w)
1754 while (w)
1756 if (WINDOWP (w->contents))
1757 allocate_matrices_for_window_redisplay (XWINDOW (w->contents));
1758 else
1760 /* W is a leaf window. */
1761 struct dim dim;
1763 /* If matrices are not yet allocated, allocate them now. */
1764 if (w->desired_matrix == NULL)
1766 w->desired_matrix = new_glyph_matrix (NULL);
1767 w->current_matrix = new_glyph_matrix (NULL);
1770 dim.width = required_matrix_width (w);
1771 dim.height = required_matrix_height (w);
1772 adjust_glyph_matrix (w, w->desired_matrix, 0, 0, dim);
1773 adjust_glyph_matrix (w, w->current_matrix, 0, 0, dim);
1776 w = NILP (w->next) ? NULL : XWINDOW (w->next);
1780 /* Allocate/reallocate glyph matrices of a single frame F.
1781 This function must be called when a new frame is created,
1782 its size changes, or its window configuration changes. */
1784 void
1785 adjust_frame_glyphs (struct frame *f)
1787 /* Block input so that expose events and other events that access
1788 glyph matrices are not processed while we are changing them. */
1789 block_input ();
1791 if (FRAME_WINDOW_P (f))
1792 adjust_frame_glyphs_for_window_redisplay (f);
1793 else
1794 adjust_frame_glyphs_for_frame_redisplay (f);
1796 /* Don't forget the buffer for decode_mode_spec. */
1797 adjust_decode_mode_spec_buffer (f);
1799 f->glyphs_initialized_p = 1;
1801 unblock_input ();
1804 /* Return true if any window in the tree has nonzero window margins. See
1805 the hack at the end of adjust_frame_glyphs_for_frame_redisplay. */
1806 static bool
1807 showing_window_margins_p (struct window *w)
1809 while (w)
1811 if (WINDOWP (w->contents))
1813 if (showing_window_margins_p (XWINDOW (w->contents)))
1814 return 1;
1816 else if (w->left_margin_cols > 0 || w->right_margin_cols > 0)
1817 return 1;
1819 w = NILP (w->next) ? 0 : XWINDOW (w->next);
1821 return 0;
1825 /* In the window tree with root W, build current matrices of leaf
1826 windows from the frame's current matrix. */
1828 static void
1829 fake_current_matrices (Lisp_Object window)
1831 struct window *w;
1833 for (; !NILP (window); window = w->next)
1835 w = XWINDOW (window);
1837 if (WINDOWP (w->contents))
1838 fake_current_matrices (w->contents);
1839 else
1841 int i;
1842 struct frame *f = XFRAME (w->frame);
1843 struct glyph_matrix *m = w->current_matrix;
1844 struct glyph_matrix *fm = f->current_matrix;
1846 eassert (m->matrix_h == WINDOW_TOTAL_LINES (w));
1847 eassert (m->matrix_w == WINDOW_TOTAL_COLS (w));
1849 for (i = 0; i < m->matrix_h; ++i)
1851 struct glyph_row *r = m->rows + i;
1852 struct glyph_row *fr = fm->rows + i + WINDOW_TOP_EDGE_LINE (w);
1854 eassert (r->glyphs[TEXT_AREA] >= fr->glyphs[TEXT_AREA]
1855 && r->glyphs[LAST_AREA] <= fr->glyphs[LAST_AREA]);
1857 r->enabled_p = fr->enabled_p;
1858 if (r->enabled_p)
1860 r->used[LEFT_MARGIN_AREA] = m->left_margin_glyphs;
1861 r->used[RIGHT_MARGIN_AREA] = m->right_margin_glyphs;
1862 r->used[TEXT_AREA] = (m->matrix_w
1863 - r->used[LEFT_MARGIN_AREA]
1864 - r->used[RIGHT_MARGIN_AREA]);
1865 r->mode_line_p = 0;
1873 /* Save away the contents of frame F's current frame matrix. Value is
1874 a glyph matrix holding the contents of F's current frame matrix. */
1876 static struct glyph_matrix *
1877 save_current_matrix (struct frame *f)
1879 int i;
1880 struct glyph_matrix *saved = xzalloc (sizeof *saved);
1881 saved->nrows = f->current_matrix->nrows;
1882 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
1884 for (i = 0; i < saved->nrows; ++i)
1886 struct glyph_row *from = f->current_matrix->rows + i;
1887 struct glyph_row *to = saved->rows + i;
1888 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
1890 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
1891 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
1892 to->used[TEXT_AREA] = from->used[TEXT_AREA];
1893 to->enabled_p = from->enabled_p;
1894 to->hash = from->hash;
1895 if (from->used[LEFT_MARGIN_AREA])
1897 nbytes = from->used[LEFT_MARGIN_AREA] * sizeof (struct glyph);
1898 to->glyphs[LEFT_MARGIN_AREA] = xmalloc (nbytes);
1899 memcpy (to->glyphs[LEFT_MARGIN_AREA],
1900 from->glyphs[LEFT_MARGIN_AREA], nbytes);
1901 to->used[LEFT_MARGIN_AREA] = from->used[LEFT_MARGIN_AREA];
1903 if (from->used[RIGHT_MARGIN_AREA])
1905 nbytes = from->used[RIGHT_MARGIN_AREA] * sizeof (struct glyph);
1906 to->glyphs[RIGHT_MARGIN_AREA] = xmalloc (nbytes);
1907 memcpy (to->glyphs[RIGHT_MARGIN_AREA],
1908 from->glyphs[RIGHT_MARGIN_AREA], nbytes);
1909 to->used[RIGHT_MARGIN_AREA] = from->used[RIGHT_MARGIN_AREA];
1913 return saved;
1917 /* Restore the contents of frame F's current frame matrix from SAVED,
1918 and free memory associated with SAVED. */
1920 static void
1921 restore_current_matrix (struct frame *f, struct glyph_matrix *saved)
1923 int i;
1925 for (i = 0; i < saved->nrows; ++i)
1927 struct glyph_row *from = saved->rows + i;
1928 struct glyph_row *to = f->current_matrix->rows + i;
1929 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
1931 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
1932 to->used[TEXT_AREA] = from->used[TEXT_AREA];
1933 xfree (from->glyphs[TEXT_AREA]);
1934 nbytes = from->used[LEFT_MARGIN_AREA] * sizeof (struct glyph);
1935 if (nbytes)
1937 memcpy (to->glyphs[LEFT_MARGIN_AREA],
1938 from->glyphs[LEFT_MARGIN_AREA], nbytes);
1939 to->used[LEFT_MARGIN_AREA] = from->used[LEFT_MARGIN_AREA];
1940 xfree (from->glyphs[LEFT_MARGIN_AREA]);
1942 else
1943 to->used[LEFT_MARGIN_AREA] = 0;
1944 nbytes = from->used[RIGHT_MARGIN_AREA] * sizeof (struct glyph);
1945 if (nbytes)
1947 memcpy (to->glyphs[RIGHT_MARGIN_AREA],
1948 from->glyphs[RIGHT_MARGIN_AREA], nbytes);
1949 to->used[RIGHT_MARGIN_AREA] = from->used[RIGHT_MARGIN_AREA];
1950 xfree (from->glyphs[RIGHT_MARGIN_AREA]);
1952 else
1953 to->used[RIGHT_MARGIN_AREA] = 0;
1956 xfree (saved->rows);
1957 xfree (saved);
1962 /* Allocate/reallocate glyph matrices of a single frame F for
1963 frame-based redisplay. */
1965 static void
1966 adjust_frame_glyphs_for_frame_redisplay (struct frame *f)
1968 struct dim matrix_dim;
1969 bool pool_changed_p;
1970 int window_change_flags;
1971 int top_window_y;
1973 if (!FRAME_LIVE_P (f))
1974 return;
1976 top_window_y = FRAME_TOP_MARGIN (f);
1978 /* Allocate glyph pool structures if not already done. */
1979 if (f->desired_pool == NULL)
1981 f->desired_pool = new_glyph_pool ();
1982 f->current_pool = new_glyph_pool ();
1985 /* Allocate frames matrix structures if needed. */
1986 if (f->desired_matrix == NULL)
1988 f->desired_matrix = new_glyph_matrix (f->desired_pool);
1989 f->current_matrix = new_glyph_matrix (f->current_pool);
1992 /* Compute window glyph matrices. (This takes the mini-buffer
1993 window into account). The result is the size of the frame glyph
1994 matrix needed. The variable window_change_flags is set to a bit
1995 mask indicating whether new matrices will be allocated or
1996 existing matrices change their size or location within the frame
1997 matrix. */
1998 window_change_flags = 0;
1999 matrix_dim
2000 = allocate_matrices_for_frame_redisplay (FRAME_ROOT_WINDOW (f),
2001 0, top_window_y,
2003 &window_change_flags);
2005 /* Add in menu bar lines, if any. */
2006 matrix_dim.height += top_window_y;
2008 /* Enlarge pools as necessary. */
2009 pool_changed_p = realloc_glyph_pool (f->desired_pool, matrix_dim);
2010 realloc_glyph_pool (f->current_pool, matrix_dim);
2012 /* Set up glyph pointers within window matrices. Do this only if
2013 absolutely necessary since it requires a frame redraw. */
2014 if (pool_changed_p || window_change_flags)
2016 /* Do it for window matrices. */
2017 allocate_matrices_for_frame_redisplay (FRAME_ROOT_WINDOW (f),
2018 0, top_window_y, 0,
2019 &window_change_flags);
2021 /* Size of frame matrices must equal size of frame. Note
2022 that we are called for X frames with window widths NOT equal
2023 to the frame width (from CHANGE_FRAME_SIZE_1). */
2024 if (matrix_dim.width != FRAME_TOTAL_COLS (f)
2025 || matrix_dim.height != FRAME_TOTAL_LINES (f))
2026 return;
2028 eassert (matrix_dim.width == FRAME_TOTAL_COLS (f)
2029 && matrix_dim.height == FRAME_TOTAL_LINES (f));
2031 /* Pointers to glyph memory in glyph rows are exchanged during
2032 the update phase of redisplay, which means in general that a
2033 frame's current matrix consists of pointers into both the
2034 desired and current glyph pool of the frame. Adjusting a
2035 matrix sets the frame matrix up so that pointers are all into
2036 the same pool. If we want to preserve glyph contents of the
2037 current matrix over a call to adjust_glyph_matrix, we must
2038 make a copy of the current glyphs, and restore the current
2039 matrix' contents from that copy. */
2040 if (display_completed
2041 && !FRAME_GARBAGED_P (f)
2042 && matrix_dim.width == f->current_matrix->matrix_w
2043 && matrix_dim.height == f->current_matrix->matrix_h
2044 /* For some reason, the frame glyph matrix gets corrupted if
2045 any of the windows contain margins. I haven't been able
2046 to hunt down the reason, but for the moment this prevents
2047 the problem from manifesting. -- cyd */
2048 && !showing_window_margins_p (XWINDOW (FRAME_ROOT_WINDOW (f))))
2050 struct glyph_matrix *copy = save_current_matrix (f);
2051 adjust_glyph_matrix (NULL, f->desired_matrix, 0, 0, matrix_dim);
2052 adjust_glyph_matrix (NULL, f->current_matrix, 0, 0, matrix_dim);
2053 restore_current_matrix (f, copy);
2054 fake_current_matrices (FRAME_ROOT_WINDOW (f));
2056 else
2058 adjust_glyph_matrix (NULL, f->desired_matrix, 0, 0, matrix_dim);
2059 adjust_glyph_matrix (NULL, f->current_matrix, 0, 0, matrix_dim);
2060 SET_FRAME_GARBAGED (f);
2066 /* Allocate/reallocate glyph matrices of a single frame F for
2067 window-based redisplay. */
2069 static void
2070 adjust_frame_glyphs_for_window_redisplay (struct frame *f)
2072 eassert (FRAME_WINDOW_P (f) && FRAME_LIVE_P (f));
2074 /* Allocate/reallocate window matrices. */
2075 allocate_matrices_for_window_redisplay (XWINDOW (FRAME_ROOT_WINDOW (f)));
2077 #if defined (HAVE_X_WINDOWS) && ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
2078 /* Allocate/ reallocate matrices of the dummy window used to display
2079 the menu bar under X when no X toolkit support is available. */
2081 /* Allocate a dummy window if not already done. */
2082 struct window *w;
2083 if (NILP (f->menu_bar_window))
2085 Lisp_Object frame;
2086 fset_menu_bar_window (f, make_window ());
2087 w = XWINDOW (f->menu_bar_window);
2088 XSETFRAME (frame, f);
2089 wset_frame (w, frame);
2090 w->pseudo_window_p = 1;
2092 else
2093 w = XWINDOW (f->menu_bar_window);
2095 /* Set window dimensions to frame dimensions and allocate or
2096 adjust glyph matrices of W. */
2097 w->pixel_left = 0;
2098 w->left_col = 0;
2099 w->pixel_top = 0;
2100 w->top_line = 0;
2101 w->pixel_width = (FRAME_PIXEL_WIDTH (f)
2102 - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
2103 w->total_cols = FRAME_TOTAL_COLS (f);
2104 w->pixel_height = FRAME_MENU_BAR_HEIGHT (f);
2105 w->total_lines = FRAME_MENU_BAR_LINES (f);
2106 allocate_matrices_for_window_redisplay (w);
2108 #endif
2110 #if defined (HAVE_WINDOW_SYSTEM) && ! defined (USE_GTK) && ! defined (HAVE_NS)
2112 /* Allocate/ reallocate matrices of the tool bar window. If we
2113 don't have a tool bar window yet, make one. */
2114 struct window *w;
2115 if (NILP (f->tool_bar_window))
2117 Lisp_Object frame;
2118 fset_tool_bar_window (f, make_window ());
2119 w = XWINDOW (f->tool_bar_window);
2120 XSETFRAME (frame, f);
2121 wset_frame (w, frame);
2122 w->pseudo_window_p = 1;
2124 else
2125 w = XWINDOW (f->tool_bar_window);
2127 w->pixel_left = 0;
2128 w->left_col = 0;
2129 w->pixel_top = FRAME_MENU_BAR_HEIGHT (f);
2130 w->top_line = FRAME_MENU_BAR_LINES (f);
2131 w->total_cols = FRAME_TOTAL_COLS (f);
2132 w->pixel_width = (FRAME_PIXEL_WIDTH (f)
2133 - 2 * FRAME_INTERNAL_BORDER_WIDTH (f));
2134 w->total_lines = FRAME_TOOL_BAR_LINES (f);
2135 w->pixel_height = FRAME_TOOL_BAR_HEIGHT (f);
2136 allocate_matrices_for_window_redisplay (w);
2138 #endif
2142 /* Re-allocate buffer for decode_mode_spec on frame F. */
2144 static void
2145 adjust_decode_mode_spec_buffer (struct frame *f)
2147 int frame_message_buf_size = FRAME_MESSAGE_BUF_SIZE (f);
2149 eassert (frame_message_buf_size >= 0);
2150 f->decode_mode_spec_buffer = xrealloc (f->decode_mode_spec_buffer,
2151 frame_message_buf_size + 1);
2156 /**********************************************************************
2157 Freeing Glyph Matrices
2158 **********************************************************************/
2160 /* Free glyph memory for a frame F. F may be null. This function can
2161 be called for the same frame more than once. The root window of
2162 F may be nil when this function is called. This is the case when
2163 the function is called when F is destroyed. */
2165 void
2166 free_glyphs (struct frame *f)
2168 if (f && f->glyphs_initialized_p)
2170 /* Block interrupt input so that we don't get surprised by an X
2171 event while we're in an inconsistent state. */
2172 block_input ();
2173 f->glyphs_initialized_p = 0;
2175 /* Release window sub-matrices. */
2176 if (!NILP (f->root_window))
2177 free_window_matrices (XWINDOW (f->root_window));
2179 #if defined (HAVE_X_WINDOWS) && ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
2180 /* Free the dummy window for menu bars without X toolkit and its
2181 glyph matrices. */
2182 if (!NILP (f->menu_bar_window))
2184 struct window *w = XWINDOW (f->menu_bar_window);
2185 free_glyph_matrix (w->desired_matrix);
2186 free_glyph_matrix (w->current_matrix);
2187 w->desired_matrix = w->current_matrix = NULL;
2188 fset_menu_bar_window (f, Qnil);
2190 #endif
2192 #if defined (HAVE_WINDOW_SYSTEM) && ! defined (USE_GTK) && ! defined (HAVE_NS)
2193 /* Free the tool bar window and its glyph matrices. */
2194 if (!NILP (f->tool_bar_window))
2196 struct window *w = XWINDOW (f->tool_bar_window);
2197 free_glyph_matrix (w->desired_matrix);
2198 free_glyph_matrix (w->current_matrix);
2199 w->desired_matrix = w->current_matrix = NULL;
2200 fset_tool_bar_window (f, Qnil);
2202 #endif
2204 /* Release frame glyph matrices. Reset fields to zero in
2205 case we are called a second time. */
2206 if (f->desired_matrix)
2208 free_glyph_matrix (f->desired_matrix);
2209 free_glyph_matrix (f->current_matrix);
2210 f->desired_matrix = f->current_matrix = NULL;
2213 /* Release glyph pools. */
2214 if (f->desired_pool)
2216 free_glyph_pool (f->desired_pool);
2217 free_glyph_pool (f->current_pool);
2218 f->desired_pool = f->current_pool = NULL;
2221 unblock_input ();
2226 /* Free glyph sub-matrices in the window tree rooted at W. This
2227 function may be called with a null pointer, and it may be called on
2228 the same tree more than once. */
2230 void
2231 free_window_matrices (struct window *w)
2233 while (w)
2235 if (WINDOWP (w->contents))
2236 free_window_matrices (XWINDOW (w->contents));
2237 else
2239 /* This is a leaf window. Free its memory and reset fields
2240 to zero in case this function is called a second time for
2241 W. */
2242 free_glyph_matrix (w->current_matrix);
2243 free_glyph_matrix (w->desired_matrix);
2244 w->current_matrix = w->desired_matrix = NULL;
2247 /* Next window on same level. */
2248 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2253 /* Check glyph memory leaks. This function is called from
2254 shut_down_emacs. Note that frames are not destroyed when Emacs
2255 exits. We therefore free all glyph memory for all active frames
2256 explicitly and check that nothing is left allocated. */
2258 void
2259 check_glyph_memory (void)
2261 Lisp_Object tail, frame;
2263 /* Free glyph memory for all frames. */
2264 FOR_EACH_FRAME (tail, frame)
2265 free_glyphs (XFRAME (frame));
2267 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
2268 /* Check that nothing is left allocated. */
2269 eassert (glyph_matrix_count == 0);
2270 eassert (glyph_pool_count == 0);
2271 #endif
2276 /**********************************************************************
2277 Building a Frame Matrix
2278 **********************************************************************/
2280 /* Most of the redisplay code works on glyph matrices attached to
2281 windows. This is a good solution most of the time, but it is not
2282 suitable for terminal code. Terminal output functions cannot rely
2283 on being able to set an arbitrary terminal window. Instead they
2284 must be provided with a view of the whole frame, i.e. the whole
2285 screen. We build such a view by constructing a frame matrix from
2286 window matrices in this section.
2288 Windows that must be updated have their must_be_updated_p flag set.
2289 For all such windows, their desired matrix is made part of the
2290 desired frame matrix. For other windows, their current matrix is
2291 made part of the desired frame matrix.
2293 +-----------------+----------------+
2294 | desired | desired |
2295 | | |
2296 +-----------------+----------------+
2297 | current |
2299 +----------------------------------+
2301 Desired window matrices can be made part of the frame matrix in a
2302 cheap way: We exploit the fact that the desired frame matrix and
2303 desired window matrices share their glyph memory. This is not
2304 possible for current window matrices. Their glyphs are copied to
2305 the desired frame matrix. The latter is equivalent to
2306 preserve_other_columns in the old redisplay.
2308 Used glyphs counters for frame matrix rows are the result of adding
2309 up glyph lengths of the window matrices. A line in the frame
2310 matrix is enabled, if a corresponding line in a window matrix is
2311 enabled.
2313 After building the desired frame matrix, it will be passed to
2314 terminal code, which will manipulate both the desired and current
2315 frame matrix. Changes applied to the frame's current matrix have
2316 to be visible in current window matrices afterwards, of course.
2318 This problem is solved like this:
2320 1. Window and frame matrices share glyphs. Window matrices are
2321 constructed in a way that their glyph contents ARE the glyph
2322 contents needed in a frame matrix. Thus, any modification of
2323 glyphs done in terminal code will be reflected in window matrices
2324 automatically.
2326 2. Exchanges of rows in a frame matrix done by terminal code are
2327 intercepted by hook functions so that corresponding row operations
2328 on window matrices can be performed. This is necessary because we
2329 use pointers to glyphs in glyph row structures. To satisfy the
2330 assumption of point 1 above that glyphs are updated implicitly in
2331 window matrices when they are manipulated via the frame matrix,
2332 window and frame matrix must of course agree where to find the
2333 glyphs for their rows. Possible manipulations that must be
2334 mirrored are assignments of rows of the desired frame matrix to the
2335 current frame matrix and scrolling the current frame matrix. */
2337 /* Build frame F's desired matrix from window matrices. Only windows
2338 which have the flag must_be_updated_p set have to be updated. Menu
2339 bar lines of a frame are not covered by window matrices, so make
2340 sure not to touch them in this function. */
2342 static void
2343 build_frame_matrix (struct frame *f)
2345 int i;
2347 /* F must have a frame matrix when this function is called. */
2348 eassert (!FRAME_WINDOW_P (f));
2350 /* Clear all rows in the frame matrix covered by window matrices.
2351 Menu bar lines are not covered by windows. */
2352 for (i = FRAME_TOP_MARGIN (f); i < f->desired_matrix->nrows; ++i)
2353 clear_glyph_row (MATRIX_ROW (f->desired_matrix, i));
2355 /* Build the matrix by walking the window tree. */
2356 build_frame_matrix_from_window_tree (f->desired_matrix,
2357 XWINDOW (FRAME_ROOT_WINDOW (f)));
2361 /* Walk a window tree, building a frame matrix MATRIX from window
2362 matrices. W is the root of a window tree. */
2364 static void
2365 build_frame_matrix_from_window_tree (struct glyph_matrix *matrix, struct window *w)
2367 while (w)
2369 if (WINDOWP (w->contents))
2370 build_frame_matrix_from_window_tree (matrix, XWINDOW (w->contents));
2371 else
2372 build_frame_matrix_from_leaf_window (matrix, w);
2374 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2379 /* Add a window's matrix to a frame matrix. FRAME_MATRIX is the
2380 desired frame matrix built. W is a leaf window whose desired or
2381 current matrix is to be added to FRAME_MATRIX. W's flag
2382 must_be_updated_p determines which matrix it contributes to
2383 FRAME_MATRIX. If W->must_be_updated_p, W's desired matrix
2384 is added to FRAME_MATRIX, otherwise W's current matrix is added.
2385 Adding a desired matrix means setting up used counters and such in
2386 frame rows, while adding a current window matrix to FRAME_MATRIX
2387 means copying glyphs. The latter case corresponds to
2388 preserve_other_columns in the old redisplay. */
2390 static void
2391 build_frame_matrix_from_leaf_window (struct glyph_matrix *frame_matrix, struct window *w)
2393 struct glyph_matrix *window_matrix;
2394 int window_y, frame_y;
2395 /* If non-zero, a glyph to insert at the right border of W. */
2396 GLYPH right_border_glyph;
2398 SET_GLYPH_FROM_CHAR (right_border_glyph, 0);
2400 /* Set window_matrix to the matrix we have to add to FRAME_MATRIX. */
2401 if (w->must_be_updated_p)
2403 window_matrix = w->desired_matrix;
2405 /* Decide whether we want to add a vertical border glyph. */
2406 if (!WINDOW_RIGHTMOST_P (w))
2408 struct Lisp_Char_Table *dp = window_display_table (w);
2409 Lisp_Object gc;
2411 SET_GLYPH_FROM_CHAR (right_border_glyph, '|');
2412 if (dp
2413 && (gc = DISP_BORDER_GLYPH (dp), GLYPH_CODE_P (gc)))
2415 SET_GLYPH_FROM_GLYPH_CODE (right_border_glyph, gc);
2416 spec_glyph_lookup_face (w, &right_border_glyph);
2419 if (GLYPH_FACE (right_border_glyph) <= 0)
2420 SET_GLYPH_FACE (right_border_glyph, VERTICAL_BORDER_FACE_ID);
2423 else
2424 window_matrix = w->current_matrix;
2426 /* For all rows in the window matrix and corresponding rows in the
2427 frame matrix. */
2428 window_y = 0;
2429 frame_y = window_matrix->matrix_y;
2430 while (window_y < window_matrix->nrows)
2432 struct glyph_row *frame_row = frame_matrix->rows + frame_y;
2433 struct glyph_row *window_row = window_matrix->rows + window_y;
2434 bool current_row_p = window_matrix == w->current_matrix;
2436 /* Fill up the frame row with spaces up to the left margin of the
2437 window row. */
2438 fill_up_frame_row_with_spaces (frame_row, window_matrix->matrix_x);
2440 /* Fill up areas in the window matrix row with spaces. */
2441 fill_up_glyph_row_with_spaces (window_row);
2443 /* If only part of W's desired matrix has been built, and
2444 window_row wasn't displayed, use the corresponding current
2445 row instead. */
2446 if (window_matrix == w->desired_matrix
2447 && !window_row->enabled_p)
2449 window_row = w->current_matrix->rows + window_y;
2450 current_row_p = 1;
2453 if (current_row_p)
2455 /* Copy window row to frame row. */
2456 memcpy (frame_row->glyphs[TEXT_AREA] + window_matrix->matrix_x,
2457 window_row->glyphs[0],
2458 window_matrix->matrix_w * sizeof (struct glyph));
2460 else
2462 eassert (window_row->enabled_p);
2464 /* Only when a desired row has been displayed, we want
2465 the corresponding frame row to be updated. */
2466 frame_row->enabled_p = true;
2468 /* Maybe insert a vertical border between horizontally adjacent
2469 windows. */
2470 if (GLYPH_CHAR (right_border_glyph) != 0)
2472 struct glyph *border = window_row->glyphs[LAST_AREA] - 1;
2473 SET_CHAR_GLYPH_FROM_GLYPH (*border, right_border_glyph);
2476 #ifdef GLYPH_DEBUG
2477 /* Window row window_y must be a slice of frame row
2478 frame_y. */
2479 eassert (glyph_row_slice_p (window_row, frame_row));
2481 /* If rows are in sync, we don't have to copy glyphs because
2482 frame and window share glyphs. */
2484 strcpy (w->current_matrix->method, w->desired_matrix->method);
2485 add_window_display_history (w, w->current_matrix->method, 0);
2486 #endif
2489 /* Set number of used glyphs in the frame matrix. Since we fill
2490 up with spaces, and visit leaf windows from left to right it
2491 can be done simply. */
2492 frame_row->used[TEXT_AREA]
2493 = window_matrix->matrix_x + window_matrix->matrix_w;
2495 /* Next row. */
2496 ++window_y;
2497 ++frame_y;
2501 /* Given a user-specified glyph, possibly including a Lisp-level face
2502 ID, return a glyph that has a realized face ID.
2503 This is used for glyphs displayed specially and not part of the text;
2504 for instance, vertical separators, truncation markers, etc. */
2506 void
2507 spec_glyph_lookup_face (struct window *w, GLYPH *glyph)
2509 int lface_id = GLYPH_FACE (*glyph);
2510 /* Convert the glyph's specified face to a realized (cache) face. */
2511 if (lface_id > 0)
2513 int face_id = merge_faces (XFRAME (w->frame),
2514 Qt, lface_id, DEFAULT_FACE_ID);
2515 SET_GLYPH_FACE (*glyph, face_id);
2519 /* Add spaces to a glyph row ROW in a window matrix.
2521 Each row has the form:
2523 +---------+-----------------------------+------------+
2524 | left | text | right |
2525 +---------+-----------------------------+------------+
2527 Left and right marginal areas are optional. This function adds
2528 spaces to areas so that there are no empty holes between areas.
2529 In other words: If the right area is not empty, the text area
2530 is filled up with spaces up to the right area. If the text area
2531 is not empty, the left area is filled up.
2533 To be called for frame-based redisplay, only. */
2535 static void
2536 fill_up_glyph_row_with_spaces (struct glyph_row *row)
2538 fill_up_glyph_row_area_with_spaces (row, LEFT_MARGIN_AREA);
2539 fill_up_glyph_row_area_with_spaces (row, TEXT_AREA);
2540 fill_up_glyph_row_area_with_spaces (row, RIGHT_MARGIN_AREA);
2544 /* Fill area AREA of glyph row ROW with spaces. To be called for
2545 frame-based redisplay only. */
2547 static void
2548 fill_up_glyph_row_area_with_spaces (struct glyph_row *row, int area)
2550 if (row->glyphs[area] < row->glyphs[area + 1])
2552 struct glyph *end = row->glyphs[area + 1];
2553 struct glyph *text = row->glyphs[area] + row->used[area];
2555 while (text < end)
2556 *text++ = space_glyph;
2557 row->used[area] = text - row->glyphs[area];
2562 /* Add spaces to the end of ROW in a frame matrix until index UPTO is
2563 reached. In frame matrices only one area, TEXT_AREA, is used. */
2565 void
2566 fill_up_frame_row_with_spaces (struct glyph_row *row, int upto)
2568 int i = row->used[TEXT_AREA];
2569 struct glyph *glyph = row->glyphs[TEXT_AREA];
2571 while (i < upto)
2572 glyph[i++] = space_glyph;
2574 row->used[TEXT_AREA] = i;
2579 /**********************************************************************
2580 Mirroring operations on frame matrices in window matrices
2581 **********************************************************************/
2583 /* Set frame being updated via frame-based redisplay to F. This
2584 function must be called before updates to make explicit that we are
2585 working on frame matrices or not. */
2587 static void
2588 set_frame_matrix_frame (struct frame *f)
2590 frame_matrix_frame = f;
2594 /* Make sure glyph row ROW in CURRENT_MATRIX is up to date.
2595 DESIRED_MATRIX is the desired matrix corresponding to
2596 CURRENT_MATRIX. The update is done by exchanging glyph pointers
2597 between rows in CURRENT_MATRIX and DESIRED_MATRIX. If
2598 frame_matrix_frame is non-null, this indicates that the exchange is
2599 done in frame matrices, and that we have to perform analogous
2600 operations in window matrices of frame_matrix_frame. */
2602 static void
2603 make_current (struct glyph_matrix *desired_matrix, struct glyph_matrix *current_matrix, int row)
2605 struct glyph_row *current_row = MATRIX_ROW (current_matrix, row);
2606 struct glyph_row *desired_row = MATRIX_ROW (desired_matrix, row);
2607 bool mouse_face_p = current_row->mouse_face_p;
2609 /* Do current_row = desired_row. This exchanges glyph pointers
2610 between both rows, and does a structure assignment otherwise. */
2611 assign_row (current_row, desired_row);
2613 /* Enable current_row to mark it as valid. */
2614 current_row->enabled_p = true;
2615 current_row->mouse_face_p = mouse_face_p;
2617 /* If we are called on frame matrices, perform analogous operations
2618 for window matrices. */
2619 if (frame_matrix_frame)
2620 mirror_make_current (XWINDOW (frame_matrix_frame->root_window), row);
2624 /* W is the root of a window tree. FRAME_ROW is the index of a row in
2625 W's frame which has been made current (by swapping pointers between
2626 current and desired matrix). Perform analogous operations in the
2627 matrices of leaf windows in the window tree rooted at W. */
2629 static void
2630 mirror_make_current (struct window *w, int frame_row)
2632 while (w)
2634 if (WINDOWP (w->contents))
2635 mirror_make_current (XWINDOW (w->contents), frame_row);
2636 else
2638 /* Row relative to window W. Don't use FRAME_TO_WINDOW_VPOS
2639 here because the checks performed in debug mode there
2640 will not allow the conversion. */
2641 int row = frame_row - w->desired_matrix->matrix_y;
2643 /* If FRAME_ROW is within W, assign the desired row to the
2644 current row (exchanging glyph pointers). */
2645 if (row >= 0 && row < w->desired_matrix->matrix_h)
2647 struct glyph_row *current_row
2648 = MATRIX_ROW (w->current_matrix, row);
2649 struct glyph_row *desired_row
2650 = MATRIX_ROW (w->desired_matrix, row);
2652 if (desired_row->enabled_p)
2653 assign_row (current_row, desired_row);
2654 else
2655 swap_glyph_pointers (desired_row, current_row);
2656 current_row->enabled_p = true;
2658 /* Set the Y coordinate of the mode/header line's row.
2659 It is needed in draw_row_with_mouse_face to find the
2660 screen coordinates. (Window-based redisplay sets
2661 this in update_window, but no one seems to do that
2662 for frame-based redisplay.) */
2663 if (current_row->mode_line_p)
2664 current_row->y = row;
2668 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2673 /* Perform row dance after scrolling. We are working on the range of
2674 lines UNCHANGED_AT_TOP + 1 to UNCHANGED_AT_TOP + NLINES (not
2675 including) in MATRIX. COPY_FROM is a vector containing, for each
2676 row I in the range 0 <= I < NLINES, the index of the original line
2677 to move to I. This index is relative to the row range, i.e. 0 <=
2678 index < NLINES. RETAINED_P is a vector containing zero for each
2679 row 0 <= I < NLINES which is empty.
2681 This function is called from do_scrolling and do_direct_scrolling. */
2683 void
2684 mirrored_line_dance (struct glyph_matrix *matrix, int unchanged_at_top, int nlines,
2685 int *copy_from, char *retained_p)
2687 /* A copy of original rows. */
2688 struct glyph_row *old_rows;
2690 /* Rows to assign to. */
2691 struct glyph_row *new_rows = MATRIX_ROW (matrix, unchanged_at_top);
2693 int i;
2695 /* Make a copy of the original rows. */
2696 USE_SAFE_ALLOCA;
2697 SAFE_NALLOCA (old_rows, 1, nlines);
2698 memcpy (old_rows, new_rows, nlines * sizeof *old_rows);
2700 /* Assign new rows, maybe clear lines. */
2701 for (i = 0; i < nlines; ++i)
2703 bool enabled_before_p = new_rows[i].enabled_p;
2705 eassert (i + unchanged_at_top < matrix->nrows);
2706 eassert (unchanged_at_top + copy_from[i] < matrix->nrows);
2707 new_rows[i] = old_rows[copy_from[i]];
2708 new_rows[i].enabled_p = enabled_before_p;
2710 /* RETAINED_P is zero for empty lines. */
2711 if (!retained_p[copy_from[i]])
2712 new_rows[i].enabled_p = false;
2715 /* Do the same for window matrices, if MATRIX is a frame matrix. */
2716 if (frame_matrix_frame)
2717 mirror_line_dance (XWINDOW (frame_matrix_frame->root_window),
2718 unchanged_at_top, nlines, copy_from, retained_p);
2720 SAFE_FREE ();
2724 /* Synchronize glyph pointers in the current matrix of window W with
2725 the current frame matrix. */
2727 static void
2728 sync_window_with_frame_matrix_rows (struct window *w)
2730 struct frame *f = XFRAME (w->frame);
2731 struct glyph_row *window_row, *window_row_end, *frame_row;
2732 int left, right, x, width;
2734 /* Preconditions: W must be a live window on a tty frame. */
2735 eassert (BUFFERP (w->contents));
2736 eassert (!FRAME_WINDOW_P (f));
2738 left = margin_glyphs_to_reserve (w, 1, w->left_margin_cols);
2739 right = margin_glyphs_to_reserve (w, 1, w->right_margin_cols);
2740 x = w->current_matrix->matrix_x;
2741 width = w->current_matrix->matrix_w;
2743 window_row = w->current_matrix->rows;
2744 window_row_end = window_row + w->current_matrix->nrows;
2745 frame_row = f->current_matrix->rows + WINDOW_TOP_EDGE_LINE (w);
2747 for (; window_row < window_row_end; ++window_row, ++frame_row)
2749 window_row->glyphs[LEFT_MARGIN_AREA]
2750 = frame_row->glyphs[0] + x;
2751 window_row->glyphs[TEXT_AREA]
2752 = window_row->glyphs[LEFT_MARGIN_AREA] + left;
2753 window_row->glyphs[LAST_AREA]
2754 = window_row->glyphs[LEFT_MARGIN_AREA] + width;
2755 window_row->glyphs[RIGHT_MARGIN_AREA]
2756 = window_row->glyphs[LAST_AREA] - right;
2761 /* Return the window in the window tree rooted in W containing frame
2762 row ROW. Value is null if none is found. */
2764 static struct window *
2765 frame_row_to_window (struct window *w, int row)
2767 struct window *found = NULL;
2769 while (w && !found)
2771 if (WINDOWP (w->contents))
2772 found = frame_row_to_window (XWINDOW (w->contents), row);
2773 else if (row >= WINDOW_TOP_EDGE_LINE (w)
2774 && row < WINDOW_BOTTOM_EDGE_LINE (w))
2775 found = w;
2777 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2780 return found;
2784 /* Perform a line dance in the window tree rooted at W, after
2785 scrolling a frame matrix in mirrored_line_dance.
2787 We are working on the range of lines UNCHANGED_AT_TOP + 1 to
2788 UNCHANGED_AT_TOP + NLINES (not including) in W's frame matrix.
2789 COPY_FROM is a vector containing, for each row I in the range 0 <=
2790 I < NLINES, the index of the original line to move to I. This
2791 index is relative to the row range, i.e. 0 <= index < NLINES.
2792 RETAINED_P is a vector containing zero for each row 0 <= I < NLINES
2793 which is empty. */
2795 static void
2796 mirror_line_dance (struct window *w, int unchanged_at_top, int nlines, int *copy_from, char *retained_p)
2798 while (w)
2800 if (WINDOWP (w->contents))
2801 mirror_line_dance (XWINDOW (w->contents), unchanged_at_top,
2802 nlines, copy_from, retained_p);
2803 else
2805 /* W is a leaf window, and we are working on its current
2806 matrix m. */
2807 struct glyph_matrix *m = w->current_matrix;
2808 int i;
2809 bool sync_p = 0;
2810 struct glyph_row *old_rows;
2812 /* Make a copy of the original rows of matrix m. */
2813 USE_SAFE_ALLOCA;
2814 SAFE_NALLOCA (old_rows, 1, m->nrows);
2815 memcpy (old_rows, m->rows, m->nrows * sizeof *old_rows);
2817 for (i = 0; i < nlines; ++i)
2819 /* Frame relative line assigned to. */
2820 int frame_to = i + unchanged_at_top;
2822 /* Frame relative line assigned. */
2823 int frame_from = copy_from[i] + unchanged_at_top;
2825 /* Window relative line assigned to. */
2826 int window_to = frame_to - m->matrix_y;
2828 /* Window relative line assigned. */
2829 int window_from = frame_from - m->matrix_y;
2831 /* Is assigned line inside window? */
2832 bool from_inside_window_p
2833 = window_from >= 0 && window_from < m->matrix_h;
2835 /* Is assigned to line inside window? */
2836 bool to_inside_window_p
2837 = window_to >= 0 && window_to < m->matrix_h;
2839 if (from_inside_window_p && to_inside_window_p)
2841 /* Do the assignment. The enabled_p flag is saved
2842 over the assignment because the old redisplay did
2843 that. */
2844 bool enabled_before_p = m->rows[window_to].enabled_p;
2845 m->rows[window_to] = old_rows[window_from];
2846 m->rows[window_to].enabled_p = enabled_before_p;
2848 /* If frame line is empty, window line is empty, too. */
2849 if (!retained_p[copy_from[i]])
2850 m->rows[window_to].enabled_p = false;
2852 else if (to_inside_window_p)
2854 /* A copy between windows. This is an infrequent
2855 case not worth optimizing. */
2856 struct frame *f = XFRAME (w->frame);
2857 struct window *root = XWINDOW (FRAME_ROOT_WINDOW (f));
2858 struct window *w2;
2859 struct glyph_matrix *m2;
2860 int m2_from;
2862 w2 = frame_row_to_window (root, frame_from);
2863 /* ttn@surf.glug.org: when enabling menu bar using `emacs
2864 -nw', FROM_FRAME sometimes has no associated window.
2865 This check avoids a segfault if W2 is null. */
2866 if (w2)
2868 m2 = w2->current_matrix;
2869 m2_from = frame_from - m2->matrix_y;
2870 copy_row_except_pointers (m->rows + window_to,
2871 m2->rows + m2_from);
2873 /* If frame line is empty, window line is empty, too. */
2874 if (!retained_p[copy_from[i]])
2875 m->rows[window_to].enabled_p = false;
2877 sync_p = 1;
2879 else if (from_inside_window_p)
2880 sync_p = 1;
2883 /* If there was a copy between windows, make sure glyph
2884 pointers are in sync with the frame matrix. */
2885 if (sync_p)
2886 sync_window_with_frame_matrix_rows (w);
2888 /* Check that no pointers are lost. */
2889 CHECK_MATRIX (m);
2891 SAFE_FREE ();
2894 /* Next window on same level. */
2895 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2900 #ifdef GLYPH_DEBUG
2902 /* Check that window and frame matrices agree about their
2903 understanding where glyphs of the rows are to find. For each
2904 window in the window tree rooted at W, check that rows in the
2905 matrices of leaf window agree with their frame matrices about
2906 glyph pointers. */
2908 static void
2909 check_window_matrix_pointers (struct window *w)
2911 while (w)
2913 if (WINDOWP (w->contents))
2914 check_window_matrix_pointers (XWINDOW (w->contents));
2915 else
2917 struct frame *f = XFRAME (w->frame);
2918 check_matrix_pointers (w->desired_matrix, f->desired_matrix);
2919 check_matrix_pointers (w->current_matrix, f->current_matrix);
2922 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2927 /* Check that window rows are slices of frame rows. WINDOW_MATRIX is
2928 a window and FRAME_MATRIX is the corresponding frame matrix. For
2929 each row in WINDOW_MATRIX check that it's a slice of the
2930 corresponding frame row. If it isn't, abort. */
2932 static void
2933 check_matrix_pointers (struct glyph_matrix *window_matrix,
2934 struct glyph_matrix *frame_matrix)
2936 /* Row number in WINDOW_MATRIX. */
2937 int i = 0;
2939 /* Row number corresponding to I in FRAME_MATRIX. */
2940 int j = window_matrix->matrix_y;
2942 /* For all rows check that the row in the window matrix is a
2943 slice of the row in the frame matrix. If it isn't we didn't
2944 mirror an operation on the frame matrix correctly. */
2945 while (i < window_matrix->nrows)
2947 if (!glyph_row_slice_p (window_matrix->rows + i,
2948 frame_matrix->rows + j))
2949 emacs_abort ();
2950 ++i, ++j;
2954 #endif /* GLYPH_DEBUG */
2958 /**********************************************************************
2959 VPOS and HPOS translations
2960 **********************************************************************/
2962 #ifdef GLYPH_DEBUG
2964 /* Translate vertical position VPOS which is relative to window W to a
2965 vertical position relative to W's frame. */
2967 static int
2968 window_to_frame_vpos (struct window *w, int vpos)
2970 eassert (!FRAME_WINDOW_P (XFRAME (w->frame)));
2971 eassert (vpos >= 0 && vpos <= w->desired_matrix->nrows);
2972 vpos += WINDOW_TOP_EDGE_LINE (w);
2973 eassert (vpos >= 0 && vpos <= FRAME_TOTAL_LINES (XFRAME (w->frame)));
2974 return vpos;
2978 /* Translate horizontal position HPOS which is relative to window W to
2979 a horizontal position relative to W's frame. */
2981 static int
2982 window_to_frame_hpos (struct window *w, int hpos)
2984 eassert (!FRAME_WINDOW_P (XFRAME (w->frame)));
2985 hpos += WINDOW_LEFT_EDGE_COL (w);
2986 return hpos;
2989 #endif /* GLYPH_DEBUG */
2993 /**********************************************************************
2994 Redrawing Frames
2995 **********************************************************************/
2997 /* Redraw frame F. */
2999 void
3000 redraw_frame (struct frame *f)
3002 /* Error if F has no glyphs. */
3003 eassert (f->glyphs_initialized_p);
3004 update_begin (f);
3005 if (FRAME_MSDOS_P (f))
3006 FRAME_TERMINAL (f)->set_terminal_modes_hook (FRAME_TERMINAL (f));
3007 clear_frame (f);
3008 clear_current_matrices (f);
3009 update_end (f);
3010 fset_redisplay (f);
3011 /* Mark all windows as inaccurate, so that every window will have
3012 its redisplay done. */
3013 mark_window_display_accurate (FRAME_ROOT_WINDOW (f), 0);
3014 set_window_update_flags (XWINDOW (FRAME_ROOT_WINDOW (f)), true);
3015 f->garbaged = false;
3018 DEFUN ("redraw-frame", Fredraw_frame, Sredraw_frame, 0, 1, 0,
3019 doc: /* Clear frame FRAME and output again what is supposed to appear on it.
3020 If FRAME is omitted or nil, the selected frame is used. */)
3021 (Lisp_Object frame)
3023 redraw_frame (decode_live_frame (frame));
3024 return Qnil;
3027 DEFUN ("redraw-display", Fredraw_display, Sredraw_display, 0, 0, "",
3028 doc: /* Clear and redisplay all visible frames. */)
3029 (void)
3031 Lisp_Object tail, frame;
3033 FOR_EACH_FRAME (tail, frame)
3034 if (FRAME_VISIBLE_P (XFRAME (frame)))
3035 redraw_frame (XFRAME (frame));
3037 return Qnil;
3042 /***********************************************************************
3043 Frame Update
3044 ***********************************************************************/
3046 /* Update frame F based on the data in desired matrices.
3048 If FORCE_P, don't let redisplay be stopped by detecting pending input.
3049 If INHIBIT_HAIRY_ID_P, don't try scrolling.
3051 Value is true if redisplay was stopped due to pending input. */
3053 bool
3054 update_frame (struct frame *f, bool force_p, bool inhibit_hairy_id_p)
3056 /* True means display has been paused because of pending input. */
3057 bool paused_p;
3058 struct window *root_window = XWINDOW (f->root_window);
3060 if (redisplay_dont_pause)
3061 force_p = true;
3062 else if (!force_p && detect_input_pending_ignore_squeezables ())
3064 paused_p = true;
3065 goto do_pause;
3068 if (FRAME_WINDOW_P (f))
3070 /* We are working on window matrix basis. All windows whose
3071 flag must_be_updated_p is set have to be updated. */
3073 /* Record that we are not working on frame matrices. */
3074 set_frame_matrix_frame (NULL);
3076 /* Update all windows in the window tree of F, maybe stopping
3077 when pending input is detected. */
3078 update_begin (f);
3080 #if defined (HAVE_X_WINDOWS) && ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
3081 /* Update the menu bar on X frames that don't have toolkit
3082 support. */
3083 if (WINDOWP (f->menu_bar_window))
3084 update_window (XWINDOW (f->menu_bar_window), true);
3085 #endif
3087 #if defined (HAVE_WINDOW_SYSTEM) && ! defined (USE_GTK) && ! defined (HAVE_NS)
3088 /* Update the tool-bar window, if present. */
3089 if (WINDOWP (f->tool_bar_window))
3091 struct window *w = XWINDOW (f->tool_bar_window);
3093 /* Update tool-bar window. */
3094 if (w->must_be_updated_p)
3096 Lisp_Object tem;
3098 update_window (w, true);
3099 w->must_be_updated_p = false;
3101 /* Swap tool-bar strings. We swap because we want to
3102 reuse strings. */
3103 tem = f->current_tool_bar_string;
3104 fset_current_tool_bar_string (f, f->desired_tool_bar_string);
3105 fset_desired_tool_bar_string (f, tem);
3108 #endif
3110 /* Update windows. */
3111 paused_p = update_window_tree (root_window, force_p);
3112 update_end (f);
3114 else
3116 /* We are working on frame matrix basis. Set the frame on whose
3117 frame matrix we operate. */
3118 set_frame_matrix_frame (f);
3120 /* Build F's desired matrix from window matrices. */
3121 build_frame_matrix (f);
3123 /* Update the display. */
3124 update_begin (f);
3125 paused_p = update_frame_1 (f, force_p, inhibit_hairy_id_p, 1, false);
3126 update_end (f);
3128 if (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f))
3130 if (FRAME_TTY (f)->termscript)
3131 fflush_unlocked (FRAME_TTY (f)->termscript);
3132 if (FRAME_TERMCAP_P (f))
3133 fflush_unlocked (FRAME_TTY (f)->output);
3136 /* Check window matrices for lost pointers. */
3137 #ifdef GLYPH_DEBUG
3138 check_window_matrix_pointers (root_window);
3139 add_frame_display_history (f, paused_p);
3140 #endif
3143 do_pause:
3144 /* Reset flags indicating that a window should be updated. */
3145 set_window_update_flags (root_window, false);
3147 display_completed = !paused_p;
3148 return paused_p;
3151 /* Update a TTY frame F that has a menu dropped down over some of its
3152 glyphs. This is like the second part of update_frame, but it
3153 doesn't call build_frame_matrix, because we already have the
3154 desired matrix prepared, and don't want it to be overwritten by the
3155 text of the normal display.
3157 ROW and COL, if non-negative, are the row and column of the TTY
3158 frame where to position the cursor after the frame update is
3159 complete. Negative values mean ask update_frame_1 to position the
3160 cursor "normally", i.e. at point in the selected window. */
3161 void
3162 update_frame_with_menu (struct frame *f, int row, int col)
3164 struct window *root_window = XWINDOW (f->root_window);
3165 bool paused_p, cursor_at_point_p;
3167 eassert (FRAME_TERMCAP_P (f));
3169 /* We are working on frame matrix basis. Set the frame on whose
3170 frame matrix we operate. */
3171 set_frame_matrix_frame (f);
3173 /* Update the display. */
3174 update_begin (f);
3175 cursor_at_point_p = !(row >= 0 && col >= 0);
3176 /* Force update_frame_1 not to stop due to pending input, and not
3177 try scrolling. */
3178 paused_p = update_frame_1 (f, 1, 1, cursor_at_point_p, true);
3179 /* ROW and COL tell us where in the menu to position the cursor, so
3180 that screen readers know the active region on the screen. */
3181 if (!cursor_at_point_p)
3182 cursor_to (f, row, col);
3183 update_end (f);
3185 if (FRAME_TTY (f)->termscript)
3186 fflush_unlocked (FRAME_TTY (f)->termscript);
3187 fflush_unlocked (FRAME_TTY (f)->output);
3188 /* Check window matrices for lost pointers. */
3189 #if GLYPH_DEBUG
3190 #if 0
3191 /* We cannot possibly survive the matrix pointers check, since
3192 we have overwritten parts of the frame glyph matrix without
3193 making any updates to the window matrices. */
3194 check_window_matrix_pointers (root_window);
3195 #endif
3196 add_frame_display_history (f, paused_p);
3197 #endif
3199 /* Reset flags indicating that a window should be updated. */
3200 set_window_update_flags (root_window, false);
3201 display_completed = !paused_p;
3205 /************************************************************************
3206 Window-based updates
3207 ************************************************************************/
3209 /* Perform updates in window tree rooted at W.
3210 If FORCE_P, don't stop updating if input is pending. */
3212 static bool
3213 update_window_tree (struct window *w, bool force_p)
3215 bool paused_p = 0;
3217 while (w && !paused_p)
3219 if (WINDOWP (w->contents))
3220 paused_p |= update_window_tree (XWINDOW (w->contents), force_p);
3221 else if (w->must_be_updated_p)
3222 paused_p |= update_window (w, force_p);
3224 w = NILP (w->next) ? 0 : XWINDOW (w->next);
3227 return paused_p;
3231 /* Update window W if its flag must_be_updated_p is set.
3232 If FORCE_P, don't stop updating if input is pending. */
3234 void
3235 update_single_window (struct window *w)
3237 if (w->must_be_updated_p)
3239 struct frame *f = XFRAME (WINDOW_FRAME (w));
3241 /* Record that this is not a frame-based redisplay. */
3242 set_frame_matrix_frame (NULL);
3244 /* Update W. */
3245 update_begin (f);
3246 update_window (w, true);
3247 update_end (f);
3249 /* Reset flag in W. */
3250 w->must_be_updated_p = false;
3254 #ifdef HAVE_WINDOW_SYSTEM
3256 /* Redraw lines from the current matrix of window W that are
3257 overlapped by other rows. YB is bottom-most y-position in W. */
3259 static void
3260 redraw_overlapped_rows (struct window *w, int yb)
3262 int i;
3263 struct frame *f = XFRAME (WINDOW_FRAME (w));
3265 /* If rows overlapping others have been changed, the rows being
3266 overlapped have to be redrawn. This won't draw lines that have
3267 already been drawn in update_window_line because overlapped_p in
3268 desired rows is 0, so after row assignment overlapped_p in
3269 current rows is 0. */
3270 for (i = 0; i < w->current_matrix->nrows; ++i)
3272 struct glyph_row *row = w->current_matrix->rows + i;
3274 if (!row->enabled_p)
3275 break;
3276 else if (row->mode_line_p)
3277 continue;
3279 if (row->overlapped_p)
3281 enum glyph_row_area area;
3283 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
3285 output_cursor_to (w, i, 0, row->y,
3286 area == TEXT_AREA ? row->x : 0);
3287 if (row->used[area])
3288 FRAME_RIF (f)->write_glyphs (w, row, row->glyphs[area],
3289 area, row->used[area]);
3290 FRAME_RIF (f)->clear_end_of_line (w, row, area, -1);
3293 row->overlapped_p = 0;
3296 if (MATRIX_ROW_BOTTOM_Y (row) >= yb)
3297 break;
3302 /* Redraw lines from the current matrix of window W that overlap
3303 others. YB is bottom-most y-position in W. */
3305 static void
3306 redraw_overlapping_rows (struct window *w, int yb)
3308 int i, bottom_y;
3309 struct glyph_row *row;
3310 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3312 for (i = 0; i < w->current_matrix->nrows; ++i)
3314 row = w->current_matrix->rows + i;
3316 if (!row->enabled_p)
3317 break;
3318 else if (row->mode_line_p)
3319 continue;
3321 bottom_y = MATRIX_ROW_BOTTOM_Y (row);
3323 if (row->overlapping_p)
3325 int overlaps = 0;
3327 if (MATRIX_ROW_OVERLAPS_PRED_P (row) && i > 0
3328 && !MATRIX_ROW (w->current_matrix, i - 1)->overlapped_p)
3329 overlaps |= OVERLAPS_PRED;
3330 if (MATRIX_ROW_OVERLAPS_SUCC_P (row) && bottom_y < yb
3331 && !MATRIX_ROW (w->current_matrix, i + 1)->overlapped_p)
3332 overlaps |= OVERLAPS_SUCC;
3334 if (overlaps)
3336 if (row->used[LEFT_MARGIN_AREA])
3337 rif->fix_overlapping_area (w, row, LEFT_MARGIN_AREA, overlaps);
3339 if (row->used[TEXT_AREA])
3340 rif->fix_overlapping_area (w, row, TEXT_AREA, overlaps);
3342 if (row->used[RIGHT_MARGIN_AREA])
3343 rif->fix_overlapping_area (w, row, RIGHT_MARGIN_AREA, overlaps);
3345 /* Record in neighbor rows that ROW overwrites part of
3346 their display. */
3347 if (overlaps & OVERLAPS_PRED)
3348 MATRIX_ROW (w->current_matrix, i - 1)->overlapped_p = 1;
3349 if (overlaps & OVERLAPS_SUCC)
3350 MATRIX_ROW (w->current_matrix, i + 1)->overlapped_p = 1;
3354 if (bottom_y >= yb)
3355 break;
3359 #endif /* HAVE_WINDOW_SYSTEM */
3362 #if defined GLYPH_DEBUG && 0
3364 /* Check that no row in the current matrix of window W is enabled
3365 which is below what's displayed in the window. */
3367 static void
3368 check_current_matrix_flags (struct window *w)
3370 bool last_seen_p = 0;
3371 int i, yb = window_text_bottom_y (w);
3373 for (i = 0; i < w->current_matrix->nrows - 1; ++i)
3375 struct glyph_row *row = MATRIX_ROW (w->current_matrix, i);
3376 if (!last_seen_p && MATRIX_ROW_BOTTOM_Y (row) >= yb)
3377 last_seen_p = 1;
3378 else if (last_seen_p && row->enabled_p)
3379 emacs_abort ();
3383 #endif /* GLYPH_DEBUG */
3386 /* Update display of window W.
3387 If FORCE_P, don't stop updating when input is pending. */
3389 static bool
3390 update_window (struct window *w, bool force_p)
3392 struct glyph_matrix *desired_matrix = w->desired_matrix;
3393 bool paused_p;
3394 int preempt_count = baud_rate / 2400 + 1;
3395 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3396 #ifdef GLYPH_DEBUG
3397 /* Check that W's frame doesn't have glyph matrices. */
3398 eassert (FRAME_WINDOW_P (XFRAME (WINDOW_FRAME (w))));
3399 #endif
3401 /* Check pending input the first time so that we can quickly return. */
3402 if (!force_p)
3403 detect_input_pending_ignore_squeezables ();
3405 /* If forced to complete the update, or if no input is pending, do
3406 the update. */
3407 if (force_p || !input_pending || !NILP (do_mouse_tracking))
3409 struct glyph_row *row, *end;
3410 struct glyph_row *mode_line_row;
3411 struct glyph_row *header_line_row;
3412 int yb;
3413 bool changed_p = 0, mouse_face_overwritten_p = 0;
3414 int n_updated = 0;
3416 rif->update_window_begin_hook (w);
3417 yb = window_text_bottom_y (w);
3418 row = MATRIX_ROW (desired_matrix, 0);
3419 end = MATRIX_MODE_LINE_ROW (desired_matrix);
3421 /* Take note of the header line, if there is one. We will
3422 update it below, after updating all of the window's lines. */
3423 if (row->mode_line_p)
3425 header_line_row = row;
3426 ++row;
3428 else
3429 header_line_row = NULL;
3431 /* Update the mode line, if necessary. */
3432 mode_line_row = MATRIX_MODE_LINE_ROW (desired_matrix);
3433 if (mode_line_row->mode_line_p && mode_line_row->enabled_p)
3435 mode_line_row->y = yb + WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
3436 update_window_line (w, MATRIX_ROW_VPOS (mode_line_row,
3437 desired_matrix),
3438 &mouse_face_overwritten_p);
3441 /* Find first enabled row. Optimizations in redisplay_internal
3442 may lead to an update with only one row enabled. There may
3443 be also completely empty matrices. */
3444 while (row < end && !row->enabled_p)
3445 ++row;
3447 /* Try reusing part of the display by copying. */
3448 if (row < end && !desired_matrix->no_scrolling_p)
3450 int rc = scrolling_window (w, header_line_row != NULL);
3451 if (rc < 0)
3453 /* All rows were found to be equal. */
3454 paused_p = 0;
3455 goto set_cursor;
3457 else if (rc > 0)
3459 /* We've scrolled the display. */
3460 force_p = 1;
3461 changed_p = 1;
3465 /* Update the rest of the lines. */
3466 for (; row < end && (force_p || !input_pending); ++row)
3467 /* scrolling_window resets the enabled_p flag of the rows it
3468 reuses from current_matrix. */
3469 if (row->enabled_p)
3471 int vpos = MATRIX_ROW_VPOS (row, desired_matrix);
3472 int i;
3474 /* We'll have to play a little bit with when to
3475 detect_input_pending. If it's done too often,
3476 scrolling large windows with repeated scroll-up
3477 commands will too quickly pause redisplay. */
3478 if (!force_p && ++n_updated % preempt_count == 0)
3479 detect_input_pending_ignore_squeezables ();
3480 changed_p |= update_window_line (w, vpos,
3481 &mouse_face_overwritten_p);
3483 /* Mark all rows below the last visible one in the current
3484 matrix as invalid. This is necessary because of
3485 variable line heights. Consider the case of three
3486 successive redisplays, where the first displays 5
3487 lines, the second 3 lines, and the third 5 lines again.
3488 If the second redisplay wouldn't mark rows in the
3489 current matrix invalid, the third redisplay might be
3490 tempted to optimize redisplay based on lines displayed
3491 in the first redisplay. */
3492 if (MATRIX_ROW_BOTTOM_Y (row) >= yb)
3493 for (i = vpos + 1; i < w->current_matrix->nrows - 1; ++i)
3494 SET_MATRIX_ROW_ENABLED_P (w->current_matrix, i, false);
3497 /* Was display preempted? */
3498 paused_p = row < end;
3500 set_cursor:
3502 /* Update the header line after scrolling because a new header
3503 line would otherwise overwrite lines at the top of the window
3504 that can be scrolled. */
3505 if (header_line_row && header_line_row->enabled_p)
3507 header_line_row->y = 0;
3508 update_window_line (w, 0, &mouse_face_overwritten_p);
3511 /* Fix the appearance of overlapping/overlapped rows. */
3512 if (!paused_p && !w->pseudo_window_p)
3514 #ifdef HAVE_WINDOW_SYSTEM
3515 if (changed_p && rif->fix_overlapping_area)
3517 redraw_overlapped_rows (w, yb);
3518 redraw_overlapping_rows (w, yb);
3520 #endif
3522 /* Make cursor visible at cursor position of W. */
3523 set_window_cursor_after_update (w);
3525 #if 0 /* Check that current matrix invariants are satisfied. This is
3526 for debugging only. See the comment of check_matrix_invariants. */
3527 IF_DEBUG (check_matrix_invariants (w));
3528 #endif
3531 #ifdef GLYPH_DEBUG
3532 /* Remember the redisplay method used to display the matrix. */
3533 strcpy (w->current_matrix->method, w->desired_matrix->method);
3534 #endif
3536 #ifdef HAVE_WINDOW_SYSTEM
3537 update_window_fringes (w, 0);
3538 #endif
3540 /* End the update of window W. Don't set the cursor if we
3541 paused updating the display because in this case,
3542 set_window_cursor_after_update hasn't been called, and
3543 W->output_cursor doesn't contain the cursor location. */
3544 rif->update_window_end_hook (w, !paused_p, mouse_face_overwritten_p);
3546 else
3547 paused_p = 1;
3549 #ifdef GLYPH_DEBUG
3550 /* check_current_matrix_flags (w); */
3551 add_window_display_history (w, w->current_matrix->method, paused_p);
3552 #endif
3554 xwidget_end_redisplay (w, w->current_matrix);
3555 clear_glyph_matrix (desired_matrix);
3557 return paused_p;
3561 /* Update the display of area AREA in window W, row number VPOS.
3562 AREA can be either LEFT_MARGIN_AREA or RIGHT_MARGIN_AREA. */
3564 static void
3565 update_marginal_area (struct window *w, struct glyph_row *updated_row,
3566 enum glyph_row_area area, int vpos)
3568 struct glyph_row *desired_row = MATRIX_ROW (w->desired_matrix, vpos);
3569 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3571 /* Set cursor to start of glyphs, write them, and clear to the end
3572 of the area. I don't think that something more sophisticated is
3573 necessary here, since marginal areas will not be the default. */
3574 output_cursor_to (w, vpos, 0, desired_row->y, 0);
3575 if (desired_row->used[area])
3576 rif->write_glyphs (w, updated_row, desired_row->glyphs[area],
3577 area, desired_row->used[area]);
3578 rif->clear_end_of_line (w, updated_row, area, -1);
3582 /* Update the display of the text area of row VPOS in window W.
3583 Value is true if display has changed. */
3585 static bool
3586 update_text_area (struct window *w, struct glyph_row *updated_row, int vpos)
3588 struct glyph_row *current_row = MATRIX_ROW (w->current_matrix, vpos);
3589 struct glyph_row *desired_row = MATRIX_ROW (w->desired_matrix, vpos);
3590 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3591 bool changed_p = 0;
3593 /* If rows are at different X or Y, or rows have different height,
3594 or the current row is marked invalid, write the entire line. */
3595 if (!current_row->enabled_p
3596 || desired_row->y != current_row->y
3597 || desired_row->ascent != current_row->ascent
3598 || desired_row->phys_ascent != current_row->phys_ascent
3599 || desired_row->phys_height != current_row->phys_height
3600 || desired_row->visible_height != current_row->visible_height
3601 || current_row->overlapped_p
3602 /* This next line is necessary for correctly redrawing
3603 mouse-face areas after scrolling and other operations.
3604 However, it causes excessive flickering when mouse is moved
3605 across the mode line. Luckily, turning it off for the mode
3606 line doesn't seem to hurt anything. -- cyd.
3607 But it is still needed for the header line. -- kfs. */
3608 || (current_row->mouse_face_p
3609 && !(current_row->mode_line_p && vpos > 0))
3610 || current_row->x != desired_row->x)
3612 output_cursor_to (w, vpos, 0, desired_row->y, desired_row->x);
3614 if (desired_row->used[TEXT_AREA])
3615 rif->write_glyphs (w, updated_row, desired_row->glyphs[TEXT_AREA],
3616 TEXT_AREA, desired_row->used[TEXT_AREA]);
3618 /* Clear to end of window. */
3619 rif->clear_end_of_line (w, updated_row, TEXT_AREA, -1);
3620 changed_p = 1;
3622 /* This erases the cursor. We do this here because
3623 notice_overwritten_cursor cannot easily check this, which
3624 might indicate that the whole functionality of
3625 notice_overwritten_cursor would better be implemented here.
3626 On the other hand, we need notice_overwritten_cursor as long
3627 as mouse highlighting is done asynchronously outside of
3628 redisplay. */
3629 if (vpos == w->phys_cursor.vpos)
3630 w->phys_cursor_on_p = 0;
3632 else
3634 int stop, i, x;
3635 struct glyph *current_glyph = current_row->glyphs[TEXT_AREA];
3636 struct glyph *desired_glyph = desired_row->glyphs[TEXT_AREA];
3637 bool overlapping_glyphs_p = current_row->contains_overlapping_glyphs_p;
3638 int desired_stop_pos = desired_row->used[TEXT_AREA];
3639 bool abort_skipping = 0;
3641 /* If the desired row extends its face to the text area end, and
3642 unless the current row also does so at the same position,
3643 make sure we write at least one glyph, so that the face
3644 extension actually takes place. */
3645 if (MATRIX_ROW_EXTENDS_FACE_P (desired_row)
3646 && (desired_stop_pos < current_row->used[TEXT_AREA]
3647 || (desired_stop_pos == current_row->used[TEXT_AREA]
3648 && !MATRIX_ROW_EXTENDS_FACE_P (current_row))))
3649 --desired_stop_pos;
3651 stop = min (current_row->used[TEXT_AREA], desired_stop_pos);
3652 i = 0;
3653 x = desired_row->x;
3655 /* Loop over glyphs that current and desired row may have
3656 in common. */
3657 while (i < stop)
3659 bool can_skip_p = !abort_skipping;
3661 /* Skip over glyphs that both rows have in common. These
3662 don't have to be written. We can't skip if the last
3663 current glyph overlaps the glyph to its right. For
3664 example, consider a current row of `if ' with the `f' in
3665 Courier bold so that it overlaps the ` ' to its right.
3666 If the desired row is ` ', we would skip over the space
3667 after the `if' and there would remain a pixel from the
3668 `f' on the screen. */
3669 if (overlapping_glyphs_p && i > 0)
3671 struct glyph *glyph = &current_row->glyphs[TEXT_AREA][i - 1];
3672 int left, right;
3674 rif->get_glyph_overhangs (glyph, XFRAME (w->frame),
3675 &left, &right);
3676 can_skip_p = (right == 0 && !abort_skipping);
3679 if (can_skip_p)
3681 int start_hpos = i;
3683 while (i < stop
3684 && GLYPH_EQUAL_P (desired_glyph, current_glyph))
3686 x += desired_glyph->pixel_width;
3687 ++desired_glyph, ++current_glyph, ++i;
3690 /* Consider the case that the current row contains "xxx
3691 ppp ggg" in italic Courier font, and the desired row
3692 is "xxx ggg". The character `p' has lbearing, `g'
3693 has not. The loop above will stop in front of the
3694 first `p' in the current row. If we would start
3695 writing glyphs there, we wouldn't erase the lbearing
3696 of the `p'. The rest of the lbearing problem is then
3697 taken care of by draw_glyphs. */
3698 if (overlapping_glyphs_p
3699 && i > 0
3700 && i < current_row->used[TEXT_AREA]
3701 && (current_row->used[TEXT_AREA]
3702 != desired_row->used[TEXT_AREA]))
3704 int left, right;
3706 rif->get_glyph_overhangs (current_glyph,
3707 XFRAME (w->frame),
3708 &left, &right);
3709 while (left > 0 && i > 0)
3711 --i, --desired_glyph, --current_glyph;
3712 x -= desired_glyph->pixel_width;
3713 left -= desired_glyph->pixel_width;
3716 /* Abort the skipping algorithm if we end up before
3717 our starting point, to avoid looping (bug#1070).
3718 This can happen when the lbearing is larger than
3719 the pixel width. */
3720 abort_skipping = (i < start_hpos);
3724 /* Try to avoid writing the entire rest of the desired row
3725 by looking for a resync point. This mainly prevents
3726 mode line flickering in the case the mode line is in
3727 fixed-pitch font, which it usually will be. */
3728 if (i < desired_row->used[TEXT_AREA])
3730 int start_x = x, start_hpos = i;
3731 struct glyph *start = desired_glyph;
3732 int current_x = x;
3733 bool skip_first_p = !can_skip_p;
3735 /* Find the next glyph that's equal again. */
3736 while (i < stop
3737 && (skip_first_p
3738 || !GLYPH_EQUAL_P (desired_glyph, current_glyph))
3739 && x == current_x)
3741 x += desired_glyph->pixel_width;
3742 current_x += current_glyph->pixel_width;
3743 ++desired_glyph, ++current_glyph, ++i;
3744 skip_first_p = 0;
3747 if (i == start_hpos || x != current_x)
3749 i = start_hpos;
3750 x = start_x;
3751 desired_glyph = start;
3752 break;
3755 output_cursor_to (w, vpos, start_hpos, desired_row->y, start_x);
3756 rif->write_glyphs (w, updated_row, start,
3757 TEXT_AREA, i - start_hpos);
3758 changed_p = 1;
3762 /* Write the rest. */
3763 if (i < desired_row->used[TEXT_AREA])
3765 output_cursor_to (w, vpos, i, desired_row->y, x);
3766 rif->write_glyphs (w, updated_row, desired_glyph,
3767 TEXT_AREA, desired_row->used[TEXT_AREA] - i);
3768 changed_p = 1;
3771 /* Maybe clear to end of line. */
3772 if (MATRIX_ROW_EXTENDS_FACE_P (desired_row))
3774 /* If new row extends to the end of the text area, nothing
3775 has to be cleared, if and only if we did a write_glyphs
3776 above. This is made sure by setting desired_stop_pos
3777 appropriately above. */
3778 eassert (i < desired_row->used[TEXT_AREA]
3779 || ((desired_row->used[TEXT_AREA]
3780 == current_row->used[TEXT_AREA])
3781 && MATRIX_ROW_EXTENDS_FACE_P (current_row)));
3783 else if (MATRIX_ROW_EXTENDS_FACE_P (current_row))
3785 /* If old row extends to the end of the text area, clear. */
3786 if (i >= desired_row->used[TEXT_AREA])
3787 output_cursor_to (w, vpos, i, desired_row->y,
3788 desired_row->pixel_width);
3789 rif->clear_end_of_line (w, updated_row, TEXT_AREA, -1);
3790 changed_p = 1;
3792 else if (desired_row->pixel_width < current_row->pixel_width)
3794 /* Otherwise clear to the end of the old row. Everything
3795 after that position should be clear already. */
3796 int xlim;
3798 if (i >= desired_row->used[TEXT_AREA])
3799 output_cursor_to (w, vpos, i, desired_row->y,
3800 desired_row->pixel_width);
3802 /* If cursor is displayed at the end of the line, make sure
3803 it's cleared. Nowadays we don't have a phys_cursor_glyph
3804 with which to erase the cursor (because this method
3805 doesn't work with lbearing/rbearing), so we must do it
3806 this way. */
3807 if (vpos == w->phys_cursor.vpos
3808 && (desired_row->reversed_p
3809 ? (w->phys_cursor.hpos < 0)
3810 : (w->phys_cursor.hpos >= desired_row->used[TEXT_AREA])))
3812 w->phys_cursor_on_p = 0;
3813 xlim = -1;
3815 else
3816 xlim = current_row->pixel_width;
3817 rif->clear_end_of_line (w, updated_row, TEXT_AREA, xlim);
3818 changed_p = 1;
3822 return changed_p;
3826 /* Update row VPOS in window W. Value is true if display has been changed. */
3828 static bool
3829 update_window_line (struct window *w, int vpos, bool *mouse_face_overwritten_p)
3831 struct glyph_row *current_row = MATRIX_ROW (w->current_matrix, vpos);
3832 struct glyph_row *desired_row = MATRIX_ROW (w->desired_matrix, vpos);
3833 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3834 bool changed_p = 0;
3836 /* A row can be completely invisible in case a desired matrix was
3837 built with a vscroll and then make_cursor_line_fully_visible shifts
3838 the matrix. Make sure to make such rows current anyway, since
3839 we need the correct y-position, for example, in the current matrix. */
3840 if (desired_row->mode_line_p
3841 || desired_row->visible_height > 0)
3843 eassert (desired_row->enabled_p);
3845 /* Update display of the left margin area, if there is one. */
3846 if (!desired_row->full_width_p && w->left_margin_cols > 0)
3848 changed_p = 1;
3849 update_marginal_area (w, desired_row, LEFT_MARGIN_AREA, vpos);
3850 /* Setting this flag will ensure the vertical border, if
3851 any, between this window and the one on its left will be
3852 redrawn. This is necessary because updating the left
3853 margin area can potentially draw over the border. */
3854 current_row->redraw_fringe_bitmaps_p = 1;
3857 /* Update the display of the text area. */
3858 if (update_text_area (w, desired_row, vpos))
3860 changed_p = 1;
3861 if (current_row->mouse_face_p)
3862 *mouse_face_overwritten_p = 1;
3865 /* Update display of the right margin area, if there is one. */
3866 if (!desired_row->full_width_p && w->right_margin_cols > 0)
3868 changed_p = 1;
3869 update_marginal_area (w, desired_row, RIGHT_MARGIN_AREA, vpos);
3872 /* Draw truncation marks etc. */
3873 if (!current_row->enabled_p
3874 || desired_row->y != current_row->y
3875 || desired_row->visible_height != current_row->visible_height
3876 || desired_row->cursor_in_fringe_p != current_row->cursor_in_fringe_p
3877 || desired_row->overlay_arrow_bitmap != current_row->overlay_arrow_bitmap
3878 || current_row->redraw_fringe_bitmaps_p
3879 || desired_row->mode_line_p != current_row->mode_line_p
3880 || desired_row->exact_window_width_line_p != current_row->exact_window_width_line_p
3881 || (MATRIX_ROW_CONTINUATION_LINE_P (desired_row)
3882 != MATRIX_ROW_CONTINUATION_LINE_P (current_row)))
3883 rif->after_update_window_line_hook (w, desired_row);
3886 /* Update current_row from desired_row. */
3887 make_current (w->desired_matrix, w->current_matrix, vpos);
3888 return changed_p;
3892 /* Set the cursor after an update of window W. This function may only
3893 be called from update_window. */
3895 static void
3896 set_window_cursor_after_update (struct window *w)
3898 struct frame *f = XFRAME (w->frame);
3899 int cx, cy, vpos, hpos;
3901 /* Not intended for frame matrix updates. */
3902 eassert (FRAME_WINDOW_P (f));
3904 if (cursor_in_echo_area
3905 && !NILP (echo_area_buffer[0])
3906 /* If we are showing a message instead of the mini-buffer,
3907 show the cursor for the message instead. */
3908 && XWINDOW (minibuf_window) == w
3909 && EQ (minibuf_window, echo_area_window)
3910 /* These cases apply only to the frame that contains
3911 the active mini-buffer window. */
3912 && FRAME_HAS_MINIBUF_P (f)
3913 && EQ (FRAME_MINIBUF_WINDOW (f), echo_area_window))
3915 cx = cy = vpos = hpos = 0;
3917 /* If the mini-buffer is several lines high, find the last
3918 line that has any text on it. Note: either all lines
3919 are enabled or none. Otherwise we wouldn't be able to
3920 determine Y. */
3921 struct glyph_row *last_row = NULL;
3922 int yb = window_text_bottom_y (w);
3924 for (struct glyph_row *row = w->current_matrix->rows;
3925 row->enabled_p && (!last_row || MATRIX_ROW_BOTTOM_Y (row) <= yb);
3926 row++)
3927 if (row->used[TEXT_AREA] && row->glyphs[TEXT_AREA][0].charpos >= 0)
3928 last_row = row;
3930 if (last_row)
3932 struct glyph *start = last_row->glyphs[TEXT_AREA];
3933 struct glyph *last = start + last_row->used[TEXT_AREA] - 1;
3935 while (last > start && last->charpos < 0)
3936 --last;
3938 for (struct glyph *glyph = start; glyph < last; glyph++)
3940 cx += glyph->pixel_width;
3941 hpos++;
3944 cy = last_row->y;
3945 vpos = MATRIX_ROW_VPOS (last_row, w->current_matrix);
3948 else
3950 cx = w->cursor.x;
3951 cy = w->cursor.y;
3952 hpos = w->cursor.hpos;
3953 vpos = w->cursor.vpos;
3956 /* Window cursor can be out of sync for horizontally split windows.
3957 Horizontal position is -1 when cursor is on the left fringe. */
3958 hpos = clip_to_bounds (-1, hpos, w->current_matrix->matrix_w - 1);
3959 vpos = clip_to_bounds (0, vpos, w->current_matrix->nrows - 1);
3960 output_cursor_to (w, vpos, hpos, cy, cx);
3964 /* Set WINDOW->must_be_updated_p to ON_P for all windows in
3965 the window tree rooted at W. */
3967 static void
3968 set_window_update_flags (struct window *w, bool on_p)
3970 while (w)
3972 if (WINDOWP (w->contents))
3973 set_window_update_flags (XWINDOW (w->contents), on_p);
3974 else
3975 w->must_be_updated_p = on_p;
3977 w = NILP (w->next) ? 0 : XWINDOW (w->next);
3983 /***********************************************************************
3984 Window-Based Scrolling
3985 ***********************************************************************/
3987 /* Structure describing rows in scrolling_window. */
3989 struct row_entry
3991 /* Number of occurrences of this row in desired and current matrix. */
3992 int old_uses, new_uses;
3994 /* Vpos of row in new matrix. */
3995 int new_line_number;
3997 /* Bucket index of this row_entry in the hash table row_table. */
3998 ptrdiff_t bucket;
4000 /* The row described by this entry. */
4001 struct glyph_row *row;
4003 /* Hash collision chain. */
4004 struct row_entry *next;
4007 /* A pool to allocate row_entry structures from, and the size of the
4008 pool. The pool is reallocated in scrolling_window when we find
4009 that we need a larger one. */
4011 static struct row_entry *row_entry_pool;
4012 static ptrdiff_t row_entry_pool_size;
4014 /* Index of next free entry in row_entry_pool. */
4016 static ptrdiff_t row_entry_idx;
4018 /* The hash table used during scrolling, and the table's size. This
4019 table is used to quickly identify equal rows in the desired and
4020 current matrix. */
4022 static struct row_entry **row_table;
4023 static ptrdiff_t row_table_size;
4025 /* Vectors of pointers to row_entry structures belonging to the
4026 current and desired matrix, and the size of the vectors. */
4028 static struct row_entry **old_lines, **new_lines;
4029 static ptrdiff_t old_lines_size, new_lines_size;
4031 /* A pool to allocate run structures from, and its size. */
4033 static struct run *run_pool;
4034 static ptrdiff_t runs_size;
4036 /* A vector of runs of lines found during scrolling. */
4038 static struct run **runs;
4040 /* Add glyph row ROW to the scrolling hash table. */
4042 static struct row_entry *
4043 add_row_entry (struct glyph_row *row)
4045 struct row_entry *entry;
4046 ptrdiff_t i = row->hash % row_table_size;
4048 entry = row_table[i];
4049 eassert (entry || verify_row_hash (row));
4050 while (entry && !row_equal_p (entry->row, row, 1))
4051 entry = entry->next;
4053 if (entry == NULL)
4055 entry = row_entry_pool + row_entry_idx++;
4056 entry->row = row;
4057 entry->old_uses = entry->new_uses = 0;
4058 entry->new_line_number = 0;
4059 entry->bucket = i;
4060 entry->next = row_table[i];
4061 row_table[i] = entry;
4064 return entry;
4068 /* Try to reuse part of the current display of W by scrolling lines.
4069 HEADER_LINE_P means W has a header line.
4071 The algorithm is taken from Communications of the ACM, Apr78 "A
4072 Technique for Isolating Differences Between Files." It should take
4073 O(N) time.
4075 A short outline of the steps of the algorithm
4077 1. Skip lines equal at the start and end of both matrices.
4079 2. Enter rows in the current and desired matrix into a symbol
4080 table, counting how often they appear in both matrices.
4082 3. Rows that appear exactly once in both matrices serve as anchors,
4083 i.e. we assume that such lines are likely to have been moved.
4085 4. Starting from anchor lines, extend regions to be scrolled both
4086 forward and backward.
4088 Value is
4090 -1 if all rows were found to be equal.
4091 0 to indicate that we did not scroll the display, or
4092 1 if we did scroll. */
4094 static int
4095 scrolling_window (struct window *w, bool header_line_p)
4097 struct glyph_matrix *desired_matrix = w->desired_matrix;
4098 struct glyph_matrix *current_matrix = w->current_matrix;
4099 int yb = window_text_bottom_y (w);
4100 ptrdiff_t i;
4101 int j, first_old, first_new, last_old, last_new;
4102 int nruns, run_idx;
4103 ptrdiff_t n;
4104 struct row_entry *entry;
4105 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
4107 /* Skip over rows equal at the start. */
4108 for (i = header_line_p; i < current_matrix->nrows - 1; ++i)
4110 struct glyph_row *d = MATRIX_ROW (desired_matrix, i);
4111 struct glyph_row *c = MATRIX_ROW (current_matrix, i);
4113 if (c->enabled_p
4114 && d->enabled_p
4115 && !d->redraw_fringe_bitmaps_p
4116 && c->y == d->y
4117 && MATRIX_ROW_BOTTOM_Y (c) <= yb
4118 && MATRIX_ROW_BOTTOM_Y (d) <= yb
4119 && row_equal_p (c, d, 1))
4121 assign_row (c, d);
4122 d->enabled_p = false;
4124 else
4125 break;
4128 #ifdef HAVE_XWIDGETS
4129 /* Currently this seems needed to detect xwidget movement reliably. */
4130 return 0;
4131 #endif
4133 /* Give up if some rows in the desired matrix are not enabled. */
4134 if (! MATRIX_ROW_ENABLED_P (desired_matrix, i))
4135 return -1;
4137 first_old = first_new = i;
4139 /* Set last_new to the index + 1 of the row that reaches the
4140 bottom boundary in the desired matrix. Give up if we find a
4141 disabled row before we reach the bottom boundary. */
4142 i = first_new + 1;
4143 while (i < desired_matrix->nrows - 1)
4145 int bottom;
4147 if (! MATRIX_ROW_ENABLED_P (desired_matrix, i))
4148 return 0;
4149 bottom = MATRIX_ROW_BOTTOM_Y (MATRIX_ROW (desired_matrix, i));
4150 if (bottom <= yb)
4151 ++i;
4152 if (bottom >= yb)
4153 break;
4156 last_new = i;
4158 /* Set last_old to the index + 1 of the row that reaches the bottom
4159 boundary in the current matrix. We don't look at the enabled
4160 flag here because we plan to reuse part of the display even if
4161 other parts are disabled. */
4162 i = first_old + 1;
4163 while (i < current_matrix->nrows - 1)
4165 int bottom = MATRIX_ROW_BOTTOM_Y (MATRIX_ROW (current_matrix, i));
4166 if (bottom <= yb)
4167 ++i;
4168 if (bottom >= yb)
4169 break;
4172 last_old = i;
4174 /* Skip over rows equal at the bottom. */
4175 i = last_new;
4176 j = last_old;
4177 while (i - 1 > first_new
4178 && j - 1 > first_old
4179 && MATRIX_ROW_ENABLED_P (current_matrix, j - 1)
4180 && (MATRIX_ROW (current_matrix, j - 1)->y
4181 == MATRIX_ROW (desired_matrix, i - 1)->y)
4182 && !MATRIX_ROW (desired_matrix, i - 1)->redraw_fringe_bitmaps_p
4183 && row_equal_p (MATRIX_ROW (desired_matrix, i - 1),
4184 MATRIX_ROW (current_matrix, j - 1), 1))
4185 --i, --j;
4186 last_new = i;
4187 last_old = j;
4189 /* Nothing to do if all rows are equal. */
4190 if (last_new == first_new)
4191 return 0;
4193 /* Check for integer overflow in size calculation.
4195 If next_almost_prime checks (N) for divisibility by 2..10, then
4196 it can return at most N + 10, e.g., next_almost_prime (1) == 11.
4197 So, set next_almost_prime_increment_max to 10.
4199 It's just a coincidence that next_almost_prime_increment_max ==
4200 NEXT_ALMOST_PRIME_LIMIT - 1. If NEXT_ALMOST_PRIME_LIMIT were
4201 13, then next_almost_prime_increment_max would be 14, e.g.,
4202 because next_almost_prime (113) would be 127. */
4204 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
4205 enum { next_almost_prime_increment_max = 10 };
4206 ptrdiff_t row_table_max =
4207 (min (PTRDIFF_MAX, SIZE_MAX) / (3 * sizeof *row_table)
4208 - next_almost_prime_increment_max);
4209 ptrdiff_t current_nrows_max = row_table_max - desired_matrix->nrows;
4210 if (current_nrows_max < current_matrix->nrows)
4211 memory_full (SIZE_MAX);
4214 /* Reallocate vectors, tables etc. if necessary. */
4216 if (current_matrix->nrows > old_lines_size)
4217 old_lines = xpalloc (old_lines, &old_lines_size,
4218 current_matrix->nrows - old_lines_size,
4219 INT_MAX, sizeof *old_lines);
4221 if (desired_matrix->nrows > new_lines_size)
4222 new_lines = xpalloc (new_lines, &new_lines_size,
4223 desired_matrix->nrows - new_lines_size,
4224 INT_MAX, sizeof *new_lines);
4226 n = desired_matrix->nrows;
4227 n += current_matrix->nrows;
4228 if (row_table_size < 3 * n)
4230 ptrdiff_t size = next_almost_prime (3 * n);
4231 row_table = xnrealloc (row_table, size, sizeof *row_table);
4232 row_table_size = size;
4233 memset (row_table, 0, size * sizeof *row_table);
4236 if (n > row_entry_pool_size)
4237 row_entry_pool = xpalloc (row_entry_pool, &row_entry_pool_size,
4238 n - row_entry_pool_size,
4239 -1, sizeof *row_entry_pool);
4241 if (desired_matrix->nrows > runs_size)
4243 runs = xnrealloc (runs, desired_matrix->nrows, sizeof *runs);
4244 run_pool = xnrealloc (run_pool, desired_matrix->nrows, sizeof *run_pool);
4245 runs_size = desired_matrix->nrows;
4248 nruns = run_idx = 0;
4249 row_entry_idx = 0;
4251 /* Add rows from the current and desired matrix to the hash table
4252 row_hash_table to be able to find equal ones quickly. */
4254 for (i = first_old; i < last_old; ++i)
4256 if (MATRIX_ROW_ENABLED_P (current_matrix, i))
4258 entry = add_row_entry (MATRIX_ROW (current_matrix, i));
4259 old_lines[i] = entry;
4260 ++entry->old_uses;
4262 else
4263 old_lines[i] = NULL;
4266 for (i = first_new; i < last_new; ++i)
4268 eassert (MATRIX_ROW_ENABLED_P (desired_matrix, i));
4269 entry = add_row_entry (MATRIX_ROW (desired_matrix, i));
4270 ++entry->new_uses;
4271 entry->new_line_number = i;
4272 new_lines[i] = entry;
4275 /* Identify moves based on lines that are unique and equal
4276 in both matrices. */
4277 for (i = first_old; i < last_old;)
4278 if (old_lines[i]
4279 && old_lines[i]->old_uses == 1
4280 && old_lines[i]->new_uses == 1)
4282 int p, q;
4283 int new_line = old_lines[i]->new_line_number;
4284 struct run *run = run_pool + run_idx++;
4286 /* Record move. */
4287 run->current_vpos = i;
4288 run->current_y = MATRIX_ROW (current_matrix, i)->y;
4289 run->desired_vpos = new_line;
4290 run->desired_y = MATRIX_ROW (desired_matrix, new_line)->y;
4291 run->nrows = 1;
4292 run->height = MATRIX_ROW (current_matrix, i)->height;
4294 /* Extend backward. */
4295 p = i - 1;
4296 q = new_line - 1;
4297 while (p > first_old
4298 && q > first_new
4299 && old_lines[p] == new_lines[q])
4301 int h = MATRIX_ROW (current_matrix, p)->height;
4302 --run->current_vpos;
4303 --run->desired_vpos;
4304 ++run->nrows;
4305 run->height += h;
4306 run->desired_y -= h;
4307 run->current_y -= h;
4308 --p, --q;
4311 /* Extend forward. */
4312 p = i + 1;
4313 q = new_line + 1;
4314 while (p < last_old
4315 && q < last_new
4316 && old_lines[p] == new_lines[q])
4318 int h = MATRIX_ROW (current_matrix, p)->height;
4319 ++run->nrows;
4320 run->height += h;
4321 ++p, ++q;
4324 /* Insert run into list of all runs. Order runs by copied
4325 pixel lines. Note that we record runs that don't have to
4326 be copied because they are already in place. This is done
4327 because we can avoid calling update_window_line in this
4328 case. */
4329 for (p = 0; p < nruns && runs[p]->height > run->height; ++p)
4331 for (q = nruns; q > p; --q)
4332 runs[q] = runs[q - 1];
4333 runs[p] = run;
4334 ++nruns;
4336 i += run->nrows;
4338 else
4339 ++i;
4341 /* Do the moves. Do it in a way that we don't overwrite something
4342 we want to copy later on. This is not solvable in general
4343 because there is only one display and we don't have a way to
4344 exchange areas on this display. Example:
4346 +-----------+ +-----------+
4347 | A | | B |
4348 +-----------+ --> +-----------+
4349 | B | | A |
4350 +-----------+ +-----------+
4352 Instead, prefer bigger moves, and invalidate moves that would
4353 copy from where we copied to. */
4355 for (i = 0; i < nruns; ++i)
4356 if (runs[i]->nrows > 0)
4358 struct run *r = runs[i];
4360 /* Copy on the display. */
4361 if (r->current_y != r->desired_y)
4363 rif->clear_window_mouse_face (w);
4364 rif->scroll_run_hook (w, r);
4367 /* Truncate runs that copy to where we copied to, and
4368 invalidate runs that copy from where we copied to. */
4369 for (j = nruns - 1; j > i; --j)
4371 struct run *p = runs[j];
4372 bool truncated_p = 0;
4374 if (p->nrows > 0
4375 && p->desired_y < r->desired_y + r->height
4376 && p->desired_y + p->height > r->desired_y)
4378 if (p->desired_y < r->desired_y)
4380 p->nrows = r->desired_vpos - p->desired_vpos;
4381 p->height = r->desired_y - p->desired_y;
4382 truncated_p = 1;
4384 else
4386 int nrows_copied = (r->desired_vpos + r->nrows
4387 - p->desired_vpos);
4389 if (p->nrows <= nrows_copied)
4390 p->nrows = 0;
4391 else
4393 int height_copied = (r->desired_y + r->height
4394 - p->desired_y);
4396 p->current_vpos += nrows_copied;
4397 p->desired_vpos += nrows_copied;
4398 p->nrows -= nrows_copied;
4399 p->current_y += height_copied;
4400 p->desired_y += height_copied;
4401 p->height -= height_copied;
4402 truncated_p = 1;
4407 if (r->current_y != r->desired_y
4408 /* The condition below is equivalent to
4409 ((p->current_y >= r->desired_y
4410 && p->current_y < r->desired_y + r->height)
4411 || (p->current_y + p->height > r->desired_y
4412 && (p->current_y + p->height
4413 <= r->desired_y + r->height)))
4414 because we have 0 < p->height <= r->height. */
4415 && p->current_y < r->desired_y + r->height
4416 && p->current_y + p->height > r->desired_y)
4417 p->nrows = 0;
4419 /* Reorder runs by copied pixel lines if truncated. */
4420 if (truncated_p && p->nrows > 0)
4422 int k = nruns - 1;
4424 while (runs[k]->nrows == 0 || runs[k]->height < p->height)
4425 k--;
4426 memmove (runs + j, runs + j + 1, (k - j) * sizeof (*runs));
4427 runs[k] = p;
4431 /* Assign matrix rows. */
4432 for (j = 0; j < r->nrows; ++j)
4434 struct glyph_row *from, *to;
4435 bool to_overlapped_p;
4437 to = MATRIX_ROW (current_matrix, r->desired_vpos + j);
4438 from = MATRIX_ROW (desired_matrix, r->desired_vpos + j);
4439 to_overlapped_p = to->overlapped_p;
4440 from->redraw_fringe_bitmaps_p = from->fringe_bitmap_periodic_p;
4441 assign_row (to, from);
4442 /* The above `assign_row' actually does swap, so if we had
4443 an overlap in the copy destination of two runs, then
4444 the second run would assign a previously disabled bogus
4445 row. But thanks to the truncation code in the
4446 preceding for-loop, we no longer have such an overlap,
4447 and thus the assigned row should always be enabled. */
4448 eassert (to->enabled_p);
4449 from->enabled_p = false;
4450 to->overlapped_p = to_overlapped_p;
4454 /* Clear the hash table, for the next time. */
4455 for (i = 0; i < row_entry_idx; ++i)
4456 row_table[row_entry_pool[i].bucket] = NULL;
4458 /* Value is 1 to indicate that we scrolled the display. */
4459 return nruns > 0;
4464 /************************************************************************
4465 Frame-Based Updates
4466 ************************************************************************/
4468 /* Update the desired frame matrix of frame F.
4470 FORCE_P means that the update should not be stopped by pending input.
4471 INHIBIT_ID_P means that scrolling by insert/delete should not be tried.
4472 SET_CURSOR_P false means do not set cursor at point in selected window.
4474 Value is true if update was stopped due to pending input. */
4476 static bool
4477 update_frame_1 (struct frame *f, bool force_p, bool inhibit_id_p,
4478 bool set_cursor_p, bool updating_menu_p)
4480 /* Frame matrices to work on. */
4481 struct glyph_matrix *current_matrix = f->current_matrix;
4482 struct glyph_matrix *desired_matrix = f->desired_matrix;
4483 int i;
4484 bool pause_p;
4485 int preempt_count = baud_rate / 2400 + 1;
4487 eassert (current_matrix && desired_matrix);
4489 if (baud_rate != FRAME_COST_BAUD_RATE (f))
4490 calculate_costs (f);
4492 if (preempt_count <= 0)
4493 preempt_count = 1;
4495 if (!force_p && detect_input_pending_ignore_squeezables ())
4497 pause_p = 1;
4498 goto do_pause;
4501 /* If we cannot insert/delete lines, it's no use trying it. */
4502 if (!FRAME_LINE_INS_DEL_OK (f))
4503 inhibit_id_p = 1;
4505 /* See if any of the desired lines are enabled; don't compute for
4506 i/d line if just want cursor motion. */
4507 for (i = 0; i < desired_matrix->nrows; i++)
4508 if (MATRIX_ROW_ENABLED_P (desired_matrix, i))
4509 break;
4511 /* Try doing i/d line, if not yet inhibited. */
4512 if (!inhibit_id_p && i < desired_matrix->nrows)
4513 force_p |= scrolling (f);
4515 /* Update the individual lines as needed. Do bottom line first. */
4516 if (MATRIX_ROW_ENABLED_P (desired_matrix, desired_matrix->nrows - 1))
4517 update_frame_line (f, desired_matrix->nrows - 1, updating_menu_p);
4519 /* Now update the rest of the lines. */
4520 for (i = 0; i < desired_matrix->nrows - 1 && (force_p || !input_pending); i++)
4522 if (MATRIX_ROW_ENABLED_P (desired_matrix, i))
4524 if (FRAME_TERMCAP_P (f))
4526 /* Flush out every so many lines.
4527 Also flush out if likely to have more than 1k buffered
4528 otherwise. I'm told that some telnet connections get
4529 really screwed by more than 1k output at once. */
4530 FILE *display_output = FRAME_TTY (f)->output;
4531 if (display_output)
4533 ptrdiff_t outq = __fpending (display_output);
4534 if (outq > 900
4535 || (outq > 20 && ((i - 1) % preempt_count == 0)))
4536 fflush_unlocked (display_output);
4540 if (!force_p && (i - 1) % preempt_count == 0)
4541 detect_input_pending_ignore_squeezables ();
4543 update_frame_line (f, i, updating_menu_p);
4547 pause_p = 0 < i && i < FRAME_TOTAL_LINES (f) - 1;
4549 /* Now just clean up termcap drivers and set cursor, etc. */
4550 if (!pause_p && set_cursor_p)
4552 if ((cursor_in_echo_area
4553 /* If we are showing a message instead of the mini-buffer,
4554 show the cursor for the message instead of for the
4555 (now hidden) mini-buffer contents. */
4556 || (EQ (minibuf_window, selected_window)
4557 && EQ (minibuf_window, echo_area_window)
4558 && !NILP (echo_area_buffer[0])))
4559 /* These cases apply only to the frame that contains
4560 the active mini-buffer window. */
4561 && FRAME_HAS_MINIBUF_P (f)
4562 && EQ (FRAME_MINIBUF_WINDOW (f), echo_area_window))
4564 int top = WINDOW_TOP_EDGE_LINE (XWINDOW (FRAME_MINIBUF_WINDOW (f)));
4565 int col;
4567 /* Put cursor at the end of the prompt. If the mini-buffer
4568 is several lines high, find the last line that has
4569 any text on it. */
4570 int row = FRAME_TOTAL_LINES (f);
4573 row--;
4574 col = 0;
4576 if (MATRIX_ROW_ENABLED_P (current_matrix, row))
4578 /* Frame rows are filled up with spaces that
4579 must be ignored here. */
4580 struct glyph_row *r = MATRIX_ROW (current_matrix, row);
4581 struct glyph *start = r->glyphs[TEXT_AREA];
4583 col = r->used[TEXT_AREA];
4584 while (0 < col && start[col - 1].charpos < 0)
4585 col--;
4588 while (row > top && col == 0);
4590 /* Make sure COL is not out of range. */
4591 if (col >= FRAME_CURSOR_X_LIMIT (f))
4593 /* If we have another row, advance cursor into it. */
4594 if (row < FRAME_TOTAL_LINES (f) - 1)
4596 col = FRAME_LEFT_SCROLL_BAR_COLS (f);
4597 row++;
4599 /* Otherwise move it back in range. */
4600 else
4601 col = FRAME_CURSOR_X_LIMIT (f) - 1;
4604 cursor_to (f, row, col);
4606 else
4608 /* We have only one cursor on terminal frames. Use it to
4609 display the cursor of the selected window. */
4610 struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
4611 if (w->cursor.vpos >= 0
4612 /* The cursor vpos may be temporarily out of bounds
4613 in the following situation: There is one window,
4614 with the cursor in the lower half of it. The window
4615 is split, and a message causes a redisplay before
4616 a new cursor position has been computed. */
4617 && w->cursor.vpos < WINDOW_TOTAL_LINES (w))
4619 int x = WINDOW_TO_FRAME_HPOS (w, w->cursor.hpos);
4620 int y = WINDOW_TO_FRAME_VPOS (w, w->cursor.vpos);
4622 x += max (0, w->left_margin_cols);
4623 cursor_to (f, y, x);
4628 do_pause:
4630 clear_desired_matrices (f);
4631 return pause_p;
4635 /* Do line insertions/deletions on frame F for frame-based redisplay. */
4637 static bool
4638 scrolling (struct frame *frame)
4640 int unchanged_at_top, unchanged_at_bottom;
4641 int window_size;
4642 int changed_lines;
4643 int i;
4644 int height = FRAME_TOTAL_LINES (frame);
4645 int free_at_end_vpos = height;
4646 struct glyph_matrix *current_matrix = frame->current_matrix;
4647 struct glyph_matrix *desired_matrix = frame->desired_matrix;
4648 verify (sizeof (int) <= sizeof (unsigned));
4649 verify (alignof (unsigned) % alignof (int) == 0);
4650 unsigned *old_hash;
4651 USE_SAFE_ALLOCA;
4652 SAFE_NALLOCA (old_hash, 4, height);
4653 unsigned *new_hash = old_hash + height;
4654 int *draw_cost = (int *) (new_hash + height);
4655 int *old_draw_cost = draw_cost + height;
4656 old_hash = ptr_bounds_clip (old_hash, height * sizeof *old_hash);
4657 new_hash = ptr_bounds_clip (new_hash, height * sizeof *new_hash);
4658 draw_cost = ptr_bounds_clip (draw_cost, height * sizeof *draw_cost);
4659 old_draw_cost = ptr_bounds_clip (old_draw_cost,
4660 height * sizeof *old_draw_cost);
4662 eassert (current_matrix);
4664 /* Compute hash codes of all the lines. Also calculate number of
4665 changed lines, number of unchanged lines at the beginning, and
4666 number of unchanged lines at the end. */
4667 changed_lines = 0;
4668 unchanged_at_top = 0;
4669 unchanged_at_bottom = height;
4670 for (i = 0; i < height; i++)
4672 /* Give up on this scrolling if some old lines are not enabled. */
4673 if (!MATRIX_ROW_ENABLED_P (current_matrix, i))
4675 SAFE_FREE ();
4676 return false;
4678 old_hash[i] = line_hash_code (frame, MATRIX_ROW (current_matrix, i));
4679 if (! MATRIX_ROW_ENABLED_P (desired_matrix, i))
4681 /* This line cannot be redrawn, so don't let scrolling mess it. */
4682 new_hash[i] = old_hash[i];
4683 #define INFINITY 1000000 /* Taken from scroll.c */
4684 draw_cost[i] = INFINITY;
4686 else
4688 new_hash[i] = line_hash_code (frame, MATRIX_ROW (desired_matrix, i));
4689 draw_cost[i] = line_draw_cost (frame, desired_matrix, i);
4692 if (old_hash[i] != new_hash[i])
4694 changed_lines++;
4695 unchanged_at_bottom = height - i - 1;
4697 else if (i == unchanged_at_top)
4698 unchanged_at_top++;
4699 old_draw_cost[i] = line_draw_cost (frame, current_matrix, i);
4702 /* If changed lines are few, don't allow preemption, don't scroll. */
4703 if ((!FRAME_SCROLL_REGION_OK (frame)
4704 && changed_lines < baud_rate / 2400)
4705 || unchanged_at_bottom == height)
4707 SAFE_FREE ();
4708 return true;
4711 window_size = (height - unchanged_at_top
4712 - unchanged_at_bottom);
4714 if (FRAME_SCROLL_REGION_OK (frame))
4715 free_at_end_vpos -= unchanged_at_bottom;
4716 else if (FRAME_MEMORY_BELOW_FRAME (frame))
4717 free_at_end_vpos = -1;
4719 /* Do id/calc only if small window, or slow terminal, or many lines
4720 in common between current frame and desired frame. But the
4721 window size must be at least 2. */
4722 if ((FRAME_SCROLL_REGION_OK (frame)
4723 || window_size < 18 || baud_rate <= 2400
4724 || (window_size
4725 < 10 * scrolling_max_lines_saved (unchanged_at_top,
4726 height - unchanged_at_bottom,
4727 old_hash, new_hash, draw_cost)))
4728 && 2 <= window_size)
4729 scrolling_1 (frame, window_size, unchanged_at_top, unchanged_at_bottom,
4730 draw_cost + unchanged_at_top - 1,
4731 old_draw_cost + unchanged_at_top - 1,
4732 old_hash + unchanged_at_top - 1,
4733 new_hash + unchanged_at_top - 1,
4734 free_at_end_vpos - unchanged_at_top);
4736 SAFE_FREE ();
4737 return false;
4741 /* Count the number of blanks at the start of the vector of glyphs R
4742 which is LEN glyphs long. */
4744 static int
4745 count_blanks (struct glyph *r, int len)
4747 int i;
4749 for (i = 0; i < len; ++i)
4750 if (!CHAR_GLYPH_SPACE_P (r[i]))
4751 break;
4753 return i;
4757 /* Count the number of glyphs in common at the start of the glyph
4758 vectors STR1 and STR2. END1 is the end of STR1 and END2 is the end
4759 of STR2. Value is the number of equal glyphs equal at the start. */
4761 static int
4762 count_match (struct glyph *str1, struct glyph *end1, struct glyph *str2, struct glyph *end2)
4764 struct glyph *p1 = str1;
4765 struct glyph *p2 = str2;
4767 while (p1 < end1
4768 && p2 < end2
4769 && GLYPH_CHAR_AND_FACE_EQUAL_P (p1, p2))
4770 ++p1, ++p2;
4772 return p1 - str1;
4776 /* Char insertion/deletion cost vector, from term.c */
4778 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_TOTAL_COLS ((f))])
4781 /* Perform a frame-based update on line VPOS in frame FRAME. */
4783 static void
4784 update_frame_line (struct frame *f, int vpos, bool updating_menu_p)
4786 struct glyph *obody, *nbody, *op1, *op2, *np1, *nend;
4787 int tem;
4788 int osp, nsp, begmatch, endmatch, olen, nlen;
4789 struct glyph_matrix *current_matrix = f->current_matrix;
4790 struct glyph_matrix *desired_matrix = f->desired_matrix;
4791 struct glyph_row *current_row = MATRIX_ROW (current_matrix, vpos);
4792 struct glyph_row *desired_row = MATRIX_ROW (desired_matrix, vpos);
4793 bool must_write_whole_line_p;
4794 bool write_spaces_p = FRAME_MUST_WRITE_SPACES (f);
4795 bool colored_spaces_p = (FACE_FROM_ID (f, DEFAULT_FACE_ID)->background
4796 != FACE_TTY_DEFAULT_BG_COLOR);
4798 if (colored_spaces_p)
4799 write_spaces_p = 1;
4801 /* Current row not enabled means it has unknown contents. We must
4802 write the whole desired line in that case. */
4803 must_write_whole_line_p = !current_row->enabled_p;
4804 if (must_write_whole_line_p)
4806 obody = 0;
4807 olen = 0;
4809 else
4811 obody = MATRIX_ROW_GLYPH_START (current_matrix, vpos);
4812 olen = current_row->used[TEXT_AREA];
4814 /* Ignore trailing spaces, if we can. */
4815 if (!write_spaces_p)
4816 while (olen > 0 && CHAR_GLYPH_SPACE_P (obody[olen-1]))
4817 olen--;
4820 current_row->enabled_p = true;
4821 current_row->used[TEXT_AREA] = desired_row->used[TEXT_AREA];
4823 /* For some reason, cursor is sometimes moved behind our back when a
4824 frame with a TTY menu is redrawn. Homing the cursor as below
4825 fixes that. */
4826 if (updating_menu_p)
4827 cursor_to (f, 0, 0);
4829 /* If desired line is empty, just clear the line. */
4830 if (!desired_row->enabled_p)
4832 nlen = 0;
4833 goto just_erase;
4836 nbody = desired_row->glyphs[TEXT_AREA];
4837 nlen = desired_row->used[TEXT_AREA];
4838 nend = nbody + nlen;
4840 /* If display line has unknown contents, write the whole line. */
4841 if (must_write_whole_line_p)
4843 /* Ignore spaces at the end, if we can. */
4844 if (!write_spaces_p)
4845 while (nlen > 0 && CHAR_GLYPH_SPACE_P (nbody[nlen - 1]))
4846 --nlen;
4848 /* Write the contents of the desired line. */
4849 if (nlen)
4851 cursor_to (f, vpos, 0);
4852 write_glyphs (f, nbody, nlen);
4855 /* Don't call clear_end_of_line if we already wrote the whole
4856 line. The cursor will not be at the right margin in that
4857 case but in the line below. */
4858 if (nlen < FRAME_TOTAL_COLS (f))
4860 cursor_to (f, vpos, nlen);
4861 clear_end_of_line (f, FRAME_TOTAL_COLS (f));
4863 else
4864 /* Make sure we are in the right row, otherwise cursor movement
4865 with cmgoto might use `ch' in the wrong row. */
4866 cursor_to (f, vpos, 0);
4868 make_current (desired_matrix, current_matrix, vpos);
4869 return;
4872 /* Pretend trailing spaces are not there at all,
4873 unless for one reason or another we must write all spaces. */
4874 if (!write_spaces_p)
4875 while (nlen > 0 && CHAR_GLYPH_SPACE_P (nbody[nlen - 1]))
4876 nlen--;
4878 /* If there's no i/d char, quickly do the best we can without it. */
4879 if (!FRAME_CHAR_INS_DEL_OK (f))
4881 int i, j;
4883 /* Find the first glyph in desired row that doesn't agree with
4884 a glyph in the current row, and write the rest from there on. */
4885 for (i = 0; i < nlen; i++)
4887 if (i >= olen || !GLYPH_EQUAL_P (nbody + i, obody + i))
4889 /* Find the end of the run of different glyphs. */
4890 j = i + 1;
4891 while (j < nlen
4892 && (j >= olen
4893 || !GLYPH_EQUAL_P (nbody + j, obody + j)
4894 || CHAR_GLYPH_PADDING_P (nbody[j])))
4895 ++j;
4897 /* Output this run of non-matching chars. */
4898 cursor_to (f, vpos, i);
4899 write_glyphs (f, nbody + i, j - i);
4900 i = j - 1;
4902 /* Now find the next non-match. */
4906 /* Clear the rest of the line, or the non-clear part of it. */
4907 if (olen > nlen)
4909 cursor_to (f, vpos, nlen);
4910 clear_end_of_line (f, olen);
4913 /* Make current row = desired row. */
4914 make_current (desired_matrix, current_matrix, vpos);
4915 return;
4918 /* Here when CHAR_INS_DEL_OK != 0, i.e. we can insert or delete
4919 characters in a row. */
4921 if (!olen)
4923 /* If current line is blank, skip over initial spaces, if
4924 possible, and write the rest. */
4925 if (write_spaces_p)
4926 nsp = 0;
4927 else
4928 nsp = count_blanks (nbody, nlen);
4930 if (nlen > nsp)
4932 cursor_to (f, vpos, nsp);
4933 write_glyphs (f, nbody + nsp, nlen - nsp);
4936 /* Exchange contents between current_frame and new_frame. */
4937 make_current (desired_matrix, current_matrix, vpos);
4938 return;
4941 /* Compute number of leading blanks in old and new contents. */
4942 osp = count_blanks (obody, olen);
4943 nsp = (colored_spaces_p ? 0 : count_blanks (nbody, nlen));
4945 /* Compute number of matching chars starting with first non-blank. */
4946 begmatch = count_match (obody + osp, obody + olen,
4947 nbody + nsp, nbody + nlen);
4949 /* Spaces in new match implicit space past the end of old. */
4950 /* A bug causing this to be a no-op was fixed in 18.29. */
4951 if (!write_spaces_p && osp + begmatch == olen)
4953 np1 = nbody + nsp;
4954 while (np1 + begmatch < nend && CHAR_GLYPH_SPACE_P (np1[begmatch]))
4955 ++begmatch;
4958 /* Avoid doing insert/delete char
4959 just cause number of leading spaces differs
4960 when the following text does not match. */
4961 if (begmatch == 0 && osp != nsp)
4962 osp = nsp = min (osp, nsp);
4964 /* Find matching characters at end of line */
4965 op1 = obody + olen;
4966 np1 = nbody + nlen;
4967 op2 = op1 + begmatch - min (olen - osp, nlen - nsp);
4968 while (op1 > op2
4969 && GLYPH_EQUAL_P (op1 - 1, np1 - 1))
4971 op1--;
4972 np1--;
4974 endmatch = obody + olen - op1;
4976 /* tem gets the distance to insert or delete.
4977 endmatch is how many characters we save by doing so.
4978 Is it worth it? */
4980 tem = (nlen - nsp) - (olen - osp);
4981 if (endmatch && tem
4982 && (!FRAME_CHAR_INS_DEL_OK (f)
4983 || endmatch <= char_ins_del_cost (f)[tem]))
4984 endmatch = 0;
4986 /* nsp - osp is the distance to insert or delete.
4987 If that is nonzero, begmatch is known to be nonzero also.
4988 begmatch + endmatch is how much we save by doing the ins/del.
4989 Is it worth it? */
4991 if (nsp != osp
4992 && (!FRAME_CHAR_INS_DEL_OK (f)
4993 || begmatch + endmatch <= char_ins_del_cost (f)[nsp - osp]))
4995 begmatch = 0;
4996 endmatch = 0;
4997 osp = nsp = min (osp, nsp);
5000 /* Now go through the line, inserting, writing and
5001 deleting as appropriate. */
5003 if (osp > nsp)
5005 cursor_to (f, vpos, nsp);
5006 delete_glyphs (f, osp - nsp);
5008 else if (nsp > osp)
5010 /* If going to delete chars later in line
5011 and insert earlier in the line,
5012 must delete first to avoid losing data in the insert */
5013 if (endmatch && nlen < olen + nsp - osp)
5015 cursor_to (f, vpos, nlen - endmatch + osp - nsp);
5016 delete_glyphs (f, olen + nsp - osp - nlen);
5017 olen = nlen - (nsp - osp);
5019 cursor_to (f, vpos, osp);
5020 insert_glyphs (f, 0, nsp - osp);
5022 olen += nsp - osp;
5024 tem = nsp + begmatch + endmatch;
5025 if (nlen != tem || olen != tem)
5027 if (!endmatch || nlen == olen)
5029 /* If new text being written reaches right margin, there is
5030 no need to do clear-to-eol at the end of this function
5031 (and it would not be safe, since cursor is not going to
5032 be "at the margin" after the text is done). */
5033 if (nlen == FRAME_TOTAL_COLS (f))
5034 olen = 0;
5036 /* Function write_glyphs is prepared to do nothing
5037 if passed a length <= 0. Check it here to avoid
5038 unnecessary cursor movement. */
5039 if (nlen - tem > 0)
5041 cursor_to (f, vpos, nsp + begmatch);
5042 write_glyphs (f, nbody + nsp + begmatch, nlen - tem);
5045 else if (nlen > olen)
5047 /* Here, we used to have the following simple code:
5048 ----------------------------------------
5049 write_glyphs (nbody + nsp + begmatch, olen - tem);
5050 insert_glyphs (nbody + nsp + begmatch + olen - tem, nlen - olen);
5051 ----------------------------------------
5052 but it doesn't work if nbody[nsp + begmatch + olen - tem]
5053 is a padding glyph. */
5054 int out = olen - tem; /* Columns to be overwritten originally. */
5055 int del;
5057 cursor_to (f, vpos, nsp + begmatch);
5059 /* Calculate columns we can actually overwrite. */
5060 while (CHAR_GLYPH_PADDING_P (nbody[nsp + begmatch + out]))
5061 out--;
5062 write_glyphs (f, nbody + nsp + begmatch, out);
5064 /* If we left columns to be overwritten, we must delete them. */
5065 del = olen - tem - out;
5066 if (del > 0)
5067 delete_glyphs (f, del);
5069 /* At last, we insert columns not yet written out. */
5070 insert_glyphs (f, nbody + nsp + begmatch + out, nlen - olen + del);
5071 olen = nlen;
5073 else if (olen > nlen)
5075 cursor_to (f, vpos, nsp + begmatch);
5076 write_glyphs (f, nbody + nsp + begmatch, nlen - tem);
5077 delete_glyphs (f, olen - nlen);
5078 olen = nlen;
5082 just_erase:
5083 /* If any unerased characters remain after the new line, erase them. */
5084 if (olen > nlen)
5086 cursor_to (f, vpos, nlen);
5087 clear_end_of_line (f, olen);
5090 /* Exchange contents between current_frame and new_frame. */
5091 make_current (desired_matrix, current_matrix, vpos);
5096 /***********************************************************************
5097 X/Y Position -> Buffer Position
5098 ***********************************************************************/
5100 /* Determine what's under window-relative pixel position (*X, *Y).
5101 Return the OBJECT (string or buffer) that's there.
5102 Return in *POS the position in that object.
5103 Adjust *X and *Y to character positions.
5104 Return in *DX and *DY the pixel coordinates of the click,
5105 relative to the top left corner of OBJECT, or relative to
5106 the top left corner of the character glyph at (*X, *Y)
5107 if OBJECT is nil.
5108 Return WIDTH and HEIGHT of the object at (*X, *Y), or zero
5109 if the coordinates point to an empty area of the display. */
5111 Lisp_Object
5112 buffer_posn_from_coords (struct window *w, int *x, int *y, struct display_pos *pos, Lisp_Object *object, int *dx, int *dy, int *width, int *height)
5114 struct it it;
5115 Lisp_Object old_current_buffer = Fcurrent_buffer ();
5116 struct text_pos startp;
5117 Lisp_Object string;
5118 struct glyph_row *row;
5119 #ifdef HAVE_WINDOW_SYSTEM
5120 struct image *img = 0;
5121 #endif
5122 int x0, x1, to_x, it_vpos;
5123 void *itdata = NULL;
5125 /* We used to set current_buffer directly here, but that does the
5126 wrong thing with `face-remapping-alist' (bug#2044). */
5127 Fset_buffer (w->contents);
5128 itdata = bidi_shelve_cache ();
5129 CLIP_TEXT_POS_FROM_MARKER (startp, w->start);
5130 start_display (&it, w, startp);
5131 x0 = *x;
5133 /* First, move to the beginning of the row corresponding to *Y. We
5134 need to be in that row to get the correct value of base paragraph
5135 direction for the text at (*X, *Y). */
5136 move_it_to (&it, -1, 0, *y, -1, MOVE_TO_X | MOVE_TO_Y);
5138 /* TO_X is the pixel position that the iterator will compute for the
5139 glyph at *X. */
5140 to_x = x0;
5141 if (it.bidi_it.paragraph_dir == R2L)
5142 /* For lines in an R2L paragraph, we need to mirror TO_X wrt the
5143 text area. This is because the iterator, even in R2L
5144 paragraphs, delivers glyphs as if they started at the left
5145 margin of the window. (When we actually produce glyphs for
5146 display, we reverse their order in PRODUCE_GLYPHS, but the
5147 iterator doesn't know about that.) The following line adjusts
5148 the pixel position to the iterator geometry, which is what
5149 move_it_* routines use. (The -1 is because in a window whose
5150 text-area width is W, the rightmost pixel position is W-1, and
5151 it should be mirrored into zero pixel position.) */
5152 to_x = window_box_width (w, TEXT_AREA) - to_x - 1;
5154 /* We need to add it.first_visible_x because iterator positions
5155 include the hscroll. */
5156 to_x += it.first_visible_x;
5158 /* If we are hscrolling only the current line, and Y is at the line
5159 containing point, augment TO_X with the hscroll amount of the
5160 current line. */
5161 if (it.line_wrap == TRUNCATE
5162 && EQ (automatic_hscrolling, Qcurrent_line) && IT_CHARPOS (it) < PT)
5164 struct it it2 = it;
5165 void *it2data = bidi_shelve_cache ();
5166 it2.last_visible_x = 1000000;
5167 /* If the line at Y shows point, the call below to
5168 move_it_in_display_line will succeed in reaching point. */
5169 move_it_in_display_line (&it2, PT, -1, MOVE_TO_POS);
5170 if (IT_CHARPOS (it2) >= PT)
5172 to_x += (w->hscroll - w->min_hscroll) * FRAME_COLUMN_WIDTH (it.f);
5173 /* We need to pretend the window is hscrolled, so that
5174 move_it_in_display_line below will DTRT with TO_X. */
5175 it.first_visible_x += w->hscroll * FRAME_COLUMN_WIDTH (it.f);
5176 it.last_visible_x += w->hscroll * FRAME_COLUMN_WIDTH (it.f);
5178 bidi_unshelve_cache (it2data, 0);
5181 /* Now move horizontally in the row to the glyph under *X. Second
5182 argument is ZV to prevent move_it_in_display_line from matching
5183 based on buffer positions. */
5184 move_it_in_display_line (&it, ZV, to_x, MOVE_TO_X);
5185 bidi_unshelve_cache (itdata, 0);
5187 Fset_buffer (old_current_buffer);
5189 *dx = to_x - it.current_x;
5190 *dy = *y - it.current_y;
5192 string = w->contents;
5193 if (STRINGP (it.string))
5194 string = it.string;
5195 *pos = it.current;
5196 if (it.what == IT_COMPOSITION
5197 && it.cmp_it.nchars > 1
5198 && it.cmp_it.reversed_p)
5200 /* The current display element is a grapheme cluster in a
5201 composition. In that case, we need the position of the first
5202 character of the cluster. But, as it.cmp_it.reversed_p is 1,
5203 it.current points to the last character of the cluster, thus
5204 we must move back to the first character of the same
5205 cluster. */
5206 CHARPOS (pos->pos) -= it.cmp_it.nchars - 1;
5207 if (STRINGP (it.string))
5208 BYTEPOS (pos->pos) = string_char_to_byte (string, CHARPOS (pos->pos));
5209 else
5210 BYTEPOS (pos->pos) = buf_charpos_to_bytepos (XBUFFER (w->contents),
5211 CHARPOS (pos->pos));
5214 #ifdef HAVE_WINDOW_SYSTEM
5215 if (it.what == IT_IMAGE)
5217 img = IMAGE_OPT_FROM_ID (it.f, it.image_id);
5218 if (img && !NILP (img->spec))
5219 *object = img->spec;
5221 #endif
5223 /* IT's vpos counts from the glyph row that includes the window's
5224 start position, i.e. it excludes the header-line row, but
5225 MATRIX_ROW includes the header-line row. Adjust for a possible
5226 header-line row. */
5227 it_vpos = it.vpos + window_wants_header_line (w);
5228 if (it_vpos < w->current_matrix->nrows
5229 && (row = MATRIX_ROW (w->current_matrix, it_vpos),
5230 row->enabled_p))
5232 if (it.hpos < row->used[TEXT_AREA])
5234 struct glyph *glyph = row->glyphs[TEXT_AREA] + it.hpos;
5235 #ifdef HAVE_WINDOW_SYSTEM
5236 if (img)
5238 *dy -= row->ascent - glyph->ascent;
5239 *dx += glyph->slice.img.x;
5240 *dy += glyph->slice.img.y;
5241 /* Image slices positions are still relative to the entire image */
5242 *width = img->width;
5243 *height = img->height;
5245 else
5246 #endif
5248 *width = glyph->pixel_width;
5249 *height = glyph->ascent + glyph->descent;
5252 else
5254 *width = 0;
5255 *height = row->height;
5258 else
5260 *width = *height = 0;
5263 /* Add extra (default width) columns if clicked after EOL. */
5264 x1 = max (0, it.current_x + it.pixel_width);
5265 if (to_x > x1)
5266 it.hpos += (to_x - x1) / WINDOW_FRAME_COLUMN_WIDTH (w);
5268 *x = it.hpos;
5269 *y = it.vpos;
5271 return string;
5275 /* Value is the string under window-relative coordinates X/Y in the
5276 mode line or header line (PART says which) of window W, or nil if none.
5277 *CHARPOS is set to the position in the string returned. */
5279 Lisp_Object
5280 mode_line_string (struct window *w, enum window_part part,
5281 int *x, int *y, ptrdiff_t *charpos, Lisp_Object *object,
5282 int *dx, int *dy, int *width, int *height)
5284 struct glyph_row *row;
5285 struct glyph *glyph, *end;
5286 int x0, y0;
5287 Lisp_Object string = Qnil;
5289 if (part == ON_MODE_LINE)
5290 row = MATRIX_MODE_LINE_ROW (w->current_matrix);
5291 else
5292 row = MATRIX_HEADER_LINE_ROW (w->current_matrix);
5293 y0 = *y - row->y;
5294 *y = row - MATRIX_FIRST_TEXT_ROW (w->current_matrix);
5296 if (row->mode_line_p && row->enabled_p)
5298 /* Find the glyph under X. If we find one with a string object,
5299 it's the one we were looking for. */
5300 glyph = row->glyphs[TEXT_AREA];
5301 end = glyph + row->used[TEXT_AREA];
5302 for (x0 = *x; glyph < end && x0 >= glyph->pixel_width; ++glyph)
5303 x0 -= glyph->pixel_width;
5304 *x = glyph - row->glyphs[TEXT_AREA];
5305 if (glyph < end)
5307 string = glyph->object;
5308 *charpos = glyph->charpos;
5309 *width = glyph->pixel_width;
5310 *height = glyph->ascent + glyph->descent;
5311 #ifdef HAVE_WINDOW_SYSTEM
5312 if (glyph->type == IMAGE_GLYPH)
5314 struct image *img;
5315 img = IMAGE_OPT_FROM_ID (WINDOW_XFRAME (w), glyph->u.img_id);
5316 if (img != NULL)
5317 *object = img->spec;
5318 y0 -= row->ascent - glyph->ascent;
5320 #endif
5322 else
5324 /* Add extra (default width) columns if clicked after EOL. */
5325 *x += x0 / WINDOW_FRAME_COLUMN_WIDTH (w);
5326 *width = 0;
5327 *height = row->height;
5330 else
5332 *x = 0;
5333 x0 = 0;
5334 *width = *height = 0;
5337 *dx = x0;
5338 *dy = y0;
5340 return string;
5344 /* Value is the string under window-relative coordinates X/Y in either
5345 marginal area, or nil if none. *CHARPOS is set to the position in
5346 the string returned. */
5348 Lisp_Object
5349 marginal_area_string (struct window *w, enum window_part part,
5350 int *x, int *y, ptrdiff_t *charpos, Lisp_Object *object,
5351 int *dx, int *dy, int *width, int *height)
5353 struct glyph_row *row = w->current_matrix->rows;
5354 struct glyph *glyph, *end;
5355 int x0, y0, i, wy = *y;
5356 int area;
5357 Lisp_Object string = Qnil;
5359 if (part == ON_LEFT_MARGIN)
5360 area = LEFT_MARGIN_AREA;
5361 else if (part == ON_RIGHT_MARGIN)
5362 area = RIGHT_MARGIN_AREA;
5363 else
5364 emacs_abort ();
5366 for (i = 0; row->enabled_p && i < w->current_matrix->nrows; ++i, ++row)
5367 if (wy >= row->y && wy < MATRIX_ROW_BOTTOM_Y (row))
5368 break;
5369 y0 = *y - row->y;
5370 *y = row - MATRIX_FIRST_TEXT_ROW (w->current_matrix);
5372 if (row->enabled_p)
5374 /* Find the glyph under X. If we find one with a string object,
5375 it's the one we were looking for. */
5376 if (area == RIGHT_MARGIN_AREA)
5377 x0 = ((WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5378 ? WINDOW_LEFT_FRINGE_WIDTH (w)
5379 : WINDOW_FRINGES_WIDTH (w))
5380 + window_box_width (w, LEFT_MARGIN_AREA)
5381 + window_box_width (w, TEXT_AREA));
5382 else
5383 x0 = (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5384 ? WINDOW_LEFT_FRINGE_WIDTH (w)
5385 : 0);
5387 glyph = row->glyphs[area];
5388 end = glyph + row->used[area];
5389 for (x0 = *x - x0; glyph < end && x0 >= glyph->pixel_width; ++glyph)
5390 x0 -= glyph->pixel_width;
5391 *x = glyph - row->glyphs[area];
5392 if (glyph < end)
5394 string = glyph->object;
5395 *charpos = glyph->charpos;
5396 *width = glyph->pixel_width;
5397 *height = glyph->ascent + glyph->descent;
5398 #ifdef HAVE_WINDOW_SYSTEM
5399 if (glyph->type == IMAGE_GLYPH)
5401 struct image *img;
5402 img = IMAGE_OPT_FROM_ID (WINDOW_XFRAME (w), glyph->u.img_id);
5403 if (img != NULL)
5404 *object = img->spec;
5405 y0 -= row->ascent - glyph->ascent;
5406 x0 += glyph->slice.img.x;
5407 y0 += glyph->slice.img.y;
5409 #endif
5411 else
5413 /* Add extra (default width) columns if clicked after EOL. */
5414 *x += x0 / WINDOW_FRAME_COLUMN_WIDTH (w);
5415 *width = 0;
5416 *height = row->height;
5419 else
5421 x0 = 0;
5422 *x = 0;
5423 *width = *height = 0;
5426 *dx = x0;
5427 *dy = y0;
5429 return string;
5433 /***********************************************************************
5434 Changing Frame Sizes
5435 ***********************************************************************/
5437 #ifdef SIGWINCH
5439 static void deliver_window_change_signal (int);
5441 static void
5442 handle_window_change_signal (int sig)
5444 int width, height;
5445 struct tty_display_info *tty;
5447 /* The frame size change obviously applies to a single
5448 termcap-controlled terminal, but we can't decide which.
5449 Therefore, we resize the frames corresponding to each tty.
5451 for (tty = tty_list; tty; tty = tty->next) {
5453 if (! tty->term_initted)
5454 continue;
5456 /* Suspended tty frames have tty->input == NULL avoid trying to
5457 use it. */
5458 if (!tty->input)
5459 continue;
5461 get_tty_size (fileno (tty->input), &width, &height);
5463 if (width > 5 && height > 2) {
5464 Lisp_Object tail, frame;
5466 FOR_EACH_FRAME (tail, frame)
5467 if (FRAME_TERMCAP_P (XFRAME (frame)) && FRAME_TTY (XFRAME (frame)) == tty)
5468 /* Record the new sizes, but don't reallocate the data
5469 structures now. Let that be done later outside of the
5470 signal handler. */
5471 change_frame_size (XFRAME (frame), width,
5472 height - FRAME_MENU_BAR_LINES (XFRAME (frame)),
5473 0, 1, 0, 0);
5478 static void
5479 deliver_window_change_signal (int sig)
5481 deliver_process_signal (sig, handle_window_change_signal);
5483 #endif /* SIGWINCH */
5486 /* Do any change in frame size that was requested by a signal.
5487 SAFE means this function is called from a place where it is
5488 safe to change frame sizes while a redisplay is in progress. */
5490 void
5491 do_pending_window_change (bool safe)
5493 /* If window change signal handler should have run before, run it now. */
5494 if (redisplaying_p && !safe)
5495 return;
5497 while (delayed_size_change)
5499 Lisp_Object tail, frame;
5501 delayed_size_change = 0;
5503 FOR_EACH_FRAME (tail, frame)
5505 struct frame *f = XFRAME (frame);
5507 if (f->new_height != 0 || f->new_width != 0)
5508 change_frame_size (f, f->new_width, f->new_height,
5509 0, 0, safe, f->new_pixelwise);
5515 static void
5516 change_frame_size_1 (struct frame *f, int new_width, int new_height,
5517 bool pretend, bool delay, bool safe, bool pixelwise)
5519 /* If we can't deal with the change now, queue it for later. */
5520 if (delay || (redisplaying_p && !safe))
5522 f->new_width = new_width;
5523 f->new_height = new_height;
5524 f->new_pixelwise = pixelwise;
5525 delayed_size_change = 1;
5527 else
5529 /* This size-change overrides any pending one for this frame. */
5530 f->new_height = 0;
5531 f->new_width = 0;
5532 f->new_pixelwise = 0;
5534 /* If an argument is zero, set it to the current value. */
5535 if (pixelwise)
5537 new_width = (new_width <= 0) ? FRAME_TEXT_WIDTH (f) : new_width;
5538 new_height = (new_height <= 0) ? FRAME_TEXT_HEIGHT (f) : new_height;
5540 else
5542 new_width = (((new_width <= 0) ? FRAME_COLS (f) : new_width)
5543 * FRAME_COLUMN_WIDTH (f));
5544 new_height = (((new_height <= 0) ? FRAME_LINES (f) : new_height)
5545 * FRAME_LINE_HEIGHT (f));
5548 /* Adjust frame size but make sure x_set_window_size does not
5549 get called. */
5550 adjust_frame_size (f, new_width, new_height, 5, pretend,
5551 Qchange_frame_size);
5556 /* Change text height/width of frame F. Values may be given as zero to
5557 indicate that no change is needed.
5559 If DELAY, assume we're being called from a signal handler, and queue
5560 the change for later - perhaps the next redisplay. Since this tries
5561 to resize windows, we can't call it from a signal handler.
5563 SAFE means this function is called from a place where it's safe to
5564 change frame sizes while a redisplay is in progress. */
5565 void
5566 change_frame_size (struct frame *f, int new_width, int new_height,
5567 bool pretend, bool delay, bool safe, bool pixelwise)
5569 Lisp_Object tail, frame;
5571 if (FRAME_MSDOS_P (f))
5573 /* On MS-DOS, all frames use the same screen, so a change in
5574 size affects all frames. Termcap now supports multiple
5575 ttys. */
5576 FOR_EACH_FRAME (tail, frame)
5577 if (! FRAME_WINDOW_P (XFRAME (frame)))
5578 change_frame_size_1 (XFRAME (frame), new_width, new_height,
5579 pretend, delay, safe, pixelwise);
5581 else
5582 change_frame_size_1 (f, new_width, new_height, pretend, delay, safe,
5583 pixelwise);
5586 /***********************************************************************
5587 Terminal Related Lisp Functions
5588 ***********************************************************************/
5590 DEFUN ("open-termscript", Fopen_termscript, Sopen_termscript,
5591 1, 1, "FOpen termscript file: ",
5592 doc: /* Start writing all terminal output to FILE as well as the terminal.
5593 FILE = nil means just close any termscript file currently open. */)
5594 (Lisp_Object file)
5596 struct tty_display_info *tty;
5598 if (! FRAME_TERMCAP_P (SELECTED_FRAME ())
5599 && ! FRAME_MSDOS_P (SELECTED_FRAME ()))
5600 error ("Current frame is not on a tty device");
5602 tty = CURTTY ();
5604 if (tty->termscript != 0)
5606 block_input ();
5607 fclose (tty->termscript);
5608 tty->termscript = 0;
5609 unblock_input ();
5612 if (! NILP (file))
5614 file = Fexpand_file_name (file, Qnil);
5615 tty->termscript = emacs_fopen (SSDATA (file), "w");
5616 if (tty->termscript == 0)
5617 report_file_error ("Opening termscript", file);
5619 return Qnil;
5623 DEFUN ("send-string-to-terminal", Fsend_string_to_terminal,
5624 Ssend_string_to_terminal, 1, 2, 0,
5625 doc: /* Send STRING to the terminal without alteration.
5626 Control characters in STRING will have terminal-dependent effects.
5628 Optional parameter TERMINAL specifies the tty terminal device to use.
5629 It may be a terminal object, a frame, or nil for the terminal used by
5630 the currently selected frame. In batch mode, STRING is sent to stdout
5631 when TERMINAL is nil. */)
5632 (Lisp_Object string, Lisp_Object terminal)
5634 struct terminal *t = decode_live_terminal (terminal);
5635 FILE *out;
5637 /* ??? Perhaps we should do something special for multibyte strings here. */
5638 CHECK_STRING (string);
5639 block_input ();
5641 if (t->type == output_initial)
5642 out = stdout;
5643 else if (t->type != output_termcap && t->type != output_msdos_raw)
5644 error ("Device %d is not a termcap terminal device", t->id);
5645 else
5647 struct tty_display_info *tty = t->display_info.tty;
5649 if (! tty->output)
5650 error ("Terminal is currently suspended");
5652 if (tty->termscript)
5654 fwrite_unlocked (SDATA (string), 1, SBYTES (string), tty->termscript);
5655 fflush_unlocked (tty->termscript);
5657 out = tty->output;
5659 fwrite_unlocked (SDATA (string), 1, SBYTES (string), out);
5660 fflush_unlocked (out);
5661 unblock_input ();
5662 return Qnil;
5666 DEFUN ("ding", Fding, Sding, 0, 1, 0,
5667 doc: /* Beep, or flash the screen.
5668 Also, unless an argument is given,
5669 terminate any keyboard macro currently executing. */)
5670 (Lisp_Object arg)
5672 if (!NILP (arg))
5674 if (noninteractive)
5675 putchar_unlocked (07);
5676 else
5677 ring_bell (XFRAME (selected_frame));
5679 else
5680 bitch_at_user ();
5682 return Qnil;
5685 void
5686 bitch_at_user (void)
5688 if (noninteractive)
5689 putchar_unlocked (07);
5690 else if (!INTERACTIVE) /* Stop executing a keyboard macro. */
5692 const char *msg
5693 = "Keyboard macro terminated by a command ringing the bell";
5694 Fsignal (Quser_error, list1 (build_string (msg)));
5696 else
5697 ring_bell (XFRAME (selected_frame));
5702 /***********************************************************************
5703 Sleeping, Waiting
5704 ***********************************************************************/
5706 DEFUN ("sleep-for", Fsleep_for, Ssleep_for, 1, 2, 0,
5707 doc: /* Pause, without updating display, for SECONDS seconds.
5708 SECONDS may be a floating-point value, meaning that you can wait for a
5709 fraction of a second. Optional second arg MILLISECONDS specifies an
5710 additional wait period, in milliseconds; this is for backwards compatibility.
5711 \(Not all operating systems support waiting for a fraction of a second.) */)
5712 (Lisp_Object seconds, Lisp_Object milliseconds)
5714 double duration = extract_float (seconds);
5716 if (!NILP (milliseconds))
5718 CHECK_NUMBER (milliseconds);
5719 duration += XINT (milliseconds) / 1000.0;
5722 if (duration > 0)
5724 struct timespec t = dtotimespec (duration);
5725 struct timespec tend = timespec_add (current_timespec (), t);
5727 /* wait_reading_process_output returns as soon as it detects
5728 output from any subprocess, so we wait in a loop until the
5729 time expires. */
5730 do {
5731 wait_reading_process_output (min (t.tv_sec, WAIT_READING_MAX),
5732 t.tv_nsec, 0, 0, Qnil, NULL, 0);
5733 t = timespec_sub (tend, current_timespec ());
5734 } while (timespec_sign (t) > 0);
5737 return Qnil;
5741 /* This is just like wait_reading_process_output, except that
5742 it does redisplay.
5744 TIMEOUT is number of seconds to wait (float or integer),
5745 or t to wait forever.
5746 READING is true if reading input.
5747 If DISPLAY_OPTION is >0 display process output while waiting.
5748 If DISPLAY_OPTION is >1 perform an initial redisplay before waiting.
5751 Lisp_Object
5752 sit_for (Lisp_Object timeout, bool reading, int display_option)
5754 intmax_t sec;
5755 int nsec;
5756 bool do_display = display_option > 0;
5758 swallow_events (do_display);
5760 if ((detect_input_pending_run_timers (do_display))
5761 || !NILP (Vexecuting_kbd_macro))
5762 return Qnil;
5764 if (display_option > 1)
5765 redisplay_preserve_echo_area (2);
5767 if (INTEGERP (timeout))
5769 sec = XINT (timeout);
5770 if (sec <= 0)
5771 return Qt;
5772 nsec = 0;
5774 else if (FLOATP (timeout))
5776 double seconds = XFLOAT_DATA (timeout);
5777 if (! (0 < seconds))
5778 return Qt;
5779 else
5781 struct timespec t = dtotimespec (seconds);
5782 sec = min (t.tv_sec, WAIT_READING_MAX);
5783 nsec = t.tv_nsec;
5786 else if (EQ (timeout, Qt))
5788 sec = 0;
5789 nsec = 0;
5791 else
5792 wrong_type_argument (Qnumberp, timeout);
5795 #ifdef USABLE_SIGIO
5796 gobble_input ();
5797 #endif
5799 wait_reading_process_output (sec, nsec, reading ? -1 : 1, do_display,
5800 Qnil, NULL, 0);
5802 return detect_input_pending () ? Qnil : Qt;
5806 DEFUN ("redisplay", Fredisplay, Sredisplay, 0, 1, 0,
5807 doc: /* Perform redisplay.
5808 Optional arg FORCE, if non-nil, prevents redisplay from being
5809 preempted by arriving input, even if `redisplay-dont-pause' is nil.
5810 If `redisplay-dont-pause' is non-nil (the default), redisplay is never
5811 preempted by arriving input, so FORCE does nothing.
5813 Return t if redisplay was performed, nil if redisplay was preempted
5814 immediately by pending input. */)
5815 (Lisp_Object force)
5817 ptrdiff_t count;
5819 swallow_events (true);
5820 if ((detect_input_pending_run_timers (1)
5821 && NILP (force) && !redisplay_dont_pause)
5822 || !NILP (Vexecuting_kbd_macro))
5823 return Qnil;
5825 count = SPECPDL_INDEX ();
5826 if (!NILP (force) && !redisplay_dont_pause)
5827 specbind (Qredisplay_dont_pause, Qt);
5828 redisplay_preserve_echo_area (2);
5829 unbind_to (count, Qnil);
5830 return Qt;
5835 /***********************************************************************
5836 Other Lisp Functions
5837 ***********************************************************************/
5839 /* A vector of size >= 2 * NFRAMES + 3 * NBUFFERS + 1, containing the
5840 session's frames, frame names, buffers, buffer-read-only flags, and
5841 buffer-modified-flags. */
5843 static Lisp_Object frame_and_buffer_state;
5846 DEFUN ("frame-or-buffer-changed-p", Fframe_or_buffer_changed_p,
5847 Sframe_or_buffer_changed_p, 0, 1, 0,
5848 doc: /* Return non-nil if the frame and buffer state appears to have changed.
5849 VARIABLE is a variable name whose value is either nil or a state vector
5850 that will be updated to contain all frames and buffers,
5851 aside from buffers whose names start with space,
5852 along with the buffers' read-only and modified flags. This allows a fast
5853 check to see whether buffer menus might need to be recomputed.
5854 If this function returns non-nil, it updates the internal vector to reflect
5855 the current state.
5857 If VARIABLE is nil, an internal variable is used. Users should not
5858 pass nil for VARIABLE. */)
5859 (Lisp_Object variable)
5861 Lisp_Object state, tail, frame, buf;
5862 ptrdiff_t n, idx;
5864 if (! NILP (variable))
5866 CHECK_SYMBOL (variable);
5867 state = Fsymbol_value (variable);
5868 if (! VECTORP (state))
5869 goto changed;
5871 else
5872 state = frame_and_buffer_state;
5874 idx = 0;
5875 FOR_EACH_FRAME (tail, frame)
5877 if (idx == ASIZE (state))
5878 goto changed;
5879 if (!EQ (AREF (state, idx++), frame))
5880 goto changed;
5881 if (idx == ASIZE (state))
5882 goto changed;
5883 if (!EQ (AREF (state, idx++), XFRAME (frame)->name))
5884 goto changed;
5886 /* Check that the buffer info matches. */
5887 FOR_EACH_LIVE_BUFFER (tail, buf)
5889 /* Ignore buffers that aren't included in buffer lists. */
5890 if (SREF (BVAR (XBUFFER (buf), name), 0) == ' ')
5891 continue;
5892 if (idx == ASIZE (state))
5893 goto changed;
5894 if (!EQ (AREF (state, idx++), buf))
5895 goto changed;
5896 if (idx == ASIZE (state))
5897 goto changed;
5898 if (!EQ (AREF (state, idx++), BVAR (XBUFFER (buf), read_only)))
5899 goto changed;
5900 if (idx == ASIZE (state))
5901 goto changed;
5902 if (!EQ (AREF (state, idx++), Fbuffer_modified_p (buf)))
5903 goto changed;
5905 if (idx == ASIZE (state))
5906 goto changed;
5907 /* Detect deletion of a buffer at the end of the list. */
5908 if (EQ (AREF (state, idx), Qlambda))
5909 return Qnil;
5911 /* Come here if we decide the data has changed. */
5912 changed:
5913 /* Count the size we will need.
5914 Start with 1 so there is room for at least one lambda at the end. */
5915 n = 1;
5916 FOR_EACH_FRAME (tail, frame)
5917 n += 2;
5918 FOR_EACH_LIVE_BUFFER (tail, buf)
5919 n += 3;
5920 /* Reallocate the vector if data has grown to need it,
5921 or if it has shrunk a lot. */
5922 if (! VECTORP (state)
5923 || n > ASIZE (state)
5924 || n + 20 < ASIZE (state) / 2)
5925 /* Add 20 extra so we grow it less often. */
5927 state = Fmake_vector (make_number (n + 20), Qlambda);
5928 if (! NILP (variable))
5929 Fset (variable, state);
5930 else
5931 frame_and_buffer_state = state;
5934 /* Record the new data in the (possibly reallocated) vector. */
5935 idx = 0;
5936 FOR_EACH_FRAME (tail, frame)
5938 ASET (state, idx, frame);
5939 idx++;
5940 ASET (state, idx, XFRAME (frame)->name);
5941 idx++;
5943 FOR_EACH_LIVE_BUFFER (tail, buf)
5945 /* Ignore buffers that aren't included in buffer lists. */
5946 if (SREF (BVAR (XBUFFER (buf), name), 0) == ' ')
5947 continue;
5948 ASET (state, idx, buf);
5949 idx++;
5950 ASET (state, idx, BVAR (XBUFFER (buf), read_only));
5951 idx++;
5952 ASET (state, idx, Fbuffer_modified_p (buf));
5953 idx++;
5955 /* Fill up the vector with lambdas (always at least one). */
5956 ASET (state, idx, Qlambda);
5957 idx++;
5958 while (idx < ASIZE (state))
5960 ASET (state, idx, Qlambda);
5961 idx++;
5963 /* Make sure we didn't overflow the vector. */
5964 eassert (idx <= ASIZE (state));
5965 return Qt;
5970 /***********************************************************************
5971 Initialization
5972 ***********************************************************************/
5974 /* Initialization done when Emacs fork is started, before doing stty.
5975 Determine terminal type and set terminal_driver. Then invoke its
5976 decoding routine to set up variables in the terminal package. */
5978 void
5979 init_display (void)
5981 char *terminal_type;
5983 /* Construct the space glyph. */
5984 space_glyph.type = CHAR_GLYPH;
5985 SET_CHAR_GLYPH (space_glyph, ' ', DEFAULT_FACE_ID, 0);
5986 space_glyph.charpos = -1;
5988 inverse_video = 0;
5989 cursor_in_echo_area = false;
5991 /* Now is the time to initialize this; it's used by init_sys_modes
5992 during startup. */
5993 Vinitial_window_system = Qnil;
5995 /* SIGWINCH needs to be handled no matter what display we start
5996 with. Otherwise newly opened tty frames will not resize
5997 automatically. */
5998 #ifdef SIGWINCH
5999 #ifndef CANNOT_DUMP
6000 if (initialized)
6001 #endif /* CANNOT_DUMP */
6003 struct sigaction action;
6004 emacs_sigaction_init (&action, deliver_window_change_signal);
6005 sigaction (SIGWINCH, &action, 0);
6007 #endif /* SIGWINCH */
6009 /* If running as a daemon, no need to initialize any frames/terminal,
6010 except on Windows, where we at least want to initialize it. */
6011 #ifndef WINDOWSNT
6012 if (IS_DAEMON)
6013 return;
6014 #endif
6016 /* If the user wants to use a window system, we shouldn't bother
6017 initializing the terminal. This is especially important when the
6018 terminal is so dumb that emacs gives up before and doesn't bother
6019 using the window system.
6021 If the DISPLAY environment variable is set and nonempty,
6022 try to use X, and die with an error message if that doesn't work. */
6024 #ifdef HAVE_X_WINDOWS
6025 if (! inhibit_window_system && ! display_arg)
6027 char *display;
6028 display = getenv ("DISPLAY");
6029 display_arg = (display != 0 && *display != 0);
6031 if (display_arg && !x_display_ok (display))
6033 fprintf (stderr, "Display %s unavailable, simulating -nw\n",
6034 display);
6035 inhibit_window_system = 1;
6039 if (!inhibit_window_system && display_arg)
6041 Vinitial_window_system = Qx;
6042 #ifdef HAVE_X11
6043 Vwindow_system_version = make_number (11);
6044 #endif
6045 #ifdef USE_NCURSES
6046 /* In some versions of ncurses,
6047 tputs crashes if we have not called tgetent.
6048 So call tgetent. */
6049 { char b[2044]; tgetent (b, "xterm");}
6050 #endif
6051 return;
6053 #endif /* HAVE_X_WINDOWS */
6055 #ifdef HAVE_NTGUI
6056 if (!inhibit_window_system)
6058 Vinitial_window_system = Qw32;
6059 Vwindow_system_version = make_number (1);
6060 return;
6062 #endif /* HAVE_NTGUI */
6064 #ifdef HAVE_NS
6065 if (!inhibit_window_system
6066 #ifndef CANNOT_DUMP
6067 && initialized
6068 #endif
6071 Vinitial_window_system = Qns;
6072 Vwindow_system_version = make_number (10);
6073 return;
6075 #endif
6077 /* If no window system has been specified, try to use the terminal. */
6078 if (! isatty (STDIN_FILENO))
6079 fatal ("standard input is not a tty");
6081 #ifdef WINDOWSNT
6082 terminal_type = (char *)"w32console";
6083 #else
6084 terminal_type = getenv ("TERM");
6085 #endif
6086 if (!terminal_type)
6088 #ifdef HAVE_WINDOW_SYSTEM
6089 if (! inhibit_window_system)
6090 fprintf (stderr, "Please set the environment variable DISPLAY or TERM (see 'tset').\n");
6091 else
6092 #endif /* HAVE_WINDOW_SYSTEM */
6093 fprintf (stderr, "Please set the environment variable TERM; see 'tset'.\n");
6094 exit (1);
6098 struct terminal *t;
6099 struct frame *f = XFRAME (selected_frame);
6101 init_foreground_group ();
6103 /* Open a display on the controlling tty. */
6104 t = init_tty (0, terminal_type, 1); /* Errors are fatal. */
6106 /* Convert the initial frame to use the new display. */
6107 if (f->output_method != output_initial)
6108 emacs_abort ();
6109 f->output_method = t->type;
6110 f->terminal = t;
6112 t->reference_count++;
6113 #ifdef MSDOS
6114 f->output_data.tty->display_info = &the_only_display_info;
6115 #else
6116 if (f->output_method == output_termcap)
6117 create_tty_output (f);
6118 #endif
6119 t->display_info.tty->top_frame = selected_frame;
6120 change_frame_size (XFRAME (selected_frame),
6121 FrameCols (t->display_info.tty),
6122 FrameRows (t->display_info.tty)
6123 - FRAME_MENU_BAR_LINES (f), 0, 0, 1, 0);
6125 /* Delete the initial terminal. */
6126 if (--initial_terminal->reference_count == 0
6127 && initial_terminal->delete_terminal_hook)
6128 (*initial_terminal->delete_terminal_hook) (initial_terminal);
6130 /* Update frame parameters to reflect the new type. */
6131 AUTO_FRAME_ARG (tty_type_arg, Qtty_type, Ftty_type (selected_frame));
6132 Fmodify_frame_parameters (selected_frame, tty_type_arg);
6133 AUTO_FRAME_ARG (tty_arg, Qtty, (t->display_info.tty->name
6134 ? build_string (t->display_info.tty->name)
6135 : Qnil));
6136 Fmodify_frame_parameters (selected_frame, tty_arg);
6140 struct frame *sf = SELECTED_FRAME ();
6141 int width = FRAME_TOTAL_COLS (sf);
6142 int height = FRAME_TOTAL_LINES (sf);
6143 int area;
6145 /* If these sizes are so big they cause overflow, just ignore the
6146 change. It's not clear what better we could do. The rest of
6147 the code assumes that (width + 2) * height * sizeof (struct glyph)
6148 does not overflow and does not exceed PTRDIFF_MAX or SIZE_MAX. */
6149 if (INT_ADD_WRAPV (width, 2, &area)
6150 || INT_MULTIPLY_WRAPV (height, area, &area)
6151 || min (PTRDIFF_MAX, SIZE_MAX) / sizeof (struct glyph) < area)
6152 fatal ("screen size %dx%d too big", width, height);
6155 calculate_costs (XFRAME (selected_frame));
6157 /* Set up faces of the initial terminal frame of a dumped Emacs. */
6158 if (initialized
6159 && !noninteractive
6160 && NILP (Vinitial_window_system))
6162 /* For the initial frame, we don't have any way of knowing what
6163 are the foreground and background colors of the terminal. */
6164 struct frame *sf = SELECTED_FRAME ();
6166 FRAME_FOREGROUND_PIXEL (sf) = FACE_TTY_DEFAULT_FG_COLOR;
6167 FRAME_BACKGROUND_PIXEL (sf) = FACE_TTY_DEFAULT_BG_COLOR;
6168 call0 (intern ("tty-set-up-initial-frame-faces"));
6174 /***********************************************************************
6175 Blinking cursor
6176 ***********************************************************************/
6178 DEFUN ("internal-show-cursor", Finternal_show_cursor,
6179 Sinternal_show_cursor, 2, 2, 0,
6180 doc: /* Set the cursor-visibility flag of WINDOW to SHOW.
6181 WINDOW nil means use the selected window. SHOW non-nil means
6182 show a cursor in WINDOW in the next redisplay. SHOW nil means
6183 don't show a cursor. */)
6184 (Lisp_Object window, Lisp_Object show)
6186 /* Don't change cursor state while redisplaying. This could confuse
6187 output routines. */
6188 if (!redisplaying_p)
6189 decode_any_window (window)->cursor_off_p = NILP (show);
6190 return Qnil;
6194 DEFUN ("internal-show-cursor-p", Finternal_show_cursor_p,
6195 Sinternal_show_cursor_p, 0, 1, 0,
6196 doc: /* Value is non-nil if next redisplay will display a cursor in WINDOW.
6197 WINDOW nil or omitted means report on the selected window. */)
6198 (Lisp_Object window)
6200 return decode_any_window (window)->cursor_off_p ? Qnil : Qt;
6203 /***********************************************************************
6204 Initialization
6205 ***********************************************************************/
6207 void
6208 syms_of_display (void)
6210 defsubr (&Sredraw_frame);
6211 defsubr (&Sredraw_display);
6212 defsubr (&Sframe_or_buffer_changed_p);
6213 defsubr (&Sopen_termscript);
6214 defsubr (&Sding);
6215 defsubr (&Sredisplay);
6216 defsubr (&Ssleep_for);
6217 defsubr (&Ssend_string_to_terminal);
6218 defsubr (&Sinternal_show_cursor);
6219 defsubr (&Sinternal_show_cursor_p);
6221 #ifdef GLYPH_DEBUG
6222 defsubr (&Sdump_redisplay_history);
6223 #endif
6225 frame_and_buffer_state = Fmake_vector (make_number (20), Qlambda);
6226 staticpro (&frame_and_buffer_state);
6228 /* This is the "purpose" slot of a display table. */
6229 DEFSYM (Qdisplay_table, "display-table");
6231 DEFSYM (Qredisplay_dont_pause, "redisplay-dont-pause");
6233 DEFVAR_INT ("baud-rate", baud_rate,
6234 doc: /* The output baud rate of the terminal.
6235 On most systems, changing this value will affect the amount of padding
6236 and the other strategic decisions made during redisplay. */);
6238 DEFVAR_BOOL ("inverse-video", inverse_video,
6239 doc: /* Non-nil means invert the entire frame display.
6240 This means everything is in inverse video which otherwise would not be. */);
6242 DEFVAR_BOOL ("visible-bell", visible_bell,
6243 doc: /* Non-nil means try to flash the frame to represent a bell.
6245 See also `ring-bell-function'. */);
6247 DEFVAR_BOOL ("no-redraw-on-reenter", no_redraw_on_reenter,
6248 doc: /* Non-nil means no need to redraw entire frame after suspending.
6249 A non-nil value is useful if the terminal can automatically preserve
6250 Emacs's frame display when you reenter Emacs.
6251 It is up to you to set this variable if your terminal can do that. */);
6253 DEFVAR_LISP ("initial-window-system", Vinitial_window_system,
6254 doc: /* Name of the window system that Emacs uses for the first frame.
6255 The value is a symbol:
6256 nil for a termcap frame (a character-only terminal),
6257 `x' for an Emacs frame that is really an X window,
6258 `w32' for an Emacs frame that is a window on MS-Windows display,
6259 `ns' for an Emacs frame on a GNUstep or Macintosh Cocoa display,
6260 `pc' for a direct-write MS-DOS frame.
6262 Use of this variable as a boolean is deprecated. Instead,
6263 use `display-graphic-p' or any of the other `display-*-p'
6264 predicates which report frame's specific UI-related capabilities. */);
6266 DEFVAR_KBOARD ("window-system", Vwindow_system,
6267 doc: /* Name of window system through which the selected frame is displayed.
6268 The value is a symbol:
6269 nil for a termcap frame (a character-only terminal),
6270 `x' for an Emacs frame that is really an X window,
6271 `w32' for an Emacs frame that is a window on MS-Windows display,
6272 `ns' for an Emacs frame on a GNUstep or Macintosh Cocoa display,
6273 `pc' for a direct-write MS-DOS frame.
6275 Use of this variable as a boolean is deprecated. Instead,
6276 use `display-graphic-p' or any of the other `display-*-p'
6277 predicates which report frame's specific UI-related capabilities. */);
6279 DEFVAR_LISP ("window-system-version", Vwindow_system_version,
6280 doc: /* The version number of the window system in use.
6281 For X windows, this is 11. */);
6283 DEFVAR_BOOL ("cursor-in-echo-area", cursor_in_echo_area,
6284 doc: /* Non-nil means put cursor in minibuffer, at end of any message there. */);
6286 DEFVAR_LISP ("glyph-table", Vglyph_table,
6287 doc: /* Table defining how to output a glyph code to the frame.
6288 If not nil, this is a vector indexed by glyph code to define the glyph.
6289 Each element can be:
6290 integer: a glyph code which this glyph is an alias for.
6291 string: output this glyph using that string (not impl. in X windows).
6292 nil: this glyph mod 524288 is the code of a character to output,
6293 and this glyph / 524288 is the face number (see `face-id') to use
6294 while outputting it. */);
6295 Vglyph_table = Qnil;
6297 DEFVAR_LISP ("standard-display-table", Vstandard_display_table,
6298 doc: /* Display table to use for buffers that specify none.
6299 It is also used for standard output and error streams.
6300 See `buffer-display-table' for more information. */);
6301 Vstandard_display_table = Qnil;
6303 DEFVAR_BOOL ("redisplay-dont-pause", redisplay_dont_pause,
6304 doc: /* Nil means display update is paused when input is detected. */);
6305 /* Contrary to expectations, a value of "false" can be detrimental to
6306 responsiveness since aborting a redisplay throws away some of the
6307 work already performed. It's usually more efficient (and gives
6308 more prompt feedback to the user) to let the redisplay terminate,
6309 and just completely skip the next command's redisplay (which is
6310 done regardless of this setting if there's pending input at the
6311 beginning of the next redisplay). */
6312 redisplay_dont_pause = true;
6314 #ifdef CANNOT_DUMP
6315 if (noninteractive)
6316 #endif
6318 Vinitial_window_system = Qnil;
6319 Vwindow_system_version = Qnil;