* lisp/emacs-lisp/advice.el (ad-should-compile): Don't compile advice if the
[emacs.git] / src / dispnew.c
blob675c06c22e920a46eda98e705f8bbd1ce83d0685
1 /* Updating of data structures for redisplay.
3 Copyright (C) 1985-1988, 1993-1995, 1997-2012 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #define DISPEXTERN_INLINE EXTERN_INLINE
24 #include <stdio.h>
25 #include <unistd.h>
27 #include "lisp.h"
28 #include "termchar.h"
29 /* cm.h must come after dispextern.h on Windows. */
30 #include "dispextern.h"
31 #include "cm.h"
32 #include "character.h"
33 #include "buffer.h"
34 #include "keyboard.h"
35 #include "frame.h"
36 #include "termhooks.h"
37 #include "window.h"
38 #include "commands.h"
39 #include "disptab.h"
40 #include "indent.h"
41 #include "intervals.h"
42 #include "blockinput.h"
43 #include "process.h"
45 #include "syssignal.h"
47 #ifdef HAVE_WINDOW_SYSTEM
48 #include TERM_HEADER
49 #endif /* HAVE_WINDOW_SYSTEM */
51 /* Include systime.h after xterm.h to avoid double inclusion of time.h. */
53 #include "systime.h"
54 #include <errno.h>
56 #include <fpending.h>
58 #if defined (HAVE_TERM_H) && defined (GNU_LINUX)
59 #include <term.h> /* for tgetent */
60 #endif
62 #ifdef WINDOWSNT
63 #include "w32.h"
64 #endif
66 /* Structure to pass dimensions around. Used for character bounding
67 boxes, glyph matrix dimensions and alike. */
69 struct dim
71 int width;
72 int height;
76 /* Function prototypes. */
78 static void update_frame_line (struct frame *, int);
79 static int required_matrix_height (struct window *);
80 static int required_matrix_width (struct window *);
81 static void adjust_frame_glyphs (struct frame *);
82 static void change_frame_size_1 (struct frame *, int, int, bool, bool, bool);
83 static void increment_row_positions (struct glyph_row *, ptrdiff_t, ptrdiff_t);
84 static void fill_up_frame_row_with_spaces (struct glyph_row *, int);
85 static void build_frame_matrix_from_window_tree (struct glyph_matrix *,
86 struct window *);
87 static void build_frame_matrix_from_leaf_window (struct glyph_matrix *,
88 struct window *);
89 static void adjust_frame_message_buffer (struct frame *);
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 *);
111 /* Redisplay preemption timers. */
113 static EMACS_TIME preemption_period;
114 static EMACS_TIME preemption_next_check;
116 /* True upon entry to redisplay means do not assume anything about
117 current contents of actual terminal frame; clear and redraw it. */
119 bool frame_garbaged;
121 /* True means last display completed. False means it was preempted. */
123 bool display_completed;
125 Lisp_Object Qdisplay_table, Qredisplay_dont_pause;
128 /* The currently selected frame. In a single-frame version, this
129 variable always equals the_only_frame. */
131 Lisp_Object selected_frame;
133 /* A frame which is not just a mini-buffer, or 0 if there are no such
134 frames. This is usually the most recent such frame that was
135 selected. In a single-frame version, this variable always holds
136 the address of the_only_frame. */
138 struct frame *last_nonminibuf_frame;
140 /* True means SIGWINCH happened when not safe. */
142 static bool delayed_size_change;
144 /* Updated window if != 0. Set by update_window. */
146 struct window *updated_window;
148 /* Glyph row updated in update_window_line, and area that is updated. */
150 struct glyph_row *updated_row;
151 int updated_area;
153 /* A glyph for a space. */
155 struct glyph space_glyph;
157 /* Counts of allocated structures. These counts serve to diagnose
158 memory leaks and double frees. */
160 static int glyph_matrix_count;
161 static int glyph_pool_count;
163 /* If non-null, the frame whose frame matrices are manipulated. If
164 null, window matrices are worked on. */
166 static struct frame *frame_matrix_frame;
168 /* True means that fonts have been loaded since the last glyph
169 matrix adjustments. Redisplay must stop, and glyph matrices must
170 be adjusted when this flag becomes true during display. The
171 reason fonts can be loaded so late is that fonts of fontsets are
172 loaded on demand. Another reason is that a line contains many
173 characters displayed by zero width or very narrow glyphs of
174 variable-width fonts. */
176 bool fonts_changed_p;
178 /* Convert vpos and hpos from frame to window and vice versa.
179 This may only be used for terminal frames. */
181 #ifdef GLYPH_DEBUG
183 static int window_to_frame_vpos (struct window *, int);
184 static int window_to_frame_hpos (struct window *, int);
185 #define WINDOW_TO_FRAME_VPOS(W, VPOS) window_to_frame_vpos ((W), (VPOS))
186 #define WINDOW_TO_FRAME_HPOS(W, HPOS) window_to_frame_hpos ((W), (HPOS))
188 /* One element of the ring buffer containing redisplay history
189 information. */
191 struct redisplay_history
193 char trace[512 + 100];
196 /* The size of the history buffer. */
198 #define REDISPLAY_HISTORY_SIZE 30
200 /* The redisplay history buffer. */
202 static struct redisplay_history redisplay_history[REDISPLAY_HISTORY_SIZE];
204 /* Next free entry in redisplay_history. */
206 static int history_idx;
208 /* A tick that's incremented each time something is added to the
209 history. */
211 static uprintmax_t history_tick;
213 /* Add to the redisplay history how window W has been displayed.
214 MSG is a trace containing the information how W's glyph matrix
215 has been constructed. PAUSED_P means that the update
216 has been interrupted for pending input. */
218 static void
219 add_window_display_history (struct window *w, const char *msg, bool paused_p)
221 char *buf;
223 if (history_idx >= REDISPLAY_HISTORY_SIZE)
224 history_idx = 0;
225 buf = redisplay_history[history_idx].trace;
226 ++history_idx;
228 snprintf (buf, sizeof redisplay_history[0].trace,
229 "%"pMu": window %p (`%s')%s\n%s",
230 history_tick++,
232 ((BUFFERP (w->buffer)
233 && STRINGP (BVAR (XBUFFER (w->buffer), name)))
234 ? SSDATA (BVAR (XBUFFER (w->buffer), name))
235 : "???"),
236 paused_p ? " ***paused***" : "",
237 msg);
241 /* Add to the redisplay history that frame F has been displayed.
242 PAUSED_P means that the update has been interrupted for
243 pending input. */
245 static void
246 add_frame_display_history (struct frame *f, bool paused_p)
248 char *buf;
250 if (history_idx >= REDISPLAY_HISTORY_SIZE)
251 history_idx = 0;
252 buf = redisplay_history[history_idx].trace;
253 ++history_idx;
255 sprintf (buf, "%"pMu": update frame %p%s",
256 history_tick++,
257 f, paused_p ? " ***paused***" : "");
261 DEFUN ("dump-redisplay-history", Fdump_redisplay_history,
262 Sdump_redisplay_history, 0, 0, "",
263 doc: /* Dump redisplay history to stderr. */)
264 (void)
266 int i;
268 for (i = history_idx - 1; i != history_idx; --i)
270 if (i < 0)
271 i = REDISPLAY_HISTORY_SIZE - 1;
272 fprintf (stderr, "%s\n", redisplay_history[i].trace);
275 return Qnil;
279 #else /* not GLYPH_DEBUG */
281 #define WINDOW_TO_FRAME_VPOS(W, VPOS) ((VPOS) + WINDOW_TOP_EDGE_LINE (W))
282 #define WINDOW_TO_FRAME_HPOS(W, HPOS) ((HPOS) + WINDOW_LEFT_EDGE_COL (W))
284 #endif /* GLYPH_DEBUG */
287 #if (defined PROFILING \
288 && (defined __FreeBSD__ || defined GNU_LINUX || defined __MINGW32__) \
289 && !HAVE___EXECUTABLE_START)
290 /* This function comes first in the Emacs executable and is used only
291 to estimate the text start for profiling. */
292 void
293 __executable_start (void)
295 emacs_abort ();
297 #endif
299 /***********************************************************************
300 Glyph Matrices
301 ***********************************************************************/
303 /* Allocate and return a glyph_matrix structure. POOL is the glyph
304 pool from which memory for the matrix should be allocated, or null
305 for window-based redisplay where no glyph pools are used. The
306 member `pool' of the glyph matrix structure returned is set to
307 POOL, the structure is otherwise zeroed. */
309 static struct glyph_matrix *
310 new_glyph_matrix (struct glyph_pool *pool)
312 struct glyph_matrix *result = xzalloc (sizeof *result);
314 /* Increment number of allocated matrices. This count is used
315 to detect memory leaks. */
316 ++glyph_matrix_count;
318 /* Set pool and return. */
319 result->pool = pool;
320 return result;
324 /* Free glyph matrix MATRIX. Passing in a null MATRIX is allowed.
326 The global counter glyph_matrix_count is decremented when a matrix
327 is freed. If the count gets negative, more structures were freed
328 than allocated, i.e. one matrix was freed more than once or a bogus
329 pointer was passed to this function.
331 If MATRIX->pool is null, this means that the matrix manages its own
332 glyph memory---this is done for matrices on X frames. Freeing the
333 matrix also frees the glyph memory in this case. */
335 static void
336 free_glyph_matrix (struct glyph_matrix *matrix)
338 if (matrix)
340 int i;
342 /* Detect the case that more matrices are freed than were
343 allocated. */
344 if (--glyph_matrix_count < 0)
345 emacs_abort ();
347 /* Free glyph memory if MATRIX owns it. */
348 if (matrix->pool == NULL)
349 for (i = 0; i < matrix->rows_allocated; ++i)
350 xfree (matrix->rows[i].glyphs[LEFT_MARGIN_AREA]);
352 /* Free row structures and the matrix itself. */
353 xfree (matrix->rows);
354 xfree (matrix);
359 /* Return the number of glyphs to reserve for a marginal area of
360 window W. TOTAL_GLYPHS is the number of glyphs in a complete
361 display line of window W. MARGIN gives the width of the marginal
362 area in canonical character units. MARGIN should be an integer
363 or a float. */
365 static int
366 margin_glyphs_to_reserve (struct window *w, int total_glyphs, Lisp_Object margin)
368 int n;
370 if (NUMBERP (margin))
372 int width = XFASTINT (w->total_cols);
373 double d = max (0, XFLOATINT (margin));
374 d = min (width / 2 - 1, d);
375 n = (int) ((double) total_glyphs / width * d);
377 else
378 n = 0;
380 return n;
383 /* Return true if ROW's hash value is correct.
384 Optimized away if ENABLE_CHECKING is not defined. */
386 static bool
387 verify_row_hash (struct glyph_row *row)
389 return row->hash == row_hash (row);
392 /* Adjust glyph matrix MATRIX on window W or on a frame to changed
393 window sizes.
395 W is null if the function is called for a frame glyph matrix.
396 Otherwise it is the window MATRIX is a member of. X and Y are the
397 indices of the first column and row of MATRIX within the frame
398 matrix, if such a matrix exists. They are zero for purely
399 window-based redisplay. DIM is the needed size of the matrix.
401 In window-based redisplay, where no frame matrices exist, glyph
402 matrices manage their own glyph storage. Otherwise, they allocate
403 storage from a common frame glyph pool which can be found in
404 MATRIX->pool.
406 The reason for this memory management strategy is to avoid complete
407 frame redraws if possible. When we allocate from a common pool, a
408 change of the location or size of a sub-matrix within the pool
409 requires a complete redisplay of the frame because we cannot easily
410 make sure that the current matrices of all windows still agree with
411 what is displayed on the screen. While this is usually fast, it
412 leads to screen flickering. */
414 static void
415 adjust_glyph_matrix (struct window *w, struct glyph_matrix *matrix, int x, int y, struct dim dim)
417 int i;
418 int new_rows;
419 bool marginal_areas_changed_p = 0;
420 bool header_line_changed_p = 0;
421 bool header_line_p = 0;
422 int left = -1, right = -1;
423 int window_width = -1, window_height = -1;
425 /* See if W had a header line that has disappeared now, or vice versa.
426 Get W's size. */
427 if (w)
429 window_box (w, -1, 0, 0, &window_width, &window_height);
431 header_line_p = WINDOW_WANTS_HEADER_LINE_P (w);
432 header_line_changed_p = header_line_p != matrix->header_line_p;
434 matrix->header_line_p = header_line_p;
436 /* If POOL is null, MATRIX is a window matrix for window-based redisplay.
437 Do nothing if MATRIX' size, position, vscroll, and marginal areas
438 haven't changed. This optimization is important because preserving
439 the matrix means preventing redisplay. */
440 if (matrix->pool == NULL)
442 left = margin_glyphs_to_reserve (w, dim.width, w->left_margin_cols);
443 right = margin_glyphs_to_reserve (w, dim.width, w->right_margin_cols);
444 eassert (left >= 0 && right >= 0);
445 marginal_areas_changed_p = (left != matrix->left_margin_glyphs
446 || right != matrix->right_margin_glyphs);
448 if (!marginal_areas_changed_p
449 && !fonts_changed_p
450 && !header_line_changed_p
451 && matrix->window_left_col == WINDOW_LEFT_EDGE_COL (w)
452 && matrix->window_top_line == WINDOW_TOP_EDGE_LINE (w)
453 && matrix->window_height == window_height
454 && matrix->window_vscroll == w->vscroll
455 && matrix->window_width == window_width)
456 return;
459 /* Enlarge MATRIX->rows if necessary. New rows are cleared. */
460 if (matrix->rows_allocated < dim.height)
462 int old_alloc = matrix->rows_allocated;
463 new_rows = dim.height - matrix->rows_allocated;
464 matrix->rows = xpalloc (matrix->rows, &matrix->rows_allocated,
465 new_rows, INT_MAX, sizeof *matrix->rows);
466 memset (matrix->rows + old_alloc, 0,
467 (matrix->rows_allocated - old_alloc) * sizeof *matrix->rows);
469 else
470 new_rows = 0;
472 /* If POOL is not null, MATRIX is a frame matrix or a window matrix
473 on a frame not using window-based redisplay. Set up pointers for
474 each row into the glyph pool. */
475 if (matrix->pool)
477 eassert (matrix->pool->glyphs);
479 if (w)
481 left = margin_glyphs_to_reserve (w, dim.width,
482 w->left_margin_cols);
483 right = margin_glyphs_to_reserve (w, dim.width,
484 w->right_margin_cols);
486 else
487 left = right = 0;
489 for (i = 0; i < dim.height; ++i)
491 struct glyph_row *row = &matrix->rows[i];
493 row->glyphs[LEFT_MARGIN_AREA]
494 = (matrix->pool->glyphs
495 + (y + i) * matrix->pool->ncolumns
496 + x);
498 if (w == NULL
499 || row == matrix->rows + dim.height - 1
500 || (row == matrix->rows && matrix->header_line_p))
502 row->glyphs[TEXT_AREA]
503 = row->glyphs[LEFT_MARGIN_AREA];
504 row->glyphs[RIGHT_MARGIN_AREA]
505 = row->glyphs[TEXT_AREA] + dim.width;
506 row->glyphs[LAST_AREA]
507 = row->glyphs[RIGHT_MARGIN_AREA];
509 else
511 row->glyphs[TEXT_AREA]
512 = row->glyphs[LEFT_MARGIN_AREA] + left;
513 row->glyphs[RIGHT_MARGIN_AREA]
514 = row->glyphs[TEXT_AREA] + dim.width - left - right;
515 row->glyphs[LAST_AREA]
516 = row->glyphs[LEFT_MARGIN_AREA] + dim.width;
520 matrix->left_margin_glyphs = left;
521 matrix->right_margin_glyphs = right;
523 else
525 /* If MATRIX->pool is null, MATRIX is responsible for managing
526 its own memory. It is a window matrix for window-based redisplay.
527 Allocate glyph memory from the heap. */
528 if (dim.width > matrix->matrix_w
529 || new_rows
530 || header_line_changed_p
531 || marginal_areas_changed_p)
533 struct glyph_row *row = matrix->rows;
534 struct glyph_row *end = row + matrix->rows_allocated;
536 while (row < end)
538 row->glyphs[LEFT_MARGIN_AREA]
539 = xnrealloc (row->glyphs[LEFT_MARGIN_AREA],
540 dim.width, sizeof (struct glyph));
542 /* The mode line never has marginal areas. */
543 if (row == matrix->rows + dim.height - 1
544 || (row == matrix->rows && matrix->header_line_p))
546 row->glyphs[TEXT_AREA]
547 = row->glyphs[LEFT_MARGIN_AREA];
548 row->glyphs[RIGHT_MARGIN_AREA]
549 = row->glyphs[TEXT_AREA] + dim.width;
550 row->glyphs[LAST_AREA]
551 = row->glyphs[RIGHT_MARGIN_AREA];
553 else
555 row->glyphs[TEXT_AREA]
556 = row->glyphs[LEFT_MARGIN_AREA] + left;
557 row->glyphs[RIGHT_MARGIN_AREA]
558 = row->glyphs[TEXT_AREA] + dim.width - left - right;
559 row->glyphs[LAST_AREA]
560 = row->glyphs[LEFT_MARGIN_AREA] + dim.width;
562 ++row;
566 eassert (left >= 0 && right >= 0);
567 matrix->left_margin_glyphs = left;
568 matrix->right_margin_glyphs = right;
571 /* Number of rows to be used by MATRIX. */
572 matrix->nrows = dim.height;
573 eassert (matrix->nrows >= 0);
575 if (w)
577 if (matrix == w->current_matrix)
579 /* Mark rows in a current matrix of a window as not having
580 valid contents. It's important to not do this for
581 desired matrices. When Emacs starts, it may already be
582 building desired matrices when this function runs. */
583 if (window_width < 0)
584 window_width = window_box_width (w, -1);
586 /* Optimize the case that only the height has changed (C-x 2,
587 upper window). Invalidate all rows that are no longer part
588 of the window. */
589 if (!marginal_areas_changed_p
590 && !header_line_changed_p
591 && new_rows == 0
592 && dim.width == matrix->matrix_w
593 && matrix->window_left_col == WINDOW_LEFT_EDGE_COL (w)
594 && matrix->window_top_line == WINDOW_TOP_EDGE_LINE (w)
595 && matrix->window_width == window_width)
597 /* Find the last row in the window. */
598 for (i = 0; i < matrix->nrows && matrix->rows[i].enabled_p; ++i)
599 if (MATRIX_ROW_BOTTOM_Y (matrix->rows + i) >= window_height)
601 ++i;
602 break;
605 /* Window end is invalid, if inside of the rows that
606 are invalidated below. */
607 if (INTEGERP (w->window_end_vpos)
608 && XFASTINT (w->window_end_vpos) >= i)
609 wset_window_end_valid (w, Qnil);
611 while (i < matrix->nrows)
612 matrix->rows[i++].enabled_p = 0;
614 else
616 for (i = 0; i < matrix->nrows; ++i)
617 matrix->rows[i].enabled_p = 0;
620 else if (matrix == w->desired_matrix)
622 /* Rows in desired matrices always have to be cleared;
623 redisplay expects this is the case when it runs, so it
624 had better be the case when we adjust matrices between
625 redisplays. */
626 for (i = 0; i < matrix->nrows; ++i)
627 matrix->rows[i].enabled_p = 0;
632 /* Remember last values to be able to optimize frame redraws. */
633 matrix->matrix_x = x;
634 matrix->matrix_y = y;
635 matrix->matrix_w = dim.width;
636 matrix->matrix_h = dim.height;
638 /* Record the top y location and height of W at the time the matrix
639 was last adjusted. This is used to optimize redisplay above. */
640 if (w)
642 matrix->window_left_col = WINDOW_LEFT_EDGE_COL (w);
643 matrix->window_top_line = WINDOW_TOP_EDGE_LINE (w);
644 matrix->window_height = window_height;
645 matrix->window_width = window_width;
646 matrix->window_vscroll = w->vscroll;
651 /* Reverse the contents of rows in MATRIX between START and END. The
652 contents of the row at END - 1 end up at START, END - 2 at START +
653 1 etc. This is part of the implementation of rotate_matrix (see
654 below). */
656 static void
657 reverse_rows (struct glyph_matrix *matrix, int start, int end)
659 int i, j;
661 for (i = start, j = end - 1; i < j; ++i, --j)
663 /* Non-ISO HP/UX compiler doesn't like auto struct
664 initialization. */
665 struct glyph_row temp;
666 temp = matrix->rows[i];
667 matrix->rows[i] = matrix->rows[j];
668 matrix->rows[j] = temp;
673 /* Rotate the contents of rows in MATRIX in the range FIRST .. LAST -
674 1 by BY positions. BY < 0 means rotate left, i.e. towards lower
675 indices. (Note: this does not copy glyphs, only glyph pointers in
676 row structures are moved around).
678 The algorithm used for rotating the vector was, I believe, first
679 described by Kernighan. See the vector R as consisting of two
680 sub-vectors AB, where A has length BY for BY >= 0. The result
681 after rotating is then BA. Reverse both sub-vectors to get ArBr
682 and reverse the result to get (ArBr)r which is BA. Similar for
683 rotating right. */
685 void
686 rotate_matrix (struct glyph_matrix *matrix, int first, int last, int by)
688 if (by < 0)
690 /* Up (rotate left, i.e. towards lower indices). */
691 by = -by;
692 reverse_rows (matrix, first, first + by);
693 reverse_rows (matrix, first + by, last);
694 reverse_rows (matrix, first, last);
696 else if (by > 0)
698 /* Down (rotate right, i.e. towards higher indices). */
699 reverse_rows (matrix, last - by, last);
700 reverse_rows (matrix, first, last - by);
701 reverse_rows (matrix, first, last);
706 /* Increment buffer positions in glyph rows of MATRIX. Do it for rows
707 with indices START <= index < END. Increment positions by DELTA/
708 DELTA_BYTES. */
710 void
711 increment_matrix_positions (struct glyph_matrix *matrix, int start, int end,
712 ptrdiff_t delta, ptrdiff_t delta_bytes)
714 /* Check that START and END are reasonable values. */
715 eassert (start >= 0 && start <= matrix->nrows);
716 eassert (end >= 0 && end <= matrix->nrows);
717 eassert (start <= end);
719 for (; start < end; ++start)
720 increment_row_positions (matrix->rows + start, delta, delta_bytes);
724 /* Clear the enable_p flags in a range of rows in glyph matrix MATRIX.
725 START and END are the row indices of the first and last + 1 row to clear. */
727 void
728 clear_glyph_matrix_rows (struct glyph_matrix *matrix, int start, int end)
730 eassert (start <= end);
731 eassert (start >= 0 && start < matrix->nrows);
732 eassert (end >= 0 && end <= matrix->nrows);
734 for (; start < end; ++start)
735 matrix->rows[start].enabled_p = 0;
739 /* Clear MATRIX.
741 Empty all rows in MATRIX by clearing their enabled_p flags.
742 The function prepare_desired_row will eventually really clear a row
743 when it sees one with a false enabled_p flag.
745 Reset update hints to default values. The only update hint
746 currently present is the flag MATRIX->no_scrolling_p. */
748 void
749 clear_glyph_matrix (struct glyph_matrix *matrix)
751 if (matrix)
753 clear_glyph_matrix_rows (matrix, 0, matrix->nrows);
754 matrix->no_scrolling_p = 0;
759 /* Shift part of the glyph matrix MATRIX of window W up or down.
760 Increment y-positions in glyph rows between START and END by DY,
761 and recompute their visible height. */
763 void
764 shift_glyph_matrix (struct window *w, struct glyph_matrix *matrix, int start, int end, int dy)
766 int min_y, max_y;
768 eassert (start <= end);
769 eassert (start >= 0 && start < matrix->nrows);
770 eassert (end >= 0 && end <= matrix->nrows);
772 min_y = WINDOW_HEADER_LINE_HEIGHT (w);
773 max_y = WINDOW_BOX_HEIGHT_NO_MODE_LINE (w);
775 for (; start < end; ++start)
777 struct glyph_row *row = &matrix->rows[start];
779 row->y += dy;
780 row->visible_height = row->height;
782 if (row->y < min_y)
783 row->visible_height -= min_y - row->y;
784 if (row->y + row->height > max_y)
785 row->visible_height -= row->y + row->height - max_y;
786 if (row->fringe_bitmap_periodic_p)
787 row->redraw_fringe_bitmaps_p = 1;
792 /* Mark all rows in current matrices of frame F as invalid. Marking
793 invalid is done by setting enabled_p to zero for all rows in a
794 current matrix. */
796 void
797 clear_current_matrices (register struct frame *f)
799 /* Clear frame current matrix, if we have one. */
800 if (f->current_matrix)
801 clear_glyph_matrix (f->current_matrix);
803 /* Clear the matrix of the menu bar window, if such a window exists.
804 The menu bar window is currently used to display menus on X when
805 no toolkit support is compiled in. */
806 if (WINDOWP (f->menu_bar_window))
807 clear_glyph_matrix (XWINDOW (f->menu_bar_window)->current_matrix);
809 /* Clear the matrix of the tool-bar window, if any. */
810 if (WINDOWP (f->tool_bar_window))
811 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
813 /* Clear current window matrices. */
814 eassert (WINDOWP (FRAME_ROOT_WINDOW (f)));
815 clear_window_matrices (XWINDOW (FRAME_ROOT_WINDOW (f)), 0);
819 /* Clear out all display lines of F for a coming redisplay. */
821 void
822 clear_desired_matrices (register struct frame *f)
824 if (f->desired_matrix)
825 clear_glyph_matrix (f->desired_matrix);
827 if (WINDOWP (f->menu_bar_window))
828 clear_glyph_matrix (XWINDOW (f->menu_bar_window)->desired_matrix);
830 if (WINDOWP (f->tool_bar_window))
831 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->desired_matrix);
833 /* Do it for window matrices. */
834 eassert (WINDOWP (FRAME_ROOT_WINDOW (f)));
835 clear_window_matrices (XWINDOW (FRAME_ROOT_WINDOW (f)), 1);
839 /* Clear matrices in window tree rooted in W. If DESIRED_P,
840 clear desired matrices, otherwise clear current matrices. */
842 static void
843 clear_window_matrices (struct window *w, bool desired_p)
845 while (w)
847 if (!NILP (w->hchild))
849 eassert (WINDOWP (w->hchild));
850 clear_window_matrices (XWINDOW (w->hchild), desired_p);
852 else if (!NILP (w->vchild))
854 eassert (WINDOWP (w->vchild));
855 clear_window_matrices (XWINDOW (w->vchild), desired_p);
857 else
859 if (desired_p)
860 clear_glyph_matrix (w->desired_matrix);
861 else
863 clear_glyph_matrix (w->current_matrix);
864 wset_window_end_valid (w, Qnil);
868 w = NILP (w->next) ? 0 : XWINDOW (w->next);
874 /***********************************************************************
875 Glyph Rows
877 See dispextern.h for an overall explanation of glyph rows.
878 ***********************************************************************/
880 /* Clear glyph row ROW. Do it in a way that makes it robust against
881 changes in the glyph_row structure, i.e. addition or removal of
882 structure members. */
884 static struct glyph_row null_row;
886 void
887 clear_glyph_row (struct glyph_row *row)
889 struct glyph *p[1 + LAST_AREA];
891 /* Save pointers. */
892 p[LEFT_MARGIN_AREA] = row->glyphs[LEFT_MARGIN_AREA];
893 p[TEXT_AREA] = row->glyphs[TEXT_AREA];
894 p[RIGHT_MARGIN_AREA] = row->glyphs[RIGHT_MARGIN_AREA];
895 p[LAST_AREA] = row->glyphs[LAST_AREA];
897 /* Clear. */
898 *row = null_row;
900 /* Restore pointers. */
901 row->glyphs[LEFT_MARGIN_AREA] = p[LEFT_MARGIN_AREA];
902 row->glyphs[TEXT_AREA] = p[TEXT_AREA];
903 row->glyphs[RIGHT_MARGIN_AREA] = p[RIGHT_MARGIN_AREA];
904 row->glyphs[LAST_AREA] = p[LAST_AREA];
906 #if 0 /* At some point, some bit-fields of struct glyph were not set,
907 which made glyphs unequal when compared with GLYPH_EQUAL_P.
908 Redisplay outputs such glyphs, and flickering effects were
909 the result. This also depended on the contents of memory
910 returned by xmalloc. If flickering happens again, activate
911 the code below. If the flickering is gone with that, chances
912 are that the flickering has the same reason as here. */
913 memset (p[0], 0, (char *) p[LAST_AREA] - (char *) p[0]);
914 #endif
918 /* Make ROW an empty, enabled row of canonical character height,
919 in window W starting at y-position Y. */
921 void
922 blank_row (struct window *w, struct glyph_row *row, int y)
924 int min_y, max_y;
926 min_y = WINDOW_HEADER_LINE_HEIGHT (w);
927 max_y = WINDOW_BOX_HEIGHT_NO_MODE_LINE (w);
929 clear_glyph_row (row);
930 row->y = y;
931 row->ascent = row->phys_ascent = 0;
932 row->height = row->phys_height = FRAME_LINE_HEIGHT (XFRAME (w->frame));
933 row->visible_height = row->height;
935 if (row->y < min_y)
936 row->visible_height -= min_y - row->y;
937 if (row->y + row->height > max_y)
938 row->visible_height -= row->y + row->height - max_y;
940 row->enabled_p = 1;
944 /* Increment buffer positions in glyph row ROW. DELTA and DELTA_BYTES
945 are the amounts by which to change positions. Note that the first
946 glyph of the text area of a row can have a buffer position even if
947 the used count of the text area is zero. Such rows display line
948 ends. */
950 static void
951 increment_row_positions (struct glyph_row *row,
952 ptrdiff_t delta, ptrdiff_t delta_bytes)
954 int area, i;
956 /* Increment start and end positions. */
957 MATRIX_ROW_START_CHARPOS (row) += delta;
958 MATRIX_ROW_START_BYTEPOS (row) += delta_bytes;
959 MATRIX_ROW_END_CHARPOS (row) += delta;
960 MATRIX_ROW_END_BYTEPOS (row) += delta_bytes;
961 CHARPOS (row->start.pos) += delta;
962 BYTEPOS (row->start.pos) += delta_bytes;
963 CHARPOS (row->end.pos) += delta;
964 BYTEPOS (row->end.pos) += delta_bytes;
966 if (!row->enabled_p)
967 return;
969 /* Increment positions in glyphs. */
970 for (area = 0; area < LAST_AREA; ++area)
971 for (i = 0; i < row->used[area]; ++i)
972 if (BUFFERP (row->glyphs[area][i].object)
973 && row->glyphs[area][i].charpos > 0)
974 row->glyphs[area][i].charpos += delta;
976 /* Capture the case of rows displaying a line end. */
977 if (row->used[TEXT_AREA] == 0
978 && MATRIX_ROW_DISPLAYS_TEXT_P (row))
979 row->glyphs[TEXT_AREA]->charpos += delta;
983 #if 0
984 /* Swap glyphs between two glyph rows A and B. This exchanges glyph
985 contents, i.e. glyph structure contents are exchanged between A and
986 B without changing glyph pointers in A and B. */
988 static void
989 swap_glyphs_in_rows (struct glyph_row *a, struct glyph_row *b)
991 int area;
993 for (area = 0; area < LAST_AREA; ++area)
995 /* Number of glyphs to swap. */
996 int max_used = max (a->used[area], b->used[area]);
998 /* Start of glyphs in area of row A. */
999 struct glyph *glyph_a = a->glyphs[area];
1001 /* End + 1 of glyphs in area of row A. */
1002 struct glyph *glyph_a_end = a->glyphs[max_used];
1004 /* Start of glyphs in area of row B. */
1005 struct glyph *glyph_b = b->glyphs[area];
1007 while (glyph_a < glyph_a_end)
1009 /* Non-ISO HP/UX compiler doesn't like auto struct
1010 initialization. */
1011 struct glyph temp;
1012 temp = *glyph_a;
1013 *glyph_a = *glyph_b;
1014 *glyph_b = temp;
1015 ++glyph_a;
1016 ++glyph_b;
1021 #endif /* 0 */
1023 /* Exchange pointers to glyph memory between glyph rows A and B. Also
1024 exchange the used[] array and the hash values of the rows, because
1025 these should all go together for the row's hash value to be
1026 correct. */
1028 static void
1029 swap_glyph_pointers (struct glyph_row *a, struct glyph_row *b)
1031 int i;
1032 unsigned hash_tem = a->hash;
1034 for (i = 0; i < LAST_AREA + 1; ++i)
1036 struct glyph *temp = a->glyphs[i];
1038 a->glyphs[i] = b->glyphs[i];
1039 b->glyphs[i] = temp;
1040 if (i < LAST_AREA)
1042 short used_tem = a->used[i];
1044 a->used[i] = b->used[i];
1045 b->used[i] = used_tem;
1048 a->hash = b->hash;
1049 b->hash = hash_tem;
1053 /* Copy glyph row structure FROM to glyph row structure TO, except
1054 that glyph pointers, the `used' counts, and the hash values in the
1055 structures are left unchanged. */
1057 static void
1058 copy_row_except_pointers (struct glyph_row *to, struct glyph_row *from)
1060 struct glyph *pointers[1 + LAST_AREA];
1061 short used[LAST_AREA];
1062 unsigned hashval;
1064 /* Save glyph pointers of TO. */
1065 memcpy (pointers, to->glyphs, sizeof to->glyphs);
1066 memcpy (used, to->used, sizeof to->used);
1067 hashval = to->hash;
1069 /* Do a structure assignment. */
1070 *to = *from;
1072 /* Restore original pointers of TO. */
1073 memcpy (to->glyphs, pointers, sizeof to->glyphs);
1074 memcpy (to->used, used, sizeof to->used);
1075 to->hash = hashval;
1079 /* Assign glyph row FROM to glyph row TO. This works like a structure
1080 assignment TO = FROM, except that glyph pointers are not copied but
1081 exchanged between TO and FROM. Pointers must be exchanged to avoid
1082 a memory leak. */
1084 static void
1085 assign_row (struct glyph_row *to, struct glyph_row *from)
1087 swap_glyph_pointers (to, from);
1088 copy_row_except_pointers (to, from);
1092 /* Test whether the glyph memory of the glyph row WINDOW_ROW, which is
1093 a row in a window matrix, is a slice of the glyph memory of the
1094 glyph row FRAME_ROW which is a row in a frame glyph matrix. Value
1095 is true if the glyph memory of WINDOW_ROW is part of the glyph
1096 memory of FRAME_ROW. */
1098 #ifdef GLYPH_DEBUG
1100 static bool
1101 glyph_row_slice_p (struct glyph_row *window_row, struct glyph_row *frame_row)
1103 struct glyph *window_glyph_start = window_row->glyphs[0];
1104 struct glyph *frame_glyph_start = frame_row->glyphs[0];
1105 struct glyph *frame_glyph_end = frame_row->glyphs[LAST_AREA];
1107 return (frame_glyph_start <= window_glyph_start
1108 && window_glyph_start < frame_glyph_end);
1111 #endif /* GLYPH_DEBUG */
1113 #if 0
1115 /* Find the row in the window glyph matrix WINDOW_MATRIX being a slice
1116 of ROW in the frame matrix FRAME_MATRIX. Value is null if no row
1117 in WINDOW_MATRIX is found satisfying the condition. */
1119 static struct glyph_row *
1120 find_glyph_row_slice (struct glyph_matrix *window_matrix,
1121 struct glyph_matrix *frame_matrix, int row)
1123 int i;
1125 eassert (row >= 0 && row < frame_matrix->nrows);
1127 for (i = 0; i < window_matrix->nrows; ++i)
1128 if (glyph_row_slice_p (window_matrix->rows + i,
1129 frame_matrix->rows + row))
1130 break;
1132 return i < window_matrix->nrows ? window_matrix->rows + i : 0;
1135 #endif /* 0 */
1137 /* Prepare ROW for display. Desired rows are cleared lazily,
1138 i.e. they are only marked as to be cleared by setting their
1139 enabled_p flag to zero. When a row is to be displayed, a prior
1140 call to this function really clears it. */
1142 void
1143 prepare_desired_row (struct glyph_row *row)
1145 if (!row->enabled_p)
1147 bool rp = row->reversed_p;
1149 clear_glyph_row (row);
1150 row->enabled_p = 1;
1151 row->reversed_p = rp;
1156 /* Return a hash code for glyph row ROW. */
1158 static int
1159 line_hash_code (struct glyph_row *row)
1161 int hash = 0;
1163 if (row->enabled_p)
1165 struct glyph *glyph = row->glyphs[TEXT_AREA];
1166 struct glyph *end = glyph + row->used[TEXT_AREA];
1168 while (glyph < end)
1170 int c = glyph->u.ch;
1171 int face_id = glyph->face_id;
1172 if (FRAME_MUST_WRITE_SPACES (SELECTED_FRAME ())) /* XXX Is SELECTED_FRAME OK here? */
1173 c -= SPACEGLYPH;
1174 hash = (((hash << 4) + (hash >> 24)) & 0x0fffffff) + c;
1175 hash = (((hash << 4) + (hash >> 24)) & 0x0fffffff) + face_id;
1176 ++glyph;
1179 if (hash == 0)
1180 hash = 1;
1183 return hash;
1187 /* Return the cost of drawing line VPOS in MATRIX. The cost equals
1188 the number of characters in the line. If must_write_spaces is
1189 zero, leading and trailing spaces are ignored. */
1191 static int
1192 line_draw_cost (struct glyph_matrix *matrix, int vpos)
1194 struct glyph_row *row = matrix->rows + vpos;
1195 struct glyph *beg = row->glyphs[TEXT_AREA];
1196 struct glyph *end = beg + row->used[TEXT_AREA];
1197 int len;
1198 Lisp_Object *glyph_table_base = GLYPH_TABLE_BASE;
1199 ptrdiff_t glyph_table_len = GLYPH_TABLE_LENGTH;
1201 /* Ignore trailing and leading spaces if we can. */
1202 if (!FRAME_MUST_WRITE_SPACES (SELECTED_FRAME ())) /* XXX Is SELECTED_FRAME OK here? */
1204 /* Skip from the end over trailing spaces. */
1205 while (end > beg && CHAR_GLYPH_SPACE_P (*(end - 1)))
1206 --end;
1208 /* All blank line. */
1209 if (end == beg)
1210 return 0;
1212 /* Skip over leading spaces. */
1213 while (CHAR_GLYPH_SPACE_P (*beg))
1214 ++beg;
1217 /* If we don't have a glyph-table, each glyph is one character,
1218 so return the number of glyphs. */
1219 if (glyph_table_base == 0)
1220 len = end - beg;
1221 else
1223 /* Otherwise, scan the glyphs and accumulate their total length
1224 in LEN. */
1225 len = 0;
1226 while (beg < end)
1228 GLYPH g;
1230 SET_GLYPH_FROM_CHAR_GLYPH (g, *beg);
1232 if (GLYPH_INVALID_P (g)
1233 || GLYPH_SIMPLE_P (glyph_table_base, glyph_table_len, g))
1234 len += 1;
1235 else
1236 len += GLYPH_LENGTH (glyph_table_base, g);
1238 ++beg;
1242 return len;
1246 /* Return true if the glyph rows A and B have equal contents.
1247 MOUSE_FACE_P means compare the mouse_face_p flags of A and B, too. */
1249 static bool
1250 row_equal_p (struct glyph_row *a, struct glyph_row *b, bool mouse_face_p)
1252 eassert (verify_row_hash (a));
1253 eassert (verify_row_hash (b));
1255 if (a == b)
1256 return 1;
1257 else if (a->hash != b->hash)
1258 return 0;
1259 else
1261 struct glyph *a_glyph, *b_glyph, *a_end;
1262 int area;
1264 if (mouse_face_p && a->mouse_face_p != b->mouse_face_p)
1265 return 0;
1267 /* Compare glyphs. */
1268 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
1270 if (a->used[area] != b->used[area])
1271 return 0;
1273 a_glyph = a->glyphs[area];
1274 a_end = a_glyph + a->used[area];
1275 b_glyph = b->glyphs[area];
1277 while (a_glyph < a_end
1278 && GLYPH_EQUAL_P (a_glyph, b_glyph))
1279 ++a_glyph, ++b_glyph;
1281 if (a_glyph != a_end)
1282 return 0;
1285 if (a->fill_line_p != b->fill_line_p
1286 || a->cursor_in_fringe_p != b->cursor_in_fringe_p
1287 || a->left_fringe_bitmap != b->left_fringe_bitmap
1288 || a->left_fringe_face_id != b->left_fringe_face_id
1289 || a->left_fringe_offset != b->left_fringe_offset
1290 || a->right_fringe_bitmap != b->right_fringe_bitmap
1291 || a->right_fringe_face_id != b->right_fringe_face_id
1292 || a->right_fringe_offset != b->right_fringe_offset
1293 || a->fringe_bitmap_periodic_p != b->fringe_bitmap_periodic_p
1294 || a->overlay_arrow_bitmap != b->overlay_arrow_bitmap
1295 || a->exact_window_width_line_p != b->exact_window_width_line_p
1296 || a->overlapped_p != b->overlapped_p
1297 || (MATRIX_ROW_CONTINUATION_LINE_P (a)
1298 != MATRIX_ROW_CONTINUATION_LINE_P (b))
1299 || a->reversed_p != b->reversed_p
1300 /* Different partially visible characters on left margin. */
1301 || a->x != b->x
1302 /* Different height. */
1303 || a->ascent != b->ascent
1304 || a->phys_ascent != b->phys_ascent
1305 || a->phys_height != b->phys_height
1306 || a->visible_height != b->visible_height)
1307 return 0;
1310 return 1;
1315 /***********************************************************************
1316 Glyph Pool
1318 See dispextern.h for an overall explanation of glyph pools.
1319 ***********************************************************************/
1321 /* Allocate a glyph_pool structure. The structure returned is
1322 initialized with zeros. The global variable glyph_pool_count is
1323 incremented for each pool allocated. */
1325 static struct glyph_pool *
1326 new_glyph_pool (void)
1328 struct glyph_pool *result = xzalloc (sizeof *result);
1330 /* For memory leak and double deletion checking. */
1331 ++glyph_pool_count;
1333 return result;
1337 /* Free a glyph_pool structure POOL. The function may be called with
1338 a null POOL pointer. The global variable glyph_pool_count is
1339 decremented with every pool structure freed. If this count gets
1340 negative, more structures were freed than allocated, i.e. one
1341 structure must have been freed more than once or a bogus pointer
1342 was passed to free_glyph_pool. */
1344 static void
1345 free_glyph_pool (struct glyph_pool *pool)
1347 if (pool)
1349 /* More freed than allocated? */
1350 --glyph_pool_count;
1351 eassert (glyph_pool_count >= 0);
1353 xfree (pool->glyphs);
1354 xfree (pool);
1359 /* Enlarge a glyph pool POOL. MATRIX_DIM gives the number of rows and
1360 columns we need. This function never shrinks a pool. The only
1361 case in which this would make sense, would be when a frame's size
1362 is changed from a large value to a smaller one. But, if someone
1363 does it once, we can expect that he will do it again.
1365 Return true if the pool changed in a way which makes
1366 re-adjusting window glyph matrices necessary. */
1368 static bool
1369 realloc_glyph_pool (struct glyph_pool *pool, struct dim matrix_dim)
1371 ptrdiff_t needed;
1372 bool changed_p;
1374 changed_p = (pool->glyphs == 0
1375 || matrix_dim.height != pool->nrows
1376 || matrix_dim.width != pool->ncolumns);
1378 /* Enlarge the glyph pool. */
1379 needed = matrix_dim.width;
1380 if (INT_MULTIPLY_OVERFLOW (needed, matrix_dim.height))
1381 memory_full (SIZE_MAX);
1382 needed *= matrix_dim.height;
1383 if (needed > pool->nglyphs)
1385 ptrdiff_t old_nglyphs = pool->nglyphs;
1386 pool->glyphs = xpalloc (pool->glyphs, &pool->nglyphs,
1387 needed - old_nglyphs, -1, sizeof *pool->glyphs);
1388 memset (pool->glyphs + old_nglyphs, 0,
1389 (pool->nglyphs - old_nglyphs) * sizeof *pool->glyphs);
1392 /* Remember the number of rows and columns because (a) we use them
1393 to do sanity checks, and (b) the number of columns determines
1394 where rows in the frame matrix start---this must be available to
1395 determine pointers to rows of window sub-matrices. */
1396 pool->nrows = matrix_dim.height;
1397 pool->ncolumns = matrix_dim.width;
1399 return changed_p;
1404 /***********************************************************************
1405 Debug Code
1406 ***********************************************************************/
1408 #ifdef GLYPH_DEBUG
1411 /* Flush standard output. This is sometimes useful to call from the debugger.
1412 XXX Maybe this should be changed to flush the current terminal instead of
1413 stdout.
1416 void flush_stdout (void) EXTERNALLY_VISIBLE;
1418 void
1419 flush_stdout (void)
1421 fflush (stdout);
1425 /* Check that no glyph pointers have been lost in MATRIX. If a
1426 pointer has been lost, e.g. by using a structure assignment between
1427 rows, at least one pointer must occur more than once in the rows of
1428 MATRIX. */
1430 void
1431 check_matrix_pointer_lossage (struct glyph_matrix *matrix)
1433 int i, j;
1435 for (i = 0; i < matrix->nrows; ++i)
1436 for (j = 0; j < matrix->nrows; ++j)
1437 eassert (i == j
1438 || (matrix->rows[i].glyphs[TEXT_AREA]
1439 != matrix->rows[j].glyphs[TEXT_AREA]));
1443 /* Get a pointer to glyph row ROW in MATRIX, with bounds checks. */
1445 struct glyph_row *
1446 matrix_row (struct glyph_matrix *matrix, int row)
1448 eassert (matrix && matrix->rows);
1449 eassert (row >= 0 && row < matrix->nrows);
1451 /* That's really too slow for normal testing because this function
1452 is called almost everywhere. Although---it's still astonishingly
1453 fast, so it is valuable to have for debugging purposes. */
1454 #if 0
1455 check_matrix_pointer_lossage (matrix);
1456 #endif
1458 return matrix->rows + row;
1462 #if 0 /* This function makes invalid assumptions when text is
1463 partially invisible. But it might come handy for debugging
1464 nevertheless. */
1466 /* Check invariants that must hold for an up to date current matrix of
1467 window W. */
1469 static void
1470 check_matrix_invariants (struct window *w)
1472 struct glyph_matrix *matrix = w->current_matrix;
1473 int yb = window_text_bottom_y (w);
1474 struct glyph_row *row = matrix->rows;
1475 struct glyph_row *last_text_row = NULL;
1476 struct buffer *saved = current_buffer;
1477 struct buffer *buffer = XBUFFER (w->buffer);
1478 int c;
1480 /* This can sometimes happen for a fresh window. */
1481 if (matrix->nrows < 2)
1482 return;
1484 set_buffer_temp (buffer);
1486 /* Note: last row is always reserved for the mode line. */
1487 while (MATRIX_ROW_DISPLAYS_TEXT_P (row)
1488 && MATRIX_ROW_BOTTOM_Y (row) < yb)
1490 struct glyph_row *next = row + 1;
1492 if (MATRIX_ROW_DISPLAYS_TEXT_P (row))
1493 last_text_row = row;
1495 /* Check that character and byte positions are in sync. */
1496 eassert (MATRIX_ROW_START_BYTEPOS (row)
1497 == CHAR_TO_BYTE (MATRIX_ROW_START_CHARPOS (row)));
1498 eassert (BYTEPOS (row->start.pos)
1499 == CHAR_TO_BYTE (CHARPOS (row->start.pos)));
1501 /* CHAR_TO_BYTE aborts when invoked for a position > Z. We can
1502 have such a position temporarily in case of a minibuffer
1503 displaying something like `[Sole completion]' at its end. */
1504 if (MATRIX_ROW_END_CHARPOS (row) < BUF_ZV (current_buffer))
1506 eassert (MATRIX_ROW_END_BYTEPOS (row)
1507 == CHAR_TO_BYTE (MATRIX_ROW_END_CHARPOS (row)));
1508 eassert (BYTEPOS (row->end.pos)
1509 == CHAR_TO_BYTE (CHARPOS (row->end.pos)));
1512 /* Check that end position of `row' is equal to start position
1513 of next row. */
1514 if (next->enabled_p && MATRIX_ROW_DISPLAYS_TEXT_P (next))
1516 eassert (MATRIX_ROW_END_CHARPOS (row)
1517 == MATRIX_ROW_START_CHARPOS (next));
1518 eassert (MATRIX_ROW_END_BYTEPOS (row)
1519 == MATRIX_ROW_START_BYTEPOS (next));
1520 eassert (CHARPOS (row->end.pos) == CHARPOS (next->start.pos));
1521 eassert (BYTEPOS (row->end.pos) == BYTEPOS (next->start.pos));
1523 row = next;
1526 eassert (w->current_matrix->nrows == w->desired_matrix->nrows);
1527 eassert (w->desired_matrix->rows != NULL);
1528 set_buffer_temp (saved);
1531 #endif /* 0 */
1533 #endif /* GLYPH_DEBUG */
1537 /**********************************************************************
1538 Allocating/ Adjusting Glyph Matrices
1539 **********************************************************************/
1541 /* Allocate glyph matrices over a window tree for a frame-based
1542 redisplay
1544 X and Y are column/row within the frame glyph matrix where
1545 sub-matrices for the window tree rooted at WINDOW must be
1546 allocated. DIM_ONLY_P means that the caller of this
1547 function is only interested in the result matrix dimension, and
1548 matrix adjustments should not be performed.
1550 The function returns the total width/height of the sub-matrices of
1551 the window tree. If called on a frame root window, the computation
1552 will take the mini-buffer window into account.
1554 *WINDOW_CHANGE_FLAGS is set to a bit mask with bits
1556 NEW_LEAF_MATRIX set if any window in the tree did not have a
1557 glyph matrices yet, and
1559 CHANGED_LEAF_MATRIX set if the dimension or location of a matrix of
1560 any window in the tree will be changed or have been changed (see
1561 DIM_ONLY_P)
1563 *WINDOW_CHANGE_FLAGS must be initialized by the caller of this
1564 function.
1566 Windows are arranged into chains of windows on the same level
1567 through the next fields of window structures. Such a level can be
1568 either a sequence of horizontally adjacent windows from left to
1569 right, or a sequence of vertically adjacent windows from top to
1570 bottom. Each window in a horizontal sequence can be either a leaf
1571 window or a vertical sequence; a window in a vertical sequence can
1572 be either a leaf or a horizontal sequence. All windows in a
1573 horizontal sequence have the same height, and all windows in a
1574 vertical sequence have the same width.
1576 This function uses, for historical reasons, a more general
1577 algorithm to determine glyph matrix dimensions that would be
1578 necessary.
1580 The matrix height of a horizontal sequence is determined by the
1581 maximum height of any matrix in the sequence. The matrix width of
1582 a horizontal sequence is computed by adding up matrix widths of
1583 windows in the sequence.
1585 |<------- result width ------->|
1586 +---------+----------+---------+ ---
1587 | | | | |
1588 | | | |
1589 +---------+ | | result height
1590 | +---------+
1591 | | |
1592 +----------+ ---
1594 The matrix width of a vertical sequence is the maximum matrix width
1595 of any window in the sequence. Its height is computed by adding up
1596 matrix heights of windows in the sequence.
1598 |<---- result width -->|
1599 +---------+ ---
1600 | | |
1601 | | |
1602 +---------+--+ |
1603 | | |
1604 | | result height
1606 +------------+---------+ |
1607 | | |
1608 | | |
1609 +------------+---------+ --- */
1611 /* Bit indicating that a new matrix will be allocated or has been
1612 allocated. */
1614 #define NEW_LEAF_MATRIX (1 << 0)
1616 /* Bit indicating that a matrix will or has changed its location or
1617 size. */
1619 #define CHANGED_LEAF_MATRIX (1 << 1)
1621 static struct dim
1622 allocate_matrices_for_frame_redisplay (Lisp_Object window, int x, int y,
1623 bool dim_only_p, int *window_change_flags)
1625 struct frame *f = XFRAME (WINDOW_FRAME (XWINDOW (window)));
1626 int x0 = x, y0 = y;
1627 int wmax = 0, hmax = 0;
1628 struct dim total;
1629 struct dim dim;
1630 struct window *w;
1631 bool in_horz_combination_p;
1633 /* What combination is WINDOW part of? Compute this once since the
1634 result is the same for all windows in the `next' chain. The
1635 special case of a root window (parent equal to nil) is treated
1636 like a vertical combination because a root window's `next'
1637 points to the mini-buffer window, if any, which is arranged
1638 vertically below other windows. */
1639 in_horz_combination_p
1640 = (!NILP (XWINDOW (window)->parent)
1641 && !NILP (XWINDOW (XWINDOW (window)->parent)->hchild));
1643 /* For WINDOW and all windows on the same level. */
1646 w = XWINDOW (window);
1648 /* Get the dimension of the window sub-matrix for W, depending
1649 on whether this is a combination or a leaf window. */
1650 if (!NILP (w->hchild))
1651 dim = allocate_matrices_for_frame_redisplay (w->hchild, x, y,
1652 dim_only_p,
1653 window_change_flags);
1654 else if (!NILP (w->vchild))
1655 dim = allocate_matrices_for_frame_redisplay (w->vchild, x, y,
1656 dim_only_p,
1657 window_change_flags);
1658 else
1660 /* If not already done, allocate sub-matrix structures. */
1661 if (w->desired_matrix == NULL)
1663 w->desired_matrix = new_glyph_matrix (f->desired_pool);
1664 w->current_matrix = new_glyph_matrix (f->current_pool);
1665 *window_change_flags |= NEW_LEAF_MATRIX;
1668 /* Width and height MUST be chosen so that there are no
1669 holes in the frame matrix. */
1670 dim.width = required_matrix_width (w);
1671 dim.height = required_matrix_height (w);
1673 /* Will matrix be re-allocated? */
1674 if (x != w->desired_matrix->matrix_x
1675 || y != w->desired_matrix->matrix_y
1676 || dim.width != w->desired_matrix->matrix_w
1677 || dim.height != w->desired_matrix->matrix_h
1678 || (margin_glyphs_to_reserve (w, dim.width,
1679 w->left_margin_cols)
1680 != w->desired_matrix->left_margin_glyphs)
1681 || (margin_glyphs_to_reserve (w, dim.width,
1682 w->right_margin_cols)
1683 != w->desired_matrix->right_margin_glyphs))
1684 *window_change_flags |= CHANGED_LEAF_MATRIX;
1686 /* Actually change matrices, if allowed. Do not consider
1687 CHANGED_LEAF_MATRIX computed above here because the pool
1688 may have been changed which we don't now here. We trust
1689 that we only will be called with DIM_ONLY_P when
1690 necessary. */
1691 if (!dim_only_p)
1693 adjust_glyph_matrix (w, w->desired_matrix, x, y, dim);
1694 adjust_glyph_matrix (w, w->current_matrix, x, y, dim);
1698 /* If we are part of a horizontal combination, advance x for
1699 windows to the right of W; otherwise advance y for windows
1700 below W. */
1701 if (in_horz_combination_p)
1702 x += dim.width;
1703 else
1704 y += dim.height;
1706 /* Remember maximum glyph matrix dimensions. */
1707 wmax = max (wmax, dim.width);
1708 hmax = max (hmax, dim.height);
1710 /* Next window on same level. */
1711 window = w->next;
1713 while (!NILP (window));
1715 /* Set `total' to the total glyph matrix dimension of this window
1716 level. In a vertical combination, the width is the width of the
1717 widest window; the height is the y we finally reached, corrected
1718 by the y we started with. In a horizontal combination, the total
1719 height is the height of the tallest window, and the width is the
1720 x we finally reached, corrected by the x we started with. */
1721 if (in_horz_combination_p)
1723 total.width = x - x0;
1724 total.height = hmax;
1726 else
1728 total.width = wmax;
1729 total.height = y - y0;
1732 return total;
1736 /* Return the required height of glyph matrices for window W. */
1738 static int
1739 required_matrix_height (struct window *w)
1741 #ifdef HAVE_WINDOW_SYSTEM
1742 struct frame *f = XFRAME (w->frame);
1744 if (FRAME_WINDOW_P (f))
1746 int ch_height = FRAME_SMALLEST_FONT_HEIGHT (f);
1747 int window_pixel_height = window_box_height (w) + eabs (w->vscroll);
1748 return (((window_pixel_height + ch_height - 1)
1749 / ch_height) * w->nrows_scale_factor
1750 /* One partially visible line at the top and
1751 bottom of the window. */
1753 /* 2 for header and mode line. */
1754 + 2);
1756 #endif /* HAVE_WINDOW_SYSTEM */
1758 return WINDOW_TOTAL_LINES (w);
1762 /* Return the required width of glyph matrices for window W. */
1764 static int
1765 required_matrix_width (struct window *w)
1767 #ifdef HAVE_WINDOW_SYSTEM
1768 struct frame *f = XFRAME (w->frame);
1769 if (FRAME_WINDOW_P (f))
1771 int ch_width = FRAME_SMALLEST_CHAR_WIDTH (f);
1772 int window_pixel_width = WINDOW_TOTAL_WIDTH (w);
1774 /* Compute number of glyphs needed in a glyph row. */
1775 return (((window_pixel_width + ch_width - 1)
1776 / ch_width) * w->ncols_scale_factor
1777 /* 2 partially visible columns in the text area. */
1779 /* One partially visible column at the right
1780 edge of each marginal area. */
1781 + 1 + 1);
1783 #endif /* HAVE_WINDOW_SYSTEM */
1785 return XINT (w->total_cols);
1789 /* Allocate window matrices for window-based redisplay. W is the
1790 window whose matrices must be allocated/reallocated. */
1792 static void
1793 allocate_matrices_for_window_redisplay (struct window *w)
1795 while (w)
1797 if (!NILP (w->vchild))
1798 allocate_matrices_for_window_redisplay (XWINDOW (w->vchild));
1799 else if (!NILP (w->hchild))
1800 allocate_matrices_for_window_redisplay (XWINDOW (w->hchild));
1801 else
1803 /* W is a leaf window. */
1804 struct dim dim;
1806 /* If matrices are not yet allocated, allocate them now. */
1807 if (w->desired_matrix == NULL)
1809 w->desired_matrix = new_glyph_matrix (NULL);
1810 w->current_matrix = new_glyph_matrix (NULL);
1813 dim.width = required_matrix_width (w);
1814 dim.height = required_matrix_height (w);
1815 adjust_glyph_matrix (w, w->desired_matrix, 0, 0, dim);
1816 adjust_glyph_matrix (w, w->current_matrix, 0, 0, dim);
1819 w = NILP (w->next) ? NULL : XWINDOW (w->next);
1824 /* Re-allocate/ re-compute glyph matrices on frame F. If F is null,
1825 do it for all frames; otherwise do it just for the given frame.
1826 This function must be called when a new frame is created, its size
1827 changes, or its window configuration changes. */
1829 void
1830 adjust_glyphs (struct frame *f)
1832 /* Block input so that expose events and other events that access
1833 glyph matrices are not processed while we are changing them. */
1834 block_input ();
1836 if (f)
1837 adjust_frame_glyphs (f);
1838 else
1840 Lisp_Object tail, lisp_frame;
1842 FOR_EACH_FRAME (tail, lisp_frame)
1843 adjust_frame_glyphs (XFRAME (lisp_frame));
1846 unblock_input ();
1849 /* Allocate/reallocate glyph matrices of a single frame F. */
1851 static void
1852 adjust_frame_glyphs (struct frame *f)
1854 if (FRAME_WINDOW_P (f))
1855 adjust_frame_glyphs_for_window_redisplay (f);
1856 else
1857 adjust_frame_glyphs_for_frame_redisplay (f);
1859 /* Don't forget the message buffer and the buffer for
1860 decode_mode_spec. */
1861 adjust_frame_message_buffer (f);
1862 adjust_decode_mode_spec_buffer (f);
1864 f->glyphs_initialized_p = 1;
1867 /* Return true if any window in the tree has nonzero window margins. See
1868 the hack at the end of adjust_frame_glyphs_for_frame_redisplay. */
1869 static bool
1870 showing_window_margins_p (struct window *w)
1872 while (w)
1874 if (!NILP (w->hchild))
1876 if (showing_window_margins_p (XWINDOW (w->hchild)))
1877 return 1;
1879 else if (!NILP (w->vchild))
1881 if (showing_window_margins_p (XWINDOW (w->vchild)))
1882 return 1;
1884 else if (!NILP (w->left_margin_cols)
1885 || !NILP (w->right_margin_cols))
1886 return 1;
1888 w = NILP (w->next) ? 0 : XWINDOW (w->next);
1890 return 0;
1894 /* In the window tree with root W, build current matrices of leaf
1895 windows from the frame's current matrix. */
1897 static void
1898 fake_current_matrices (Lisp_Object window)
1900 struct window *w;
1902 for (; !NILP (window); window = w->next)
1904 w = XWINDOW (window);
1906 if (!NILP (w->hchild))
1907 fake_current_matrices (w->hchild);
1908 else if (!NILP (w->vchild))
1909 fake_current_matrices (w->vchild);
1910 else
1912 int i;
1913 struct frame *f = XFRAME (w->frame);
1914 struct glyph_matrix *m = w->current_matrix;
1915 struct glyph_matrix *fm = f->current_matrix;
1917 eassert (m->matrix_h == WINDOW_TOTAL_LINES (w));
1918 eassert (m->matrix_w == WINDOW_TOTAL_COLS (w));
1920 for (i = 0; i < m->matrix_h; ++i)
1922 struct glyph_row *r = m->rows + i;
1923 struct glyph_row *fr = fm->rows + i + WINDOW_TOP_EDGE_LINE (w);
1925 eassert (r->glyphs[TEXT_AREA] >= fr->glyphs[TEXT_AREA]
1926 && r->glyphs[LAST_AREA] <= fr->glyphs[LAST_AREA]);
1928 r->enabled_p = fr->enabled_p;
1929 if (r->enabled_p)
1931 r->used[LEFT_MARGIN_AREA] = m->left_margin_glyphs;
1932 r->used[RIGHT_MARGIN_AREA] = m->right_margin_glyphs;
1933 r->used[TEXT_AREA] = (m->matrix_w
1934 - r->used[LEFT_MARGIN_AREA]
1935 - r->used[RIGHT_MARGIN_AREA]);
1936 r->mode_line_p = 0;
1944 /* Save away the contents of frame F's current frame matrix. Value is
1945 a glyph matrix holding the contents of F's current frame matrix. */
1947 static struct glyph_matrix *
1948 save_current_matrix (struct frame *f)
1950 int i;
1951 struct glyph_matrix *saved = xzalloc (sizeof *saved);
1952 saved->nrows = f->current_matrix->nrows;
1953 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
1955 for (i = 0; i < saved->nrows; ++i)
1957 struct glyph_row *from = f->current_matrix->rows + i;
1958 struct glyph_row *to = saved->rows + i;
1959 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
1960 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
1961 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
1962 to->used[TEXT_AREA] = from->used[TEXT_AREA];
1965 return saved;
1969 /* Restore the contents of frame F's current frame matrix from SAVED,
1970 and free memory associated with SAVED. */
1972 static void
1973 restore_current_matrix (struct frame *f, struct glyph_matrix *saved)
1975 int i;
1977 for (i = 0; i < saved->nrows; ++i)
1979 struct glyph_row *from = saved->rows + i;
1980 struct glyph_row *to = f->current_matrix->rows + i;
1981 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
1982 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
1983 to->used[TEXT_AREA] = from->used[TEXT_AREA];
1984 xfree (from->glyphs[TEXT_AREA]);
1987 xfree (saved->rows);
1988 xfree (saved);
1993 /* Allocate/reallocate glyph matrices of a single frame F for
1994 frame-based redisplay. */
1996 static void
1997 adjust_frame_glyphs_for_frame_redisplay (struct frame *f)
1999 struct dim matrix_dim;
2000 bool pool_changed_p;
2001 int window_change_flags;
2002 int top_window_y;
2004 if (!FRAME_LIVE_P (f))
2005 return;
2007 top_window_y = FRAME_TOP_MARGIN (f);
2009 /* Allocate glyph pool structures if not already done. */
2010 if (f->desired_pool == NULL)
2012 f->desired_pool = new_glyph_pool ();
2013 f->current_pool = new_glyph_pool ();
2016 /* Allocate frames matrix structures if needed. */
2017 if (f->desired_matrix == NULL)
2019 f->desired_matrix = new_glyph_matrix (f->desired_pool);
2020 f->current_matrix = new_glyph_matrix (f->current_pool);
2023 /* Compute window glyph matrices. (This takes the mini-buffer
2024 window into account). The result is the size of the frame glyph
2025 matrix needed. The variable window_change_flags is set to a bit
2026 mask indicating whether new matrices will be allocated or
2027 existing matrices change their size or location within the frame
2028 matrix. */
2029 window_change_flags = 0;
2030 matrix_dim
2031 = allocate_matrices_for_frame_redisplay (FRAME_ROOT_WINDOW (f),
2032 0, top_window_y,
2034 &window_change_flags);
2036 /* Add in menu bar lines, if any. */
2037 matrix_dim.height += top_window_y;
2039 /* Enlarge pools as necessary. */
2040 pool_changed_p = realloc_glyph_pool (f->desired_pool, matrix_dim);
2041 realloc_glyph_pool (f->current_pool, matrix_dim);
2043 /* Set up glyph pointers within window matrices. Do this only if
2044 absolutely necessary since it requires a frame redraw. */
2045 if (pool_changed_p || window_change_flags)
2047 /* Do it for window matrices. */
2048 allocate_matrices_for_frame_redisplay (FRAME_ROOT_WINDOW (f),
2049 0, top_window_y, 0,
2050 &window_change_flags);
2052 /* Size of frame matrices must equal size of frame. Note
2053 that we are called for X frames with window widths NOT equal
2054 to the frame width (from CHANGE_FRAME_SIZE_1). */
2055 eassert (matrix_dim.width == FRAME_COLS (f)
2056 && matrix_dim.height == FRAME_LINES (f));
2058 /* Pointers to glyph memory in glyph rows are exchanged during
2059 the update phase of redisplay, which means in general that a
2060 frame's current matrix consists of pointers into both the
2061 desired and current glyph pool of the frame. Adjusting a
2062 matrix sets the frame matrix up so that pointers are all into
2063 the same pool. If we want to preserve glyph contents of the
2064 current matrix over a call to adjust_glyph_matrix, we must
2065 make a copy of the current glyphs, and restore the current
2066 matrix' contents from that copy. */
2067 if (display_completed
2068 && !FRAME_GARBAGED_P (f)
2069 && matrix_dim.width == f->current_matrix->matrix_w
2070 && matrix_dim.height == f->current_matrix->matrix_h
2071 /* For some reason, the frame glyph matrix gets corrupted if
2072 any of the windows contain margins. I haven't been able
2073 to hunt down the reason, but for the moment this prevents
2074 the problem from manifesting. -- cyd */
2075 && !showing_window_margins_p (XWINDOW (FRAME_ROOT_WINDOW (f))))
2077 struct glyph_matrix *copy = save_current_matrix (f);
2078 adjust_glyph_matrix (NULL, f->desired_matrix, 0, 0, matrix_dim);
2079 adjust_glyph_matrix (NULL, f->current_matrix, 0, 0, matrix_dim);
2080 restore_current_matrix (f, copy);
2081 fake_current_matrices (FRAME_ROOT_WINDOW (f));
2083 else
2085 adjust_glyph_matrix (NULL, f->desired_matrix, 0, 0, matrix_dim);
2086 adjust_glyph_matrix (NULL, f->current_matrix, 0, 0, matrix_dim);
2087 SET_FRAME_GARBAGED (f);
2093 /* Allocate/reallocate glyph matrices of a single frame F for
2094 window-based redisplay. */
2096 static void
2097 adjust_frame_glyphs_for_window_redisplay (struct frame *f)
2099 eassert (FRAME_WINDOW_P (f) && FRAME_LIVE_P (f));
2101 /* Allocate/reallocate window matrices. */
2102 allocate_matrices_for_window_redisplay (XWINDOW (FRAME_ROOT_WINDOW (f)));
2104 #ifdef HAVE_X_WINDOWS
2105 /* Allocate/ reallocate matrices of the dummy window used to display
2106 the menu bar under X when no X toolkit support is available. */
2107 #if ! defined (USE_X_TOOLKIT) && ! defined (USE_GTK)
2109 /* Allocate a dummy window if not already done. */
2110 struct window *w;
2111 if (NILP (f->menu_bar_window))
2113 Lisp_Object frame;
2114 fset_menu_bar_window (f, make_window ());
2115 w = XWINDOW (f->menu_bar_window);
2116 XSETFRAME (frame, f);
2117 wset_frame (w, frame);
2118 w->pseudo_window_p = 1;
2120 else
2121 w = XWINDOW (f->menu_bar_window);
2123 /* Set window dimensions to frame dimensions and allocate or
2124 adjust glyph matrices of W. */
2125 wset_top_line (w, make_number (0));
2126 wset_left_col (w, make_number (0));
2127 wset_total_lines (w, make_number (FRAME_MENU_BAR_LINES (f)));
2128 wset_total_cols (w, make_number (FRAME_TOTAL_COLS (f)));
2129 allocate_matrices_for_window_redisplay (w);
2131 #endif /* not USE_X_TOOLKIT && not USE_GTK */
2132 #endif /* HAVE_X_WINDOWS */
2134 #ifndef USE_GTK
2136 /* Allocate/ reallocate matrices of the tool bar window. If we
2137 don't have a tool bar window yet, make one. */
2138 struct window *w;
2139 if (NILP (f->tool_bar_window))
2141 Lisp_Object frame;
2142 fset_tool_bar_window (f, make_window ());
2143 w = XWINDOW (f->tool_bar_window);
2144 XSETFRAME (frame, f);
2145 wset_frame (w, frame);
2146 w->pseudo_window_p = 1;
2148 else
2149 w = XWINDOW (f->tool_bar_window);
2151 wset_top_line (w, make_number (FRAME_MENU_BAR_LINES (f)));
2152 wset_left_col (w, make_number (0));
2153 wset_total_lines (w, make_number (FRAME_TOOL_BAR_LINES (f)));
2154 wset_total_cols (w, make_number (FRAME_TOTAL_COLS (f)));
2155 allocate_matrices_for_window_redisplay (w);
2157 #endif
2161 /* Adjust/ allocate message buffer of frame F.
2163 Note that the message buffer is never freed. Since I could not
2164 find a free in 19.34, I assume that freeing it would be
2165 problematic in some way and don't do it either.
2167 (Implementation note: It should be checked if we can free it
2168 eventually without causing trouble). */
2170 static void
2171 adjust_frame_message_buffer (struct frame *f)
2173 FRAME_MESSAGE_BUF (f) = xrealloc (FRAME_MESSAGE_BUF (f),
2174 FRAME_MESSAGE_BUF_SIZE (f) + 1);
2178 /* Re-allocate buffer for decode_mode_spec on frame F. */
2180 static void
2181 adjust_decode_mode_spec_buffer (struct frame *f)
2183 f->decode_mode_spec_buffer = xrealloc (f->decode_mode_spec_buffer,
2184 FRAME_MESSAGE_BUF_SIZE (f) + 1);
2189 /**********************************************************************
2190 Freeing Glyph Matrices
2191 **********************************************************************/
2193 /* Free glyph memory for a frame F. F may be null. This function can
2194 be called for the same frame more than once. The root window of
2195 F may be nil when this function is called. This is the case when
2196 the function is called when F is destroyed. */
2198 void
2199 free_glyphs (struct frame *f)
2201 if (f && f->glyphs_initialized_p)
2203 /* Block interrupt input so that we don't get surprised by an X
2204 event while we're in an inconsistent state. */
2205 block_input ();
2206 f->glyphs_initialized_p = 0;
2208 /* Release window sub-matrices. */
2209 if (!NILP (f->root_window))
2210 free_window_matrices (XWINDOW (f->root_window));
2212 /* Free the dummy window for menu bars without X toolkit and its
2213 glyph matrices. */
2214 if (!NILP (f->menu_bar_window))
2216 struct window *w = XWINDOW (f->menu_bar_window);
2217 free_glyph_matrix (w->desired_matrix);
2218 free_glyph_matrix (w->current_matrix);
2219 w->desired_matrix = w->current_matrix = NULL;
2220 fset_menu_bar_window (f, Qnil);
2223 /* Free the tool bar window and its glyph matrices. */
2224 if (!NILP (f->tool_bar_window))
2226 struct window *w = XWINDOW (f->tool_bar_window);
2227 free_glyph_matrix (w->desired_matrix);
2228 free_glyph_matrix (w->current_matrix);
2229 w->desired_matrix = w->current_matrix = NULL;
2230 fset_tool_bar_window (f, Qnil);
2233 /* Release frame glyph matrices. Reset fields to zero in
2234 case we are called a second time. */
2235 if (f->desired_matrix)
2237 free_glyph_matrix (f->desired_matrix);
2238 free_glyph_matrix (f->current_matrix);
2239 f->desired_matrix = f->current_matrix = NULL;
2242 /* Release glyph pools. */
2243 if (f->desired_pool)
2245 free_glyph_pool (f->desired_pool);
2246 free_glyph_pool (f->current_pool);
2247 f->desired_pool = f->current_pool = NULL;
2250 unblock_input ();
2255 /* Free glyph sub-matrices in the window tree rooted at W. This
2256 function may be called with a null pointer, and it may be called on
2257 the same tree more than once. */
2259 void
2260 free_window_matrices (struct window *w)
2262 while (w)
2264 if (!NILP (w->hchild))
2265 free_window_matrices (XWINDOW (w->hchild));
2266 else if (!NILP (w->vchild))
2267 free_window_matrices (XWINDOW (w->vchild));
2268 else
2270 /* This is a leaf window. Free its memory and reset fields
2271 to zero in case this function is called a second time for
2272 W. */
2273 free_glyph_matrix (w->current_matrix);
2274 free_glyph_matrix (w->desired_matrix);
2275 w->current_matrix = w->desired_matrix = NULL;
2278 /* Next window on same level. */
2279 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2284 /* Check glyph memory leaks. This function is called from
2285 shut_down_emacs. Note that frames are not destroyed when Emacs
2286 exits. We therefore free all glyph memory for all active frames
2287 explicitly and check that nothing is left allocated. */
2289 void
2290 check_glyph_memory (void)
2292 Lisp_Object tail, frame;
2294 /* Free glyph memory for all frames. */
2295 FOR_EACH_FRAME (tail, frame)
2296 free_glyphs (XFRAME (frame));
2298 /* Check that nothing is left allocated. */
2299 if (glyph_matrix_count)
2300 emacs_abort ();
2301 if (glyph_pool_count)
2302 emacs_abort ();
2307 /**********************************************************************
2308 Building a Frame Matrix
2309 **********************************************************************/
2311 /* Most of the redisplay code works on glyph matrices attached to
2312 windows. This is a good solution most of the time, but it is not
2313 suitable for terminal code. Terminal output functions cannot rely
2314 on being able to set an arbitrary terminal window. Instead they
2315 must be provided with a view of the whole frame, i.e. the whole
2316 screen. We build such a view by constructing a frame matrix from
2317 window matrices in this section.
2319 Windows that must be updated have their must_be_update_p flag set.
2320 For all such windows, their desired matrix is made part of the
2321 desired frame matrix. For other windows, their current matrix is
2322 made part of the desired frame matrix.
2324 +-----------------+----------------+
2325 | desired | desired |
2326 | | |
2327 +-----------------+----------------+
2328 | current |
2330 +----------------------------------+
2332 Desired window matrices can be made part of the frame matrix in a
2333 cheap way: We exploit the fact that the desired frame matrix and
2334 desired window matrices share their glyph memory. This is not
2335 possible for current window matrices. Their glyphs are copied to
2336 the desired frame matrix. The latter is equivalent to
2337 preserve_other_columns in the old redisplay.
2339 Used glyphs counters for frame matrix rows are the result of adding
2340 up glyph lengths of the window matrices. A line in the frame
2341 matrix is enabled, if a corresponding line in a window matrix is
2342 enabled.
2344 After building the desired frame matrix, it will be passed to
2345 terminal code, which will manipulate both the desired and current
2346 frame matrix. Changes applied to the frame's current matrix have
2347 to be visible in current window matrices afterwards, of course.
2349 This problem is solved like this:
2351 1. Window and frame matrices share glyphs. Window matrices are
2352 constructed in a way that their glyph contents ARE the glyph
2353 contents needed in a frame matrix. Thus, any modification of
2354 glyphs done in terminal code will be reflected in window matrices
2355 automatically.
2357 2. Exchanges of rows in a frame matrix done by terminal code are
2358 intercepted by hook functions so that corresponding row operations
2359 on window matrices can be performed. This is necessary because we
2360 use pointers to glyphs in glyph row structures. To satisfy the
2361 assumption of point 1 above that glyphs are updated implicitly in
2362 window matrices when they are manipulated via the frame matrix,
2363 window and frame matrix must of course agree where to find the
2364 glyphs for their rows. Possible manipulations that must be
2365 mirrored are assignments of rows of the desired frame matrix to the
2366 current frame matrix and scrolling the current frame matrix. */
2368 /* Build frame F's desired matrix from window matrices. Only windows
2369 which have the flag must_be_updated_p set have to be updated. Menu
2370 bar lines of a frame are not covered by window matrices, so make
2371 sure not to touch them in this function. */
2373 static void
2374 build_frame_matrix (struct frame *f)
2376 int i;
2378 /* F must have a frame matrix when this function is called. */
2379 eassert (!FRAME_WINDOW_P (f));
2381 /* Clear all rows in the frame matrix covered by window matrices.
2382 Menu bar lines are not covered by windows. */
2383 for (i = FRAME_TOP_MARGIN (f); i < f->desired_matrix->nrows; ++i)
2384 clear_glyph_row (MATRIX_ROW (f->desired_matrix, i));
2386 /* Build the matrix by walking the window tree. */
2387 build_frame_matrix_from_window_tree (f->desired_matrix,
2388 XWINDOW (FRAME_ROOT_WINDOW (f)));
2392 /* Walk a window tree, building a frame matrix MATRIX from window
2393 matrices. W is the root of a window tree. */
2395 static void
2396 build_frame_matrix_from_window_tree (struct glyph_matrix *matrix, struct window *w)
2398 while (w)
2400 if (!NILP (w->hchild))
2401 build_frame_matrix_from_window_tree (matrix, XWINDOW (w->hchild));
2402 else if (!NILP (w->vchild))
2403 build_frame_matrix_from_window_tree (matrix, XWINDOW (w->vchild));
2404 else
2405 build_frame_matrix_from_leaf_window (matrix, w);
2407 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2412 /* Add a window's matrix to a frame matrix. FRAME_MATRIX is the
2413 desired frame matrix built. W is a leaf window whose desired or
2414 current matrix is to be added to FRAME_MATRIX. W's flag
2415 must_be_updated_p determines which matrix it contributes to
2416 FRAME_MATRIX. If W->must_be_updated_p, W's desired matrix
2417 is added to FRAME_MATRIX, otherwise W's current matrix is added.
2418 Adding a desired matrix means setting up used counters and such in
2419 frame rows, while adding a current window matrix to FRAME_MATRIX
2420 means copying glyphs. The latter case corresponds to
2421 preserve_other_columns in the old redisplay. */
2423 static void
2424 build_frame_matrix_from_leaf_window (struct glyph_matrix *frame_matrix, struct window *w)
2426 struct glyph_matrix *window_matrix;
2427 int window_y, frame_y;
2428 /* If non-zero, a glyph to insert at the right border of W. */
2429 GLYPH right_border_glyph;
2431 SET_GLYPH_FROM_CHAR (right_border_glyph, 0);
2433 /* Set window_matrix to the matrix we have to add to FRAME_MATRIX. */
2434 if (w->must_be_updated_p)
2436 window_matrix = w->desired_matrix;
2438 /* Decide whether we want to add a vertical border glyph. */
2439 if (!WINDOW_RIGHTMOST_P (w))
2441 struct Lisp_Char_Table *dp = window_display_table (w);
2442 Lisp_Object gc;
2444 SET_GLYPH_FROM_CHAR (right_border_glyph, '|');
2445 if (dp
2446 && (gc = DISP_BORDER_GLYPH (dp), GLYPH_CODE_P (gc)))
2448 SET_GLYPH_FROM_GLYPH_CODE (right_border_glyph, gc);
2449 spec_glyph_lookup_face (w, &right_border_glyph);
2452 if (GLYPH_FACE (right_border_glyph) <= 0)
2453 SET_GLYPH_FACE (right_border_glyph, VERTICAL_BORDER_FACE_ID);
2456 else
2457 window_matrix = w->current_matrix;
2459 /* For all rows in the window matrix and corresponding rows in the
2460 frame matrix. */
2461 window_y = 0;
2462 frame_y = window_matrix->matrix_y;
2463 while (window_y < window_matrix->nrows)
2465 struct glyph_row *frame_row = frame_matrix->rows + frame_y;
2466 struct glyph_row *window_row = window_matrix->rows + window_y;
2467 bool current_row_p = window_matrix == w->current_matrix;
2469 /* Fill up the frame row with spaces up to the left margin of the
2470 window row. */
2471 fill_up_frame_row_with_spaces (frame_row, window_matrix->matrix_x);
2473 /* Fill up areas in the window matrix row with spaces. */
2474 fill_up_glyph_row_with_spaces (window_row);
2476 /* If only part of W's desired matrix has been built, and
2477 window_row wasn't displayed, use the corresponding current
2478 row instead. */
2479 if (window_matrix == w->desired_matrix
2480 && !window_row->enabled_p)
2482 window_row = w->current_matrix->rows + window_y;
2483 current_row_p = 1;
2486 if (current_row_p)
2488 /* Copy window row to frame row. */
2489 memcpy (frame_row->glyphs[TEXT_AREA] + window_matrix->matrix_x,
2490 window_row->glyphs[0],
2491 window_matrix->matrix_w * sizeof (struct glyph));
2493 else
2495 eassert (window_row->enabled_p);
2497 /* Only when a desired row has been displayed, we want
2498 the corresponding frame row to be updated. */
2499 frame_row->enabled_p = 1;
2501 /* Maybe insert a vertical border between horizontally adjacent
2502 windows. */
2503 if (GLYPH_CHAR (right_border_glyph) != 0)
2505 struct glyph *border = window_row->glyphs[LAST_AREA] - 1;
2506 SET_CHAR_GLYPH_FROM_GLYPH (*border, right_border_glyph);
2509 #ifdef GLYPH_DEBUG
2510 /* Window row window_y must be a slice of frame row
2511 frame_y. */
2512 eassert (glyph_row_slice_p (window_row, frame_row));
2514 /* If rows are in sync, we don't have to copy glyphs because
2515 frame and window share glyphs. */
2517 strcpy (w->current_matrix->method, w->desired_matrix->method);
2518 add_window_display_history (w, w->current_matrix->method, 0);
2519 #endif
2522 /* Set number of used glyphs in the frame matrix. Since we fill
2523 up with spaces, and visit leaf windows from left to right it
2524 can be done simply. */
2525 frame_row->used[TEXT_AREA]
2526 = window_matrix->matrix_x + window_matrix->matrix_w;
2528 /* Next row. */
2529 ++window_y;
2530 ++frame_y;
2534 /* Given a user-specified glyph, possibly including a Lisp-level face
2535 ID, return a glyph that has a realized face ID.
2536 This is used for glyphs displayed specially and not part of the text;
2537 for instance, vertical separators, truncation markers, etc. */
2539 void
2540 spec_glyph_lookup_face (struct window *w, GLYPH *glyph)
2542 int lface_id = GLYPH_FACE (*glyph);
2543 /* Convert the glyph's specified face to a realized (cache) face. */
2544 if (lface_id > 0)
2546 int face_id = merge_faces (XFRAME (w->frame),
2547 Qt, lface_id, DEFAULT_FACE_ID);
2548 SET_GLYPH_FACE (*glyph, face_id);
2552 /* Add spaces to a glyph row ROW in a window matrix.
2554 Each row has the form:
2556 +---------+-----------------------------+------------+
2557 | left | text | right |
2558 +---------+-----------------------------+------------+
2560 Left and right marginal areas are optional. This function adds
2561 spaces to areas so that there are no empty holes between areas.
2562 In other words: If the right area is not empty, the text area
2563 is filled up with spaces up to the right area. If the text area
2564 is not empty, the left area is filled up.
2566 To be called for frame-based redisplay, only. */
2568 static void
2569 fill_up_glyph_row_with_spaces (struct glyph_row *row)
2571 fill_up_glyph_row_area_with_spaces (row, LEFT_MARGIN_AREA);
2572 fill_up_glyph_row_area_with_spaces (row, TEXT_AREA);
2573 fill_up_glyph_row_area_with_spaces (row, RIGHT_MARGIN_AREA);
2577 /* Fill area AREA of glyph row ROW with spaces. To be called for
2578 frame-based redisplay only. */
2580 static void
2581 fill_up_glyph_row_area_with_spaces (struct glyph_row *row, int area)
2583 if (row->glyphs[area] < row->glyphs[area + 1])
2585 struct glyph *end = row->glyphs[area + 1];
2586 struct glyph *text = row->glyphs[area] + row->used[area];
2588 while (text < end)
2589 *text++ = space_glyph;
2590 row->used[area] = text - row->glyphs[area];
2595 /* Add spaces to the end of ROW in a frame matrix until index UPTO is
2596 reached. In frame matrices only one area, TEXT_AREA, is used. */
2598 static void
2599 fill_up_frame_row_with_spaces (struct glyph_row *row, int upto)
2601 int i = row->used[TEXT_AREA];
2602 struct glyph *glyph = row->glyphs[TEXT_AREA];
2604 while (i < upto)
2605 glyph[i++] = space_glyph;
2607 row->used[TEXT_AREA] = i;
2612 /**********************************************************************
2613 Mirroring operations on frame matrices in window matrices
2614 **********************************************************************/
2616 /* Set frame being updated via frame-based redisplay to F. This
2617 function must be called before updates to make explicit that we are
2618 working on frame matrices or not. */
2620 static void
2621 set_frame_matrix_frame (struct frame *f)
2623 frame_matrix_frame = f;
2627 /* Make sure glyph row ROW in CURRENT_MATRIX is up to date.
2628 DESIRED_MATRIX is the desired matrix corresponding to
2629 CURRENT_MATRIX. The update is done by exchanging glyph pointers
2630 between rows in CURRENT_MATRIX and DESIRED_MATRIX. If
2631 frame_matrix_frame is non-null, this indicates that the exchange is
2632 done in frame matrices, and that we have to perform analogous
2633 operations in window matrices of frame_matrix_frame. */
2635 static void
2636 make_current (struct glyph_matrix *desired_matrix, struct glyph_matrix *current_matrix, int row)
2638 struct glyph_row *current_row = MATRIX_ROW (current_matrix, row);
2639 struct glyph_row *desired_row = MATRIX_ROW (desired_matrix, row);
2640 bool mouse_face_p = current_row->mouse_face_p;
2642 /* Do current_row = desired_row. This exchanges glyph pointers
2643 between both rows, and does a structure assignment otherwise. */
2644 assign_row (current_row, desired_row);
2646 /* Enable current_row to mark it as valid. */
2647 current_row->enabled_p = 1;
2648 current_row->mouse_face_p = mouse_face_p;
2650 /* If we are called on frame matrices, perform analogous operations
2651 for window matrices. */
2652 if (frame_matrix_frame)
2653 mirror_make_current (XWINDOW (frame_matrix_frame->root_window), row);
2657 /* W is the root of a window tree. FRAME_ROW is the index of a row in
2658 W's frame which has been made current (by swapping pointers between
2659 current and desired matrix). Perform analogous operations in the
2660 matrices of leaf windows in the window tree rooted at W. */
2662 static void
2663 mirror_make_current (struct window *w, int frame_row)
2665 while (w)
2667 if (!NILP (w->hchild))
2668 mirror_make_current (XWINDOW (w->hchild), frame_row);
2669 else if (!NILP (w->vchild))
2670 mirror_make_current (XWINDOW (w->vchild), frame_row);
2671 else
2673 /* Row relative to window W. Don't use FRAME_TO_WINDOW_VPOS
2674 here because the checks performed in debug mode there
2675 will not allow the conversion. */
2676 int row = frame_row - w->desired_matrix->matrix_y;
2678 /* If FRAME_ROW is within W, assign the desired row to the
2679 current row (exchanging glyph pointers). */
2680 if (row >= 0 && row < w->desired_matrix->matrix_h)
2682 struct glyph_row *current_row
2683 = MATRIX_ROW (w->current_matrix, row);
2684 struct glyph_row *desired_row
2685 = MATRIX_ROW (w->desired_matrix, row);
2687 if (desired_row->enabled_p)
2688 assign_row (current_row, desired_row);
2689 else
2690 swap_glyph_pointers (desired_row, current_row);
2691 current_row->enabled_p = 1;
2693 /* Set the Y coordinate of the mode/header line's row.
2694 It is needed in draw_row_with_mouse_face to find the
2695 screen coordinates. (Window-based redisplay sets
2696 this in update_window, but no one seems to do that
2697 for frame-based redisplay.) */
2698 if (current_row->mode_line_p)
2699 current_row->y = row;
2703 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2708 /* Perform row dance after scrolling. We are working on the range of
2709 lines UNCHANGED_AT_TOP + 1 to UNCHANGED_AT_TOP + NLINES (not
2710 including) in MATRIX. COPY_FROM is a vector containing, for each
2711 row I in the range 0 <= I < NLINES, the index of the original line
2712 to move to I. This index is relative to the row range, i.e. 0 <=
2713 index < NLINES. RETAINED_P is a vector containing zero for each
2714 row 0 <= I < NLINES which is empty.
2716 This function is called from do_scrolling and do_direct_scrolling. */
2718 void
2719 mirrored_line_dance (struct glyph_matrix *matrix, int unchanged_at_top, int nlines,
2720 int *copy_from, char *retained_p)
2722 /* A copy of original rows. */
2723 struct glyph_row *old_rows;
2725 /* Rows to assign to. */
2726 struct glyph_row *new_rows = MATRIX_ROW (matrix, unchanged_at_top);
2728 int i;
2730 /* Make a copy of the original rows. */
2731 old_rows = alloca (nlines * sizeof *old_rows);
2732 memcpy (old_rows, new_rows, nlines * sizeof *old_rows);
2734 /* Assign new rows, maybe clear lines. */
2735 for (i = 0; i < nlines; ++i)
2737 bool enabled_before_p = new_rows[i].enabled_p;
2739 eassert (i + unchanged_at_top < matrix->nrows);
2740 eassert (unchanged_at_top + copy_from[i] < matrix->nrows);
2741 new_rows[i] = old_rows[copy_from[i]];
2742 new_rows[i].enabled_p = enabled_before_p;
2744 /* RETAINED_P is zero for empty lines. */
2745 if (!retained_p[copy_from[i]])
2746 new_rows[i].enabled_p = 0;
2749 /* Do the same for window matrices, if MATRIX is a frame matrix. */
2750 if (frame_matrix_frame)
2751 mirror_line_dance (XWINDOW (frame_matrix_frame->root_window),
2752 unchanged_at_top, nlines, copy_from, retained_p);
2756 /* Synchronize glyph pointers in the current matrix of window W with
2757 the current frame matrix. */
2759 static void
2760 sync_window_with_frame_matrix_rows (struct window *w)
2762 struct frame *f = XFRAME (w->frame);
2763 struct glyph_row *window_row, *window_row_end, *frame_row;
2764 int left, right, x, width;
2766 /* Preconditions: W must be a leaf window on a tty frame. */
2767 eassert (NILP (w->hchild) && NILP (w->vchild));
2768 eassert (!FRAME_WINDOW_P (f));
2770 left = margin_glyphs_to_reserve (w, 1, w->left_margin_cols);
2771 right = margin_glyphs_to_reserve (w, 1, w->right_margin_cols);
2772 x = w->current_matrix->matrix_x;
2773 width = w->current_matrix->matrix_w;
2775 window_row = w->current_matrix->rows;
2776 window_row_end = window_row + w->current_matrix->nrows;
2777 frame_row = f->current_matrix->rows + WINDOW_TOP_EDGE_LINE (w);
2779 for (; window_row < window_row_end; ++window_row, ++frame_row)
2781 window_row->glyphs[LEFT_MARGIN_AREA]
2782 = frame_row->glyphs[0] + x;
2783 window_row->glyphs[TEXT_AREA]
2784 = window_row->glyphs[LEFT_MARGIN_AREA] + left;
2785 window_row->glyphs[LAST_AREA]
2786 = window_row->glyphs[LEFT_MARGIN_AREA] + width;
2787 window_row->glyphs[RIGHT_MARGIN_AREA]
2788 = window_row->glyphs[LAST_AREA] - right;
2793 /* Return the window in the window tree rooted in W containing frame
2794 row ROW. Value is null if none is found. */
2796 static struct window *
2797 frame_row_to_window (struct window *w, int row)
2799 struct window *found = NULL;
2801 while (w && !found)
2803 if (!NILP (w->hchild))
2804 found = frame_row_to_window (XWINDOW (w->hchild), row);
2805 else if (!NILP (w->vchild))
2806 found = frame_row_to_window (XWINDOW (w->vchild), row);
2807 else if (row >= WINDOW_TOP_EDGE_LINE (w)
2808 && row < WINDOW_BOTTOM_EDGE_LINE (w))
2809 found = w;
2811 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2814 return found;
2818 /* Perform a line dance in the window tree rooted at W, after
2819 scrolling a frame matrix in mirrored_line_dance.
2821 We are working on the range of lines UNCHANGED_AT_TOP + 1 to
2822 UNCHANGED_AT_TOP + NLINES (not including) in W's frame matrix.
2823 COPY_FROM is a vector containing, for each row I in the range 0 <=
2824 I < NLINES, the index of the original line to move to I. This
2825 index is relative to the row range, i.e. 0 <= index < NLINES.
2826 RETAINED_P is a vector containing zero for each row 0 <= I < NLINES
2827 which is empty. */
2829 static void
2830 mirror_line_dance (struct window *w, int unchanged_at_top, int nlines, int *copy_from, char *retained_p)
2832 while (w)
2834 if (!NILP (w->hchild))
2835 mirror_line_dance (XWINDOW (w->hchild), unchanged_at_top,
2836 nlines, copy_from, retained_p);
2837 else if (!NILP (w->vchild))
2838 mirror_line_dance (XWINDOW (w->vchild), unchanged_at_top,
2839 nlines, copy_from, retained_p);
2840 else
2842 /* W is a leaf window, and we are working on its current
2843 matrix m. */
2844 struct glyph_matrix *m = w->current_matrix;
2845 int i;
2846 bool sync_p = 0;
2847 struct glyph_row *old_rows;
2849 /* Make a copy of the original rows of matrix m. */
2850 old_rows = alloca (m->nrows * sizeof *old_rows);
2851 memcpy (old_rows, m->rows, m->nrows * sizeof *old_rows);
2853 for (i = 0; i < nlines; ++i)
2855 /* Frame relative line assigned to. */
2856 int frame_to = i + unchanged_at_top;
2858 /* Frame relative line assigned. */
2859 int frame_from = copy_from[i] + unchanged_at_top;
2861 /* Window relative line assigned to. */
2862 int window_to = frame_to - m->matrix_y;
2864 /* Window relative line assigned. */
2865 int window_from = frame_from - m->matrix_y;
2867 /* Is assigned line inside window? */
2868 bool from_inside_window_p
2869 = window_from >= 0 && window_from < m->matrix_h;
2871 /* Is assigned to line inside window? */
2872 bool to_inside_window_p
2873 = window_to >= 0 && window_to < m->matrix_h;
2875 if (from_inside_window_p && to_inside_window_p)
2877 /* Do the assignment. The enabled_p flag is saved
2878 over the assignment because the old redisplay did
2879 that. */
2880 bool enabled_before_p = m->rows[window_to].enabled_p;
2881 m->rows[window_to] = old_rows[window_from];
2882 m->rows[window_to].enabled_p = enabled_before_p;
2884 /* If frame line is empty, window line is empty, too. */
2885 if (!retained_p[copy_from[i]])
2886 m->rows[window_to].enabled_p = 0;
2888 else if (to_inside_window_p)
2890 /* A copy between windows. This is an infrequent
2891 case not worth optimizing. */
2892 struct frame *f = XFRAME (w->frame);
2893 struct window *root = XWINDOW (FRAME_ROOT_WINDOW (f));
2894 struct window *w2;
2895 struct glyph_matrix *m2;
2896 int m2_from;
2898 w2 = frame_row_to_window (root, frame_from);
2899 /* ttn@surf.glug.org: when enabling menu bar using `emacs
2900 -nw', FROM_FRAME sometimes has no associated window.
2901 This check avoids a segfault if W2 is null. */
2902 if (w2)
2904 m2 = w2->current_matrix;
2905 m2_from = frame_from - m2->matrix_y;
2906 copy_row_except_pointers (m->rows + window_to,
2907 m2->rows + m2_from);
2909 /* If frame line is empty, window line is empty, too. */
2910 if (!retained_p[copy_from[i]])
2911 m->rows[window_to].enabled_p = 0;
2913 sync_p = 1;
2915 else if (from_inside_window_p)
2916 sync_p = 1;
2919 /* If there was a copy between windows, make sure glyph
2920 pointers are in sync with the frame matrix. */
2921 if (sync_p)
2922 sync_window_with_frame_matrix_rows (w);
2924 /* Check that no pointers are lost. */
2925 CHECK_MATRIX (m);
2928 /* Next window on same level. */
2929 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2934 #ifdef GLYPH_DEBUG
2936 /* Check that window and frame matrices agree about their
2937 understanding where glyphs of the rows are to find. For each
2938 window in the window tree rooted at W, check that rows in the
2939 matrices of leaf window agree with their frame matrices about
2940 glyph pointers. */
2942 static void
2943 check_window_matrix_pointers (struct window *w)
2945 while (w)
2947 if (!NILP (w->hchild))
2948 check_window_matrix_pointers (XWINDOW (w->hchild));
2949 else if (!NILP (w->vchild))
2950 check_window_matrix_pointers (XWINDOW (w->vchild));
2951 else
2953 struct frame *f = XFRAME (w->frame);
2954 check_matrix_pointers (w->desired_matrix, f->desired_matrix);
2955 check_matrix_pointers (w->current_matrix, f->current_matrix);
2958 w = NILP (w->next) ? 0 : XWINDOW (w->next);
2963 /* Check that window rows are slices of frame rows. WINDOW_MATRIX is
2964 a window and FRAME_MATRIX is the corresponding frame matrix. For
2965 each row in WINDOW_MATRIX check that it's a slice of the
2966 corresponding frame row. If it isn't, abort. */
2968 static void
2969 check_matrix_pointers (struct glyph_matrix *window_matrix,
2970 struct glyph_matrix *frame_matrix)
2972 /* Row number in WINDOW_MATRIX. */
2973 int i = 0;
2975 /* Row number corresponding to I in FRAME_MATRIX. */
2976 int j = window_matrix->matrix_y;
2978 /* For all rows check that the row in the window matrix is a
2979 slice of the row in the frame matrix. If it isn't we didn't
2980 mirror an operation on the frame matrix correctly. */
2981 while (i < window_matrix->nrows)
2983 if (!glyph_row_slice_p (window_matrix->rows + i,
2984 frame_matrix->rows + j))
2985 emacs_abort ();
2986 ++i, ++j;
2990 #endif /* GLYPH_DEBUG */
2994 /**********************************************************************
2995 VPOS and HPOS translations
2996 **********************************************************************/
2998 #ifdef GLYPH_DEBUG
3000 /* Translate vertical position VPOS which is relative to window W to a
3001 vertical position relative to W's frame. */
3003 static int
3004 window_to_frame_vpos (struct window *w, int vpos)
3006 eassert (!FRAME_WINDOW_P (XFRAME (w->frame)));
3007 eassert (vpos >= 0 && vpos <= w->desired_matrix->nrows);
3008 vpos += WINDOW_TOP_EDGE_LINE (w);
3009 eassert (vpos >= 0 && vpos <= FRAME_LINES (XFRAME (w->frame)));
3010 return vpos;
3014 /* Translate horizontal position HPOS which is relative to window W to
3015 a horizontal position relative to W's frame. */
3017 static int
3018 window_to_frame_hpos (struct window *w, int hpos)
3020 eassert (!FRAME_WINDOW_P (XFRAME (w->frame)));
3021 hpos += WINDOW_LEFT_EDGE_COL (w);
3022 return hpos;
3025 #endif /* GLYPH_DEBUG */
3029 /**********************************************************************
3030 Redrawing Frames
3031 **********************************************************************/
3033 /* Redraw frame F. */
3035 void
3036 redraw_frame (struct frame *f)
3038 /* Error if F has no glyphs. */
3039 eassert (f->glyphs_initialized_p);
3040 update_begin (f);
3041 #ifdef MSDOS
3042 if (FRAME_MSDOS_P (f))
3043 FRAME_TERMINAL (f)->set_terminal_modes_hook (FRAME_TERMINAL (f));
3044 #endif
3045 clear_frame (f);
3046 clear_current_matrices (f);
3047 update_end (f);
3048 if (FRAME_TERMCAP_P (f))
3049 fflush (FRAME_TTY (f)->output);
3050 windows_or_buffers_changed++;
3051 /* Mark all windows as inaccurate, so that every window will have
3052 its redisplay done. */
3053 mark_window_display_accurate (FRAME_ROOT_WINDOW (f), 0);
3054 set_window_update_flags (XWINDOW (FRAME_ROOT_WINDOW (f)), 1);
3055 f->garbaged = 0;
3058 DEFUN ("redraw-frame", Fredraw_frame, Sredraw_frame, 0, 1, 0,
3059 doc: /* Clear frame FRAME and output again what is supposed to appear on it.
3060 If FRAME is omitted or nil, the selected frame is used. */)
3061 (Lisp_Object frame)
3063 redraw_frame (decode_live_frame (frame));
3064 return Qnil;
3067 DEFUN ("redraw-display", Fredraw_display, Sredraw_display, 0, 0, "",
3068 doc: /* Clear and redisplay all visible frames. */)
3069 (void)
3071 Lisp_Object tail, frame;
3073 FOR_EACH_FRAME (tail, frame)
3074 if (FRAME_VISIBLE_P (XFRAME (frame)))
3075 redraw_frame (XFRAME (frame));
3077 return Qnil;
3082 /***********************************************************************
3083 Frame Update
3084 ***********************************************************************/
3086 /* Update frame F based on the data in desired matrices.
3088 If FORCE_P, don't let redisplay be stopped by detecting pending input.
3089 If INHIBIT_HAIRY_ID_P, don't try scrolling.
3091 Value is true if redisplay was stopped due to pending input. */
3093 bool
3094 update_frame (struct frame *f, bool force_p, bool inhibit_hairy_id_p)
3096 /* True means display has been paused because of pending input. */
3097 bool paused_p;
3098 struct window *root_window = XWINDOW (f->root_window);
3100 if (redisplay_dont_pause)
3101 force_p = 1;
3102 else if (NILP (Vredisplay_preemption_period))
3103 force_p = 1;
3104 else if (!force_p && NUMBERP (Vredisplay_preemption_period))
3106 double p = XFLOATINT (Vredisplay_preemption_period);
3108 if (detect_input_pending_ignore_squeezables ())
3110 paused_p = 1;
3111 goto do_pause;
3114 preemption_period = EMACS_TIME_FROM_DOUBLE (p);
3115 preemption_next_check = add_emacs_time (current_emacs_time (),
3116 preemption_period);
3119 if (FRAME_WINDOW_P (f))
3121 /* We are working on window matrix basis. All windows whose
3122 flag must_be_updated_p is set have to be updated. */
3124 /* Record that we are not working on frame matrices. */
3125 set_frame_matrix_frame (NULL);
3127 /* Update all windows in the window tree of F, maybe stopping
3128 when pending input is detected. */
3129 update_begin (f);
3131 /* Update the menu bar on X frames that don't have toolkit
3132 support. */
3133 if (WINDOWP (f->menu_bar_window))
3134 update_window (XWINDOW (f->menu_bar_window), 1);
3136 /* Update the tool-bar window, if present. */
3137 if (WINDOWP (f->tool_bar_window))
3139 struct window *w = XWINDOW (f->tool_bar_window);
3141 /* Update tool-bar window. */
3142 if (w->must_be_updated_p)
3144 Lisp_Object tem;
3146 update_window (w, 1);
3147 w->must_be_updated_p = 0;
3149 /* Swap tool-bar strings. We swap because we want to
3150 reuse strings. */
3151 tem = f->current_tool_bar_string;
3152 fset_current_tool_bar_string (f, f->desired_tool_bar_string);
3153 fset_desired_tool_bar_string (f, tem);
3158 /* Update windows. */
3159 paused_p = update_window_tree (root_window, force_p);
3160 update_end (f);
3162 /* This flush is a performance bottleneck under X,
3163 and it doesn't seem to be necessary anyway (in general).
3164 It is necessary when resizing the window with the mouse, or
3165 at least the fringes are not redrawn in a timely manner. ++kfs */
3166 if (f->force_flush_display_p)
3168 FRAME_RIF (f)->flush_display (f);
3169 f->force_flush_display_p = 0;
3172 else
3174 /* We are working on frame matrix basis. Set the frame on whose
3175 frame matrix we operate. */
3176 set_frame_matrix_frame (f);
3178 /* Build F's desired matrix from window matrices. */
3179 build_frame_matrix (f);
3181 /* Update the display */
3182 update_begin (f);
3183 paused_p = update_frame_1 (f, force_p, inhibit_hairy_id_p);
3184 update_end (f);
3186 if (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f))
3188 if (FRAME_TTY (f)->termscript)
3189 fflush (FRAME_TTY (f)->termscript);
3190 if (FRAME_TERMCAP_P (f))
3191 fflush (FRAME_TTY (f)->output);
3194 /* Check window matrices for lost pointers. */
3195 #ifdef GLYPH_DEBUG
3196 check_window_matrix_pointers (root_window);
3197 add_frame_display_history (f, paused_p);
3198 #endif
3201 do_pause:
3202 /* Reset flags indicating that a window should be updated. */
3203 set_window_update_flags (root_window, 0);
3205 display_completed = !paused_p;
3206 return paused_p;
3211 /************************************************************************
3212 Window-based updates
3213 ************************************************************************/
3215 /* Perform updates in window tree rooted at W.
3216 If FORCE_P, don't stop updating if input is pending. */
3218 static bool
3219 update_window_tree (struct window *w, bool force_p)
3221 bool paused_p = 0;
3223 while (w && !paused_p)
3225 if (!NILP (w->hchild))
3226 paused_p |= update_window_tree (XWINDOW (w->hchild), force_p);
3227 else if (!NILP (w->vchild))
3228 paused_p |= update_window_tree (XWINDOW (w->vchild), force_p);
3229 else if (w->must_be_updated_p)
3230 paused_p |= update_window (w, force_p);
3232 w = NILP (w->next) ? 0 : XWINDOW (w->next);
3235 return paused_p;
3239 /* Update window W if its flag must_be_updated_p is set.
3240 If FORCE_P, don't stop updating if input is pending. */
3242 void
3243 update_single_window (struct window *w, bool force_p)
3245 if (w->must_be_updated_p)
3247 struct frame *f = XFRAME (WINDOW_FRAME (w));
3249 /* Record that this is not a frame-based redisplay. */
3250 set_frame_matrix_frame (NULL);
3252 if (redisplay_dont_pause)
3253 force_p = 1;
3254 else if (NILP (Vredisplay_preemption_period))
3255 force_p = 1;
3256 else if (!force_p && NUMBERP (Vredisplay_preemption_period))
3258 double p = XFLOATINT (Vredisplay_preemption_period);
3259 preemption_period = EMACS_TIME_FROM_DOUBLE (p);
3260 preemption_next_check = add_emacs_time (current_emacs_time (),
3261 preemption_period);
3264 /* Update W. */
3265 update_begin (f);
3266 update_window (w, force_p);
3267 update_end (f);
3269 /* Reset flag in W. */
3270 w->must_be_updated_p = 0;
3274 #ifdef HAVE_WINDOW_SYSTEM
3276 /* Redraw lines from the current matrix of window W that are
3277 overlapped by other rows. YB is bottom-most y-position in W. */
3279 static void
3280 redraw_overlapped_rows (struct window *w, int yb)
3282 int i;
3283 struct frame *f = XFRAME (WINDOW_FRAME (w));
3285 /* If rows overlapping others have been changed, the rows being
3286 overlapped have to be redrawn. This won't draw lines that have
3287 already been drawn in update_window_line because overlapped_p in
3288 desired rows is 0, so after row assignment overlapped_p in
3289 current rows is 0. */
3290 for (i = 0; i < w->current_matrix->nrows; ++i)
3292 struct glyph_row *row = w->current_matrix->rows + i;
3294 if (!row->enabled_p)
3295 break;
3296 else if (row->mode_line_p)
3297 continue;
3299 if (row->overlapped_p)
3301 enum glyph_row_area area;
3303 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
3305 updated_row = row;
3306 updated_area = area;
3307 FRAME_RIF (f)->cursor_to (i, 0, row->y,
3308 area == TEXT_AREA ? row->x : 0);
3309 if (row->used[area])
3310 FRAME_RIF (f)->write_glyphs (row->glyphs[area],
3311 row->used[area]);
3312 FRAME_RIF (f)->clear_end_of_line (-1);
3315 row->overlapped_p = 0;
3318 if (MATRIX_ROW_BOTTOM_Y (row) >= yb)
3319 break;
3324 /* Redraw lines from the current matrix of window W that overlap
3325 others. YB is bottom-most y-position in W. */
3327 static void
3328 redraw_overlapping_rows (struct window *w, int yb)
3330 int i, bottom_y;
3331 struct glyph_row *row;
3332 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3334 for (i = 0; i < w->current_matrix->nrows; ++i)
3336 row = w->current_matrix->rows + i;
3338 if (!row->enabled_p)
3339 break;
3340 else if (row->mode_line_p)
3341 continue;
3343 bottom_y = MATRIX_ROW_BOTTOM_Y (row);
3345 if (row->overlapping_p)
3347 int overlaps = 0;
3349 if (MATRIX_ROW_OVERLAPS_PRED_P (row) && i > 0
3350 && !MATRIX_ROW (w->current_matrix, i - 1)->overlapped_p)
3351 overlaps |= OVERLAPS_PRED;
3352 if (MATRIX_ROW_OVERLAPS_SUCC_P (row) && bottom_y < yb
3353 && !MATRIX_ROW (w->current_matrix, i + 1)->overlapped_p)
3354 overlaps |= OVERLAPS_SUCC;
3356 if (overlaps)
3358 if (row->used[LEFT_MARGIN_AREA])
3359 rif->fix_overlapping_area (w, row, LEFT_MARGIN_AREA, overlaps);
3361 if (row->used[TEXT_AREA])
3362 rif->fix_overlapping_area (w, row, TEXT_AREA, overlaps);
3364 if (row->used[RIGHT_MARGIN_AREA])
3365 rif->fix_overlapping_area (w, row, RIGHT_MARGIN_AREA, overlaps);
3367 /* Record in neighbor rows that ROW overwrites part of
3368 their display. */
3369 if (overlaps & OVERLAPS_PRED)
3370 MATRIX_ROW (w->current_matrix, i - 1)->overlapped_p = 1;
3371 if (overlaps & OVERLAPS_SUCC)
3372 MATRIX_ROW (w->current_matrix, i + 1)->overlapped_p = 1;
3376 if (bottom_y >= yb)
3377 break;
3381 #endif /* HAVE_WINDOW_SYSTEM */
3384 #if defined GLYPH_DEBUG && 0
3386 /* Check that no row in the current matrix of window W is enabled
3387 which is below what's displayed in the window. */
3389 static void
3390 check_current_matrix_flags (struct window *w)
3392 bool last_seen_p = 0;
3393 int i, yb = window_text_bottom_y (w);
3395 for (i = 0; i < w->current_matrix->nrows - 1; ++i)
3397 struct glyph_row *row = MATRIX_ROW (w->current_matrix, i);
3398 if (!last_seen_p && MATRIX_ROW_BOTTOM_Y (row) >= yb)
3399 last_seen_p = 1;
3400 else if (last_seen_p && row->enabled_p)
3401 emacs_abort ();
3405 #endif /* GLYPH_DEBUG */
3408 /* Update display of window W.
3409 If FORCE_P, don't stop updating when input is pending. */
3411 static bool
3412 update_window (struct window *w, bool force_p)
3414 struct glyph_matrix *desired_matrix = w->desired_matrix;
3415 bool paused_p;
3416 #if !PERIODIC_PREEMPTION_CHECKING
3417 int preempt_count = baud_rate / 2400 + 1;
3418 #endif
3419 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3420 #ifdef GLYPH_DEBUG
3421 /* Check that W's frame doesn't have glyph matrices. */
3422 eassert (FRAME_WINDOW_P (XFRAME (WINDOW_FRAME (w))));
3423 #endif
3425 /* Check pending input the first time so that we can quickly return. */
3426 #if !PERIODIC_PREEMPTION_CHECKING
3427 if (!force_p)
3428 detect_input_pending_ignore_squeezables ();
3429 #endif
3431 /* If forced to complete the update, or if no input is pending, do
3432 the update. */
3433 if (force_p || !input_pending || !NILP (do_mouse_tracking))
3435 struct glyph_row *row, *end;
3436 struct glyph_row *mode_line_row;
3437 struct glyph_row *header_line_row;
3438 int yb;
3439 bool changed_p = 0, mouse_face_overwritten_p = 0;
3440 #if ! PERIODIC_PREEMPTION_CHECKING
3441 int n_updated = 0;
3442 #endif
3444 rif->update_window_begin_hook (w);
3445 yb = window_text_bottom_y (w);
3446 row = desired_matrix->rows;
3447 end = row + desired_matrix->nrows - 1;
3449 /* Take note of the header line, if there is one. We will
3450 update it below, after updating all of the window's lines. */
3451 if (row->mode_line_p)
3453 header_line_row = row;
3454 ++row;
3456 else
3457 header_line_row = NULL;
3459 /* Update the mode line, if necessary. */
3460 mode_line_row = MATRIX_MODE_LINE_ROW (desired_matrix);
3461 if (mode_line_row->mode_line_p && mode_line_row->enabled_p)
3463 mode_line_row->y = yb;
3464 update_window_line (w, MATRIX_ROW_VPOS (mode_line_row,
3465 desired_matrix),
3466 &mouse_face_overwritten_p);
3469 /* Find first enabled row. Optimizations in redisplay_internal
3470 may lead to an update with only one row enabled. There may
3471 be also completely empty matrices. */
3472 while (row < end && !row->enabled_p)
3473 ++row;
3475 /* Try reusing part of the display by copying. */
3476 if (row < end && !desired_matrix->no_scrolling_p)
3478 int rc = scrolling_window (w, header_line_row != NULL);
3479 if (rc < 0)
3481 /* All rows were found to be equal. */
3482 paused_p = 0;
3483 goto set_cursor;
3485 else if (rc > 0)
3487 /* We've scrolled the display. */
3488 force_p = 1;
3489 changed_p = 1;
3493 /* Update the rest of the lines. */
3494 for (; row < end && (force_p || !input_pending); ++row)
3495 /* scrolling_window resets the enabled_p flag of the rows it
3496 reuses from current_matrix. */
3497 if (row->enabled_p)
3499 int vpos = MATRIX_ROW_VPOS (row, desired_matrix);
3500 int i;
3502 /* We'll have to play a little bit with when to
3503 detect_input_pending. If it's done too often,
3504 scrolling large windows with repeated scroll-up
3505 commands will too quickly pause redisplay. */
3506 #if PERIODIC_PREEMPTION_CHECKING
3507 if (!force_p)
3509 EMACS_TIME tm = current_emacs_time ();
3510 if (EMACS_TIME_LT (preemption_next_check, tm))
3512 preemption_next_check = add_emacs_time (tm,
3513 preemption_period);
3514 if (detect_input_pending_ignore_squeezables ())
3515 break;
3518 #else
3519 if (!force_p && ++n_updated % preempt_count == 0)
3520 detect_input_pending_ignore_squeezables ();
3521 #endif
3522 changed_p |= update_window_line (w, vpos,
3523 &mouse_face_overwritten_p);
3525 /* Mark all rows below the last visible one in the current
3526 matrix as invalid. This is necessary because of
3527 variable line heights. Consider the case of three
3528 successive redisplays, where the first displays 5
3529 lines, the second 3 lines, and the third 5 lines again.
3530 If the second redisplay wouldn't mark rows in the
3531 current matrix invalid, the third redisplay might be
3532 tempted to optimize redisplay based on lines displayed
3533 in the first redisplay. */
3534 if (MATRIX_ROW_BOTTOM_Y (row) >= yb)
3535 for (i = vpos + 1; i < w->current_matrix->nrows - 1; ++i)
3536 MATRIX_ROW (w->current_matrix, i)->enabled_p = 0;
3539 /* Was display preempted? */
3540 paused_p = row < end;
3542 set_cursor:
3544 /* Update the header line after scrolling because a new header
3545 line would otherwise overwrite lines at the top of the window
3546 that can be scrolled. */
3547 if (header_line_row && header_line_row->enabled_p)
3549 header_line_row->y = 0;
3550 update_window_line (w, 0, &mouse_face_overwritten_p);
3553 /* Fix the appearance of overlapping/overlapped rows. */
3554 if (!paused_p && !w->pseudo_window_p)
3556 #ifdef HAVE_WINDOW_SYSTEM
3557 if (changed_p && rif->fix_overlapping_area)
3559 redraw_overlapped_rows (w, yb);
3560 redraw_overlapping_rows (w, yb);
3562 #endif
3564 /* Make cursor visible at cursor position of W. */
3565 set_window_cursor_after_update (w);
3567 #if 0 /* Check that current matrix invariants are satisfied. This is
3568 for debugging only. See the comment of check_matrix_invariants. */
3569 IF_DEBUG (check_matrix_invariants (w));
3570 #endif
3573 #ifdef GLYPH_DEBUG
3574 /* Remember the redisplay method used to display the matrix. */
3575 strcpy (w->current_matrix->method, w->desired_matrix->method);
3576 #endif
3578 #ifdef HAVE_WINDOW_SYSTEM
3579 update_window_fringes (w, 0);
3580 #endif
3582 /* End the update of window W. Don't set the cursor if we
3583 paused updating the display because in this case,
3584 set_window_cursor_after_update hasn't been called, and
3585 output_cursor doesn't contain the cursor location. */
3586 rif->update_window_end_hook (w, !paused_p, mouse_face_overwritten_p);
3588 else
3589 paused_p = 1;
3591 #ifdef GLYPH_DEBUG
3592 /* check_current_matrix_flags (w); */
3593 add_window_display_history (w, w->current_matrix->method, paused_p);
3594 #endif
3596 clear_glyph_matrix (desired_matrix);
3598 return paused_p;
3602 /* Update the display of area AREA in window W, row number VPOS.
3603 AREA can be either LEFT_MARGIN_AREA or RIGHT_MARGIN_AREA. */
3605 static void
3606 update_marginal_area (struct window *w, int area, int vpos)
3608 struct glyph_row *desired_row = MATRIX_ROW (w->desired_matrix, vpos);
3609 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3611 /* Let functions in xterm.c know what area subsequent X positions
3612 will be relative to. */
3613 updated_area = area;
3615 /* Set cursor to start of glyphs, write them, and clear to the end
3616 of the area. I don't think that something more sophisticated is
3617 necessary here, since marginal areas will not be the default. */
3618 rif->cursor_to (vpos, 0, desired_row->y, 0);
3619 if (desired_row->used[area])
3620 rif->write_glyphs (desired_row->glyphs[area], desired_row->used[area]);
3621 rif->clear_end_of_line (-1);
3625 /* Update the display of the text area of row VPOS in window W.
3626 Value is true if display has changed. */
3628 static bool
3629 update_text_area (struct window *w, int vpos)
3631 struct glyph_row *current_row = MATRIX_ROW (w->current_matrix, vpos);
3632 struct glyph_row *desired_row = MATRIX_ROW (w->desired_matrix, vpos);
3633 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3634 bool changed_p = 0;
3636 /* Let functions in xterm.c know what area subsequent X positions
3637 will be relative to. */
3638 updated_area = TEXT_AREA;
3640 /* If rows are at different X or Y, or rows have different height,
3641 or the current row is marked invalid, write the entire line. */
3642 if (!current_row->enabled_p
3643 || desired_row->y != current_row->y
3644 || desired_row->ascent != current_row->ascent
3645 || desired_row->phys_ascent != current_row->phys_ascent
3646 || desired_row->phys_height != current_row->phys_height
3647 || desired_row->visible_height != current_row->visible_height
3648 || current_row->overlapped_p
3649 /* This next line is necessary for correctly redrawing
3650 mouse-face areas after scrolling and other operations.
3651 However, it causes excessive flickering when mouse is moved
3652 across the mode line. Luckily, turning it off for the mode
3653 line doesn't seem to hurt anything. -- cyd.
3654 But it is still needed for the header line. -- kfs. */
3655 || (current_row->mouse_face_p
3656 && !(current_row->mode_line_p && vpos > 0))
3657 || current_row->x != desired_row->x)
3659 rif->cursor_to (vpos, 0, desired_row->y, desired_row->x);
3661 if (desired_row->used[TEXT_AREA])
3662 rif->write_glyphs (desired_row->glyphs[TEXT_AREA],
3663 desired_row->used[TEXT_AREA]);
3665 /* Clear to end of window. */
3666 rif->clear_end_of_line (-1);
3667 changed_p = 1;
3669 /* This erases the cursor. We do this here because
3670 notice_overwritten_cursor cannot easily check this, which
3671 might indicate that the whole functionality of
3672 notice_overwritten_cursor would better be implemented here.
3673 On the other hand, we need notice_overwritten_cursor as long
3674 as mouse highlighting is done asynchronously outside of
3675 redisplay. */
3676 if (vpos == w->phys_cursor.vpos)
3677 w->phys_cursor_on_p = 0;
3679 else
3681 int stop, i, x;
3682 struct glyph *current_glyph = current_row->glyphs[TEXT_AREA];
3683 struct glyph *desired_glyph = desired_row->glyphs[TEXT_AREA];
3684 bool overlapping_glyphs_p = current_row->contains_overlapping_glyphs_p;
3685 int desired_stop_pos = desired_row->used[TEXT_AREA];
3686 bool abort_skipping = 0;
3688 /* If the desired row extends its face to the text area end, and
3689 unless the current row also does so at the same position,
3690 make sure we write at least one glyph, so that the face
3691 extension actually takes place. */
3692 if (MATRIX_ROW_EXTENDS_FACE_P (desired_row)
3693 && (desired_stop_pos < current_row->used[TEXT_AREA]
3694 || (desired_stop_pos == current_row->used[TEXT_AREA]
3695 && !MATRIX_ROW_EXTENDS_FACE_P (current_row))))
3696 --desired_stop_pos;
3698 stop = min (current_row->used[TEXT_AREA], desired_stop_pos);
3699 i = 0;
3700 x = desired_row->x;
3702 /* Loop over glyphs that current and desired row may have
3703 in common. */
3704 while (i < stop)
3706 bool can_skip_p = !abort_skipping;
3708 /* Skip over glyphs that both rows have in common. These
3709 don't have to be written. We can't skip if the last
3710 current glyph overlaps the glyph to its right. For
3711 example, consider a current row of `if ' with the `f' in
3712 Courier bold so that it overlaps the ` ' to its right.
3713 If the desired row is ` ', we would skip over the space
3714 after the `if' and there would remain a pixel from the
3715 `f' on the screen. */
3716 if (overlapping_glyphs_p && i > 0)
3718 struct glyph *glyph = &current_row->glyphs[TEXT_AREA][i - 1];
3719 int left, right;
3721 rif->get_glyph_overhangs (glyph, XFRAME (w->frame),
3722 &left, &right);
3723 can_skip_p = (right == 0 && !abort_skipping);
3726 if (can_skip_p)
3728 int start_hpos = i;
3730 while (i < stop
3731 && GLYPH_EQUAL_P (desired_glyph, current_glyph))
3733 x += desired_glyph->pixel_width;
3734 ++desired_glyph, ++current_glyph, ++i;
3737 /* Consider the case that the current row contains "xxx
3738 ppp ggg" in italic Courier font, and the desired row
3739 is "xxx ggg". The character `p' has lbearing, `g'
3740 has not. The loop above will stop in front of the
3741 first `p' in the current row. If we would start
3742 writing glyphs there, we wouldn't erase the lbearing
3743 of the `p'. The rest of the lbearing problem is then
3744 taken care of by draw_glyphs. */
3745 if (overlapping_glyphs_p
3746 && i > 0
3747 && i < current_row->used[TEXT_AREA]
3748 && (current_row->used[TEXT_AREA]
3749 != desired_row->used[TEXT_AREA]))
3751 int left, right;
3753 rif->get_glyph_overhangs (current_glyph,
3754 XFRAME (w->frame),
3755 &left, &right);
3756 while (left > 0 && i > 0)
3758 --i, --desired_glyph, --current_glyph;
3759 x -= desired_glyph->pixel_width;
3760 left -= desired_glyph->pixel_width;
3763 /* Abort the skipping algorithm if we end up before
3764 our starting point, to avoid looping (bug#1070).
3765 This can happen when the lbearing is larger than
3766 the pixel width. */
3767 abort_skipping = (i < start_hpos);
3771 /* Try to avoid writing the entire rest of the desired row
3772 by looking for a resync point. This mainly prevents
3773 mode line flickering in the case the mode line is in
3774 fixed-pitch font, which it usually will be. */
3775 if (i < desired_row->used[TEXT_AREA])
3777 int start_x = x, start_hpos = i;
3778 struct glyph *start = desired_glyph;
3779 int current_x = x;
3780 bool skip_first_p = !can_skip_p;
3782 /* Find the next glyph that's equal again. */
3783 while (i < stop
3784 && (skip_first_p
3785 || !GLYPH_EQUAL_P (desired_glyph, current_glyph))
3786 && x == current_x)
3788 x += desired_glyph->pixel_width;
3789 current_x += current_glyph->pixel_width;
3790 ++desired_glyph, ++current_glyph, ++i;
3791 skip_first_p = 0;
3794 if (i == start_hpos || x != current_x)
3796 i = start_hpos;
3797 x = start_x;
3798 desired_glyph = start;
3799 break;
3802 rif->cursor_to (vpos, start_hpos, desired_row->y, start_x);
3803 rif->write_glyphs (start, i - start_hpos);
3804 changed_p = 1;
3808 /* Write the rest. */
3809 if (i < desired_row->used[TEXT_AREA])
3811 rif->cursor_to (vpos, i, desired_row->y, x);
3812 rif->write_glyphs (desired_glyph, desired_row->used[TEXT_AREA] - i);
3813 changed_p = 1;
3816 /* Maybe clear to end of line. */
3817 if (MATRIX_ROW_EXTENDS_FACE_P (desired_row))
3819 /* If new row extends to the end of the text area, nothing
3820 has to be cleared, if and only if we did a write_glyphs
3821 above. This is made sure by setting desired_stop_pos
3822 appropriately above. */
3823 eassert (i < desired_row->used[TEXT_AREA]
3824 || ((desired_row->used[TEXT_AREA]
3825 == current_row->used[TEXT_AREA])
3826 && MATRIX_ROW_EXTENDS_FACE_P (current_row)));
3828 else if (MATRIX_ROW_EXTENDS_FACE_P (current_row))
3830 /* If old row extends to the end of the text area, clear. */
3831 if (i >= desired_row->used[TEXT_AREA])
3832 rif->cursor_to (vpos, i, desired_row->y,
3833 desired_row->pixel_width);
3834 rif->clear_end_of_line (-1);
3835 changed_p = 1;
3837 else if (desired_row->pixel_width < current_row->pixel_width)
3839 /* Otherwise clear to the end of the old row. Everything
3840 after that position should be clear already. */
3841 int xlim;
3843 if (i >= desired_row->used[TEXT_AREA])
3844 rif->cursor_to (vpos, i, desired_row->y,
3845 desired_row->pixel_width);
3847 /* If cursor is displayed at the end of the line, make sure
3848 it's cleared. Nowadays we don't have a phys_cursor_glyph
3849 with which to erase the cursor (because this method
3850 doesn't work with lbearing/rbearing), so we must do it
3851 this way. */
3852 if (vpos == w->phys_cursor.vpos
3853 && (desired_row->reversed_p
3854 ? (w->phys_cursor.hpos < 0)
3855 : (w->phys_cursor.hpos >= desired_row->used[TEXT_AREA])))
3857 w->phys_cursor_on_p = 0;
3858 xlim = -1;
3860 else
3861 xlim = current_row->pixel_width;
3862 rif->clear_end_of_line (xlim);
3863 changed_p = 1;
3867 return changed_p;
3871 /* Update row VPOS in window W. Value is true if display has been changed. */
3873 static bool
3874 update_window_line (struct window *w, int vpos, bool *mouse_face_overwritten_p)
3876 struct glyph_row *current_row = MATRIX_ROW (w->current_matrix, vpos);
3877 struct glyph_row *desired_row = MATRIX_ROW (w->desired_matrix, vpos);
3878 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
3879 bool changed_p = 0;
3881 /* Set the row being updated. This is important to let xterm.c
3882 know what line height values are in effect. */
3883 updated_row = desired_row;
3885 /* A row can be completely invisible in case a desired matrix was
3886 built with a vscroll and then make_cursor_line_fully_visible shifts
3887 the matrix. Make sure to make such rows current anyway, since
3888 we need the correct y-position, for example, in the current matrix. */
3889 if (desired_row->mode_line_p
3890 || desired_row->visible_height > 0)
3892 eassert (desired_row->enabled_p);
3894 /* Update display of the left margin area, if there is one. */
3895 if (!desired_row->full_width_p
3896 && !NILP (w->left_margin_cols))
3898 changed_p = 1;
3899 update_marginal_area (w, LEFT_MARGIN_AREA, vpos);
3900 /* Setting this flag will ensure the vertical border, if
3901 any, between this window and the one on its left will be
3902 redrawn. This is necessary because updating the left
3903 margin area can potentially draw over the border. */
3904 current_row->redraw_fringe_bitmaps_p = 1;
3907 /* Update the display of the text area. */
3908 if (update_text_area (w, vpos))
3910 changed_p = 1;
3911 if (current_row->mouse_face_p)
3912 *mouse_face_overwritten_p = 1;
3915 /* Update display of the right margin area, if there is one. */
3916 if (!desired_row->full_width_p
3917 && !NILP (w->right_margin_cols))
3919 changed_p = 1;
3920 update_marginal_area (w, RIGHT_MARGIN_AREA, vpos);
3923 /* Draw truncation marks etc. */
3924 if (!current_row->enabled_p
3925 || desired_row->y != current_row->y
3926 || desired_row->visible_height != current_row->visible_height
3927 || desired_row->cursor_in_fringe_p != current_row->cursor_in_fringe_p
3928 || desired_row->overlay_arrow_bitmap != current_row->overlay_arrow_bitmap
3929 || current_row->redraw_fringe_bitmaps_p
3930 || desired_row->mode_line_p != current_row->mode_line_p
3931 || desired_row->exact_window_width_line_p != current_row->exact_window_width_line_p
3932 || (MATRIX_ROW_CONTINUATION_LINE_P (desired_row)
3933 != MATRIX_ROW_CONTINUATION_LINE_P (current_row)))
3934 rif->after_update_window_line_hook (desired_row);
3937 /* Update current_row from desired_row. */
3938 make_current (w->desired_matrix, w->current_matrix, vpos);
3939 updated_row = NULL;
3940 return changed_p;
3944 /* Set the cursor after an update of window W. This function may only
3945 be called from update_window. */
3947 static void
3948 set_window_cursor_after_update (struct window *w)
3950 struct frame *f = XFRAME (w->frame);
3951 struct redisplay_interface *rif = FRAME_RIF (f);
3952 int cx, cy, vpos, hpos;
3954 /* Not intended for frame matrix updates. */
3955 eassert (FRAME_WINDOW_P (f));
3957 if (cursor_in_echo_area
3958 && !NILP (echo_area_buffer[0])
3959 /* If we are showing a message instead of the mini-buffer,
3960 show the cursor for the message instead. */
3961 && XWINDOW (minibuf_window) == w
3962 && EQ (minibuf_window, echo_area_window)
3963 /* These cases apply only to the frame that contains
3964 the active mini-buffer window. */
3965 && FRAME_HAS_MINIBUF_P (f)
3966 && EQ (FRAME_MINIBUF_WINDOW (f), echo_area_window))
3968 cx = cy = vpos = hpos = 0;
3970 if (cursor_in_echo_area >= 0)
3972 /* If the mini-buffer is several lines high, find the last
3973 line that has any text on it. Note: either all lines
3974 are enabled or none. Otherwise we wouldn't be able to
3975 determine Y. */
3976 struct glyph_row *row, *last_row;
3977 struct glyph *glyph;
3978 int yb = window_text_bottom_y (w);
3980 last_row = NULL;
3981 row = w->current_matrix->rows;
3982 while (row->enabled_p
3983 && (last_row == NULL
3984 || MATRIX_ROW_BOTTOM_Y (row) <= yb))
3986 if (row->used[TEXT_AREA]
3987 && row->glyphs[TEXT_AREA][0].charpos >= 0)
3988 last_row = row;
3989 ++row;
3992 if (last_row)
3994 struct glyph *start = last_row->glyphs[TEXT_AREA];
3995 struct glyph *last = start + last_row->used[TEXT_AREA] - 1;
3997 while (last > start && last->charpos < 0)
3998 --last;
4000 for (glyph = start; glyph < last; ++glyph)
4002 cx += glyph->pixel_width;
4003 ++hpos;
4006 cy = last_row->y;
4007 vpos = MATRIX_ROW_VPOS (last_row, w->current_matrix);
4011 else
4013 cx = w->cursor.x;
4014 cy = w->cursor.y;
4015 hpos = w->cursor.hpos;
4016 vpos = w->cursor.vpos;
4019 /* Window cursor can be out of sync for horizontally split windows. */
4020 hpos = max (-1, hpos); /* -1 is for when cursor is on the left fringe */
4021 hpos = min (w->current_matrix->matrix_w - 1, hpos);
4022 vpos = max (0, vpos);
4023 vpos = min (w->current_matrix->nrows - 1, vpos);
4024 rif->cursor_to (vpos, hpos, cy, cx);
4028 /* Set WINDOW->must_be_updated_p to ON_P for all windows in the window
4029 tree rooted at W. */
4031 void
4032 set_window_update_flags (struct window *w, bool on_p)
4034 while (w)
4036 if (!NILP (w->hchild))
4037 set_window_update_flags (XWINDOW (w->hchild), on_p);
4038 else if (!NILP (w->vchild))
4039 set_window_update_flags (XWINDOW (w->vchild), on_p);
4040 else
4041 w->must_be_updated_p = on_p;
4043 w = NILP (w->next) ? 0 : XWINDOW (w->next);
4049 /***********************************************************************
4050 Window-Based Scrolling
4051 ***********************************************************************/
4053 /* Structure describing rows in scrolling_window. */
4055 struct row_entry
4057 /* Number of occurrences of this row in desired and current matrix. */
4058 int old_uses, new_uses;
4060 /* Vpos of row in new matrix. */
4061 int new_line_number;
4063 /* Bucket index of this row_entry in the hash table row_table. */
4064 ptrdiff_t bucket;
4066 /* The row described by this entry. */
4067 struct glyph_row *row;
4069 /* Hash collision chain. */
4070 struct row_entry *next;
4073 /* A pool to allocate row_entry structures from, and the size of the
4074 pool. The pool is reallocated in scrolling_window when we find
4075 that we need a larger one. */
4077 static struct row_entry *row_entry_pool;
4078 static ptrdiff_t row_entry_pool_size;
4080 /* Index of next free entry in row_entry_pool. */
4082 static ptrdiff_t row_entry_idx;
4084 /* The hash table used during scrolling, and the table's size. This
4085 table is used to quickly identify equal rows in the desired and
4086 current matrix. */
4088 static struct row_entry **row_table;
4089 static ptrdiff_t row_table_size;
4091 /* Vectors of pointers to row_entry structures belonging to the
4092 current and desired matrix, and the size of the vectors. */
4094 static struct row_entry **old_lines, **new_lines;
4095 static ptrdiff_t old_lines_size, new_lines_size;
4097 /* A pool to allocate run structures from, and its size. */
4099 static struct run *run_pool;
4100 static ptrdiff_t runs_size;
4102 /* A vector of runs of lines found during scrolling. */
4104 static struct run **runs;
4106 /* Add glyph row ROW to the scrolling hash table. */
4108 static struct row_entry *
4109 add_row_entry (struct glyph_row *row)
4111 struct row_entry *entry;
4112 ptrdiff_t i = row->hash % row_table_size;
4114 entry = row_table[i];
4115 eassert (entry || verify_row_hash (row));
4116 while (entry && !row_equal_p (entry->row, row, 1))
4117 entry = entry->next;
4119 if (entry == NULL)
4121 entry = row_entry_pool + row_entry_idx++;
4122 entry->row = row;
4123 entry->old_uses = entry->new_uses = 0;
4124 entry->new_line_number = 0;
4125 entry->bucket = i;
4126 entry->next = row_table[i];
4127 row_table[i] = entry;
4130 return entry;
4134 /* Try to reuse part of the current display of W by scrolling lines.
4135 HEADER_LINE_P means W has a header line.
4137 The algorithm is taken from Communications of the ACM, Apr78 "A
4138 Technique for Isolating Differences Between Files." It should take
4139 O(N) time.
4141 A short outline of the steps of the algorithm
4143 1. Skip lines equal at the start and end of both matrices.
4145 2. Enter rows in the current and desired matrix into a symbol
4146 table, counting how often they appear in both matrices.
4148 3. Rows that appear exactly once in both matrices serve as anchors,
4149 i.e. we assume that such lines are likely to have been moved.
4151 4. Starting from anchor lines, extend regions to be scrolled both
4152 forward and backward.
4154 Value is
4156 -1 if all rows were found to be equal.
4157 0 to indicate that we did not scroll the display, or
4158 1 if we did scroll. */
4160 static int
4161 scrolling_window (struct window *w, bool header_line_p)
4163 struct glyph_matrix *desired_matrix = w->desired_matrix;
4164 struct glyph_matrix *current_matrix = w->current_matrix;
4165 int yb = window_text_bottom_y (w);
4166 ptrdiff_t i;
4167 int j, first_old, first_new, last_old, last_new;
4168 int nruns, run_idx;
4169 ptrdiff_t n;
4170 struct row_entry *entry;
4171 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
4173 /* Skip over rows equal at the start. */
4174 for (i = header_line_p; i < current_matrix->nrows - 1; ++i)
4176 struct glyph_row *d = MATRIX_ROW (desired_matrix, i);
4177 struct glyph_row *c = MATRIX_ROW (current_matrix, i);
4179 if (c->enabled_p
4180 && d->enabled_p
4181 && !d->redraw_fringe_bitmaps_p
4182 && c->y == d->y
4183 && MATRIX_ROW_BOTTOM_Y (c) <= yb
4184 && MATRIX_ROW_BOTTOM_Y (d) <= yb
4185 && row_equal_p (c, d, 1))
4187 assign_row (c, d);
4188 d->enabled_p = 0;
4190 else
4191 break;
4194 /* Give up if some rows in the desired matrix are not enabled. */
4195 if (!MATRIX_ROW (desired_matrix, i)->enabled_p)
4196 return -1;
4198 first_old = first_new = i;
4200 /* Set last_new to the index + 1 of the row that reaches the
4201 bottom boundary in the desired matrix. Give up if we find a
4202 disabled row before we reach the bottom boundary. */
4203 i = first_new + 1;
4204 while (i < desired_matrix->nrows - 1)
4206 int bottom;
4208 if (!MATRIX_ROW (desired_matrix, i)->enabled_p)
4209 return 0;
4210 bottom = MATRIX_ROW_BOTTOM_Y (MATRIX_ROW (desired_matrix, i));
4211 if (bottom <= yb)
4212 ++i;
4213 if (bottom >= yb)
4214 break;
4217 last_new = i;
4219 /* Set last_old to the index + 1 of the row that reaches the bottom
4220 boundary in the current matrix. We don't look at the enabled
4221 flag here because we plan to reuse part of the display even if
4222 other parts are disabled. */
4223 i = first_old + 1;
4224 while (i < current_matrix->nrows - 1)
4226 int bottom = MATRIX_ROW_BOTTOM_Y (MATRIX_ROW (current_matrix, i));
4227 if (bottom <= yb)
4228 ++i;
4229 if (bottom >= yb)
4230 break;
4233 last_old = i;
4235 /* Skip over rows equal at the bottom. */
4236 i = last_new;
4237 j = last_old;
4238 while (i - 1 > first_new
4239 && j - 1 > first_old
4240 && MATRIX_ROW (current_matrix, j - 1)->enabled_p
4241 && (MATRIX_ROW (current_matrix, j - 1)->y
4242 == MATRIX_ROW (desired_matrix, i - 1)->y)
4243 && !MATRIX_ROW (desired_matrix, i - 1)->redraw_fringe_bitmaps_p
4244 && row_equal_p (MATRIX_ROW (desired_matrix, i - 1),
4245 MATRIX_ROW (current_matrix, j - 1), 1))
4246 --i, --j;
4247 last_new = i;
4248 last_old = j;
4250 /* Nothing to do if all rows are equal. */
4251 if (last_new == first_new)
4252 return 0;
4254 /* Check for integer overflow in size calculation.
4256 If next_almost_prime checks (N) for divisibility by 2..10, then
4257 it can return at most N + 10, e.g., next_almost_prime (1) == 11.
4258 So, set next_almost_prime_increment_max to 10.
4260 It's just a coincidence that next_almost_prime_increment_max ==
4261 NEXT_ALMOST_PRIME_LIMIT - 1. If NEXT_ALMOST_PRIME_LIMIT were
4262 13, then next_almost_prime_increment_max would be 14, e.g.,
4263 because next_almost_prime (113) would be 127. */
4265 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
4266 enum { next_almost_prime_increment_max = 10 };
4267 ptrdiff_t row_table_max =
4268 (min (PTRDIFF_MAX, SIZE_MAX) / (3 * sizeof *row_table)
4269 - next_almost_prime_increment_max);
4270 ptrdiff_t current_nrows_max = row_table_max - desired_matrix->nrows;
4271 if (current_nrows_max < current_matrix->nrows)
4272 memory_full (SIZE_MAX);
4275 /* Reallocate vectors, tables etc. if necessary. */
4277 if (current_matrix->nrows > old_lines_size)
4278 old_lines = xpalloc (old_lines, &old_lines_size,
4279 current_matrix->nrows - old_lines_size,
4280 INT_MAX, sizeof *old_lines);
4282 if (desired_matrix->nrows > new_lines_size)
4283 new_lines = xpalloc (new_lines, &new_lines_size,
4284 desired_matrix->nrows - new_lines_size,
4285 INT_MAX, sizeof *new_lines);
4287 n = desired_matrix->nrows;
4288 n += current_matrix->nrows;
4289 if (row_table_size < 3 * n)
4291 ptrdiff_t size = next_almost_prime (3 * n);
4292 row_table = xnrealloc (row_table, size, sizeof *row_table);
4293 row_table_size = size;
4294 memset (row_table, 0, size * sizeof *row_table);
4297 if (n > row_entry_pool_size)
4298 row_entry_pool = xpalloc (row_entry_pool, &row_entry_pool_size,
4299 n - row_entry_pool_size,
4300 -1, sizeof *row_entry_pool);
4302 if (desired_matrix->nrows > runs_size)
4304 runs = xnrealloc (runs, desired_matrix->nrows, sizeof *runs);
4305 run_pool = xnrealloc (run_pool, desired_matrix->nrows, sizeof *run_pool);
4306 runs_size = desired_matrix->nrows;
4309 nruns = run_idx = 0;
4310 row_entry_idx = 0;
4312 /* Add rows from the current and desired matrix to the hash table
4313 row_hash_table to be able to find equal ones quickly. */
4315 for (i = first_old; i < last_old; ++i)
4317 if (MATRIX_ROW (current_matrix, i)->enabled_p)
4319 entry = add_row_entry (MATRIX_ROW (current_matrix, i));
4320 old_lines[i] = entry;
4321 ++entry->old_uses;
4323 else
4324 old_lines[i] = NULL;
4327 for (i = first_new; i < last_new; ++i)
4329 eassert (MATRIX_ROW_ENABLED_P (desired_matrix, i));
4330 entry = add_row_entry (MATRIX_ROW (desired_matrix, i));
4331 ++entry->new_uses;
4332 entry->new_line_number = i;
4333 new_lines[i] = entry;
4336 /* Identify moves based on lines that are unique and equal
4337 in both matrices. */
4338 for (i = first_old; i < last_old;)
4339 if (old_lines[i]
4340 && old_lines[i]->old_uses == 1
4341 && old_lines[i]->new_uses == 1)
4343 int p, q;
4344 int new_line = old_lines[i]->new_line_number;
4345 struct run *run = run_pool + run_idx++;
4347 /* Record move. */
4348 run->current_vpos = i;
4349 run->current_y = MATRIX_ROW (current_matrix, i)->y;
4350 run->desired_vpos = new_line;
4351 run->desired_y = MATRIX_ROW (desired_matrix, new_line)->y;
4352 run->nrows = 1;
4353 run->height = MATRIX_ROW (current_matrix, i)->height;
4355 /* Extend backward. */
4356 p = i - 1;
4357 q = new_line - 1;
4358 while (p > first_old
4359 && q > first_new
4360 && old_lines[p] == new_lines[q])
4362 int h = MATRIX_ROW (current_matrix, p)->height;
4363 --run->current_vpos;
4364 --run->desired_vpos;
4365 ++run->nrows;
4366 run->height += h;
4367 run->desired_y -= h;
4368 run->current_y -= h;
4369 --p, --q;
4372 /* Extend forward. */
4373 p = i + 1;
4374 q = new_line + 1;
4375 while (p < last_old
4376 && q < last_new
4377 && old_lines[p] == new_lines[q])
4379 int h = MATRIX_ROW (current_matrix, p)->height;
4380 ++run->nrows;
4381 run->height += h;
4382 ++p, ++q;
4385 /* Insert run into list of all runs. Order runs by copied
4386 pixel lines. Note that we record runs that don't have to
4387 be copied because they are already in place. This is done
4388 because we can avoid calling update_window_line in this
4389 case. */
4390 for (p = 0; p < nruns && runs[p]->height > run->height; ++p)
4392 for (q = nruns; q > p; --q)
4393 runs[q] = runs[q - 1];
4394 runs[p] = run;
4395 ++nruns;
4397 i += run->nrows;
4399 else
4400 ++i;
4402 /* Do the moves. Do it in a way that we don't overwrite something
4403 we want to copy later on. This is not solvable in general
4404 because there is only one display and we don't have a way to
4405 exchange areas on this display. Example:
4407 +-----------+ +-----------+
4408 | A | | B |
4409 +-----------+ --> +-----------+
4410 | B | | A |
4411 +-----------+ +-----------+
4413 Instead, prefer bigger moves, and invalidate moves that would
4414 copy from where we copied to. */
4416 for (i = 0; i < nruns; ++i)
4417 if (runs[i]->nrows > 0)
4419 struct run *r = runs[i];
4421 /* Copy on the display. */
4422 if (r->current_y != r->desired_y)
4424 rif->clear_window_mouse_face (w);
4425 rif->scroll_run_hook (w, r);
4428 /* Truncate runs that copy to where we copied to, and
4429 invalidate runs that copy from where we copied to. */
4430 for (j = nruns - 1; j > i; --j)
4432 struct run *p = runs[j];
4433 bool truncated_p = 0;
4435 if (p->nrows > 0
4436 && p->desired_y < r->desired_y + r->height
4437 && p->desired_y + p->height > r->desired_y)
4439 if (p->desired_y < r->desired_y)
4441 p->nrows = r->desired_vpos - p->desired_vpos;
4442 p->height = r->desired_y - p->desired_y;
4443 truncated_p = 1;
4445 else
4447 int nrows_copied = (r->desired_vpos + r->nrows
4448 - p->desired_vpos);
4450 if (p->nrows <= nrows_copied)
4451 p->nrows = 0;
4452 else
4454 int height_copied = (r->desired_y + r->height
4455 - p->desired_y);
4457 p->current_vpos += nrows_copied;
4458 p->desired_vpos += nrows_copied;
4459 p->nrows -= nrows_copied;
4460 p->current_y += height_copied;
4461 p->desired_y += height_copied;
4462 p->height -= height_copied;
4463 truncated_p = 1;
4468 if (r->current_y != r->desired_y
4469 /* The condition below is equivalent to
4470 ((p->current_y >= r->desired_y
4471 && p->current_y < r->desired_y + r->height)
4472 || (p->current_y + p->height > r->desired_y
4473 && (p->current_y + p->height
4474 <= r->desired_y + r->height)))
4475 because we have 0 < p->height <= r->height. */
4476 && p->current_y < r->desired_y + r->height
4477 && p->current_y + p->height > r->desired_y)
4478 p->nrows = 0;
4480 /* Reorder runs by copied pixel lines if truncated. */
4481 if (truncated_p && p->nrows > 0)
4483 int k = nruns - 1;
4485 while (runs[k]->nrows == 0 || runs[k]->height < p->height)
4486 k--;
4487 memmove (runs + j, runs + j + 1, (k - j) * sizeof (*runs));
4488 runs[k] = p;
4492 /* Assign matrix rows. */
4493 for (j = 0; j < r->nrows; ++j)
4495 struct glyph_row *from, *to;
4496 bool to_overlapped_p;
4498 to = MATRIX_ROW (current_matrix, r->desired_vpos + j);
4499 from = MATRIX_ROW (desired_matrix, r->desired_vpos + j);
4500 to_overlapped_p = to->overlapped_p;
4501 from->redraw_fringe_bitmaps_p = from->fringe_bitmap_periodic_p;
4502 assign_row (to, from);
4503 /* The above `assign_row' actually does swap, so if we had
4504 an overlap in the copy destination of two runs, then
4505 the second run would assign a previously disabled bogus
4506 row. But thanks to the truncation code in the
4507 preceding for-loop, we no longer have such an overlap,
4508 and thus the assigned row should always be enabled. */
4509 eassert (to->enabled_p);
4510 from->enabled_p = 0;
4511 to->overlapped_p = to_overlapped_p;
4515 /* Clear the hash table, for the next time. */
4516 for (i = 0; i < row_entry_idx; ++i)
4517 row_table[row_entry_pool[i].bucket] = NULL;
4519 /* Value is 1 to indicate that we scrolled the display. */
4520 return 0 < nruns;
4525 /************************************************************************
4526 Frame-Based Updates
4527 ************************************************************************/
4529 /* Update the desired frame matrix of frame F.
4531 FORCE_P means that the update should not be stopped by pending input.
4532 INHIBIT_HAIRY_ID_P means that scrolling should not be tried.
4534 Value is true if update was stopped due to pending input. */
4536 static bool
4537 update_frame_1 (struct frame *f, bool force_p, bool inhibit_id_p)
4539 /* Frame matrices to work on. */
4540 struct glyph_matrix *current_matrix = f->current_matrix;
4541 struct glyph_matrix *desired_matrix = f->desired_matrix;
4542 int i;
4543 bool pause_p;
4544 int preempt_count = baud_rate / 2400 + 1;
4546 eassert (current_matrix && desired_matrix);
4548 if (baud_rate != FRAME_COST_BAUD_RATE (f))
4549 calculate_costs (f);
4551 if (preempt_count <= 0)
4552 preempt_count = 1;
4554 #if !PERIODIC_PREEMPTION_CHECKING
4555 if (!force_p && detect_input_pending_ignore_squeezables ())
4557 pause_p = 1;
4558 goto do_pause;
4560 #endif
4562 /* If we cannot insert/delete lines, it's no use trying it. */
4563 if (!FRAME_LINE_INS_DEL_OK (f))
4564 inhibit_id_p = 1;
4566 /* See if any of the desired lines are enabled; don't compute for
4567 i/d line if just want cursor motion. */
4568 for (i = 0; i < desired_matrix->nrows; i++)
4569 if (MATRIX_ROW_ENABLED_P (desired_matrix, i))
4570 break;
4572 /* Try doing i/d line, if not yet inhibited. */
4573 if (!inhibit_id_p && i < desired_matrix->nrows)
4574 force_p |= scrolling (f);
4576 /* Update the individual lines as needed. Do bottom line first. */
4577 if (MATRIX_ROW_ENABLED_P (desired_matrix, desired_matrix->nrows - 1))
4578 update_frame_line (f, desired_matrix->nrows - 1);
4580 /* Now update the rest of the lines. */
4581 for (i = 0; i < desired_matrix->nrows - 1 && (force_p || !input_pending); i++)
4583 if (MATRIX_ROW_ENABLED_P (desired_matrix, i))
4585 if (FRAME_TERMCAP_P (f))
4587 /* Flush out every so many lines.
4588 Also flush out if likely to have more than 1k buffered
4589 otherwise. I'm told that some telnet connections get
4590 really screwed by more than 1k output at once. */
4591 FILE *display_output = FRAME_TTY (f)->output;
4592 if (display_output)
4594 ptrdiff_t outq = __fpending (display_output);
4595 if (outq > 900
4596 || (outq > 20 && ((i - 1) % preempt_count == 0)))
4597 fflush (display_output);
4601 #if PERIODIC_PREEMPTION_CHECKING
4602 if (!force_p)
4604 EMACS_TIME tm = current_emacs_time ();
4605 if (EMACS_TIME_LT (preemption_next_check, tm))
4607 preemption_next_check = add_emacs_time (tm, preemption_period);
4608 if (detect_input_pending_ignore_squeezables ())
4609 break;
4612 #else
4613 if (!force_p && (i - 1) % preempt_count == 0)
4614 detect_input_pending_ignore_squeezables ();
4615 #endif
4617 update_frame_line (f, i);
4621 lint_assume (0 <= FRAME_LINES (f));
4622 pause_p = 0 < i && i < FRAME_LINES (f) - 1;
4624 /* Now just clean up termcap drivers and set cursor, etc. */
4625 if (!pause_p)
4627 if ((cursor_in_echo_area
4628 /* If we are showing a message instead of the mini-buffer,
4629 show the cursor for the message instead of for the
4630 (now hidden) mini-buffer contents. */
4631 || (EQ (minibuf_window, selected_window)
4632 && EQ (minibuf_window, echo_area_window)
4633 && !NILP (echo_area_buffer[0])))
4634 /* These cases apply only to the frame that contains
4635 the active mini-buffer window. */
4636 && FRAME_HAS_MINIBUF_P (f)
4637 && EQ (FRAME_MINIBUF_WINDOW (f), echo_area_window))
4639 int top = WINDOW_TOP_EDGE_LINE (XWINDOW (FRAME_MINIBUF_WINDOW (f)));
4640 int row, col;
4642 if (cursor_in_echo_area < 0)
4644 /* Negative value of cursor_in_echo_area means put
4645 cursor at beginning of line. */
4646 row = top;
4647 col = 0;
4649 else
4651 /* Positive value of cursor_in_echo_area means put
4652 cursor at the end of the prompt. If the mini-buffer
4653 is several lines high, find the last line that has
4654 any text on it. */
4655 row = FRAME_LINES (f);
4658 --row;
4659 col = 0;
4661 if (MATRIX_ROW_ENABLED_P (current_matrix, row))
4663 /* Frame rows are filled up with spaces that
4664 must be ignored here. */
4665 struct glyph_row *r = MATRIX_ROW (current_matrix,
4666 row);
4667 struct glyph *start = r->glyphs[TEXT_AREA];
4668 struct glyph *last = start + r->used[TEXT_AREA];
4670 while (last > start
4671 && (last - 1)->charpos < 0)
4672 --last;
4674 col = last - start;
4677 while (row > top && col == 0);
4679 /* Make sure COL is not out of range. */
4680 if (col >= FRAME_CURSOR_X_LIMIT (f))
4682 /* If we have another row, advance cursor into it. */
4683 if (row < FRAME_LINES (f) - 1)
4685 col = FRAME_LEFT_SCROLL_BAR_COLS (f);
4686 row++;
4688 /* Otherwise move it back in range. */
4689 else
4690 col = FRAME_CURSOR_X_LIMIT (f) - 1;
4694 cursor_to (f, row, col);
4696 else
4698 /* We have only one cursor on terminal frames. Use it to
4699 display the cursor of the selected window. */
4700 struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
4701 if (w->cursor.vpos >= 0
4702 /* The cursor vpos may be temporarily out of bounds
4703 in the following situation: There is one window,
4704 with the cursor in the lower half of it. The window
4705 is split, and a message causes a redisplay before
4706 a new cursor position has been computed. */
4707 && w->cursor.vpos < WINDOW_TOTAL_LINES (w))
4709 int x = WINDOW_TO_FRAME_HPOS (w, w->cursor.hpos);
4710 int y = WINDOW_TO_FRAME_VPOS (w, w->cursor.vpos);
4712 if (INTEGERP (w->left_margin_cols))
4713 x += XFASTINT (w->left_margin_cols);
4715 /* x = max (min (x, FRAME_TOTAL_COLS (f) - 1), 0); */
4716 cursor_to (f, y, x);
4721 #if !PERIODIC_PREEMPTION_CHECKING
4722 do_pause:
4723 #endif
4725 clear_desired_matrices (f);
4726 return pause_p;
4730 /* Do line insertions/deletions on frame F for frame-based redisplay. */
4732 static bool
4733 scrolling (struct frame *frame)
4735 int unchanged_at_top, unchanged_at_bottom;
4736 int window_size;
4737 int changed_lines;
4738 int *old_hash = alloca (FRAME_LINES (frame) * sizeof (int));
4739 int *new_hash = alloca (FRAME_LINES (frame) * sizeof (int));
4740 int *draw_cost = alloca (FRAME_LINES (frame) * sizeof (int));
4741 int *old_draw_cost = alloca (FRAME_LINES (frame) * sizeof (int));
4742 register int i;
4743 int free_at_end_vpos = FRAME_LINES (frame);
4744 struct glyph_matrix *current_matrix = frame->current_matrix;
4745 struct glyph_matrix *desired_matrix = frame->desired_matrix;
4747 if (!current_matrix)
4748 emacs_abort ();
4750 /* Compute hash codes of all the lines. Also calculate number of
4751 changed lines, number of unchanged lines at the beginning, and
4752 number of unchanged lines at the end. */
4753 changed_lines = 0;
4754 unchanged_at_top = 0;
4755 unchanged_at_bottom = FRAME_LINES (frame);
4756 for (i = 0; i < FRAME_LINES (frame); i++)
4758 /* Give up on this scrolling if some old lines are not enabled. */
4759 if (!MATRIX_ROW_ENABLED_P (current_matrix, i))
4760 return 0;
4761 old_hash[i] = line_hash_code (MATRIX_ROW (current_matrix, i));
4762 if (! MATRIX_ROW_ENABLED_P (desired_matrix, i))
4764 /* This line cannot be redrawn, so don't let scrolling mess it. */
4765 new_hash[i] = old_hash[i];
4766 #define INFINITY 1000000 /* Taken from scroll.c */
4767 draw_cost[i] = INFINITY;
4769 else
4771 new_hash[i] = line_hash_code (MATRIX_ROW (desired_matrix, i));
4772 draw_cost[i] = line_draw_cost (desired_matrix, i);
4775 if (old_hash[i] != new_hash[i])
4777 changed_lines++;
4778 unchanged_at_bottom = FRAME_LINES (frame) - i - 1;
4780 else if (i == unchanged_at_top)
4781 unchanged_at_top++;
4782 old_draw_cost[i] = line_draw_cost (current_matrix, i);
4785 /* If changed lines are few, don't allow preemption, don't scroll. */
4786 if ((!FRAME_SCROLL_REGION_OK (frame)
4787 && changed_lines < baud_rate / 2400)
4788 || unchanged_at_bottom == FRAME_LINES (frame))
4789 return 1;
4791 window_size = (FRAME_LINES (frame) - unchanged_at_top
4792 - unchanged_at_bottom);
4794 if (FRAME_SCROLL_REGION_OK (frame))
4795 free_at_end_vpos -= unchanged_at_bottom;
4796 else if (FRAME_MEMORY_BELOW_FRAME (frame))
4797 free_at_end_vpos = -1;
4799 /* If large window, fast terminal and few lines in common between
4800 current frame and desired frame, don't bother with i/d calc. */
4801 if (!FRAME_SCROLL_REGION_OK (frame)
4802 && window_size >= 18 && baud_rate > 2400
4803 && (window_size >=
4804 10 * scrolling_max_lines_saved (unchanged_at_top,
4805 FRAME_LINES (frame) - unchanged_at_bottom,
4806 old_hash, new_hash, draw_cost)))
4807 return 0;
4809 if (window_size < 2)
4810 return 0;
4812 scrolling_1 (frame, window_size, unchanged_at_top, unchanged_at_bottom,
4813 draw_cost + unchanged_at_top - 1,
4814 old_draw_cost + unchanged_at_top - 1,
4815 old_hash + unchanged_at_top - 1,
4816 new_hash + unchanged_at_top - 1,
4817 free_at_end_vpos - unchanged_at_top);
4819 return 0;
4823 /* Count the number of blanks at the start of the vector of glyphs R
4824 which is LEN glyphs long. */
4826 static int
4827 count_blanks (struct glyph *r, int len)
4829 int i;
4831 for (i = 0; i < len; ++i)
4832 if (!CHAR_GLYPH_SPACE_P (r[i]))
4833 break;
4835 return i;
4839 /* Count the number of glyphs in common at the start of the glyph
4840 vectors STR1 and STR2. END1 is the end of STR1 and END2 is the end
4841 of STR2. Value is the number of equal glyphs equal at the start. */
4843 static int
4844 count_match (struct glyph *str1, struct glyph *end1, struct glyph *str2, struct glyph *end2)
4846 struct glyph *p1 = str1;
4847 struct glyph *p2 = str2;
4849 while (p1 < end1
4850 && p2 < end2
4851 && GLYPH_CHAR_AND_FACE_EQUAL_P (p1, p2))
4852 ++p1, ++p2;
4854 return p1 - str1;
4858 /* Char insertion/deletion cost vector, from term.c */
4860 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_TOTAL_COLS ((f))])
4863 /* Perform a frame-based update on line VPOS in frame FRAME. */
4865 static void
4866 update_frame_line (struct frame *f, int vpos)
4868 struct glyph *obody, *nbody, *op1, *op2, *np1, *nend;
4869 int tem;
4870 int osp, nsp, begmatch, endmatch, olen, nlen;
4871 struct glyph_matrix *current_matrix = f->current_matrix;
4872 struct glyph_matrix *desired_matrix = f->desired_matrix;
4873 struct glyph_row *current_row = MATRIX_ROW (current_matrix, vpos);
4874 struct glyph_row *desired_row = MATRIX_ROW (desired_matrix, vpos);
4875 bool must_write_whole_line_p;
4876 bool write_spaces_p = FRAME_MUST_WRITE_SPACES (f);
4877 bool colored_spaces_p = (FACE_FROM_ID (f, DEFAULT_FACE_ID)->background
4878 != FACE_TTY_DEFAULT_BG_COLOR);
4880 if (colored_spaces_p)
4881 write_spaces_p = 1;
4883 /* Current row not enabled means it has unknown contents. We must
4884 write the whole desired line in that case. */
4885 must_write_whole_line_p = !current_row->enabled_p;
4886 if (must_write_whole_line_p)
4888 obody = 0;
4889 olen = 0;
4891 else
4893 obody = MATRIX_ROW_GLYPH_START (current_matrix, vpos);
4894 olen = current_row->used[TEXT_AREA];
4896 /* Ignore trailing spaces, if we can. */
4897 if (!write_spaces_p)
4898 while (olen > 0 && CHAR_GLYPH_SPACE_P (obody[olen-1]))
4899 olen--;
4902 current_row->enabled_p = 1;
4903 current_row->used[TEXT_AREA] = desired_row->used[TEXT_AREA];
4905 /* If desired line is empty, just clear the line. */
4906 if (!desired_row->enabled_p)
4908 nlen = 0;
4909 goto just_erase;
4912 nbody = desired_row->glyphs[TEXT_AREA];
4913 nlen = desired_row->used[TEXT_AREA];
4914 nend = nbody + nlen;
4916 /* If display line has unknown contents, write the whole line. */
4917 if (must_write_whole_line_p)
4919 /* Ignore spaces at the end, if we can. */
4920 if (!write_spaces_p)
4921 while (nlen > 0 && CHAR_GLYPH_SPACE_P (nbody[nlen - 1]))
4922 --nlen;
4924 /* Write the contents of the desired line. */
4925 if (nlen)
4927 cursor_to (f, vpos, 0);
4928 write_glyphs (f, nbody, nlen);
4931 /* Don't call clear_end_of_line if we already wrote the whole
4932 line. The cursor will not be at the right margin in that
4933 case but in the line below. */
4934 if (nlen < FRAME_TOTAL_COLS (f))
4936 cursor_to (f, vpos, nlen);
4937 clear_end_of_line (f, FRAME_TOTAL_COLS (f));
4939 else
4940 /* Make sure we are in the right row, otherwise cursor movement
4941 with cmgoto might use `ch' in the wrong row. */
4942 cursor_to (f, vpos, 0);
4944 make_current (desired_matrix, current_matrix, vpos);
4945 return;
4948 /* Pretend trailing spaces are not there at all,
4949 unless for one reason or another we must write all spaces. */
4950 if (!write_spaces_p)
4951 while (nlen > 0 && CHAR_GLYPH_SPACE_P (nbody[nlen - 1]))
4952 nlen--;
4954 /* If there's no i/d char, quickly do the best we can without it. */
4955 if (!FRAME_CHAR_INS_DEL_OK (f))
4957 int i, j;
4959 /* Find the first glyph in desired row that doesn't agree with
4960 a glyph in the current row, and write the rest from there on. */
4961 for (i = 0; i < nlen; i++)
4963 if (i >= olen || !GLYPH_EQUAL_P (nbody + i, obody + i))
4965 /* Find the end of the run of different glyphs. */
4966 j = i + 1;
4967 while (j < nlen
4968 && (j >= olen
4969 || !GLYPH_EQUAL_P (nbody + j, obody + j)
4970 || CHAR_GLYPH_PADDING_P (nbody[j])))
4971 ++j;
4973 /* Output this run of non-matching chars. */
4974 cursor_to (f, vpos, i);
4975 write_glyphs (f, nbody + i, j - i);
4976 i = j - 1;
4978 /* Now find the next non-match. */
4982 /* Clear the rest of the line, or the non-clear part of it. */
4983 if (olen > nlen)
4985 cursor_to (f, vpos, nlen);
4986 clear_end_of_line (f, olen);
4989 /* Make current row = desired row. */
4990 make_current (desired_matrix, current_matrix, vpos);
4991 return;
4994 /* Here when CHAR_INS_DEL_OK != 0, i.e. we can insert or delete
4995 characters in a row. */
4997 if (!olen)
4999 /* If current line is blank, skip over initial spaces, if
5000 possible, and write the rest. */
5001 if (write_spaces_p)
5002 nsp = 0;
5003 else
5004 nsp = count_blanks (nbody, nlen);
5006 if (nlen > nsp)
5008 cursor_to (f, vpos, nsp);
5009 write_glyphs (f, nbody + nsp, nlen - nsp);
5012 /* Exchange contents between current_frame and new_frame. */
5013 make_current (desired_matrix, current_matrix, vpos);
5014 return;
5017 /* Compute number of leading blanks in old and new contents. */
5018 osp = count_blanks (obody, olen);
5019 nsp = (colored_spaces_p ? 0 : count_blanks (nbody, nlen));
5021 /* Compute number of matching chars starting with first non-blank. */
5022 begmatch = count_match (obody + osp, obody + olen,
5023 nbody + nsp, nbody + nlen);
5025 /* Spaces in new match implicit space past the end of old. */
5026 /* A bug causing this to be a no-op was fixed in 18.29. */
5027 if (!write_spaces_p && osp + begmatch == olen)
5029 np1 = nbody + nsp;
5030 while (np1 + begmatch < nend && CHAR_GLYPH_SPACE_P (np1[begmatch]))
5031 ++begmatch;
5034 /* Avoid doing insert/delete char
5035 just cause number of leading spaces differs
5036 when the following text does not match. */
5037 if (begmatch == 0 && osp != nsp)
5038 osp = nsp = min (osp, nsp);
5040 /* Find matching characters at end of line */
5041 op1 = obody + olen;
5042 np1 = nbody + nlen;
5043 op2 = op1 + begmatch - min (olen - osp, nlen - nsp);
5044 while (op1 > op2
5045 && GLYPH_EQUAL_P (op1 - 1, np1 - 1))
5047 op1--;
5048 np1--;
5050 endmatch = obody + olen - op1;
5052 /* tem gets the distance to insert or delete.
5053 endmatch is how many characters we save by doing so.
5054 Is it worth it? */
5056 tem = (nlen - nsp) - (olen - osp);
5057 if (endmatch && tem
5058 && (!FRAME_CHAR_INS_DEL_OK (f)
5059 || endmatch <= char_ins_del_cost (f)[tem]))
5060 endmatch = 0;
5062 /* nsp - osp is the distance to insert or delete.
5063 If that is nonzero, begmatch is known to be nonzero also.
5064 begmatch + endmatch is how much we save by doing the ins/del.
5065 Is it worth it? */
5067 if (nsp != osp
5068 && (!FRAME_CHAR_INS_DEL_OK (f)
5069 || begmatch + endmatch <= char_ins_del_cost (f)[nsp - osp]))
5071 begmatch = 0;
5072 endmatch = 0;
5073 osp = nsp = min (osp, nsp);
5076 /* Now go through the line, inserting, writing and
5077 deleting as appropriate. */
5079 if (osp > nsp)
5081 cursor_to (f, vpos, nsp);
5082 delete_glyphs (f, osp - nsp);
5084 else if (nsp > osp)
5086 /* If going to delete chars later in line
5087 and insert earlier in the line,
5088 must delete first to avoid losing data in the insert */
5089 if (endmatch && nlen < olen + nsp - osp)
5091 cursor_to (f, vpos, nlen - endmatch + osp - nsp);
5092 delete_glyphs (f, olen + nsp - osp - nlen);
5093 olen = nlen - (nsp - osp);
5095 cursor_to (f, vpos, osp);
5096 insert_glyphs (f, 0, nsp - osp);
5098 olen += nsp - osp;
5100 tem = nsp + begmatch + endmatch;
5101 if (nlen != tem || olen != tem)
5103 if (!endmatch || nlen == olen)
5105 /* If new text being written reaches right margin, there is
5106 no need to do clear-to-eol at the end of this function
5107 (and it would not be safe, since cursor is not going to
5108 be "at the margin" after the text is done). */
5109 if (nlen == FRAME_TOTAL_COLS (f))
5110 olen = 0;
5112 /* Function write_glyphs is prepared to do nothing
5113 if passed a length <= 0. Check it here to avoid
5114 unnecessary cursor movement. */
5115 if (nlen - tem > 0)
5117 cursor_to (f, vpos, nsp + begmatch);
5118 write_glyphs (f, nbody + nsp + begmatch, nlen - tem);
5121 else if (nlen > olen)
5123 /* Here, we used to have the following simple code:
5124 ----------------------------------------
5125 write_glyphs (nbody + nsp + begmatch, olen - tem);
5126 insert_glyphs (nbody + nsp + begmatch + olen - tem, nlen - olen);
5127 ----------------------------------------
5128 but it doesn't work if nbody[nsp + begmatch + olen - tem]
5129 is a padding glyph. */
5130 int out = olen - tem; /* Columns to be overwritten originally. */
5131 int del;
5133 cursor_to (f, vpos, nsp + begmatch);
5135 /* Calculate columns we can actually overwrite. */
5136 while (CHAR_GLYPH_PADDING_P (nbody[nsp + begmatch + out]))
5137 out--;
5138 write_glyphs (f, nbody + nsp + begmatch, out);
5140 /* If we left columns to be overwritten, we must delete them. */
5141 del = olen - tem - out;
5142 if (del > 0)
5143 delete_glyphs (f, del);
5145 /* At last, we insert columns not yet written out. */
5146 insert_glyphs (f, nbody + nsp + begmatch + out, nlen - olen + del);
5147 olen = nlen;
5149 else if (olen > nlen)
5151 cursor_to (f, vpos, nsp + begmatch);
5152 write_glyphs (f, nbody + nsp + begmatch, nlen - tem);
5153 delete_glyphs (f, olen - nlen);
5154 olen = nlen;
5158 just_erase:
5159 /* If any unerased characters remain after the new line, erase them. */
5160 if (olen > nlen)
5162 cursor_to (f, vpos, nlen);
5163 clear_end_of_line (f, olen);
5166 /* Exchange contents between current_frame and new_frame. */
5167 make_current (desired_matrix, current_matrix, vpos);
5172 /***********************************************************************
5173 X/Y Position -> Buffer Position
5174 ***********************************************************************/
5176 /* Determine what's under window-relative pixel position (*X, *Y).
5177 Return the OBJECT (string or buffer) that's there.
5178 Return in *POS the position in that object.
5179 Adjust *X and *Y to character positions.
5180 Return in *DX and *DY the pixel coordinates of the click,
5181 relative to the top left corner of OBJECT, or relative to
5182 the top left corner of the character glyph at (*X, *Y)
5183 if OBJECT is nil.
5184 Return WIDTH and HEIGHT of the object at (*X, *Y), or zero
5185 if the coordinates point to an empty area of the display. */
5187 Lisp_Object
5188 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)
5190 struct it it;
5191 Lisp_Object old_current_buffer = Fcurrent_buffer ();
5192 struct text_pos startp;
5193 Lisp_Object string;
5194 struct glyph_row *row;
5195 #ifdef HAVE_WINDOW_SYSTEM
5196 struct image *img = 0;
5197 #endif
5198 int x0, x1, to_x;
5199 void *itdata = NULL;
5201 /* We used to set current_buffer directly here, but that does the
5202 wrong thing with `face-remapping-alist' (bug#2044). */
5203 Fset_buffer (w->buffer);
5204 itdata = bidi_shelve_cache ();
5205 SET_TEXT_POS_FROM_MARKER (startp, w->start);
5206 CHARPOS (startp) = min (ZV, max (BEGV, CHARPOS (startp)));
5207 BYTEPOS (startp) = min (ZV_BYTE, max (BEGV_BYTE, BYTEPOS (startp)));
5208 start_display (&it, w, startp);
5209 /* start_display takes into account the header-line row, but IT's
5210 vpos still counts from the glyph row that includes the window's
5211 start position. Adjust for a possible header-line row. */
5212 it.vpos += WINDOW_WANTS_HEADER_LINE_P (w);
5214 x0 = *x;
5216 /* First, move to the beginning of the row corresponding to *Y. We
5217 need to be in that row to get the correct value of base paragraph
5218 direction for the text at (*X, *Y). */
5219 move_it_to (&it, -1, 0, *y, -1, MOVE_TO_X | MOVE_TO_Y);
5221 /* TO_X is the pixel position that the iterator will compute for the
5222 glyph at *X. We add it.first_visible_x because iterator
5223 positions include the hscroll. */
5224 to_x = x0 + it.first_visible_x;
5225 if (it.bidi_it.paragraph_dir == R2L)
5226 /* For lines in an R2L paragraph, we need to mirror TO_X wrt the
5227 text area. This is because the iterator, even in R2L
5228 paragraphs, delivers glyphs as if they started at the left
5229 margin of the window. (When we actually produce glyphs for
5230 display, we reverse their order in PRODUCE_GLYPHS, but the
5231 iterator doesn't know about that.) The following line adjusts
5232 the pixel position to the iterator geometry, which is what
5233 move_it_* routines use. (The -1 is because in a window whose
5234 text-area width is W, the rightmost pixel position is W-1, and
5235 it should be mirrored into zero pixel position.) */
5236 to_x = window_box_width (w, TEXT_AREA) - to_x - 1;
5238 /* Now move horizontally in the row to the glyph under *X. Second
5239 argument is ZV to prevent move_it_in_display_line from matching
5240 based on buffer positions. */
5241 move_it_in_display_line (&it, ZV, to_x, MOVE_TO_X);
5242 bidi_unshelve_cache (itdata, 0);
5244 Fset_buffer (old_current_buffer);
5246 *dx = x0 + it.first_visible_x - it.current_x;
5247 *dy = *y - it.current_y;
5249 string = w->buffer;
5250 if (STRINGP (it.string))
5251 string = it.string;
5252 *pos = it.current;
5253 if (it.what == IT_COMPOSITION
5254 && it.cmp_it.nchars > 1
5255 && it.cmp_it.reversed_p)
5257 /* The current display element is a grapheme cluster in a
5258 composition. In that case, we need the position of the first
5259 character of the cluster. But, as it.cmp_it.reversed_p is 1,
5260 it.current points to the last character of the cluster, thus
5261 we must move back to the first character of the same
5262 cluster. */
5263 CHARPOS (pos->pos) -= it.cmp_it.nchars - 1;
5264 if (STRINGP (it.string))
5265 BYTEPOS (pos->pos) = string_char_to_byte (string, CHARPOS (pos->pos));
5266 else
5267 BYTEPOS (pos->pos) = buf_charpos_to_bytepos (XBUFFER (w->buffer),
5268 CHARPOS (pos->pos));
5271 #ifdef HAVE_WINDOW_SYSTEM
5272 if (it.what == IT_IMAGE)
5274 if ((img = IMAGE_FROM_ID (it.f, it.image_id)) != NULL
5275 && !NILP (img->spec))
5276 *object = img->spec;
5278 #endif
5280 if (it.vpos < w->current_matrix->nrows
5281 && (row = MATRIX_ROW (w->current_matrix, it.vpos),
5282 row->enabled_p))
5284 if (it.hpos < row->used[TEXT_AREA])
5286 struct glyph *glyph = row->glyphs[TEXT_AREA] + it.hpos;
5287 #ifdef HAVE_WINDOW_SYSTEM
5288 if (img)
5290 *dy -= row->ascent - glyph->ascent;
5291 *dx += glyph->slice.img.x;
5292 *dy += glyph->slice.img.y;
5293 /* Image slices positions are still relative to the entire image */
5294 *width = img->width;
5295 *height = img->height;
5297 else
5298 #endif
5300 *width = glyph->pixel_width;
5301 *height = glyph->ascent + glyph->descent;
5304 else
5306 *width = 0;
5307 *height = row->height;
5310 else
5312 *width = *height = 0;
5315 /* Add extra (default width) columns if clicked after EOL. */
5316 x1 = max (0, it.current_x + it.pixel_width - it.first_visible_x);
5317 if (x0 > x1)
5318 it.hpos += (x0 - x1) / WINDOW_FRAME_COLUMN_WIDTH (w);
5320 *x = it.hpos;
5321 *y = it.vpos;
5323 return string;
5327 /* Value is the string under window-relative coordinates X/Y in the
5328 mode line or header line (PART says which) of window W, or nil if none.
5329 *CHARPOS is set to the position in the string returned. */
5331 Lisp_Object
5332 mode_line_string (struct window *w, enum window_part part,
5333 int *x, int *y, ptrdiff_t *charpos, Lisp_Object *object,
5334 int *dx, int *dy, int *width, int *height)
5336 struct glyph_row *row;
5337 struct glyph *glyph, *end;
5338 int x0, y0;
5339 Lisp_Object string = Qnil;
5341 if (part == ON_MODE_LINE)
5342 row = MATRIX_MODE_LINE_ROW (w->current_matrix);
5343 else
5344 row = MATRIX_HEADER_LINE_ROW (w->current_matrix);
5345 y0 = *y - row->y;
5346 *y = row - MATRIX_FIRST_TEXT_ROW (w->current_matrix);
5348 if (row->mode_line_p && row->enabled_p)
5350 /* Find the glyph under X. If we find one with a string object,
5351 it's the one we were looking for. */
5352 glyph = row->glyphs[TEXT_AREA];
5353 end = glyph + row->used[TEXT_AREA];
5354 for (x0 = *x; glyph < end && x0 >= glyph->pixel_width; ++glyph)
5355 x0 -= glyph->pixel_width;
5356 *x = glyph - row->glyphs[TEXT_AREA];
5357 if (glyph < end)
5359 string = glyph->object;
5360 *charpos = glyph->charpos;
5361 *width = glyph->pixel_width;
5362 *height = glyph->ascent + glyph->descent;
5363 #ifdef HAVE_WINDOW_SYSTEM
5364 if (glyph->type == IMAGE_GLYPH)
5366 struct image *img;
5367 img = IMAGE_FROM_ID (WINDOW_XFRAME (w), glyph->u.img_id);
5368 if (img != NULL)
5369 *object = img->spec;
5370 y0 -= row->ascent - glyph->ascent;
5372 #endif
5374 else
5376 /* Add extra (default width) columns if clicked after EOL. */
5377 *x += x0 / WINDOW_FRAME_COLUMN_WIDTH (w);
5378 *width = 0;
5379 *height = row->height;
5382 else
5384 *x = 0;
5385 x0 = 0;
5386 *width = *height = 0;
5389 *dx = x0;
5390 *dy = y0;
5392 return string;
5396 /* Value is the string under window-relative coordinates X/Y in either
5397 marginal area, or nil if none. *CHARPOS is set to the position in
5398 the string returned. */
5400 Lisp_Object
5401 marginal_area_string (struct window *w, enum window_part part,
5402 int *x, int *y, ptrdiff_t *charpos, Lisp_Object *object,
5403 int *dx, int *dy, int *width, int *height)
5405 struct glyph_row *row = w->current_matrix->rows;
5406 struct glyph *glyph, *end;
5407 int x0, y0, i, wy = *y;
5408 int area;
5409 Lisp_Object string = Qnil;
5411 if (part == ON_LEFT_MARGIN)
5412 area = LEFT_MARGIN_AREA;
5413 else if (part == ON_RIGHT_MARGIN)
5414 area = RIGHT_MARGIN_AREA;
5415 else
5416 emacs_abort ();
5418 for (i = 0; row->enabled_p && i < w->current_matrix->nrows; ++i, ++row)
5419 if (wy >= row->y && wy < MATRIX_ROW_BOTTOM_Y (row))
5420 break;
5421 y0 = *y - row->y;
5422 *y = row - MATRIX_FIRST_TEXT_ROW (w->current_matrix);
5424 if (row->enabled_p)
5426 /* Find the glyph under X. If we find one with a string object,
5427 it's the one we were looking for. */
5428 if (area == RIGHT_MARGIN_AREA)
5429 x0 = ((WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5430 ? WINDOW_LEFT_FRINGE_WIDTH (w)
5431 : WINDOW_TOTAL_FRINGE_WIDTH (w))
5432 + window_box_width (w, LEFT_MARGIN_AREA)
5433 + window_box_width (w, TEXT_AREA));
5434 else
5435 x0 = (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5436 ? WINDOW_LEFT_FRINGE_WIDTH (w)
5437 : 0);
5439 glyph = row->glyphs[area];
5440 end = glyph + row->used[area];
5441 for (x0 = *x - x0; glyph < end && x0 >= glyph->pixel_width; ++glyph)
5442 x0 -= glyph->pixel_width;
5443 *x = glyph - row->glyphs[area];
5444 if (glyph < end)
5446 string = glyph->object;
5447 *charpos = glyph->charpos;
5448 *width = glyph->pixel_width;
5449 *height = glyph->ascent + glyph->descent;
5450 #ifdef HAVE_WINDOW_SYSTEM
5451 if (glyph->type == IMAGE_GLYPH)
5453 struct image *img;
5454 img = IMAGE_FROM_ID (WINDOW_XFRAME (w), glyph->u.img_id);
5455 if (img != NULL)
5456 *object = img->spec;
5457 y0 -= row->ascent - glyph->ascent;
5458 x0 += glyph->slice.img.x;
5459 y0 += glyph->slice.img.y;
5461 #endif
5463 else
5465 /* Add extra (default width) columns if clicked after EOL. */
5466 *x += x0 / WINDOW_FRAME_COLUMN_WIDTH (w);
5467 *width = 0;
5468 *height = row->height;
5471 else
5473 x0 = 0;
5474 *x = 0;
5475 *width = *height = 0;
5478 *dx = x0;
5479 *dy = y0;
5481 return string;
5485 /***********************************************************************
5486 Changing Frame Sizes
5487 ***********************************************************************/
5489 #ifdef SIGWINCH
5491 static void deliver_window_change_signal (int);
5493 static void
5494 handle_window_change_signal (int sig)
5496 int width, height;
5497 struct tty_display_info *tty;
5499 /* The frame size change obviously applies to a single
5500 termcap-controlled terminal, but we can't decide which.
5501 Therefore, we resize the frames corresponding to each tty.
5503 for (tty = tty_list; tty; tty = tty->next) {
5505 if (! tty->term_initted)
5506 continue;
5508 /* Suspended tty frames have tty->input == NULL avoid trying to
5509 use it. */
5510 if (!tty->input)
5511 continue;
5513 get_tty_size (fileno (tty->input), &width, &height);
5515 if (width > 5 && height > 2) {
5516 Lisp_Object tail, frame;
5518 FOR_EACH_FRAME (tail, frame)
5519 if (FRAME_TERMCAP_P (XFRAME (frame)) && FRAME_TTY (XFRAME (frame)) == tty)
5520 /* Record the new sizes, but don't reallocate the data
5521 structures now. Let that be done later outside of the
5522 signal handler. */
5523 change_frame_size (XFRAME (frame), height, width, 0, 1, 0);
5528 static void
5529 deliver_window_change_signal (int sig)
5531 deliver_process_signal (sig, handle_window_change_signal);
5533 #endif /* SIGWINCH */
5536 /* Do any change in frame size that was requested by a signal.
5537 SAFE means this function is called from a place where it is
5538 safe to change frame sizes while a redisplay is in progress. */
5540 void
5541 do_pending_window_change (bool safe)
5543 /* If window change signal handler should have run before, run it now. */
5544 if (redisplaying_p && !safe)
5545 return;
5547 while (delayed_size_change)
5549 Lisp_Object tail, frame;
5551 delayed_size_change = 0;
5553 FOR_EACH_FRAME (tail, frame)
5555 struct frame *f = XFRAME (frame);
5557 if (f->new_text_lines != 0 || f->new_text_cols != 0)
5558 change_frame_size (f, f->new_text_lines, f->new_text_cols,
5559 0, 0, safe);
5565 /* Change the frame height and/or width. Values may be given as zero to
5566 indicate no change is to take place.
5568 If DELAY, assume we're being called from a signal handler, and
5569 queue the change for later - perhaps the next redisplay.
5570 Since this tries to resize windows, we can't call it
5571 from a signal handler.
5573 SAFE means this function is called from a place where it's
5574 safe to change frame sizes while a redisplay is in progress. */
5576 void
5577 change_frame_size (struct frame *f, int newheight, int newwidth,
5578 bool pretend, bool delay, bool safe)
5580 Lisp_Object tail, frame;
5582 if (FRAME_MSDOS_P (f))
5584 /* On MS-DOS, all frames use the same screen, so a change in
5585 size affects all frames. Termcap now supports multiple
5586 ttys. */
5587 FOR_EACH_FRAME (tail, frame)
5588 if (! FRAME_WINDOW_P (XFRAME (frame)))
5589 change_frame_size_1 (XFRAME (frame), newheight, newwidth,
5590 pretend, delay, safe);
5592 else
5593 change_frame_size_1 (f, newheight, newwidth, pretend, delay, safe);
5596 static void
5597 change_frame_size_1 (struct frame *f, int newheight, int newwidth,
5598 bool pretend, bool delay, bool safe)
5600 int new_frame_total_cols;
5601 ptrdiff_t count = SPECPDL_INDEX ();
5603 /* If we can't deal with the change now, queue it for later. */
5604 if (delay || (redisplaying_p && !safe))
5606 f->new_text_lines = newheight;
5607 f->new_text_cols = newwidth;
5608 delayed_size_change = 1;
5609 return;
5612 /* This size-change overrides any pending one for this frame. */
5613 f->new_text_lines = 0;
5614 f->new_text_cols = 0;
5616 /* If an argument is zero, set it to the current value. */
5617 if (newheight == 0)
5618 newheight = FRAME_LINES (f);
5619 if (newwidth == 0)
5620 newwidth = FRAME_COLS (f);
5622 /* Compute width of windows in F. */
5623 /* Round up to the smallest acceptable size. */
5624 check_frame_size (f, &newheight, &newwidth);
5626 /* This is the width of the frame with vertical scroll bars and fringe
5627 columns. Do this after rounding - see discussion of bug#9723. */
5628 new_frame_total_cols = FRAME_TOTAL_COLS_ARG (f, newwidth);
5630 /* If we're not changing the frame size, quit now. */
5631 /* Frame width may be unchanged but the text portion may change, for
5632 example, fullscreen and remove/add scroll bar. */
5633 if (newheight == FRAME_LINES (f)
5634 /* Text portion unchanged? */
5635 && newwidth == FRAME_COLS (f)
5636 /* Frame width unchanged? */
5637 && new_frame_total_cols == FRAME_TOTAL_COLS (f))
5638 return;
5640 block_input ();
5642 #ifdef MSDOS
5643 /* We only can set screen dimensions to certain values supported
5644 by our video hardware. Try to find the smallest size greater
5645 or equal to the requested dimensions. */
5646 dos_set_window_size (&newheight, &newwidth);
5647 #endif
5649 if (newheight != FRAME_LINES (f))
5651 resize_frame_windows (f, newheight, 0);
5653 /* MSDOS frames cannot PRETEND, as they change frame size by
5654 manipulating video hardware. */
5655 if ((FRAME_TERMCAP_P (f) && !pretend) || FRAME_MSDOS_P (f))
5656 FrameRows (FRAME_TTY (f)) = newheight;
5659 if (new_frame_total_cols != FRAME_TOTAL_COLS (f))
5661 resize_frame_windows (f, new_frame_total_cols, 1);
5663 /* MSDOS frames cannot PRETEND, as they change frame size by
5664 manipulating video hardware. */
5665 if ((FRAME_TERMCAP_P (f) && !pretend) || FRAME_MSDOS_P (f))
5666 FrameCols (FRAME_TTY (f)) = newwidth;
5668 if (WINDOWP (f->tool_bar_window))
5669 wset_total_cols (XWINDOW (f->tool_bar_window), make_number (newwidth));
5672 FRAME_LINES (f) = newheight;
5673 SET_FRAME_COLS (f, newwidth);
5676 struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
5677 int text_area_x, text_area_y, text_area_width, text_area_height;
5679 window_box (w, TEXT_AREA, &text_area_x, &text_area_y, &text_area_width,
5680 &text_area_height);
5681 if (w->cursor.x >= text_area_x + text_area_width)
5682 w->cursor.hpos = w->cursor.x = 0;
5683 if (w->cursor.y >= text_area_y + text_area_height)
5684 w->cursor.vpos = w->cursor.y = 0;
5687 adjust_glyphs (f);
5688 calculate_costs (f);
5689 SET_FRAME_GARBAGED (f);
5690 f->resized_p = 1;
5692 unblock_input ();
5694 record_unwind_current_buffer ();
5696 run_window_configuration_change_hook (f);
5698 unbind_to (count, Qnil);
5703 /***********************************************************************
5704 Terminal Related Lisp Functions
5705 ***********************************************************************/
5707 DEFUN ("open-termscript", Fopen_termscript, Sopen_termscript,
5708 1, 1, "FOpen termscript file: ",
5709 doc: /* Start writing all terminal output to FILE as well as the terminal.
5710 FILE = nil means just close any termscript file currently open. */)
5711 (Lisp_Object file)
5713 struct tty_display_info *tty;
5715 if (! FRAME_TERMCAP_P (SELECTED_FRAME ())
5716 && ! FRAME_MSDOS_P (SELECTED_FRAME ()))
5717 error ("Current frame is not on a tty device");
5719 tty = CURTTY ();
5721 if (tty->termscript != 0)
5723 block_input ();
5724 fclose (tty->termscript);
5725 unblock_input ();
5727 tty->termscript = 0;
5729 if (! NILP (file))
5731 file = Fexpand_file_name (file, Qnil);
5732 tty->termscript = fopen (SSDATA (file), "w");
5733 if (tty->termscript == 0)
5734 report_file_error ("Opening termscript", Fcons (file, Qnil));
5736 return Qnil;
5740 DEFUN ("send-string-to-terminal", Fsend_string_to_terminal,
5741 Ssend_string_to_terminal, 1, 2, 0,
5742 doc: /* Send STRING to the terminal without alteration.
5743 Control characters in STRING will have terminal-dependent effects.
5745 Optional parameter TERMINAL specifies the tty terminal device to use.
5746 It may be a terminal object, a frame, or nil for the terminal used by
5747 the currently selected frame. In batch mode, STRING is sent to stdout
5748 when TERMINAL is nil. */)
5749 (Lisp_Object string, Lisp_Object terminal)
5751 struct terminal *t = get_terminal (terminal, 1);
5752 FILE *out;
5754 /* ??? Perhaps we should do something special for multibyte strings here. */
5755 CHECK_STRING (string);
5756 block_input ();
5758 if (!t)
5759 error ("Unknown terminal device");
5761 if (t->type == output_initial)
5762 out = stdout;
5763 else if (t->type != output_termcap && t->type != output_msdos_raw)
5764 error ("Device %d is not a termcap terminal device", t->id);
5765 else
5767 struct tty_display_info *tty = t->display_info.tty;
5769 if (! tty->output)
5770 error ("Terminal is currently suspended");
5772 if (tty->termscript)
5774 fwrite (SDATA (string), 1, SBYTES (string), tty->termscript);
5775 fflush (tty->termscript);
5777 out = tty->output;
5779 fwrite (SDATA (string), 1, SBYTES (string), out);
5780 fflush (out);
5781 unblock_input ();
5782 return Qnil;
5786 DEFUN ("ding", Fding, Sding, 0, 1, 0,
5787 doc: /* Beep, or flash the screen.
5788 Also, unless an argument is given,
5789 terminate any keyboard macro currently executing. */)
5790 (Lisp_Object arg)
5792 if (!NILP (arg))
5794 if (noninteractive)
5795 putchar (07);
5796 else
5797 ring_bell (XFRAME (selected_frame));
5799 else
5800 bitch_at_user ();
5802 return Qnil;
5805 void
5806 bitch_at_user (void)
5808 if (noninteractive)
5809 putchar (07);
5810 else if (!INTERACTIVE) /* Stop executing a keyboard macro. */
5811 error ("Keyboard macro terminated by a command ringing the bell");
5812 else
5813 ring_bell (XFRAME (selected_frame));
5818 /***********************************************************************
5819 Sleeping, Waiting
5820 ***********************************************************************/
5822 DEFUN ("sleep-for", Fsleep_for, Ssleep_for, 1, 2, 0,
5823 doc: /* Pause, without updating display, for SECONDS seconds.
5824 SECONDS may be a floating-point value, meaning that you can wait for a
5825 fraction of a second. Optional second arg MILLISECONDS specifies an
5826 additional wait period, in milliseconds; this is for backwards compatibility.
5827 \(Not all operating systems support waiting for a fraction of a second.) */)
5828 (Lisp_Object seconds, Lisp_Object milliseconds)
5830 double duration = extract_float (seconds);
5832 if (!NILP (milliseconds))
5834 CHECK_NUMBER (milliseconds);
5835 duration += XINT (milliseconds) / 1000.0;
5838 if (0 < duration)
5840 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (duration);
5841 wait_reading_process_output (min (EMACS_SECS (t), WAIT_READING_MAX),
5842 EMACS_NSECS (t), 0, 0, Qnil, NULL, 0);
5845 return Qnil;
5849 /* This is just like wait_reading_process_output, except that
5850 it does redisplay.
5852 TIMEOUT is number of seconds to wait (float or integer),
5853 or t to wait forever.
5854 READING is true if reading input.
5855 If DISPLAY_OPTION is >0 display process output while waiting.
5856 If DISPLAY_OPTION is >1 perform an initial redisplay before waiting.
5859 Lisp_Object
5860 sit_for (Lisp_Object timeout, bool reading, int display_option)
5862 intmax_t sec;
5863 int nsec;
5864 bool do_display = display_option > 0;
5866 swallow_events (do_display);
5868 if ((detect_input_pending_run_timers (do_display))
5869 || !NILP (Vexecuting_kbd_macro))
5870 return Qnil;
5872 if (display_option > 1)
5873 redisplay_preserve_echo_area (2);
5875 if (INTEGERP (timeout))
5877 sec = XINT (timeout);
5878 if (! (0 < sec))
5879 return Qt;
5880 nsec = 0;
5882 else if (FLOATP (timeout))
5884 double seconds = XFLOAT_DATA (timeout);
5885 if (! (0 < seconds))
5886 return Qt;
5887 else
5889 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (seconds);
5890 sec = min (EMACS_SECS (t), WAIT_READING_MAX);
5891 nsec = EMACS_NSECS (t);
5894 else if (EQ (timeout, Qt))
5896 sec = 0;
5897 nsec = 0;
5899 else
5900 wrong_type_argument (Qnumberp, timeout);
5903 #ifdef USABLE_SIGIO
5904 gobble_input ();
5905 #endif
5907 wait_reading_process_output (sec, nsec, reading ? -1 : 1, do_display,
5908 Qnil, NULL, 0);
5910 return detect_input_pending () ? Qnil : Qt;
5914 DEFUN ("redisplay", Fredisplay, Sredisplay, 0, 1, 0,
5915 doc: /* Perform redisplay.
5916 Optional arg FORCE, if non-nil, prevents redisplay from being
5917 preempted by arriving input, even if `redisplay-dont-pause' is nil.
5918 If `redisplay-dont-pause' is non-nil (the default), redisplay is never
5919 preempted by arriving input, so FORCE does nothing.
5921 Return t if redisplay was performed, nil if redisplay was preempted
5922 immediately by pending input. */)
5923 (Lisp_Object force)
5925 ptrdiff_t count;
5927 swallow_events (1);
5928 if ((detect_input_pending_run_timers (1)
5929 && NILP (force) && !redisplay_dont_pause)
5930 || !NILP (Vexecuting_kbd_macro))
5931 return Qnil;
5933 count = SPECPDL_INDEX ();
5934 if (!NILP (force) && !redisplay_dont_pause)
5935 specbind (Qredisplay_dont_pause, Qt);
5936 redisplay_preserve_echo_area (2);
5937 unbind_to (count, Qnil);
5938 return Qt;
5943 /***********************************************************************
5944 Other Lisp Functions
5945 ***********************************************************************/
5947 /* A vector of size >= 2 * NFRAMES + 3 * NBUFFERS + 1, containing the
5948 session's frames, frame names, buffers, buffer-read-only flags, and
5949 buffer-modified-flags. */
5951 static Lisp_Object frame_and_buffer_state;
5954 DEFUN ("frame-or-buffer-changed-p", Fframe_or_buffer_changed_p,
5955 Sframe_or_buffer_changed_p, 0, 1, 0,
5956 doc: /* Return non-nil if the frame and buffer state appears to have changed.
5957 VARIABLE is a variable name whose value is either nil or a state vector
5958 that will be updated to contain all frames and buffers,
5959 aside from buffers whose names start with space,
5960 along with the buffers' read-only and modified flags. This allows a fast
5961 check to see whether buffer menus might need to be recomputed.
5962 If this function returns non-nil, it updates the internal vector to reflect
5963 the current state.
5965 If VARIABLE is nil, an internal variable is used. Users should not
5966 pass nil for VARIABLE. */)
5967 (Lisp_Object variable)
5969 Lisp_Object state, tail, frame, buf;
5970 ptrdiff_t n, idx;
5972 if (! NILP (variable))
5974 CHECK_SYMBOL (variable);
5975 state = Fsymbol_value (variable);
5976 if (! VECTORP (state))
5977 goto changed;
5979 else
5980 state = frame_and_buffer_state;
5982 idx = 0;
5983 FOR_EACH_FRAME (tail, frame)
5985 if (idx == ASIZE (state))
5986 goto changed;
5987 if (!EQ (AREF (state, idx++), frame))
5988 goto changed;
5989 if (idx == ASIZE (state))
5990 goto changed;
5991 if (!EQ (AREF (state, idx++), XFRAME (frame)->name))
5992 goto changed;
5994 /* Check that the buffer info matches. */
5995 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
5997 buf = XCDR (XCAR (tail));
5998 /* Ignore buffers that aren't included in buffer lists. */
5999 if (SREF (BVAR (XBUFFER (buf), name), 0) == ' ')
6000 continue;
6001 if (idx == ASIZE (state))
6002 goto changed;
6003 if (!EQ (AREF (state, idx++), buf))
6004 goto changed;
6005 if (idx == ASIZE (state))
6006 goto changed;
6007 if (!EQ (AREF (state, idx++), BVAR (XBUFFER (buf), read_only)))
6008 goto changed;
6009 if (idx == ASIZE (state))
6010 goto changed;
6011 if (!EQ (AREF (state, idx++), Fbuffer_modified_p (buf)))
6012 goto changed;
6014 if (idx == ASIZE (state))
6015 goto changed;
6016 /* Detect deletion of a buffer at the end of the list. */
6017 if (EQ (AREF (state, idx), Qlambda))
6018 return Qnil;
6020 /* Come here if we decide the data has changed. */
6021 changed:
6022 /* Count the size we will need.
6023 Start with 1 so there is room for at least one lambda at the end. */
6024 n = 1;
6025 FOR_EACH_FRAME (tail, frame)
6026 n += 2;
6027 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
6028 n += 3;
6029 /* Reallocate the vector if data has grown to need it,
6030 or if it has shrunk a lot. */
6031 if (! VECTORP (state)
6032 || n > ASIZE (state)
6033 || n + 20 < ASIZE (state) / 2)
6034 /* Add 20 extra so we grow it less often. */
6036 state = Fmake_vector (make_number (n + 20), Qlambda);
6037 if (! NILP (variable))
6038 Fset (variable, state);
6039 else
6040 frame_and_buffer_state = state;
6043 /* Record the new data in the (possibly reallocated) vector. */
6044 idx = 0;
6045 FOR_EACH_FRAME (tail, frame)
6047 ASET (state, idx, frame);
6048 idx++;
6049 ASET (state, idx, XFRAME (frame)->name);
6050 idx++;
6052 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
6054 buf = XCDR (XCAR (tail));
6055 /* Ignore buffers that aren't included in buffer lists. */
6056 if (SREF (BVAR (XBUFFER (buf), name), 0) == ' ')
6057 continue;
6058 ASET (state, idx, buf);
6059 idx++;
6060 ASET (state, idx, BVAR (XBUFFER (buf), read_only));
6061 idx++;
6062 ASET (state, idx, Fbuffer_modified_p (buf));
6063 idx++;
6065 /* Fill up the vector with lambdas (always at least one). */
6066 ASET (state, idx, Qlambda);
6067 idx++;
6068 while (idx < ASIZE (state))
6070 ASET (state, idx, Qlambda);
6071 idx++;
6073 /* Make sure we didn't overflow the vector. */
6074 eassert (idx <= ASIZE (state));
6075 return Qt;
6080 /***********************************************************************
6081 Initialization
6082 ***********************************************************************/
6084 /* Initialization done when Emacs fork is started, before doing stty.
6085 Determine terminal type and set terminal_driver. Then invoke its
6086 decoding routine to set up variables in the terminal package. */
6088 void
6089 init_display (void)
6091 char *terminal_type;
6093 /* Construct the space glyph. */
6094 space_glyph.type = CHAR_GLYPH;
6095 SET_CHAR_GLYPH (space_glyph, ' ', DEFAULT_FACE_ID, 0);
6096 space_glyph.charpos = -1;
6098 inverse_video = 0;
6099 cursor_in_echo_area = 0;
6100 terminal_type = (char *) 0;
6102 /* Now is the time to initialize this; it's used by init_sys_modes
6103 during startup. */
6104 Vinitial_window_system = Qnil;
6106 /* SIGWINCH needs to be handled no matter what display we start
6107 with. Otherwise newly opened tty frames will not resize
6108 automatically. */
6109 #ifdef SIGWINCH
6110 #ifndef CANNOT_DUMP
6111 if (initialized)
6112 #endif /* CANNOT_DUMP */
6114 struct sigaction action;
6115 emacs_sigaction_init (&action, deliver_window_change_signal);
6116 sigaction (SIGWINCH, &action, 0);
6118 #endif /* SIGWINCH */
6120 /* If running as a daemon, no need to initialize any frames/terminal. */
6121 if (IS_DAEMON)
6122 return;
6124 /* If the user wants to use a window system, we shouldn't bother
6125 initializing the terminal. This is especially important when the
6126 terminal is so dumb that emacs gives up before and doesn't bother
6127 using the window system.
6129 If the DISPLAY environment variable is set and nonempty,
6130 try to use X, and die with an error message if that doesn't work. */
6132 #ifdef HAVE_X_WINDOWS
6133 if (! inhibit_window_system && ! display_arg)
6135 char *display;
6136 display = getenv ("DISPLAY");
6137 display_arg = (display != 0 && *display != 0);
6139 if (display_arg && !x_display_ok (display))
6141 fprintf (stderr, "Display %s unavailable, simulating -nw\n",
6142 display);
6143 inhibit_window_system = 1;
6147 if (!inhibit_window_system && display_arg)
6149 Vinitial_window_system = Qx;
6150 #ifdef HAVE_X11
6151 Vwindow_system_version = make_number (11);
6152 #endif
6153 #ifdef GNU_LINUX
6154 /* In some versions of ncurses,
6155 tputs crashes if we have not called tgetent.
6156 So call tgetent. */
6157 { char b[2044]; tgetent (b, "xterm");}
6158 #endif
6159 return;
6161 #endif /* HAVE_X_WINDOWS */
6163 #ifdef HAVE_NTGUI
6164 if (!inhibit_window_system)
6166 Vinitial_window_system = Qw32;
6167 Vwindow_system_version = make_number (1);
6168 return;
6170 #endif /* HAVE_NTGUI */
6172 #ifdef HAVE_NS
6173 if (!inhibit_window_system
6174 #ifndef CANNOT_DUMP
6175 && initialized
6176 #endif
6179 Vinitial_window_system = Qns;
6180 Vwindow_system_version = make_number (10);
6181 return;
6183 #endif
6185 /* If no window system has been specified, try to use the terminal. */
6186 if (! isatty (0))
6188 fatal ("standard input is not a tty");
6189 exit (1);
6192 #ifdef WINDOWSNT
6193 terminal_type = "w32console";
6194 #else
6195 /* Look at the TERM variable. */
6196 terminal_type = (char *) getenv ("TERM");
6197 #endif
6198 if (!terminal_type)
6200 #ifdef HAVE_WINDOW_SYSTEM
6201 if (! inhibit_window_system)
6202 fprintf (stderr, "Please set the environment variable DISPLAY or TERM (see `tset').\n");
6203 else
6204 #endif /* HAVE_WINDOW_SYSTEM */
6205 fprintf (stderr, "Please set the environment variable TERM; see `tset'.\n");
6206 exit (1);
6210 struct terminal *t;
6211 struct frame *f = XFRAME (selected_frame);
6213 init_foreground_group ();
6215 /* Open a display on the controlling tty. */
6216 t = init_tty (0, terminal_type, 1); /* Errors are fatal. */
6218 /* Convert the initial frame to use the new display. */
6219 if (f->output_method != output_initial)
6220 emacs_abort ();
6221 f->output_method = t->type;
6222 f->terminal = t;
6224 t->reference_count++;
6225 #ifdef MSDOS
6226 f->output_data.tty->display_info = &the_only_display_info;
6227 #else
6228 if (f->output_method == output_termcap)
6229 create_tty_output (f);
6230 #endif
6231 t->display_info.tty->top_frame = selected_frame;
6232 change_frame_size (XFRAME (selected_frame),
6233 FrameRows (t->display_info.tty),
6234 FrameCols (t->display_info.tty), 0, 0, 1);
6236 /* Delete the initial terminal. */
6237 if (--initial_terminal->reference_count == 0
6238 && initial_terminal->delete_terminal_hook)
6239 (*initial_terminal->delete_terminal_hook) (initial_terminal);
6241 /* Update frame parameters to reflect the new type. */
6242 Fmodify_frame_parameters
6243 (selected_frame, Fcons (Fcons (Qtty_type,
6244 Ftty_type (selected_frame)), Qnil));
6245 if (t->display_info.tty->name)
6246 Fmodify_frame_parameters (selected_frame,
6247 Fcons (Fcons (Qtty, build_string (t->display_info.tty->name)),
6248 Qnil));
6249 else
6250 Fmodify_frame_parameters (selected_frame, Fcons (Fcons (Qtty, Qnil),
6251 Qnil));
6255 struct frame *sf = SELECTED_FRAME ();
6256 int width = FRAME_TOTAL_COLS (sf);
6257 int height = FRAME_LINES (sf);
6259 /* If these sizes are so big they cause overflow, just ignore the
6260 change. It's not clear what better we could do. The rest of
6261 the code assumes that (width + 2) * height * sizeof (struct glyph)
6262 does not overflow and does not exceed PTRDIFF_MAX or SIZE_MAX. */
6263 if (INT_ADD_RANGE_OVERFLOW (width, 2, INT_MIN, INT_MAX)
6264 || INT_MULTIPLY_RANGE_OVERFLOW (width + 2, height, INT_MIN, INT_MAX)
6265 || (min (PTRDIFF_MAX, SIZE_MAX) / sizeof (struct glyph)
6266 < (width + 2) * height))
6267 fatal ("screen size %dx%d too big", width, height);
6270 calculate_costs (XFRAME (selected_frame));
6272 /* Set up faces of the initial terminal frame of a dumped Emacs. */
6273 if (initialized
6274 && !noninteractive
6275 && NILP (Vinitial_window_system))
6277 /* For the initial frame, we don't have any way of knowing what
6278 are the foreground and background colors of the terminal. */
6279 struct frame *sf = SELECTED_FRAME ();
6281 FRAME_FOREGROUND_PIXEL (sf) = FACE_TTY_DEFAULT_FG_COLOR;
6282 FRAME_BACKGROUND_PIXEL (sf) = FACE_TTY_DEFAULT_BG_COLOR;
6283 call0 (intern ("tty-set-up-initial-frame-faces"));
6289 /***********************************************************************
6290 Blinking cursor
6291 ***********************************************************************/
6293 DEFUN ("internal-show-cursor", Finternal_show_cursor,
6294 Sinternal_show_cursor, 2, 2, 0,
6295 doc: /* Set the cursor-visibility flag of WINDOW to SHOW.
6296 WINDOW nil means use the selected window. SHOW non-nil means
6297 show a cursor in WINDOW in the next redisplay. SHOW nil means
6298 don't show a cursor. */)
6299 (Lisp_Object window, Lisp_Object show)
6301 /* Don't change cursor state while redisplaying. This could confuse
6302 output routines. */
6303 if (!redisplaying_p)
6304 decode_any_window (window)->cursor_off_p = NILP (show);
6305 return Qnil;
6309 DEFUN ("internal-show-cursor-p", Finternal_show_cursor_p,
6310 Sinternal_show_cursor_p, 0, 1, 0,
6311 doc: /* Value is non-nil if next redisplay will display a cursor in WINDOW.
6312 WINDOW nil or omitted means report on the selected window. */)
6313 (Lisp_Object window)
6315 return decode_any_window (window)->cursor_off_p ? Qnil : Qt;
6318 DEFUN ("last-nonminibuffer-frame", Flast_nonminibuf_frame,
6319 Slast_nonminibuf_frame, 0, 0, 0,
6320 doc: /* Value is last nonminibuffer frame. */)
6321 (void)
6323 Lisp_Object frame = Qnil;
6325 if (last_nonminibuf_frame)
6326 XSETFRAME (frame, last_nonminibuf_frame);
6328 return frame;
6331 /***********************************************************************
6332 Initialization
6333 ***********************************************************************/
6335 void
6336 syms_of_display (void)
6338 defsubr (&Sredraw_frame);
6339 defsubr (&Sredraw_display);
6340 defsubr (&Sframe_or_buffer_changed_p);
6341 defsubr (&Sopen_termscript);
6342 defsubr (&Sding);
6343 defsubr (&Sredisplay);
6344 defsubr (&Ssleep_for);
6345 defsubr (&Ssend_string_to_terminal);
6346 defsubr (&Sinternal_show_cursor);
6347 defsubr (&Sinternal_show_cursor_p);
6348 defsubr (&Slast_nonminibuf_frame);
6350 #ifdef GLYPH_DEBUG
6351 defsubr (&Sdump_redisplay_history);
6352 #endif
6354 frame_and_buffer_state = Fmake_vector (make_number (20), Qlambda);
6355 staticpro (&frame_and_buffer_state);
6357 DEFSYM (Qdisplay_table, "display-table");
6358 DEFSYM (Qredisplay_dont_pause, "redisplay-dont-pause");
6360 DEFVAR_INT ("baud-rate", baud_rate,
6361 doc: /* The output baud rate of the terminal.
6362 On most systems, changing this value will affect the amount of padding
6363 and the other strategic decisions made during redisplay. */);
6365 DEFVAR_BOOL ("inverse-video", inverse_video,
6366 doc: /* Non-nil means invert the entire frame display.
6367 This means everything is in inverse video which otherwise would not be. */);
6369 DEFVAR_BOOL ("visible-bell", visible_bell,
6370 doc: /* Non-nil means try to flash the frame to represent a bell.
6372 See also `ring-bell-function'. */);
6374 DEFVAR_BOOL ("no-redraw-on-reenter", no_redraw_on_reenter,
6375 doc: /* Non-nil means no need to redraw entire frame after suspending.
6376 A non-nil value is useful if the terminal can automatically preserve
6377 Emacs's frame display when you reenter Emacs.
6378 It is up to you to set this variable if your terminal can do that. */);
6380 DEFVAR_LISP ("initial-window-system", Vinitial_window_system,
6381 doc: /* Name of the window system that Emacs uses for the first frame.
6382 The value is a symbol:
6383 nil for a termcap frame (a character-only terminal),
6384 'x' for an Emacs frame that is really an X window,
6385 'w32' for an Emacs frame that is a window on MS-Windows display,
6386 'ns' for an Emacs frame on a GNUstep or Macintosh Cocoa display,
6387 'pc' for a direct-write MS-DOS frame.
6389 Use of this variable as a boolean is deprecated. Instead,
6390 use `display-graphic-p' or any of the other `display-*-p'
6391 predicates which report frame's specific UI-related capabilities. */);
6393 DEFVAR_KBOARD ("window-system", Vwindow_system,
6394 doc: /* Name of window system through which the selected frame is displayed.
6395 The value is a symbol:
6396 nil for a termcap frame (a character-only terminal),
6397 'x' for an Emacs frame that is really an X window,
6398 'w32' for an Emacs frame that is a window on MS-Windows display,
6399 'ns' for an Emacs frame on a GNUstep or Macintosh Cocoa display,
6400 'pc' for a direct-write MS-DOS frame.
6402 Use of this variable as a boolean is deprecated. Instead,
6403 use `display-graphic-p' or any of the other `display-*-p'
6404 predicates which report frame's specific UI-related capabilities. */);
6406 DEFVAR_LISP ("window-system-version", Vwindow_system_version,
6407 doc: /* The version number of the window system in use.
6408 For X windows, this is 11. */);
6410 DEFVAR_BOOL ("cursor-in-echo-area", cursor_in_echo_area,
6411 doc: /* Non-nil means put cursor in minibuffer, at end of any message there. */);
6413 DEFVAR_LISP ("glyph-table", Vglyph_table,
6414 doc: /* Table defining how to output a glyph code to the frame.
6415 If not nil, this is a vector indexed by glyph code to define the glyph.
6416 Each element can be:
6417 integer: a glyph code which this glyph is an alias for.
6418 string: output this glyph using that string (not impl. in X windows).
6419 nil: this glyph mod 524288 is the code of a character to output,
6420 and this glyph / 524288 is the face number (see `face-id') to use
6421 while outputting it. */);
6422 Vglyph_table = Qnil;
6424 DEFVAR_LISP ("standard-display-table", Vstandard_display_table,
6425 doc: /* Display table to use for buffers that specify none.
6426 See `buffer-display-table' for more information. */);
6427 Vstandard_display_table = Qnil;
6429 DEFVAR_BOOL ("redisplay-dont-pause", redisplay_dont_pause,
6430 doc: /* Non-nil means display update isn't paused when input is detected. */);
6431 redisplay_dont_pause = 1;
6433 #if PERIODIC_PREEMPTION_CHECKING
6434 DEFVAR_LISP ("redisplay-preemption-period", Vredisplay_preemption_period,
6435 doc: /* Period in seconds between checking for input during redisplay.
6436 This has an effect only if `redisplay-dont-pause' is nil; in that
6437 case, arriving input preempts redisplay until the input is processed.
6438 If the value is nil, redisplay is never preempted. */);
6439 Vredisplay_preemption_period = make_float (0.10);
6440 #endif
6442 #ifdef CANNOT_DUMP
6443 if (noninteractive)
6444 #endif
6446 Vinitial_window_system = Qnil;
6447 Vwindow_system_version = Qnil;