In display-buffer-pop-up-frame make BUFFER current (Bug#15133).
[emacs.git] / src / dispnew.c
blob3c6b89bde682c1ddec29d5c266a5a65f30d89c73
1 /* Updating of data structures for redisplay.
3 Copyright (C) 1985-1988, 1993-1995, 1997-2013 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
11 (at 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 <http://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #define DISPEXTERN_INLINE EXTERN_INLINE
25 #include "sysstdio.h"
26 #include <unistd.h>
28 #include "lisp.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 "character.h"
34 #include "buffer.h"
35 #include "keyboard.h"
36 #include "frame.h"
37 #include "termhooks.h"
38 #include "window.h"
39 #include "commands.h"
40 #include "disptab.h"
41 #include "indent.h"
42 #include "intervals.h"
43 #include "blockinput.h"
44 #include "process.h"
46 #include "syssignal.h"
48 #ifdef HAVE_WINDOW_SYSTEM
49 #include TERM_HEADER
50 #endif /* HAVE_WINDOW_SYSTEM */
52 /* Include systime.h after xterm.h to avoid double inclusion of time.h. */
54 #include "systime.h"
55 #include <errno.h>
57 #include <fpending.h>
59 #if defined (HAVE_TERM_H) && defined (GNU_LINUX)
60 #include <term.h> /* for tgetent */
61 #endif
63 #ifdef WINDOWSNT
64 #include "w32.h"
65 #endif
67 /* Structure to pass dimensions around. Used for character bounding
68 boxes, glyph matrix dimensions and alike. */
70 struct dim
72 int width;
73 int height;
77 /* Function prototypes. */
79 static void update_frame_line (struct frame *, int);
80 static int required_matrix_height (struct window *);
81 static int required_matrix_width (struct window *);
82 static void adjust_frame_glyphs (struct frame *);
83 static void change_frame_size_1 (struct frame *, int, int, bool, bool, bool);
84 static void increment_row_positions (struct glyph_row *, ptrdiff_t, ptrdiff_t);
85 static void fill_up_frame_row_with_spaces (struct glyph_row *, int);
86 static void build_frame_matrix_from_window_tree (struct glyph_matrix *,
87 struct window *);
88 static void build_frame_matrix_from_leaf_window (struct glyph_matrix *,
89 struct window *);
90 static void adjust_decode_mode_spec_buffer (struct frame *);
91 static void fill_up_glyph_row_with_spaces (struct glyph_row *);
92 static void clear_window_matrices (struct window *, bool);
93 static void fill_up_glyph_row_area_with_spaces (struct glyph_row *, int);
94 static int scrolling_window (struct window *, bool);
95 static bool update_window_line (struct window *, int, bool *);
96 static void mirror_make_current (struct window *, int);
97 #ifdef GLYPH_DEBUG
98 static void check_matrix_pointers (struct glyph_matrix *,
99 struct glyph_matrix *);
100 #endif
101 static void mirror_line_dance (struct window *, int, int, int *, char *);
102 static bool update_window_tree (struct window *, bool);
103 static bool update_window (struct window *, bool);
104 static bool update_frame_1 (struct frame *, bool, bool);
105 static bool scrolling (struct frame *);
106 static void set_window_cursor_after_update (struct window *);
107 static void adjust_frame_glyphs_for_window_redisplay (struct frame *);
108 static void adjust_frame_glyphs_for_frame_redisplay (struct frame *);
110 /* True upon entry to redisplay means do not assume anything about
111 current contents of actual terminal frame; clear and redraw it. */
113 bool frame_garbaged;
115 /* True means last display completed. False means it was preempted. */
117 bool display_completed;
119 Lisp_Object Qdisplay_table, Qredisplay_dont_pause;
122 /* The currently selected frame. In a single-frame version, this
123 variable always equals the_only_frame. */
125 Lisp_Object selected_frame;
127 /* A frame which is not just a mini-buffer, or 0 if there are no such
128 frames. This is usually the most recent such frame that was
129 selected. In a single-frame version, this variable always holds
130 the address of the_only_frame. */
132 struct frame *last_nonminibuf_frame;
134 /* True means SIGWINCH happened when not safe. */
136 static bool delayed_size_change;
138 /* A glyph for a space. */
140 struct glyph space_glyph;
142 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
144 /* Counts of allocated structures. These counts serve to diagnose
145 memory leaks and double frees. */
147 static int glyph_matrix_count;
148 static int glyph_pool_count;
150 #endif /* GLYPH_DEBUG and ENABLE_CHECKING */
152 /* If non-null, the frame whose frame matrices are manipulated. If
153 null, window matrices are worked on. */
155 static struct frame *frame_matrix_frame;
157 /* True means that fonts have been loaded since the last glyph
158 matrix adjustments. Redisplay must stop, and glyph matrices must
159 be adjusted when this flag becomes true during display. The
160 reason fonts can be loaded so late is that fonts of fontsets are
161 loaded on demand. Another reason is that a line contains many
162 characters displayed by zero width or very narrow glyphs of
163 variable-width fonts. */
165 bool fonts_changed_p;
167 /* Convert vpos and hpos from frame to window and vice versa.
168 This may only be used for terminal frames. */
170 #ifdef GLYPH_DEBUG
172 static int window_to_frame_vpos (struct window *, int);
173 static int window_to_frame_hpos (struct window *, int);
174 #define WINDOW_TO_FRAME_VPOS(W, VPOS) window_to_frame_vpos ((W), (VPOS))
175 #define WINDOW_TO_FRAME_HPOS(W, HPOS) window_to_frame_hpos ((W), (HPOS))
177 /* One element of the ring buffer containing redisplay history
178 information. */
180 struct redisplay_history
182 char trace[512 + 100];
185 /* The size of the history buffer. */
187 #define REDISPLAY_HISTORY_SIZE 30
189 /* The redisplay history buffer. */
191 static struct redisplay_history redisplay_history[REDISPLAY_HISTORY_SIZE];
193 /* Next free entry in redisplay_history. */
195 static int history_idx;
197 /* A tick that's incremented each time something is added to the
198 history. */
200 static uprintmax_t history_tick;
202 /* Add to the redisplay history how window W has been displayed.
203 MSG is a trace containing the information how W's glyph matrix
204 has been constructed. PAUSED_P means that the update
205 has been interrupted for pending input. */
207 static void
208 add_window_display_history (struct window *w, const char *msg, bool paused_p)
210 char *buf;
211 void *ptr = w;
213 if (history_idx >= REDISPLAY_HISTORY_SIZE)
214 history_idx = 0;
215 buf = redisplay_history[history_idx].trace;
216 ++history_idx;
218 snprintf (buf, sizeof redisplay_history[0].trace,
219 "%"pMu": window %p (`%s')%s\n%s",
220 history_tick++,
221 ptr,
222 ((BUFFERP (w->contents)
223 && STRINGP (BVAR (XBUFFER (w->contents), name)))
224 ? SSDATA (BVAR (XBUFFER (w->contents), name))
225 : "???"),
226 paused_p ? " ***paused***" : "",
227 msg);
231 /* Add to the redisplay history that frame F has been displayed.
232 PAUSED_P means that the update has been interrupted for
233 pending input. */
235 static void
236 add_frame_display_history (struct frame *f, bool paused_p)
238 char *buf;
239 void *ptr = f;
241 if (history_idx >= REDISPLAY_HISTORY_SIZE)
242 history_idx = 0;
243 buf = redisplay_history[history_idx].trace;
244 ++history_idx;
246 sprintf (buf, "%"pMu": update frame %p%s",
247 history_tick++,
248 ptr, paused_p ? " ***paused***" : "");
252 DEFUN ("dump-redisplay-history", Fdump_redisplay_history,
253 Sdump_redisplay_history, 0, 0, "",
254 doc: /* Dump redisplay history to stderr. */)
255 (void)
257 int i;
259 for (i = history_idx - 1; i != history_idx; --i)
261 if (i < 0)
262 i = REDISPLAY_HISTORY_SIZE - 1;
263 fprintf (stderr, "%s\n", redisplay_history[i].trace);
266 return Qnil;
270 #else /* not GLYPH_DEBUG */
272 #define WINDOW_TO_FRAME_VPOS(W, VPOS) ((VPOS) + WINDOW_TOP_EDGE_LINE (W))
273 #define WINDOW_TO_FRAME_HPOS(W, HPOS) ((HPOS) + WINDOW_LEFT_EDGE_COL (W))
275 #endif /* GLYPH_DEBUG */
278 #if (defined PROFILING \
279 && (defined __FreeBSD__ || defined GNU_LINUX || defined __MINGW32__) \
280 && !HAVE___EXECUTABLE_START)
281 /* This function comes first in the Emacs executable and is used only
282 to estimate the text start for profiling. */
283 void
284 __executable_start (void)
286 emacs_abort ();
288 #endif
290 /***********************************************************************
291 Glyph Matrices
292 ***********************************************************************/
294 /* Allocate and return a glyph_matrix structure. POOL is the glyph
295 pool from which memory for the matrix should be allocated, or null
296 for window-based redisplay where no glyph pools are used. The
297 member `pool' of the glyph matrix structure returned is set to
298 POOL, the structure is otherwise zeroed. */
300 static struct glyph_matrix *
301 new_glyph_matrix (struct glyph_pool *pool)
303 struct glyph_matrix *result = xzalloc (sizeof *result);
305 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
306 /* Increment number of allocated matrices. This count is used
307 to detect memory leaks. */
308 ++glyph_matrix_count;
309 #endif
311 /* Set pool and return. */
312 result->pool = pool;
313 return result;
317 /* Free glyph matrix MATRIX. Passing in a null MATRIX is allowed.
319 If GLYPH_DEBUG and ENABLE_CHECKING are in effect, the global counter
320 glyph_matrix_count is decremented when a matrix is freed. If the count
321 gets negative, more structures were freed than allocated, i.e. one matrix
322 was freed more than once or a bogus pointer was passed to this function.
324 If MATRIX->pool is null, this means that the matrix manages its own
325 glyph memory---this is done for matrices on X frames. Freeing the
326 matrix also frees the glyph memory in this case. */
328 static void
329 free_glyph_matrix (struct glyph_matrix *matrix)
331 if (matrix)
333 int i;
335 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
336 /* Detect the case that more matrices are freed than were
337 allocated. */
338 --glyph_matrix_count;
339 eassert (glyph_matrix_count >= 0);
340 #endif
342 /* Free glyph memory if MATRIX owns it. */
343 if (matrix->pool == NULL)
344 for (i = 0; i < matrix->rows_allocated; ++i)
345 xfree (matrix->rows[i].glyphs[LEFT_MARGIN_AREA]);
347 /* Free row structures and the matrix itself. */
348 xfree (matrix->rows);
349 xfree (matrix);
354 /* Return the number of glyphs to reserve for a marginal area of
355 window W. TOTAL_GLYPHS is the number of glyphs in a complete
356 display line of window W. MARGIN gives the width of the marginal
357 area in canonical character units. */
359 static int
360 margin_glyphs_to_reserve (struct window *w, int total_glyphs, int margin)
362 if (margin > 0)
364 int width = w->total_cols;
365 double d = max (0, margin);
366 d = min (width / 2 - 1, d);
367 return (int) ((double) total_glyphs / width * d);
369 return 0;
372 /* Return true if ROW's hash value is correct.
373 Optimized away if ENABLE_CHECKING is not defined. */
375 static bool
376 verify_row_hash (struct glyph_row *row)
378 return row->hash == row_hash (row);
381 /* Adjust glyph matrix MATRIX on window W or on a frame to changed
382 window sizes.
384 W is null if the function is called for a frame glyph matrix.
385 Otherwise it is the window MATRIX is a member of. X and Y are the
386 indices of the first column and row of MATRIX within the frame
387 matrix, if such a matrix exists. They are zero for purely
388 window-based redisplay. DIM is the needed size of the matrix.
390 In window-based redisplay, where no frame matrices exist, glyph
391 matrices manage their own glyph storage. Otherwise, they allocate
392 storage from a common frame glyph pool which can be found in
393 MATRIX->pool.
395 The reason for this memory management strategy is to avoid complete
396 frame redraws if possible. When we allocate from a common pool, a
397 change of the location or size of a sub-matrix within the pool
398 requires a complete redisplay of the frame because we cannot easily
399 make sure that the current matrices of all windows still agree with
400 what is displayed on the screen. While this is usually fast, it
401 leads to screen flickering. */
403 static void
404 adjust_glyph_matrix (struct window *w, struct glyph_matrix *matrix, int x, int y, struct dim dim)
406 int i;
407 int new_rows;
408 bool marginal_areas_changed_p = 0;
409 bool header_line_changed_p = 0;
410 bool header_line_p = 0;
411 int left = -1, right = -1;
412 int window_width = -1, window_height = -1;
414 /* See if W had a header line that has disappeared now, or vice versa.
415 Get W's size. */
416 if (w)
418 window_box (w, -1, 0, 0, &window_width, &window_height);
420 header_line_p = WINDOW_WANTS_HEADER_LINE_P (w);
421 header_line_changed_p = header_line_p != matrix->header_line_p;
423 matrix->header_line_p = header_line_p;
425 /* If POOL is null, MATRIX is a window matrix for window-based redisplay.
426 Do nothing if MATRIX' size, position, vscroll, and marginal areas
427 haven't changed. This optimization is important because preserving
428 the matrix means preventing redisplay. */
429 if (matrix->pool == NULL)
431 left = margin_glyphs_to_reserve (w, dim.width, w->left_margin_cols);
432 right = margin_glyphs_to_reserve (w, dim.width, w->right_margin_cols);
433 eassert (left >= 0 && right >= 0);
434 marginal_areas_changed_p = (left != matrix->left_margin_glyphs
435 || right != matrix->right_margin_glyphs);
437 if (!marginal_areas_changed_p
438 && !fonts_changed_p
439 && !header_line_changed_p
440 && matrix->window_left_col == WINDOW_LEFT_EDGE_COL (w)
441 && matrix->window_top_line == WINDOW_TOP_EDGE_LINE (w)
442 && matrix->window_height == window_height
443 && matrix->window_vscroll == w->vscroll
444 && matrix->window_width == window_width)
445 return;
448 /* Enlarge MATRIX->rows if necessary. New rows are cleared. */
449 if (matrix->rows_allocated < dim.height)
451 int old_alloc = matrix->rows_allocated;
452 new_rows = dim.height - matrix->rows_allocated;
453 matrix->rows = xpalloc (matrix->rows, &matrix->rows_allocated,
454 new_rows, INT_MAX, sizeof *matrix->rows);
455 memset (matrix->rows + old_alloc, 0,
456 (matrix->rows_allocated - old_alloc) * sizeof *matrix->rows);
458 else
459 new_rows = 0;
461 /* If POOL is not null, MATRIX is a frame matrix or a window matrix
462 on a frame not using window-based redisplay. Set up pointers for
463 each row into the glyph pool. */
464 if (matrix->pool)
466 eassert (matrix->pool->glyphs);
468 if (w)
470 left = margin_glyphs_to_reserve (w, dim.width,
471 w->left_margin_cols);
472 right = margin_glyphs_to_reserve (w, dim.width,
473 w->right_margin_cols);
475 else
476 left = right = 0;
478 for (i = 0; i < dim.height; ++i)
480 struct glyph_row *row = &matrix->rows[i];
482 row->glyphs[LEFT_MARGIN_AREA]
483 = (matrix->pool->glyphs
484 + (y + i) * matrix->pool->ncolumns
485 + x);
487 if (w == NULL
488 || row == matrix->rows + dim.height - 1
489 || (row == matrix->rows && matrix->header_line_p))
491 row->glyphs[TEXT_AREA]
492 = row->glyphs[LEFT_MARGIN_AREA];
493 row->glyphs[RIGHT_MARGIN_AREA]
494 = row->glyphs[TEXT_AREA] + dim.width;
495 row->glyphs[LAST_AREA]
496 = row->glyphs[RIGHT_MARGIN_AREA];
498 else
500 row->glyphs[TEXT_AREA]
501 = row->glyphs[LEFT_MARGIN_AREA] + left;
502 row->glyphs[RIGHT_MARGIN_AREA]
503 = row->glyphs[TEXT_AREA] + dim.width - left - right;
504 row->glyphs[LAST_AREA]
505 = row->glyphs[LEFT_MARGIN_AREA] + dim.width;
509 matrix->left_margin_glyphs = left;
510 matrix->right_margin_glyphs = right;
512 else
514 /* If MATRIX->pool is null, MATRIX is responsible for managing
515 its own memory. It is a window matrix for window-based redisplay.
516 Allocate glyph memory from the heap. */
517 if (dim.width > matrix->matrix_w
518 || new_rows
519 || header_line_changed_p
520 || marginal_areas_changed_p)
522 struct glyph_row *row = matrix->rows;
523 struct glyph_row *end = row + matrix->rows_allocated;
525 while (row < end)
527 row->glyphs[LEFT_MARGIN_AREA]
528 = xnrealloc (row->glyphs[LEFT_MARGIN_AREA],
529 dim.width, sizeof (struct glyph));
531 /* The mode line never has marginal areas. */
532 if (row == matrix->rows + dim.height - 1
533 || (row == matrix->rows && matrix->header_line_p))
535 row->glyphs[TEXT_AREA]
536 = row->glyphs[LEFT_MARGIN_AREA];
537 row->glyphs[RIGHT_MARGIN_AREA]
538 = row->glyphs[TEXT_AREA] + dim.width;
539 row->glyphs[LAST_AREA]
540 = row->glyphs[RIGHT_MARGIN_AREA];
542 else
544 row->glyphs[TEXT_AREA]
545 = row->glyphs[LEFT_MARGIN_AREA] + left;
546 row->glyphs[RIGHT_MARGIN_AREA]
547 = row->glyphs[TEXT_AREA] + dim.width - left - right;
548 row->glyphs[LAST_AREA]
549 = row->glyphs[LEFT_MARGIN_AREA] + dim.width;
551 ++row;
555 eassert (left >= 0 && right >= 0);
556 matrix->left_margin_glyphs = left;
557 matrix->right_margin_glyphs = right;
560 /* Number of rows to be used by MATRIX. */
561 matrix->nrows = dim.height;
562 eassert (matrix->nrows >= 0);
564 if (w)
566 if (matrix == w->current_matrix)
568 /* Mark rows in a current matrix of a window as not having
569 valid contents. It's important to not do this for
570 desired matrices. When Emacs starts, it may already be
571 building desired matrices when this function runs. */
572 if (window_width < 0)
573 window_width = window_box_width (w, -1);
575 /* Optimize the case that only the height has changed (C-x 2,
576 upper window). Invalidate all rows that are no longer part
577 of the window. */
578 if (!marginal_areas_changed_p
579 && !header_line_changed_p
580 && new_rows == 0
581 && dim.width == matrix->matrix_w
582 && matrix->window_left_col == WINDOW_LEFT_EDGE_COL (w)
583 && matrix->window_top_line == WINDOW_TOP_EDGE_LINE (w)
584 && matrix->window_width == window_width)
586 /* Find the last row in the window. */
587 for (i = 0; i < matrix->nrows && matrix->rows[i].enabled_p; ++i)
588 if (MATRIX_ROW_BOTTOM_Y (matrix->rows + i) >= window_height)
590 ++i;
591 break;
594 /* Window end is invalid, if inside of the rows that
595 are invalidated below. */
596 if (w->window_end_vpos >= i)
597 w->window_end_valid = 0;
599 while (i < matrix->nrows)
600 matrix->rows[i++].enabled_p = 0;
602 else
604 for (i = 0; i < matrix->nrows; ++i)
605 matrix->rows[i].enabled_p = 0;
608 else if (matrix == w->desired_matrix)
610 /* Rows in desired matrices always have to be cleared;
611 redisplay expects this is the case when it runs, so it
612 had better be the case when we adjust matrices between
613 redisplays. */
614 for (i = 0; i < matrix->nrows; ++i)
615 matrix->rows[i].enabled_p = 0;
620 /* Remember last values to be able to optimize frame redraws. */
621 matrix->matrix_x = x;
622 matrix->matrix_y = y;
623 matrix->matrix_w = dim.width;
624 matrix->matrix_h = dim.height;
626 /* Record the top y location and height of W at the time the matrix
627 was last adjusted. This is used to optimize redisplay above. */
628 if (w)
630 matrix->window_left_col = WINDOW_LEFT_EDGE_COL (w);
631 matrix->window_top_line = WINDOW_TOP_EDGE_LINE (w);
632 matrix->window_height = window_height;
633 matrix->window_width = window_width;
634 matrix->window_vscroll = w->vscroll;
639 /* Reverse the contents of rows in MATRIX between START and END. The
640 contents of the row at END - 1 end up at START, END - 2 at START +
641 1 etc. This is part of the implementation of rotate_matrix (see
642 below). */
644 static void
645 reverse_rows (struct glyph_matrix *matrix, int start, int end)
647 int i, j;
649 for (i = start, j = end - 1; i < j; ++i, --j)
651 /* Non-ISO HP/UX compiler doesn't like auto struct
652 initialization. */
653 struct glyph_row temp;
654 temp = matrix->rows[i];
655 matrix->rows[i] = matrix->rows[j];
656 matrix->rows[j] = temp;
661 /* Rotate the contents of rows in MATRIX in the range FIRST .. LAST -
662 1 by BY positions. BY < 0 means rotate left, i.e. towards lower
663 indices. (Note: this does not copy glyphs, only glyph pointers in
664 row structures are moved around).
666 The algorithm used for rotating the vector was, I believe, first
667 described by Kernighan. See the vector R as consisting of two
668 sub-vectors AB, where A has length BY for BY >= 0. The result
669 after rotating is then BA. Reverse both sub-vectors to get ArBr
670 and reverse the result to get (ArBr)r which is BA. Similar for
671 rotating right. */
673 void
674 rotate_matrix (struct glyph_matrix *matrix, int first, int last, int by)
676 if (by < 0)
678 /* Up (rotate left, i.e. towards lower indices). */
679 by = -by;
680 reverse_rows (matrix, first, first + by);
681 reverse_rows (matrix, first + by, last);
682 reverse_rows (matrix, first, last);
684 else if (by > 0)
686 /* Down (rotate right, i.e. towards higher indices). */
687 reverse_rows (matrix, last - by, last);
688 reverse_rows (matrix, first, last - by);
689 reverse_rows (matrix, first, last);
694 /* Increment buffer positions in glyph rows of MATRIX. Do it for rows
695 with indices START <= index < END. Increment positions by DELTA/
696 DELTA_BYTES. */
698 void
699 increment_matrix_positions (struct glyph_matrix *matrix, int start, int end,
700 ptrdiff_t delta, ptrdiff_t delta_bytes)
702 /* Check that START and END are reasonable values. */
703 eassert (start >= 0 && start <= matrix->nrows);
704 eassert (end >= 0 && end <= matrix->nrows);
705 eassert (start <= end);
707 for (; start < end; ++start)
708 increment_row_positions (matrix->rows + start, delta, delta_bytes);
712 /* Clear the enable_p flags in a range of rows in glyph matrix MATRIX.
713 START and END are the row indices of the first and last + 1 row to clear. */
715 void
716 clear_glyph_matrix_rows (struct glyph_matrix *matrix, int start, int end)
718 eassert (start <= end);
719 eassert (start >= 0 && start < matrix->nrows);
720 eassert (end >= 0 && end <= matrix->nrows);
722 for (; start < end; ++start)
723 matrix->rows[start].enabled_p = 0;
727 /* Clear MATRIX.
729 Empty all rows in MATRIX by clearing their enabled_p flags.
730 The function prepare_desired_row will eventually really clear a row
731 when it sees one with a false enabled_p flag.
733 Reset update hints to default values. The only update hint
734 currently present is the flag MATRIX->no_scrolling_p. */
736 void
737 clear_glyph_matrix (struct glyph_matrix *matrix)
739 if (matrix)
741 clear_glyph_matrix_rows (matrix, 0, matrix->nrows);
742 matrix->no_scrolling_p = 0;
747 /* Shift part of the glyph matrix MATRIX of window W up or down.
748 Increment y-positions in glyph rows between START and END by DY,
749 and recompute their visible height. */
751 void
752 shift_glyph_matrix (struct window *w, struct glyph_matrix *matrix, int start, int end, int dy)
754 int min_y, max_y;
756 eassert (start <= end);
757 eassert (start >= 0 && start < matrix->nrows);
758 eassert (end >= 0 && end <= matrix->nrows);
760 min_y = WINDOW_HEADER_LINE_HEIGHT (w);
761 max_y = WINDOW_BOX_HEIGHT_NO_MODE_LINE (w);
763 for (; start < end; ++start)
765 struct glyph_row *row = &matrix->rows[start];
767 row->y += dy;
768 row->visible_height = row->height;
770 if (row->y < min_y)
771 row->visible_height -= min_y - row->y;
772 if (row->y + row->height > max_y)
773 row->visible_height -= row->y + row->height - max_y;
774 if (row->fringe_bitmap_periodic_p)
775 row->redraw_fringe_bitmaps_p = 1;
780 /* Mark all rows in current matrices of frame F as invalid. Marking
781 invalid is done by setting enabled_p to zero for all rows in a
782 current matrix. */
784 void
785 clear_current_matrices (register struct frame *f)
787 /* Clear frame current matrix, if we have one. */
788 if (f->current_matrix)
789 clear_glyph_matrix (f->current_matrix);
791 #if defined (HAVE_X_WINDOWS) && ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
792 /* Clear the matrix of the menu bar window, if such a window exists.
793 The menu bar window is currently used to display menus on X when
794 no toolkit support is compiled in. */
795 if (WINDOWP (f->menu_bar_window))
796 clear_glyph_matrix (XWINDOW (f->menu_bar_window)->current_matrix);
797 #endif
799 /* Clear the matrix of the tool-bar window, if any. */
800 if (WINDOWP (f->tool_bar_window))
801 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
803 /* Clear current window matrices. */
804 eassert (WINDOWP (FRAME_ROOT_WINDOW (f)));
805 clear_window_matrices (XWINDOW (FRAME_ROOT_WINDOW (f)), 0);
809 /* Clear out all display lines of F for a coming redisplay. */
811 void
812 clear_desired_matrices (register struct frame *f)
814 if (f->desired_matrix)
815 clear_glyph_matrix (f->desired_matrix);
817 #if defined (HAVE_X_WINDOWS) && ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
818 if (WINDOWP (f->menu_bar_window))
819 clear_glyph_matrix (XWINDOW (f->menu_bar_window)->desired_matrix);
820 #endif
822 if (WINDOWP (f->tool_bar_window))
823 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->desired_matrix);
825 /* Do it for window matrices. */
826 eassert (WINDOWP (FRAME_ROOT_WINDOW (f)));
827 clear_window_matrices (XWINDOW (FRAME_ROOT_WINDOW (f)), 1);
831 /* Clear matrices in window tree rooted in W. If DESIRED_P,
832 clear desired matrices, otherwise clear current matrices. */
834 static void
835 clear_window_matrices (struct window *w, bool desired_p)
837 while (w)
839 if (WINDOWP (w->contents))
840 clear_window_matrices (XWINDOW (w->contents), desired_p);
841 else
843 if (desired_p)
844 clear_glyph_matrix (w->desired_matrix);
845 else
847 clear_glyph_matrix (w->current_matrix);
848 w->window_end_valid = 0;
852 w = NILP (w->next) ? 0 : XWINDOW (w->next);
858 /***********************************************************************
859 Glyph Rows
861 See dispextern.h for an overall explanation of glyph rows.
862 ***********************************************************************/
864 /* Clear glyph row ROW. Do it in a way that makes it robust against
865 changes in the glyph_row structure, i.e. addition or removal of
866 structure members. */
868 static struct glyph_row null_row;
870 void
871 clear_glyph_row (struct glyph_row *row)
873 struct glyph *p[1 + LAST_AREA];
875 /* Save pointers. */
876 p[LEFT_MARGIN_AREA] = row->glyphs[LEFT_MARGIN_AREA];
877 p[TEXT_AREA] = row->glyphs[TEXT_AREA];
878 p[RIGHT_MARGIN_AREA] = row->glyphs[RIGHT_MARGIN_AREA];
879 p[LAST_AREA] = row->glyphs[LAST_AREA];
881 /* Clear. */
882 *row = null_row;
884 /* Restore pointers. */
885 row->glyphs[LEFT_MARGIN_AREA] = p[LEFT_MARGIN_AREA];
886 row->glyphs[TEXT_AREA] = p[TEXT_AREA];
887 row->glyphs[RIGHT_MARGIN_AREA] = p[RIGHT_MARGIN_AREA];
888 row->glyphs[LAST_AREA] = p[LAST_AREA];
890 #if 0 /* At some point, some bit-fields of struct glyph were not set,
891 which made glyphs unequal when compared with GLYPH_EQUAL_P.
892 Redisplay outputs such glyphs, and flickering effects were
893 the result. This also depended on the contents of memory
894 returned by xmalloc. If flickering happens again, activate
895 the code below. If the flickering is gone with that, chances
896 are that the flickering has the same reason as here. */
897 memset (p[0], 0, (char *) p[LAST_AREA] - (char *) p[0]);
898 #endif
902 /* Make ROW an empty, enabled row of canonical character height,
903 in window W starting at y-position Y. */
905 void
906 blank_row (struct window *w, struct glyph_row *row, int y)
908 int min_y, max_y;
910 min_y = WINDOW_HEADER_LINE_HEIGHT (w);
911 max_y = WINDOW_BOX_HEIGHT_NO_MODE_LINE (w);
913 clear_glyph_row (row);
914 row->y = y;
915 row->ascent = row->phys_ascent = 0;
916 row->height = row->phys_height = FRAME_LINE_HEIGHT (XFRAME (w->frame));
917 row->visible_height = row->height;
919 if (row->y < min_y)
920 row->visible_height -= min_y - row->y;
921 if (row->y + row->height > max_y)
922 row->visible_height -= row->y + row->height - max_y;
924 row->enabled_p = 1;
928 /* Increment buffer positions in glyph row ROW. DELTA and DELTA_BYTES
929 are the amounts by which to change positions. Note that the first
930 glyph of the text area of a row can have a buffer position even if
931 the used count of the text area is zero. Such rows display line
932 ends. */
934 static void
935 increment_row_positions (struct glyph_row *row,
936 ptrdiff_t delta, ptrdiff_t delta_bytes)
938 int area, i;
940 /* Increment start and end positions. */
941 MATRIX_ROW_START_CHARPOS (row) += delta;
942 MATRIX_ROW_START_BYTEPOS (row) += delta_bytes;
943 MATRIX_ROW_END_CHARPOS (row) += delta;
944 MATRIX_ROW_END_BYTEPOS (row) += delta_bytes;
945 CHARPOS (row->start.pos) += delta;
946 BYTEPOS (row->start.pos) += delta_bytes;
947 CHARPOS (row->end.pos) += delta;
948 BYTEPOS (row->end.pos) += delta_bytes;
950 if (!row->enabled_p)
951 return;
953 /* Increment positions in glyphs. */
954 for (area = 0; area < LAST_AREA; ++area)
955 for (i = 0; i < row->used[area]; ++i)
956 if (BUFFERP (row->glyphs[area][i].object)
957 && row->glyphs[area][i].charpos > 0)
958 row->glyphs[area][i].charpos += delta;
960 /* Capture the case of rows displaying a line end. */
961 if (row->used[TEXT_AREA] == 0
962 && MATRIX_ROW_DISPLAYS_TEXT_P (row))
963 row->glyphs[TEXT_AREA]->charpos += delta;
967 #if 0
968 /* Swap glyphs between two glyph rows A and B. This exchanges glyph
969 contents, i.e. glyph structure contents are exchanged between A and
970 B without changing glyph pointers in A and B. */
972 static void
973 swap_glyphs_in_rows (struct glyph_row *a, struct glyph_row *b)
975 int area;
977 for (area = 0; area < LAST_AREA; ++area)
979 /* Number of glyphs to swap. */
980 int max_used = max (a->used[area], b->used[area]);
982 /* Start of glyphs in area of row A. */
983 struct glyph *glyph_a = a->glyphs[area];
985 /* End + 1 of glyphs in area of row A. */
986 struct glyph *glyph_a_end = a->glyphs[max_used];
988 /* Start of glyphs in area of row B. */
989 struct glyph *glyph_b = b->glyphs[area];
991 while (glyph_a < glyph_a_end)
993 /* Non-ISO HP/UX compiler doesn't like auto struct
994 initialization. */
995 struct glyph temp;
996 temp = *glyph_a;
997 *glyph_a = *glyph_b;
998 *glyph_b = temp;
999 ++glyph_a;
1000 ++glyph_b;
1005 #endif /* 0 */
1007 /* Exchange pointers to glyph memory between glyph rows A and B. Also
1008 exchange the used[] array and the hash values of the rows, because
1009 these should all go together for the row's hash value to be
1010 correct. */
1012 static void
1013 swap_glyph_pointers (struct glyph_row *a, struct glyph_row *b)
1015 int i;
1016 unsigned hash_tem = a->hash;
1018 for (i = 0; i < LAST_AREA + 1; ++i)
1020 struct glyph *temp = a->glyphs[i];
1022 a->glyphs[i] = b->glyphs[i];
1023 b->glyphs[i] = temp;
1024 if (i < LAST_AREA)
1026 short used_tem = a->used[i];
1028 a->used[i] = b->used[i];
1029 b->used[i] = used_tem;
1032 a->hash = b->hash;
1033 b->hash = hash_tem;
1037 /* Copy glyph row structure FROM to glyph row structure TO, except
1038 that glyph pointers, the `used' counts, and the hash values in the
1039 structures are left unchanged. */
1041 static void
1042 copy_row_except_pointers (struct glyph_row *to, struct glyph_row *from)
1044 struct glyph *pointers[1 + LAST_AREA];
1045 short used[LAST_AREA];
1046 unsigned hashval;
1048 /* Save glyph pointers of TO. */
1049 memcpy (pointers, to->glyphs, sizeof to->glyphs);
1050 memcpy (used, to->used, sizeof to->used);
1051 hashval = to->hash;
1053 /* Do a structure assignment. */
1054 *to = *from;
1056 /* Restore original pointers of TO. */
1057 memcpy (to->glyphs, pointers, sizeof to->glyphs);
1058 memcpy (to->used, used, sizeof to->used);
1059 to->hash = hashval;
1063 /* Assign glyph row FROM to glyph row TO. This works like a structure
1064 assignment TO = FROM, except that glyph pointers are not copied but
1065 exchanged between TO and FROM. Pointers must be exchanged to avoid
1066 a memory leak. */
1068 static void
1069 assign_row (struct glyph_row *to, struct glyph_row *from)
1071 swap_glyph_pointers (to, from);
1072 copy_row_except_pointers (to, from);
1076 /* Test whether the glyph memory of the glyph row WINDOW_ROW, which is
1077 a row in a window matrix, is a slice of the glyph memory of the
1078 glyph row FRAME_ROW which is a row in a frame glyph matrix. Value
1079 is true if the glyph memory of WINDOW_ROW is part of the glyph
1080 memory of FRAME_ROW. */
1082 #ifdef GLYPH_DEBUG
1084 static bool
1085 glyph_row_slice_p (struct glyph_row *window_row, struct glyph_row *frame_row)
1087 struct glyph *window_glyph_start = window_row->glyphs[0];
1088 struct glyph *frame_glyph_start = frame_row->glyphs[0];
1089 struct glyph *frame_glyph_end = frame_row->glyphs[LAST_AREA];
1091 return (frame_glyph_start <= window_glyph_start
1092 && window_glyph_start < frame_glyph_end);
1095 #endif /* GLYPH_DEBUG */
1097 #if 0
1099 /* Find the row in the window glyph matrix WINDOW_MATRIX being a slice
1100 of ROW in the frame matrix FRAME_MATRIX. Value is null if no row
1101 in WINDOW_MATRIX is found satisfying the condition. */
1103 static struct glyph_row *
1104 find_glyph_row_slice (struct glyph_matrix *window_matrix,
1105 struct glyph_matrix *frame_matrix, int row)
1107 int i;
1109 eassert (row >= 0 && row < frame_matrix->nrows);
1111 for (i = 0; i < window_matrix->nrows; ++i)
1112 if (glyph_row_slice_p (window_matrix->rows + i,
1113 frame_matrix->rows + row))
1114 break;
1116 return i < window_matrix->nrows ? window_matrix->rows + i : 0;
1119 #endif /* 0 */
1121 /* Prepare ROW for display. Desired rows are cleared lazily,
1122 i.e. they are only marked as to be cleared by setting their
1123 enabled_p flag to zero. When a row is to be displayed, a prior
1124 call to this function really clears it. */
1126 void
1127 prepare_desired_row (struct glyph_row *row)
1129 if (!row->enabled_p)
1131 bool rp = row->reversed_p;
1133 clear_glyph_row (row);
1134 row->enabled_p = 1;
1135 row->reversed_p = rp;
1140 /* Return a hash code for glyph row ROW. */
1142 static int
1143 line_hash_code (struct glyph_row *row)
1145 int hash = 0;
1147 if (row->enabled_p)
1149 struct glyph *glyph = row->glyphs[TEXT_AREA];
1150 struct glyph *end = glyph + row->used[TEXT_AREA];
1152 while (glyph < end)
1154 int c = glyph->u.ch;
1155 int face_id = glyph->face_id;
1156 if (FRAME_MUST_WRITE_SPACES (SELECTED_FRAME ())) /* XXX Is SELECTED_FRAME OK here? */
1157 c -= SPACEGLYPH;
1158 hash = (((hash << 4) + (hash >> 24)) & 0x0fffffff) + c;
1159 hash = (((hash << 4) + (hash >> 24)) & 0x0fffffff) + face_id;
1160 ++glyph;
1163 if (hash == 0)
1164 hash = 1;
1167 return hash;
1171 /* Return the cost of drawing line VPOS in MATRIX. The cost equals
1172 the number of characters in the line. If must_write_spaces is
1173 zero, leading and trailing spaces are ignored. */
1175 static int
1176 line_draw_cost (struct glyph_matrix *matrix, int vpos)
1178 struct glyph_row *row = matrix->rows + vpos;
1179 struct glyph *beg = row->glyphs[TEXT_AREA];
1180 struct glyph *end = beg + row->used[TEXT_AREA];
1181 int len;
1182 Lisp_Object *glyph_table_base = GLYPH_TABLE_BASE;
1183 ptrdiff_t glyph_table_len = GLYPH_TABLE_LENGTH;
1185 /* Ignore trailing and leading spaces if we can. */
1186 if (!FRAME_MUST_WRITE_SPACES (SELECTED_FRAME ())) /* XXX Is SELECTED_FRAME OK here? */
1188 /* Skip from the end over trailing spaces. */
1189 while (end > beg && CHAR_GLYPH_SPACE_P (*(end - 1)))
1190 --end;
1192 /* All blank line. */
1193 if (end == beg)
1194 return 0;
1196 /* Skip over leading spaces. */
1197 while (CHAR_GLYPH_SPACE_P (*beg))
1198 ++beg;
1201 /* If we don't have a glyph-table, each glyph is one character,
1202 so return the number of glyphs. */
1203 if (glyph_table_base == 0)
1204 len = end - beg;
1205 else
1207 /* Otherwise, scan the glyphs and accumulate their total length
1208 in LEN. */
1209 len = 0;
1210 while (beg < end)
1212 GLYPH g;
1214 SET_GLYPH_FROM_CHAR_GLYPH (g, *beg);
1216 if (GLYPH_INVALID_P (g)
1217 || GLYPH_SIMPLE_P (glyph_table_base, glyph_table_len, g))
1218 len += 1;
1219 else
1220 len += GLYPH_LENGTH (glyph_table_base, g);
1222 ++beg;
1226 return len;
1230 /* Return true if the glyph rows A and B have equal contents.
1231 MOUSE_FACE_P means compare the mouse_face_p flags of A and B, too. */
1233 static bool
1234 row_equal_p (struct glyph_row *a, struct glyph_row *b, bool mouse_face_p)
1236 eassert (verify_row_hash (a));
1237 eassert (verify_row_hash (b));
1239 if (a == b)
1240 return 1;
1241 else if (a->hash != b->hash)
1242 return 0;
1243 else
1245 struct glyph *a_glyph, *b_glyph, *a_end;
1246 int area;
1248 if (mouse_face_p && a->mouse_face_p != b->mouse_face_p)
1249 return 0;
1251 /* Compare glyphs. */
1252 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
1254 if (a->used[area] != b->used[area])
1255 return 0;
1257 a_glyph = a->glyphs[area];
1258 a_end = a_glyph + a->used[area];
1259 b_glyph = b->glyphs[area];
1261 while (a_glyph < a_end
1262 && GLYPH_EQUAL_P (a_glyph, b_glyph))
1263 ++a_glyph, ++b_glyph;
1265 if (a_glyph != a_end)
1266 return 0;
1269 if (a->fill_line_p != b->fill_line_p
1270 || a->cursor_in_fringe_p != b->cursor_in_fringe_p
1271 || a->left_fringe_bitmap != b->left_fringe_bitmap
1272 || a->left_fringe_face_id != b->left_fringe_face_id
1273 || a->left_fringe_offset != b->left_fringe_offset
1274 || a->right_fringe_bitmap != b->right_fringe_bitmap
1275 || a->right_fringe_face_id != b->right_fringe_face_id
1276 || a->right_fringe_offset != b->right_fringe_offset
1277 || a->fringe_bitmap_periodic_p != b->fringe_bitmap_periodic_p
1278 || a->overlay_arrow_bitmap != b->overlay_arrow_bitmap
1279 || a->exact_window_width_line_p != b->exact_window_width_line_p
1280 || a->overlapped_p != b->overlapped_p
1281 || (MATRIX_ROW_CONTINUATION_LINE_P (a)
1282 != MATRIX_ROW_CONTINUATION_LINE_P (b))
1283 || a->reversed_p != b->reversed_p
1284 /* Different partially visible characters on left margin. */
1285 || a->x != b->x
1286 /* Different height. */
1287 || a->ascent != b->ascent
1288 || a->phys_ascent != b->phys_ascent
1289 || a->phys_height != b->phys_height
1290 || a->visible_height != b->visible_height)
1291 return 0;
1294 return 1;
1299 /***********************************************************************
1300 Glyph Pool
1302 See dispextern.h for an overall explanation of glyph pools.
1303 ***********************************************************************/
1305 /* Allocate a glyph_pool structure. The structure returned is initialized
1306 with zeros. If GLYPH_DEBUG and ENABLE_CHECKING are in effect, the global
1307 variable glyph_pool_count is incremented for each pool allocated. */
1309 static struct glyph_pool *
1310 new_glyph_pool (void)
1312 struct glyph_pool *result = xzalloc (sizeof *result);
1314 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1315 /* For memory leak and double deletion checking. */
1316 ++glyph_pool_count;
1317 #endif
1319 return result;
1323 /* Free a glyph_pool structure POOL. The function may be called with
1324 a null POOL pointer. If GLYPH_DEBUG and ENABLE_CHECKING are in effect,
1325 global variable glyph_pool_count is decremented with every pool structure
1326 freed. If this count gets negative, more structures were freed than
1327 allocated, i.e. one structure must have been freed more than once or
1328 a bogus pointer was passed to free_glyph_pool. */
1330 static void
1331 free_glyph_pool (struct glyph_pool *pool)
1333 if (pool)
1335 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
1336 /* More freed than allocated? */
1337 --glyph_pool_count;
1338 eassert (glyph_pool_count >= 0);
1339 #endif
1340 xfree (pool->glyphs);
1341 xfree (pool);
1346 /* Enlarge a glyph pool POOL. MATRIX_DIM gives the number of rows and
1347 columns we need. This function never shrinks a pool. The only
1348 case in which this would make sense, would be when a frame's size
1349 is changed from a large value to a smaller one. But, if someone
1350 does it once, we can expect that he will do it again.
1352 Return true if the pool changed in a way which makes
1353 re-adjusting window glyph matrices necessary. */
1355 static bool
1356 realloc_glyph_pool (struct glyph_pool *pool, struct dim matrix_dim)
1358 ptrdiff_t needed;
1359 bool changed_p;
1361 changed_p = (pool->glyphs == 0
1362 || matrix_dim.height != pool->nrows
1363 || matrix_dim.width != pool->ncolumns);
1365 /* Enlarge the glyph pool. */
1366 needed = matrix_dim.width;
1367 if (INT_MULTIPLY_OVERFLOW (needed, matrix_dim.height))
1368 memory_full (SIZE_MAX);
1369 needed *= matrix_dim.height;
1370 if (needed > pool->nglyphs)
1372 ptrdiff_t old_nglyphs = pool->nglyphs;
1373 pool->glyphs = xpalloc (pool->glyphs, &pool->nglyphs,
1374 needed - old_nglyphs, -1, sizeof *pool->glyphs);
1375 memset (pool->glyphs + old_nglyphs, 0,
1376 (pool->nglyphs - old_nglyphs) * sizeof *pool->glyphs);
1379 /* Remember the number of rows and columns because (a) we use them
1380 to do sanity checks, and (b) the number of columns determines
1381 where rows in the frame matrix start---this must be available to
1382 determine pointers to rows of window sub-matrices. */
1383 pool->nrows = matrix_dim.height;
1384 pool->ncolumns = matrix_dim.width;
1386 return changed_p;
1391 /***********************************************************************
1392 Debug Code
1393 ***********************************************************************/
1395 #ifdef GLYPH_DEBUG
1398 /* Flush standard output. This is sometimes useful to call from the debugger.
1399 XXX Maybe this should be changed to flush the current terminal instead of
1400 stdout.
1403 void flush_stdout (void) EXTERNALLY_VISIBLE;
1405 void
1406 flush_stdout (void)
1408 fflush (stdout);
1412 /* Check that no glyph pointers have been lost in MATRIX. If a
1413 pointer has been lost, e.g. by using a structure assignment between
1414 rows, at least one pointer must occur more than once in the rows of
1415 MATRIX. */
1417 void
1418 check_matrix_pointer_lossage (struct glyph_matrix *matrix)
1420 int i, j;
1422 for (i = 0; i < matrix->nrows; ++i)
1423 for (j = 0; j < matrix->nrows; ++j)
1424 eassert (i == j
1425 || (matrix->rows[i].glyphs[TEXT_AREA]
1426 != matrix->rows[j].glyphs[TEXT_AREA]));
1430 /* Get a pointer to glyph row ROW in MATRIX, with bounds checks. */
1432 struct glyph_row *
1433 matrix_row (struct glyph_matrix *matrix, int row)
1435 eassert (matrix && matrix->rows);
1436 eassert (row >= 0 && row < matrix->nrows);
1438 /* That's really too slow for normal testing because this function
1439 is called almost everywhere. Although---it's still astonishingly
1440 fast, so it is valuable to have for debugging purposes. */
1441 #if 0
1442 check_matrix_pointer_lossage (matrix);
1443 #endif
1445 return matrix->rows + row;
1449 #if 0 /* This function makes invalid assumptions when text is
1450 partially invisible. But it might come handy for debugging
1451 nevertheless. */
1453 /* Check invariants that must hold for an up to date current matrix of
1454 window W. */
1456 static void
1457 check_matrix_invariants (struct window *w)
1459 struct glyph_matrix *matrix = w->current_matrix;
1460 int yb = window_text_bottom_y (w);
1461 struct glyph_row *row = matrix->rows;
1462 struct glyph_row *last_text_row = NULL;
1463 struct buffer *saved = current_buffer;
1464 struct buffer *buffer = XBUFFER (w->contents);
1465 int c;
1467 /* This can sometimes happen for a fresh window. */
1468 if (matrix->nrows < 2)
1469 return;
1471 set_buffer_temp (buffer);
1473 /* Note: last row is always reserved for the mode line. */
1474 while (MATRIX_ROW_DISPLAYS_TEXT_P (row)
1475 && MATRIX_ROW_BOTTOM_Y (row) < yb)
1477 struct glyph_row *next = row + 1;
1479 if (MATRIX_ROW_DISPLAYS_TEXT_P (row))
1480 last_text_row = row;
1482 /* Check that character and byte positions are in sync. */
1483 eassert (MATRIX_ROW_START_BYTEPOS (row)
1484 == CHAR_TO_BYTE (MATRIX_ROW_START_CHARPOS (row)));
1485 eassert (BYTEPOS (row->start.pos)
1486 == CHAR_TO_BYTE (CHARPOS (row->start.pos)));
1488 /* CHAR_TO_BYTE aborts when invoked for a position > Z. We can
1489 have such a position temporarily in case of a minibuffer
1490 displaying something like `[Sole completion]' at its end. */
1491 if (MATRIX_ROW_END_CHARPOS (row) < BUF_ZV (current_buffer))
1493 eassert (MATRIX_ROW_END_BYTEPOS (row)
1494 == CHAR_TO_BYTE (MATRIX_ROW_END_CHARPOS (row)));
1495 eassert (BYTEPOS (row->end.pos)
1496 == CHAR_TO_BYTE (CHARPOS (row->end.pos)));
1499 /* Check that end position of `row' is equal to start position
1500 of next row. */
1501 if (next->enabled_p && MATRIX_ROW_DISPLAYS_TEXT_P (next))
1503 eassert (MATRIX_ROW_END_CHARPOS (row)
1504 == MATRIX_ROW_START_CHARPOS (next));
1505 eassert (MATRIX_ROW_END_BYTEPOS (row)
1506 == MATRIX_ROW_START_BYTEPOS (next));
1507 eassert (CHARPOS (row->end.pos) == CHARPOS (next->start.pos));
1508 eassert (BYTEPOS (row->end.pos) == BYTEPOS (next->start.pos));
1510 row = next;
1513 eassert (w->current_matrix->nrows == w->desired_matrix->nrows);
1514 eassert (w->desired_matrix->rows != NULL);
1515 set_buffer_temp (saved);
1518 #endif /* 0 */
1520 #endif /* GLYPH_DEBUG */
1524 /**********************************************************************
1525 Allocating/ Adjusting Glyph Matrices
1526 **********************************************************************/
1528 /* Allocate glyph matrices over a window tree for a frame-based
1529 redisplay
1531 X and Y are column/row within the frame glyph matrix where
1532 sub-matrices for the window tree rooted at WINDOW must be
1533 allocated. DIM_ONLY_P means that the caller of this
1534 function is only interested in the result matrix dimension, and
1535 matrix adjustments should not be performed.
1537 The function returns the total width/height of the sub-matrices of
1538 the window tree. If called on a frame root window, the computation
1539 will take the mini-buffer window into account.
1541 *WINDOW_CHANGE_FLAGS is set to a bit mask with bits
1543 NEW_LEAF_MATRIX set if any window in the tree did not have a
1544 glyph matrices yet, and
1546 CHANGED_LEAF_MATRIX set if the dimension or location of a matrix of
1547 any window in the tree will be changed or have been changed (see
1548 DIM_ONLY_P)
1550 *WINDOW_CHANGE_FLAGS must be initialized by the caller of this
1551 function.
1553 Windows are arranged into chains of windows on the same level
1554 through the next fields of window structures. Such a level can be
1555 either a sequence of horizontally adjacent windows from left to
1556 right, or a sequence of vertically adjacent windows from top to
1557 bottom. Each window in a horizontal sequence can be either a leaf
1558 window or a vertical sequence; a window in a vertical sequence can
1559 be either a leaf or a horizontal sequence. All windows in a
1560 horizontal sequence have the same height, and all windows in a
1561 vertical sequence have the same width.
1563 This function uses, for historical reasons, a more general
1564 algorithm to determine glyph matrix dimensions that would be
1565 necessary.
1567 The matrix height of a horizontal sequence is determined by the
1568 maximum height of any matrix in the sequence. The matrix width of
1569 a horizontal sequence is computed by adding up matrix widths of
1570 windows in the sequence.
1572 |<------- result width ------->|
1573 +---------+----------+---------+ ---
1574 | | | | |
1575 | | | |
1576 +---------+ | | result height
1577 | +---------+
1578 | | |
1579 +----------+ ---
1581 The matrix width of a vertical sequence is the maximum matrix width
1582 of any window in the sequence. Its height is computed by adding up
1583 matrix heights of windows in the sequence.
1585 |<---- result width -->|
1586 +---------+ ---
1587 | | |
1588 | | |
1589 +---------+--+ |
1590 | | |
1591 | | result height
1593 +------------+---------+ |
1594 | | |
1595 | | |
1596 +------------+---------+ --- */
1598 /* Bit indicating that a new matrix will be allocated or has been
1599 allocated. */
1601 #define NEW_LEAF_MATRIX (1 << 0)
1603 /* Bit indicating that a matrix will or has changed its location or
1604 size. */
1606 #define CHANGED_LEAF_MATRIX (1 << 1)
1608 static struct dim
1609 allocate_matrices_for_frame_redisplay (Lisp_Object window, int x, int y,
1610 bool dim_only_p, int *window_change_flags)
1612 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (window)));
1613 int x0 = x, y0 = y;
1614 int wmax = 0, hmax = 0;
1615 struct dim total;
1616 struct dim dim;
1617 struct window *w;
1618 bool in_horz_combination_p;
1620 /* What combination is WINDOW part of? Compute this once since the
1621 result is the same for all windows in the `next' chain. The
1622 special case of a root window (parent equal to nil) is treated
1623 like a vertical combination because a root window's `next'
1624 points to the mini-buffer window, if any, which is arranged
1625 vertically below other windows. */
1626 in_horz_combination_p
1627 = (!NILP (XWINDOW (window)->parent)
1628 && WINDOW_HORIZONTAL_COMBINATION_P (XWINDOW (XWINDOW (window)->parent)));
1630 /* For WINDOW and all windows on the same level. */
1633 w = XWINDOW (window);
1635 /* Get the dimension of the window sub-matrix for W, depending
1636 on whether this is a combination or a leaf window. */
1637 if (WINDOWP (w->contents))
1638 dim = allocate_matrices_for_frame_redisplay (w->contents, x, y,
1639 dim_only_p,
1640 window_change_flags);
1641 else
1643 /* If not already done, allocate sub-matrix structures. */
1644 if (w->desired_matrix == NULL)
1646 w->desired_matrix = new_glyph_matrix (f->desired_pool);
1647 w->current_matrix = new_glyph_matrix (f->current_pool);
1648 *window_change_flags |= NEW_LEAF_MATRIX;
1651 /* Width and height MUST be chosen so that there are no
1652 holes in the frame matrix. */
1653 dim.width = required_matrix_width (w);
1654 dim.height = required_matrix_height (w);
1656 /* Will matrix be re-allocated? */
1657 if (x != w->desired_matrix->matrix_x
1658 || y != w->desired_matrix->matrix_y
1659 || dim.width != w->desired_matrix->matrix_w
1660 || dim.height != w->desired_matrix->matrix_h
1661 || (margin_glyphs_to_reserve (w, dim.width,
1662 w->left_margin_cols)
1663 != w->desired_matrix->left_margin_glyphs)
1664 || (margin_glyphs_to_reserve (w, dim.width,
1665 w->right_margin_cols)
1666 != w->desired_matrix->right_margin_glyphs))
1667 *window_change_flags |= CHANGED_LEAF_MATRIX;
1669 /* Actually change matrices, if allowed. Do not consider
1670 CHANGED_LEAF_MATRIX computed above here because the pool
1671 may have been changed which we don't now here. We trust
1672 that we only will be called with DIM_ONLY_P when
1673 necessary. */
1674 if (!dim_only_p)
1676 adjust_glyph_matrix (w, w->desired_matrix, x, y, dim);
1677 adjust_glyph_matrix (w, w->current_matrix, x, y, dim);
1681 /* If we are part of a horizontal combination, advance x for
1682 windows to the right of W; otherwise advance y for windows
1683 below W. */
1684 if (in_horz_combination_p)
1685 x += dim.width;
1686 else
1687 y += dim.height;
1689 /* Remember maximum glyph matrix dimensions. */
1690 wmax = max (wmax, dim.width);
1691 hmax = max (hmax, dim.height);
1693 /* Next window on same level. */
1694 window = w->next;
1696 while (!NILP (window));
1698 /* Set `total' to the total glyph matrix dimension of this window
1699 level. In a vertical combination, the width is the width of the
1700 widest window; the height is the y we finally reached, corrected
1701 by the y we started with. In a horizontal combination, the total
1702 height is the height of the tallest window, and the width is the
1703 x we finally reached, corrected by the x we started with. */
1704 if (in_horz_combination_p)
1706 total.width = x - x0;
1707 total.height = hmax;
1709 else
1711 total.width = wmax;
1712 total.height = y - y0;
1715 return total;
1719 /* Return the required height of glyph matrices for window W. */
1721 static int
1722 required_matrix_height (struct window *w)
1724 #ifdef HAVE_WINDOW_SYSTEM
1725 struct frame *f = XFRAME (w->frame);
1727 if (FRAME_WINDOW_P (f))
1729 int ch_height = FRAME_SMALLEST_FONT_HEIGHT (f);
1730 int window_pixel_height = window_box_height (w) + eabs (w->vscroll);
1731 return (((window_pixel_height + ch_height - 1)
1732 / ch_height) * w->nrows_scale_factor
1733 /* One partially visible line at the top and
1734 bottom of the window. */
1736 /* 2 for header and mode line. */
1737 + 2);
1739 #endif /* HAVE_WINDOW_SYSTEM */
1741 return WINDOW_TOTAL_LINES (w);
1745 /* Return the required width of glyph matrices for window W. */
1747 static int
1748 required_matrix_width (struct window *w)
1750 #ifdef HAVE_WINDOW_SYSTEM
1751 struct frame *f = XFRAME (w->frame);
1752 if (FRAME_WINDOW_P (f))
1754 int ch_width = FRAME_SMALLEST_CHAR_WIDTH (f);
1755 int window_pixel_width = WINDOW_TOTAL_WIDTH (w);
1757 /* Compute number of glyphs needed in a glyph row. */
1758 return (((window_pixel_width + ch_width - 1)
1759 / ch_width) * w->ncols_scale_factor
1760 /* 2 partially visible columns in the text area. */
1762 /* One partially visible column at the right
1763 edge of each marginal area. */
1764 + 1 + 1);
1766 #endif /* HAVE_WINDOW_SYSTEM */
1768 return w->total_cols;
1772 /* Allocate window matrices for window-based redisplay. W is the
1773 window whose matrices must be allocated/reallocated. */
1775 static void
1776 allocate_matrices_for_window_redisplay (struct window *w)
1778 while (w)
1780 if (WINDOWP (w->contents))
1781 allocate_matrices_for_window_redisplay (XWINDOW (w->contents));
1782 else
1784 /* W is a leaf window. */
1785 struct dim dim;
1787 /* If matrices are not yet allocated, allocate them now. */
1788 if (w->desired_matrix == NULL)
1790 w->desired_matrix = new_glyph_matrix (NULL);
1791 w->current_matrix = new_glyph_matrix (NULL);
1794 dim.width = required_matrix_width (w);
1795 dim.height = required_matrix_height (w);
1796 adjust_glyph_matrix (w, w->desired_matrix, 0, 0, dim);
1797 adjust_glyph_matrix (w, w->current_matrix, 0, 0, dim);
1800 w = NILP (w->next) ? NULL : XWINDOW (w->next);
1805 /* Re-allocate/ re-compute glyph matrices on frame F. If F is null,
1806 do it for all frames; otherwise do it just for the given frame.
1807 This function must be called when a new frame is created, its size
1808 changes, or its window configuration changes. */
1810 void
1811 adjust_glyphs (struct frame *f)
1813 /* Block input so that expose events and other events that access
1814 glyph matrices are not processed while we are changing them. */
1815 block_input ();
1817 if (f)
1818 adjust_frame_glyphs (f);
1819 else
1821 Lisp_Object tail, lisp_frame;
1823 FOR_EACH_FRAME (tail, lisp_frame)
1824 adjust_frame_glyphs (XFRAME (lisp_frame));
1827 unblock_input ();
1830 /* Allocate/reallocate glyph matrices of a single frame F. */
1832 static void
1833 adjust_frame_glyphs (struct frame *f)
1835 if (FRAME_WINDOW_P (f))
1836 adjust_frame_glyphs_for_window_redisplay (f);
1837 else
1838 adjust_frame_glyphs_for_frame_redisplay (f);
1840 /* Don't forget the buffer for decode_mode_spec. */
1841 adjust_decode_mode_spec_buffer (f);
1843 f->glyphs_initialized_p = 1;
1846 /* Return true if any window in the tree has nonzero window margins. See
1847 the hack at the end of adjust_frame_glyphs_for_frame_redisplay. */
1848 static bool
1849 showing_window_margins_p (struct window *w)
1851 while (w)
1853 if (WINDOWP (w->contents))
1855 if (showing_window_margins_p (XWINDOW (w->contents)))
1856 return 1;
1858 else if (w->left_margin_cols > 0 || w->right_margin_cols > 0)
1859 return 1;
1861 w = NILP (w->next) ? 0 : XWINDOW (w->next);
1863 return 0;
1867 /* In the window tree with root W, build current matrices of leaf
1868 windows from the frame's current matrix. */
1870 static void
1871 fake_current_matrices (Lisp_Object window)
1873 struct window *w;
1875 for (; !NILP (window); window = w->next)
1877 w = XWINDOW (window);
1879 if (WINDOWP (w->contents))
1880 fake_current_matrices (w->contents);
1881 else
1883 int i;
1884 struct frame *f = XFRAME (w->frame);
1885 struct glyph_matrix *m = w->current_matrix;
1886 struct glyph_matrix *fm = f->current_matrix;
1888 eassert (m->matrix_h == WINDOW_TOTAL_LINES (w));
1889 eassert (m->matrix_w == WINDOW_TOTAL_COLS (w));
1891 for (i = 0; i < m->matrix_h; ++i)
1893 struct glyph_row *r = m->rows + i;
1894 struct glyph_row *fr = fm->rows + i + WINDOW_TOP_EDGE_LINE (w);
1896 eassert (r->glyphs[TEXT_AREA] >= fr->glyphs[TEXT_AREA]
1897 && r->glyphs[LAST_AREA] <= fr->glyphs[LAST_AREA]);
1899 r->enabled_p = fr->enabled_p;
1900 if (r->enabled_p)
1902 r->used[LEFT_MARGIN_AREA] = m->left_margin_glyphs;
1903 r->used[RIGHT_MARGIN_AREA] = m->right_margin_glyphs;
1904 r->used[TEXT_AREA] = (m->matrix_w
1905 - r->used[LEFT_MARGIN_AREA]
1906 - r->used[RIGHT_MARGIN_AREA]);
1907 r->mode_line_p = 0;
1915 /* Save away the contents of frame F's current frame matrix. Value is
1916 a glyph matrix holding the contents of F's current frame matrix. */
1918 static struct glyph_matrix *
1919 save_current_matrix (struct frame *f)
1921 int i;
1922 struct glyph_matrix *saved = xzalloc (sizeof *saved);
1923 saved->nrows = f->current_matrix->nrows;
1924 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
1926 for (i = 0; i < saved->nrows; ++i)
1928 struct glyph_row *from = f->current_matrix->rows + i;
1929 struct glyph_row *to = saved->rows + i;
1930 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
1931 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
1932 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
1933 to->used[TEXT_AREA] = from->used[TEXT_AREA];
1936 return saved;
1940 /* Restore the contents of frame F's current frame matrix from SAVED,
1941 and free memory associated with SAVED. */
1943 static void
1944 restore_current_matrix (struct frame *f, struct glyph_matrix *saved)
1946 int i;
1948 for (i = 0; i < saved->nrows; ++i)
1950 struct glyph_row *from = saved->rows + i;
1951 struct glyph_row *to = f->current_matrix->rows + i;
1952 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
1953 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
1954 to->used[TEXT_AREA] = from->used[TEXT_AREA];
1955 xfree (from->glyphs[TEXT_AREA]);
1958 xfree (saved->rows);
1959 xfree (saved);
1964 /* Allocate/reallocate glyph matrices of a single frame F for
1965 frame-based redisplay. */
1967 static void
1968 adjust_frame_glyphs_for_frame_redisplay (struct frame *f)
1970 struct dim matrix_dim;
1971 bool pool_changed_p;
1972 int window_change_flags;
1973 int top_window_y;
1975 if (!FRAME_LIVE_P (f))
1976 return;
1978 top_window_y = FRAME_TOP_MARGIN (f);
1980 /* Allocate glyph pool structures if not already done. */
1981 if (f->desired_pool == NULL)
1983 f->desired_pool = new_glyph_pool ();
1984 f->current_pool = new_glyph_pool ();
1987 /* Allocate frames matrix structures if needed. */
1988 if (f->desired_matrix == NULL)
1990 f->desired_matrix = new_glyph_matrix (f->desired_pool);
1991 f->current_matrix = new_glyph_matrix (f->current_pool);
1994 /* Compute window glyph matrices. (This takes the mini-buffer
1995 window into account). The result is the size of the frame glyph
1996 matrix needed. The variable window_change_flags is set to a bit
1997 mask indicating whether new matrices will be allocated or
1998 existing matrices change their size or location within the frame
1999 matrix. */
2000 window_change_flags = 0;
2001 matrix_dim
2002 = allocate_matrices_for_frame_redisplay (FRAME_ROOT_WINDOW (f),
2003 0, top_window_y,
2005 &window_change_flags);
2007 /* Add in menu bar lines, if any. */
2008 matrix_dim.height += top_window_y;
2010 /* Enlarge pools as necessary. */
2011 pool_changed_p = realloc_glyph_pool (f->desired_pool, matrix_dim);
2012 realloc_glyph_pool (f->current_pool, matrix_dim);
2014 /* Set up glyph pointers within window matrices. Do this only if
2015 absolutely necessary since it requires a frame redraw. */
2016 if (pool_changed_p || window_change_flags)
2018 /* Do it for window matrices. */
2019 allocate_matrices_for_frame_redisplay (FRAME_ROOT_WINDOW (f),
2020 0, top_window_y, 0,
2021 &window_change_flags);
2023 /* Size of frame matrices must equal size of frame. Note
2024 that we are called for X frames with window widths NOT equal
2025 to the frame width (from CHANGE_FRAME_SIZE_1). */
2026 eassert (matrix_dim.width == FRAME_COLS (f)
2027 && matrix_dim.height == FRAME_LINES (f));
2029 /* Pointers to glyph memory in glyph rows are exchanged during
2030 the update phase of redisplay, which means in general that a
2031 frame's current matrix consists of pointers into both the
2032 desired and current glyph pool of the frame. Adjusting a
2033 matrix sets the frame matrix up so that pointers are all into
2034 the same pool. If we want to preserve glyph contents of the
2035 current matrix over a call to adjust_glyph_matrix, we must
2036 make a copy of the current glyphs, and restore the current
2037 matrix' contents from that copy. */
2038 if (display_completed
2039 && !FRAME_GARBAGED_P (f)
2040 && matrix_dim.width == f->current_matrix->matrix_w
2041 && matrix_dim.height == f->current_matrix->matrix_h
2042 /* For some reason, the frame glyph matrix gets corrupted if
2043 any of the windows contain margins. I haven't been able
2044 to hunt down the reason, but for the moment this prevents
2045 the problem from manifesting. -- cyd */
2046 && !showing_window_margins_p (XWINDOW (FRAME_ROOT_WINDOW (f))))
2048 struct glyph_matrix *copy = save_current_matrix (f);
2049 adjust_glyph_matrix (NULL, f->desired_matrix, 0, 0, matrix_dim);
2050 adjust_glyph_matrix (NULL, f->current_matrix, 0, 0, matrix_dim);
2051 restore_current_matrix (f, copy);
2052 fake_current_matrices (FRAME_ROOT_WINDOW (f));
2054 else
2056 adjust_glyph_matrix (NULL, f->desired_matrix, 0, 0, matrix_dim);
2057 adjust_glyph_matrix (NULL, f->current_matrix, 0, 0, matrix_dim);
2058 SET_FRAME_GARBAGED (f);
2064 /* Allocate/reallocate glyph matrices of a single frame F for
2065 window-based redisplay. */
2067 static void
2068 adjust_frame_glyphs_for_window_redisplay (struct frame *f)
2070 eassert (FRAME_WINDOW_P (f) && FRAME_LIVE_P (f));
2072 /* Allocate/reallocate window matrices. */
2073 allocate_matrices_for_window_redisplay (XWINDOW (FRAME_ROOT_WINDOW (f)));
2075 #ifdef HAVE_X_WINDOWS
2076 /* Allocate/ reallocate matrices of the dummy window used to display
2077 the menu bar under X when no X toolkit support is available. */
2078 #if ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
2080 /* Allocate a dummy window if not already done. */
2081 struct window *w;
2082 if (NILP (f->menu_bar_window))
2084 Lisp_Object frame;
2085 fset_menu_bar_window (f, make_window ());
2086 w = XWINDOW (f->menu_bar_window);
2087 XSETFRAME (frame, f);
2088 wset_frame (w, frame);
2089 w->pseudo_window_p = 1;
2091 else
2092 w = XWINDOW (f->menu_bar_window);
2094 /* Set window dimensions to frame dimensions and allocate or
2095 adjust glyph matrices of W. */
2096 w->top_line = 0;
2097 w->left_col = 0;
2098 w->total_lines = FRAME_MENU_BAR_LINES (f);
2099 w->total_cols = FRAME_TOTAL_COLS (f);
2100 allocate_matrices_for_window_redisplay (w);
2102 #endif /* not USE_X_TOOLKIT && not USE_GTK */
2103 #endif /* HAVE_X_WINDOWS */
2105 #ifndef USE_GTK
2107 /* Allocate/ reallocate matrices of the tool bar window. If we
2108 don't have a tool bar window yet, make one. */
2109 struct window *w;
2110 if (NILP (f->tool_bar_window))
2112 Lisp_Object frame;
2113 fset_tool_bar_window (f, make_window ());
2114 w = XWINDOW (f->tool_bar_window);
2115 XSETFRAME (frame, f);
2116 wset_frame (w, frame);
2117 w->pseudo_window_p = 1;
2119 else
2120 w = XWINDOW (f->tool_bar_window);
2122 w->top_line = FRAME_MENU_BAR_LINES (f);
2123 w->left_col = 0;
2124 w->total_lines = FRAME_TOOL_BAR_LINES (f);
2125 w->total_cols = FRAME_TOTAL_COLS (f);
2126 allocate_matrices_for_window_redisplay (w);
2128 #endif
2132 /* Re-allocate buffer for decode_mode_spec on frame F. */
2134 static void
2135 adjust_decode_mode_spec_buffer (struct frame *f)
2137 f->decode_mode_spec_buffer = xrealloc (f->decode_mode_spec_buffer,
2138 FRAME_MESSAGE_BUF_SIZE (f) + 1);
2143 /**********************************************************************
2144 Freeing Glyph Matrices
2145 **********************************************************************/
2147 /* Free glyph memory for a frame F. F may be null. This function can
2148 be called for the same frame more than once. The root window of
2149 F may be nil when this function is called. This is the case when
2150 the function is called when F is destroyed. */
2152 void
2153 free_glyphs (struct frame *f)
2155 if (f && f->glyphs_initialized_p)
2157 /* Block interrupt input so that we don't get surprised by an X
2158 event while we're in an inconsistent state. */
2159 block_input ();
2160 f->glyphs_initialized_p = 0;
2162 /* Release window sub-matrices. */
2163 if (!NILP (f->root_window))
2164 free_window_matrices (XWINDOW (f->root_window));
2166 #if defined (HAVE_X_WINDOWS) && ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
2167 /* Free the dummy window for menu bars without X toolkit and its
2168 glyph matrices. */
2169 if (!NILP (f->menu_bar_window))
2171 struct window *w = XWINDOW (f->menu_bar_window);
2172 free_glyph_matrix (w->desired_matrix);
2173 free_glyph_matrix (w->current_matrix);
2174 w->desired_matrix = w->current_matrix = NULL;
2175 fset_menu_bar_window (f, Qnil);
2177 #endif
2179 /* Free the tool bar window and its glyph matrices. */
2180 if (!NILP (f->tool_bar_window))
2182 struct window *w = XWINDOW (f->tool_bar_window);
2183 free_glyph_matrix (w->desired_matrix);
2184 free_glyph_matrix (w->current_matrix);
2185 w->desired_matrix = w->current_matrix = NULL;
2186 fset_tool_bar_window (f, Qnil);
2189 /* Release frame glyph matrices. Reset fields to zero in
2190 case we are called a second time. */
2191 if (f->desired_matrix)
2193 free_glyph_matrix (f->desired_matrix);
2194 free_glyph_matrix (f->current_matrix);
2195 f->desired_matrix = f->current_matrix = NULL;
2198 /* Release glyph pools. */
2199 if (f->desired_pool)
2201 free_glyph_pool (f->desired_pool);
2202 free_glyph_pool (f->current_pool);
2203 f->desired_pool = f->current_pool = NULL;
2206 unblock_input ();
2211 /* Free glyph sub-matrices in the window tree rooted at W. This
2212 function may be called with a null pointer, and it may be called on
2213 the same tree more than once. */
2215 void
2216 free_window_matrices (struct window *w)
2218 while (w)
2220 if (WINDOWP (w->contents))
2221 free_window_matrices (XWINDOW (w->contents));
2222 else
2224 /* This is a leaf window. Free its memory and reset fields
2225 to zero in case this function is called a second time for
2226 W. */
2227 free_glyph_matrix (w->current_matrix);
2228 free_glyph_matrix (w->desired_matrix);
2229 w->current_matrix = w->desired_matrix = NULL;
2232 /* Next window on same level. */
2233 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2238 /* Check glyph memory leaks. This function is called from
2239 shut_down_emacs. Note that frames are not destroyed when Emacs
2240 exits. We therefore free all glyph memory for all active frames
2241 explicitly and check that nothing is left allocated. */
2243 void
2244 check_glyph_memory (void)
2246 Lisp_Object tail, frame;
2248 /* Free glyph memory for all frames. */
2249 FOR_EACH_FRAME (tail, frame)
2250 free_glyphs (XFRAME (frame));
2252 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
2253 /* Check that nothing is left allocated. */
2254 eassert (glyph_matrix_count == 0);
2255 eassert (glyph_pool_count == 0);
2256 #endif
2261 /**********************************************************************
2262 Building a Frame Matrix
2263 **********************************************************************/
2265 /* Most of the redisplay code works on glyph matrices attached to
2266 windows. This is a good solution most of the time, but it is not
2267 suitable for terminal code. Terminal output functions cannot rely
2268 on being able to set an arbitrary terminal window. Instead they
2269 must be provided with a view of the whole frame, i.e. the whole
2270 screen. We build such a view by constructing a frame matrix from
2271 window matrices in this section.
2273 Windows that must be updated have their must_be_updated_p flag set.
2274 For all such windows, their desired matrix is made part of the
2275 desired frame matrix. For other windows, their current matrix is
2276 made part of the desired frame matrix.
2278 +-----------------+----------------+
2279 | desired | desired |
2280 | | |
2281 +-----------------+----------------+
2282 | current |
2284 +----------------------------------+
2286 Desired window matrices can be made part of the frame matrix in a
2287 cheap way: We exploit the fact that the desired frame matrix and
2288 desired window matrices share their glyph memory. This is not
2289 possible for current window matrices. Their glyphs are copied to
2290 the desired frame matrix. The latter is equivalent to
2291 preserve_other_columns in the old redisplay.
2293 Used glyphs counters for frame matrix rows are the result of adding
2294 up glyph lengths of the window matrices. A line in the frame
2295 matrix is enabled, if a corresponding line in a window matrix is
2296 enabled.
2298 After building the desired frame matrix, it will be passed to
2299 terminal code, which will manipulate both the desired and current
2300 frame matrix. Changes applied to the frame's current matrix have
2301 to be visible in current window matrices afterwards, of course.
2303 This problem is solved like this:
2305 1. Window and frame matrices share glyphs. Window matrices are
2306 constructed in a way that their glyph contents ARE the glyph
2307 contents needed in a frame matrix. Thus, any modification of
2308 glyphs done in terminal code will be reflected in window matrices
2309 automatically.
2311 2. Exchanges of rows in a frame matrix done by terminal code are
2312 intercepted by hook functions so that corresponding row operations
2313 on window matrices can be performed. This is necessary because we
2314 use pointers to glyphs in glyph row structures. To satisfy the
2315 assumption of point 1 above that glyphs are updated implicitly in
2316 window matrices when they are manipulated via the frame matrix,
2317 window and frame matrix must of course agree where to find the
2318 glyphs for their rows. Possible manipulations that must be
2319 mirrored are assignments of rows of the desired frame matrix to the
2320 current frame matrix and scrolling the current frame matrix. */
2322 /* Build frame F's desired matrix from window matrices. Only windows
2323 which have the flag must_be_updated_p set have to be updated. Menu
2324 bar lines of a frame are not covered by window matrices, so make
2325 sure not to touch them in this function. */
2327 static void
2328 build_frame_matrix (struct frame *f)
2330 int i;
2332 /* F must have a frame matrix when this function is called. */
2333 eassert (!FRAME_WINDOW_P (f));
2335 /* Clear all rows in the frame matrix covered by window matrices.
2336 Menu bar lines are not covered by windows. */
2337 for (i = FRAME_TOP_MARGIN (f); i < f->desired_matrix->nrows; ++i)
2338 clear_glyph_row (MATRIX_ROW (f->desired_matrix, i));
2340 /* Build the matrix by walking the window tree. */
2341 build_frame_matrix_from_window_tree (f->desired_matrix,
2342 XWINDOW (FRAME_ROOT_WINDOW (f)));
2346 /* Walk a window tree, building a frame matrix MATRIX from window
2347 matrices. W is the root of a window tree. */
2349 static void
2350 build_frame_matrix_from_window_tree (struct glyph_matrix *matrix, struct window *w)
2352 while (w)
2354 if (WINDOWP (w->contents))
2355 build_frame_matrix_from_window_tree (matrix, XWINDOW (w->contents));
2356 else
2357 build_frame_matrix_from_leaf_window (matrix, w);
2359 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2364 /* Add a window's matrix to a frame matrix. FRAME_MATRIX is the
2365 desired frame matrix built. W is a leaf window whose desired or
2366 current matrix is to be added to FRAME_MATRIX. W's flag
2367 must_be_updated_p determines which matrix it contributes to
2368 FRAME_MATRIX. If W->must_be_updated_p, W's desired matrix
2369 is added to FRAME_MATRIX, otherwise W's current matrix is added.
2370 Adding a desired matrix means setting up used counters and such in
2371 frame rows, while adding a current window matrix to FRAME_MATRIX
2372 means copying glyphs. The latter case corresponds to
2373 preserve_other_columns in the old redisplay. */
2375 static void
2376 build_frame_matrix_from_leaf_window (struct glyph_matrix *frame_matrix, struct window *w)
2378 struct glyph_matrix *window_matrix;
2379 int window_y, frame_y;
2380 /* If non-zero, a glyph to insert at the right border of W. */
2381 GLYPH right_border_glyph;
2383 SET_GLYPH_FROM_CHAR (right_border_glyph, 0);
2385 /* Set window_matrix to the matrix we have to add to FRAME_MATRIX. */
2386 if (w->must_be_updated_p)
2388 window_matrix = w->desired_matrix;
2390 /* Decide whether we want to add a vertical border glyph. */
2391 if (!WINDOW_RIGHTMOST_P (w))
2393 struct Lisp_Char_Table *dp = window_display_table (w);
2394 Lisp_Object gc;
2396 SET_GLYPH_FROM_CHAR (right_border_glyph, '|');
2397 if (dp
2398 && (gc = DISP_BORDER_GLYPH (dp), GLYPH_CODE_P (gc)))
2400 SET_GLYPH_FROM_GLYPH_CODE (right_border_glyph, gc);
2401 spec_glyph_lookup_face (w, &right_border_glyph);
2404 if (GLYPH_FACE (right_border_glyph) <= 0)
2405 SET_GLYPH_FACE (right_border_glyph, VERTICAL_BORDER_FACE_ID);
2408 else
2409 window_matrix = w->current_matrix;
2411 /* For all rows in the window matrix and corresponding rows in the
2412 frame matrix. */
2413 window_y = 0;
2414 frame_y = window_matrix->matrix_y;
2415 while (window_y < window_matrix->nrows)
2417 struct glyph_row *frame_row = frame_matrix->rows + frame_y;
2418 struct glyph_row *window_row = window_matrix->rows + window_y;
2419 bool current_row_p = window_matrix == w->current_matrix;
2421 /* Fill up the frame row with spaces up to the left margin of the
2422 window row. */
2423 fill_up_frame_row_with_spaces (frame_row, window_matrix->matrix_x);
2425 /* Fill up areas in the window matrix row with spaces. */
2426 fill_up_glyph_row_with_spaces (window_row);
2428 /* If only part of W's desired matrix has been built, and
2429 window_row wasn't displayed, use the corresponding current
2430 row instead. */
2431 if (window_matrix == w->desired_matrix
2432 && !window_row->enabled_p)
2434 window_row = w->current_matrix->rows + window_y;
2435 current_row_p = 1;
2438 if (current_row_p)
2440 /* Copy window row to frame row. */
2441 memcpy (frame_row->glyphs[TEXT_AREA] + window_matrix->matrix_x,
2442 window_row->glyphs[0],
2443 window_matrix->matrix_w * sizeof (struct glyph));
2445 else
2447 eassert (window_row->enabled_p);
2449 /* Only when a desired row has been displayed, we want
2450 the corresponding frame row to be updated. */
2451 frame_row->enabled_p = 1;
2453 /* Maybe insert a vertical border between horizontally adjacent
2454 windows. */
2455 if (GLYPH_CHAR (right_border_glyph) != 0)
2457 struct glyph *border = window_row->glyphs[LAST_AREA] - 1;
2458 SET_CHAR_GLYPH_FROM_GLYPH (*border, right_border_glyph);
2461 #ifdef GLYPH_DEBUG
2462 /* Window row window_y must be a slice of frame row
2463 frame_y. */
2464 eassert (glyph_row_slice_p (window_row, frame_row));
2466 /* If rows are in sync, we don't have to copy glyphs because
2467 frame and window share glyphs. */
2469 strcpy (w->current_matrix->method, w->desired_matrix->method);
2470 add_window_display_history (w, w->current_matrix->method, 0);
2471 #endif
2474 /* Set number of used glyphs in the frame matrix. Since we fill
2475 up with spaces, and visit leaf windows from left to right it
2476 can be done simply. */
2477 frame_row->used[TEXT_AREA]
2478 = window_matrix->matrix_x + window_matrix->matrix_w;
2480 /* Next row. */
2481 ++window_y;
2482 ++frame_y;
2486 /* Given a user-specified glyph, possibly including a Lisp-level face
2487 ID, return a glyph that has a realized face ID.
2488 This is used for glyphs displayed specially and not part of the text;
2489 for instance, vertical separators, truncation markers, etc. */
2491 void
2492 spec_glyph_lookup_face (struct window *w, GLYPH *glyph)
2494 int lface_id = GLYPH_FACE (*glyph);
2495 /* Convert the glyph's specified face to a realized (cache) face. */
2496 if (lface_id > 0)
2498 int face_id = merge_faces (XFRAME (w->frame),
2499 Qt, lface_id, DEFAULT_FACE_ID);
2500 SET_GLYPH_FACE (*glyph, face_id);
2504 /* Add spaces to a glyph row ROW in a window matrix.
2506 Each row has the form:
2508 +---------+-----------------------------+------------+
2509 | left | text | right |
2510 +---------+-----------------------------+------------+
2512 Left and right marginal areas are optional. This function adds
2513 spaces to areas so that there are no empty holes between areas.
2514 In other words: If the right area is not empty, the text area
2515 is filled up with spaces up to the right area. If the text area
2516 is not empty, the left area is filled up.
2518 To be called for frame-based redisplay, only. */
2520 static void
2521 fill_up_glyph_row_with_spaces (struct glyph_row *row)
2523 fill_up_glyph_row_area_with_spaces (row, LEFT_MARGIN_AREA);
2524 fill_up_glyph_row_area_with_spaces (row, TEXT_AREA);
2525 fill_up_glyph_row_area_with_spaces (row, RIGHT_MARGIN_AREA);
2529 /* Fill area AREA of glyph row ROW with spaces. To be called for
2530 frame-based redisplay only. */
2532 static void
2533 fill_up_glyph_row_area_with_spaces (struct glyph_row *row, int area)
2535 if (row->glyphs[area] < row->glyphs[area + 1])
2537 struct glyph *end = row->glyphs[area + 1];
2538 struct glyph *text = row->glyphs[area] + row->used[area];
2540 while (text < end)
2541 *text++ = space_glyph;
2542 row->used[area] = text - row->glyphs[area];
2547 /* Add spaces to the end of ROW in a frame matrix until index UPTO is
2548 reached. In frame matrices only one area, TEXT_AREA, is used. */
2550 static void
2551 fill_up_frame_row_with_spaces (struct glyph_row *row, int upto)
2553 int i = row->used[TEXT_AREA];
2554 struct glyph *glyph = row->glyphs[TEXT_AREA];
2556 while (i < upto)
2557 glyph[i++] = space_glyph;
2559 row->used[TEXT_AREA] = i;
2564 /**********************************************************************
2565 Mirroring operations on frame matrices in window matrices
2566 **********************************************************************/
2568 /* Set frame being updated via frame-based redisplay to F. This
2569 function must be called before updates to make explicit that we are
2570 working on frame matrices or not. */
2572 static void
2573 set_frame_matrix_frame (struct frame *f)
2575 frame_matrix_frame = f;
2579 /* Make sure glyph row ROW in CURRENT_MATRIX is up to date.
2580 DESIRED_MATRIX is the desired matrix corresponding to
2581 CURRENT_MATRIX. The update is done by exchanging glyph pointers
2582 between rows in CURRENT_MATRIX and DESIRED_MATRIX. If
2583 frame_matrix_frame is non-null, this indicates that the exchange is
2584 done in frame matrices, and that we have to perform analogous
2585 operations in window matrices of frame_matrix_frame. */
2587 static void
2588 make_current (struct glyph_matrix *desired_matrix, struct glyph_matrix *current_matrix, int row)
2590 struct glyph_row *current_row = MATRIX_ROW (current_matrix, row);
2591 struct glyph_row *desired_row = MATRIX_ROW (desired_matrix, row);
2592 bool mouse_face_p = current_row->mouse_face_p;
2594 /* Do current_row = desired_row. This exchanges glyph pointers
2595 between both rows, and does a structure assignment otherwise. */
2596 assign_row (current_row, desired_row);
2598 /* Enable current_row to mark it as valid. */
2599 current_row->enabled_p = 1;
2600 current_row->mouse_face_p = mouse_face_p;
2602 /* If we are called on frame matrices, perform analogous operations
2603 for window matrices. */
2604 if (frame_matrix_frame)
2605 mirror_make_current (XWINDOW (frame_matrix_frame->root_window), row);
2609 /* W is the root of a window tree. FRAME_ROW is the index of a row in
2610 W's frame which has been made current (by swapping pointers between
2611 current and desired matrix). Perform analogous operations in the
2612 matrices of leaf windows in the window tree rooted at W. */
2614 static void
2615 mirror_make_current (struct window *w, int frame_row)
2617 while (w)
2619 if (WINDOWP (w->contents))
2620 mirror_make_current (XWINDOW (w->contents), frame_row);
2621 else
2623 /* Row relative to window W. Don't use FRAME_TO_WINDOW_VPOS
2624 here because the checks performed in debug mode there
2625 will not allow the conversion. */
2626 int row = frame_row - w->desired_matrix->matrix_y;
2628 /* If FRAME_ROW is within W, assign the desired row to the
2629 current row (exchanging glyph pointers). */
2630 if (row >= 0 && row < w->desired_matrix->matrix_h)
2632 struct glyph_row *current_row
2633 = MATRIX_ROW (w->current_matrix, row);
2634 struct glyph_row *desired_row
2635 = MATRIX_ROW (w->desired_matrix, row);
2637 if (desired_row->enabled_p)
2638 assign_row (current_row, desired_row);
2639 else
2640 swap_glyph_pointers (desired_row, current_row);
2641 current_row->enabled_p = 1;
2643 /* Set the Y coordinate of the mode/header line's row.
2644 It is needed in draw_row_with_mouse_face to find the
2645 screen coordinates. (Window-based redisplay sets
2646 this in update_window, but no one seems to do that
2647 for frame-based redisplay.) */
2648 if (current_row->mode_line_p)
2649 current_row->y = row;
2653 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2658 /* Perform row dance after scrolling. We are working on the range of
2659 lines UNCHANGED_AT_TOP + 1 to UNCHANGED_AT_TOP + NLINES (not
2660 including) in MATRIX. COPY_FROM is a vector containing, for each
2661 row I in the range 0 <= I < NLINES, the index of the original line
2662 to move to I. This index is relative to the row range, i.e. 0 <=
2663 index < NLINES. RETAINED_P is a vector containing zero for each
2664 row 0 <= I < NLINES which is empty.
2666 This function is called from do_scrolling and do_direct_scrolling. */
2668 void
2669 mirrored_line_dance (struct glyph_matrix *matrix, int unchanged_at_top, int nlines,
2670 int *copy_from, char *retained_p)
2672 /* A copy of original rows. */
2673 struct glyph_row *old_rows;
2675 /* Rows to assign to. */
2676 struct glyph_row *new_rows = MATRIX_ROW (matrix, unchanged_at_top);
2678 int i;
2680 /* Make a copy of the original rows. */
2681 old_rows = alloca (nlines * sizeof *old_rows);
2682 memcpy (old_rows, new_rows, nlines * sizeof *old_rows);
2684 /* Assign new rows, maybe clear lines. */
2685 for (i = 0; i < nlines; ++i)
2687 bool enabled_before_p = new_rows[i].enabled_p;
2689 eassert (i + unchanged_at_top < matrix->nrows);
2690 eassert (unchanged_at_top + copy_from[i] < matrix->nrows);
2691 new_rows[i] = old_rows[copy_from[i]];
2692 new_rows[i].enabled_p = enabled_before_p;
2694 /* RETAINED_P is zero for empty lines. */
2695 if (!retained_p[copy_from[i]])
2696 new_rows[i].enabled_p = 0;
2699 /* Do the same for window matrices, if MATRIX is a frame matrix. */
2700 if (frame_matrix_frame)
2701 mirror_line_dance (XWINDOW (frame_matrix_frame->root_window),
2702 unchanged_at_top, nlines, copy_from, retained_p);
2706 /* Synchronize glyph pointers in the current matrix of window W with
2707 the current frame matrix. */
2709 static void
2710 sync_window_with_frame_matrix_rows (struct window *w)
2712 struct frame *f = XFRAME (w->frame);
2713 struct glyph_row *window_row, *window_row_end, *frame_row;
2714 int left, right, x, width;
2716 /* Preconditions: W must be a live window on a tty frame. */
2717 eassert (BUFFERP (w->contents));
2718 eassert (!FRAME_WINDOW_P (f));
2720 left = margin_glyphs_to_reserve (w, 1, w->left_margin_cols);
2721 right = margin_glyphs_to_reserve (w, 1, w->right_margin_cols);
2722 x = w->current_matrix->matrix_x;
2723 width = w->current_matrix->matrix_w;
2725 window_row = w->current_matrix->rows;
2726 window_row_end = window_row + w->current_matrix->nrows;
2727 frame_row = f->current_matrix->rows + WINDOW_TOP_EDGE_LINE (w);
2729 for (; window_row < window_row_end; ++window_row, ++frame_row)
2731 window_row->glyphs[LEFT_MARGIN_AREA]
2732 = frame_row->glyphs[0] + x;
2733 window_row->glyphs[TEXT_AREA]
2734 = window_row->glyphs[LEFT_MARGIN_AREA] + left;
2735 window_row->glyphs[LAST_AREA]
2736 = window_row->glyphs[LEFT_MARGIN_AREA] + width;
2737 window_row->glyphs[RIGHT_MARGIN_AREA]
2738 = window_row->glyphs[LAST_AREA] - right;
2743 /* Return the window in the window tree rooted in W containing frame
2744 row ROW. Value is null if none is found. */
2746 static struct window *
2747 frame_row_to_window (struct window *w, int row)
2749 struct window *found = NULL;
2751 while (w && !found)
2753 if (WINDOWP (w->contents))
2754 found = frame_row_to_window (XWINDOW (w->contents), row);
2755 else if (row >= WINDOW_TOP_EDGE_LINE (w)
2756 && row < WINDOW_BOTTOM_EDGE_LINE (w))
2757 found = w;
2759 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2762 return found;
2766 /* Perform a line dance in the window tree rooted at W, after
2767 scrolling a frame matrix in mirrored_line_dance.
2769 We are working on the range of lines UNCHANGED_AT_TOP + 1 to
2770 UNCHANGED_AT_TOP + NLINES (not including) in W's frame matrix.
2771 COPY_FROM is a vector containing, for each row I in the range 0 <=
2772 I < NLINES, the index of the original line to move to I. This
2773 index is relative to the row range, i.e. 0 <= index < NLINES.
2774 RETAINED_P is a vector containing zero for each row 0 <= I < NLINES
2775 which is empty. */
2777 static void
2778 mirror_line_dance (struct window *w, int unchanged_at_top, int nlines, int *copy_from, char *retained_p)
2780 while (w)
2782 if (WINDOWP (w->contents))
2783 mirror_line_dance (XWINDOW (w->contents), unchanged_at_top,
2784 nlines, copy_from, retained_p);
2785 else
2787 /* W is a leaf window, and we are working on its current
2788 matrix m. */
2789 struct glyph_matrix *m = w->current_matrix;
2790 int i;
2791 bool sync_p = 0;
2792 struct glyph_row *old_rows;
2794 /* Make a copy of the original rows of matrix m. */
2795 old_rows = alloca (m->nrows * sizeof *old_rows);
2796 memcpy (old_rows, m->rows, m->nrows * sizeof *old_rows);
2798 for (i = 0; i < nlines; ++i)
2800 /* Frame relative line assigned to. */
2801 int frame_to = i + unchanged_at_top;
2803 /* Frame relative line assigned. */
2804 int frame_from = copy_from[i] + unchanged_at_top;
2806 /* Window relative line assigned to. */
2807 int window_to = frame_to - m->matrix_y;
2809 /* Window relative line assigned. */
2810 int window_from = frame_from - m->matrix_y;
2812 /* Is assigned line inside window? */
2813 bool from_inside_window_p
2814 = window_from >= 0 && window_from < m->matrix_h;
2816 /* Is assigned to line inside window? */
2817 bool to_inside_window_p
2818 = window_to >= 0 && window_to < m->matrix_h;
2820 if (from_inside_window_p && to_inside_window_p)
2822 /* Do the assignment. The enabled_p flag is saved
2823 over the assignment because the old redisplay did
2824 that. */
2825 bool enabled_before_p = m->rows[window_to].enabled_p;
2826 m->rows[window_to] = old_rows[window_from];
2827 m->rows[window_to].enabled_p = enabled_before_p;
2829 /* If frame line is empty, window line is empty, too. */
2830 if (!retained_p[copy_from[i]])
2831 m->rows[window_to].enabled_p = 0;
2833 else if (to_inside_window_p)
2835 /* A copy between windows. This is an infrequent
2836 case not worth optimizing. */
2837 struct frame *f = XFRAME (w->frame);
2838 struct window *root = XWINDOW (FRAME_ROOT_WINDOW (f));
2839 struct window *w2;
2840 struct glyph_matrix *m2;
2841 int m2_from;
2843 w2 = frame_row_to_window (root, frame_from);
2844 /* ttn@surf.glug.org: when enabling menu bar using `emacs
2845 -nw', FROM_FRAME sometimes has no associated window.
2846 This check avoids a segfault if W2 is null. */
2847 if (w2)
2849 m2 = w2->current_matrix;
2850 m2_from = frame_from - m2->matrix_y;
2851 copy_row_except_pointers (m->rows + window_to,
2852 m2->rows + m2_from);
2854 /* If frame line is empty, window line is empty, too. */
2855 if (!retained_p[copy_from[i]])
2856 m->rows[window_to].enabled_p = 0;
2858 sync_p = 1;
2860 else if (from_inside_window_p)
2861 sync_p = 1;
2864 /* If there was a copy between windows, make sure glyph
2865 pointers are in sync with the frame matrix. */
2866 if (sync_p)
2867 sync_window_with_frame_matrix_rows (w);
2869 /* Check that no pointers are lost. */
2870 CHECK_MATRIX (m);
2873 /* Next window on same level. */
2874 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2879 #ifdef GLYPH_DEBUG
2881 /* Check that window and frame matrices agree about their
2882 understanding where glyphs of the rows are to find. For each
2883 window in the window tree rooted at W, check that rows in the
2884 matrices of leaf window agree with their frame matrices about
2885 glyph pointers. */
2887 static void
2888 check_window_matrix_pointers (struct window *w)
2890 while (w)
2892 if (WINDOWP (w->contents))
2893 check_window_matrix_pointers (XWINDOW (w->contents));
2894 else
2896 struct frame *f = XFRAME (w->frame);
2897 check_matrix_pointers (w->desired_matrix, f->desired_matrix);
2898 check_matrix_pointers (w->current_matrix, f->current_matrix);
2901 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2906 /* Check that window rows are slices of frame rows. WINDOW_MATRIX is
2907 a window and FRAME_MATRIX is the corresponding frame matrix. For
2908 each row in WINDOW_MATRIX check that it's a slice of the
2909 corresponding frame row. If it isn't, abort. */
2911 static void
2912 check_matrix_pointers (struct glyph_matrix *window_matrix,
2913 struct glyph_matrix *frame_matrix)
2915 /* Row number in WINDOW_MATRIX. */
2916 int i = 0;
2918 /* Row number corresponding to I in FRAME_MATRIX. */
2919 int j = window_matrix->matrix_y;
2921 /* For all rows check that the row in the window matrix is a
2922 slice of the row in the frame matrix. If it isn't we didn't
2923 mirror an operation on the frame matrix correctly. */
2924 while (i < window_matrix->nrows)
2926 if (!glyph_row_slice_p (window_matrix->rows + i,
2927 frame_matrix->rows + j))
2928 emacs_abort ();
2929 ++i, ++j;
2933 #endif /* GLYPH_DEBUG */
2937 /**********************************************************************
2938 VPOS and HPOS translations
2939 **********************************************************************/
2941 #ifdef GLYPH_DEBUG
2943 /* Translate vertical position VPOS which is relative to window W to a
2944 vertical position relative to W's frame. */
2946 static int
2947 window_to_frame_vpos (struct window *w, int vpos)
2949 eassert (!FRAME_WINDOW_P (XFRAME (w->frame)));
2950 eassert (vpos >= 0 && vpos <= w->desired_matrix->nrows);
2951 vpos += WINDOW_TOP_EDGE_LINE (w);
2952 eassert (vpos >= 0 && vpos <= FRAME_LINES (XFRAME (w->frame)));
2953 return vpos;
2957 /* Translate horizontal position HPOS which is relative to window W to
2958 a horizontal position relative to W's frame. */
2960 static int
2961 window_to_frame_hpos (struct window *w, int hpos)
2963 eassert (!FRAME_WINDOW_P (XFRAME (w->frame)));
2964 hpos += WINDOW_LEFT_EDGE_COL (w);
2965 return hpos;
2968 #endif /* GLYPH_DEBUG */
2972 /**********************************************************************
2973 Redrawing Frames
2974 **********************************************************************/
2976 /* Redraw frame F. */
2978 void
2979 redraw_frame (struct frame *f)
2981 /* Error if F has no glyphs. */
2982 eassert (f->glyphs_initialized_p);
2983 update_begin (f);
2984 #ifdef MSDOS
2985 if (FRAME_MSDOS_P (f))
2986 FRAME_TERMINAL (f)->set_terminal_modes_hook (FRAME_TERMINAL (f));
2987 #endif
2988 clear_frame (f);
2989 clear_current_matrices (f);
2990 update_end (f);
2991 if (FRAME_TERMCAP_P (f))
2992 fflush (FRAME_TTY (f)->output);
2993 windows_or_buffers_changed++;
2994 /* Mark all windows as inaccurate, so that every window will have
2995 its redisplay done. */
2996 mark_window_display_accurate (FRAME_ROOT_WINDOW (f), 0);
2997 set_window_update_flags (XWINDOW (FRAME_ROOT_WINDOW (f)), 1);
2998 f->garbaged = 0;
3001 DEFUN ("redraw-frame", Fredraw_frame, Sredraw_frame, 0, 1, 0,
3002 doc: /* Clear frame FRAME and output again what is supposed to appear on it.
3003 If FRAME is omitted or nil, the selected frame is used. */)
3004 (Lisp_Object frame)
3006 redraw_frame (decode_live_frame (frame));
3007 return Qnil;
3010 DEFUN ("redraw-display", Fredraw_display, Sredraw_display, 0, 0, "",
3011 doc: /* Clear and redisplay all visible frames. */)
3012 (void)
3014 Lisp_Object tail, frame;
3016 FOR_EACH_FRAME (tail, frame)
3017 if (FRAME_VISIBLE_P (XFRAME (frame)))
3018 redraw_frame (XFRAME (frame));
3020 return Qnil;
3025 /***********************************************************************
3026 Frame Update
3027 ***********************************************************************/
3029 /* Update frame F based on the data in desired matrices.
3031 If FORCE_P, don't let redisplay be stopped by detecting pending input.
3032 If INHIBIT_HAIRY_ID_P, don't try scrolling.
3034 Value is true if redisplay was stopped due to pending input. */
3036 bool
3037 update_frame (struct frame *f, bool force_p, bool inhibit_hairy_id_p)
3039 /* True means display has been paused because of pending input. */
3040 bool paused_p;
3041 struct window *root_window = XWINDOW (f->root_window);
3043 if (redisplay_dont_pause)
3044 force_p = 1;
3045 else if (!force_p && detect_input_pending_ignore_squeezables ())
3047 paused_p = 1;
3048 goto do_pause;
3051 if (FRAME_WINDOW_P (f))
3053 /* We are working on window matrix basis. All windows whose
3054 flag must_be_updated_p is set have to be updated. */
3056 /* Record that we are not working on frame matrices. */
3057 set_frame_matrix_frame (NULL);
3059 /* Update all windows in the window tree of F, maybe stopping
3060 when pending input is detected. */
3061 update_begin (f);
3063 #if defined (HAVE_X_WINDOWS) && ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
3064 /* Update the menu bar on X frames that don't have toolkit
3065 support. */
3066 if (WINDOWP (f->menu_bar_window))
3067 update_window (XWINDOW (f->menu_bar_window), 1);
3068 #endif
3070 /* Update the tool-bar window, if present. */
3071 if (WINDOWP (f->tool_bar_window))
3073 struct window *w = XWINDOW (f->tool_bar_window);
3075 /* Update tool-bar window. */
3076 if (w->must_be_updated_p)
3078 Lisp_Object tem;
3080 update_window (w, 1);
3081 w->must_be_updated_p = 0;
3083 /* Swap tool-bar strings. We swap because we want to
3084 reuse strings. */
3085 tem = f->current_tool_bar_string;
3086 fset_current_tool_bar_string (f, f->desired_tool_bar_string);
3087 fset_desired_tool_bar_string (f, tem);
3092 /* Update windows. */
3093 paused_p = update_window_tree (root_window, force_p);
3094 update_end (f);
3096 /* This flush is a performance bottleneck under X,
3097 and it doesn't seem to be necessary anyway (in general).
3098 It is necessary when resizing the window with the mouse, or
3099 at least the fringes are not redrawn in a timely manner. ++kfs */
3100 if (f->force_flush_display_p)
3102 FRAME_RIF (f)->flush_display (f);
3103 f->force_flush_display_p = 0;
3106 else
3108 /* We are working on frame matrix basis. Set the frame on whose
3109 frame matrix we operate. */
3110 set_frame_matrix_frame (f);
3112 /* Build F's desired matrix from window matrices. */
3113 build_frame_matrix (f);
3115 /* Update the display */
3116 update_begin (f);
3117 paused_p = update_frame_1 (f, force_p, inhibit_hairy_id_p);
3118 update_end (f);
3120 if (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f))
3122 if (FRAME_TTY (f)->termscript)
3123 fflush (FRAME_TTY (f)->termscript);
3124 if (FRAME_TERMCAP_P (f))
3125 fflush (FRAME_TTY (f)->output);
3128 /* Check window matrices for lost pointers. */
3129 #ifdef GLYPH_DEBUG
3130 check_window_matrix_pointers (root_window);
3131 add_frame_display_history (f, paused_p);
3132 #endif
3135 do_pause:
3136 /* Reset flags indicating that a window should be updated. */
3137 set_window_update_flags (root_window, 0);
3139 display_completed = !paused_p;
3140 return paused_p;
3145 /************************************************************************
3146 Window-based updates
3147 ************************************************************************/
3149 /* Perform updates in window tree rooted at W.
3150 If FORCE_P, don't stop updating if input is pending. */
3152 static bool
3153 update_window_tree (struct window *w, bool force_p)
3155 bool paused_p = 0;
3157 while (w && !paused_p)
3159 if (WINDOWP (w->contents))
3160 paused_p |= update_window_tree (XWINDOW (w->contents), force_p);
3161 else if (w->must_be_updated_p)
3162 paused_p |= update_window (w, force_p);
3164 w = NILP (w->next) ? 0 : XWINDOW (w->next);
3167 return paused_p;
3171 /* Update window W if its flag must_be_updated_p is set.
3172 If FORCE_P, don't stop updating if input is pending. */
3174 void
3175 update_single_window (struct window *w, bool force_p)
3177 if (w->must_be_updated_p)
3179 struct frame *f = XFRAME (WINDOW_FRAME (w));
3181 /* Record that this is not a frame-based redisplay. */
3182 set_frame_matrix_frame (NULL);
3184 if (redisplay_dont_pause)
3185 force_p = 1;
3187 /* Update W. */
3188 update_begin (f);
3189 update_window (w, force_p);
3190 update_end (f);
3192 /* Reset flag in W. */
3193 w->must_be_updated_p = 0;
3197 #ifdef HAVE_WINDOW_SYSTEM
3199 /* Redraw lines from the current matrix of window W that are
3200 overlapped by other rows. YB is bottom-most y-position in W. */
3202 static void
3203 redraw_overlapped_rows (struct window *w, int yb)
3205 int i;
3206 struct frame *f = XFRAME (WINDOW_FRAME (w));
3208 /* If rows overlapping others have been changed, the rows being
3209 overlapped have to be redrawn. This won't draw lines that have
3210 already been drawn in update_window_line because overlapped_p in
3211 desired rows is 0, so after row assignment overlapped_p in
3212 current rows is 0. */
3213 for (i = 0; i < w->current_matrix->nrows; ++i)
3215 struct glyph_row *row = w->current_matrix->rows + i;
3217 if (!row->enabled_p)
3218 break;
3219 else if (row->mode_line_p)
3220 continue;
3222 if (row->overlapped_p)
3224 enum glyph_row_area area;
3226 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
3228 FRAME_RIF (f)->cursor_to (w, i, 0, row->y,
3229 area == TEXT_AREA ? row->x : 0);
3230 if (row->used[area])
3231 FRAME_RIF (f)->write_glyphs (w, row, row->glyphs[area],
3232 area, row->used[area]);
3233 FRAME_RIF (f)->clear_end_of_line (w, row, area, -1);
3236 row->overlapped_p = 0;
3239 if (MATRIX_ROW_BOTTOM_Y (row) >= yb)
3240 break;
3245 /* Redraw lines from the current matrix of window W that overlap
3246 others. YB is bottom-most y-position in W. */
3248 static void
3249 redraw_overlapping_rows (struct window *w, int yb)
3251 int i, bottom_y;
3252 struct glyph_row *row;
3253 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3255 for (i = 0; i < w->current_matrix->nrows; ++i)
3257 row = w->current_matrix->rows + i;
3259 if (!row->enabled_p)
3260 break;
3261 else if (row->mode_line_p)
3262 continue;
3264 bottom_y = MATRIX_ROW_BOTTOM_Y (row);
3266 if (row->overlapping_p)
3268 int overlaps = 0;
3270 if (MATRIX_ROW_OVERLAPS_PRED_P (row) && i > 0
3271 && !MATRIX_ROW (w->current_matrix, i - 1)->overlapped_p)
3272 overlaps |= OVERLAPS_PRED;
3273 if (MATRIX_ROW_OVERLAPS_SUCC_P (row) && bottom_y < yb
3274 && !MATRIX_ROW (w->current_matrix, i + 1)->overlapped_p)
3275 overlaps |= OVERLAPS_SUCC;
3277 if (overlaps)
3279 if (row->used[LEFT_MARGIN_AREA])
3280 rif->fix_overlapping_area (w, row, LEFT_MARGIN_AREA, overlaps);
3282 if (row->used[TEXT_AREA])
3283 rif->fix_overlapping_area (w, row, TEXT_AREA, overlaps);
3285 if (row->used[RIGHT_MARGIN_AREA])
3286 rif->fix_overlapping_area (w, row, RIGHT_MARGIN_AREA, overlaps);
3288 /* Record in neighbor rows that ROW overwrites part of
3289 their display. */
3290 if (overlaps & OVERLAPS_PRED)
3291 MATRIX_ROW (w->current_matrix, i - 1)->overlapped_p = 1;
3292 if (overlaps & OVERLAPS_SUCC)
3293 MATRIX_ROW (w->current_matrix, i + 1)->overlapped_p = 1;
3297 if (bottom_y >= yb)
3298 break;
3302 #endif /* HAVE_WINDOW_SYSTEM */
3305 #if defined GLYPH_DEBUG && 0
3307 /* Check that no row in the current matrix of window W is enabled
3308 which is below what's displayed in the window. */
3310 static void
3311 check_current_matrix_flags (struct window *w)
3313 bool last_seen_p = 0;
3314 int i, yb = window_text_bottom_y (w);
3316 for (i = 0; i < w->current_matrix->nrows - 1; ++i)
3318 struct glyph_row *row = MATRIX_ROW (w->current_matrix, i);
3319 if (!last_seen_p && MATRIX_ROW_BOTTOM_Y (row) >= yb)
3320 last_seen_p = 1;
3321 else if (last_seen_p && row->enabled_p)
3322 emacs_abort ();
3326 #endif /* GLYPH_DEBUG */
3329 /* Update display of window W.
3330 If FORCE_P, don't stop updating when input is pending. */
3332 static bool
3333 update_window (struct window *w, bool force_p)
3335 struct glyph_matrix *desired_matrix = w->desired_matrix;
3336 bool paused_p;
3337 int preempt_count = baud_rate / 2400 + 1;
3338 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3339 #ifdef GLYPH_DEBUG
3340 /* Check that W's frame doesn't have glyph matrices. */
3341 eassert (FRAME_WINDOW_P (XFRAME (WINDOW_FRAME (w))));
3342 #endif
3344 /* Check pending input the first time so that we can quickly return. */
3345 if (!force_p)
3346 detect_input_pending_ignore_squeezables ();
3348 /* If forced to complete the update, or if no input is pending, do
3349 the update. */
3350 if (force_p || !input_pending || !NILP (do_mouse_tracking))
3352 struct glyph_row *row, *end;
3353 struct glyph_row *mode_line_row;
3354 struct glyph_row *header_line_row;
3355 int yb;
3356 bool changed_p = 0, mouse_face_overwritten_p = 0;
3357 int n_updated = 0;
3359 rif->update_window_begin_hook (w);
3360 yb = window_text_bottom_y (w);
3361 row = MATRIX_ROW (desired_matrix, 0);
3362 end = MATRIX_MODE_LINE_ROW (desired_matrix);
3364 /* Take note of the header line, if there is one. We will
3365 update it below, after updating all of the window's lines. */
3366 if (row->mode_line_p)
3368 header_line_row = row;
3369 ++row;
3371 else
3372 header_line_row = NULL;
3374 /* Update the mode line, if necessary. */
3375 mode_line_row = MATRIX_MODE_LINE_ROW (desired_matrix);
3376 if (mode_line_row->mode_line_p && mode_line_row->enabled_p)
3378 mode_line_row->y = yb;
3379 update_window_line (w, MATRIX_ROW_VPOS (mode_line_row,
3380 desired_matrix),
3381 &mouse_face_overwritten_p);
3384 /* Find first enabled row. Optimizations in redisplay_internal
3385 may lead to an update with only one row enabled. There may
3386 be also completely empty matrices. */
3387 while (row < end && !row->enabled_p)
3388 ++row;
3390 /* Try reusing part of the display by copying. */
3391 if (row < end && !desired_matrix->no_scrolling_p)
3393 int rc = scrolling_window (w, header_line_row != NULL);
3394 if (rc < 0)
3396 /* All rows were found to be equal. */
3397 paused_p = 0;
3398 goto set_cursor;
3400 else if (rc > 0)
3402 /* We've scrolled the display. */
3403 force_p = 1;
3404 changed_p = 1;
3408 /* Update the rest of the lines. */
3409 for (; row < end && (force_p || !input_pending); ++row)
3410 /* scrolling_window resets the enabled_p flag of the rows it
3411 reuses from current_matrix. */
3412 if (row->enabled_p)
3414 int vpos = MATRIX_ROW_VPOS (row, desired_matrix);
3415 int i;
3417 /* We'll have to play a little bit with when to
3418 detect_input_pending. If it's done too often,
3419 scrolling large windows with repeated scroll-up
3420 commands will too quickly pause redisplay. */
3421 if (!force_p && ++n_updated % preempt_count == 0)
3422 detect_input_pending_ignore_squeezables ();
3423 changed_p |= update_window_line (w, vpos,
3424 &mouse_face_overwritten_p);
3426 /* Mark all rows below the last visible one in the current
3427 matrix as invalid. This is necessary because of
3428 variable line heights. Consider the case of three
3429 successive redisplays, where the first displays 5
3430 lines, the second 3 lines, and the third 5 lines again.
3431 If the second redisplay wouldn't mark rows in the
3432 current matrix invalid, the third redisplay might be
3433 tempted to optimize redisplay based on lines displayed
3434 in the first redisplay. */
3435 if (MATRIX_ROW_BOTTOM_Y (row) >= yb)
3436 for (i = vpos + 1; i < w->current_matrix->nrows - 1; ++i)
3437 MATRIX_ROW (w->current_matrix, i)->enabled_p = 0;
3440 /* Was display preempted? */
3441 paused_p = row < end;
3443 set_cursor:
3445 /* Update the header line after scrolling because a new header
3446 line would otherwise overwrite lines at the top of the window
3447 that can be scrolled. */
3448 if (header_line_row && header_line_row->enabled_p)
3450 header_line_row->y = 0;
3451 update_window_line (w, 0, &mouse_face_overwritten_p);
3454 /* Fix the appearance of overlapping/overlapped rows. */
3455 if (!paused_p && !w->pseudo_window_p)
3457 #ifdef HAVE_WINDOW_SYSTEM
3458 if (changed_p && rif->fix_overlapping_area)
3460 redraw_overlapped_rows (w, yb);
3461 redraw_overlapping_rows (w, yb);
3463 #endif
3465 /* Make cursor visible at cursor position of W. */
3466 set_window_cursor_after_update (w);
3468 #if 0 /* Check that current matrix invariants are satisfied. This is
3469 for debugging only. See the comment of check_matrix_invariants. */
3470 IF_DEBUG (check_matrix_invariants (w));
3471 #endif
3474 #ifdef GLYPH_DEBUG
3475 /* Remember the redisplay method used to display the matrix. */
3476 strcpy (w->current_matrix->method, w->desired_matrix->method);
3477 #endif
3479 #ifdef HAVE_WINDOW_SYSTEM
3480 update_window_fringes (w, 0);
3481 #endif
3483 /* End the update of window W. Don't set the cursor if we
3484 paused updating the display because in this case,
3485 set_window_cursor_after_update hasn't been called, and
3486 output_cursor doesn't contain the cursor location. */
3487 rif->update_window_end_hook (w, !paused_p, mouse_face_overwritten_p);
3489 else
3490 paused_p = 1;
3492 #ifdef GLYPH_DEBUG
3493 /* check_current_matrix_flags (w); */
3494 add_window_display_history (w, w->current_matrix->method, paused_p);
3495 #endif
3497 clear_glyph_matrix (desired_matrix);
3499 return paused_p;
3503 /* Update the display of area AREA in window W, row number VPOS.
3504 AREA can be either LEFT_MARGIN_AREA or RIGHT_MARGIN_AREA. */
3506 static void
3507 update_marginal_area (struct window *w, struct glyph_row *updated_row,
3508 enum glyph_row_area area, int vpos)
3510 struct glyph_row *desired_row = MATRIX_ROW (w->desired_matrix, vpos);
3511 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3513 /* Set cursor to start of glyphs, write them, and clear to the end
3514 of the area. I don't think that something more sophisticated is
3515 necessary here, since marginal areas will not be the default. */
3516 rif->cursor_to (w, vpos, 0, desired_row->y, 0);
3517 if (desired_row->used[area])
3518 rif->write_glyphs (w, updated_row, desired_row->glyphs[area],
3519 area, desired_row->used[area]);
3520 rif->clear_end_of_line (w, updated_row, area, -1);
3524 /* Update the display of the text area of row VPOS in window W.
3525 Value is true if display has changed. */
3527 static bool
3528 update_text_area (struct window *w, struct glyph_row *updated_row, int vpos)
3530 struct glyph_row *current_row = MATRIX_ROW (w->current_matrix, vpos);
3531 struct glyph_row *desired_row = MATRIX_ROW (w->desired_matrix, vpos);
3532 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3533 bool changed_p = 0;
3535 /* If rows are at different X or Y, or rows have different height,
3536 or the current row is marked invalid, write the entire line. */
3537 if (!current_row->enabled_p
3538 || desired_row->y != current_row->y
3539 || desired_row->ascent != current_row->ascent
3540 || desired_row->phys_ascent != current_row->phys_ascent
3541 || desired_row->phys_height != current_row->phys_height
3542 || desired_row->visible_height != current_row->visible_height
3543 || current_row->overlapped_p
3544 /* This next line is necessary for correctly redrawing
3545 mouse-face areas after scrolling and other operations.
3546 However, it causes excessive flickering when mouse is moved
3547 across the mode line. Luckily, turning it off for the mode
3548 line doesn't seem to hurt anything. -- cyd.
3549 But it is still needed for the header line. -- kfs. */
3550 || (current_row->mouse_face_p
3551 && !(current_row->mode_line_p && vpos > 0))
3552 || current_row->x != desired_row->x)
3554 rif->cursor_to (w, vpos, 0, desired_row->y, desired_row->x);
3556 if (desired_row->used[TEXT_AREA])
3557 rif->write_glyphs (w, updated_row, desired_row->glyphs[TEXT_AREA],
3558 TEXT_AREA, desired_row->used[TEXT_AREA]);
3560 /* Clear to end of window. */
3561 rif->clear_end_of_line (w, updated_row, TEXT_AREA, -1);
3562 changed_p = 1;
3564 /* This erases the cursor. We do this here because
3565 notice_overwritten_cursor cannot easily check this, which
3566 might indicate that the whole functionality of
3567 notice_overwritten_cursor would better be implemented here.
3568 On the other hand, we need notice_overwritten_cursor as long
3569 as mouse highlighting is done asynchronously outside of
3570 redisplay. */
3571 if (vpos == w->phys_cursor.vpos)
3572 w->phys_cursor_on_p = 0;
3574 else
3576 int stop, i, x;
3577 struct glyph *current_glyph = current_row->glyphs[TEXT_AREA];
3578 struct glyph *desired_glyph = desired_row->glyphs[TEXT_AREA];
3579 bool overlapping_glyphs_p = current_row->contains_overlapping_glyphs_p;
3580 int desired_stop_pos = desired_row->used[TEXT_AREA];
3581 bool abort_skipping = 0;
3583 /* If the desired row extends its face to the text area end, and
3584 unless the current row also does so at the same position,
3585 make sure we write at least one glyph, so that the face
3586 extension actually takes place. */
3587 if (MATRIX_ROW_EXTENDS_FACE_P (desired_row)
3588 && (desired_stop_pos < current_row->used[TEXT_AREA]
3589 || (desired_stop_pos == current_row->used[TEXT_AREA]
3590 && !MATRIX_ROW_EXTENDS_FACE_P (current_row))))
3591 --desired_stop_pos;
3593 stop = min (current_row->used[TEXT_AREA], desired_stop_pos);
3594 i = 0;
3595 x = desired_row->x;
3597 /* Loop over glyphs that current and desired row may have
3598 in common. */
3599 while (i < stop)
3601 bool can_skip_p = !abort_skipping;
3603 /* Skip over glyphs that both rows have in common. These
3604 don't have to be written. We can't skip if the last
3605 current glyph overlaps the glyph to its right. For
3606 example, consider a current row of `if ' with the `f' in
3607 Courier bold so that it overlaps the ` ' to its right.
3608 If the desired row is ` ', we would skip over the space
3609 after the `if' and there would remain a pixel from the
3610 `f' on the screen. */
3611 if (overlapping_glyphs_p && i > 0)
3613 struct glyph *glyph = &current_row->glyphs[TEXT_AREA][i - 1];
3614 int left, right;
3616 rif->get_glyph_overhangs (glyph, XFRAME (w->frame),
3617 &left, &right);
3618 can_skip_p = (right == 0 && !abort_skipping);
3621 if (can_skip_p)
3623 int start_hpos = i;
3625 while (i < stop
3626 && GLYPH_EQUAL_P (desired_glyph, current_glyph))
3628 x += desired_glyph->pixel_width;
3629 ++desired_glyph, ++current_glyph, ++i;
3632 /* Consider the case that the current row contains "xxx
3633 ppp ggg" in italic Courier font, and the desired row
3634 is "xxx ggg". The character `p' has lbearing, `g'
3635 has not. The loop above will stop in front of the
3636 first `p' in the current row. If we would start
3637 writing glyphs there, we wouldn't erase the lbearing
3638 of the `p'. The rest of the lbearing problem is then
3639 taken care of by draw_glyphs. */
3640 if (overlapping_glyphs_p
3641 && i > 0
3642 && i < current_row->used[TEXT_AREA]
3643 && (current_row->used[TEXT_AREA]
3644 != desired_row->used[TEXT_AREA]))
3646 int left, right;
3648 rif->get_glyph_overhangs (current_glyph,
3649 XFRAME (w->frame),
3650 &left, &right);
3651 while (left > 0 && i > 0)
3653 --i, --desired_glyph, --current_glyph;
3654 x -= desired_glyph->pixel_width;
3655 left -= desired_glyph->pixel_width;
3658 /* Abort the skipping algorithm if we end up before
3659 our starting point, to avoid looping (bug#1070).
3660 This can happen when the lbearing is larger than
3661 the pixel width. */
3662 abort_skipping = (i < start_hpos);
3666 /* Try to avoid writing the entire rest of the desired row
3667 by looking for a resync point. This mainly prevents
3668 mode line flickering in the case the mode line is in
3669 fixed-pitch font, which it usually will be. */
3670 if (i < desired_row->used[TEXT_AREA])
3672 int start_x = x, start_hpos = i;
3673 struct glyph *start = desired_glyph;
3674 int current_x = x;
3675 bool skip_first_p = !can_skip_p;
3677 /* Find the next glyph that's equal again. */
3678 while (i < stop
3679 && (skip_first_p
3680 || !GLYPH_EQUAL_P (desired_glyph, current_glyph))
3681 && x == current_x)
3683 x += desired_glyph->pixel_width;
3684 current_x += current_glyph->pixel_width;
3685 ++desired_glyph, ++current_glyph, ++i;
3686 skip_first_p = 0;
3689 if (i == start_hpos || x != current_x)
3691 i = start_hpos;
3692 x = start_x;
3693 desired_glyph = start;
3694 break;
3697 rif->cursor_to (w, vpos, start_hpos, desired_row->y, start_x);
3698 rif->write_glyphs (w, updated_row, start,
3699 TEXT_AREA, i - start_hpos);
3700 changed_p = 1;
3704 /* Write the rest. */
3705 if (i < desired_row->used[TEXT_AREA])
3707 rif->cursor_to (w, vpos, i, desired_row->y, x);
3708 rif->write_glyphs (w, updated_row, desired_glyph,
3709 TEXT_AREA, desired_row->used[TEXT_AREA] - i);
3710 changed_p = 1;
3713 /* Maybe clear to end of line. */
3714 if (MATRIX_ROW_EXTENDS_FACE_P (desired_row))
3716 /* If new row extends to the end of the text area, nothing
3717 has to be cleared, if and only if we did a write_glyphs
3718 above. This is made sure by setting desired_stop_pos
3719 appropriately above. */
3720 eassert (i < desired_row->used[TEXT_AREA]
3721 || ((desired_row->used[TEXT_AREA]
3722 == current_row->used[TEXT_AREA])
3723 && MATRIX_ROW_EXTENDS_FACE_P (current_row)));
3725 else if (MATRIX_ROW_EXTENDS_FACE_P (current_row))
3727 /* If old row extends to the end of the text area, clear. */
3728 if (i >= desired_row->used[TEXT_AREA])
3729 rif->cursor_to (w, vpos, i, desired_row->y,
3730 desired_row->pixel_width);
3731 rif->clear_end_of_line (w, updated_row, TEXT_AREA, -1);
3732 changed_p = 1;
3734 else if (desired_row->pixel_width < current_row->pixel_width)
3736 /* Otherwise clear to the end of the old row. Everything
3737 after that position should be clear already. */
3738 int xlim;
3740 if (i >= desired_row->used[TEXT_AREA])
3741 rif->cursor_to (w, vpos, i, desired_row->y,
3742 desired_row->pixel_width);
3744 /* If cursor is displayed at the end of the line, make sure
3745 it's cleared. Nowadays we don't have a phys_cursor_glyph
3746 with which to erase the cursor (because this method
3747 doesn't work with lbearing/rbearing), so we must do it
3748 this way. */
3749 if (vpos == w->phys_cursor.vpos
3750 && (desired_row->reversed_p
3751 ? (w->phys_cursor.hpos < 0)
3752 : (w->phys_cursor.hpos >= desired_row->used[TEXT_AREA])))
3754 w->phys_cursor_on_p = 0;
3755 xlim = -1;
3757 else
3758 xlim = current_row->pixel_width;
3759 rif->clear_end_of_line (w, updated_row, TEXT_AREA, xlim);
3760 changed_p = 1;
3764 return changed_p;
3768 /* Update row VPOS in window W. Value is true if display has been changed. */
3770 static bool
3771 update_window_line (struct window *w, int vpos, bool *mouse_face_overwritten_p)
3773 struct glyph_row *current_row = MATRIX_ROW (w->current_matrix, vpos);
3774 struct glyph_row *desired_row = MATRIX_ROW (w->desired_matrix, vpos);
3775 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3776 bool changed_p = 0;
3778 /* A row can be completely invisible in case a desired matrix was
3779 built with a vscroll and then make_cursor_line_fully_visible shifts
3780 the matrix. Make sure to make such rows current anyway, since
3781 we need the correct y-position, for example, in the current matrix. */
3782 if (desired_row->mode_line_p
3783 || desired_row->visible_height > 0)
3785 eassert (desired_row->enabled_p);
3787 /* Update display of the left margin area, if there is one. */
3788 if (!desired_row->full_width_p && w->left_margin_cols > 0)
3790 changed_p = 1;
3791 update_marginal_area (w, desired_row, LEFT_MARGIN_AREA, vpos);
3792 /* Setting this flag will ensure the vertical border, if
3793 any, between this window and the one on its left will be
3794 redrawn. This is necessary because updating the left
3795 margin area can potentially draw over the border. */
3796 current_row->redraw_fringe_bitmaps_p = 1;
3799 /* Update the display of the text area. */
3800 if (update_text_area (w, desired_row, vpos))
3802 changed_p = 1;
3803 if (current_row->mouse_face_p)
3804 *mouse_face_overwritten_p = 1;
3807 /* Update display of the right margin area, if there is one. */
3808 if (!desired_row->full_width_p && w->right_margin_cols > 0)
3810 changed_p = 1;
3811 update_marginal_area (w, desired_row, RIGHT_MARGIN_AREA, vpos);
3814 /* Draw truncation marks etc. */
3815 if (!current_row->enabled_p
3816 || desired_row->y != current_row->y
3817 || desired_row->visible_height != current_row->visible_height
3818 || desired_row->cursor_in_fringe_p != current_row->cursor_in_fringe_p
3819 || desired_row->overlay_arrow_bitmap != current_row->overlay_arrow_bitmap
3820 || current_row->redraw_fringe_bitmaps_p
3821 || desired_row->mode_line_p != current_row->mode_line_p
3822 || desired_row->exact_window_width_line_p != current_row->exact_window_width_line_p
3823 || (MATRIX_ROW_CONTINUATION_LINE_P (desired_row)
3824 != MATRIX_ROW_CONTINUATION_LINE_P (current_row)))
3825 rif->after_update_window_line_hook (w, desired_row);
3828 /* Update current_row from desired_row. */
3829 make_current (w->desired_matrix, w->current_matrix, vpos);
3830 return changed_p;
3834 /* Set the cursor after an update of window W. This function may only
3835 be called from update_window. */
3837 static void
3838 set_window_cursor_after_update (struct window *w)
3840 struct frame *f = XFRAME (w->frame);
3841 struct redisplay_interface *rif = FRAME_RIF (f);
3842 int cx, cy, vpos, hpos;
3844 /* Not intended for frame matrix updates. */
3845 eassert (FRAME_WINDOW_P (f));
3847 if (cursor_in_echo_area
3848 && !NILP (echo_area_buffer[0])
3849 /* If we are showing a message instead of the mini-buffer,
3850 show the cursor for the message instead. */
3851 && XWINDOW (minibuf_window) == w
3852 && EQ (minibuf_window, echo_area_window)
3853 /* These cases apply only to the frame that contains
3854 the active mini-buffer window. */
3855 && FRAME_HAS_MINIBUF_P (f)
3856 && EQ (FRAME_MINIBUF_WINDOW (f), echo_area_window))
3858 cx = cy = vpos = hpos = 0;
3860 if (cursor_in_echo_area >= 0)
3862 /* If the mini-buffer is several lines high, find the last
3863 line that has any text on it. Note: either all lines
3864 are enabled or none. Otherwise we wouldn't be able to
3865 determine Y. */
3866 struct glyph_row *row, *last_row;
3867 struct glyph *glyph;
3868 int yb = window_text_bottom_y (w);
3870 last_row = NULL;
3871 row = w->current_matrix->rows;
3872 while (row->enabled_p
3873 && (last_row == NULL
3874 || MATRIX_ROW_BOTTOM_Y (row) <= yb))
3876 if (row->used[TEXT_AREA]
3877 && row->glyphs[TEXT_AREA][0].charpos >= 0)
3878 last_row = row;
3879 ++row;
3882 if (last_row)
3884 struct glyph *start = last_row->glyphs[TEXT_AREA];
3885 struct glyph *last = start + last_row->used[TEXT_AREA] - 1;
3887 while (last > start && last->charpos < 0)
3888 --last;
3890 for (glyph = start; glyph < last; ++glyph)
3892 cx += glyph->pixel_width;
3893 ++hpos;
3896 cy = last_row->y;
3897 vpos = MATRIX_ROW_VPOS (last_row, w->current_matrix);
3901 else
3903 cx = w->cursor.x;
3904 cy = w->cursor.y;
3905 hpos = w->cursor.hpos;
3906 vpos = w->cursor.vpos;
3909 /* Window cursor can be out of sync for horizontally split windows.
3910 Horizontal position is -1 when cursor is on the left fringe. */
3911 hpos = clip_to_bounds (-1, hpos, w->current_matrix->matrix_w - 1);
3912 vpos = clip_to_bounds (0, vpos, w->current_matrix->nrows - 1);
3913 rif->cursor_to (w, vpos, hpos, cy, cx);
3917 /* Set WINDOW->must_be_updated_p to ON_P for all windows in the window
3918 tree rooted at W. */
3920 void
3921 set_window_update_flags (struct window *w, bool on_p)
3923 while (w)
3925 if (WINDOWP (w->contents))
3926 set_window_update_flags (XWINDOW (w->contents), on_p);
3927 else
3928 w->must_be_updated_p = on_p;
3930 w = NILP (w->next) ? 0 : XWINDOW (w->next);
3936 /***********************************************************************
3937 Window-Based Scrolling
3938 ***********************************************************************/
3940 /* Structure describing rows in scrolling_window. */
3942 struct row_entry
3944 /* Number of occurrences of this row in desired and current matrix. */
3945 int old_uses, new_uses;
3947 /* Vpos of row in new matrix. */
3948 int new_line_number;
3950 /* Bucket index of this row_entry in the hash table row_table. */
3951 ptrdiff_t bucket;
3953 /* The row described by this entry. */
3954 struct glyph_row *row;
3956 /* Hash collision chain. */
3957 struct row_entry *next;
3960 /* A pool to allocate row_entry structures from, and the size of the
3961 pool. The pool is reallocated in scrolling_window when we find
3962 that we need a larger one. */
3964 static struct row_entry *row_entry_pool;
3965 static ptrdiff_t row_entry_pool_size;
3967 /* Index of next free entry in row_entry_pool. */
3969 static ptrdiff_t row_entry_idx;
3971 /* The hash table used during scrolling, and the table's size. This
3972 table is used to quickly identify equal rows in the desired and
3973 current matrix. */
3975 static struct row_entry **row_table;
3976 static ptrdiff_t row_table_size;
3978 /* Vectors of pointers to row_entry structures belonging to the
3979 current and desired matrix, and the size of the vectors. */
3981 static struct row_entry **old_lines, **new_lines;
3982 static ptrdiff_t old_lines_size, new_lines_size;
3984 /* A pool to allocate run structures from, and its size. */
3986 static struct run *run_pool;
3987 static ptrdiff_t runs_size;
3989 /* A vector of runs of lines found during scrolling. */
3991 static struct run **runs;
3993 /* Add glyph row ROW to the scrolling hash table. */
3995 static struct row_entry *
3996 add_row_entry (struct glyph_row *row)
3998 struct row_entry *entry;
3999 ptrdiff_t i = row->hash % row_table_size;
4001 entry = row_table[i];
4002 eassert (entry || verify_row_hash (row));
4003 while (entry && !row_equal_p (entry->row, row, 1))
4004 entry = entry->next;
4006 if (entry == NULL)
4008 entry = row_entry_pool + row_entry_idx++;
4009 entry->row = row;
4010 entry->old_uses = entry->new_uses = 0;
4011 entry->new_line_number = 0;
4012 entry->bucket = i;
4013 entry->next = row_table[i];
4014 row_table[i] = entry;
4017 return entry;
4021 /* Try to reuse part of the current display of W by scrolling lines.
4022 HEADER_LINE_P means W has a header line.
4024 The algorithm is taken from Communications of the ACM, Apr78 "A
4025 Technique for Isolating Differences Between Files." It should take
4026 O(N) time.
4028 A short outline of the steps of the algorithm
4030 1. Skip lines equal at the start and end of both matrices.
4032 2. Enter rows in the current and desired matrix into a symbol
4033 table, counting how often they appear in both matrices.
4035 3. Rows that appear exactly once in both matrices serve as anchors,
4036 i.e. we assume that such lines are likely to have been moved.
4038 4. Starting from anchor lines, extend regions to be scrolled both
4039 forward and backward.
4041 Value is
4043 -1 if all rows were found to be equal.
4044 0 to indicate that we did not scroll the display, or
4045 1 if we did scroll. */
4047 static int
4048 scrolling_window (struct window *w, bool header_line_p)
4050 struct glyph_matrix *desired_matrix = w->desired_matrix;
4051 struct glyph_matrix *current_matrix = w->current_matrix;
4052 int yb = window_text_bottom_y (w);
4053 ptrdiff_t i;
4054 int j, first_old, first_new, last_old, last_new;
4055 int nruns, run_idx;
4056 ptrdiff_t n;
4057 struct row_entry *entry;
4058 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
4060 /* Skip over rows equal at the start. */
4061 for (i = header_line_p; i < current_matrix->nrows - 1; ++i)
4063 struct glyph_row *d = MATRIX_ROW (desired_matrix, i);
4064 struct glyph_row *c = MATRIX_ROW (current_matrix, i);
4066 if (c->enabled_p
4067 && d->enabled_p
4068 && !d->redraw_fringe_bitmaps_p
4069 && c->y == d->y
4070 && MATRIX_ROW_BOTTOM_Y (c) <= yb
4071 && MATRIX_ROW_BOTTOM_Y (d) <= yb
4072 && row_equal_p (c, d, 1))
4074 assign_row (c, d);
4075 d->enabled_p = 0;
4077 else
4078 break;
4081 /* Give up if some rows in the desired matrix are not enabled. */
4082 if (!MATRIX_ROW (desired_matrix, i)->enabled_p)
4083 return -1;
4085 first_old = first_new = i;
4087 /* Set last_new to the index + 1 of the row that reaches the
4088 bottom boundary in the desired matrix. Give up if we find a
4089 disabled row before we reach the bottom boundary. */
4090 i = first_new + 1;
4091 while (i < desired_matrix->nrows - 1)
4093 int bottom;
4095 if (!MATRIX_ROW (desired_matrix, i)->enabled_p)
4096 return 0;
4097 bottom = MATRIX_ROW_BOTTOM_Y (MATRIX_ROW (desired_matrix, i));
4098 if (bottom <= yb)
4099 ++i;
4100 if (bottom >= yb)
4101 break;
4104 last_new = i;
4106 /* Set last_old to the index + 1 of the row that reaches the bottom
4107 boundary in the current matrix. We don't look at the enabled
4108 flag here because we plan to reuse part of the display even if
4109 other parts are disabled. */
4110 i = first_old + 1;
4111 while (i < current_matrix->nrows - 1)
4113 int bottom = MATRIX_ROW_BOTTOM_Y (MATRIX_ROW (current_matrix, i));
4114 if (bottom <= yb)
4115 ++i;
4116 if (bottom >= yb)
4117 break;
4120 last_old = i;
4122 /* Skip over rows equal at the bottom. */
4123 i = last_new;
4124 j = last_old;
4125 while (i - 1 > first_new
4126 && j - 1 > first_old
4127 && MATRIX_ROW (current_matrix, j - 1)->enabled_p
4128 && (MATRIX_ROW (current_matrix, j - 1)->y
4129 == MATRIX_ROW (desired_matrix, i - 1)->y)
4130 && !MATRIX_ROW (desired_matrix, i - 1)->redraw_fringe_bitmaps_p
4131 && row_equal_p (MATRIX_ROW (desired_matrix, i - 1),
4132 MATRIX_ROW (current_matrix, j - 1), 1))
4133 --i, --j;
4134 last_new = i;
4135 last_old = j;
4137 /* Nothing to do if all rows are equal. */
4138 if (last_new == first_new)
4139 return 0;
4141 /* Check for integer overflow in size calculation.
4143 If next_almost_prime checks (N) for divisibility by 2..10, then
4144 it can return at most N + 10, e.g., next_almost_prime (1) == 11.
4145 So, set next_almost_prime_increment_max to 10.
4147 It's just a coincidence that next_almost_prime_increment_max ==
4148 NEXT_ALMOST_PRIME_LIMIT - 1. If NEXT_ALMOST_PRIME_LIMIT were
4149 13, then next_almost_prime_increment_max would be 14, e.g.,
4150 because next_almost_prime (113) would be 127. */
4152 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
4153 enum { next_almost_prime_increment_max = 10 };
4154 ptrdiff_t row_table_max =
4155 (min (PTRDIFF_MAX, SIZE_MAX) / (3 * sizeof *row_table)
4156 - next_almost_prime_increment_max);
4157 ptrdiff_t current_nrows_max = row_table_max - desired_matrix->nrows;
4158 if (current_nrows_max < current_matrix->nrows)
4159 memory_full (SIZE_MAX);
4162 /* Reallocate vectors, tables etc. if necessary. */
4164 if (current_matrix->nrows > old_lines_size)
4165 old_lines = xpalloc (old_lines, &old_lines_size,
4166 current_matrix->nrows - old_lines_size,
4167 INT_MAX, sizeof *old_lines);
4169 if (desired_matrix->nrows > new_lines_size)
4170 new_lines = xpalloc (new_lines, &new_lines_size,
4171 desired_matrix->nrows - new_lines_size,
4172 INT_MAX, sizeof *new_lines);
4174 n = desired_matrix->nrows;
4175 n += current_matrix->nrows;
4176 if (row_table_size < 3 * n)
4178 ptrdiff_t size = next_almost_prime (3 * n);
4179 row_table = xnrealloc (row_table, size, sizeof *row_table);
4180 row_table_size = size;
4181 memset (row_table, 0, size * sizeof *row_table);
4184 if (n > row_entry_pool_size)
4185 row_entry_pool = xpalloc (row_entry_pool, &row_entry_pool_size,
4186 n - row_entry_pool_size,
4187 -1, sizeof *row_entry_pool);
4189 if (desired_matrix->nrows > runs_size)
4191 runs = xnrealloc (runs, desired_matrix->nrows, sizeof *runs);
4192 run_pool = xnrealloc (run_pool, desired_matrix->nrows, sizeof *run_pool);
4193 runs_size = desired_matrix->nrows;
4196 nruns = run_idx = 0;
4197 row_entry_idx = 0;
4199 /* Add rows from the current and desired matrix to the hash table
4200 row_hash_table to be able to find equal ones quickly. */
4202 for (i = first_old; i < last_old; ++i)
4204 if (MATRIX_ROW (current_matrix, i)->enabled_p)
4206 entry = add_row_entry (MATRIX_ROW (current_matrix, i));
4207 old_lines[i] = entry;
4208 ++entry->old_uses;
4210 else
4211 old_lines[i] = NULL;
4214 for (i = first_new; i < last_new; ++i)
4216 eassert (MATRIX_ROW_ENABLED_P (desired_matrix, i));
4217 entry = add_row_entry (MATRIX_ROW (desired_matrix, i));
4218 ++entry->new_uses;
4219 entry->new_line_number = i;
4220 new_lines[i] = entry;
4223 /* Identify moves based on lines that are unique and equal
4224 in both matrices. */
4225 for (i = first_old; i < last_old;)
4226 if (old_lines[i]
4227 && old_lines[i]->old_uses == 1
4228 && old_lines[i]->new_uses == 1)
4230 int p, q;
4231 int new_line = old_lines[i]->new_line_number;
4232 struct run *run = run_pool + run_idx++;
4234 /* Record move. */
4235 run->current_vpos = i;
4236 run->current_y = MATRIX_ROW (current_matrix, i)->y;
4237 run->desired_vpos = new_line;
4238 run->desired_y = MATRIX_ROW (desired_matrix, new_line)->y;
4239 run->nrows = 1;
4240 run->height = MATRIX_ROW (current_matrix, i)->height;
4242 /* Extend backward. */
4243 p = i - 1;
4244 q = new_line - 1;
4245 while (p > first_old
4246 && q > first_new
4247 && old_lines[p] == new_lines[q])
4249 int h = MATRIX_ROW (current_matrix, p)->height;
4250 --run->current_vpos;
4251 --run->desired_vpos;
4252 ++run->nrows;
4253 run->height += h;
4254 run->desired_y -= h;
4255 run->current_y -= h;
4256 --p, --q;
4259 /* Extend forward. */
4260 p = i + 1;
4261 q = new_line + 1;
4262 while (p < last_old
4263 && q < last_new
4264 && old_lines[p] == new_lines[q])
4266 int h = MATRIX_ROW (current_matrix, p)->height;
4267 ++run->nrows;
4268 run->height += h;
4269 ++p, ++q;
4272 /* Insert run into list of all runs. Order runs by copied
4273 pixel lines. Note that we record runs that don't have to
4274 be copied because they are already in place. This is done
4275 because we can avoid calling update_window_line in this
4276 case. */
4277 for (p = 0; p < nruns && runs[p]->height > run->height; ++p)
4279 for (q = nruns; q > p; --q)
4280 runs[q] = runs[q - 1];
4281 runs[p] = run;
4282 ++nruns;
4284 i += run->nrows;
4286 else
4287 ++i;
4289 /* Do the moves. Do it in a way that we don't overwrite something
4290 we want to copy later on. This is not solvable in general
4291 because there is only one display and we don't have a way to
4292 exchange areas on this display. Example:
4294 +-----------+ +-----------+
4295 | A | | B |
4296 +-----------+ --> +-----------+
4297 | B | | A |
4298 +-----------+ +-----------+
4300 Instead, prefer bigger moves, and invalidate moves that would
4301 copy from where we copied to. */
4303 for (i = 0; i < nruns; ++i)
4304 if (runs[i]->nrows > 0)
4306 struct run *r = runs[i];
4308 /* Copy on the display. */
4309 if (r->current_y != r->desired_y)
4311 rif->clear_window_mouse_face (w);
4312 rif->scroll_run_hook (w, r);
4315 /* Truncate runs that copy to where we copied to, and
4316 invalidate runs that copy from where we copied to. */
4317 for (j = nruns - 1; j > i; --j)
4319 struct run *p = runs[j];
4320 bool truncated_p = 0;
4322 if (p->nrows > 0
4323 && p->desired_y < r->desired_y + r->height
4324 && p->desired_y + p->height > r->desired_y)
4326 if (p->desired_y < r->desired_y)
4328 p->nrows = r->desired_vpos - p->desired_vpos;
4329 p->height = r->desired_y - p->desired_y;
4330 truncated_p = 1;
4332 else
4334 int nrows_copied = (r->desired_vpos + r->nrows
4335 - p->desired_vpos);
4337 if (p->nrows <= nrows_copied)
4338 p->nrows = 0;
4339 else
4341 int height_copied = (r->desired_y + r->height
4342 - p->desired_y);
4344 p->current_vpos += nrows_copied;
4345 p->desired_vpos += nrows_copied;
4346 p->nrows -= nrows_copied;
4347 p->current_y += height_copied;
4348 p->desired_y += height_copied;
4349 p->height -= height_copied;
4350 truncated_p = 1;
4355 if (r->current_y != r->desired_y
4356 /* The condition below is equivalent to
4357 ((p->current_y >= r->desired_y
4358 && p->current_y < r->desired_y + r->height)
4359 || (p->current_y + p->height > r->desired_y
4360 && (p->current_y + p->height
4361 <= r->desired_y + r->height)))
4362 because we have 0 < p->height <= r->height. */
4363 && p->current_y < r->desired_y + r->height
4364 && p->current_y + p->height > r->desired_y)
4365 p->nrows = 0;
4367 /* Reorder runs by copied pixel lines if truncated. */
4368 if (truncated_p && p->nrows > 0)
4370 int k = nruns - 1;
4372 while (runs[k]->nrows == 0 || runs[k]->height < p->height)
4373 k--;
4374 memmove (runs + j, runs + j + 1, (k - j) * sizeof (*runs));
4375 runs[k] = p;
4379 /* Assign matrix rows. */
4380 for (j = 0; j < r->nrows; ++j)
4382 struct glyph_row *from, *to;
4383 bool to_overlapped_p;
4385 to = MATRIX_ROW (current_matrix, r->desired_vpos + j);
4386 from = MATRIX_ROW (desired_matrix, r->desired_vpos + j);
4387 to_overlapped_p = to->overlapped_p;
4388 from->redraw_fringe_bitmaps_p = from->fringe_bitmap_periodic_p;
4389 assign_row (to, from);
4390 /* The above `assign_row' actually does swap, so if we had
4391 an overlap in the copy destination of two runs, then
4392 the second run would assign a previously disabled bogus
4393 row. But thanks to the truncation code in the
4394 preceding for-loop, we no longer have such an overlap,
4395 and thus the assigned row should always be enabled. */
4396 eassert (to->enabled_p);
4397 from->enabled_p = 0;
4398 to->overlapped_p = to_overlapped_p;
4402 /* Clear the hash table, for the next time. */
4403 for (i = 0; i < row_entry_idx; ++i)
4404 row_table[row_entry_pool[i].bucket] = NULL;
4406 /* Value is 1 to indicate that we scrolled the display. */
4407 return nruns > 0;
4412 /************************************************************************
4413 Frame-Based Updates
4414 ************************************************************************/
4416 /* Update the desired frame matrix of frame F.
4418 FORCE_P means that the update should not be stopped by pending input.
4419 INHIBIT_HAIRY_ID_P means that scrolling should not be tried.
4421 Value is true if update was stopped due to pending input. */
4423 static bool
4424 update_frame_1 (struct frame *f, bool force_p, bool inhibit_id_p)
4426 /* Frame matrices to work on. */
4427 struct glyph_matrix *current_matrix = f->current_matrix;
4428 struct glyph_matrix *desired_matrix = f->desired_matrix;
4429 int i;
4430 bool pause_p;
4431 int preempt_count = baud_rate / 2400 + 1;
4433 eassert (current_matrix && desired_matrix);
4435 if (baud_rate != FRAME_COST_BAUD_RATE (f))
4436 calculate_costs (f);
4438 if (preempt_count <= 0)
4439 preempt_count = 1;
4441 if (!force_p && detect_input_pending_ignore_squeezables ())
4443 pause_p = 1;
4444 goto do_pause;
4447 /* If we cannot insert/delete lines, it's no use trying it. */
4448 if (!FRAME_LINE_INS_DEL_OK (f))
4449 inhibit_id_p = 1;
4451 /* See if any of the desired lines are enabled; don't compute for
4452 i/d line if just want cursor motion. */
4453 for (i = 0; i < desired_matrix->nrows; i++)
4454 if (MATRIX_ROW_ENABLED_P (desired_matrix, i))
4455 break;
4457 /* Try doing i/d line, if not yet inhibited. */
4458 if (!inhibit_id_p && i < desired_matrix->nrows)
4459 force_p |= scrolling (f);
4461 /* Update the individual lines as needed. Do bottom line first. */
4462 if (MATRIX_ROW_ENABLED_P (desired_matrix, desired_matrix->nrows - 1))
4463 update_frame_line (f, desired_matrix->nrows - 1);
4465 /* Now update the rest of the lines. */
4466 for (i = 0; i < desired_matrix->nrows - 1 && (force_p || !input_pending); i++)
4468 if (MATRIX_ROW_ENABLED_P (desired_matrix, i))
4470 if (FRAME_TERMCAP_P (f))
4472 /* Flush out every so many lines.
4473 Also flush out if likely to have more than 1k buffered
4474 otherwise. I'm told that some telnet connections get
4475 really screwed by more than 1k output at once. */
4476 FILE *display_output = FRAME_TTY (f)->output;
4477 if (display_output)
4479 ptrdiff_t outq = __fpending (display_output);
4480 if (outq > 900
4481 || (outq > 20 && ((i - 1) % preempt_count == 0)))
4482 fflush (display_output);
4486 if (!force_p && (i - 1) % preempt_count == 0)
4487 detect_input_pending_ignore_squeezables ();
4489 update_frame_line (f, i);
4493 lint_assume (0 <= FRAME_LINES (f));
4494 pause_p = 0 < i && i < FRAME_LINES (f) - 1;
4496 /* Now just clean up termcap drivers and set cursor, etc. */
4497 if (!pause_p)
4499 if ((cursor_in_echo_area
4500 /* If we are showing a message instead of the mini-buffer,
4501 show the cursor for the message instead of for the
4502 (now hidden) mini-buffer contents. */
4503 || (EQ (minibuf_window, selected_window)
4504 && EQ (minibuf_window, echo_area_window)
4505 && !NILP (echo_area_buffer[0])))
4506 /* These cases apply only to the frame that contains
4507 the active mini-buffer window. */
4508 && FRAME_HAS_MINIBUF_P (f)
4509 && EQ (FRAME_MINIBUF_WINDOW (f), echo_area_window))
4511 int top = WINDOW_TOP_EDGE_LINE (XWINDOW (FRAME_MINIBUF_WINDOW (f)));
4512 int row, col;
4514 if (cursor_in_echo_area < 0)
4516 /* Negative value of cursor_in_echo_area means put
4517 cursor at beginning of line. */
4518 row = top;
4519 col = 0;
4521 else
4523 /* Positive value of cursor_in_echo_area means put
4524 cursor at the end of the prompt. If the mini-buffer
4525 is several lines high, find the last line that has
4526 any text on it. */
4527 row = FRAME_LINES (f);
4530 --row;
4531 col = 0;
4533 if (MATRIX_ROW_ENABLED_P (current_matrix, row))
4535 /* Frame rows are filled up with spaces that
4536 must be ignored here. */
4537 struct glyph_row *r = MATRIX_ROW (current_matrix,
4538 row);
4539 struct glyph *start = r->glyphs[TEXT_AREA];
4540 struct glyph *last = start + r->used[TEXT_AREA];
4542 while (last > start
4543 && (last - 1)->charpos < 0)
4544 --last;
4546 col = last - start;
4549 while (row > top && col == 0);
4551 /* Make sure COL is not out of range. */
4552 if (col >= FRAME_CURSOR_X_LIMIT (f))
4554 /* If we have another row, advance cursor into it. */
4555 if (row < FRAME_LINES (f) - 1)
4557 col = FRAME_LEFT_SCROLL_BAR_COLS (f);
4558 row++;
4560 /* Otherwise move it back in range. */
4561 else
4562 col = FRAME_CURSOR_X_LIMIT (f) - 1;
4566 cursor_to (f, row, col);
4568 else
4570 /* We have only one cursor on terminal frames. Use it to
4571 display the cursor of the selected window. */
4572 struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
4573 if (w->cursor.vpos >= 0
4574 /* The cursor vpos may be temporarily out of bounds
4575 in the following situation: There is one window,
4576 with the cursor in the lower half of it. The window
4577 is split, and a message causes a redisplay before
4578 a new cursor position has been computed. */
4579 && w->cursor.vpos < WINDOW_TOTAL_LINES (w))
4581 int x = WINDOW_TO_FRAME_HPOS (w, w->cursor.hpos);
4582 int y = WINDOW_TO_FRAME_VPOS (w, w->cursor.vpos);
4584 x += max (0, w->left_margin_cols);
4585 cursor_to (f, y, x);
4590 do_pause:
4592 clear_desired_matrices (f);
4593 return pause_p;
4597 /* Do line insertions/deletions on frame F for frame-based redisplay. */
4599 static bool
4600 scrolling (struct frame *frame)
4602 int unchanged_at_top, unchanged_at_bottom;
4603 int window_size;
4604 int changed_lines;
4605 int *old_hash = alloca (FRAME_LINES (frame) * sizeof (int));
4606 int *new_hash = alloca (FRAME_LINES (frame) * sizeof (int));
4607 int *draw_cost = alloca (FRAME_LINES (frame) * sizeof (int));
4608 int *old_draw_cost = alloca (FRAME_LINES (frame) * sizeof (int));
4609 register int i;
4610 int free_at_end_vpos = FRAME_LINES (frame);
4611 struct glyph_matrix *current_matrix = frame->current_matrix;
4612 struct glyph_matrix *desired_matrix = frame->desired_matrix;
4614 if (!current_matrix)
4615 emacs_abort ();
4617 /* Compute hash codes of all the lines. Also calculate number of
4618 changed lines, number of unchanged lines at the beginning, and
4619 number of unchanged lines at the end. */
4620 changed_lines = 0;
4621 unchanged_at_top = 0;
4622 unchanged_at_bottom = FRAME_LINES (frame);
4623 for (i = 0; i < FRAME_LINES (frame); i++)
4625 /* Give up on this scrolling if some old lines are not enabled. */
4626 if (!MATRIX_ROW_ENABLED_P (current_matrix, i))
4627 return 0;
4628 old_hash[i] = line_hash_code (MATRIX_ROW (current_matrix, i));
4629 if (! MATRIX_ROW_ENABLED_P (desired_matrix, i))
4631 /* This line cannot be redrawn, so don't let scrolling mess it. */
4632 new_hash[i] = old_hash[i];
4633 #define INFINITY 1000000 /* Taken from scroll.c */
4634 draw_cost[i] = INFINITY;
4636 else
4638 new_hash[i] = line_hash_code (MATRIX_ROW (desired_matrix, i));
4639 draw_cost[i] = line_draw_cost (desired_matrix, i);
4642 if (old_hash[i] != new_hash[i])
4644 changed_lines++;
4645 unchanged_at_bottom = FRAME_LINES (frame) - i - 1;
4647 else if (i == unchanged_at_top)
4648 unchanged_at_top++;
4649 old_draw_cost[i] = line_draw_cost (current_matrix, i);
4652 /* If changed lines are few, don't allow preemption, don't scroll. */
4653 if ((!FRAME_SCROLL_REGION_OK (frame)
4654 && changed_lines < baud_rate / 2400)
4655 || unchanged_at_bottom == FRAME_LINES (frame))
4656 return 1;
4658 window_size = (FRAME_LINES (frame) - unchanged_at_top
4659 - unchanged_at_bottom);
4661 if (FRAME_SCROLL_REGION_OK (frame))
4662 free_at_end_vpos -= unchanged_at_bottom;
4663 else if (FRAME_MEMORY_BELOW_FRAME (frame))
4664 free_at_end_vpos = -1;
4666 /* If large window, fast terminal and few lines in common between
4667 current frame and desired frame, don't bother with i/d calc. */
4668 if (!FRAME_SCROLL_REGION_OK (frame)
4669 && window_size >= 18 && baud_rate > 2400
4670 && (window_size >=
4671 10 * scrolling_max_lines_saved (unchanged_at_top,
4672 FRAME_LINES (frame) - unchanged_at_bottom,
4673 old_hash, new_hash, draw_cost)))
4674 return 0;
4676 if (window_size < 2)
4677 return 0;
4679 scrolling_1 (frame, window_size, unchanged_at_top, unchanged_at_bottom,
4680 draw_cost + unchanged_at_top - 1,
4681 old_draw_cost + unchanged_at_top - 1,
4682 old_hash + unchanged_at_top - 1,
4683 new_hash + unchanged_at_top - 1,
4684 free_at_end_vpos - unchanged_at_top);
4686 return 0;
4690 /* Count the number of blanks at the start of the vector of glyphs R
4691 which is LEN glyphs long. */
4693 static int
4694 count_blanks (struct glyph *r, int len)
4696 int i;
4698 for (i = 0; i < len; ++i)
4699 if (!CHAR_GLYPH_SPACE_P (r[i]))
4700 break;
4702 return i;
4706 /* Count the number of glyphs in common at the start of the glyph
4707 vectors STR1 and STR2. END1 is the end of STR1 and END2 is the end
4708 of STR2. Value is the number of equal glyphs equal at the start. */
4710 static int
4711 count_match (struct glyph *str1, struct glyph *end1, struct glyph *str2, struct glyph *end2)
4713 struct glyph *p1 = str1;
4714 struct glyph *p2 = str2;
4716 while (p1 < end1
4717 && p2 < end2
4718 && GLYPH_CHAR_AND_FACE_EQUAL_P (p1, p2))
4719 ++p1, ++p2;
4721 return p1 - str1;
4725 /* Char insertion/deletion cost vector, from term.c */
4727 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_TOTAL_COLS ((f))])
4730 /* Perform a frame-based update on line VPOS in frame FRAME. */
4732 static void
4733 update_frame_line (struct frame *f, int vpos)
4735 struct glyph *obody, *nbody, *op1, *op2, *np1, *nend;
4736 int tem;
4737 int osp, nsp, begmatch, endmatch, olen, nlen;
4738 struct glyph_matrix *current_matrix = f->current_matrix;
4739 struct glyph_matrix *desired_matrix = f->desired_matrix;
4740 struct glyph_row *current_row = MATRIX_ROW (current_matrix, vpos);
4741 struct glyph_row *desired_row = MATRIX_ROW (desired_matrix, vpos);
4742 bool must_write_whole_line_p;
4743 bool write_spaces_p = FRAME_MUST_WRITE_SPACES (f);
4744 bool colored_spaces_p = (FACE_FROM_ID (f, DEFAULT_FACE_ID)->background
4745 != FACE_TTY_DEFAULT_BG_COLOR);
4747 if (colored_spaces_p)
4748 write_spaces_p = 1;
4750 /* Current row not enabled means it has unknown contents. We must
4751 write the whole desired line in that case. */
4752 must_write_whole_line_p = !current_row->enabled_p;
4753 if (must_write_whole_line_p)
4755 obody = 0;
4756 olen = 0;
4758 else
4760 obody = MATRIX_ROW_GLYPH_START (current_matrix, vpos);
4761 olen = current_row->used[TEXT_AREA];
4763 /* Ignore trailing spaces, if we can. */
4764 if (!write_spaces_p)
4765 while (olen > 0 && CHAR_GLYPH_SPACE_P (obody[olen-1]))
4766 olen--;
4769 current_row->enabled_p = 1;
4770 current_row->used[TEXT_AREA] = desired_row->used[TEXT_AREA];
4772 /* If desired line is empty, just clear the line. */
4773 if (!desired_row->enabled_p)
4775 nlen = 0;
4776 goto just_erase;
4779 nbody = desired_row->glyphs[TEXT_AREA];
4780 nlen = desired_row->used[TEXT_AREA];
4781 nend = nbody + nlen;
4783 /* If display line has unknown contents, write the whole line. */
4784 if (must_write_whole_line_p)
4786 /* Ignore spaces at the end, if we can. */
4787 if (!write_spaces_p)
4788 while (nlen > 0 && CHAR_GLYPH_SPACE_P (nbody[nlen - 1]))
4789 --nlen;
4791 /* Write the contents of the desired line. */
4792 if (nlen)
4794 cursor_to (f, vpos, 0);
4795 write_glyphs (f, nbody, nlen);
4798 /* Don't call clear_end_of_line if we already wrote the whole
4799 line. The cursor will not be at the right margin in that
4800 case but in the line below. */
4801 if (nlen < FRAME_TOTAL_COLS (f))
4803 cursor_to (f, vpos, nlen);
4804 clear_end_of_line (f, FRAME_TOTAL_COLS (f));
4806 else
4807 /* Make sure we are in the right row, otherwise cursor movement
4808 with cmgoto might use `ch' in the wrong row. */
4809 cursor_to (f, vpos, 0);
4811 make_current (desired_matrix, current_matrix, vpos);
4812 return;
4815 /* Pretend trailing spaces are not there at all,
4816 unless for one reason or another we must write all spaces. */
4817 if (!write_spaces_p)
4818 while (nlen > 0 && CHAR_GLYPH_SPACE_P (nbody[nlen - 1]))
4819 nlen--;
4821 /* If there's no i/d char, quickly do the best we can without it. */
4822 if (!FRAME_CHAR_INS_DEL_OK (f))
4824 int i, j;
4826 /* Find the first glyph in desired row that doesn't agree with
4827 a glyph in the current row, and write the rest from there on. */
4828 for (i = 0; i < nlen; i++)
4830 if (i >= olen || !GLYPH_EQUAL_P (nbody + i, obody + i))
4832 /* Find the end of the run of different glyphs. */
4833 j = i + 1;
4834 while (j < nlen
4835 && (j >= olen
4836 || !GLYPH_EQUAL_P (nbody + j, obody + j)
4837 || CHAR_GLYPH_PADDING_P (nbody[j])))
4838 ++j;
4840 /* Output this run of non-matching chars. */
4841 cursor_to (f, vpos, i);
4842 write_glyphs (f, nbody + i, j - i);
4843 i = j - 1;
4845 /* Now find the next non-match. */
4849 /* Clear the rest of the line, or the non-clear part of it. */
4850 if (olen > nlen)
4852 cursor_to (f, vpos, nlen);
4853 clear_end_of_line (f, olen);
4856 /* Make current row = desired row. */
4857 make_current (desired_matrix, current_matrix, vpos);
4858 return;
4861 /* Here when CHAR_INS_DEL_OK != 0, i.e. we can insert or delete
4862 characters in a row. */
4864 if (!olen)
4866 /* If current line is blank, skip over initial spaces, if
4867 possible, and write the rest. */
4868 if (write_spaces_p)
4869 nsp = 0;
4870 else
4871 nsp = count_blanks (nbody, nlen);
4873 if (nlen > nsp)
4875 cursor_to (f, vpos, nsp);
4876 write_glyphs (f, nbody + nsp, nlen - nsp);
4879 /* Exchange contents between current_frame and new_frame. */
4880 make_current (desired_matrix, current_matrix, vpos);
4881 return;
4884 /* Compute number of leading blanks in old and new contents. */
4885 osp = count_blanks (obody, olen);
4886 nsp = (colored_spaces_p ? 0 : count_blanks (nbody, nlen));
4888 /* Compute number of matching chars starting with first non-blank. */
4889 begmatch = count_match (obody + osp, obody + olen,
4890 nbody + nsp, nbody + nlen);
4892 /* Spaces in new match implicit space past the end of old. */
4893 /* A bug causing this to be a no-op was fixed in 18.29. */
4894 if (!write_spaces_p && osp + begmatch == olen)
4896 np1 = nbody + nsp;
4897 while (np1 + begmatch < nend && CHAR_GLYPH_SPACE_P (np1[begmatch]))
4898 ++begmatch;
4901 /* Avoid doing insert/delete char
4902 just cause number of leading spaces differs
4903 when the following text does not match. */
4904 if (begmatch == 0 && osp != nsp)
4905 osp = nsp = min (osp, nsp);
4907 /* Find matching characters at end of line */
4908 op1 = obody + olen;
4909 np1 = nbody + nlen;
4910 op2 = op1 + begmatch - min (olen - osp, nlen - nsp);
4911 while (op1 > op2
4912 && GLYPH_EQUAL_P (op1 - 1, np1 - 1))
4914 op1--;
4915 np1--;
4917 endmatch = obody + olen - op1;
4919 /* tem gets the distance to insert or delete.
4920 endmatch is how many characters we save by doing so.
4921 Is it worth it? */
4923 tem = (nlen - nsp) - (olen - osp);
4924 if (endmatch && tem
4925 && (!FRAME_CHAR_INS_DEL_OK (f)
4926 || endmatch <= char_ins_del_cost (f)[tem]))
4927 endmatch = 0;
4929 /* nsp - osp is the distance to insert or delete.
4930 If that is nonzero, begmatch is known to be nonzero also.
4931 begmatch + endmatch is how much we save by doing the ins/del.
4932 Is it worth it? */
4934 if (nsp != osp
4935 && (!FRAME_CHAR_INS_DEL_OK (f)
4936 || begmatch + endmatch <= char_ins_del_cost (f)[nsp - osp]))
4938 begmatch = 0;
4939 endmatch = 0;
4940 osp = nsp = min (osp, nsp);
4943 /* Now go through the line, inserting, writing and
4944 deleting as appropriate. */
4946 if (osp > nsp)
4948 cursor_to (f, vpos, nsp);
4949 delete_glyphs (f, osp - nsp);
4951 else if (nsp > osp)
4953 /* If going to delete chars later in line
4954 and insert earlier in the line,
4955 must delete first to avoid losing data in the insert */
4956 if (endmatch && nlen < olen + nsp - osp)
4958 cursor_to (f, vpos, nlen - endmatch + osp - nsp);
4959 delete_glyphs (f, olen + nsp - osp - nlen);
4960 olen = nlen - (nsp - osp);
4962 cursor_to (f, vpos, osp);
4963 insert_glyphs (f, 0, nsp - osp);
4965 olen += nsp - osp;
4967 tem = nsp + begmatch + endmatch;
4968 if (nlen != tem || olen != tem)
4970 if (!endmatch || nlen == olen)
4972 /* If new text being written reaches right margin, there is
4973 no need to do clear-to-eol at the end of this function
4974 (and it would not be safe, since cursor is not going to
4975 be "at the margin" after the text is done). */
4976 if (nlen == FRAME_TOTAL_COLS (f))
4977 olen = 0;
4979 /* Function write_glyphs is prepared to do nothing
4980 if passed a length <= 0. Check it here to avoid
4981 unnecessary cursor movement. */
4982 if (nlen - tem > 0)
4984 cursor_to (f, vpos, nsp + begmatch);
4985 write_glyphs (f, nbody + nsp + begmatch, nlen - tem);
4988 else if (nlen > olen)
4990 /* Here, we used to have the following simple code:
4991 ----------------------------------------
4992 write_glyphs (nbody + nsp + begmatch, olen - tem);
4993 insert_glyphs (nbody + nsp + begmatch + olen - tem, nlen - olen);
4994 ----------------------------------------
4995 but it doesn't work if nbody[nsp + begmatch + olen - tem]
4996 is a padding glyph. */
4997 int out = olen - tem; /* Columns to be overwritten originally. */
4998 int del;
5000 cursor_to (f, vpos, nsp + begmatch);
5002 /* Calculate columns we can actually overwrite. */
5003 while (CHAR_GLYPH_PADDING_P (nbody[nsp + begmatch + out]))
5004 out--;
5005 write_glyphs (f, nbody + nsp + begmatch, out);
5007 /* If we left columns to be overwritten, we must delete them. */
5008 del = olen - tem - out;
5009 if (del > 0)
5010 delete_glyphs (f, del);
5012 /* At last, we insert columns not yet written out. */
5013 insert_glyphs (f, nbody + nsp + begmatch + out, nlen - olen + del);
5014 olen = nlen;
5016 else if (olen > nlen)
5018 cursor_to (f, vpos, nsp + begmatch);
5019 write_glyphs (f, nbody + nsp + begmatch, nlen - tem);
5020 delete_glyphs (f, olen - nlen);
5021 olen = nlen;
5025 just_erase:
5026 /* If any unerased characters remain after the new line, erase them. */
5027 if (olen > nlen)
5029 cursor_to (f, vpos, nlen);
5030 clear_end_of_line (f, olen);
5033 /* Exchange contents between current_frame and new_frame. */
5034 make_current (desired_matrix, current_matrix, vpos);
5039 /***********************************************************************
5040 X/Y Position -> Buffer Position
5041 ***********************************************************************/
5043 /* Determine what's under window-relative pixel position (*X, *Y).
5044 Return the OBJECT (string or buffer) that's there.
5045 Return in *POS the position in that object.
5046 Adjust *X and *Y to character positions.
5047 Return in *DX and *DY the pixel coordinates of the click,
5048 relative to the top left corner of OBJECT, or relative to
5049 the top left corner of the character glyph at (*X, *Y)
5050 if OBJECT is nil.
5051 Return WIDTH and HEIGHT of the object at (*X, *Y), or zero
5052 if the coordinates point to an empty area of the display. */
5054 Lisp_Object
5055 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)
5057 struct it it;
5058 Lisp_Object old_current_buffer = Fcurrent_buffer ();
5059 struct text_pos startp;
5060 Lisp_Object string;
5061 struct glyph_row *row;
5062 #ifdef HAVE_WINDOW_SYSTEM
5063 struct image *img = 0;
5064 #endif
5065 int x0, x1, to_x;
5066 void *itdata = NULL;
5068 /* We used to set current_buffer directly here, but that does the
5069 wrong thing with `face-remapping-alist' (bug#2044). */
5070 Fset_buffer (w->contents);
5071 itdata = bidi_shelve_cache ();
5072 SET_TEXT_POS_FROM_MARKER (startp, w->start);
5073 CHARPOS (startp) = min (ZV, max (BEGV, CHARPOS (startp)));
5074 BYTEPOS (startp) = min (ZV_BYTE, max (BEGV_BYTE, BYTEPOS (startp)));
5075 start_display (&it, w, startp);
5076 /* start_display takes into account the header-line row, but IT's
5077 vpos still counts from the glyph row that includes the window's
5078 start position. Adjust for a possible header-line row. */
5079 it.vpos += WINDOW_WANTS_HEADER_LINE_P (w);
5081 x0 = *x;
5083 /* First, move to the beginning of the row corresponding to *Y. We
5084 need to be in that row to get the correct value of base paragraph
5085 direction for the text at (*X, *Y). */
5086 move_it_to (&it, -1, 0, *y, -1, MOVE_TO_X | MOVE_TO_Y);
5088 /* TO_X is the pixel position that the iterator will compute for the
5089 glyph at *X. We add it.first_visible_x because iterator
5090 positions include the hscroll. */
5091 to_x = x0 + it.first_visible_x;
5092 if (it.bidi_it.paragraph_dir == R2L)
5093 /* For lines in an R2L paragraph, we need to mirror TO_X wrt the
5094 text area. This is because the iterator, even in R2L
5095 paragraphs, delivers glyphs as if they started at the left
5096 margin of the window. (When we actually produce glyphs for
5097 display, we reverse their order in PRODUCE_GLYPHS, but the
5098 iterator doesn't know about that.) The following line adjusts
5099 the pixel position to the iterator geometry, which is what
5100 move_it_* routines use. (The -1 is because in a window whose
5101 text-area width is W, the rightmost pixel position is W-1, and
5102 it should be mirrored into zero pixel position.) */
5103 to_x = window_box_width (w, TEXT_AREA) - to_x - 1;
5105 /* Now move horizontally in the row to the glyph under *X. Second
5106 argument is ZV to prevent move_it_in_display_line from matching
5107 based on buffer positions. */
5108 move_it_in_display_line (&it, ZV, to_x, MOVE_TO_X);
5109 bidi_unshelve_cache (itdata, 0);
5111 Fset_buffer (old_current_buffer);
5113 *dx = x0 + it.first_visible_x - it.current_x;
5114 *dy = *y - it.current_y;
5116 string = w->contents;
5117 if (STRINGP (it.string))
5118 string = it.string;
5119 *pos = it.current;
5120 if (it.what == IT_COMPOSITION
5121 && it.cmp_it.nchars > 1
5122 && it.cmp_it.reversed_p)
5124 /* The current display element is a grapheme cluster in a
5125 composition. In that case, we need the position of the first
5126 character of the cluster. But, as it.cmp_it.reversed_p is 1,
5127 it.current points to the last character of the cluster, thus
5128 we must move back to the first character of the same
5129 cluster. */
5130 CHARPOS (pos->pos) -= it.cmp_it.nchars - 1;
5131 if (STRINGP (it.string))
5132 BYTEPOS (pos->pos) = string_char_to_byte (string, CHARPOS (pos->pos));
5133 else
5134 BYTEPOS (pos->pos) = buf_charpos_to_bytepos (XBUFFER (w->contents),
5135 CHARPOS (pos->pos));
5138 #ifdef HAVE_WINDOW_SYSTEM
5139 if (it.what == IT_IMAGE)
5141 if ((img = IMAGE_FROM_ID (it.f, it.image_id)) != NULL
5142 && !NILP (img->spec))
5143 *object = img->spec;
5145 #endif
5147 if (it.vpos < w->current_matrix->nrows
5148 && (row = MATRIX_ROW (w->current_matrix, it.vpos),
5149 row->enabled_p))
5151 if (it.hpos < row->used[TEXT_AREA])
5153 struct glyph *glyph = row->glyphs[TEXT_AREA] + it.hpos;
5154 #ifdef HAVE_WINDOW_SYSTEM
5155 if (img)
5157 *dy -= row->ascent - glyph->ascent;
5158 *dx += glyph->slice.img.x;
5159 *dy += glyph->slice.img.y;
5160 /* Image slices positions are still relative to the entire image */
5161 *width = img->width;
5162 *height = img->height;
5164 else
5165 #endif
5167 *width = glyph->pixel_width;
5168 *height = glyph->ascent + glyph->descent;
5171 else
5173 *width = 0;
5174 *height = row->height;
5177 else
5179 *width = *height = 0;
5182 /* Add extra (default width) columns if clicked after EOL. */
5183 x1 = max (0, it.current_x + it.pixel_width - it.first_visible_x);
5184 if (x0 > x1)
5185 it.hpos += (x0 - x1) / WINDOW_FRAME_COLUMN_WIDTH (w);
5187 *x = it.hpos;
5188 *y = it.vpos;
5190 return string;
5194 /* Value is the string under window-relative coordinates X/Y in the
5195 mode line or header line (PART says which) of window W, or nil if none.
5196 *CHARPOS is set to the position in the string returned. */
5198 Lisp_Object
5199 mode_line_string (struct window *w, enum window_part part,
5200 int *x, int *y, ptrdiff_t *charpos, Lisp_Object *object,
5201 int *dx, int *dy, int *width, int *height)
5203 struct glyph_row *row;
5204 struct glyph *glyph, *end;
5205 int x0, y0;
5206 Lisp_Object string = Qnil;
5208 if (part == ON_MODE_LINE)
5209 row = MATRIX_MODE_LINE_ROW (w->current_matrix);
5210 else
5211 row = MATRIX_HEADER_LINE_ROW (w->current_matrix);
5212 y0 = *y - row->y;
5213 *y = row - MATRIX_FIRST_TEXT_ROW (w->current_matrix);
5215 if (row->mode_line_p && row->enabled_p)
5217 /* Find the glyph under X. If we find one with a string object,
5218 it's the one we were looking for. */
5219 glyph = row->glyphs[TEXT_AREA];
5220 end = glyph + row->used[TEXT_AREA];
5221 for (x0 = *x; glyph < end && x0 >= glyph->pixel_width; ++glyph)
5222 x0 -= glyph->pixel_width;
5223 *x = glyph - row->glyphs[TEXT_AREA];
5224 if (glyph < end)
5226 string = glyph->object;
5227 *charpos = glyph->charpos;
5228 *width = glyph->pixel_width;
5229 *height = glyph->ascent + glyph->descent;
5230 #ifdef HAVE_WINDOW_SYSTEM
5231 if (glyph->type == IMAGE_GLYPH)
5233 struct image *img;
5234 img = IMAGE_FROM_ID (WINDOW_XFRAME (w), glyph->u.img_id);
5235 if (img != NULL)
5236 *object = img->spec;
5237 y0 -= row->ascent - glyph->ascent;
5239 #endif
5241 else
5243 /* Add extra (default width) columns if clicked after EOL. */
5244 *x += x0 / WINDOW_FRAME_COLUMN_WIDTH (w);
5245 *width = 0;
5246 *height = row->height;
5249 else
5251 *x = 0;
5252 x0 = 0;
5253 *width = *height = 0;
5256 *dx = x0;
5257 *dy = y0;
5259 return string;
5263 /* Value is the string under window-relative coordinates X/Y in either
5264 marginal area, or nil if none. *CHARPOS is set to the position in
5265 the string returned. */
5267 Lisp_Object
5268 marginal_area_string (struct window *w, enum window_part part,
5269 int *x, int *y, ptrdiff_t *charpos, Lisp_Object *object,
5270 int *dx, int *dy, int *width, int *height)
5272 struct glyph_row *row = w->current_matrix->rows;
5273 struct glyph *glyph, *end;
5274 int x0, y0, i, wy = *y;
5275 int area;
5276 Lisp_Object string = Qnil;
5278 if (part == ON_LEFT_MARGIN)
5279 area = LEFT_MARGIN_AREA;
5280 else if (part == ON_RIGHT_MARGIN)
5281 area = RIGHT_MARGIN_AREA;
5282 else
5283 emacs_abort ();
5285 for (i = 0; row->enabled_p && i < w->current_matrix->nrows; ++i, ++row)
5286 if (wy >= row->y && wy < MATRIX_ROW_BOTTOM_Y (row))
5287 break;
5288 y0 = *y - row->y;
5289 *y = row - MATRIX_FIRST_TEXT_ROW (w->current_matrix);
5291 if (row->enabled_p)
5293 /* Find the glyph under X. If we find one with a string object,
5294 it's the one we were looking for. */
5295 if (area == RIGHT_MARGIN_AREA)
5296 x0 = ((WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5297 ? WINDOW_LEFT_FRINGE_WIDTH (w)
5298 : WINDOW_TOTAL_FRINGE_WIDTH (w))
5299 + window_box_width (w, LEFT_MARGIN_AREA)
5300 + window_box_width (w, TEXT_AREA));
5301 else
5302 x0 = (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5303 ? WINDOW_LEFT_FRINGE_WIDTH (w)
5304 : 0);
5306 glyph = row->glyphs[area];
5307 end = glyph + row->used[area];
5308 for (x0 = *x - x0; glyph < end && x0 >= glyph->pixel_width; ++glyph)
5309 x0 -= glyph->pixel_width;
5310 *x = glyph - row->glyphs[area];
5311 if (glyph < end)
5313 string = glyph->object;
5314 *charpos = glyph->charpos;
5315 *width = glyph->pixel_width;
5316 *height = glyph->ascent + glyph->descent;
5317 #ifdef HAVE_WINDOW_SYSTEM
5318 if (glyph->type == IMAGE_GLYPH)
5320 struct image *img;
5321 img = IMAGE_FROM_ID (WINDOW_XFRAME (w), glyph->u.img_id);
5322 if (img != NULL)
5323 *object = img->spec;
5324 y0 -= row->ascent - glyph->ascent;
5325 x0 += glyph->slice.img.x;
5326 y0 += glyph->slice.img.y;
5328 #endif
5330 else
5332 /* Add extra (default width) columns if clicked after EOL. */
5333 *x += x0 / WINDOW_FRAME_COLUMN_WIDTH (w);
5334 *width = 0;
5335 *height = row->height;
5338 else
5340 x0 = 0;
5341 *x = 0;
5342 *width = *height = 0;
5345 *dx = x0;
5346 *dy = y0;
5348 return string;
5352 /***********************************************************************
5353 Changing Frame Sizes
5354 ***********************************************************************/
5356 #ifdef SIGWINCH
5358 static void deliver_window_change_signal (int);
5360 static void
5361 handle_window_change_signal (int sig)
5363 int width, height;
5364 struct tty_display_info *tty;
5366 /* The frame size change obviously applies to a single
5367 termcap-controlled terminal, but we can't decide which.
5368 Therefore, we resize the frames corresponding to each tty.
5370 for (tty = tty_list; tty; tty = tty->next) {
5372 if (! tty->term_initted)
5373 continue;
5375 /* Suspended tty frames have tty->input == NULL avoid trying to
5376 use it. */
5377 if (!tty->input)
5378 continue;
5380 get_tty_size (fileno (tty->input), &width, &height);
5382 if (width > 5 && height > 2) {
5383 Lisp_Object tail, frame;
5385 FOR_EACH_FRAME (tail, frame)
5386 if (FRAME_TERMCAP_P (XFRAME (frame)) && FRAME_TTY (XFRAME (frame)) == tty)
5387 /* Record the new sizes, but don't reallocate the data
5388 structures now. Let that be done later outside of the
5389 signal handler. */
5390 change_frame_size (XFRAME (frame), height, width, 0, 1, 0);
5395 static void
5396 deliver_window_change_signal (int sig)
5398 deliver_process_signal (sig, handle_window_change_signal);
5400 #endif /* SIGWINCH */
5403 /* Do any change in frame size that was requested by a signal.
5404 SAFE means this function is called from a place where it is
5405 safe to change frame sizes while a redisplay is in progress. */
5407 void
5408 do_pending_window_change (bool safe)
5410 /* If window change signal handler should have run before, run it now. */
5411 if (redisplaying_p && !safe)
5412 return;
5414 while (delayed_size_change)
5416 Lisp_Object tail, frame;
5418 delayed_size_change = 0;
5420 FOR_EACH_FRAME (tail, frame)
5422 struct frame *f = XFRAME (frame);
5424 if (f->new_text_lines != 0 || f->new_text_cols != 0)
5425 change_frame_size (f, f->new_text_lines, f->new_text_cols,
5426 0, 0, safe);
5432 /* Change the frame height and/or width. Values may be given as zero to
5433 indicate no change is to take place.
5435 If DELAY, assume we're being called from a signal handler, and
5436 queue the change for later - perhaps the next redisplay.
5437 Since this tries to resize windows, we can't call it
5438 from a signal handler.
5440 SAFE means this function is called from a place where it's
5441 safe to change frame sizes while a redisplay is in progress. */
5443 void
5444 change_frame_size (struct frame *f, int newheight, int newwidth,
5445 bool pretend, bool delay, bool safe)
5447 Lisp_Object tail, frame;
5449 if (FRAME_MSDOS_P (f))
5451 /* On MS-DOS, all frames use the same screen, so a change in
5452 size affects all frames. Termcap now supports multiple
5453 ttys. */
5454 FOR_EACH_FRAME (tail, frame)
5455 if (! FRAME_WINDOW_P (XFRAME (frame)))
5456 change_frame_size_1 (XFRAME (frame), newheight, newwidth,
5457 pretend, delay, safe);
5459 else
5460 change_frame_size_1 (f, newheight, newwidth, pretend, delay, safe);
5463 static void
5464 change_frame_size_1 (struct frame *f, int newheight, int newwidth,
5465 bool pretend, bool delay, bool safe)
5467 int new_frame_total_cols;
5468 ptrdiff_t count = SPECPDL_INDEX ();
5470 /* If we can't deal with the change now, queue it for later. */
5471 if (delay || (redisplaying_p && !safe))
5473 f->new_text_lines = newheight;
5474 f->new_text_cols = newwidth;
5475 delayed_size_change = 1;
5476 return;
5479 /* This size-change overrides any pending one for this frame. */
5480 f->new_text_lines = 0;
5481 f->new_text_cols = 0;
5483 /* If an argument is zero, set it to the current value. */
5484 if (newheight == 0)
5485 newheight = FRAME_LINES (f);
5486 if (newwidth == 0)
5487 newwidth = FRAME_COLS (f);
5489 /* Compute width of windows in F. */
5490 /* Round up to the smallest acceptable size. */
5491 check_frame_size (f, &newheight, &newwidth);
5493 /* This is the width of the frame with vertical scroll bars and fringe
5494 columns. Do this after rounding - see discussion of bug#9723. */
5495 new_frame_total_cols = FRAME_TOTAL_COLS_ARG (f, newwidth);
5497 /* If we're not changing the frame size, quit now. */
5498 /* Frame width may be unchanged but the text portion may change, for
5499 example, fullscreen and remove/add scroll bar. */
5500 if (newheight == FRAME_LINES (f)
5501 /* Text portion unchanged? */
5502 && newwidth == FRAME_COLS (f)
5503 /* Frame width unchanged? */
5504 && new_frame_total_cols == FRAME_TOTAL_COLS (f))
5505 return;
5507 block_input ();
5509 #ifdef MSDOS
5510 /* We only can set screen dimensions to certain values supported
5511 by our video hardware. Try to find the smallest size greater
5512 or equal to the requested dimensions. */
5513 dos_set_window_size (&newheight, &newwidth);
5514 #endif
5516 if (newheight != FRAME_LINES (f))
5518 resize_frame_windows (f, newheight, 0);
5520 /* MSDOS frames cannot PRETEND, as they change frame size by
5521 manipulating video hardware. */
5522 if ((FRAME_TERMCAP_P (f) && !pretend) || FRAME_MSDOS_P (f))
5523 FrameRows (FRAME_TTY (f)) = newheight;
5526 if (new_frame_total_cols != FRAME_TOTAL_COLS (f))
5528 resize_frame_windows (f, new_frame_total_cols, 1);
5530 /* MSDOS frames cannot PRETEND, as they change frame size by
5531 manipulating video hardware. */
5532 if ((FRAME_TERMCAP_P (f) && !pretend) || FRAME_MSDOS_P (f))
5533 FrameCols (FRAME_TTY (f)) = newwidth;
5535 if (WINDOWP (f->tool_bar_window))
5536 XWINDOW (f->tool_bar_window)->total_cols = newwidth;
5539 FRAME_LINES (f) = newheight;
5540 SET_FRAME_COLS (f, newwidth);
5543 struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
5544 int text_area_x, text_area_y, text_area_width, text_area_height;
5546 window_box (w, TEXT_AREA, &text_area_x, &text_area_y, &text_area_width,
5547 &text_area_height);
5548 if (w->cursor.x >= text_area_x + text_area_width)
5549 w->cursor.hpos = w->cursor.x = 0;
5550 if (w->cursor.y >= text_area_y + text_area_height)
5551 w->cursor.vpos = w->cursor.y = 0;
5554 adjust_glyphs (f);
5555 calculate_costs (f);
5556 SET_FRAME_GARBAGED (f);
5557 f->resized_p = 1;
5559 unblock_input ();
5561 record_unwind_current_buffer ();
5563 run_window_configuration_change_hook (f);
5565 unbind_to (count, Qnil);
5570 /***********************************************************************
5571 Terminal Related Lisp Functions
5572 ***********************************************************************/
5574 DEFUN ("open-termscript", Fopen_termscript, Sopen_termscript,
5575 1, 1, "FOpen termscript file: ",
5576 doc: /* Start writing all terminal output to FILE as well as the terminal.
5577 FILE = nil means just close any termscript file currently open. */)
5578 (Lisp_Object file)
5580 struct tty_display_info *tty;
5582 if (! FRAME_TERMCAP_P (SELECTED_FRAME ())
5583 && ! FRAME_MSDOS_P (SELECTED_FRAME ()))
5584 error ("Current frame is not on a tty device");
5586 tty = CURTTY ();
5588 if (tty->termscript != 0)
5590 block_input ();
5591 fclose (tty->termscript);
5592 tty->termscript = 0;
5593 unblock_input ();
5596 if (! NILP (file))
5598 file = Fexpand_file_name (file, Qnil);
5599 tty->termscript = emacs_fopen (SSDATA (file), "w");
5600 if (tty->termscript == 0)
5601 report_file_error ("Opening termscript", file);
5603 return Qnil;
5607 DEFUN ("send-string-to-terminal", Fsend_string_to_terminal,
5608 Ssend_string_to_terminal, 1, 2, 0,
5609 doc: /* Send STRING to the terminal without alteration.
5610 Control characters in STRING will have terminal-dependent effects.
5612 Optional parameter TERMINAL specifies the tty terminal device to use.
5613 It may be a terminal object, a frame, or nil for the terminal used by
5614 the currently selected frame. In batch mode, STRING is sent to stdout
5615 when TERMINAL is nil. */)
5616 (Lisp_Object string, Lisp_Object terminal)
5618 struct terminal *t = get_terminal (terminal, 1);
5619 FILE *out;
5621 /* ??? Perhaps we should do something special for multibyte strings here. */
5622 CHECK_STRING (string);
5623 block_input ();
5625 if (!t)
5626 error ("Unknown terminal device");
5628 if (t->type == output_initial)
5629 out = stdout;
5630 else if (t->type != output_termcap && t->type != output_msdos_raw)
5631 error ("Device %d is not a termcap terminal device", t->id);
5632 else
5634 struct tty_display_info *tty = t->display_info.tty;
5636 if (! tty->output)
5637 error ("Terminal is currently suspended");
5639 if (tty->termscript)
5641 fwrite (SDATA (string), 1, SBYTES (string), tty->termscript);
5642 fflush (tty->termscript);
5644 out = tty->output;
5646 fwrite (SDATA (string), 1, SBYTES (string), out);
5647 fflush (out);
5648 unblock_input ();
5649 return Qnil;
5653 DEFUN ("ding", Fding, Sding, 0, 1, 0,
5654 doc: /* Beep, or flash the screen.
5655 Also, unless an argument is given,
5656 terminate any keyboard macro currently executing. */)
5657 (Lisp_Object arg)
5659 if (!NILP (arg))
5661 if (noninteractive)
5662 putchar (07);
5663 else
5664 ring_bell (XFRAME (selected_frame));
5666 else
5667 bitch_at_user ();
5669 return Qnil;
5672 void
5673 bitch_at_user (void)
5675 if (noninteractive)
5676 putchar (07);
5677 else if (!INTERACTIVE) /* Stop executing a keyboard macro. */
5679 const char *msg
5680 = "Keyboard macro terminated by a command ringing the bell";
5681 Fsignal (Quser_error, list1 (build_string (msg)));
5683 else
5684 ring_bell (XFRAME (selected_frame));
5689 /***********************************************************************
5690 Sleeping, Waiting
5691 ***********************************************************************/
5693 DEFUN ("sleep-for", Fsleep_for, Ssleep_for, 1, 2, 0,
5694 doc: /* Pause, without updating display, for SECONDS seconds.
5695 SECONDS may be a floating-point value, meaning that you can wait for a
5696 fraction of a second. Optional second arg MILLISECONDS specifies an
5697 additional wait period, in milliseconds; this is for backwards compatibility.
5698 \(Not all operating systems support waiting for a fraction of a second.) */)
5699 (Lisp_Object seconds, Lisp_Object milliseconds)
5701 double duration = extract_float (seconds);
5703 if (!NILP (milliseconds))
5705 CHECK_NUMBER (milliseconds);
5706 duration += XINT (milliseconds) / 1000.0;
5709 if (duration > 0)
5711 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (duration);
5712 wait_reading_process_output (min (EMACS_SECS (t), WAIT_READING_MAX),
5713 EMACS_NSECS (t), 0, 0, Qnil, NULL, 0);
5716 return Qnil;
5720 /* This is just like wait_reading_process_output, except that
5721 it does redisplay.
5723 TIMEOUT is number of seconds to wait (float or integer),
5724 or t to wait forever.
5725 READING is true if reading input.
5726 If DISPLAY_OPTION is >0 display process output while waiting.
5727 If DISPLAY_OPTION is >1 perform an initial redisplay before waiting.
5730 Lisp_Object
5731 sit_for (Lisp_Object timeout, bool reading, int display_option)
5733 intmax_t sec;
5734 int nsec;
5735 bool do_display = display_option > 0;
5737 swallow_events (do_display);
5739 if ((detect_input_pending_run_timers (do_display))
5740 || !NILP (Vexecuting_kbd_macro))
5741 return Qnil;
5743 if (display_option > 1)
5744 redisplay_preserve_echo_area (2);
5746 if (INTEGERP (timeout))
5748 sec = XINT (timeout);
5749 if (sec <= 0)
5750 return Qt;
5751 nsec = 0;
5753 else if (FLOATP (timeout))
5755 double seconds = XFLOAT_DATA (timeout);
5756 if (! (0 < seconds))
5757 return Qt;
5758 else
5760 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (seconds);
5761 sec = min (EMACS_SECS (t), WAIT_READING_MAX);
5762 nsec = EMACS_NSECS (t);
5765 else if (EQ (timeout, Qt))
5767 sec = 0;
5768 nsec = 0;
5770 else
5771 wrong_type_argument (Qnumberp, timeout);
5774 #ifdef USABLE_SIGIO
5775 gobble_input ();
5776 #endif
5778 wait_reading_process_output (sec, nsec, reading ? -1 : 1, do_display,
5779 Qnil, NULL, 0);
5781 return detect_input_pending () ? Qnil : Qt;
5785 DEFUN ("redisplay", Fredisplay, Sredisplay, 0, 1, 0,
5786 doc: /* Perform redisplay.
5787 Optional arg FORCE, if non-nil, prevents redisplay from being
5788 preempted by arriving input, even if `redisplay-dont-pause' is nil.
5789 If `redisplay-dont-pause' is non-nil (the default), redisplay is never
5790 preempted by arriving input, so FORCE does nothing.
5792 Return t if redisplay was performed, nil if redisplay was preempted
5793 immediately by pending input. */)
5794 (Lisp_Object force)
5796 ptrdiff_t count;
5798 swallow_events (1);
5799 if ((detect_input_pending_run_timers (1)
5800 && NILP (force) && !redisplay_dont_pause)
5801 || !NILP (Vexecuting_kbd_macro))
5802 return Qnil;
5804 count = SPECPDL_INDEX ();
5805 if (!NILP (force) && !redisplay_dont_pause)
5806 specbind (Qredisplay_dont_pause, Qt);
5807 redisplay_preserve_echo_area (2);
5808 unbind_to (count, Qnil);
5809 return Qt;
5814 /***********************************************************************
5815 Other Lisp Functions
5816 ***********************************************************************/
5818 /* A vector of size >= 2 * NFRAMES + 3 * NBUFFERS + 1, containing the
5819 session's frames, frame names, buffers, buffer-read-only flags, and
5820 buffer-modified-flags. */
5822 static Lisp_Object frame_and_buffer_state;
5825 DEFUN ("frame-or-buffer-changed-p", Fframe_or_buffer_changed_p,
5826 Sframe_or_buffer_changed_p, 0, 1, 0,
5827 doc: /* Return non-nil if the frame and buffer state appears to have changed.
5828 VARIABLE is a variable name whose value is either nil or a state vector
5829 that will be updated to contain all frames and buffers,
5830 aside from buffers whose names start with space,
5831 along with the buffers' read-only and modified flags. This allows a fast
5832 check to see whether buffer menus might need to be recomputed.
5833 If this function returns non-nil, it updates the internal vector to reflect
5834 the current state.
5836 If VARIABLE is nil, an internal variable is used. Users should not
5837 pass nil for VARIABLE. */)
5838 (Lisp_Object variable)
5840 Lisp_Object state, tail, frame, buf;
5841 ptrdiff_t n, idx;
5843 if (! NILP (variable))
5845 CHECK_SYMBOL (variable);
5846 state = Fsymbol_value (variable);
5847 if (! VECTORP (state))
5848 goto changed;
5850 else
5851 state = frame_and_buffer_state;
5853 idx = 0;
5854 FOR_EACH_FRAME (tail, frame)
5856 if (idx == ASIZE (state))
5857 goto changed;
5858 if (!EQ (AREF (state, idx++), frame))
5859 goto changed;
5860 if (idx == ASIZE (state))
5861 goto changed;
5862 if (!EQ (AREF (state, idx++), XFRAME (frame)->name))
5863 goto changed;
5865 /* Check that the buffer info matches. */
5866 FOR_EACH_LIVE_BUFFER (tail, buf)
5868 /* Ignore buffers that aren't included in buffer lists. */
5869 if (SREF (BVAR (XBUFFER (buf), name), 0) == ' ')
5870 continue;
5871 if (idx == ASIZE (state))
5872 goto changed;
5873 if (!EQ (AREF (state, idx++), buf))
5874 goto changed;
5875 if (idx == ASIZE (state))
5876 goto changed;
5877 if (!EQ (AREF (state, idx++), BVAR (XBUFFER (buf), read_only)))
5878 goto changed;
5879 if (idx == ASIZE (state))
5880 goto changed;
5881 if (!EQ (AREF (state, idx++), Fbuffer_modified_p (buf)))
5882 goto changed;
5884 if (idx == ASIZE (state))
5885 goto changed;
5886 /* Detect deletion of a buffer at the end of the list. */
5887 if (EQ (AREF (state, idx), Qlambda))
5888 return Qnil;
5890 /* Come here if we decide the data has changed. */
5891 changed:
5892 /* Count the size we will need.
5893 Start with 1 so there is room for at least one lambda at the end. */
5894 n = 1;
5895 FOR_EACH_FRAME (tail, frame)
5896 n += 2;
5897 FOR_EACH_LIVE_BUFFER (tail, buf)
5898 n += 3;
5899 /* Reallocate the vector if data has grown to need it,
5900 or if it has shrunk a lot. */
5901 if (! VECTORP (state)
5902 || n > ASIZE (state)
5903 || n + 20 < ASIZE (state) / 2)
5904 /* Add 20 extra so we grow it less often. */
5906 state = Fmake_vector (make_number (n + 20), Qlambda);
5907 if (! NILP (variable))
5908 Fset (variable, state);
5909 else
5910 frame_and_buffer_state = state;
5913 /* Record the new data in the (possibly reallocated) vector. */
5914 idx = 0;
5915 FOR_EACH_FRAME (tail, frame)
5917 ASET (state, idx, frame);
5918 idx++;
5919 ASET (state, idx, XFRAME (frame)->name);
5920 idx++;
5922 FOR_EACH_LIVE_BUFFER (tail, buf)
5924 /* Ignore buffers that aren't included in buffer lists. */
5925 if (SREF (BVAR (XBUFFER (buf), name), 0) == ' ')
5926 continue;
5927 ASET (state, idx, buf);
5928 idx++;
5929 ASET (state, idx, BVAR (XBUFFER (buf), read_only));
5930 idx++;
5931 ASET (state, idx, Fbuffer_modified_p (buf));
5932 idx++;
5934 /* Fill up the vector with lambdas (always at least one). */
5935 ASET (state, idx, Qlambda);
5936 idx++;
5937 while (idx < ASIZE (state))
5939 ASET (state, idx, Qlambda);
5940 idx++;
5942 /* Make sure we didn't overflow the vector. */
5943 eassert (idx <= ASIZE (state));
5944 return Qt;
5949 /***********************************************************************
5950 Initialization
5951 ***********************************************************************/
5953 /* Initialization done when Emacs fork is started, before doing stty.
5954 Determine terminal type and set terminal_driver. Then invoke its
5955 decoding routine to set up variables in the terminal package. */
5957 void
5958 init_display (void)
5960 char *terminal_type;
5962 /* Construct the space glyph. */
5963 space_glyph.type = CHAR_GLYPH;
5964 SET_CHAR_GLYPH (space_glyph, ' ', DEFAULT_FACE_ID, 0);
5965 space_glyph.charpos = -1;
5967 inverse_video = 0;
5968 cursor_in_echo_area = 0;
5970 /* Now is the time to initialize this; it's used by init_sys_modes
5971 during startup. */
5972 Vinitial_window_system = Qnil;
5974 /* SIGWINCH needs to be handled no matter what display we start
5975 with. Otherwise newly opened tty frames will not resize
5976 automatically. */
5977 #ifdef SIGWINCH
5978 #ifndef CANNOT_DUMP
5979 if (initialized)
5980 #endif /* CANNOT_DUMP */
5982 struct sigaction action;
5983 emacs_sigaction_init (&action, deliver_window_change_signal);
5984 sigaction (SIGWINCH, &action, 0);
5986 #endif /* SIGWINCH */
5988 /* If running as a daemon, no need to initialize any frames/terminal. */
5989 if (IS_DAEMON)
5990 return;
5992 /* If the user wants to use a window system, we shouldn't bother
5993 initializing the terminal. This is especially important when the
5994 terminal is so dumb that emacs gives up before and doesn't bother
5995 using the window system.
5997 If the DISPLAY environment variable is set and nonempty,
5998 try to use X, and die with an error message if that doesn't work. */
6000 #ifdef HAVE_X_WINDOWS
6001 if (! inhibit_window_system && ! display_arg)
6003 char *display;
6004 display = getenv ("DISPLAY");
6005 display_arg = (display != 0 && *display != 0);
6007 if (display_arg && !x_display_ok (display))
6009 fprintf (stderr, "Display %s unavailable, simulating -nw\n",
6010 display);
6011 inhibit_window_system = 1;
6015 if (!inhibit_window_system && display_arg)
6017 Vinitial_window_system = Qx;
6018 #ifdef HAVE_X11
6019 Vwindow_system_version = make_number (11);
6020 #endif
6021 #ifdef USE_NCURSES
6022 /* In some versions of ncurses,
6023 tputs crashes if we have not called tgetent.
6024 So call tgetent. */
6025 { char b[2044]; tgetent (b, "xterm");}
6026 #endif
6027 return;
6029 #endif /* HAVE_X_WINDOWS */
6031 #ifdef HAVE_NTGUI
6032 if (!inhibit_window_system)
6034 Vinitial_window_system = Qw32;
6035 Vwindow_system_version = make_number (1);
6036 return;
6038 #endif /* HAVE_NTGUI */
6040 #ifdef HAVE_NS
6041 if (!inhibit_window_system
6042 #ifndef CANNOT_DUMP
6043 && initialized
6044 #endif
6047 Vinitial_window_system = Qns;
6048 Vwindow_system_version = make_number (10);
6049 return;
6051 #endif
6053 /* If no window system has been specified, try to use the terminal. */
6054 if (! isatty (0))
6055 fatal ("standard input is not a tty");
6057 #ifdef WINDOWSNT
6058 terminal_type = "w32console";
6059 #else
6060 terminal_type = getenv ("TERM");
6061 #endif
6062 if (!terminal_type)
6064 #ifdef HAVE_WINDOW_SYSTEM
6065 if (! inhibit_window_system)
6066 fprintf (stderr, "Please set the environment variable DISPLAY or TERM (see `tset').\n");
6067 else
6068 #endif /* HAVE_WINDOW_SYSTEM */
6069 fprintf (stderr, "Please set the environment variable TERM; see `tset'.\n");
6070 exit (1);
6074 struct terminal *t;
6075 struct frame *f = XFRAME (selected_frame);
6077 init_foreground_group ();
6079 /* Open a display on the controlling tty. */
6080 t = init_tty (0, terminal_type, 1); /* Errors are fatal. */
6082 /* Convert the initial frame to use the new display. */
6083 if (f->output_method != output_initial)
6084 emacs_abort ();
6085 f->output_method = t->type;
6086 f->terminal = t;
6088 t->reference_count++;
6089 #ifdef MSDOS
6090 f->output_data.tty->display_info = &the_only_display_info;
6091 #else
6092 if (f->output_method == output_termcap)
6093 create_tty_output (f);
6094 #endif
6095 t->display_info.tty->top_frame = selected_frame;
6096 change_frame_size (XFRAME (selected_frame),
6097 FrameRows (t->display_info.tty),
6098 FrameCols (t->display_info.tty), 0, 0, 1);
6100 /* Delete the initial terminal. */
6101 if (--initial_terminal->reference_count == 0
6102 && initial_terminal->delete_terminal_hook)
6103 (*initial_terminal->delete_terminal_hook) (initial_terminal);
6105 /* Update frame parameters to reflect the new type. */
6106 Fmodify_frame_parameters
6107 (selected_frame, list1 (Fcons (Qtty_type,
6108 Ftty_type (selected_frame))));
6109 if (t->display_info.tty->name)
6110 Fmodify_frame_parameters
6111 (selected_frame,
6112 list1 (Fcons (Qtty, build_string (t->display_info.tty->name))));
6113 else
6114 Fmodify_frame_parameters (selected_frame, list1 (Fcons (Qtty, Qnil)));
6118 struct frame *sf = SELECTED_FRAME ();
6119 int width = FRAME_TOTAL_COLS (sf);
6120 int height = FRAME_LINES (sf);
6122 /* If these sizes are so big they cause overflow, just ignore the
6123 change. It's not clear what better we could do. The rest of
6124 the code assumes that (width + 2) * height * sizeof (struct glyph)
6125 does not overflow and does not exceed PTRDIFF_MAX or SIZE_MAX. */
6126 if (INT_ADD_RANGE_OVERFLOW (width, 2, INT_MIN, INT_MAX)
6127 || INT_MULTIPLY_RANGE_OVERFLOW (width + 2, height, INT_MIN, INT_MAX)
6128 || (min (PTRDIFF_MAX, SIZE_MAX) / sizeof (struct glyph)
6129 < (width + 2) * height))
6130 fatal ("screen size %dx%d too big", width, height);
6133 calculate_costs (XFRAME (selected_frame));
6135 /* Set up faces of the initial terminal frame of a dumped Emacs. */
6136 if (initialized
6137 && !noninteractive
6138 && NILP (Vinitial_window_system))
6140 /* For the initial frame, we don't have any way of knowing what
6141 are the foreground and background colors of the terminal. */
6142 struct frame *sf = SELECTED_FRAME ();
6144 FRAME_FOREGROUND_PIXEL (sf) = FACE_TTY_DEFAULT_FG_COLOR;
6145 FRAME_BACKGROUND_PIXEL (sf) = FACE_TTY_DEFAULT_BG_COLOR;
6146 call0 (intern ("tty-set-up-initial-frame-faces"));
6152 /***********************************************************************
6153 Blinking cursor
6154 ***********************************************************************/
6156 DEFUN ("internal-show-cursor", Finternal_show_cursor,
6157 Sinternal_show_cursor, 2, 2, 0,
6158 doc: /* Set the cursor-visibility flag of WINDOW to SHOW.
6159 WINDOW nil means use the selected window. SHOW non-nil means
6160 show a cursor in WINDOW in the next redisplay. SHOW nil means
6161 don't show a cursor. */)
6162 (Lisp_Object window, Lisp_Object show)
6164 /* Don't change cursor state while redisplaying. This could confuse
6165 output routines. */
6166 if (!redisplaying_p)
6167 decode_any_window (window)->cursor_off_p = NILP (show);
6168 return Qnil;
6172 DEFUN ("internal-show-cursor-p", Finternal_show_cursor_p,
6173 Sinternal_show_cursor_p, 0, 1, 0,
6174 doc: /* Value is non-nil if next redisplay will display a cursor in WINDOW.
6175 WINDOW nil or omitted means report on the selected window. */)
6176 (Lisp_Object window)
6178 return decode_any_window (window)->cursor_off_p ? Qnil : Qt;
6181 DEFUN ("last-nonminibuffer-frame", Flast_nonminibuf_frame,
6182 Slast_nonminibuf_frame, 0, 0, 0,
6183 doc: /* Value is last nonminibuffer frame. */)
6184 (void)
6186 Lisp_Object frame = Qnil;
6188 if (last_nonminibuf_frame)
6189 XSETFRAME (frame, last_nonminibuf_frame);
6191 return frame;
6194 /***********************************************************************
6195 Initialization
6196 ***********************************************************************/
6198 void
6199 syms_of_display (void)
6201 defsubr (&Sredraw_frame);
6202 defsubr (&Sredraw_display);
6203 defsubr (&Sframe_or_buffer_changed_p);
6204 defsubr (&Sopen_termscript);
6205 defsubr (&Sding);
6206 defsubr (&Sredisplay);
6207 defsubr (&Ssleep_for);
6208 defsubr (&Ssend_string_to_terminal);
6209 defsubr (&Sinternal_show_cursor);
6210 defsubr (&Sinternal_show_cursor_p);
6211 defsubr (&Slast_nonminibuf_frame);
6213 #ifdef GLYPH_DEBUG
6214 defsubr (&Sdump_redisplay_history);
6215 #endif
6217 frame_and_buffer_state = Fmake_vector (make_number (20), Qlambda);
6218 staticpro (&frame_and_buffer_state);
6220 DEFSYM (Qdisplay_table, "display-table");
6221 DEFSYM (Qredisplay_dont_pause, "redisplay-dont-pause");
6223 DEFVAR_INT ("baud-rate", baud_rate,
6224 doc: /* The output baud rate of the terminal.
6225 On most systems, changing this value will affect the amount of padding
6226 and the other strategic decisions made during redisplay. */);
6228 DEFVAR_BOOL ("inverse-video", inverse_video,
6229 doc: /* Non-nil means invert the entire frame display.
6230 This means everything is in inverse video which otherwise would not be. */);
6232 DEFVAR_BOOL ("visible-bell", visible_bell,
6233 doc: /* Non-nil means try to flash the frame to represent a bell.
6235 See also `ring-bell-function'. */);
6237 DEFVAR_BOOL ("no-redraw-on-reenter", no_redraw_on_reenter,
6238 doc: /* Non-nil means no need to redraw entire frame after suspending.
6239 A non-nil value is useful if the terminal can automatically preserve
6240 Emacs's frame display when you reenter Emacs.
6241 It is up to you to set this variable if your terminal can do that. */);
6243 DEFVAR_LISP ("initial-window-system", Vinitial_window_system,
6244 doc: /* Name of the window system that Emacs uses for the first frame.
6245 The value is a symbol:
6246 nil for a termcap frame (a character-only terminal),
6247 'x' for an Emacs frame that is really an X window,
6248 'w32' for an Emacs frame that is a window on MS-Windows display,
6249 'ns' for an Emacs frame on a GNUstep or Macintosh Cocoa display,
6250 'pc' for a direct-write MS-DOS frame.
6252 Use of this variable as a boolean is deprecated. Instead,
6253 use `display-graphic-p' or any of the other `display-*-p'
6254 predicates which report frame's specific UI-related capabilities. */);
6256 DEFVAR_KBOARD ("window-system", Vwindow_system,
6257 doc: /* Name of window system through which the selected frame is displayed.
6258 The value is a symbol:
6259 nil for a termcap frame (a character-only terminal),
6260 'x' for an Emacs frame that is really an X window,
6261 'w32' for an Emacs frame that is a window on MS-Windows display,
6262 'ns' for an Emacs frame on a GNUstep or Macintosh Cocoa display,
6263 'pc' for a direct-write MS-DOS frame.
6265 Use of this variable as a boolean is deprecated. Instead,
6266 use `display-graphic-p' or any of the other `display-*-p'
6267 predicates which report frame's specific UI-related capabilities. */);
6269 DEFVAR_LISP ("window-system-version", Vwindow_system_version,
6270 doc: /* The version number of the window system in use.
6271 For X windows, this is 11. */);
6273 DEFVAR_BOOL ("cursor-in-echo-area", cursor_in_echo_area,
6274 doc: /* Non-nil means put cursor in minibuffer, at end of any message there. */);
6276 DEFVAR_LISP ("glyph-table", Vglyph_table,
6277 doc: /* Table defining how to output a glyph code to the frame.
6278 If not nil, this is a vector indexed by glyph code to define the glyph.
6279 Each element can be:
6280 integer: a glyph code which this glyph is an alias for.
6281 string: output this glyph using that string (not impl. in X windows).
6282 nil: this glyph mod 524288 is the code of a character to output,
6283 and this glyph / 524288 is the face number (see `face-id') to use
6284 while outputting it. */);
6285 Vglyph_table = Qnil;
6287 DEFVAR_LISP ("standard-display-table", Vstandard_display_table,
6288 doc: /* Display table to use for buffers that specify none.
6289 See `buffer-display-table' for more information. */);
6290 Vstandard_display_table = Qnil;
6292 DEFVAR_BOOL ("redisplay-dont-pause", redisplay_dont_pause,
6293 doc: /* Non-nil means display update isn't paused when input is detected. */);
6294 redisplay_dont_pause = 1;
6296 #ifdef CANNOT_DUMP
6297 if (noninteractive)
6298 #endif
6300 Vinitial_window_system = Qnil;
6301 Vwindow_system_version = Qnil;