* doc/misc/calc.texi (ISO-8601): New section.
[emacs.git] / src / dispnew.c
blob02b2f9c84e4aa0b46de38809b14515d4208c7e56
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 Horizontal position is -1 when cursor is on the left fringe. */
4021 hpos = clip_to_bounds (-1, hpos, w->current_matrix->matrix_w - 1);
4022 vpos = clip_to_bounds (0, vpos, w->current_matrix->nrows - 1);
4023 rif->cursor_to (vpos, hpos, cy, cx);
4027 /* Set WINDOW->must_be_updated_p to ON_P for all windows in the window
4028 tree rooted at W. */
4030 void
4031 set_window_update_flags (struct window *w, bool on_p)
4033 while (w)
4035 if (!NILP (w->hchild))
4036 set_window_update_flags (XWINDOW (w->hchild), on_p);
4037 else if (!NILP (w->vchild))
4038 set_window_update_flags (XWINDOW (w->vchild), on_p);
4039 else
4040 w->must_be_updated_p = on_p;
4042 w = NILP (w->next) ? 0 : XWINDOW (w->next);
4048 /***********************************************************************
4049 Window-Based Scrolling
4050 ***********************************************************************/
4052 /* Structure describing rows in scrolling_window. */
4054 struct row_entry
4056 /* Number of occurrences of this row in desired and current matrix. */
4057 int old_uses, new_uses;
4059 /* Vpos of row in new matrix. */
4060 int new_line_number;
4062 /* Bucket index of this row_entry in the hash table row_table. */
4063 ptrdiff_t bucket;
4065 /* The row described by this entry. */
4066 struct glyph_row *row;
4068 /* Hash collision chain. */
4069 struct row_entry *next;
4072 /* A pool to allocate row_entry structures from, and the size of the
4073 pool. The pool is reallocated in scrolling_window when we find
4074 that we need a larger one. */
4076 static struct row_entry *row_entry_pool;
4077 static ptrdiff_t row_entry_pool_size;
4079 /* Index of next free entry in row_entry_pool. */
4081 static ptrdiff_t row_entry_idx;
4083 /* The hash table used during scrolling, and the table's size. This
4084 table is used to quickly identify equal rows in the desired and
4085 current matrix. */
4087 static struct row_entry **row_table;
4088 static ptrdiff_t row_table_size;
4090 /* Vectors of pointers to row_entry structures belonging to the
4091 current and desired matrix, and the size of the vectors. */
4093 static struct row_entry **old_lines, **new_lines;
4094 static ptrdiff_t old_lines_size, new_lines_size;
4096 /* A pool to allocate run structures from, and its size. */
4098 static struct run *run_pool;
4099 static ptrdiff_t runs_size;
4101 /* A vector of runs of lines found during scrolling. */
4103 static struct run **runs;
4105 /* Add glyph row ROW to the scrolling hash table. */
4107 static struct row_entry *
4108 add_row_entry (struct glyph_row *row)
4110 struct row_entry *entry;
4111 ptrdiff_t i = row->hash % row_table_size;
4113 entry = row_table[i];
4114 eassert (entry || verify_row_hash (row));
4115 while (entry && !row_equal_p (entry->row, row, 1))
4116 entry = entry->next;
4118 if (entry == NULL)
4120 entry = row_entry_pool + row_entry_idx++;
4121 entry->row = row;
4122 entry->old_uses = entry->new_uses = 0;
4123 entry->new_line_number = 0;
4124 entry->bucket = i;
4125 entry->next = row_table[i];
4126 row_table[i] = entry;
4129 return entry;
4133 /* Try to reuse part of the current display of W by scrolling lines.
4134 HEADER_LINE_P means W has a header line.
4136 The algorithm is taken from Communications of the ACM, Apr78 "A
4137 Technique for Isolating Differences Between Files." It should take
4138 O(N) time.
4140 A short outline of the steps of the algorithm
4142 1. Skip lines equal at the start and end of both matrices.
4144 2. Enter rows in the current and desired matrix into a symbol
4145 table, counting how often they appear in both matrices.
4147 3. Rows that appear exactly once in both matrices serve as anchors,
4148 i.e. we assume that such lines are likely to have been moved.
4150 4. Starting from anchor lines, extend regions to be scrolled both
4151 forward and backward.
4153 Value is
4155 -1 if all rows were found to be equal.
4156 0 to indicate that we did not scroll the display, or
4157 1 if we did scroll. */
4159 static int
4160 scrolling_window (struct window *w, bool header_line_p)
4162 struct glyph_matrix *desired_matrix = w->desired_matrix;
4163 struct glyph_matrix *current_matrix = w->current_matrix;
4164 int yb = window_text_bottom_y (w);
4165 ptrdiff_t i;
4166 int j, first_old, first_new, last_old, last_new;
4167 int nruns, run_idx;
4168 ptrdiff_t n;
4169 struct row_entry *entry;
4170 struct redisplay_interface *rif = FRAME_RIF (XFRAME (WINDOW_FRAME (w)));
4172 /* Skip over rows equal at the start. */
4173 for (i = header_line_p; i < current_matrix->nrows - 1; ++i)
4175 struct glyph_row *d = MATRIX_ROW (desired_matrix, i);
4176 struct glyph_row *c = MATRIX_ROW (current_matrix, i);
4178 if (c->enabled_p
4179 && d->enabled_p
4180 && !d->redraw_fringe_bitmaps_p
4181 && c->y == d->y
4182 && MATRIX_ROW_BOTTOM_Y (c) <= yb
4183 && MATRIX_ROW_BOTTOM_Y (d) <= yb
4184 && row_equal_p (c, d, 1))
4186 assign_row (c, d);
4187 d->enabled_p = 0;
4189 else
4190 break;
4193 /* Give up if some rows in the desired matrix are not enabled. */
4194 if (!MATRIX_ROW (desired_matrix, i)->enabled_p)
4195 return -1;
4197 first_old = first_new = i;
4199 /* Set last_new to the index + 1 of the row that reaches the
4200 bottom boundary in the desired matrix. Give up if we find a
4201 disabled row before we reach the bottom boundary. */
4202 i = first_new + 1;
4203 while (i < desired_matrix->nrows - 1)
4205 int bottom;
4207 if (!MATRIX_ROW (desired_matrix, i)->enabled_p)
4208 return 0;
4209 bottom = MATRIX_ROW_BOTTOM_Y (MATRIX_ROW (desired_matrix, i));
4210 if (bottom <= yb)
4211 ++i;
4212 if (bottom >= yb)
4213 break;
4216 last_new = i;
4218 /* Set last_old to the index + 1 of the row that reaches the bottom
4219 boundary in the current matrix. We don't look at the enabled
4220 flag here because we plan to reuse part of the display even if
4221 other parts are disabled. */
4222 i = first_old + 1;
4223 while (i < current_matrix->nrows - 1)
4225 int bottom = MATRIX_ROW_BOTTOM_Y (MATRIX_ROW (current_matrix, i));
4226 if (bottom <= yb)
4227 ++i;
4228 if (bottom >= yb)
4229 break;
4232 last_old = i;
4234 /* Skip over rows equal at the bottom. */
4235 i = last_new;
4236 j = last_old;
4237 while (i - 1 > first_new
4238 && j - 1 > first_old
4239 && MATRIX_ROW (current_matrix, j - 1)->enabled_p
4240 && (MATRIX_ROW (current_matrix, j - 1)->y
4241 == MATRIX_ROW (desired_matrix, i - 1)->y)
4242 && !MATRIX_ROW (desired_matrix, i - 1)->redraw_fringe_bitmaps_p
4243 && row_equal_p (MATRIX_ROW (desired_matrix, i - 1),
4244 MATRIX_ROW (current_matrix, j - 1), 1))
4245 --i, --j;
4246 last_new = i;
4247 last_old = j;
4249 /* Nothing to do if all rows are equal. */
4250 if (last_new == first_new)
4251 return 0;
4253 /* Check for integer overflow in size calculation.
4255 If next_almost_prime checks (N) for divisibility by 2..10, then
4256 it can return at most N + 10, e.g., next_almost_prime (1) == 11.
4257 So, set next_almost_prime_increment_max to 10.
4259 It's just a coincidence that next_almost_prime_increment_max ==
4260 NEXT_ALMOST_PRIME_LIMIT - 1. If NEXT_ALMOST_PRIME_LIMIT were
4261 13, then next_almost_prime_increment_max would be 14, e.g.,
4262 because next_almost_prime (113) would be 127. */
4264 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
4265 enum { next_almost_prime_increment_max = 10 };
4266 ptrdiff_t row_table_max =
4267 (min (PTRDIFF_MAX, SIZE_MAX) / (3 * sizeof *row_table)
4268 - next_almost_prime_increment_max);
4269 ptrdiff_t current_nrows_max = row_table_max - desired_matrix->nrows;
4270 if (current_nrows_max < current_matrix->nrows)
4271 memory_full (SIZE_MAX);
4274 /* Reallocate vectors, tables etc. if necessary. */
4276 if (current_matrix->nrows > old_lines_size)
4277 old_lines = xpalloc (old_lines, &old_lines_size,
4278 current_matrix->nrows - old_lines_size,
4279 INT_MAX, sizeof *old_lines);
4281 if (desired_matrix->nrows > new_lines_size)
4282 new_lines = xpalloc (new_lines, &new_lines_size,
4283 desired_matrix->nrows - new_lines_size,
4284 INT_MAX, sizeof *new_lines);
4286 n = desired_matrix->nrows;
4287 n += current_matrix->nrows;
4288 if (row_table_size < 3 * n)
4290 ptrdiff_t size = next_almost_prime (3 * n);
4291 row_table = xnrealloc (row_table, size, sizeof *row_table);
4292 row_table_size = size;
4293 memset (row_table, 0, size * sizeof *row_table);
4296 if (n > row_entry_pool_size)
4297 row_entry_pool = xpalloc (row_entry_pool, &row_entry_pool_size,
4298 n - row_entry_pool_size,
4299 -1, sizeof *row_entry_pool);
4301 if (desired_matrix->nrows > runs_size)
4303 runs = xnrealloc (runs, desired_matrix->nrows, sizeof *runs);
4304 run_pool = xnrealloc (run_pool, desired_matrix->nrows, sizeof *run_pool);
4305 runs_size = desired_matrix->nrows;
4308 nruns = run_idx = 0;
4309 row_entry_idx = 0;
4311 /* Add rows from the current and desired matrix to the hash table
4312 row_hash_table to be able to find equal ones quickly. */
4314 for (i = first_old; i < last_old; ++i)
4316 if (MATRIX_ROW (current_matrix, i)->enabled_p)
4318 entry = add_row_entry (MATRIX_ROW (current_matrix, i));
4319 old_lines[i] = entry;
4320 ++entry->old_uses;
4322 else
4323 old_lines[i] = NULL;
4326 for (i = first_new; i < last_new; ++i)
4328 eassert (MATRIX_ROW_ENABLED_P (desired_matrix, i));
4329 entry = add_row_entry (MATRIX_ROW (desired_matrix, i));
4330 ++entry->new_uses;
4331 entry->new_line_number = i;
4332 new_lines[i] = entry;
4335 /* Identify moves based on lines that are unique and equal
4336 in both matrices. */
4337 for (i = first_old; i < last_old;)
4338 if (old_lines[i]
4339 && old_lines[i]->old_uses == 1
4340 && old_lines[i]->new_uses == 1)
4342 int p, q;
4343 int new_line = old_lines[i]->new_line_number;
4344 struct run *run = run_pool + run_idx++;
4346 /* Record move. */
4347 run->current_vpos = i;
4348 run->current_y = MATRIX_ROW (current_matrix, i)->y;
4349 run->desired_vpos = new_line;
4350 run->desired_y = MATRIX_ROW (desired_matrix, new_line)->y;
4351 run->nrows = 1;
4352 run->height = MATRIX_ROW (current_matrix, i)->height;
4354 /* Extend backward. */
4355 p = i - 1;
4356 q = new_line - 1;
4357 while (p > first_old
4358 && q > first_new
4359 && old_lines[p] == new_lines[q])
4361 int h = MATRIX_ROW (current_matrix, p)->height;
4362 --run->current_vpos;
4363 --run->desired_vpos;
4364 ++run->nrows;
4365 run->height += h;
4366 run->desired_y -= h;
4367 run->current_y -= h;
4368 --p, --q;
4371 /* Extend forward. */
4372 p = i + 1;
4373 q = new_line + 1;
4374 while (p < last_old
4375 && q < last_new
4376 && old_lines[p] == new_lines[q])
4378 int h = MATRIX_ROW (current_matrix, p)->height;
4379 ++run->nrows;
4380 run->height += h;
4381 ++p, ++q;
4384 /* Insert run into list of all runs. Order runs by copied
4385 pixel lines. Note that we record runs that don't have to
4386 be copied because they are already in place. This is done
4387 because we can avoid calling update_window_line in this
4388 case. */
4389 for (p = 0; p < nruns && runs[p]->height > run->height; ++p)
4391 for (q = nruns; q > p; --q)
4392 runs[q] = runs[q - 1];
4393 runs[p] = run;
4394 ++nruns;
4396 i += run->nrows;
4398 else
4399 ++i;
4401 /* Do the moves. Do it in a way that we don't overwrite something
4402 we want to copy later on. This is not solvable in general
4403 because there is only one display and we don't have a way to
4404 exchange areas on this display. Example:
4406 +-----------+ +-----------+
4407 | A | | B |
4408 +-----------+ --> +-----------+
4409 | B | | A |
4410 +-----------+ +-----------+
4412 Instead, prefer bigger moves, and invalidate moves that would
4413 copy from where we copied to. */
4415 for (i = 0; i < nruns; ++i)
4416 if (runs[i]->nrows > 0)
4418 struct run *r = runs[i];
4420 /* Copy on the display. */
4421 if (r->current_y != r->desired_y)
4423 rif->clear_window_mouse_face (w);
4424 rif->scroll_run_hook (w, r);
4427 /* Truncate runs that copy to where we copied to, and
4428 invalidate runs that copy from where we copied to. */
4429 for (j = nruns - 1; j > i; --j)
4431 struct run *p = runs[j];
4432 bool truncated_p = 0;
4434 if (p->nrows > 0
4435 && p->desired_y < r->desired_y + r->height
4436 && p->desired_y + p->height > r->desired_y)
4438 if (p->desired_y < r->desired_y)
4440 p->nrows = r->desired_vpos - p->desired_vpos;
4441 p->height = r->desired_y - p->desired_y;
4442 truncated_p = 1;
4444 else
4446 int nrows_copied = (r->desired_vpos + r->nrows
4447 - p->desired_vpos);
4449 if (p->nrows <= nrows_copied)
4450 p->nrows = 0;
4451 else
4453 int height_copied = (r->desired_y + r->height
4454 - p->desired_y);
4456 p->current_vpos += nrows_copied;
4457 p->desired_vpos += nrows_copied;
4458 p->nrows -= nrows_copied;
4459 p->current_y += height_copied;
4460 p->desired_y += height_copied;
4461 p->height -= height_copied;
4462 truncated_p = 1;
4467 if (r->current_y != r->desired_y
4468 /* The condition below is equivalent to
4469 ((p->current_y >= r->desired_y
4470 && p->current_y < r->desired_y + r->height)
4471 || (p->current_y + p->height > r->desired_y
4472 && (p->current_y + p->height
4473 <= r->desired_y + r->height)))
4474 because we have 0 < p->height <= r->height. */
4475 && p->current_y < r->desired_y + r->height
4476 && p->current_y + p->height > r->desired_y)
4477 p->nrows = 0;
4479 /* Reorder runs by copied pixel lines if truncated. */
4480 if (truncated_p && p->nrows > 0)
4482 int k = nruns - 1;
4484 while (runs[k]->nrows == 0 || runs[k]->height < p->height)
4485 k--;
4486 memmove (runs + j, runs + j + 1, (k - j) * sizeof (*runs));
4487 runs[k] = p;
4491 /* Assign matrix rows. */
4492 for (j = 0; j < r->nrows; ++j)
4494 struct glyph_row *from, *to;
4495 bool to_overlapped_p;
4497 to = MATRIX_ROW (current_matrix, r->desired_vpos + j);
4498 from = MATRIX_ROW (desired_matrix, r->desired_vpos + j);
4499 to_overlapped_p = to->overlapped_p;
4500 from->redraw_fringe_bitmaps_p = from->fringe_bitmap_periodic_p;
4501 assign_row (to, from);
4502 /* The above `assign_row' actually does swap, so if we had
4503 an overlap in the copy destination of two runs, then
4504 the second run would assign a previously disabled bogus
4505 row. But thanks to the truncation code in the
4506 preceding for-loop, we no longer have such an overlap,
4507 and thus the assigned row should always be enabled. */
4508 eassert (to->enabled_p);
4509 from->enabled_p = 0;
4510 to->overlapped_p = to_overlapped_p;
4514 /* Clear the hash table, for the next time. */
4515 for (i = 0; i < row_entry_idx; ++i)
4516 row_table[row_entry_pool[i].bucket] = NULL;
4518 /* Value is 1 to indicate that we scrolled the display. */
4519 return 0 < nruns;
4524 /************************************************************************
4525 Frame-Based Updates
4526 ************************************************************************/
4528 /* Update the desired frame matrix of frame F.
4530 FORCE_P means that the update should not be stopped by pending input.
4531 INHIBIT_HAIRY_ID_P means that scrolling should not be tried.
4533 Value is true if update was stopped due to pending input. */
4535 static bool
4536 update_frame_1 (struct frame *f, bool force_p, bool inhibit_id_p)
4538 /* Frame matrices to work on. */
4539 struct glyph_matrix *current_matrix = f->current_matrix;
4540 struct glyph_matrix *desired_matrix = f->desired_matrix;
4541 int i;
4542 bool pause_p;
4543 int preempt_count = baud_rate / 2400 + 1;
4545 eassert (current_matrix && desired_matrix);
4547 if (baud_rate != FRAME_COST_BAUD_RATE (f))
4548 calculate_costs (f);
4550 if (preempt_count <= 0)
4551 preempt_count = 1;
4553 #if !PERIODIC_PREEMPTION_CHECKING
4554 if (!force_p && detect_input_pending_ignore_squeezables ())
4556 pause_p = 1;
4557 goto do_pause;
4559 #endif
4561 /* If we cannot insert/delete lines, it's no use trying it. */
4562 if (!FRAME_LINE_INS_DEL_OK (f))
4563 inhibit_id_p = 1;
4565 /* See if any of the desired lines are enabled; don't compute for
4566 i/d line if just want cursor motion. */
4567 for (i = 0; i < desired_matrix->nrows; i++)
4568 if (MATRIX_ROW_ENABLED_P (desired_matrix, i))
4569 break;
4571 /* Try doing i/d line, if not yet inhibited. */
4572 if (!inhibit_id_p && i < desired_matrix->nrows)
4573 force_p |= scrolling (f);
4575 /* Update the individual lines as needed. Do bottom line first. */
4576 if (MATRIX_ROW_ENABLED_P (desired_matrix, desired_matrix->nrows - 1))
4577 update_frame_line (f, desired_matrix->nrows - 1);
4579 /* Now update the rest of the lines. */
4580 for (i = 0; i < desired_matrix->nrows - 1 && (force_p || !input_pending); i++)
4582 if (MATRIX_ROW_ENABLED_P (desired_matrix, i))
4584 if (FRAME_TERMCAP_P (f))
4586 /* Flush out every so many lines.
4587 Also flush out if likely to have more than 1k buffered
4588 otherwise. I'm told that some telnet connections get
4589 really screwed by more than 1k output at once. */
4590 FILE *display_output = FRAME_TTY (f)->output;
4591 if (display_output)
4593 ptrdiff_t outq = __fpending (display_output);
4594 if (outq > 900
4595 || (outq > 20 && ((i - 1) % preempt_count == 0)))
4596 fflush (display_output);
4600 #if PERIODIC_PREEMPTION_CHECKING
4601 if (!force_p)
4603 EMACS_TIME tm = current_emacs_time ();
4604 if (EMACS_TIME_LT (preemption_next_check, tm))
4606 preemption_next_check = add_emacs_time (tm, preemption_period);
4607 if (detect_input_pending_ignore_squeezables ())
4608 break;
4611 #else
4612 if (!force_p && (i - 1) % preempt_count == 0)
4613 detect_input_pending_ignore_squeezables ();
4614 #endif
4616 update_frame_line (f, i);
4620 lint_assume (0 <= FRAME_LINES (f));
4621 pause_p = 0 < i && i < FRAME_LINES (f) - 1;
4623 /* Now just clean up termcap drivers and set cursor, etc. */
4624 if (!pause_p)
4626 if ((cursor_in_echo_area
4627 /* If we are showing a message instead of the mini-buffer,
4628 show the cursor for the message instead of for the
4629 (now hidden) mini-buffer contents. */
4630 || (EQ (minibuf_window, selected_window)
4631 && EQ (minibuf_window, echo_area_window)
4632 && !NILP (echo_area_buffer[0])))
4633 /* These cases apply only to the frame that contains
4634 the active mini-buffer window. */
4635 && FRAME_HAS_MINIBUF_P (f)
4636 && EQ (FRAME_MINIBUF_WINDOW (f), echo_area_window))
4638 int top = WINDOW_TOP_EDGE_LINE (XWINDOW (FRAME_MINIBUF_WINDOW (f)));
4639 int row, col;
4641 if (cursor_in_echo_area < 0)
4643 /* Negative value of cursor_in_echo_area means put
4644 cursor at beginning of line. */
4645 row = top;
4646 col = 0;
4648 else
4650 /* Positive value of cursor_in_echo_area means put
4651 cursor at the end of the prompt. If the mini-buffer
4652 is several lines high, find the last line that has
4653 any text on it. */
4654 row = FRAME_LINES (f);
4657 --row;
4658 col = 0;
4660 if (MATRIX_ROW_ENABLED_P (current_matrix, row))
4662 /* Frame rows are filled up with spaces that
4663 must be ignored here. */
4664 struct glyph_row *r = MATRIX_ROW (current_matrix,
4665 row);
4666 struct glyph *start = r->glyphs[TEXT_AREA];
4667 struct glyph *last = start + r->used[TEXT_AREA];
4669 while (last > start
4670 && (last - 1)->charpos < 0)
4671 --last;
4673 col = last - start;
4676 while (row > top && col == 0);
4678 /* Make sure COL is not out of range. */
4679 if (col >= FRAME_CURSOR_X_LIMIT (f))
4681 /* If we have another row, advance cursor into it. */
4682 if (row < FRAME_LINES (f) - 1)
4684 col = FRAME_LEFT_SCROLL_BAR_COLS (f);
4685 row++;
4687 /* Otherwise move it back in range. */
4688 else
4689 col = FRAME_CURSOR_X_LIMIT (f) - 1;
4693 cursor_to (f, row, col);
4695 else
4697 /* We have only one cursor on terminal frames. Use it to
4698 display the cursor of the selected window. */
4699 struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
4700 if (w->cursor.vpos >= 0
4701 /* The cursor vpos may be temporarily out of bounds
4702 in the following situation: There is one window,
4703 with the cursor in the lower half of it. The window
4704 is split, and a message causes a redisplay before
4705 a new cursor position has been computed. */
4706 && w->cursor.vpos < WINDOW_TOTAL_LINES (w))
4708 int x = WINDOW_TO_FRAME_HPOS (w, w->cursor.hpos);
4709 int y = WINDOW_TO_FRAME_VPOS (w, w->cursor.vpos);
4711 if (INTEGERP (w->left_margin_cols))
4712 x += XFASTINT (w->left_margin_cols);
4714 /* x = max (min (x, FRAME_TOTAL_COLS (f) - 1), 0); */
4715 cursor_to (f, y, x);
4720 #if !PERIODIC_PREEMPTION_CHECKING
4721 do_pause:
4722 #endif
4724 clear_desired_matrices (f);
4725 return pause_p;
4729 /* Do line insertions/deletions on frame F for frame-based redisplay. */
4731 static bool
4732 scrolling (struct frame *frame)
4734 int unchanged_at_top, unchanged_at_bottom;
4735 int window_size;
4736 int changed_lines;
4737 int *old_hash = alloca (FRAME_LINES (frame) * sizeof (int));
4738 int *new_hash = alloca (FRAME_LINES (frame) * sizeof (int));
4739 int *draw_cost = alloca (FRAME_LINES (frame) * sizeof (int));
4740 int *old_draw_cost = alloca (FRAME_LINES (frame) * sizeof (int));
4741 register int i;
4742 int free_at_end_vpos = FRAME_LINES (frame);
4743 struct glyph_matrix *current_matrix = frame->current_matrix;
4744 struct glyph_matrix *desired_matrix = frame->desired_matrix;
4746 if (!current_matrix)
4747 emacs_abort ();
4749 /* Compute hash codes of all the lines. Also calculate number of
4750 changed lines, number of unchanged lines at the beginning, and
4751 number of unchanged lines at the end. */
4752 changed_lines = 0;
4753 unchanged_at_top = 0;
4754 unchanged_at_bottom = FRAME_LINES (frame);
4755 for (i = 0; i < FRAME_LINES (frame); i++)
4757 /* Give up on this scrolling if some old lines are not enabled. */
4758 if (!MATRIX_ROW_ENABLED_P (current_matrix, i))
4759 return 0;
4760 old_hash[i] = line_hash_code (MATRIX_ROW (current_matrix, i));
4761 if (! MATRIX_ROW_ENABLED_P (desired_matrix, i))
4763 /* This line cannot be redrawn, so don't let scrolling mess it. */
4764 new_hash[i] = old_hash[i];
4765 #define INFINITY 1000000 /* Taken from scroll.c */
4766 draw_cost[i] = INFINITY;
4768 else
4770 new_hash[i] = line_hash_code (MATRIX_ROW (desired_matrix, i));
4771 draw_cost[i] = line_draw_cost (desired_matrix, i);
4774 if (old_hash[i] != new_hash[i])
4776 changed_lines++;
4777 unchanged_at_bottom = FRAME_LINES (frame) - i - 1;
4779 else if (i == unchanged_at_top)
4780 unchanged_at_top++;
4781 old_draw_cost[i] = line_draw_cost (current_matrix, i);
4784 /* If changed lines are few, don't allow preemption, don't scroll. */
4785 if ((!FRAME_SCROLL_REGION_OK (frame)
4786 && changed_lines < baud_rate / 2400)
4787 || unchanged_at_bottom == FRAME_LINES (frame))
4788 return 1;
4790 window_size = (FRAME_LINES (frame) - unchanged_at_top
4791 - unchanged_at_bottom);
4793 if (FRAME_SCROLL_REGION_OK (frame))
4794 free_at_end_vpos -= unchanged_at_bottom;
4795 else if (FRAME_MEMORY_BELOW_FRAME (frame))
4796 free_at_end_vpos = -1;
4798 /* If large window, fast terminal and few lines in common between
4799 current frame and desired frame, don't bother with i/d calc. */
4800 if (!FRAME_SCROLL_REGION_OK (frame)
4801 && window_size >= 18 && baud_rate > 2400
4802 && (window_size >=
4803 10 * scrolling_max_lines_saved (unchanged_at_top,
4804 FRAME_LINES (frame) - unchanged_at_bottom,
4805 old_hash, new_hash, draw_cost)))
4806 return 0;
4808 if (window_size < 2)
4809 return 0;
4811 scrolling_1 (frame, window_size, unchanged_at_top, unchanged_at_bottom,
4812 draw_cost + unchanged_at_top - 1,
4813 old_draw_cost + unchanged_at_top - 1,
4814 old_hash + unchanged_at_top - 1,
4815 new_hash + unchanged_at_top - 1,
4816 free_at_end_vpos - unchanged_at_top);
4818 return 0;
4822 /* Count the number of blanks at the start of the vector of glyphs R
4823 which is LEN glyphs long. */
4825 static int
4826 count_blanks (struct glyph *r, int len)
4828 int i;
4830 for (i = 0; i < len; ++i)
4831 if (!CHAR_GLYPH_SPACE_P (r[i]))
4832 break;
4834 return i;
4838 /* Count the number of glyphs in common at the start of the glyph
4839 vectors STR1 and STR2. END1 is the end of STR1 and END2 is the end
4840 of STR2. Value is the number of equal glyphs equal at the start. */
4842 static int
4843 count_match (struct glyph *str1, struct glyph *end1, struct glyph *str2, struct glyph *end2)
4845 struct glyph *p1 = str1;
4846 struct glyph *p2 = str2;
4848 while (p1 < end1
4849 && p2 < end2
4850 && GLYPH_CHAR_AND_FACE_EQUAL_P (p1, p2))
4851 ++p1, ++p2;
4853 return p1 - str1;
4857 /* Char insertion/deletion cost vector, from term.c */
4859 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_TOTAL_COLS ((f))])
4862 /* Perform a frame-based update on line VPOS in frame FRAME. */
4864 static void
4865 update_frame_line (struct frame *f, int vpos)
4867 struct glyph *obody, *nbody, *op1, *op2, *np1, *nend;
4868 int tem;
4869 int osp, nsp, begmatch, endmatch, olen, nlen;
4870 struct glyph_matrix *current_matrix = f->current_matrix;
4871 struct glyph_matrix *desired_matrix = f->desired_matrix;
4872 struct glyph_row *current_row = MATRIX_ROW (current_matrix, vpos);
4873 struct glyph_row *desired_row = MATRIX_ROW (desired_matrix, vpos);
4874 bool must_write_whole_line_p;
4875 bool write_spaces_p = FRAME_MUST_WRITE_SPACES (f);
4876 bool colored_spaces_p = (FACE_FROM_ID (f, DEFAULT_FACE_ID)->background
4877 != FACE_TTY_DEFAULT_BG_COLOR);
4879 if (colored_spaces_p)
4880 write_spaces_p = 1;
4882 /* Current row not enabled means it has unknown contents. We must
4883 write the whole desired line in that case. */
4884 must_write_whole_line_p = !current_row->enabled_p;
4885 if (must_write_whole_line_p)
4887 obody = 0;
4888 olen = 0;
4890 else
4892 obody = MATRIX_ROW_GLYPH_START (current_matrix, vpos);
4893 olen = current_row->used[TEXT_AREA];
4895 /* Ignore trailing spaces, if we can. */
4896 if (!write_spaces_p)
4897 while (olen > 0 && CHAR_GLYPH_SPACE_P (obody[olen-1]))
4898 olen--;
4901 current_row->enabled_p = 1;
4902 current_row->used[TEXT_AREA] = desired_row->used[TEXT_AREA];
4904 /* If desired line is empty, just clear the line. */
4905 if (!desired_row->enabled_p)
4907 nlen = 0;
4908 goto just_erase;
4911 nbody = desired_row->glyphs[TEXT_AREA];
4912 nlen = desired_row->used[TEXT_AREA];
4913 nend = nbody + nlen;
4915 /* If display line has unknown contents, write the whole line. */
4916 if (must_write_whole_line_p)
4918 /* Ignore spaces at the end, if we can. */
4919 if (!write_spaces_p)
4920 while (nlen > 0 && CHAR_GLYPH_SPACE_P (nbody[nlen - 1]))
4921 --nlen;
4923 /* Write the contents of the desired line. */
4924 if (nlen)
4926 cursor_to (f, vpos, 0);
4927 write_glyphs (f, nbody, nlen);
4930 /* Don't call clear_end_of_line if we already wrote the whole
4931 line. The cursor will not be at the right margin in that
4932 case but in the line below. */
4933 if (nlen < FRAME_TOTAL_COLS (f))
4935 cursor_to (f, vpos, nlen);
4936 clear_end_of_line (f, FRAME_TOTAL_COLS (f));
4938 else
4939 /* Make sure we are in the right row, otherwise cursor movement
4940 with cmgoto might use `ch' in the wrong row. */
4941 cursor_to (f, vpos, 0);
4943 make_current (desired_matrix, current_matrix, vpos);
4944 return;
4947 /* Pretend trailing spaces are not there at all,
4948 unless for one reason or another we must write all spaces. */
4949 if (!write_spaces_p)
4950 while (nlen > 0 && CHAR_GLYPH_SPACE_P (nbody[nlen - 1]))
4951 nlen--;
4953 /* If there's no i/d char, quickly do the best we can without it. */
4954 if (!FRAME_CHAR_INS_DEL_OK (f))
4956 int i, j;
4958 /* Find the first glyph in desired row that doesn't agree with
4959 a glyph in the current row, and write the rest from there on. */
4960 for (i = 0; i < nlen; i++)
4962 if (i >= olen || !GLYPH_EQUAL_P (nbody + i, obody + i))
4964 /* Find the end of the run of different glyphs. */
4965 j = i + 1;
4966 while (j < nlen
4967 && (j >= olen
4968 || !GLYPH_EQUAL_P (nbody + j, obody + j)
4969 || CHAR_GLYPH_PADDING_P (nbody[j])))
4970 ++j;
4972 /* Output this run of non-matching chars. */
4973 cursor_to (f, vpos, i);
4974 write_glyphs (f, nbody + i, j - i);
4975 i = j - 1;
4977 /* Now find the next non-match. */
4981 /* Clear the rest of the line, or the non-clear part of it. */
4982 if (olen > nlen)
4984 cursor_to (f, vpos, nlen);
4985 clear_end_of_line (f, olen);
4988 /* Make current row = desired row. */
4989 make_current (desired_matrix, current_matrix, vpos);
4990 return;
4993 /* Here when CHAR_INS_DEL_OK != 0, i.e. we can insert or delete
4994 characters in a row. */
4996 if (!olen)
4998 /* If current line is blank, skip over initial spaces, if
4999 possible, and write the rest. */
5000 if (write_spaces_p)
5001 nsp = 0;
5002 else
5003 nsp = count_blanks (nbody, nlen);
5005 if (nlen > nsp)
5007 cursor_to (f, vpos, nsp);
5008 write_glyphs (f, nbody + nsp, nlen - nsp);
5011 /* Exchange contents between current_frame and new_frame. */
5012 make_current (desired_matrix, current_matrix, vpos);
5013 return;
5016 /* Compute number of leading blanks in old and new contents. */
5017 osp = count_blanks (obody, olen);
5018 nsp = (colored_spaces_p ? 0 : count_blanks (nbody, nlen));
5020 /* Compute number of matching chars starting with first non-blank. */
5021 begmatch = count_match (obody + osp, obody + olen,
5022 nbody + nsp, nbody + nlen);
5024 /* Spaces in new match implicit space past the end of old. */
5025 /* A bug causing this to be a no-op was fixed in 18.29. */
5026 if (!write_spaces_p && osp + begmatch == olen)
5028 np1 = nbody + nsp;
5029 while (np1 + begmatch < nend && CHAR_GLYPH_SPACE_P (np1[begmatch]))
5030 ++begmatch;
5033 /* Avoid doing insert/delete char
5034 just cause number of leading spaces differs
5035 when the following text does not match. */
5036 if (begmatch == 0 && osp != nsp)
5037 osp = nsp = min (osp, nsp);
5039 /* Find matching characters at end of line */
5040 op1 = obody + olen;
5041 np1 = nbody + nlen;
5042 op2 = op1 + begmatch - min (olen - osp, nlen - nsp);
5043 while (op1 > op2
5044 && GLYPH_EQUAL_P (op1 - 1, np1 - 1))
5046 op1--;
5047 np1--;
5049 endmatch = obody + olen - op1;
5051 /* tem gets the distance to insert or delete.
5052 endmatch is how many characters we save by doing so.
5053 Is it worth it? */
5055 tem = (nlen - nsp) - (olen - osp);
5056 if (endmatch && tem
5057 && (!FRAME_CHAR_INS_DEL_OK (f)
5058 || endmatch <= char_ins_del_cost (f)[tem]))
5059 endmatch = 0;
5061 /* nsp - osp is the distance to insert or delete.
5062 If that is nonzero, begmatch is known to be nonzero also.
5063 begmatch + endmatch is how much we save by doing the ins/del.
5064 Is it worth it? */
5066 if (nsp != osp
5067 && (!FRAME_CHAR_INS_DEL_OK (f)
5068 || begmatch + endmatch <= char_ins_del_cost (f)[nsp - osp]))
5070 begmatch = 0;
5071 endmatch = 0;
5072 osp = nsp = min (osp, nsp);
5075 /* Now go through the line, inserting, writing and
5076 deleting as appropriate. */
5078 if (osp > nsp)
5080 cursor_to (f, vpos, nsp);
5081 delete_glyphs (f, osp - nsp);
5083 else if (nsp > osp)
5085 /* If going to delete chars later in line
5086 and insert earlier in the line,
5087 must delete first to avoid losing data in the insert */
5088 if (endmatch && nlen < olen + nsp - osp)
5090 cursor_to (f, vpos, nlen - endmatch + osp - nsp);
5091 delete_glyphs (f, olen + nsp - osp - nlen);
5092 olen = nlen - (nsp - osp);
5094 cursor_to (f, vpos, osp);
5095 insert_glyphs (f, 0, nsp - osp);
5097 olen += nsp - osp;
5099 tem = nsp + begmatch + endmatch;
5100 if (nlen != tem || olen != tem)
5102 if (!endmatch || nlen == olen)
5104 /* If new text being written reaches right margin, there is
5105 no need to do clear-to-eol at the end of this function
5106 (and it would not be safe, since cursor is not going to
5107 be "at the margin" after the text is done). */
5108 if (nlen == FRAME_TOTAL_COLS (f))
5109 olen = 0;
5111 /* Function write_glyphs is prepared to do nothing
5112 if passed a length <= 0. Check it here to avoid
5113 unnecessary cursor movement. */
5114 if (nlen - tem > 0)
5116 cursor_to (f, vpos, nsp + begmatch);
5117 write_glyphs (f, nbody + nsp + begmatch, nlen - tem);
5120 else if (nlen > olen)
5122 /* Here, we used to have the following simple code:
5123 ----------------------------------------
5124 write_glyphs (nbody + nsp + begmatch, olen - tem);
5125 insert_glyphs (nbody + nsp + begmatch + olen - tem, nlen - olen);
5126 ----------------------------------------
5127 but it doesn't work if nbody[nsp + begmatch + olen - tem]
5128 is a padding glyph. */
5129 int out = olen - tem; /* Columns to be overwritten originally. */
5130 int del;
5132 cursor_to (f, vpos, nsp + begmatch);
5134 /* Calculate columns we can actually overwrite. */
5135 while (CHAR_GLYPH_PADDING_P (nbody[nsp + begmatch + out]))
5136 out--;
5137 write_glyphs (f, nbody + nsp + begmatch, out);
5139 /* If we left columns to be overwritten, we must delete them. */
5140 del = olen - tem - out;
5141 if (del > 0)
5142 delete_glyphs (f, del);
5144 /* At last, we insert columns not yet written out. */
5145 insert_glyphs (f, nbody + nsp + begmatch + out, nlen - olen + del);
5146 olen = nlen;
5148 else if (olen > nlen)
5150 cursor_to (f, vpos, nsp + begmatch);
5151 write_glyphs (f, nbody + nsp + begmatch, nlen - tem);
5152 delete_glyphs (f, olen - nlen);
5153 olen = nlen;
5157 just_erase:
5158 /* If any unerased characters remain after the new line, erase them. */
5159 if (olen > nlen)
5161 cursor_to (f, vpos, nlen);
5162 clear_end_of_line (f, olen);
5165 /* Exchange contents between current_frame and new_frame. */
5166 make_current (desired_matrix, current_matrix, vpos);
5171 /***********************************************************************
5172 X/Y Position -> Buffer Position
5173 ***********************************************************************/
5175 /* Determine what's under window-relative pixel position (*X, *Y).
5176 Return the OBJECT (string or buffer) that's there.
5177 Return in *POS the position in that object.
5178 Adjust *X and *Y to character positions.
5179 Return in *DX and *DY the pixel coordinates of the click,
5180 relative to the top left corner of OBJECT, or relative to
5181 the top left corner of the character glyph at (*X, *Y)
5182 if OBJECT is nil.
5183 Return WIDTH and HEIGHT of the object at (*X, *Y), or zero
5184 if the coordinates point to an empty area of the display. */
5186 Lisp_Object
5187 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)
5189 struct it it;
5190 Lisp_Object old_current_buffer = Fcurrent_buffer ();
5191 struct text_pos startp;
5192 Lisp_Object string;
5193 struct glyph_row *row;
5194 #ifdef HAVE_WINDOW_SYSTEM
5195 struct image *img = 0;
5196 #endif
5197 int x0, x1, to_x;
5198 void *itdata = NULL;
5200 /* We used to set current_buffer directly here, but that does the
5201 wrong thing with `face-remapping-alist' (bug#2044). */
5202 Fset_buffer (w->buffer);
5203 itdata = bidi_shelve_cache ();
5204 SET_TEXT_POS_FROM_MARKER (startp, w->start);
5205 CHARPOS (startp) = min (ZV, max (BEGV, CHARPOS (startp)));
5206 BYTEPOS (startp) = min (ZV_BYTE, max (BEGV_BYTE, BYTEPOS (startp)));
5207 start_display (&it, w, startp);
5208 /* start_display takes into account the header-line row, but IT's
5209 vpos still counts from the glyph row that includes the window's
5210 start position. Adjust for a possible header-line row. */
5211 it.vpos += WINDOW_WANTS_HEADER_LINE_P (w);
5213 x0 = *x;
5215 /* First, move to the beginning of the row corresponding to *Y. We
5216 need to be in that row to get the correct value of base paragraph
5217 direction for the text at (*X, *Y). */
5218 move_it_to (&it, -1, 0, *y, -1, MOVE_TO_X | MOVE_TO_Y);
5220 /* TO_X is the pixel position that the iterator will compute for the
5221 glyph at *X. We add it.first_visible_x because iterator
5222 positions include the hscroll. */
5223 to_x = x0 + it.first_visible_x;
5224 if (it.bidi_it.paragraph_dir == R2L)
5225 /* For lines in an R2L paragraph, we need to mirror TO_X wrt the
5226 text area. This is because the iterator, even in R2L
5227 paragraphs, delivers glyphs as if they started at the left
5228 margin of the window. (When we actually produce glyphs for
5229 display, we reverse their order in PRODUCE_GLYPHS, but the
5230 iterator doesn't know about that.) The following line adjusts
5231 the pixel position to the iterator geometry, which is what
5232 move_it_* routines use. (The -1 is because in a window whose
5233 text-area width is W, the rightmost pixel position is W-1, and
5234 it should be mirrored into zero pixel position.) */
5235 to_x = window_box_width (w, TEXT_AREA) - to_x - 1;
5237 /* Now move horizontally in the row to the glyph under *X. Second
5238 argument is ZV to prevent move_it_in_display_line from matching
5239 based on buffer positions. */
5240 move_it_in_display_line (&it, ZV, to_x, MOVE_TO_X);
5241 bidi_unshelve_cache (itdata, 0);
5243 Fset_buffer (old_current_buffer);
5245 *dx = x0 + it.first_visible_x - it.current_x;
5246 *dy = *y - it.current_y;
5248 string = w->buffer;
5249 if (STRINGP (it.string))
5250 string = it.string;
5251 *pos = it.current;
5252 if (it.what == IT_COMPOSITION
5253 && it.cmp_it.nchars > 1
5254 && it.cmp_it.reversed_p)
5256 /* The current display element is a grapheme cluster in a
5257 composition. In that case, we need the position of the first
5258 character of the cluster. But, as it.cmp_it.reversed_p is 1,
5259 it.current points to the last character of the cluster, thus
5260 we must move back to the first character of the same
5261 cluster. */
5262 CHARPOS (pos->pos) -= it.cmp_it.nchars - 1;
5263 if (STRINGP (it.string))
5264 BYTEPOS (pos->pos) = string_char_to_byte (string, CHARPOS (pos->pos));
5265 else
5266 BYTEPOS (pos->pos) = buf_charpos_to_bytepos (XBUFFER (w->buffer),
5267 CHARPOS (pos->pos));
5270 #ifdef HAVE_WINDOW_SYSTEM
5271 if (it.what == IT_IMAGE)
5273 if ((img = IMAGE_FROM_ID (it.f, it.image_id)) != NULL
5274 && !NILP (img->spec))
5275 *object = img->spec;
5277 #endif
5279 if (it.vpos < w->current_matrix->nrows
5280 && (row = MATRIX_ROW (w->current_matrix, it.vpos),
5281 row->enabled_p))
5283 if (it.hpos < row->used[TEXT_AREA])
5285 struct glyph *glyph = row->glyphs[TEXT_AREA] + it.hpos;
5286 #ifdef HAVE_WINDOW_SYSTEM
5287 if (img)
5289 *dy -= row->ascent - glyph->ascent;
5290 *dx += glyph->slice.img.x;
5291 *dy += glyph->slice.img.y;
5292 /* Image slices positions are still relative to the entire image */
5293 *width = img->width;
5294 *height = img->height;
5296 else
5297 #endif
5299 *width = glyph->pixel_width;
5300 *height = glyph->ascent + glyph->descent;
5303 else
5305 *width = 0;
5306 *height = row->height;
5309 else
5311 *width = *height = 0;
5314 /* Add extra (default width) columns if clicked after EOL. */
5315 x1 = max (0, it.current_x + it.pixel_width - it.first_visible_x);
5316 if (x0 > x1)
5317 it.hpos += (x0 - x1) / WINDOW_FRAME_COLUMN_WIDTH (w);
5319 *x = it.hpos;
5320 *y = it.vpos;
5322 return string;
5326 /* Value is the string under window-relative coordinates X/Y in the
5327 mode line or header line (PART says which) of window W, or nil if none.
5328 *CHARPOS is set to the position in the string returned. */
5330 Lisp_Object
5331 mode_line_string (struct window *w, enum window_part part,
5332 int *x, int *y, ptrdiff_t *charpos, Lisp_Object *object,
5333 int *dx, int *dy, int *width, int *height)
5335 struct glyph_row *row;
5336 struct glyph *glyph, *end;
5337 int x0, y0;
5338 Lisp_Object string = Qnil;
5340 if (part == ON_MODE_LINE)
5341 row = MATRIX_MODE_LINE_ROW (w->current_matrix);
5342 else
5343 row = MATRIX_HEADER_LINE_ROW (w->current_matrix);
5344 y0 = *y - row->y;
5345 *y = row - MATRIX_FIRST_TEXT_ROW (w->current_matrix);
5347 if (row->mode_line_p && row->enabled_p)
5349 /* Find the glyph under X. If we find one with a string object,
5350 it's the one we were looking for. */
5351 glyph = row->glyphs[TEXT_AREA];
5352 end = glyph + row->used[TEXT_AREA];
5353 for (x0 = *x; glyph < end && x0 >= glyph->pixel_width; ++glyph)
5354 x0 -= glyph->pixel_width;
5355 *x = glyph - row->glyphs[TEXT_AREA];
5356 if (glyph < end)
5358 string = glyph->object;
5359 *charpos = glyph->charpos;
5360 *width = glyph->pixel_width;
5361 *height = glyph->ascent + glyph->descent;
5362 #ifdef HAVE_WINDOW_SYSTEM
5363 if (glyph->type == IMAGE_GLYPH)
5365 struct image *img;
5366 img = IMAGE_FROM_ID (WINDOW_XFRAME (w), glyph->u.img_id);
5367 if (img != NULL)
5368 *object = img->spec;
5369 y0 -= row->ascent - glyph->ascent;
5371 #endif
5373 else
5375 /* Add extra (default width) columns if clicked after EOL. */
5376 *x += x0 / WINDOW_FRAME_COLUMN_WIDTH (w);
5377 *width = 0;
5378 *height = row->height;
5381 else
5383 *x = 0;
5384 x0 = 0;
5385 *width = *height = 0;
5388 *dx = x0;
5389 *dy = y0;
5391 return string;
5395 /* Value is the string under window-relative coordinates X/Y in either
5396 marginal area, or nil if none. *CHARPOS is set to the position in
5397 the string returned. */
5399 Lisp_Object
5400 marginal_area_string (struct window *w, enum window_part part,
5401 int *x, int *y, ptrdiff_t *charpos, Lisp_Object *object,
5402 int *dx, int *dy, int *width, int *height)
5404 struct glyph_row *row = w->current_matrix->rows;
5405 struct glyph *glyph, *end;
5406 int x0, y0, i, wy = *y;
5407 int area;
5408 Lisp_Object string = Qnil;
5410 if (part == ON_LEFT_MARGIN)
5411 area = LEFT_MARGIN_AREA;
5412 else if (part == ON_RIGHT_MARGIN)
5413 area = RIGHT_MARGIN_AREA;
5414 else
5415 emacs_abort ();
5417 for (i = 0; row->enabled_p && i < w->current_matrix->nrows; ++i, ++row)
5418 if (wy >= row->y && wy < MATRIX_ROW_BOTTOM_Y (row))
5419 break;
5420 y0 = *y - row->y;
5421 *y = row - MATRIX_FIRST_TEXT_ROW (w->current_matrix);
5423 if (row->enabled_p)
5425 /* Find the glyph under X. If we find one with a string object,
5426 it's the one we were looking for. */
5427 if (area == RIGHT_MARGIN_AREA)
5428 x0 = ((WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5429 ? WINDOW_LEFT_FRINGE_WIDTH (w)
5430 : WINDOW_TOTAL_FRINGE_WIDTH (w))
5431 + window_box_width (w, LEFT_MARGIN_AREA)
5432 + window_box_width (w, TEXT_AREA));
5433 else
5434 x0 = (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
5435 ? WINDOW_LEFT_FRINGE_WIDTH (w)
5436 : 0);
5438 glyph = row->glyphs[area];
5439 end = glyph + row->used[area];
5440 for (x0 = *x - x0; glyph < end && x0 >= glyph->pixel_width; ++glyph)
5441 x0 -= glyph->pixel_width;
5442 *x = glyph - row->glyphs[area];
5443 if (glyph < end)
5445 string = glyph->object;
5446 *charpos = glyph->charpos;
5447 *width = glyph->pixel_width;
5448 *height = glyph->ascent + glyph->descent;
5449 #ifdef HAVE_WINDOW_SYSTEM
5450 if (glyph->type == IMAGE_GLYPH)
5452 struct image *img;
5453 img = IMAGE_FROM_ID (WINDOW_XFRAME (w), glyph->u.img_id);
5454 if (img != NULL)
5455 *object = img->spec;
5456 y0 -= row->ascent - glyph->ascent;
5457 x0 += glyph->slice.img.x;
5458 y0 += glyph->slice.img.y;
5460 #endif
5462 else
5464 /* Add extra (default width) columns if clicked after EOL. */
5465 *x += x0 / WINDOW_FRAME_COLUMN_WIDTH (w);
5466 *width = 0;
5467 *height = row->height;
5470 else
5472 x0 = 0;
5473 *x = 0;
5474 *width = *height = 0;
5477 *dx = x0;
5478 *dy = y0;
5480 return string;
5484 /***********************************************************************
5485 Changing Frame Sizes
5486 ***********************************************************************/
5488 #ifdef SIGWINCH
5490 static void deliver_window_change_signal (int);
5492 static void
5493 handle_window_change_signal (int sig)
5495 int width, height;
5496 struct tty_display_info *tty;
5498 /* The frame size change obviously applies to a single
5499 termcap-controlled terminal, but we can't decide which.
5500 Therefore, we resize the frames corresponding to each tty.
5502 for (tty = tty_list; tty; tty = tty->next) {
5504 if (! tty->term_initted)
5505 continue;
5507 /* Suspended tty frames have tty->input == NULL avoid trying to
5508 use it. */
5509 if (!tty->input)
5510 continue;
5512 get_tty_size (fileno (tty->input), &width, &height);
5514 if (width > 5 && height > 2) {
5515 Lisp_Object tail, frame;
5517 FOR_EACH_FRAME (tail, frame)
5518 if (FRAME_TERMCAP_P (XFRAME (frame)) && FRAME_TTY (XFRAME (frame)) == tty)
5519 /* Record the new sizes, but don't reallocate the data
5520 structures now. Let that be done later outside of the
5521 signal handler. */
5522 change_frame_size (XFRAME (frame), height, width, 0, 1, 0);
5527 static void
5528 deliver_window_change_signal (int sig)
5530 deliver_process_signal (sig, handle_window_change_signal);
5532 #endif /* SIGWINCH */
5535 /* Do any change in frame size that was requested by a signal.
5536 SAFE means this function is called from a place where it is
5537 safe to change frame sizes while a redisplay is in progress. */
5539 void
5540 do_pending_window_change (bool safe)
5542 /* If window change signal handler should have run before, run it now. */
5543 if (redisplaying_p && !safe)
5544 return;
5546 while (delayed_size_change)
5548 Lisp_Object tail, frame;
5550 delayed_size_change = 0;
5552 FOR_EACH_FRAME (tail, frame)
5554 struct frame *f = XFRAME (frame);
5556 if (f->new_text_lines != 0 || f->new_text_cols != 0)
5557 change_frame_size (f, f->new_text_lines, f->new_text_cols,
5558 0, 0, safe);
5564 /* Change the frame height and/or width. Values may be given as zero to
5565 indicate no change is to take place.
5567 If DELAY, assume we're being called from a signal handler, and
5568 queue the change for later - perhaps the next redisplay.
5569 Since this tries to resize windows, we can't call it
5570 from a signal handler.
5572 SAFE means this function is called from a place where it's
5573 safe to change frame sizes while a redisplay is in progress. */
5575 void
5576 change_frame_size (struct frame *f, int newheight, int newwidth,
5577 bool pretend, bool delay, bool safe)
5579 Lisp_Object tail, frame;
5581 if (FRAME_MSDOS_P (f))
5583 /* On MS-DOS, all frames use the same screen, so a change in
5584 size affects all frames. Termcap now supports multiple
5585 ttys. */
5586 FOR_EACH_FRAME (tail, frame)
5587 if (! FRAME_WINDOW_P (XFRAME (frame)))
5588 change_frame_size_1 (XFRAME (frame), newheight, newwidth,
5589 pretend, delay, safe);
5591 else
5592 change_frame_size_1 (f, newheight, newwidth, pretend, delay, safe);
5595 static void
5596 change_frame_size_1 (struct frame *f, int newheight, int newwidth,
5597 bool pretend, bool delay, bool safe)
5599 int new_frame_total_cols;
5600 ptrdiff_t count = SPECPDL_INDEX ();
5602 /* If we can't deal with the change now, queue it for later. */
5603 if (delay || (redisplaying_p && !safe))
5605 f->new_text_lines = newheight;
5606 f->new_text_cols = newwidth;
5607 delayed_size_change = 1;
5608 return;
5611 /* This size-change overrides any pending one for this frame. */
5612 f->new_text_lines = 0;
5613 f->new_text_cols = 0;
5615 /* If an argument is zero, set it to the current value. */
5616 if (newheight == 0)
5617 newheight = FRAME_LINES (f);
5618 if (newwidth == 0)
5619 newwidth = FRAME_COLS (f);
5621 /* Compute width of windows in F. */
5622 /* Round up to the smallest acceptable size. */
5623 check_frame_size (f, &newheight, &newwidth);
5625 /* This is the width of the frame with vertical scroll bars and fringe
5626 columns. Do this after rounding - see discussion of bug#9723. */
5627 new_frame_total_cols = FRAME_TOTAL_COLS_ARG (f, newwidth);
5629 /* If we're not changing the frame size, quit now. */
5630 /* Frame width may be unchanged but the text portion may change, for
5631 example, fullscreen and remove/add scroll bar. */
5632 if (newheight == FRAME_LINES (f)
5633 /* Text portion unchanged? */
5634 && newwidth == FRAME_COLS (f)
5635 /* Frame width unchanged? */
5636 && new_frame_total_cols == FRAME_TOTAL_COLS (f))
5637 return;
5639 block_input ();
5641 #ifdef MSDOS
5642 /* We only can set screen dimensions to certain values supported
5643 by our video hardware. Try to find the smallest size greater
5644 or equal to the requested dimensions. */
5645 dos_set_window_size (&newheight, &newwidth);
5646 #endif
5648 if (newheight != FRAME_LINES (f))
5650 resize_frame_windows (f, newheight, 0);
5652 /* MSDOS frames cannot PRETEND, as they change frame size by
5653 manipulating video hardware. */
5654 if ((FRAME_TERMCAP_P (f) && !pretend) || FRAME_MSDOS_P (f))
5655 FrameRows (FRAME_TTY (f)) = newheight;
5658 if (new_frame_total_cols != FRAME_TOTAL_COLS (f))
5660 resize_frame_windows (f, new_frame_total_cols, 1);
5662 /* MSDOS frames cannot PRETEND, as they change frame size by
5663 manipulating video hardware. */
5664 if ((FRAME_TERMCAP_P (f) && !pretend) || FRAME_MSDOS_P (f))
5665 FrameCols (FRAME_TTY (f)) = newwidth;
5667 if (WINDOWP (f->tool_bar_window))
5668 wset_total_cols (XWINDOW (f->tool_bar_window), make_number (newwidth));
5671 FRAME_LINES (f) = newheight;
5672 SET_FRAME_COLS (f, newwidth);
5675 struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
5676 int text_area_x, text_area_y, text_area_width, text_area_height;
5678 window_box (w, TEXT_AREA, &text_area_x, &text_area_y, &text_area_width,
5679 &text_area_height);
5680 if (w->cursor.x >= text_area_x + text_area_width)
5681 w->cursor.hpos = w->cursor.x = 0;
5682 if (w->cursor.y >= text_area_y + text_area_height)
5683 w->cursor.vpos = w->cursor.y = 0;
5686 adjust_glyphs (f);
5687 calculate_costs (f);
5688 SET_FRAME_GARBAGED (f);
5689 f->resized_p = 1;
5691 unblock_input ();
5693 record_unwind_current_buffer ();
5695 run_window_configuration_change_hook (f);
5697 unbind_to (count, Qnil);
5702 /***********************************************************************
5703 Terminal Related Lisp Functions
5704 ***********************************************************************/
5706 DEFUN ("open-termscript", Fopen_termscript, Sopen_termscript,
5707 1, 1, "FOpen termscript file: ",
5708 doc: /* Start writing all terminal output to FILE as well as the terminal.
5709 FILE = nil means just close any termscript file currently open. */)
5710 (Lisp_Object file)
5712 struct tty_display_info *tty;
5714 if (! FRAME_TERMCAP_P (SELECTED_FRAME ())
5715 && ! FRAME_MSDOS_P (SELECTED_FRAME ()))
5716 error ("Current frame is not on a tty device");
5718 tty = CURTTY ();
5720 if (tty->termscript != 0)
5722 block_input ();
5723 fclose (tty->termscript);
5724 unblock_input ();
5726 tty->termscript = 0;
5728 if (! NILP (file))
5730 file = Fexpand_file_name (file, Qnil);
5731 tty->termscript = fopen (SSDATA (file), "w");
5732 if (tty->termscript == 0)
5733 report_file_error ("Opening termscript", Fcons (file, Qnil));
5735 return Qnil;
5739 DEFUN ("send-string-to-terminal", Fsend_string_to_terminal,
5740 Ssend_string_to_terminal, 1, 2, 0,
5741 doc: /* Send STRING to the terminal without alteration.
5742 Control characters in STRING will have terminal-dependent effects.
5744 Optional parameter TERMINAL specifies the tty terminal device to use.
5745 It may be a terminal object, a frame, or nil for the terminal used by
5746 the currently selected frame. In batch mode, STRING is sent to stdout
5747 when TERMINAL is nil. */)
5748 (Lisp_Object string, Lisp_Object terminal)
5750 struct terminal *t = get_terminal (terminal, 1);
5751 FILE *out;
5753 /* ??? Perhaps we should do something special for multibyte strings here. */
5754 CHECK_STRING (string);
5755 block_input ();
5757 if (!t)
5758 error ("Unknown terminal device");
5760 if (t->type == output_initial)
5761 out = stdout;
5762 else if (t->type != output_termcap && t->type != output_msdos_raw)
5763 error ("Device %d is not a termcap terminal device", t->id);
5764 else
5766 struct tty_display_info *tty = t->display_info.tty;
5768 if (! tty->output)
5769 error ("Terminal is currently suspended");
5771 if (tty->termscript)
5773 fwrite (SDATA (string), 1, SBYTES (string), tty->termscript);
5774 fflush (tty->termscript);
5776 out = tty->output;
5778 fwrite (SDATA (string), 1, SBYTES (string), out);
5779 fflush (out);
5780 unblock_input ();
5781 return Qnil;
5785 DEFUN ("ding", Fding, Sding, 0, 1, 0,
5786 doc: /* Beep, or flash the screen.
5787 Also, unless an argument is given,
5788 terminate any keyboard macro currently executing. */)
5789 (Lisp_Object arg)
5791 if (!NILP (arg))
5793 if (noninteractive)
5794 putchar (07);
5795 else
5796 ring_bell (XFRAME (selected_frame));
5798 else
5799 bitch_at_user ();
5801 return Qnil;
5804 void
5805 bitch_at_user (void)
5807 if (noninteractive)
5808 putchar (07);
5809 else if (!INTERACTIVE) /* Stop executing a keyboard macro. */
5810 error ("Keyboard macro terminated by a command ringing the bell");
5811 else
5812 ring_bell (XFRAME (selected_frame));
5817 /***********************************************************************
5818 Sleeping, Waiting
5819 ***********************************************************************/
5821 DEFUN ("sleep-for", Fsleep_for, Ssleep_for, 1, 2, 0,
5822 doc: /* Pause, without updating display, for SECONDS seconds.
5823 SECONDS may be a floating-point value, meaning that you can wait for a
5824 fraction of a second. Optional second arg MILLISECONDS specifies an
5825 additional wait period, in milliseconds; this is for backwards compatibility.
5826 \(Not all operating systems support waiting for a fraction of a second.) */)
5827 (Lisp_Object seconds, Lisp_Object milliseconds)
5829 double duration = extract_float (seconds);
5831 if (!NILP (milliseconds))
5833 CHECK_NUMBER (milliseconds);
5834 duration += XINT (milliseconds) / 1000.0;
5837 if (0 < duration)
5839 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (duration);
5840 wait_reading_process_output (min (EMACS_SECS (t), WAIT_READING_MAX),
5841 EMACS_NSECS (t), 0, 0, Qnil, NULL, 0);
5844 return Qnil;
5848 /* This is just like wait_reading_process_output, except that
5849 it does redisplay.
5851 TIMEOUT is number of seconds to wait (float or integer),
5852 or t to wait forever.
5853 READING is true if reading input.
5854 If DISPLAY_OPTION is >0 display process output while waiting.
5855 If DISPLAY_OPTION is >1 perform an initial redisplay before waiting.
5858 Lisp_Object
5859 sit_for (Lisp_Object timeout, bool reading, int display_option)
5861 intmax_t sec;
5862 int nsec;
5863 bool do_display = display_option > 0;
5865 swallow_events (do_display);
5867 if ((detect_input_pending_run_timers (do_display))
5868 || !NILP (Vexecuting_kbd_macro))
5869 return Qnil;
5871 if (display_option > 1)
5872 redisplay_preserve_echo_area (2);
5874 if (INTEGERP (timeout))
5876 sec = XINT (timeout);
5877 if (! (0 < sec))
5878 return Qt;
5879 nsec = 0;
5881 else if (FLOATP (timeout))
5883 double seconds = XFLOAT_DATA (timeout);
5884 if (! (0 < seconds))
5885 return Qt;
5886 else
5888 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (seconds);
5889 sec = min (EMACS_SECS (t), WAIT_READING_MAX);
5890 nsec = EMACS_NSECS (t);
5893 else if (EQ (timeout, Qt))
5895 sec = 0;
5896 nsec = 0;
5898 else
5899 wrong_type_argument (Qnumberp, timeout);
5902 #ifdef USABLE_SIGIO
5903 gobble_input ();
5904 #endif
5906 wait_reading_process_output (sec, nsec, reading ? -1 : 1, do_display,
5907 Qnil, NULL, 0);
5909 return detect_input_pending () ? Qnil : Qt;
5913 DEFUN ("redisplay", Fredisplay, Sredisplay, 0, 1, 0,
5914 doc: /* Perform redisplay.
5915 Optional arg FORCE, if non-nil, prevents redisplay from being
5916 preempted by arriving input, even if `redisplay-dont-pause' is nil.
5917 If `redisplay-dont-pause' is non-nil (the default), redisplay is never
5918 preempted by arriving input, so FORCE does nothing.
5920 Return t if redisplay was performed, nil if redisplay was preempted
5921 immediately by pending input. */)
5922 (Lisp_Object force)
5924 ptrdiff_t count;
5926 swallow_events (1);
5927 if ((detect_input_pending_run_timers (1)
5928 && NILP (force) && !redisplay_dont_pause)
5929 || !NILP (Vexecuting_kbd_macro))
5930 return Qnil;
5932 count = SPECPDL_INDEX ();
5933 if (!NILP (force) && !redisplay_dont_pause)
5934 specbind (Qredisplay_dont_pause, Qt);
5935 redisplay_preserve_echo_area (2);
5936 unbind_to (count, Qnil);
5937 return Qt;
5942 /***********************************************************************
5943 Other Lisp Functions
5944 ***********************************************************************/
5946 /* A vector of size >= 2 * NFRAMES + 3 * NBUFFERS + 1, containing the
5947 session's frames, frame names, buffers, buffer-read-only flags, and
5948 buffer-modified-flags. */
5950 static Lisp_Object frame_and_buffer_state;
5953 DEFUN ("frame-or-buffer-changed-p", Fframe_or_buffer_changed_p,
5954 Sframe_or_buffer_changed_p, 0, 1, 0,
5955 doc: /* Return non-nil if the frame and buffer state appears to have changed.
5956 VARIABLE is a variable name whose value is either nil or a state vector
5957 that will be updated to contain all frames and buffers,
5958 aside from buffers whose names start with space,
5959 along with the buffers' read-only and modified flags. This allows a fast
5960 check to see whether buffer menus might need to be recomputed.
5961 If this function returns non-nil, it updates the internal vector to reflect
5962 the current state.
5964 If VARIABLE is nil, an internal variable is used. Users should not
5965 pass nil for VARIABLE. */)
5966 (Lisp_Object variable)
5968 Lisp_Object state, tail, frame, buf;
5969 ptrdiff_t n, idx;
5971 if (! NILP (variable))
5973 CHECK_SYMBOL (variable);
5974 state = Fsymbol_value (variable);
5975 if (! VECTORP (state))
5976 goto changed;
5978 else
5979 state = frame_and_buffer_state;
5981 idx = 0;
5982 FOR_EACH_FRAME (tail, frame)
5984 if (idx == ASIZE (state))
5985 goto changed;
5986 if (!EQ (AREF (state, idx++), frame))
5987 goto changed;
5988 if (idx == ASIZE (state))
5989 goto changed;
5990 if (!EQ (AREF (state, idx++), XFRAME (frame)->name))
5991 goto changed;
5993 /* Check that the buffer info matches. */
5994 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
5996 buf = XCDR (XCAR (tail));
5997 /* Ignore buffers that aren't included in buffer lists. */
5998 if (SREF (BVAR (XBUFFER (buf), name), 0) == ' ')
5999 continue;
6000 if (idx == ASIZE (state))
6001 goto changed;
6002 if (!EQ (AREF (state, idx++), buf))
6003 goto changed;
6004 if (idx == ASIZE (state))
6005 goto changed;
6006 if (!EQ (AREF (state, idx++), BVAR (XBUFFER (buf), read_only)))
6007 goto changed;
6008 if (idx == ASIZE (state))
6009 goto changed;
6010 if (!EQ (AREF (state, idx++), Fbuffer_modified_p (buf)))
6011 goto changed;
6013 if (idx == ASIZE (state))
6014 goto changed;
6015 /* Detect deletion of a buffer at the end of the list. */
6016 if (EQ (AREF (state, idx), Qlambda))
6017 return Qnil;
6019 /* Come here if we decide the data has changed. */
6020 changed:
6021 /* Count the size we will need.
6022 Start with 1 so there is room for at least one lambda at the end. */
6023 n = 1;
6024 FOR_EACH_FRAME (tail, frame)
6025 n += 2;
6026 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
6027 n += 3;
6028 /* Reallocate the vector if data has grown to need it,
6029 or if it has shrunk a lot. */
6030 if (! VECTORP (state)
6031 || n > ASIZE (state)
6032 || n + 20 < ASIZE (state) / 2)
6033 /* Add 20 extra so we grow it less often. */
6035 state = Fmake_vector (make_number (n + 20), Qlambda);
6036 if (! NILP (variable))
6037 Fset (variable, state);
6038 else
6039 frame_and_buffer_state = state;
6042 /* Record the new data in the (possibly reallocated) vector. */
6043 idx = 0;
6044 FOR_EACH_FRAME (tail, frame)
6046 ASET (state, idx, frame);
6047 idx++;
6048 ASET (state, idx, XFRAME (frame)->name);
6049 idx++;
6051 for (tail = Vbuffer_alist; CONSP (tail); tail = XCDR (tail))
6053 buf = XCDR (XCAR (tail));
6054 /* Ignore buffers that aren't included in buffer lists. */
6055 if (SREF (BVAR (XBUFFER (buf), name), 0) == ' ')
6056 continue;
6057 ASET (state, idx, buf);
6058 idx++;
6059 ASET (state, idx, BVAR (XBUFFER (buf), read_only));
6060 idx++;
6061 ASET (state, idx, Fbuffer_modified_p (buf));
6062 idx++;
6064 /* Fill up the vector with lambdas (always at least one). */
6065 ASET (state, idx, Qlambda);
6066 idx++;
6067 while (idx < ASIZE (state))
6069 ASET (state, idx, Qlambda);
6070 idx++;
6072 /* Make sure we didn't overflow the vector. */
6073 eassert (idx <= ASIZE (state));
6074 return Qt;
6079 /***********************************************************************
6080 Initialization
6081 ***********************************************************************/
6083 /* Initialization done when Emacs fork is started, before doing stty.
6084 Determine terminal type and set terminal_driver. Then invoke its
6085 decoding routine to set up variables in the terminal package. */
6087 void
6088 init_display (void)
6090 char *terminal_type;
6092 /* Construct the space glyph. */
6093 space_glyph.type = CHAR_GLYPH;
6094 SET_CHAR_GLYPH (space_glyph, ' ', DEFAULT_FACE_ID, 0);
6095 space_glyph.charpos = -1;
6097 inverse_video = 0;
6098 cursor_in_echo_area = 0;
6099 terminal_type = (char *) 0;
6101 /* Now is the time to initialize this; it's used by init_sys_modes
6102 during startup. */
6103 Vinitial_window_system = Qnil;
6105 /* SIGWINCH needs to be handled no matter what display we start
6106 with. Otherwise newly opened tty frames will not resize
6107 automatically. */
6108 #ifdef SIGWINCH
6109 #ifndef CANNOT_DUMP
6110 if (initialized)
6111 #endif /* CANNOT_DUMP */
6113 struct sigaction action;
6114 emacs_sigaction_init (&action, deliver_window_change_signal);
6115 sigaction (SIGWINCH, &action, 0);
6117 #endif /* SIGWINCH */
6119 /* If running as a daemon, no need to initialize any frames/terminal. */
6120 if (IS_DAEMON)
6121 return;
6123 /* If the user wants to use a window system, we shouldn't bother
6124 initializing the terminal. This is especially important when the
6125 terminal is so dumb that emacs gives up before and doesn't bother
6126 using the window system.
6128 If the DISPLAY environment variable is set and nonempty,
6129 try to use X, and die with an error message if that doesn't work. */
6131 #ifdef HAVE_X_WINDOWS
6132 if (! inhibit_window_system && ! display_arg)
6134 char *display;
6135 display = getenv ("DISPLAY");
6136 display_arg = (display != 0 && *display != 0);
6138 if (display_arg && !x_display_ok (display))
6140 fprintf (stderr, "Display %s unavailable, simulating -nw\n",
6141 display);
6142 inhibit_window_system = 1;
6146 if (!inhibit_window_system && display_arg)
6148 Vinitial_window_system = Qx;
6149 #ifdef HAVE_X11
6150 Vwindow_system_version = make_number (11);
6151 #endif
6152 #ifdef GNU_LINUX
6153 /* In some versions of ncurses,
6154 tputs crashes if we have not called tgetent.
6155 So call tgetent. */
6156 { char b[2044]; tgetent (b, "xterm");}
6157 #endif
6158 return;
6160 #endif /* HAVE_X_WINDOWS */
6162 #ifdef HAVE_NTGUI
6163 if (!inhibit_window_system)
6165 Vinitial_window_system = Qw32;
6166 Vwindow_system_version = make_number (1);
6167 return;
6169 #endif /* HAVE_NTGUI */
6171 #ifdef HAVE_NS
6172 if (!inhibit_window_system
6173 #ifndef CANNOT_DUMP
6174 && initialized
6175 #endif
6178 Vinitial_window_system = Qns;
6179 Vwindow_system_version = make_number (10);
6180 return;
6182 #endif
6184 /* If no window system has been specified, try to use the terminal. */
6185 if (! isatty (0))
6187 fatal ("standard input is not a tty");
6188 exit (1);
6191 #ifdef WINDOWSNT
6192 terminal_type = "w32console";
6193 #else
6194 /* Look at the TERM variable. */
6195 terminal_type = (char *) getenv ("TERM");
6196 #endif
6197 if (!terminal_type)
6199 #ifdef HAVE_WINDOW_SYSTEM
6200 if (! inhibit_window_system)
6201 fprintf (stderr, "Please set the environment variable DISPLAY or TERM (see `tset').\n");
6202 else
6203 #endif /* HAVE_WINDOW_SYSTEM */
6204 fprintf (stderr, "Please set the environment variable TERM; see `tset'.\n");
6205 exit (1);
6209 struct terminal *t;
6210 struct frame *f = XFRAME (selected_frame);
6212 init_foreground_group ();
6214 /* Open a display on the controlling tty. */
6215 t = init_tty (0, terminal_type, 1); /* Errors are fatal. */
6217 /* Convert the initial frame to use the new display. */
6218 if (f->output_method != output_initial)
6219 emacs_abort ();
6220 f->output_method = t->type;
6221 f->terminal = t;
6223 t->reference_count++;
6224 #ifdef MSDOS
6225 f->output_data.tty->display_info = &the_only_display_info;
6226 #else
6227 if (f->output_method == output_termcap)
6228 create_tty_output (f);
6229 #endif
6230 t->display_info.tty->top_frame = selected_frame;
6231 change_frame_size (XFRAME (selected_frame),
6232 FrameRows (t->display_info.tty),
6233 FrameCols (t->display_info.tty), 0, 0, 1);
6235 /* Delete the initial terminal. */
6236 if (--initial_terminal->reference_count == 0
6237 && initial_terminal->delete_terminal_hook)
6238 (*initial_terminal->delete_terminal_hook) (initial_terminal);
6240 /* Update frame parameters to reflect the new type. */
6241 Fmodify_frame_parameters
6242 (selected_frame, Fcons (Fcons (Qtty_type,
6243 Ftty_type (selected_frame)), Qnil));
6244 if (t->display_info.tty->name)
6245 Fmodify_frame_parameters (selected_frame,
6246 Fcons (Fcons (Qtty, build_string (t->display_info.tty->name)),
6247 Qnil));
6248 else
6249 Fmodify_frame_parameters (selected_frame, Fcons (Fcons (Qtty, Qnil),
6250 Qnil));
6254 struct frame *sf = SELECTED_FRAME ();
6255 int width = FRAME_TOTAL_COLS (sf);
6256 int height = FRAME_LINES (sf);
6258 /* If these sizes are so big they cause overflow, just ignore the
6259 change. It's not clear what better we could do. The rest of
6260 the code assumes that (width + 2) * height * sizeof (struct glyph)
6261 does not overflow and does not exceed PTRDIFF_MAX or SIZE_MAX. */
6262 if (INT_ADD_RANGE_OVERFLOW (width, 2, INT_MIN, INT_MAX)
6263 || INT_MULTIPLY_RANGE_OVERFLOW (width + 2, height, INT_MIN, INT_MAX)
6264 || (min (PTRDIFF_MAX, SIZE_MAX) / sizeof (struct glyph)
6265 < (width + 2) * height))
6266 fatal ("screen size %dx%d too big", width, height);
6269 calculate_costs (XFRAME (selected_frame));
6271 /* Set up faces of the initial terminal frame of a dumped Emacs. */
6272 if (initialized
6273 && !noninteractive
6274 && NILP (Vinitial_window_system))
6276 /* For the initial frame, we don't have any way of knowing what
6277 are the foreground and background colors of the terminal. */
6278 struct frame *sf = SELECTED_FRAME ();
6280 FRAME_FOREGROUND_PIXEL (sf) = FACE_TTY_DEFAULT_FG_COLOR;
6281 FRAME_BACKGROUND_PIXEL (sf) = FACE_TTY_DEFAULT_BG_COLOR;
6282 call0 (intern ("tty-set-up-initial-frame-faces"));
6288 /***********************************************************************
6289 Blinking cursor
6290 ***********************************************************************/
6292 DEFUN ("internal-show-cursor", Finternal_show_cursor,
6293 Sinternal_show_cursor, 2, 2, 0,
6294 doc: /* Set the cursor-visibility flag of WINDOW to SHOW.
6295 WINDOW nil means use the selected window. SHOW non-nil means
6296 show a cursor in WINDOW in the next redisplay. SHOW nil means
6297 don't show a cursor. */)
6298 (Lisp_Object window, Lisp_Object show)
6300 /* Don't change cursor state while redisplaying. This could confuse
6301 output routines. */
6302 if (!redisplaying_p)
6303 decode_any_window (window)->cursor_off_p = NILP (show);
6304 return Qnil;
6308 DEFUN ("internal-show-cursor-p", Finternal_show_cursor_p,
6309 Sinternal_show_cursor_p, 0, 1, 0,
6310 doc: /* Value is non-nil if next redisplay will display a cursor in WINDOW.
6311 WINDOW nil or omitted means report on the selected window. */)
6312 (Lisp_Object window)
6314 return decode_any_window (window)->cursor_off_p ? Qnil : Qt;
6317 DEFUN ("last-nonminibuffer-frame", Flast_nonminibuf_frame,
6318 Slast_nonminibuf_frame, 0, 0, 0,
6319 doc: /* Value is last nonminibuffer frame. */)
6320 (void)
6322 Lisp_Object frame = Qnil;
6324 if (last_nonminibuf_frame)
6325 XSETFRAME (frame, last_nonminibuf_frame);
6327 return frame;
6330 /***********************************************************************
6331 Initialization
6332 ***********************************************************************/
6334 void
6335 syms_of_display (void)
6337 defsubr (&Sredraw_frame);
6338 defsubr (&Sredraw_display);
6339 defsubr (&Sframe_or_buffer_changed_p);
6340 defsubr (&Sopen_termscript);
6341 defsubr (&Sding);
6342 defsubr (&Sredisplay);
6343 defsubr (&Ssleep_for);
6344 defsubr (&Ssend_string_to_terminal);
6345 defsubr (&Sinternal_show_cursor);
6346 defsubr (&Sinternal_show_cursor_p);
6347 defsubr (&Slast_nonminibuf_frame);
6349 #ifdef GLYPH_DEBUG
6350 defsubr (&Sdump_redisplay_history);
6351 #endif
6353 frame_and_buffer_state = Fmake_vector (make_number (20), Qlambda);
6354 staticpro (&frame_and_buffer_state);
6356 DEFSYM (Qdisplay_table, "display-table");
6357 DEFSYM (Qredisplay_dont_pause, "redisplay-dont-pause");
6359 DEFVAR_INT ("baud-rate", baud_rate,
6360 doc: /* The output baud rate of the terminal.
6361 On most systems, changing this value will affect the amount of padding
6362 and the other strategic decisions made during redisplay. */);
6364 DEFVAR_BOOL ("inverse-video", inverse_video,
6365 doc: /* Non-nil means invert the entire frame display.
6366 This means everything is in inverse video which otherwise would not be. */);
6368 DEFVAR_BOOL ("visible-bell", visible_bell,
6369 doc: /* Non-nil means try to flash the frame to represent a bell.
6371 See also `ring-bell-function'. */);
6373 DEFVAR_BOOL ("no-redraw-on-reenter", no_redraw_on_reenter,
6374 doc: /* Non-nil means no need to redraw entire frame after suspending.
6375 A non-nil value is useful if the terminal can automatically preserve
6376 Emacs's frame display when you reenter Emacs.
6377 It is up to you to set this variable if your terminal can do that. */);
6379 DEFVAR_LISP ("initial-window-system", Vinitial_window_system,
6380 doc: /* Name of the window system that Emacs uses for the first frame.
6381 The value is a symbol:
6382 nil for a termcap frame (a character-only terminal),
6383 'x' for an Emacs frame that is really an X window,
6384 'w32' for an Emacs frame that is a window on MS-Windows display,
6385 'ns' for an Emacs frame on a GNUstep or Macintosh Cocoa display,
6386 'pc' for a direct-write MS-DOS frame.
6388 Use of this variable as a boolean is deprecated. Instead,
6389 use `display-graphic-p' or any of the other `display-*-p'
6390 predicates which report frame's specific UI-related capabilities. */);
6392 DEFVAR_KBOARD ("window-system", Vwindow_system,
6393 doc: /* Name of window system through which the selected frame is displayed.
6394 The value is a symbol:
6395 nil for a termcap frame (a character-only terminal),
6396 'x' for an Emacs frame that is really an X window,
6397 'w32' for an Emacs frame that is a window on MS-Windows display,
6398 'ns' for an Emacs frame on a GNUstep or Macintosh Cocoa display,
6399 'pc' for a direct-write MS-DOS frame.
6401 Use of this variable as a boolean is deprecated. Instead,
6402 use `display-graphic-p' or any of the other `display-*-p'
6403 predicates which report frame's specific UI-related capabilities. */);
6405 DEFVAR_LISP ("window-system-version", Vwindow_system_version,
6406 doc: /* The version number of the window system in use.
6407 For X windows, this is 11. */);
6409 DEFVAR_BOOL ("cursor-in-echo-area", cursor_in_echo_area,
6410 doc: /* Non-nil means put cursor in minibuffer, at end of any message there. */);
6412 DEFVAR_LISP ("glyph-table", Vglyph_table,
6413 doc: /* Table defining how to output a glyph code to the frame.
6414 If not nil, this is a vector indexed by glyph code to define the glyph.
6415 Each element can be:
6416 integer: a glyph code which this glyph is an alias for.
6417 string: output this glyph using that string (not impl. in X windows).
6418 nil: this glyph mod 524288 is the code of a character to output,
6419 and this glyph / 524288 is the face number (see `face-id') to use
6420 while outputting it. */);
6421 Vglyph_table = Qnil;
6423 DEFVAR_LISP ("standard-display-table", Vstandard_display_table,
6424 doc: /* Display table to use for buffers that specify none.
6425 See `buffer-display-table' for more information. */);
6426 Vstandard_display_table = Qnil;
6428 DEFVAR_BOOL ("redisplay-dont-pause", redisplay_dont_pause,
6429 doc: /* Non-nil means display update isn't paused when input is detected. */);
6430 redisplay_dont_pause = 1;
6432 #if PERIODIC_PREEMPTION_CHECKING
6433 DEFVAR_LISP ("redisplay-preemption-period", Vredisplay_preemption_period,
6434 doc: /* Period in seconds between checking for input during redisplay.
6435 This has an effect only if `redisplay-dont-pause' is nil; in that
6436 case, arriving input preempts redisplay until the input is processed.
6437 If the value is nil, redisplay is never preempted. */);
6438 Vredisplay_preemption_period = make_float (0.10);
6439 #endif
6441 #ifdef CANNOT_DUMP
6442 if (noninteractive)
6443 #endif
6445 Vinitial_window_system = Qnil;
6446 Vwindow_system_version = Qnil;