xref: /vim-8.2.3635/src/screen.c (revision 28ee892a)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * screen.c: Lower level code for displaying on the screen.
12  *
13  * Output to the screen (console, terminal emulator or GUI window) is minimized
14  * by remembering what is already on the screen, and only updating the parts
15  * that changed.
16  *
17  * ScreenLines[off]  Contains a copy of the whole screen, as it is currently
18  *		     displayed (excluding text written by external commands).
19  * ScreenAttrs[off]  Contains the associated attributes.
20  * LineOffset[row]   Contains the offset into ScreenLines*[] and ScreenAttrs[]
21  *		     for each line.
22  * LineWraps[row]    Flag for each line whether it wraps to the next line.
23  *
24  * For double-byte characters, two consecutive bytes in ScreenLines[] can form
25  * one character which occupies two display cells.
26  * For UTF-8 a multi-byte character is converted to Unicode and stored in
27  * ScreenLinesUC[].  ScreenLines[] contains the first byte only.  For an ASCII
28  * character without composing chars ScreenLinesUC[] will be 0 and
29  * ScreenLinesC[][] is not used.  When the character occupies two display
30  * cells the next byte in ScreenLines[] is 0.
31  * ScreenLinesC[][] contain up to 'maxcombine' composing characters
32  * (drawn on top of the first character).  There is 0 after the last one used.
33  * ScreenLines2[] is only used for euc-jp to store the second byte if the
34  * first byte is 0x8e (single-width character).
35  *
36  * The screen_*() functions write to the screen and handle updating
37  * ScreenLines[].
38  */
39 
40 #include "vim.h"
41 
42 /*
43  * The attributes that are actually active for writing to the screen.
44  */
45 static int	screen_attr = 0;
46 
47 static void screen_char_2(unsigned off, int row, int col);
48 static void screenclear2(void);
49 static void lineclear(unsigned off, int width, int attr);
50 static void lineinvalid(unsigned off, int width);
51 static int win_do_lines(win_T *wp, int row, int line_count, int mayclear, int del, int clear_attr);
52 static void win_rest_invalid(win_T *wp);
53 static void msg_pos_mode(void);
54 static void recording_mode(int attr);
55 
56 // Ugly global: overrule attribute used by screen_char()
57 static int screen_char_attr = 0;
58 
59 #if defined(FEAT_CONCEAL) || defined(PROTO)
60 /*
61  * Return TRUE if the cursor line in window "wp" may be concealed, according
62  * to the 'concealcursor' option.
63  */
64     int
65 conceal_cursor_line(win_T *wp)
66 {
67     int		c;
68 
69     if (*wp->w_p_cocu == NUL)
70 	return FALSE;
71     if (get_real_state() & VISUAL)
72 	c = 'v';
73     else if (State & INSERT)
74 	c = 'i';
75     else if (State & NORMAL)
76 	c = 'n';
77     else if (State & CMDLINE)
78 	c = 'c';
79     else
80 	return FALSE;
81     return vim_strchr(wp->w_p_cocu, c) != NULL;
82 }
83 
84 /*
85  * Check if the cursor line needs to be redrawn because of 'concealcursor'.
86  */
87     void
88 conceal_check_cursor_line(void)
89 {
90     if (curwin->w_p_cole > 0 && conceal_cursor_line(curwin))
91     {
92 	need_cursor_line_redraw = TRUE;
93 	// Need to recompute cursor column, e.g., when starting Visual mode
94 	// without concealing.
95 	curs_columns(TRUE);
96     }
97 }
98 #endif
99 
100 /*
101  * Get 'wincolor' attribute for window "wp".  If not set and "wp" is a popup
102  * window then get the "Pmenu" highlight attribute.
103  */
104     int
105 get_wcr_attr(win_T *wp)
106 {
107     int wcr_attr = 0;
108 
109     if (*wp->w_p_wcr != NUL)
110 	wcr_attr = syn_name2attr(wp->w_p_wcr);
111 #ifdef FEAT_PROP_POPUP
112     else if (WIN_IS_POPUP(wp))
113     {
114 	if (wp->w_popup_flags & POPF_INFO)
115 	    wcr_attr = HL_ATTR(HLF_PSI);    // PmenuSel
116 	else
117 	    wcr_attr = HL_ATTR(HLF_PNI);    // Pmenu
118     }
119 #endif
120     return wcr_attr;
121 }
122 
123 /*
124  * Call screen_fill() with the columns adjusted for 'rightleft' if needed.
125  * Return the new offset.
126  */
127     static int
128 screen_fill_end(
129 	win_T *wp,
130 	int	c1,
131 	int	c2,
132 	int	off,
133 	int	width,
134 	int	row,
135 	int	endrow,
136 	int	attr)
137 {
138     int	    nn = off + width;
139 
140     if (nn > wp->w_width)
141 	nn = wp->w_width;
142 #ifdef FEAT_RIGHTLEFT
143     if (wp->w_p_rl)
144     {
145 	screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
146 		W_ENDCOL(wp) - nn, (int)W_ENDCOL(wp) - off,
147 		c1, c2, attr);
148     }
149     else
150 #endif
151 	screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
152 		wp->w_wincol + off, (int)wp->w_wincol + nn,
153 		c1, c2, attr);
154     return nn;
155 }
156 
157 /*
158  * Clear lines near the end the window and mark the unused lines with "c1".
159  * use "c2" as the filler character.
160  * When "draw_margin" is TRUE then draw the sign, fold and number columns.
161  */
162     void
163 win_draw_end(
164     win_T	*wp,
165     int		c1,
166     int		c2,
167     int		draw_margin,
168     int		row,
169     int		endrow,
170     hlf_T	hl)
171 {
172     int		n = 0;
173     int		attr = HL_ATTR(hl);
174     int		wcr_attr = get_wcr_attr(wp);
175 
176     attr = hl_combine_attr(wcr_attr, attr);
177 
178     if (draw_margin)
179     {
180 #ifdef FEAT_FOLDING
181 	int	fdc = compute_foldcolumn(wp, 0);
182 
183 	if (fdc > 0)
184 	    // draw the fold column
185 	    n = screen_fill_end(wp, ' ', ' ', n, fdc,
186 		      row, endrow, hl_combine_attr(wcr_attr, HL_ATTR(HLF_FC)));
187 #endif
188 #ifdef FEAT_SIGNS
189 	if (signcolumn_on(wp))
190 	    // draw the sign column
191 	    n = screen_fill_end(wp, ' ', ' ', n, 2,
192 		      row, endrow, hl_combine_attr(wcr_attr, HL_ATTR(HLF_SC)));
193 #endif
194 	if ((wp->w_p_nu || wp->w_p_rnu)
195 				  && vim_strchr(p_cpo, CPO_NUMCOL) == NULL)
196 	    // draw the number column
197 	    n = screen_fill_end(wp, ' ', ' ', n, number_width(wp) + 1,
198 		       row, endrow, hl_combine_attr(wcr_attr, HL_ATTR(HLF_N)));
199     }
200 
201 #ifdef FEAT_RIGHTLEFT
202     if (wp->w_p_rl)
203     {
204 	screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
205 		wp->w_wincol, W_ENDCOL(wp) - 1 - n,
206 		c2, c2, attr);
207 	screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
208 		W_ENDCOL(wp) - 1 - n, W_ENDCOL(wp) - n,
209 		c1, c2, attr);
210     }
211     else
212 #endif
213     {
214 	screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
215 		wp->w_wincol + n, (int)W_ENDCOL(wp),
216 		c1, c2, attr);
217     }
218 
219     set_empty_rows(wp, row);
220 }
221 
222 #if defined(FEAT_FOLDING) || defined(PROTO)
223 /*
224  * Compute the width of the foldcolumn.  Based on 'foldcolumn' and how much
225  * space is available for window "wp", minus "col".
226  */
227     int
228 compute_foldcolumn(win_T *wp, int col)
229 {
230     int fdc = wp->w_p_fdc;
231     int wmw = wp == curwin && p_wmw == 0 ? 1 : p_wmw;
232     int wwidth = wp->w_width;
233 
234     if (fdc > wwidth - (col + wmw))
235 	fdc = wwidth - (col + wmw);
236     return fdc;
237 }
238 
239 /*
240  * Fill the foldcolumn at "p" for window "wp".
241  * Only to be called when 'foldcolumn' > 0.
242  */
243     void
244 fill_foldcolumn(
245     char_u	*p,
246     win_T	*wp,
247     int		closed,		// TRUE of FALSE
248     linenr_T	lnum)		// current line number
249 {
250     int		i = 0;
251     int		level;
252     int		first_level;
253     int		empty;
254     int		fdc = compute_foldcolumn(wp, 0);
255 
256     // Init to all spaces.
257     vim_memset(p, ' ', (size_t)fdc);
258 
259     level = win_foldinfo.fi_level;
260     if (level > 0)
261     {
262 	// If there is only one column put more info in it.
263 	empty = (fdc == 1) ? 0 : 1;
264 
265 	// If the column is too narrow, we start at the lowest level that
266 	// fits and use numbers to indicated the depth.
267 	first_level = level - fdc - closed + 1 + empty;
268 	if (first_level < 1)
269 	    first_level = 1;
270 
271 	for (i = 0; i + empty < fdc; ++i)
272 	{
273 	    if (win_foldinfo.fi_lnum == lnum
274 			      && first_level + i >= win_foldinfo.fi_low_level)
275 		p[i] = '-';
276 	    else if (first_level == 1)
277 		p[i] = '|';
278 	    else if (first_level + i <= 9)
279 		p[i] = '0' + first_level + i;
280 	    else
281 		p[i] = '>';
282 	    if (first_level + i == level)
283 		break;
284 	}
285     }
286     if (closed)
287 	p[i >= fdc ? i - 1 : i] = '+';
288 }
289 #endif // FEAT_FOLDING
290 
291 /*
292  * Return if the composing characters at "off_from" and "off_to" differ.
293  * Only to be used when ScreenLinesUC[off_from] != 0.
294  */
295     static int
296 comp_char_differs(int off_from, int off_to)
297 {
298     int	    i;
299 
300     for (i = 0; i < Screen_mco; ++i)
301     {
302 	if (ScreenLinesC[i][off_from] != ScreenLinesC[i][off_to])
303 	    return TRUE;
304 	if (ScreenLinesC[i][off_from] == 0)
305 	    break;
306     }
307     return FALSE;
308 }
309 
310 /*
311  * Check whether the given character needs redrawing:
312  * - the (first byte of the) character is different
313  * - the attributes are different
314  * - the character is multi-byte and the next byte is different
315  * - the character is two cells wide and the second cell differs.
316  */
317     static int
318 char_needs_redraw(int off_from, int off_to, int cols)
319 {
320     if (cols > 0
321 	    && ((ScreenLines[off_from] != ScreenLines[off_to]
322 		    || ScreenAttrs[off_from] != ScreenAttrs[off_to])
323 		|| (enc_dbcs != 0
324 		    && MB_BYTE2LEN(ScreenLines[off_from]) > 1
325 		    && (enc_dbcs == DBCS_JPNU && ScreenLines[off_from] == 0x8e
326 			? ScreenLines2[off_from] != ScreenLines2[off_to]
327 			: (cols > 1 && ScreenLines[off_from + 1]
328 						 != ScreenLines[off_to + 1])))
329 		|| (enc_utf8
330 		    && (ScreenLinesUC[off_from] != ScreenLinesUC[off_to]
331 			|| (ScreenLinesUC[off_from] != 0
332 			    && comp_char_differs(off_from, off_to))
333 			|| ((*mb_off2cells)(off_from, off_from + cols) > 1
334 			    && ScreenLines[off_from + 1]
335 						!= ScreenLines[off_to + 1])))))
336 	return TRUE;
337     return FALSE;
338 }
339 
340 #if defined(FEAT_TERMINAL) || defined(PROTO)
341 /*
342  * Return the index in ScreenLines[] for the current screen line.
343  */
344     int
345 screen_get_current_line_off()
346 {
347     return (int)(current_ScreenLine - ScreenLines);
348 }
349 #endif
350 
351 #ifdef FEAT_PROP_POPUP
352 /*
353  * Return TRUE if this position has a higher level popup or this cell is
354  * transparent in the current popup.
355  */
356     static int
357 blocked_by_popup(int row, int col)
358 {
359     int off;
360 
361     if (!popup_visible)
362 	return FALSE;
363     off = row * screen_Columns + col;
364     return popup_mask[off] > screen_zindex || popup_transparent[off];
365 }
366 #endif
367 
368 /*
369  * Reset the highlighting.  Used before clearing the screen.
370  */
371     void
372 reset_screen_attr(void)
373 {
374 #ifdef FEAT_GUI
375     if (gui.in_use)
376 	// Use a code that will reset gui.highlight_mask in
377 	// gui_stop_highlight().
378 	screen_attr = HL_ALL + 1;
379     else
380 #endif
381 	// Use attributes that is very unlikely to appear in text.
382 	screen_attr = HL_BOLD | HL_UNDERLINE | HL_INVERSE | HL_STRIKETHROUGH;
383 }
384 
385 /*
386  * Move one "cooked" screen line to the screen, but only the characters that
387  * have actually changed.  Handle insert/delete character.
388  * "coloff" gives the first column on the screen for this line.
389  * "endcol" gives the columns where valid characters are.
390  * "clear_width" is the width of the window.  It's > 0 if the rest of the line
391  * needs to be cleared, negative otherwise.
392  * "flags" can have bits:
393  * SLF_POPUP	    popup window
394  * SLF_RIGHTLEFT    rightleft window:
395  *    When TRUE and "clear_width" > 0, clear columns 0 to "endcol"
396  *    When FALSE and "clear_width" > 0, clear columns "endcol" to "clear_width"
397  */
398     void
399 screen_line(
400     int	    row,
401     int	    coloff,
402     int	    endcol,
403     int	    clear_width,
404     int	    flags UNUSED)
405 {
406     unsigned	    off_from;
407     unsigned	    off_to;
408     unsigned	    max_off_from;
409     unsigned	    max_off_to;
410     int		    col = 0;
411     int		    hl;
412     int		    force = FALSE;	// force update rest of the line
413     int		    redraw_this		// bool: does character need redraw?
414 #ifdef FEAT_GUI
415 				= TRUE	// For GUI when while-loop empty
416 #endif
417 				;
418     int		    redraw_next;	// redraw_this for next character
419     int		    clear_next = FALSE;
420     int		    char_cells;		// 1: normal char
421 					// 2: occupies two display cells
422 # define CHAR_CELLS char_cells
423 
424     // Check for illegal row and col, just in case.
425     if (row >= Rows)
426 	row = Rows - 1;
427     if (endcol > Columns)
428 	endcol = Columns;
429 
430 # ifdef FEAT_CLIPBOARD
431     clip_may_clear_selection(row, row);
432 # endif
433 
434     off_from = (unsigned)(current_ScreenLine - ScreenLines);
435     off_to = LineOffset[row] + coloff;
436     max_off_from = off_from + screen_Columns;
437     max_off_to = LineOffset[row] + screen_Columns;
438 
439 #ifdef FEAT_RIGHTLEFT
440     if (flags & SLF_RIGHTLEFT)
441     {
442 	// Clear rest first, because it's left of the text.
443 	if (clear_width > 0)
444 	{
445 	    while (col <= endcol && ScreenLines[off_to] == ' '
446 		    && ScreenAttrs[off_to] == 0
447 				  && (!enc_utf8 || ScreenLinesUC[off_to] == 0))
448 	    {
449 		++off_to;
450 		++col;
451 	    }
452 	    if (col <= endcol)
453 		screen_fill(row, row + 1, col + coloff,
454 					    endcol + coloff + 1, ' ', ' ', 0);
455 	}
456 	col = endcol + 1;
457 	off_to = LineOffset[row] + col + coloff;
458 	off_from += col;
459 	endcol = (clear_width > 0 ? clear_width : -clear_width);
460     }
461 #endif // FEAT_RIGHTLEFT
462 
463 #ifdef FEAT_PROP_POPUP
464     // First char of a popup window may go on top of the right half of a
465     // double-wide character. Clear the left half to avoid it getting the popup
466     // window background color.
467     if (coloff > 0 && ScreenLines[off_to] == 0
468 		   && ScreenLinesUC[off_to - 1] != 0
469 		   && (*mb_char2cells)(ScreenLinesUC[off_to - 1]) > 1)
470     {
471 	ScreenLines[off_to - 1] = ' ';
472 	ScreenLinesUC[off_to - 1] = 0;
473 	screen_char(off_to - 1, row, col + coloff - 1);
474     }
475 #endif
476 
477     redraw_next = char_needs_redraw(off_from, off_to, endcol - col);
478 
479     while (col < endcol)
480     {
481 	if (has_mbyte && (col + 1 < endcol))
482 	    char_cells = (*mb_off2cells)(off_from, max_off_from);
483 	else
484 	    char_cells = 1;
485 
486 	redraw_this = redraw_next;
487 	redraw_next = force || char_needs_redraw(off_from + CHAR_CELLS,
488 			      off_to + CHAR_CELLS, endcol - col - CHAR_CELLS);
489 
490 #ifdef FEAT_GUI
491 	// If the next character was bold, then redraw the current character to
492 	// remove any pixels that might have spilt over into us.  This only
493 	// happens in the GUI.
494 	if (redraw_next && gui.in_use)
495 	{
496 	    hl = ScreenAttrs[off_to + CHAR_CELLS];
497 	    if (hl > HL_ALL)
498 		hl = syn_attr2attr(hl);
499 	    if (hl & HL_BOLD)
500 		redraw_this = TRUE;
501 	}
502 #endif
503 #ifdef FEAT_PROP_POPUP
504 	if (blocked_by_popup(row, col + coloff))
505 	    redraw_this = FALSE;
506 #endif
507 	if (redraw_this)
508 	{
509 	    /*
510 	     * Special handling when 'xs' termcap flag set (hpterm):
511 	     * Attributes for characters are stored at the position where the
512 	     * cursor is when writing the highlighting code.  The
513 	     * start-highlighting code must be written with the cursor on the
514 	     * first highlighted character.  The stop-highlighting code must
515 	     * be written with the cursor just after the last highlighted
516 	     * character.
517 	     * Overwriting a character doesn't remove its highlighting.  Need
518 	     * to clear the rest of the line, and force redrawing it
519 	     * completely.
520 	     */
521 	    if (       p_wiv
522 		    && !force
523 #ifdef FEAT_GUI
524 		    && !gui.in_use
525 #endif
526 		    && ScreenAttrs[off_to] != 0
527 		    && ScreenAttrs[off_from] != ScreenAttrs[off_to])
528 	    {
529 		/*
530 		 * Need to remove highlighting attributes here.
531 		 */
532 		windgoto(row, col + coloff);
533 		out_str(T_CE);		// clear rest of this screen line
534 		screen_start();		// don't know where cursor is now
535 		force = TRUE;		// force redraw of rest of the line
536 		redraw_next = TRUE;	// or else next char would miss out
537 
538 		/*
539 		 * If the previous character was highlighted, need to stop
540 		 * highlighting at this character.
541 		 */
542 		if (col + coloff > 0 && ScreenAttrs[off_to - 1] != 0)
543 		{
544 		    screen_attr = ScreenAttrs[off_to - 1];
545 		    term_windgoto(row, col + coloff);
546 		    screen_stop_highlight();
547 		}
548 		else
549 		    screen_attr = 0;	    // highlighting has stopped
550 	    }
551 	    if (enc_dbcs != 0)
552 	    {
553 		// Check if overwriting a double-byte with a single-byte or
554 		// the other way around requires another character to be
555 		// redrawn.  For UTF-8 this isn't needed, because comparing
556 		// ScreenLinesUC[] is sufficient.
557 		if (char_cells == 1
558 			&& col + 1 < endcol
559 			&& (*mb_off2cells)(off_to, max_off_to) > 1)
560 		{
561 		    // Writing a single-cell character over a double-cell
562 		    // character: need to redraw the next cell.
563 		    ScreenLines[off_to + 1] = 0;
564 		    redraw_next = TRUE;
565 		}
566 		else if (char_cells == 2
567 			&& col + 2 < endcol
568 			&& (*mb_off2cells)(off_to, max_off_to) == 1
569 			&& (*mb_off2cells)(off_to + 1, max_off_to) > 1)
570 		{
571 		    // Writing the second half of a double-cell character over
572 		    // a double-cell character: need to redraw the second
573 		    // cell.
574 		    ScreenLines[off_to + 2] = 0;
575 		    redraw_next = TRUE;
576 		}
577 
578 		if (enc_dbcs == DBCS_JPNU)
579 		    ScreenLines2[off_to] = ScreenLines2[off_from];
580 	    }
581 	    // When writing a single-width character over a double-width
582 	    // character and at the end of the redrawn text, need to clear out
583 	    // the right halve of the old character.
584 	    // Also required when writing the right halve of a double-width
585 	    // char over the left halve of an existing one.
586 	    if (has_mbyte && col + char_cells == endcol
587 		    && ((char_cells == 1
588 			    && (*mb_off2cells)(off_to, max_off_to) > 1)
589 			|| (char_cells == 2
590 			    && (*mb_off2cells)(off_to, max_off_to) == 1
591 			    && (*mb_off2cells)(off_to + 1, max_off_to) > 1)))
592 		clear_next = TRUE;
593 
594 	    ScreenLines[off_to] = ScreenLines[off_from];
595 	    if (enc_utf8)
596 	    {
597 		ScreenLinesUC[off_to] = ScreenLinesUC[off_from];
598 		if (ScreenLinesUC[off_from] != 0)
599 		{
600 		    int	    i;
601 
602 		    for (i = 0; i < Screen_mco; ++i)
603 			ScreenLinesC[i][off_to] = ScreenLinesC[i][off_from];
604 		}
605 	    }
606 	    if (char_cells == 2)
607 		ScreenLines[off_to + 1] = ScreenLines[off_from + 1];
608 
609 #if defined(FEAT_GUI) || defined(UNIX)
610 	    // The bold trick makes a single column of pixels appear in the
611 	    // next character.  When a bold character is removed, the next
612 	    // character should be redrawn too.  This happens for our own GUI
613 	    // and for some xterms.
614 	    if (
615 # ifdef FEAT_GUI
616 		    gui.in_use
617 # endif
618 # if defined(FEAT_GUI) && defined(UNIX)
619 		    ||
620 # endif
621 # ifdef UNIX
622 		    term_is_xterm
623 # endif
624 		    )
625 	    {
626 		hl = ScreenAttrs[off_to];
627 		if (hl > HL_ALL)
628 		    hl = syn_attr2attr(hl);
629 		if (hl & HL_BOLD)
630 		    redraw_next = TRUE;
631 	    }
632 #endif
633 	    ScreenAttrs[off_to] = ScreenAttrs[off_from];
634 
635 	    // For simplicity set the attributes of second half of a
636 	    // double-wide character equal to the first half.
637 	    if (char_cells == 2)
638 		ScreenAttrs[off_to + 1] = ScreenAttrs[off_from];
639 
640 	    if (enc_dbcs != 0 && char_cells == 2)
641 		screen_char_2(off_to, row, col + coloff);
642 	    else
643 		screen_char(off_to, row, col + coloff);
644 	}
645 	else if (  p_wiv
646 #ifdef FEAT_GUI
647 		&& !gui.in_use
648 #endif
649 		&& col + coloff > 0)
650 	{
651 	    if (ScreenAttrs[off_to] == ScreenAttrs[off_to - 1])
652 	    {
653 		/*
654 		 * Don't output stop-highlight when moving the cursor, it will
655 		 * stop the highlighting when it should continue.
656 		 */
657 		screen_attr = 0;
658 	    }
659 	    else if (screen_attr != 0)
660 		screen_stop_highlight();
661 	}
662 
663 	off_to += CHAR_CELLS;
664 	off_from += CHAR_CELLS;
665 	col += CHAR_CELLS;
666     }
667 
668     if (clear_next)
669     {
670 	// Clear the second half of a double-wide character of which the left
671 	// half was overwritten with a single-wide character.
672 	ScreenLines[off_to] = ' ';
673 	if (enc_utf8)
674 	    ScreenLinesUC[off_to] = 0;
675 	screen_char(off_to, row, col + coloff);
676     }
677 
678     if (clear_width > 0
679 #ifdef FEAT_RIGHTLEFT
680 		    && !(flags & SLF_RIGHTLEFT)
681 #endif
682 				   )
683     {
684 #ifdef FEAT_GUI
685 	int startCol = col;
686 #endif
687 
688 	// blank out the rest of the line
689 	while (col < clear_width && ScreenLines[off_to] == ' '
690 						  && ScreenAttrs[off_to] == 0
691 				  && (!enc_utf8 || ScreenLinesUC[off_to] == 0))
692 	{
693 	    ++off_to;
694 	    ++col;
695 	}
696 	if (col < clear_width)
697 	{
698 #ifdef FEAT_GUI
699 	    /*
700 	     * In the GUI, clearing the rest of the line may leave pixels
701 	     * behind if the first character cleared was bold.  Some bold
702 	     * fonts spill over the left.  In this case we redraw the previous
703 	     * character too.  If we didn't skip any blanks above, then we
704 	     * only redraw if the character wasn't already redrawn anyway.
705 	     */
706 	    if (gui.in_use && (col > startCol || !redraw_this))
707 	    {
708 		hl = ScreenAttrs[off_to];
709 		if (hl > HL_ALL || (hl & HL_BOLD))
710 		{
711 		    int prev_cells = 1;
712 
713 		    if (enc_utf8)
714 			// for utf-8, ScreenLines[char_offset + 1] == 0 means
715 			// that its width is 2.
716 			prev_cells = ScreenLines[off_to - 1] == 0 ? 2 : 1;
717 		    else if (enc_dbcs != 0)
718 		    {
719 			// find previous character by counting from first
720 			// column and get its width.
721 			unsigned off = LineOffset[row];
722 			unsigned max_off = LineOffset[row] + screen_Columns;
723 
724 			while (off < off_to)
725 			{
726 			    prev_cells = (*mb_off2cells)(off, max_off);
727 			    off += prev_cells;
728 			}
729 		    }
730 
731 		    if (enc_dbcs != 0 && prev_cells > 1)
732 			screen_char_2(off_to - prev_cells, row,
733 						   col + coloff - prev_cells);
734 		    else
735 			screen_char(off_to - prev_cells, row,
736 						   col + coloff - prev_cells);
737 		}
738 	    }
739 #endif
740 	    screen_fill(row, row + 1, col + coloff, clear_width + coloff,
741 								 ' ', ' ', 0);
742 	    off_to += clear_width - col;
743 	    col = clear_width;
744 	}
745     }
746 
747     if (clear_width > 0
748 #ifdef FEAT_PROP_POPUP
749 	    && !(flags & SLF_POPUP)  // no separator for popup window
750 #endif
751 	    )
752     {
753 	// For a window that has a right neighbor, draw the separator char
754 	// right of the window contents.  But not on top of a popup window.
755 	if (coloff + col < Columns)
756 	{
757 #ifdef FEAT_PROP_POPUP
758 	    if (!blocked_by_popup(row, col + coloff))
759 #endif
760 	    {
761 		int c;
762 
763 		c = fillchar_vsep(&hl);
764 		if (ScreenLines[off_to] != (schar_T)c
765 			|| (enc_utf8 && (int)ScreenLinesUC[off_to]
766 							!= (c >= 0x80 ? c : 0))
767 			|| ScreenAttrs[off_to] != hl)
768 		{
769 		    ScreenLines[off_to] = c;
770 		    ScreenAttrs[off_to] = hl;
771 		    if (enc_utf8)
772 		    {
773 			if (c >= 0x80)
774 			{
775 			    ScreenLinesUC[off_to] = c;
776 			    ScreenLinesC[0][off_to] = 0;
777 			}
778 			else
779 			    ScreenLinesUC[off_to] = 0;
780 		    }
781 		    screen_char(off_to, row, col + coloff);
782 		}
783 	    }
784 	}
785 	else
786 	    LineWraps[row] = FALSE;
787     }
788 }
789 
790 #if defined(FEAT_RIGHTLEFT) || defined(PROTO)
791 /*
792  * Mirror text "str" for right-left displaying.
793  * Only works for single-byte characters (e.g., numbers).
794  */
795     void
796 rl_mirror(char_u *str)
797 {
798     char_u	*p1, *p2;
799     int		t;
800 
801     for (p1 = str, p2 = str + STRLEN(str) - 1; p1 < p2; ++p1, --p2)
802     {
803 	t = *p1;
804 	*p1 = *p2;
805 	*p2 = t;
806     }
807 }
808 #endif
809 
810 /*
811  * Draw the verticap separator right of window "wp" starting with line "row".
812  */
813     void
814 draw_vsep_win(win_T *wp, int row)
815 {
816     int		hl;
817     int		c;
818 
819     if (wp->w_vsep_width)
820     {
821 	// draw the vertical separator right of this window
822 	c = fillchar_vsep(&hl);
823 	screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + wp->w_height,
824 		W_ENDCOL(wp), W_ENDCOL(wp) + 1,
825 		c, ' ', hl);
826     }
827 }
828 
829 #ifdef FEAT_WILDMENU
830 static int skip_status_match_char(expand_T *xp, char_u *s);
831 
832 /*
833  * Get the length of an item as it will be shown in the status line.
834  */
835     static int
836 status_match_len(expand_T *xp, char_u *s)
837 {
838     int	len = 0;
839 
840 #ifdef FEAT_MENU
841     int emenu = (xp->xp_context == EXPAND_MENUS
842 	    || xp->xp_context == EXPAND_MENUNAMES);
843 
844     // Check for menu separators - replace with '|'.
845     if (emenu && menu_is_separator(s))
846 	return 1;
847 #endif
848 
849     while (*s != NUL)
850     {
851 	s += skip_status_match_char(xp, s);
852 	len += ptr2cells(s);
853 	MB_PTR_ADV(s);
854     }
855 
856     return len;
857 }
858 
859 /*
860  * Return the number of characters that should be skipped in a status match.
861  * These are backslashes used for escaping.  Do show backslashes in help tags.
862  */
863     static int
864 skip_status_match_char(expand_T *xp, char_u *s)
865 {
866     if ((rem_backslash(s) && xp->xp_context != EXPAND_HELP)
867 #ifdef FEAT_MENU
868 	    || ((xp->xp_context == EXPAND_MENUS
869 		    || xp->xp_context == EXPAND_MENUNAMES)
870 			  && (s[0] == '\t' || (s[0] == '\\' && s[1] != NUL)))
871 #endif
872 	   )
873     {
874 #ifndef BACKSLASH_IN_FILENAME
875 	if (xp->xp_shell && csh_like_shell() && s[1] == '\\' && s[2] == '!')
876 	    return 2;
877 #endif
878 	return 1;
879     }
880     return 0;
881 }
882 
883 /*
884  * Show wildchar matches in the status line.
885  * Show at least the "match" item.
886  * We start at item 'first_match' in the list and show all matches that fit.
887  *
888  * If inversion is possible we use it. Else '=' characters are used.
889  */
890     void
891 win_redr_status_matches(
892     expand_T	*xp,
893     int		num_matches,
894     char_u	**matches,	// list of matches
895     int		match,
896     int		showtail)
897 {
898 #define L_MATCH(m) (showtail ? sm_gettail(matches[m]) : matches[m])
899     int		row;
900     char_u	*buf;
901     int		len;
902     int		clen;		// length in screen cells
903     int		fillchar;
904     int		attr;
905     int		i;
906     int		highlight = TRUE;
907     char_u	*selstart = NULL;
908     int		selstart_col = 0;
909     char_u	*selend = NULL;
910     static int	first_match = 0;
911     int		add_left = FALSE;
912     char_u	*s;
913 #ifdef FEAT_MENU
914     int		emenu;
915 #endif
916     int		l;
917 
918     if (matches == NULL)	// interrupted completion?
919 	return;
920 
921     if (has_mbyte)
922 	buf = alloc(Columns * MB_MAXBYTES + 1);
923     else
924 	buf = alloc(Columns + 1);
925     if (buf == NULL)
926 	return;
927 
928     if (match == -1)	// don't show match but original text
929     {
930 	match = 0;
931 	highlight = FALSE;
932     }
933     // count 1 for the ending ">"
934     clen = status_match_len(xp, L_MATCH(match)) + 3;
935     if (match == 0)
936 	first_match = 0;
937     else if (match < first_match)
938     {
939 	// jumping left, as far as we can go
940 	first_match = match;
941 	add_left = TRUE;
942     }
943     else
944     {
945 	// check if match fits on the screen
946 	for (i = first_match; i < match; ++i)
947 	    clen += status_match_len(xp, L_MATCH(i)) + 2;
948 	if (first_match > 0)
949 	    clen += 2;
950 	// jumping right, put match at the left
951 	if ((long)clen > Columns)
952 	{
953 	    first_match = match;
954 	    // if showing the last match, we can add some on the left
955 	    clen = 2;
956 	    for (i = match; i < num_matches; ++i)
957 	    {
958 		clen += status_match_len(xp, L_MATCH(i)) + 2;
959 		if ((long)clen >= Columns)
960 		    break;
961 	    }
962 	    if (i == num_matches)
963 		add_left = TRUE;
964 	}
965     }
966     if (add_left)
967 	while (first_match > 0)
968 	{
969 	    clen += status_match_len(xp, L_MATCH(first_match - 1)) + 2;
970 	    if ((long)clen >= Columns)
971 		break;
972 	    --first_match;
973 	}
974 
975     fillchar = fillchar_status(&attr, curwin);
976 
977     if (first_match == 0)
978     {
979 	*buf = NUL;
980 	len = 0;
981     }
982     else
983     {
984 	STRCPY(buf, "< ");
985 	len = 2;
986     }
987     clen = len;
988 
989     i = first_match;
990     while ((long)(clen + status_match_len(xp, L_MATCH(i)) + 2) < Columns)
991     {
992 	if (i == match)
993 	{
994 	    selstart = buf + len;
995 	    selstart_col = clen;
996 	}
997 
998 	s = L_MATCH(i);
999 	// Check for menu separators - replace with '|'
1000 #ifdef FEAT_MENU
1001 	emenu = (xp->xp_context == EXPAND_MENUS
1002 		|| xp->xp_context == EXPAND_MENUNAMES);
1003 	if (emenu && menu_is_separator(s))
1004 	{
1005 	    STRCPY(buf + len, transchar('|'));
1006 	    l = (int)STRLEN(buf + len);
1007 	    len += l;
1008 	    clen += l;
1009 	}
1010 	else
1011 #endif
1012 	    for ( ; *s != NUL; ++s)
1013 	{
1014 	    s += skip_status_match_char(xp, s);
1015 	    clen += ptr2cells(s);
1016 	    if (has_mbyte && (l = (*mb_ptr2len)(s)) > 1)
1017 	    {
1018 		STRNCPY(buf + len, s, l);
1019 		s += l - 1;
1020 		len += l;
1021 	    }
1022 	    else
1023 	    {
1024 		STRCPY(buf + len, transchar_byte(*s));
1025 		len += (int)STRLEN(buf + len);
1026 	    }
1027 	}
1028 	if (i == match)
1029 	    selend = buf + len;
1030 
1031 	*(buf + len++) = ' ';
1032 	*(buf + len++) = ' ';
1033 	clen += 2;
1034 	if (++i == num_matches)
1035 		break;
1036     }
1037 
1038     if (i != num_matches)
1039     {
1040 	*(buf + len++) = '>';
1041 	++clen;
1042     }
1043 
1044     buf[len] = NUL;
1045 
1046     row = cmdline_row - 1;
1047     if (row >= 0)
1048     {
1049 	if (wild_menu_showing == 0)
1050 	{
1051 	    if (msg_scrolled > 0)
1052 	    {
1053 		// Put the wildmenu just above the command line.  If there is
1054 		// no room, scroll the screen one line up.
1055 		if (cmdline_row == Rows - 1)
1056 		{
1057 		    screen_del_lines(0, 0, 1, (int)Rows, TRUE, 0, NULL);
1058 		    ++msg_scrolled;
1059 		}
1060 		else
1061 		{
1062 		    ++cmdline_row;
1063 		    ++row;
1064 		}
1065 		wild_menu_showing = WM_SCROLLED;
1066 	    }
1067 	    else
1068 	    {
1069 		// Create status line if needed by setting 'laststatus' to 2.
1070 		// Set 'winminheight' to zero to avoid that the window is
1071 		// resized.
1072 		if (lastwin->w_status_height == 0)
1073 		{
1074 		    save_p_ls = p_ls;
1075 		    save_p_wmh = p_wmh;
1076 		    p_ls = 2;
1077 		    p_wmh = 0;
1078 		    last_status(FALSE);
1079 		}
1080 		wild_menu_showing = WM_SHOWN;
1081 	    }
1082 	}
1083 
1084 	screen_puts(buf, row, 0, attr);
1085 	if (selstart != NULL && highlight)
1086 	{
1087 	    *selend = NUL;
1088 	    screen_puts(selstart, row, selstart_col, HL_ATTR(HLF_WM));
1089 	}
1090 
1091 	screen_fill(row, row + 1, clen, (int)Columns, fillchar, fillchar, attr);
1092     }
1093 
1094     win_redraw_last_status(topframe);
1095     vim_free(buf);
1096 }
1097 #endif
1098 
1099 /*
1100  * Return TRUE if the status line of window "wp" is connected to the status
1101  * line of the window right of it.  If not, then it's a vertical separator.
1102  * Only call if (wp->w_vsep_width != 0).
1103  */
1104     int
1105 stl_connected(win_T *wp)
1106 {
1107     frame_T	*fr;
1108 
1109     fr = wp->w_frame;
1110     while (fr->fr_parent != NULL)
1111     {
1112 	if (fr->fr_parent->fr_layout == FR_COL)
1113 	{
1114 	    if (fr->fr_next != NULL)
1115 		break;
1116 	}
1117 	else
1118 	{
1119 	    if (fr->fr_next != NULL)
1120 		return TRUE;
1121 	}
1122 	fr = fr->fr_parent;
1123     }
1124     return FALSE;
1125 }
1126 
1127 
1128 /*
1129  * Get the value to show for the language mappings, active 'keymap'.
1130  */
1131     int
1132 get_keymap_str(
1133     win_T	*wp,
1134     char_u	*fmt,	    // format string containing one %s item
1135     char_u	*buf,	    // buffer for the result
1136     int		len)	    // length of buffer
1137 {
1138     char_u	*p;
1139 
1140     if (wp->w_buffer->b_p_iminsert != B_IMODE_LMAP)
1141 	return FALSE;
1142 
1143     {
1144 #ifdef FEAT_EVAL
1145 	buf_T	*old_curbuf = curbuf;
1146 	win_T	*old_curwin = curwin;
1147 	char_u	*s;
1148 
1149 	curbuf = wp->w_buffer;
1150 	curwin = wp;
1151 	STRCPY(buf, "b:keymap_name");	// must be writable
1152 	++emsg_skip;
1153 	s = p = eval_to_string(buf, FALSE);
1154 	--emsg_skip;
1155 	curbuf = old_curbuf;
1156 	curwin = old_curwin;
1157 	if (p == NULL || *p == NUL)
1158 #endif
1159 	{
1160 #ifdef FEAT_KEYMAP
1161 	    if (wp->w_buffer->b_kmap_state & KEYMAP_LOADED)
1162 		p = wp->w_buffer->b_p_keymap;
1163 	    else
1164 #endif
1165 		p = (char_u *)"lang";
1166 	}
1167 	if (vim_snprintf((char *)buf, len, (char *)fmt, p) > len - 1)
1168 	    buf[0] = NUL;
1169 #ifdef FEAT_EVAL
1170 	vim_free(s);
1171 #endif
1172     }
1173     return buf[0] != NUL;
1174 }
1175 
1176 #if defined(FEAT_STL_OPT) || defined(PROTO)
1177 /*
1178  * Redraw the status line or ruler of window "wp".
1179  * When "wp" is NULL redraw the tab pages line from 'tabline'.
1180  */
1181     void
1182 win_redr_custom(
1183     win_T	*wp,
1184     int		draw_ruler)	// TRUE or FALSE
1185 {
1186     static int	entered = FALSE;
1187     int		attr;
1188     int		curattr;
1189     int		row;
1190     int		col = 0;
1191     int		maxwidth;
1192     int		width;
1193     int		n;
1194     int		len;
1195     int		fillchar;
1196     char_u	buf[MAXPATHL];
1197     char_u	*stl;
1198     char_u	*p;
1199     stl_hlrec_T *hltab;
1200     stl_hlrec_T *tabtab;
1201     int		use_sandbox = FALSE;
1202     win_T	*ewp;
1203     int		p_crb_save;
1204 
1205     // There is a tiny chance that this gets called recursively: When
1206     // redrawing a status line triggers redrawing the ruler or tabline.
1207     // Avoid trouble by not allowing recursion.
1208     if (entered)
1209 	return;
1210     entered = TRUE;
1211 
1212     // setup environment for the task at hand
1213     if (wp == NULL)
1214     {
1215 	// Use 'tabline'.  Always at the first line of the screen.
1216 	stl = p_tal;
1217 	row = 0;
1218 	fillchar = ' ';
1219 	attr = HL_ATTR(HLF_TPF);
1220 	maxwidth = Columns;
1221 # ifdef FEAT_EVAL
1222 	use_sandbox = was_set_insecurely((char_u *)"tabline", 0);
1223 # endif
1224     }
1225     else
1226     {
1227 	row = W_WINROW(wp) + wp->w_height;
1228 	fillchar = fillchar_status(&attr, wp);
1229 	maxwidth = wp->w_width;
1230 
1231 	if (draw_ruler)
1232 	{
1233 	    stl = p_ruf;
1234 	    // advance past any leading group spec - implicit in ru_col
1235 	    if (*stl == '%')
1236 	    {
1237 		if (*++stl == '-')
1238 		    stl++;
1239 		if (atoi((char *)stl))
1240 		    while (VIM_ISDIGIT(*stl))
1241 			stl++;
1242 		if (*stl++ != '(')
1243 		    stl = p_ruf;
1244 	    }
1245 	    col = ru_col - (Columns - wp->w_width);
1246 	    if (col < (wp->w_width + 1) / 2)
1247 		col = (wp->w_width + 1) / 2;
1248 	    maxwidth = wp->w_width - col;
1249 	    if (!wp->w_status_height)
1250 	    {
1251 		row = Rows - 1;
1252 		--maxwidth;	// writing in last column may cause scrolling
1253 		fillchar = ' ';
1254 		attr = 0;
1255 	    }
1256 
1257 # ifdef FEAT_EVAL
1258 	    use_sandbox = was_set_insecurely((char_u *)"rulerformat", 0);
1259 # endif
1260 	}
1261 	else
1262 	{
1263 	    if (*wp->w_p_stl != NUL)
1264 		stl = wp->w_p_stl;
1265 	    else
1266 		stl = p_stl;
1267 # ifdef FEAT_EVAL
1268 	    use_sandbox = was_set_insecurely((char_u *)"statusline",
1269 					 *wp->w_p_stl == NUL ? 0 : OPT_LOCAL);
1270 # endif
1271 	}
1272 
1273 	col += wp->w_wincol;
1274     }
1275 
1276     if (maxwidth <= 0)
1277 	goto theend;
1278 
1279     // Temporarily reset 'cursorbind', we don't want a side effect from moving
1280     // the cursor away and back.
1281     ewp = wp == NULL ? curwin : wp;
1282     p_crb_save = ewp->w_p_crb;
1283     ewp->w_p_crb = FALSE;
1284 
1285     // Make a copy, because the statusline may include a function call that
1286     // might change the option value and free the memory.
1287     stl = vim_strsave(stl);
1288     width = build_stl_str_hl(ewp, buf, sizeof(buf),
1289 				stl, use_sandbox,
1290 				fillchar, maxwidth, &hltab, &tabtab);
1291     vim_free(stl);
1292     ewp->w_p_crb = p_crb_save;
1293 
1294     // Make all characters printable.
1295     p = transstr(buf);
1296     if (p != NULL)
1297     {
1298 	vim_strncpy(buf, p, sizeof(buf) - 1);
1299 	vim_free(p);
1300     }
1301 
1302     // fill up with "fillchar"
1303     len = (int)STRLEN(buf);
1304     while (width < maxwidth && len < (int)sizeof(buf) - 1)
1305     {
1306 	len += (*mb_char2bytes)(fillchar, buf + len);
1307 	++width;
1308     }
1309     buf[len] = NUL;
1310 
1311     /*
1312      * Draw each snippet with the specified highlighting.
1313      */
1314     curattr = attr;
1315     p = buf;
1316     for (n = 0; hltab[n].start != NULL; n++)
1317     {
1318 	len = (int)(hltab[n].start - p);
1319 	screen_puts_len(p, len, row, col, curattr);
1320 	col += vim_strnsize(p, len);
1321 	p = hltab[n].start;
1322 
1323 	if (hltab[n].userhl == 0)
1324 	    curattr = attr;
1325 	else if (hltab[n].userhl < 0)
1326 	    curattr = syn_id2attr(-hltab[n].userhl);
1327 #ifdef FEAT_TERMINAL
1328 	else if (wp != NULL && wp != curwin && bt_terminal(wp->w_buffer)
1329 						   && wp->w_status_height != 0)
1330 	    curattr = highlight_stltermnc[hltab[n].userhl - 1];
1331 	else if (wp != NULL && bt_terminal(wp->w_buffer)
1332 						   && wp->w_status_height != 0)
1333 	    curattr = highlight_stlterm[hltab[n].userhl - 1];
1334 #endif
1335 	else if (wp != NULL && wp != curwin && wp->w_status_height != 0)
1336 	    curattr = highlight_stlnc[hltab[n].userhl - 1];
1337 	else
1338 	    curattr = highlight_user[hltab[n].userhl - 1];
1339     }
1340     screen_puts(p, row, col, curattr);
1341 
1342     if (wp == NULL)
1343     {
1344 	// Fill the TabPageIdxs[] array for clicking in the tab pagesline.
1345 	col = 0;
1346 	len = 0;
1347 	p = buf;
1348 	fillchar = 0;
1349 	for (n = 0; tabtab[n].start != NULL; n++)
1350 	{
1351 	    len += vim_strnsize(p, (int)(tabtab[n].start - p));
1352 	    while (col < len)
1353 		TabPageIdxs[col++] = fillchar;
1354 	    p = tabtab[n].start;
1355 	    fillchar = tabtab[n].userhl;
1356 	}
1357 	while (col < Columns)
1358 	    TabPageIdxs[col++] = fillchar;
1359     }
1360 
1361 theend:
1362     entered = FALSE;
1363 }
1364 
1365 #endif // FEAT_STL_OPT
1366 
1367 /*
1368  * Output a single character directly to the screen and update ScreenLines.
1369  */
1370     void
1371 screen_putchar(int c, int row, int col, int attr)
1372 {
1373     char_u	buf[MB_MAXBYTES + 1];
1374 
1375     if (has_mbyte)
1376 	buf[(*mb_char2bytes)(c, buf)] = NUL;
1377     else
1378     {
1379 	buf[0] = c;
1380 	buf[1] = NUL;
1381     }
1382     screen_puts(buf, row, col, attr);
1383 }
1384 
1385 /*
1386  * Get a single character directly from ScreenLines into "bytes[]".
1387  * Also return its attribute in *attrp;
1388  */
1389     void
1390 screen_getbytes(int row, int col, char_u *bytes, int *attrp)
1391 {
1392     unsigned off;
1393 
1394     // safety check
1395     if (ScreenLines != NULL && row < screen_Rows && col < screen_Columns)
1396     {
1397 	off = LineOffset[row] + col;
1398 	*attrp = ScreenAttrs[off];
1399 	bytes[0] = ScreenLines[off];
1400 	bytes[1] = NUL;
1401 
1402 	if (enc_utf8 && ScreenLinesUC[off] != 0)
1403 	    bytes[utfc_char2bytes(off, bytes)] = NUL;
1404 	else if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
1405 	{
1406 	    bytes[0] = ScreenLines[off];
1407 	    bytes[1] = ScreenLines2[off];
1408 	    bytes[2] = NUL;
1409 	}
1410 	else if (enc_dbcs && MB_BYTE2LEN(bytes[0]) > 1)
1411 	{
1412 	    bytes[1] = ScreenLines[off + 1];
1413 	    bytes[2] = NUL;
1414 	}
1415     }
1416 }
1417 
1418 /*
1419  * Return TRUE if composing characters for screen posn "off" differs from
1420  * composing characters in "u8cc".
1421  * Only to be used when ScreenLinesUC[off] != 0.
1422  */
1423     static int
1424 screen_comp_differs(int off, int *u8cc)
1425 {
1426     int	    i;
1427 
1428     for (i = 0; i < Screen_mco; ++i)
1429     {
1430 	if (ScreenLinesC[i][off] != (u8char_T)u8cc[i])
1431 	    return TRUE;
1432 	if (u8cc[i] == 0)
1433 	    break;
1434     }
1435     return FALSE;
1436 }
1437 
1438 /*
1439  * Put string '*text' on the screen at position 'row' and 'col', with
1440  * attributes 'attr', and update ScreenLines[] and ScreenAttrs[].
1441  * Note: only outputs within one row, message is truncated at screen boundary!
1442  * Note: if ScreenLines[], row and/or col is invalid, nothing is done.
1443  */
1444     void
1445 screen_puts(
1446     char_u	*text,
1447     int		row,
1448     int		col,
1449     int		attr)
1450 {
1451     screen_puts_len(text, -1, row, col, attr);
1452 }
1453 
1454 /*
1455  * Like screen_puts(), but output "text[len]".  When "len" is -1 output up to
1456  * a NUL.
1457  */
1458     void
1459 screen_puts_len(
1460     char_u	*text,
1461     int		textlen,
1462     int		row,
1463     int		col,
1464     int		attr)
1465 {
1466     unsigned	off;
1467     char_u	*ptr = text;
1468     int		len = textlen;
1469     int		c;
1470     unsigned	max_off;
1471     int		mbyte_blen = 1;
1472     int		mbyte_cells = 1;
1473     int		u8c = 0;
1474     int		u8cc[MAX_MCO];
1475     int		clear_next_cell = FALSE;
1476 #ifdef FEAT_ARABIC
1477     int		prev_c = 0;		// previous Arabic character
1478     int		pc, nc, nc1;
1479     int		pcc[MAX_MCO];
1480 #endif
1481     int		force_redraw_this;
1482     int		force_redraw_next = FALSE;
1483     int		need_redraw;
1484 
1485     // Safety check. The check for negative row and column is to fix issue
1486     // #4102. TODO: find out why row/col could be negative.
1487     if (ScreenLines == NULL
1488 	    || row >= screen_Rows || row < 0
1489 	    || col >= screen_Columns || col < 0)
1490 	return;
1491     off = LineOffset[row] + col;
1492 
1493     // When drawing over the right halve of a double-wide char clear out the
1494     // left halve.  Only needed in a terminal.
1495     if (has_mbyte && col > 0 && col < screen_Columns
1496 #ifdef FEAT_GUI
1497 	    && !gui.in_use
1498 #endif
1499 	    && mb_fix_col(col, row) != col)
1500     {
1501 	ScreenLines[off - 1] = ' ';
1502 	ScreenAttrs[off - 1] = 0;
1503 	if (enc_utf8)
1504 	{
1505 	    ScreenLinesUC[off - 1] = 0;
1506 	    ScreenLinesC[0][off - 1] = 0;
1507 	}
1508 	// redraw the previous cell, make it empty
1509 	screen_char(off - 1, row, col - 1);
1510 	// force the cell at "col" to be redrawn
1511 	force_redraw_next = TRUE;
1512     }
1513 
1514     max_off = LineOffset[row] + screen_Columns;
1515     while (col < screen_Columns
1516 	    && (len < 0 || (int)(ptr - text) < len)
1517 	    && *ptr != NUL)
1518     {
1519 	c = *ptr;
1520 	// check if this is the first byte of a multibyte
1521 	if (has_mbyte)
1522 	{
1523 	    if (enc_utf8 && len > 0)
1524 		mbyte_blen = utfc_ptr2len_len(ptr, (int)((text + len) - ptr));
1525 	    else
1526 		mbyte_blen = (*mb_ptr2len)(ptr);
1527 	    if (enc_dbcs == DBCS_JPNU && c == 0x8e)
1528 		mbyte_cells = 1;
1529 	    else if (enc_dbcs != 0)
1530 		mbyte_cells = mbyte_blen;
1531 	    else	// enc_utf8
1532 	    {
1533 		if (len >= 0)
1534 		    u8c = utfc_ptr2char_len(ptr, u8cc,
1535 						   (int)((text + len) - ptr));
1536 		else
1537 		    u8c = utfc_ptr2char(ptr, u8cc);
1538 		mbyte_cells = utf_char2cells(u8c);
1539 #ifdef FEAT_ARABIC
1540 		if (p_arshape && !p_tbidi && ARABIC_CHAR(u8c))
1541 		{
1542 		    // Do Arabic shaping.
1543 		    if (len >= 0 && (int)(ptr - text) + mbyte_blen >= len)
1544 		    {
1545 			// Past end of string to be displayed.
1546 			nc = NUL;
1547 			nc1 = NUL;
1548 		    }
1549 		    else
1550 		    {
1551 			nc = utfc_ptr2char_len(ptr + mbyte_blen, pcc,
1552 				      (int)((text + len) - ptr - mbyte_blen));
1553 			nc1 = pcc[0];
1554 		    }
1555 		    pc = prev_c;
1556 		    prev_c = u8c;
1557 		    u8c = arabic_shape(u8c, &c, &u8cc[0], nc, nc1, pc);
1558 		}
1559 		else
1560 		    prev_c = u8c;
1561 #endif
1562 		if (col + mbyte_cells > screen_Columns)
1563 		{
1564 		    // Only 1 cell left, but character requires 2 cells:
1565 		    // display a '>' in the last column to avoid wrapping.
1566 		    c = '>';
1567 		    mbyte_cells = 1;
1568 		}
1569 	    }
1570 	}
1571 
1572 	force_redraw_this = force_redraw_next;
1573 	force_redraw_next = FALSE;
1574 
1575 	need_redraw = ScreenLines[off] != c
1576 		|| (mbyte_cells == 2
1577 		    && ScreenLines[off + 1] != (enc_dbcs ? ptr[1] : 0))
1578 		|| (enc_dbcs == DBCS_JPNU
1579 		    && c == 0x8e
1580 		    && ScreenLines2[off] != ptr[1])
1581 		|| (enc_utf8
1582 		    && (ScreenLinesUC[off] !=
1583 				(u8char_T)(c < 0x80 && u8cc[0] == 0 ? 0 : u8c)
1584 			|| (ScreenLinesUC[off] != 0
1585 					  && screen_comp_differs(off, u8cc))))
1586 		|| ScreenAttrs[off] != attr
1587 		|| exmode_active;
1588 
1589 	if ((need_redraw || force_redraw_this)
1590 #ifdef FEAT_PROP_POPUP
1591 		&& !blocked_by_popup(row, col)
1592 #endif
1593 	   )
1594 	{
1595 #if defined(FEAT_GUI) || defined(UNIX)
1596 	    // The bold trick makes a single row of pixels appear in the next
1597 	    // character.  When a bold character is removed, the next
1598 	    // character should be redrawn too.  This happens for our own GUI
1599 	    // and for some xterms.
1600 	    if (need_redraw && ScreenLines[off] != ' ' && (
1601 # ifdef FEAT_GUI
1602 		    gui.in_use
1603 # endif
1604 # if defined(FEAT_GUI) && defined(UNIX)
1605 		    ||
1606 # endif
1607 # ifdef UNIX
1608 		    term_is_xterm
1609 # endif
1610 		    ))
1611 	    {
1612 		int	n = ScreenAttrs[off];
1613 
1614 		if (n > HL_ALL)
1615 		    n = syn_attr2attr(n);
1616 		if (n & HL_BOLD)
1617 		    force_redraw_next = TRUE;
1618 	    }
1619 #endif
1620 	    // When at the end of the text and overwriting a two-cell
1621 	    // character with a one-cell character, need to clear the next
1622 	    // cell.  Also when overwriting the left halve of a two-cell char
1623 	    // with the right halve of a two-cell char.  Do this only once
1624 	    // (mb_off2cells() may return 2 on the right halve).
1625 	    if (clear_next_cell)
1626 		clear_next_cell = FALSE;
1627 	    else if (has_mbyte
1628 		    && (len < 0 ? ptr[mbyte_blen] == NUL
1629 					     : ptr + mbyte_blen >= text + len)
1630 		    && ((mbyte_cells == 1 && (*mb_off2cells)(off, max_off) > 1)
1631 			|| (mbyte_cells == 2
1632 			    && (*mb_off2cells)(off, max_off) == 1
1633 			    && (*mb_off2cells)(off + 1, max_off) > 1)))
1634 		clear_next_cell = TRUE;
1635 
1636 	    // Make sure we never leave a second byte of a double-byte behind,
1637 	    // it confuses mb_off2cells().
1638 	    if (enc_dbcs
1639 		    && ((mbyte_cells == 1 && (*mb_off2cells)(off, max_off) > 1)
1640 			|| (mbyte_cells == 2
1641 			    && (*mb_off2cells)(off, max_off) == 1
1642 			    && (*mb_off2cells)(off + 1, max_off) > 1)))
1643 		ScreenLines[off + mbyte_blen] = 0;
1644 	    ScreenLines[off] = c;
1645 	    ScreenAttrs[off] = attr;
1646 	    if (enc_utf8)
1647 	    {
1648 		if (c < 0x80 && u8cc[0] == 0)
1649 		    ScreenLinesUC[off] = 0;
1650 		else
1651 		{
1652 		    int	    i;
1653 
1654 		    ScreenLinesUC[off] = u8c;
1655 		    for (i = 0; i < Screen_mco; ++i)
1656 		    {
1657 			ScreenLinesC[i][off] = u8cc[i];
1658 			if (u8cc[i] == 0)
1659 			    break;
1660 		    }
1661 		}
1662 		if (mbyte_cells == 2)
1663 		{
1664 		    ScreenLines[off + 1] = 0;
1665 		    ScreenAttrs[off + 1] = attr;
1666 		}
1667 		screen_char(off, row, col);
1668 	    }
1669 	    else if (mbyte_cells == 2)
1670 	    {
1671 		ScreenLines[off + 1] = ptr[1];
1672 		ScreenAttrs[off + 1] = attr;
1673 		screen_char_2(off, row, col);
1674 	    }
1675 	    else if (enc_dbcs == DBCS_JPNU && c == 0x8e)
1676 	    {
1677 		ScreenLines2[off] = ptr[1];
1678 		screen_char(off, row, col);
1679 	    }
1680 	    else
1681 		screen_char(off, row, col);
1682 	}
1683 	if (has_mbyte)
1684 	{
1685 	    off += mbyte_cells;
1686 	    col += mbyte_cells;
1687 	    ptr += mbyte_blen;
1688 	    if (clear_next_cell)
1689 	    {
1690 		// This only happens at the end, display one space next.
1691 		ptr = (char_u *)" ";
1692 		len = -1;
1693 	    }
1694 	}
1695 	else
1696 	{
1697 	    ++off;
1698 	    ++col;
1699 	    ++ptr;
1700 	}
1701     }
1702 
1703     // If we detected the next character needs to be redrawn, but the text
1704     // doesn't extend up to there, update the character here.
1705     if (force_redraw_next && col < screen_Columns)
1706     {
1707 	if (enc_dbcs != 0 && dbcs_off2cells(off, max_off) > 1)
1708 	    screen_char_2(off, row, col);
1709 	else
1710 	    screen_char(off, row, col);
1711     }
1712 }
1713 
1714 #if defined(FEAT_SEARCH_EXTRA) || defined(PROTO)
1715 /*
1716  * Prepare for 'hlsearch' highlighting.
1717  */
1718     void
1719 start_search_hl(void)
1720 {
1721     if (p_hls && !no_hlsearch)
1722     {
1723 	end_search_hl();  // just in case it wasn't called before
1724 	last_pat_prog(&screen_search_hl.rm);
1725 	screen_search_hl.attr = HL_ATTR(HLF_L);
1726 # ifdef FEAT_RELTIME
1727 	// Set the time limit to 'redrawtime'.
1728 	profile_setlimit(p_rdt, &screen_search_hl.tm);
1729 # endif
1730     }
1731 }
1732 
1733 /*
1734  * Clean up for 'hlsearch' highlighting.
1735  */
1736     void
1737 end_search_hl(void)
1738 {
1739     if (screen_search_hl.rm.regprog != NULL)
1740     {
1741 	vim_regfree(screen_search_hl.rm.regprog);
1742 	screen_search_hl.rm.regprog = NULL;
1743     }
1744 }
1745 #endif
1746 
1747       static void
1748 screen_start_highlight(int attr)
1749 {
1750     attrentry_T *aep = NULL;
1751 
1752     screen_attr = attr;
1753     if (full_screen
1754 #ifdef MSWIN
1755 		    && termcap_active
1756 #endif
1757 				       )
1758     {
1759 #ifdef FEAT_GUI
1760 	if (gui.in_use)
1761 	{
1762 	    char	buf[20];
1763 
1764 	    // The GUI handles this internally.
1765 	    sprintf(buf, IF_EB("\033|%dh", ESC_STR "|%dh"), attr);
1766 	    OUT_STR(buf);
1767 	}
1768 	else
1769 #endif
1770 	{
1771 	    if (attr > HL_ALL)				// special HL attr.
1772 	    {
1773 		if (IS_CTERM)
1774 		    aep = syn_cterm_attr2entry(attr);
1775 		else
1776 		    aep = syn_term_attr2entry(attr);
1777 		if (aep == NULL)	    // did ":syntax clear"
1778 		    attr = 0;
1779 		else
1780 		    attr = aep->ae_attr;
1781 	    }
1782 #if defined(FEAT_VTP) && defined(FEAT_TERMGUICOLORS)
1783 	    if (use_vtp())
1784 	    {
1785 		guicolor_T  defguifg, defguibg;
1786 		int	    defctermfg, defctermbg;
1787 
1788 		// If FG and BG are unset, the color is undefined when
1789 		// BOLD+INVERSE. Use Normal as the default value.
1790 		get_default_console_color(&defctermfg, &defctermbg, &defguifg,
1791 								    &defguibg);
1792 
1793 		if (p_tgc)
1794 		{
1795 		    if (aep == NULL || COLOR_INVALID(aep->ae_u.cterm.fg_rgb))
1796 			term_fg_rgb_color(defguifg);
1797 		    if (aep == NULL || COLOR_INVALID(aep->ae_u.cterm.bg_rgb))
1798 			term_bg_rgb_color(defguibg);
1799 		}
1800 		else if (t_colors >= 256)
1801 		{
1802 		    if (aep == NULL || aep->ae_u.cterm.fg_color == 0)
1803 			term_fg_color(defctermfg);
1804 		    if (aep == NULL || aep->ae_u.cterm.bg_color == 0)
1805 			term_bg_color(defctermbg);
1806 		}
1807 	    }
1808 #endif
1809 	    if ((attr & HL_BOLD) && *T_MD != NUL)	// bold
1810 		out_str(T_MD);
1811 	    else if (aep != NULL && cterm_normal_fg_bold && (
1812 #ifdef FEAT_TERMGUICOLORS
1813 			p_tgc && aep->ae_u.cterm.fg_rgb != CTERMCOLOR
1814 			  ? aep->ae_u.cterm.fg_rgb != INVALCOLOR
1815 			  :
1816 #endif
1817 			    t_colors > 1 && aep->ae_u.cterm.fg_color))
1818 		// If the Normal FG color has BOLD attribute and the new HL
1819 		// has a FG color defined, clear BOLD.
1820 		out_str(T_ME);
1821 	    if ((attr & HL_STANDOUT) && *T_SO != NUL)	// standout
1822 		out_str(T_SO);
1823 	    if ((attr & HL_UNDERCURL) && *T_UCS != NUL) // undercurl
1824 		out_str(T_UCS);
1825 	    if (((attr & HL_UNDERLINE)	    // underline or undercurl
1826 			|| ((attr & HL_UNDERCURL) && *T_UCS == NUL))
1827 		    && *T_US != NUL)
1828 		out_str(T_US);
1829 	    if ((attr & HL_ITALIC) && *T_CZH != NUL)	// italic
1830 		out_str(T_CZH);
1831 	    if ((attr & HL_INVERSE) && *T_MR != NUL)	// inverse (reverse)
1832 		out_str(T_MR);
1833 	    if ((attr & HL_STRIKETHROUGH) && *T_STS != NUL)	// strike
1834 		out_str(T_STS);
1835 
1836 	    /*
1837 	     * Output the color or start string after bold etc., in case the
1838 	     * bold etc. override the color setting.
1839 	     */
1840 	    if (aep != NULL)
1841 	    {
1842 #ifdef FEAT_TERMGUICOLORS
1843 		// When 'termguicolors' is set but fg or bg is unset,
1844 		// fall back to the cterm colors.   This helps for SpellBad,
1845 		// where the GUI uses a red undercurl.
1846 		if (p_tgc && aep->ae_u.cterm.fg_rgb != CTERMCOLOR)
1847 		{
1848 		    if (aep->ae_u.cterm.fg_rgb != INVALCOLOR)
1849 			term_fg_rgb_color(aep->ae_u.cterm.fg_rgb);
1850 		}
1851 		else
1852 #endif
1853 		if (t_colors > 1)
1854 		{
1855 		    if (aep->ae_u.cterm.fg_color)
1856 			term_fg_color(aep->ae_u.cterm.fg_color - 1);
1857 		}
1858 #ifdef FEAT_TERMGUICOLORS
1859 		if (p_tgc && aep->ae_u.cterm.bg_rgb != CTERMCOLOR)
1860 		{
1861 		    if (aep->ae_u.cterm.bg_rgb != INVALCOLOR)
1862 			term_bg_rgb_color(aep->ae_u.cterm.bg_rgb);
1863 		}
1864 		else
1865 #endif
1866 		if (t_colors > 1)
1867 		{
1868 		    if (aep->ae_u.cterm.bg_color)
1869 			term_bg_color(aep->ae_u.cterm.bg_color - 1);
1870 		}
1871 #ifdef FEAT_TERMGUICOLORS
1872 		if (p_tgc && aep->ae_u.cterm.ul_rgb != CTERMCOLOR)
1873 		{
1874 		    if (aep->ae_u.cterm.ul_rgb != INVALCOLOR)
1875 			term_ul_rgb_color(aep->ae_u.cterm.ul_rgb);
1876 		}
1877 		else
1878 #endif
1879 		if (t_colors > 1)
1880 		{
1881 		    if (aep->ae_u.cterm.ul_color)
1882 			term_ul_color(aep->ae_u.cterm.ul_color - 1);
1883 		}
1884 
1885 		if (!IS_CTERM)
1886 		{
1887 		    if (aep->ae_u.term.start != NULL)
1888 			out_str(aep->ae_u.term.start);
1889 		}
1890 	    }
1891 	}
1892     }
1893 }
1894 
1895       void
1896 screen_stop_highlight(void)
1897 {
1898     int	    do_ME = FALSE;	    // output T_ME code
1899 #if defined(FEAT_VTP) && defined(FEAT_TERMGUICOLORS)
1900     int	    do_ME_fg = FALSE, do_ME_bg = FALSE;
1901 #endif
1902 
1903     if (screen_attr != 0
1904 #ifdef MSWIN
1905 			&& termcap_active
1906 #endif
1907 					   )
1908     {
1909 #ifdef FEAT_GUI
1910 	if (gui.in_use)
1911 	{
1912 	    char	buf[20];
1913 
1914 	    // use internal GUI code
1915 	    sprintf(buf, IF_EB("\033|%dH", ESC_STR "|%dH"), screen_attr);
1916 	    OUT_STR(buf);
1917 	}
1918 	else
1919 #endif
1920 	{
1921 	    if (screen_attr > HL_ALL)			// special HL attr.
1922 	    {
1923 		attrentry_T *aep;
1924 
1925 		if (IS_CTERM)
1926 		{
1927 		    /*
1928 		     * Assume that t_me restores the original colors!
1929 		     */
1930 		    aep = syn_cterm_attr2entry(screen_attr);
1931 		    if (aep != NULL && ((
1932 #ifdef FEAT_TERMGUICOLORS
1933 			    p_tgc && aep->ae_u.cterm.fg_rgb != CTERMCOLOR
1934 				? aep->ae_u.cterm.fg_rgb != INVALCOLOR
1935 # ifdef FEAT_VTP
1936 				    ? !(do_ME_fg = TRUE) : (do_ME_fg = FALSE)
1937 # endif
1938 				:
1939 #endif
1940 				aep->ae_u.cterm.fg_color) || (
1941 #ifdef FEAT_TERMGUICOLORS
1942 			    p_tgc && aep->ae_u.cterm.bg_rgb != CTERMCOLOR
1943 				? aep->ae_u.cterm.bg_rgb != INVALCOLOR
1944 # ifdef FEAT_VTP
1945 				    ? !(do_ME_bg = TRUE) : (do_ME_bg = FALSE)
1946 # endif
1947 				:
1948 #endif
1949 				aep->ae_u.cterm.bg_color)))
1950 			do_ME = TRUE;
1951 #if defined(FEAT_VTP) && defined(FEAT_TERMGUICOLORS)
1952 		    if (use_vtp())
1953 		    {
1954 			if (do_ME_fg && do_ME_bg)
1955 			    do_ME = TRUE;
1956 
1957 			// FG and BG cannot be separated in T_ME, which is not
1958 			// efficient.
1959 			if (!do_ME && do_ME_fg)
1960 			    out_str((char_u *)"\033|39m"); // restore FG
1961 			if (!do_ME && do_ME_bg)
1962 			    out_str((char_u *)"\033|49m"); // restore BG
1963 		    }
1964 		    else
1965 		    {
1966 			// Process FG and BG at once.
1967 			if (!do_ME)
1968 			    do_ME = do_ME_fg | do_ME_bg;
1969 		    }
1970 #endif
1971 		}
1972 		else
1973 		{
1974 		    aep = syn_term_attr2entry(screen_attr);
1975 		    if (aep != NULL && aep->ae_u.term.stop != NULL)
1976 		    {
1977 			if (STRCMP(aep->ae_u.term.stop, T_ME) == 0)
1978 			    do_ME = TRUE;
1979 			else
1980 			    out_str(aep->ae_u.term.stop);
1981 		    }
1982 		}
1983 		if (aep == NULL)	    // did ":syntax clear"
1984 		    screen_attr = 0;
1985 		else
1986 		    screen_attr = aep->ae_attr;
1987 	    }
1988 
1989 	    /*
1990 	     * Often all ending-codes are equal to T_ME.  Avoid outputting the
1991 	     * same sequence several times.
1992 	     */
1993 	    if (screen_attr & HL_STANDOUT)
1994 	    {
1995 		if (STRCMP(T_SE, T_ME) == 0)
1996 		    do_ME = TRUE;
1997 		else
1998 		    out_str(T_SE);
1999 	    }
2000 	    if ((screen_attr & HL_UNDERCURL) && *T_UCE != NUL)
2001 	    {
2002 		if (STRCMP(T_UCE, T_ME) == 0)
2003 		    do_ME = TRUE;
2004 		else
2005 		    out_str(T_UCE);
2006 	    }
2007 	    if ((screen_attr & HL_UNDERLINE)
2008 			    || ((screen_attr & HL_UNDERCURL) && *T_UCE == NUL))
2009 	    {
2010 		if (STRCMP(T_UE, T_ME) == 0)
2011 		    do_ME = TRUE;
2012 		else
2013 		    out_str(T_UE);
2014 	    }
2015 	    if (screen_attr & HL_ITALIC)
2016 	    {
2017 		if (STRCMP(T_CZR, T_ME) == 0)
2018 		    do_ME = TRUE;
2019 		else
2020 		    out_str(T_CZR);
2021 	    }
2022 	    if (screen_attr & HL_STRIKETHROUGH)
2023 	    {
2024 		if (STRCMP(T_STE, T_ME) == 0)
2025 		    do_ME = TRUE;
2026 		else
2027 		    out_str(T_STE);
2028 	    }
2029 	    if (do_ME || (screen_attr & (HL_BOLD | HL_INVERSE)))
2030 		out_str(T_ME);
2031 
2032 #ifdef FEAT_TERMGUICOLORS
2033 	    if (p_tgc)
2034 	    {
2035 		if (cterm_normal_fg_gui_color != INVALCOLOR)
2036 		    term_fg_rgb_color(cterm_normal_fg_gui_color);
2037 		if (cterm_normal_bg_gui_color != INVALCOLOR)
2038 		    term_bg_rgb_color(cterm_normal_bg_gui_color);
2039 		if (cterm_normal_ul_gui_color != INVALCOLOR)
2040 		    term_ul_rgb_color(cterm_normal_ul_gui_color);
2041 	    }
2042 	    else
2043 #endif
2044 	    {
2045 		if (t_colors > 1)
2046 		{
2047 		    // set Normal cterm colors
2048 		    if (cterm_normal_fg_color != 0)
2049 			term_fg_color(cterm_normal_fg_color - 1);
2050 		    if (cterm_normal_bg_color != 0)
2051 			term_bg_color(cterm_normal_bg_color - 1);
2052 		    if (cterm_normal_ul_color != 0)
2053 			term_ul_color(cterm_normal_ul_color - 1);
2054 		    if (cterm_normal_fg_bold)
2055 			out_str(T_MD);
2056 		}
2057 	    }
2058 	}
2059     }
2060     screen_attr = 0;
2061 }
2062 
2063 /*
2064  * Reset the colors for a cterm.  Used when leaving Vim.
2065  * The machine specific code may override this again.
2066  */
2067     void
2068 reset_cterm_colors(void)
2069 {
2070     if (IS_CTERM)
2071     {
2072 	// set Normal cterm colors
2073 #ifdef FEAT_TERMGUICOLORS
2074 	if (p_tgc ? (cterm_normal_fg_gui_color != INVALCOLOR
2075 		 || cterm_normal_bg_gui_color != INVALCOLOR)
2076 		: (cterm_normal_fg_color > 0 || cterm_normal_bg_color > 0))
2077 #else
2078 	if (cterm_normal_fg_color > 0 || cterm_normal_bg_color > 0)
2079 #endif
2080 	{
2081 	    out_str(T_OP);
2082 	    screen_attr = -1;
2083 	}
2084 	if (cterm_normal_fg_bold)
2085 	{
2086 	    out_str(T_ME);
2087 	    screen_attr = -1;
2088 	}
2089     }
2090 }
2091 
2092 /*
2093  * Put character ScreenLines["off"] on the screen at position "row" and "col",
2094  * using the attributes from ScreenAttrs["off"].
2095  */
2096     void
2097 screen_char(unsigned off, int row, int col)
2098 {
2099     int		attr;
2100 
2101     // Check for illegal values, just in case (could happen just after
2102     // resizing).
2103     if (row >= screen_Rows || col >= screen_Columns)
2104 	return;
2105 
2106     // Skip if under the popup menu.
2107     // Popup windows with zindex higher than POPUPMENU_ZINDEX go on top.
2108     if (pum_under_menu(row, col)
2109 #ifdef FEAT_PROP_POPUP
2110 	    && screen_zindex <= POPUPMENU_ZINDEX
2111 #endif
2112 	    )
2113 	return;
2114 #ifdef FEAT_PROP_POPUP
2115     if (blocked_by_popup(row, col))
2116 	return;
2117 #endif
2118 
2119     // Outputting a character in the last cell on the screen may scroll the
2120     // screen up.  Only do it when the "xn" termcap property is set, otherwise
2121     // mark the character invalid (update it when scrolled up).
2122     if (*T_XN == NUL
2123 	    && row == screen_Rows - 1 && col == screen_Columns - 1
2124 #ifdef FEAT_RIGHTLEFT
2125 	    // account for first command-line character in rightleft mode
2126 	    && !cmdmsg_rl
2127 #endif
2128        )
2129     {
2130 	ScreenAttrs[off] = (sattr_T)-1;
2131 	return;
2132     }
2133 
2134     /*
2135      * Stop highlighting first, so it's easier to move the cursor.
2136      */
2137     if (screen_char_attr != 0)
2138 	attr = screen_char_attr;
2139     else
2140 	attr = ScreenAttrs[off];
2141     if (screen_attr != attr)
2142 	screen_stop_highlight();
2143 
2144     windgoto(row, col);
2145 
2146     if (screen_attr != attr)
2147 	screen_start_highlight(attr);
2148 
2149     if (enc_utf8 && ScreenLinesUC[off] != 0)
2150     {
2151 	char_u	    buf[MB_MAXBYTES + 1];
2152 
2153 	if (utf_ambiguous_width(ScreenLinesUC[off]))
2154 	{
2155 	    if (*p_ambw == 'd'
2156 #ifdef FEAT_GUI
2157 		    && !gui.in_use
2158 #endif
2159 		    )
2160 	    {
2161 		// Clear the two screen cells. If the character is actually
2162 		// single width it won't change the second cell.
2163 		out_str((char_u *)"  ");
2164 		term_windgoto(row, col);
2165 	    }
2166 	    // not sure where the cursor is after drawing the ambiguous width
2167 	    // character
2168 	    screen_cur_col = 9999;
2169 	}
2170 	else if (utf_char2cells(ScreenLinesUC[off]) > 1)
2171 	    ++screen_cur_col;
2172 
2173 	// Convert the UTF-8 character to bytes and write it.
2174 	buf[utfc_char2bytes(off, buf)] = NUL;
2175 	out_str(buf);
2176     }
2177     else
2178     {
2179 	out_flush_check();
2180 	out_char(ScreenLines[off]);
2181 	// double-byte character in single-width cell
2182 	if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
2183 	    out_char(ScreenLines2[off]);
2184     }
2185 
2186     screen_cur_col++;
2187 }
2188 
2189 /*
2190  * Used for enc_dbcs only: Put one double-wide character at ScreenLines["off"]
2191  * on the screen at position 'row' and 'col'.
2192  * The attributes of the first byte is used for all.  This is required to
2193  * output the two bytes of a double-byte character with nothing in between.
2194  */
2195     static void
2196 screen_char_2(unsigned off, int row, int col)
2197 {
2198     // Check for illegal values (could be wrong when screen was resized).
2199     if (off + 1 >= (unsigned)(screen_Rows * screen_Columns))
2200 	return;
2201 
2202     // Outputting the last character on the screen may scrollup the screen.
2203     // Don't to it!  Mark the character invalid (update it when scrolled up)
2204     if (row == screen_Rows - 1 && col >= screen_Columns - 2)
2205     {
2206 	ScreenAttrs[off] = (sattr_T)-1;
2207 	return;
2208     }
2209 
2210     // Output the first byte normally (positions the cursor), then write the
2211     // second byte directly.
2212     screen_char(off, row, col);
2213     out_char(ScreenLines[off + 1]);
2214     ++screen_cur_col;
2215 }
2216 
2217 /*
2218  * Draw a rectangle of the screen, inverted when "invert" is TRUE.
2219  * This uses the contents of ScreenLines[] and doesn't change it.
2220  */
2221     void
2222 screen_draw_rectangle(
2223     int		row,
2224     int		col,
2225     int		height,
2226     int		width,
2227     int		invert)
2228 {
2229     int		r, c;
2230     int		off;
2231     int		max_off;
2232 
2233     // Can't use ScreenLines unless initialized
2234     if (ScreenLines == NULL)
2235 	return;
2236 
2237     if (invert)
2238 	screen_char_attr = HL_INVERSE;
2239     for (r = row; r < row + height; ++r)
2240     {
2241 	off = LineOffset[r];
2242 	max_off = off + screen_Columns;
2243 	for (c = col; c < col + width; ++c)
2244 	{
2245 	    if (enc_dbcs != 0 && dbcs_off2cells(off + c, max_off) > 1)
2246 	    {
2247 		screen_char_2(off + c, r, c);
2248 		++c;
2249 	    }
2250 	    else
2251 	    {
2252 		screen_char(off + c, r, c);
2253 		if (utf_off2cells(off + c, max_off) > 1)
2254 		    ++c;
2255 	    }
2256 	}
2257     }
2258     screen_char_attr = 0;
2259 }
2260 
2261 /*
2262  * Redraw the characters for a vertically split window.
2263  */
2264     static void
2265 redraw_block(int row, int end, win_T *wp)
2266 {
2267     int		col;
2268     int		width;
2269 
2270 # ifdef FEAT_CLIPBOARD
2271     clip_may_clear_selection(row, end - 1);
2272 # endif
2273 
2274     if (wp == NULL)
2275     {
2276 	col = 0;
2277 	width = Columns;
2278     }
2279     else
2280     {
2281 	col = wp->w_wincol;
2282 	width = wp->w_width;
2283     }
2284     screen_draw_rectangle(row, col, end - row, width, FALSE);
2285 }
2286 
2287     void
2288 space_to_screenline(int off, int attr)
2289 {
2290     ScreenLines[off] = ' ';
2291     ScreenAttrs[off] = attr;
2292     if (enc_utf8)
2293 	ScreenLinesUC[off] = 0;
2294 }
2295 
2296 /*
2297  * Fill the screen from 'start_row' to 'end_row', from 'start_col' to 'end_col'
2298  * with character 'c1' in first column followed by 'c2' in the other columns.
2299  * Use attributes 'attr'.
2300  */
2301     void
2302 screen_fill(
2303 	int	start_row,
2304 	int	end_row,
2305 	int	start_col,
2306 	int	end_col,
2307 	int	c1,
2308 	int	c2,
2309 	int	attr)
2310 {
2311     int	    row;
2312     int	    col;
2313     int	    off;
2314     int	    end_off;
2315     int	    did_delete;
2316     int	    c;
2317     int	    norm_term;
2318 #if defined(FEAT_GUI) || defined(UNIX)
2319     int	    force_next = FALSE;
2320 #endif
2321 
2322     if (end_row > screen_Rows)		// safety check
2323 	end_row = screen_Rows;
2324     if (end_col > screen_Columns)	// safety check
2325 	end_col = screen_Columns;
2326     if (ScreenLines == NULL
2327 	    || start_row >= end_row
2328 	    || start_col >= end_col)	// nothing to do
2329 	return;
2330 
2331     // it's a "normal" terminal when not in a GUI or cterm
2332     norm_term = (
2333 #ifdef FEAT_GUI
2334 	    !gui.in_use &&
2335 #endif
2336 	    !IS_CTERM);
2337     for (row = start_row; row < end_row; ++row)
2338     {
2339 	if (has_mbyte
2340 #ifdef FEAT_GUI
2341 		&& !gui.in_use
2342 #endif
2343 	   )
2344 	{
2345 	    // When drawing over the right halve of a double-wide char clear
2346 	    // out the left halve.  When drawing over the left halve of a
2347 	    // double wide-char clear out the right halve.  Only needed in a
2348 	    // terminal.
2349 	    if (start_col > 0 && mb_fix_col(start_col, row) != start_col)
2350 		screen_puts_len((char_u *)" ", 1, row, start_col - 1, 0);
2351 	    if (end_col < screen_Columns && mb_fix_col(end_col, row) != end_col)
2352 		screen_puts_len((char_u *)" ", 1, row, end_col, 0);
2353 	}
2354 	/*
2355 	 * Try to use delete-line termcap code, when no attributes or in a
2356 	 * "normal" terminal, where a bold/italic space is just a
2357 	 * space.
2358 	 */
2359 	did_delete = FALSE;
2360 	if (c2 == ' '
2361 		&& end_col == Columns
2362 		&& can_clear(T_CE)
2363 		&& (attr == 0
2364 		    || (norm_term
2365 			&& attr <= HL_ALL
2366 			&& ((attr & ~(HL_BOLD | HL_ITALIC)) == 0))))
2367 	{
2368 	    /*
2369 	     * check if we really need to clear something
2370 	     */
2371 	    col = start_col;
2372 	    if (c1 != ' ')			// don't clear first char
2373 		++col;
2374 
2375 	    off = LineOffset[row] + col;
2376 	    end_off = LineOffset[row] + end_col;
2377 
2378 	    // skip blanks (used often, keep it fast!)
2379 	    if (enc_utf8)
2380 		while (off < end_off && ScreenLines[off] == ' '
2381 			  && ScreenAttrs[off] == 0 && ScreenLinesUC[off] == 0)
2382 		    ++off;
2383 	    else
2384 		while (off < end_off && ScreenLines[off] == ' '
2385 						     && ScreenAttrs[off] == 0)
2386 		    ++off;
2387 	    if (off < end_off)		// something to be cleared
2388 	    {
2389 		col = off - LineOffset[row];
2390 		screen_stop_highlight();
2391 		term_windgoto(row, col);// clear rest of this screen line
2392 		out_str(T_CE);
2393 		screen_start();		// don't know where cursor is now
2394 		col = end_col - col;
2395 		while (col--)		// clear chars in ScreenLines
2396 		{
2397 		    space_to_screenline(off, 0);
2398 		    ++off;
2399 		}
2400 	    }
2401 	    did_delete = TRUE;		// the chars are cleared now
2402 	}
2403 
2404 	off = LineOffset[row] + start_col;
2405 	c = c1;
2406 	for (col = start_col; col < end_col; ++col)
2407 	{
2408 	    if ((ScreenLines[off] != c
2409 		    || (enc_utf8 && (int)ScreenLinesUC[off]
2410 						       != (c >= 0x80 ? c : 0))
2411 		    || ScreenAttrs[off] != attr
2412 #if defined(FEAT_GUI) || defined(UNIX)
2413 		    || force_next
2414 #endif
2415 		    )
2416 #ifdef FEAT_PROP_POPUP
2417 		    // Skip if under a(nother) popup.
2418 		    && !blocked_by_popup(row, col)
2419 #endif
2420 	       )
2421 	    {
2422 #if defined(FEAT_GUI) || defined(UNIX)
2423 		// The bold trick may make a single row of pixels appear in
2424 		// the next character.  When a bold character is removed, the
2425 		// next character should be redrawn too.  This happens for our
2426 		// own GUI and for some xterms.
2427 		if (
2428 # ifdef FEAT_GUI
2429 			gui.in_use
2430 # endif
2431 # if defined(FEAT_GUI) && defined(UNIX)
2432 			||
2433 # endif
2434 # ifdef UNIX
2435 			term_is_xterm
2436 # endif
2437 		   )
2438 		{
2439 		    if (ScreenLines[off] != ' '
2440 			    && (ScreenAttrs[off] > HL_ALL
2441 				|| ScreenAttrs[off] & HL_BOLD))
2442 			force_next = TRUE;
2443 		    else
2444 			force_next = FALSE;
2445 		}
2446 #endif
2447 		ScreenLines[off] = c;
2448 		if (enc_utf8)
2449 		{
2450 		    if (c >= 0x80)
2451 		    {
2452 			ScreenLinesUC[off] = c;
2453 			ScreenLinesC[0][off] = 0;
2454 		    }
2455 		    else
2456 			ScreenLinesUC[off] = 0;
2457 		}
2458 		ScreenAttrs[off] = attr;
2459 		if (!did_delete || c != ' ')
2460 		    screen_char(off, row, col);
2461 	    }
2462 	    ++off;
2463 	    if (col == start_col)
2464 	    {
2465 		if (did_delete)
2466 		    break;
2467 		c = c2;
2468 	    }
2469 	}
2470 	if (end_col == Columns)
2471 	    LineWraps[row] = FALSE;
2472 	if (row == Rows - 1)		// overwritten the command line
2473 	{
2474 	    redraw_cmdline = TRUE;
2475 	    if (start_col == 0 && end_col == Columns
2476 		    && c1 == ' ' && c2 == ' ' && attr == 0)
2477 		clear_cmdline = FALSE;	// command line has been cleared
2478 	    if (start_col == 0)
2479 		mode_displayed = FALSE; // mode cleared or overwritten
2480 	}
2481     }
2482 }
2483 
2484 /*
2485  * Check if there should be a delay.  Used before clearing or redrawing the
2486  * screen or the command line.
2487  */
2488     void
2489 check_for_delay(int check_msg_scroll)
2490 {
2491     if ((emsg_on_display || (check_msg_scroll && msg_scroll))
2492 	    && !did_wait_return
2493 	    && emsg_silent == 0
2494 	    && !in_assert_fails)
2495     {
2496 	out_flush();
2497 	ui_delay(1006L, TRUE);
2498 	emsg_on_display = FALSE;
2499 	if (check_msg_scroll)
2500 	    msg_scroll = FALSE;
2501     }
2502 }
2503 
2504 /*
2505  * Init TabPageIdxs[] to zero: Clicking outside of tabs has no effect.
2506  */
2507     static void
2508 clear_TabPageIdxs(void)
2509 {
2510     int		scol;
2511 
2512     for (scol = 0; scol < Columns; ++scol)
2513 	TabPageIdxs[scol] = 0;
2514 }
2515 
2516 /*
2517  * screen_valid -  allocate screen buffers if size changed
2518  *   If "doclear" is TRUE: clear screen if it has been resized.
2519  *	Returns TRUE if there is a valid screen to write to.
2520  *	Returns FALSE when starting up and screen not initialized yet.
2521  */
2522     int
2523 screen_valid(int doclear)
2524 {
2525     screenalloc(doclear);	   // allocate screen buffers if size changed
2526     return (ScreenLines != NULL);
2527 }
2528 
2529 /*
2530  * Resize the shell to Rows and Columns.
2531  * Allocate ScreenLines[] and associated items.
2532  *
2533  * There may be some time between setting Rows and Columns and (re)allocating
2534  * ScreenLines[].  This happens when starting up and when (manually) changing
2535  * the shell size.  Always use screen_Rows and screen_Columns to access items
2536  * in ScreenLines[].  Use Rows and Columns for positioning text etc. where the
2537  * final size of the shell is needed.
2538  */
2539     void
2540 screenalloc(int doclear)
2541 {
2542     int		    new_row, old_row;
2543 #ifdef FEAT_GUI
2544     int		    old_Rows;
2545 #endif
2546     win_T	    *wp;
2547     int		    outofmem = FALSE;
2548     int		    len;
2549     schar_T	    *new_ScreenLines;
2550     u8char_T	    *new_ScreenLinesUC = NULL;
2551     u8char_T	    *new_ScreenLinesC[MAX_MCO];
2552     schar_T	    *new_ScreenLines2 = NULL;
2553     int		    i;
2554     sattr_T	    *new_ScreenAttrs;
2555     unsigned	    *new_LineOffset;
2556     char_u	    *new_LineWraps;
2557     short	    *new_TabPageIdxs;
2558 #ifdef FEAT_PROP_POPUP
2559     short	    *new_popup_mask;
2560     short	    *new_popup_mask_next;
2561     char	    *new_popup_transparent;
2562 #endif
2563     tabpage_T	    *tp;
2564     static int	    entered = FALSE;		// avoid recursiveness
2565     static int	    done_outofmem_msg = FALSE;	// did outofmem message
2566     int		    retry_count = 0;
2567 
2568 retry:
2569     /*
2570      * Allocation of the screen buffers is done only when the size changes and
2571      * when Rows and Columns have been set and we have started doing full
2572      * screen stuff.
2573      */
2574     if ((ScreenLines != NULL
2575 		&& Rows == screen_Rows
2576 		&& Columns == screen_Columns
2577 		&& enc_utf8 == (ScreenLinesUC != NULL)
2578 		&& (enc_dbcs == DBCS_JPNU) == (ScreenLines2 != NULL)
2579 		&& p_mco == Screen_mco)
2580 	    || Rows == 0
2581 	    || Columns == 0
2582 	    || (!full_screen && ScreenLines == NULL))
2583 	return;
2584 
2585     /*
2586      * It's possible that we produce an out-of-memory message below, which
2587      * will cause this function to be called again.  To break the loop, just
2588      * return here.
2589      */
2590     if (entered)
2591 	return;
2592     entered = TRUE;
2593 
2594     /*
2595      * Note that the window sizes are updated before reallocating the arrays,
2596      * thus we must not redraw here!
2597      */
2598     ++RedrawingDisabled;
2599 
2600     win_new_shellsize();    // fit the windows in the new sized shell
2601 
2602 #ifdef FEAT_GUI_HAIKU
2603     vim_lock_screen();  // be safe, put it here
2604 #endif
2605 
2606     comp_col();		// recompute columns for shown command and ruler
2607 
2608     /*
2609      * We're changing the size of the screen.
2610      * - Allocate new arrays for ScreenLines and ScreenAttrs.
2611      * - Move lines from the old arrays into the new arrays, clear extra
2612      *	 lines (unless the screen is going to be cleared).
2613      * - Free the old arrays.
2614      *
2615      * If anything fails, make ScreenLines NULL, so we don't do anything!
2616      * Continuing with the old ScreenLines may result in a crash, because the
2617      * size is wrong.
2618      */
2619     FOR_ALL_TAB_WINDOWS(tp, wp)
2620 	win_free_lsize(wp);
2621     if (aucmd_win != NULL)
2622 	win_free_lsize(aucmd_win);
2623 #ifdef FEAT_PROP_POPUP
2624     // global popup windows
2625     FOR_ALL_POPUPWINS(wp)
2626 	win_free_lsize(wp);
2627     // tab-local popup windows
2628     FOR_ALL_TABPAGES(tp)
2629 	FOR_ALL_POPUPWINS_IN_TAB(tp, wp)
2630 	    win_free_lsize(wp);
2631 #endif
2632 
2633     new_ScreenLines = LALLOC_MULT(schar_T, (Rows + 1) * Columns);
2634     vim_memset(new_ScreenLinesC, 0, sizeof(u8char_T *) * MAX_MCO);
2635     if (enc_utf8)
2636     {
2637 	new_ScreenLinesUC = LALLOC_MULT(u8char_T, (Rows + 1) * Columns);
2638 	for (i = 0; i < p_mco; ++i)
2639 	    new_ScreenLinesC[i] = LALLOC_CLEAR_MULT(u8char_T,
2640 							 (Rows + 1) * Columns);
2641     }
2642     if (enc_dbcs == DBCS_JPNU)
2643 	new_ScreenLines2 = LALLOC_MULT(schar_T, (Rows + 1) * Columns);
2644     new_ScreenAttrs = LALLOC_MULT(sattr_T, (Rows + 1) * Columns);
2645     new_LineOffset = LALLOC_MULT(unsigned, Rows);
2646     new_LineWraps = LALLOC_MULT(char_u, Rows);
2647     new_TabPageIdxs = LALLOC_MULT(short, Columns);
2648 #ifdef FEAT_PROP_POPUP
2649     new_popup_mask = LALLOC_MULT(short, Rows * Columns);
2650     new_popup_mask_next = LALLOC_MULT(short, Rows * Columns);
2651     new_popup_transparent = LALLOC_MULT(char, Rows * Columns);
2652 #endif
2653 
2654     FOR_ALL_TAB_WINDOWS(tp, wp)
2655     {
2656 	if (win_alloc_lines(wp) == FAIL)
2657 	{
2658 	    outofmem = TRUE;
2659 	    goto give_up;
2660 	}
2661     }
2662     if (aucmd_win != NULL && aucmd_win->w_lines == NULL
2663 					&& win_alloc_lines(aucmd_win) == FAIL)
2664 	outofmem = TRUE;
2665 #ifdef FEAT_PROP_POPUP
2666     // global popup windows
2667     FOR_ALL_POPUPWINS(wp)
2668 	if (win_alloc_lines(wp) == FAIL)
2669 	{
2670 	    outofmem = TRUE;
2671 	    goto give_up;
2672 	}
2673     // tab-local popup windows
2674     FOR_ALL_TABPAGES(tp)
2675 	FOR_ALL_POPUPWINS_IN_TAB(tp, wp)
2676 	    if (win_alloc_lines(wp) == FAIL)
2677 	    {
2678 		outofmem = TRUE;
2679 		goto give_up;
2680 	    }
2681 #endif
2682 
2683 give_up:
2684 
2685     for (i = 0; i < p_mco; ++i)
2686 	if (new_ScreenLinesC[i] == NULL)
2687 	    break;
2688     if (new_ScreenLines == NULL
2689 	    || (enc_utf8 && (new_ScreenLinesUC == NULL || i != p_mco))
2690 	    || (enc_dbcs == DBCS_JPNU && new_ScreenLines2 == NULL)
2691 	    || new_ScreenAttrs == NULL
2692 	    || new_LineOffset == NULL
2693 	    || new_LineWraps == NULL
2694 	    || new_TabPageIdxs == NULL
2695 #ifdef FEAT_PROP_POPUP
2696 	    || new_popup_mask == NULL
2697 	    || new_popup_mask_next == NULL
2698 	    || new_popup_transparent == NULL
2699 #endif
2700 	    || outofmem)
2701     {
2702 	if (ScreenLines != NULL || !done_outofmem_msg)
2703 	{
2704 	    // guess the size
2705 	    do_outofmem_msg((long_u)((Rows + 1) * Columns));
2706 
2707 	    // Remember we did this to avoid getting outofmem messages over
2708 	    // and over again.
2709 	    done_outofmem_msg = TRUE;
2710 	}
2711 	VIM_CLEAR(new_ScreenLines);
2712 	VIM_CLEAR(new_ScreenLinesUC);
2713 	for (i = 0; i < p_mco; ++i)
2714 	    VIM_CLEAR(new_ScreenLinesC[i]);
2715 	VIM_CLEAR(new_ScreenLines2);
2716 	VIM_CLEAR(new_ScreenAttrs);
2717 	VIM_CLEAR(new_LineOffset);
2718 	VIM_CLEAR(new_LineWraps);
2719 	VIM_CLEAR(new_TabPageIdxs);
2720 #ifdef FEAT_PROP_POPUP
2721 	VIM_CLEAR(new_popup_mask);
2722 	VIM_CLEAR(new_popup_mask_next);
2723 	VIM_CLEAR(new_popup_transparent);
2724 #endif
2725     }
2726     else
2727     {
2728 	done_outofmem_msg = FALSE;
2729 
2730 	for (new_row = 0; new_row < Rows; ++new_row)
2731 	{
2732 	    new_LineOffset[new_row] = new_row * Columns;
2733 	    new_LineWraps[new_row] = FALSE;
2734 
2735 	    /*
2736 	     * If the screen is not going to be cleared, copy as much as
2737 	     * possible from the old screen to the new one and clear the rest
2738 	     * (used when resizing the window at the "--more--" prompt or when
2739 	     * executing an external command, for the GUI).
2740 	     */
2741 	    if (!doclear)
2742 	    {
2743 		(void)vim_memset(new_ScreenLines + new_row * Columns,
2744 				      ' ', (size_t)Columns * sizeof(schar_T));
2745 		if (enc_utf8)
2746 		{
2747 		    (void)vim_memset(new_ScreenLinesUC + new_row * Columns,
2748 				       0, (size_t)Columns * sizeof(u8char_T));
2749 		    for (i = 0; i < p_mco; ++i)
2750 			(void)vim_memset(new_ScreenLinesC[i]
2751 							  + new_row * Columns,
2752 				       0, (size_t)Columns * sizeof(u8char_T));
2753 		}
2754 		if (enc_dbcs == DBCS_JPNU)
2755 		    (void)vim_memset(new_ScreenLines2 + new_row * Columns,
2756 				       0, (size_t)Columns * sizeof(schar_T));
2757 		(void)vim_memset(new_ScreenAttrs + new_row * Columns,
2758 					0, (size_t)Columns * sizeof(sattr_T));
2759 		old_row = new_row + (screen_Rows - Rows);
2760 		if (old_row >= 0 && ScreenLines != NULL)
2761 		{
2762 		    if (screen_Columns < Columns)
2763 			len = screen_Columns;
2764 		    else
2765 			len = Columns;
2766 		    // When switching to utf-8 don't copy characters, they
2767 		    // may be invalid now.  Also when p_mco changes.
2768 		    if (!(enc_utf8 && ScreenLinesUC == NULL)
2769 						       && p_mco == Screen_mco)
2770 			mch_memmove(new_ScreenLines + new_LineOffset[new_row],
2771 				ScreenLines + LineOffset[old_row],
2772 				(size_t)len * sizeof(schar_T));
2773 		    if (enc_utf8 && ScreenLinesUC != NULL
2774 						       && p_mco == Screen_mco)
2775 		    {
2776 			mch_memmove(new_ScreenLinesUC + new_LineOffset[new_row],
2777 				ScreenLinesUC + LineOffset[old_row],
2778 				(size_t)len * sizeof(u8char_T));
2779 			for (i = 0; i < p_mco; ++i)
2780 			    mch_memmove(new_ScreenLinesC[i]
2781 						    + new_LineOffset[new_row],
2782 				ScreenLinesC[i] + LineOffset[old_row],
2783 				(size_t)len * sizeof(u8char_T));
2784 		    }
2785 		    if (enc_dbcs == DBCS_JPNU && ScreenLines2 != NULL)
2786 			mch_memmove(new_ScreenLines2 + new_LineOffset[new_row],
2787 				ScreenLines2 + LineOffset[old_row],
2788 				(size_t)len * sizeof(schar_T));
2789 		    mch_memmove(new_ScreenAttrs + new_LineOffset[new_row],
2790 			    ScreenAttrs + LineOffset[old_row],
2791 			    (size_t)len * sizeof(sattr_T));
2792 		}
2793 	    }
2794 	}
2795 	// Use the last line of the screen for the current line.
2796 	current_ScreenLine = new_ScreenLines + Rows * Columns;
2797 
2798 #ifdef FEAT_PROP_POPUP
2799 	vim_memset(new_popup_mask, 0, Rows * Columns * sizeof(short));
2800 	vim_memset(new_popup_transparent, 0, Rows * Columns * sizeof(char));
2801 #endif
2802     }
2803 
2804     free_screenlines();
2805 
2806     // NOTE: this may result in all pointers to become NULL.
2807     ScreenLines = new_ScreenLines;
2808     ScreenLinesUC = new_ScreenLinesUC;
2809     for (i = 0; i < p_mco; ++i)
2810 	ScreenLinesC[i] = new_ScreenLinesC[i];
2811     Screen_mco = p_mco;
2812     ScreenLines2 = new_ScreenLines2;
2813     ScreenAttrs = new_ScreenAttrs;
2814     LineOffset = new_LineOffset;
2815     LineWraps = new_LineWraps;
2816     TabPageIdxs = new_TabPageIdxs;
2817 #ifdef FEAT_PROP_POPUP
2818     popup_mask = new_popup_mask;
2819     popup_mask_next = new_popup_mask_next;
2820     popup_transparent = new_popup_transparent;
2821     popup_mask_refresh = TRUE;
2822 #endif
2823 
2824     // It's important that screen_Rows and screen_Columns reflect the actual
2825     // size of ScreenLines[].  Set them before calling anything.
2826 #ifdef FEAT_GUI
2827     old_Rows = screen_Rows;
2828 #endif
2829     screen_Rows = Rows;
2830     screen_Columns = Columns;
2831 
2832     must_redraw = CLEAR;	// need to clear the screen later
2833     if (doclear)
2834 	screenclear2();
2835 #ifdef FEAT_GUI
2836     else if (gui.in_use
2837 	    && !gui.starting
2838 	    && ScreenLines != NULL
2839 	    && old_Rows != Rows)
2840     {
2841 	gui_redraw_block(0, 0, (int)Rows - 1, (int)Columns - 1, 0);
2842 
2843 	// Adjust the position of the cursor, for when executing an external
2844 	// command.
2845 	if (msg_row >= Rows)		// Rows got smaller
2846 	    msg_row = Rows - 1;		// put cursor at last row
2847 	else if (Rows > old_Rows)	// Rows got bigger
2848 	    msg_row += Rows - old_Rows; // put cursor in same place
2849 	if (msg_col >= Columns)		// Columns got smaller
2850 	    msg_col = Columns - 1;	// put cursor at last column
2851     }
2852 #endif
2853     clear_TabPageIdxs();
2854 
2855 #ifdef FEAT_GUI_HAIKU
2856     vim_unlock_screen();
2857 #endif
2858 
2859     entered = FALSE;
2860     --RedrawingDisabled;
2861 
2862     /*
2863      * Do not apply autocommands more than 3 times to avoid an endless loop
2864      * in case applying autocommands always changes Rows or Columns.
2865      */
2866     if (starting == 0 && ++retry_count <= 3)
2867     {
2868 	apply_autocmds(EVENT_VIMRESIZED, NULL, NULL, FALSE, curbuf);
2869 	// In rare cases, autocommands may have altered Rows or Columns,
2870 	// jump back to check if we need to allocate the screen again.
2871 	goto retry;
2872     }
2873 }
2874 
2875     void
2876 free_screenlines(void)
2877 {
2878     int		i;
2879 
2880     VIM_CLEAR(ScreenLinesUC);
2881     for (i = 0; i < Screen_mco; ++i)
2882 	VIM_CLEAR(ScreenLinesC[i]);
2883     VIM_CLEAR(ScreenLines2);
2884     VIM_CLEAR(ScreenLines);
2885     VIM_CLEAR(ScreenAttrs);
2886     VIM_CLEAR(LineOffset);
2887     VIM_CLEAR(LineWraps);
2888     VIM_CLEAR(TabPageIdxs);
2889 #ifdef FEAT_PROP_POPUP
2890     VIM_CLEAR(popup_mask);
2891     VIM_CLEAR(popup_mask_next);
2892     VIM_CLEAR(popup_transparent);
2893 #endif
2894 }
2895 
2896     void
2897 screenclear(void)
2898 {
2899     check_for_delay(FALSE);
2900     screenalloc(FALSE);	    // allocate screen buffers if size changed
2901     screenclear2();	    // clear the screen
2902 }
2903 
2904     static void
2905 screenclear2(void)
2906 {
2907     int	    i;
2908 
2909     if (starting == NO_SCREEN || ScreenLines == NULL
2910 #ifdef FEAT_GUI
2911 	    || (gui.in_use && gui.starting)
2912 #endif
2913 	    )
2914 	return;
2915 
2916 #ifdef FEAT_GUI
2917     if (!gui.in_use)
2918 #endif
2919 	screen_attr = -1;	// force setting the Normal colors
2920     screen_stop_highlight();	// don't want highlighting here
2921 
2922 #ifdef FEAT_CLIPBOARD
2923     // disable selection without redrawing it
2924     clip_scroll_selection(9999);
2925 #endif
2926 
2927     // blank out ScreenLines
2928     for (i = 0; i < Rows; ++i)
2929     {
2930 	lineclear(LineOffset[i], (int)Columns, 0);
2931 	LineWraps[i] = FALSE;
2932     }
2933 
2934     if (can_clear(T_CL))
2935     {
2936 	out_str(T_CL);		// clear the display
2937 	clear_cmdline = FALSE;
2938 	mode_displayed = FALSE;
2939     }
2940     else
2941     {
2942 	// can't clear the screen, mark all chars with invalid attributes
2943 	for (i = 0; i < Rows; ++i)
2944 	    lineinvalid(LineOffset[i], (int)Columns);
2945 	clear_cmdline = TRUE;
2946     }
2947 
2948     screen_cleared = TRUE;	// can use contents of ScreenLines now
2949 
2950     win_rest_invalid(firstwin);
2951     redraw_cmdline = TRUE;
2952     redraw_tabline = TRUE;
2953     if (must_redraw == CLEAR)	// no need to clear again
2954 	must_redraw = NOT_VALID;
2955     compute_cmdrow();
2956     msg_row = cmdline_row;	// put cursor on last line for messages
2957     msg_col = 0;
2958     screen_start();		// don't know where cursor is now
2959     msg_scrolled = 0;		// can't scroll back
2960     msg_didany = FALSE;
2961     msg_didout = FALSE;
2962 }
2963 
2964 /*
2965  * Clear one line in ScreenLines.
2966  */
2967     static void
2968 lineclear(unsigned off, int width, int attr)
2969 {
2970     (void)vim_memset(ScreenLines + off, ' ', (size_t)width * sizeof(schar_T));
2971     if (enc_utf8)
2972 	(void)vim_memset(ScreenLinesUC + off, 0,
2973 					  (size_t)width * sizeof(u8char_T));
2974     (void)vim_memset(ScreenAttrs + off, attr, (size_t)width * sizeof(sattr_T));
2975 }
2976 
2977 /*
2978  * Mark one line in ScreenLines invalid by setting the attributes to an
2979  * invalid value.
2980  */
2981     static void
2982 lineinvalid(unsigned off, int width)
2983 {
2984     (void)vim_memset(ScreenAttrs + off, -1, (size_t)width * sizeof(sattr_T));
2985 }
2986 
2987 /*
2988  * To be called when characters were sent to the terminal directly, outputting
2989  * test on "screen_lnum".
2990  */
2991     void
2992 line_was_clobbered(int screen_lnum)
2993 {
2994     lineinvalid(LineOffset[screen_lnum], (int)Columns);
2995 }
2996 
2997 /*
2998  * Copy part of a Screenline for vertically split window "wp".
2999  */
3000     static void
3001 linecopy(int to, int from, win_T *wp)
3002 {
3003     unsigned	off_to = LineOffset[to] + wp->w_wincol;
3004     unsigned	off_from = LineOffset[from] + wp->w_wincol;
3005 
3006     mch_memmove(ScreenLines + off_to, ScreenLines + off_from,
3007 	    wp->w_width * sizeof(schar_T));
3008     if (enc_utf8)
3009     {
3010 	int	i;
3011 
3012 	mch_memmove(ScreenLinesUC + off_to, ScreenLinesUC + off_from,
3013 		wp->w_width * sizeof(u8char_T));
3014 	for (i = 0; i < p_mco; ++i)
3015 	    mch_memmove(ScreenLinesC[i] + off_to, ScreenLinesC[i] + off_from,
3016 		    wp->w_width * sizeof(u8char_T));
3017     }
3018     if (enc_dbcs == DBCS_JPNU)
3019 	mch_memmove(ScreenLines2 + off_to, ScreenLines2 + off_from,
3020 		wp->w_width * sizeof(schar_T));
3021     mch_memmove(ScreenAttrs + off_to, ScreenAttrs + off_from,
3022 	    wp->w_width * sizeof(sattr_T));
3023 }
3024 
3025 /*
3026  * Return TRUE if clearing with term string "p" would work.
3027  * It can't work when the string is empty or it won't set the right background.
3028  * Don't clear to end-of-line when there are popups, it may cause flicker.
3029  */
3030     int
3031 can_clear(char_u *p)
3032 {
3033     return (*p != NUL && (t_colors <= 1
3034 #ifdef FEAT_GUI
3035 		|| gui.in_use
3036 #endif
3037 #ifdef FEAT_TERMGUICOLORS
3038 		|| (p_tgc && cterm_normal_bg_gui_color == INVALCOLOR)
3039 		|| (!p_tgc && cterm_normal_bg_color == 0)
3040 #else
3041 		|| cterm_normal_bg_color == 0
3042 #endif
3043 		|| *T_UT != NUL)
3044 #ifdef FEAT_PROP_POPUP
3045 	    && !(p == T_CE && popup_visible)
3046 #endif
3047 	    );
3048 }
3049 
3050 /*
3051  * Reset cursor position. Use whenever cursor was moved because of outputting
3052  * something directly to the screen (shell commands) or a terminal control
3053  * code.
3054  */
3055     void
3056 screen_start(void)
3057 {
3058     screen_cur_row = screen_cur_col = 9999;
3059 }
3060 
3061 /*
3062  * Move the cursor to position "row","col" in the screen.
3063  * This tries to find the most efficient way to move, minimizing the number of
3064  * characters sent to the terminal.
3065  */
3066     void
3067 windgoto(int row, int col)
3068 {
3069     sattr_T	    *p;
3070     int		    i;
3071     int		    plan;
3072     int		    cost;
3073     int		    wouldbe_col;
3074     int		    noinvcurs;
3075     char_u	    *bs;
3076     int		    goto_cost;
3077     int		    attr;
3078 
3079 #define GOTO_COST   7	// assume a term_windgoto() takes about 7 chars
3080 #define HIGHL_COST  5	// assume unhighlight takes 5 chars
3081 
3082 #define PLAN_LE	    1
3083 #define PLAN_CR	    2
3084 #define PLAN_NL	    3
3085 #define PLAN_WRITE  4
3086     // Can't use ScreenLines unless initialized
3087     if (ScreenLines == NULL)
3088 	return;
3089 
3090     if (col != screen_cur_col || row != screen_cur_row)
3091     {
3092 	// Check for valid position.
3093 	if (row < 0)	// window without text lines?
3094 	    row = 0;
3095 	if (row >= screen_Rows)
3096 	    row = screen_Rows - 1;
3097 	if (col >= screen_Columns)
3098 	    col = screen_Columns - 1;
3099 
3100 	// check if no cursor movement is allowed in highlight mode
3101 	if (screen_attr && *T_MS == NUL)
3102 	    noinvcurs = HIGHL_COST;
3103 	else
3104 	    noinvcurs = 0;
3105 	goto_cost = GOTO_COST + noinvcurs;
3106 
3107 	/*
3108 	 * Plan how to do the positioning:
3109 	 * 1. Use CR to move it to column 0, same row.
3110 	 * 2. Use T_LE to move it a few columns to the left.
3111 	 * 3. Use NL to move a few lines down, column 0.
3112 	 * 4. Move a few columns to the right with T_ND or by writing chars.
3113 	 *
3114 	 * Don't do this if the cursor went beyond the last column, the cursor
3115 	 * position is unknown then (some terminals wrap, some don't )
3116 	 *
3117 	 * First check if the highlighting attributes allow us to write
3118 	 * characters to move the cursor to the right.
3119 	 */
3120 	if (row >= screen_cur_row && screen_cur_col < Columns)
3121 	{
3122 	    /*
3123 	     * If the cursor is in the same row, bigger col, we can use CR
3124 	     * or T_LE.
3125 	     */
3126 	    bs = NULL;			    // init for GCC
3127 	    attr = screen_attr;
3128 	    if (row == screen_cur_row && col < screen_cur_col)
3129 	    {
3130 		// "le" is preferred over "bc", because "bc" is obsolete
3131 		if (*T_LE)
3132 		    bs = T_LE;		    // "cursor left"
3133 		else
3134 		    bs = T_BC;		    // "backspace character (old)
3135 		if (*bs)
3136 		    cost = (screen_cur_col - col) * (int)STRLEN(bs);
3137 		else
3138 		    cost = 999;
3139 		if (col + 1 < cost)	    // using CR is less characters
3140 		{
3141 		    plan = PLAN_CR;
3142 		    wouldbe_col = 0;
3143 		    cost = 1;		    // CR is just one character
3144 		}
3145 		else
3146 		{
3147 		    plan = PLAN_LE;
3148 		    wouldbe_col = col;
3149 		}
3150 		if (noinvcurs)		    // will stop highlighting
3151 		{
3152 		    cost += noinvcurs;
3153 		    attr = 0;
3154 		}
3155 	    }
3156 
3157 	    /*
3158 	     * If the cursor is above where we want to be, we can use CR LF.
3159 	     */
3160 	    else if (row > screen_cur_row)
3161 	    {
3162 		plan = PLAN_NL;
3163 		wouldbe_col = 0;
3164 		cost = (row - screen_cur_row) * 2;  // CR LF
3165 		if (noinvcurs)		    // will stop highlighting
3166 		{
3167 		    cost += noinvcurs;
3168 		    attr = 0;
3169 		}
3170 	    }
3171 
3172 	    /*
3173 	     * If the cursor is in the same row, smaller col, just use write.
3174 	     */
3175 	    else
3176 	    {
3177 		plan = PLAN_WRITE;
3178 		wouldbe_col = screen_cur_col;
3179 		cost = 0;
3180 	    }
3181 
3182 	    /*
3183 	     * Check if any characters that need to be written have the
3184 	     * correct attributes.  Also avoid UTF-8 characters.
3185 	     */
3186 	    i = col - wouldbe_col;
3187 	    if (i > 0)
3188 		cost += i;
3189 	    if (cost < goto_cost && i > 0)
3190 	    {
3191 		/*
3192 		 * Check if the attributes are correct without additionally
3193 		 * stopping highlighting.
3194 		 */
3195 		p = ScreenAttrs + LineOffset[row] + wouldbe_col;
3196 		while (i && *p++ == attr)
3197 		    --i;
3198 		if (i != 0)
3199 		{
3200 		    /*
3201 		     * Try if it works when highlighting is stopped here.
3202 		     */
3203 		    if (*--p == 0)
3204 		    {
3205 			cost += noinvcurs;
3206 			while (i && *p++ == 0)
3207 			    --i;
3208 		    }
3209 		    if (i != 0)
3210 			cost = 999;	// different attributes, don't do it
3211 		}
3212 		if (enc_utf8)
3213 		{
3214 		    // Don't use an UTF-8 char for positioning, it's slow.
3215 		    for (i = wouldbe_col; i < col; ++i)
3216 			if (ScreenLinesUC[LineOffset[row] + i] != 0)
3217 			{
3218 			    cost = 999;
3219 			    break;
3220 			}
3221 		}
3222 	    }
3223 
3224 	    /*
3225 	     * We can do it without term_windgoto()!
3226 	     */
3227 	    if (cost < goto_cost)
3228 	    {
3229 		if (plan == PLAN_LE)
3230 		{
3231 		    if (noinvcurs)
3232 			screen_stop_highlight();
3233 		    while (screen_cur_col > col)
3234 		    {
3235 			out_str(bs);
3236 			--screen_cur_col;
3237 		    }
3238 		}
3239 		else if (plan == PLAN_CR)
3240 		{
3241 		    if (noinvcurs)
3242 			screen_stop_highlight();
3243 		    out_char('\r');
3244 		    screen_cur_col = 0;
3245 		}
3246 		else if (plan == PLAN_NL)
3247 		{
3248 		    if (noinvcurs)
3249 			screen_stop_highlight();
3250 		    while (screen_cur_row < row)
3251 		    {
3252 			out_char('\n');
3253 			++screen_cur_row;
3254 		    }
3255 		    screen_cur_col = 0;
3256 		}
3257 
3258 		i = col - screen_cur_col;
3259 		if (i > 0)
3260 		{
3261 		    /*
3262 		     * Use cursor-right if it's one character only.  Avoids
3263 		     * removing a line of pixels from the last bold char, when
3264 		     * using the bold trick in the GUI.
3265 		     */
3266 		    if (T_ND[0] != NUL && T_ND[1] == NUL)
3267 		    {
3268 			while (i-- > 0)
3269 			    out_char(*T_ND);
3270 		    }
3271 		    else
3272 		    {
3273 			int	off;
3274 
3275 			off = LineOffset[row] + screen_cur_col;
3276 			while (i-- > 0)
3277 			{
3278 			    if (ScreenAttrs[off] != screen_attr)
3279 				screen_stop_highlight();
3280 			    out_flush_check();
3281 			    out_char(ScreenLines[off]);
3282 			    if (enc_dbcs == DBCS_JPNU
3283 						  && ScreenLines[off] == 0x8e)
3284 				out_char(ScreenLines2[off]);
3285 			    ++off;
3286 			}
3287 		    }
3288 		}
3289 	    }
3290 	}
3291 	else
3292 	    cost = 999;
3293 
3294 	if (cost >= goto_cost)
3295 	{
3296 	    if (noinvcurs)
3297 		screen_stop_highlight();
3298 	    if (row == screen_cur_row && (col > screen_cur_col)
3299 							     && *T_CRI != NUL)
3300 		term_cursor_right(col - screen_cur_col);
3301 	    else
3302 		term_windgoto(row, col);
3303 	}
3304 	screen_cur_row = row;
3305 	screen_cur_col = col;
3306     }
3307 }
3308 
3309 /*
3310  * Set cursor to its position in the current window.
3311  */
3312     void
3313 setcursor(void)
3314 {
3315     setcursor_mayforce(FALSE);
3316 }
3317 
3318 /*
3319  * Set cursor to its position in the current window.
3320  * When "force" is TRUE also when not redrawing.
3321  */
3322     void
3323 setcursor_mayforce(int force)
3324 {
3325     if (force || redrawing())
3326     {
3327 	validate_cursor();
3328 	windgoto(W_WINROW(curwin) + curwin->w_wrow,
3329 		curwin->w_wincol + (
3330 #ifdef FEAT_RIGHTLEFT
3331 		// With 'rightleft' set and the cursor on a double-wide
3332 		// character, position it on the leftmost column.
3333 		curwin->w_p_rl ? ((int)curwin->w_width - curwin->w_wcol
3334 		    - ((has_mbyte
3335 			   && (*mb_ptr2cells)(ml_get_cursor()) == 2
3336 			   && vim_isprintc(gchar_cursor())) ? 2 : 1)) :
3337 #endif
3338 							    curwin->w_wcol));
3339     }
3340 }
3341 
3342 
3343 /*
3344  * Insert 'line_count' lines at 'row' in window 'wp'.
3345  * If 'invalid' is TRUE the wp->w_lines[].wl_lnum is invalidated.
3346  * If 'mayclear' is TRUE the screen will be cleared if it is faster than
3347  * scrolling.
3348  * Returns FAIL if the lines are not inserted, OK for success.
3349  */
3350     int
3351 win_ins_lines(
3352     win_T	*wp,
3353     int		row,
3354     int		line_count,
3355     int		invalid,
3356     int		mayclear)
3357 {
3358     int		did_delete;
3359     int		nextrow;
3360     int		lastrow;
3361     int		retval;
3362 
3363     if (invalid)
3364 	wp->w_lines_valid = 0;
3365 
3366     if (wp->w_height < 5)
3367 	return FAIL;
3368 
3369     if (line_count > wp->w_height - row)
3370 	line_count = wp->w_height - row;
3371 
3372     retval = win_do_lines(wp, row, line_count, mayclear, FALSE, 0);
3373     if (retval != MAYBE)
3374 	return retval;
3375 
3376     /*
3377      * If there is a next window or a status line, we first try to delete the
3378      * lines at the bottom to avoid messing what is after the window.
3379      * If this fails and there are following windows, don't do anything to
3380      * avoid messing up those windows, better just redraw.
3381      */
3382     did_delete = FALSE;
3383     if (wp->w_next != NULL || wp->w_status_height)
3384     {
3385 	if (screen_del_lines(0, W_WINROW(wp) + wp->w_height - line_count,
3386 				  line_count, (int)Rows, FALSE, 0, NULL) == OK)
3387 	    did_delete = TRUE;
3388 	else if (wp->w_next)
3389 	    return FAIL;
3390     }
3391     /*
3392      * if no lines deleted, blank the lines that will end up below the window
3393      */
3394     if (!did_delete)
3395     {
3396 	wp->w_redr_status = TRUE;
3397 	redraw_cmdline = TRUE;
3398 	nextrow = W_WINROW(wp) + wp->w_height + wp->w_status_height;
3399 	lastrow = nextrow + line_count;
3400 	if (lastrow > Rows)
3401 	    lastrow = Rows;
3402 	screen_fill(nextrow - line_count, lastrow - line_count,
3403 		  wp->w_wincol, (int)W_ENDCOL(wp),
3404 		  ' ', ' ', 0);
3405     }
3406 
3407     if (screen_ins_lines(0, W_WINROW(wp) + row, line_count, (int)Rows, 0, NULL)
3408 								      == FAIL)
3409     {
3410 	// deletion will have messed up other windows
3411 	if (did_delete)
3412 	{
3413 	    wp->w_redr_status = TRUE;
3414 	    win_rest_invalid(W_NEXT(wp));
3415 	}
3416 	return FAIL;
3417     }
3418 
3419     return OK;
3420 }
3421 
3422 /*
3423  * Delete "line_count" window lines at "row" in window "wp".
3424  * If "invalid" is TRUE curwin->w_lines[] is invalidated.
3425  * If "mayclear" is TRUE the screen will be cleared if it is faster than
3426  * scrolling
3427  * Return OK for success, FAIL if the lines are not deleted.
3428  */
3429     int
3430 win_del_lines(
3431     win_T	*wp,
3432     int		row,
3433     int		line_count,
3434     int		invalid,
3435     int		mayclear,
3436     int		clear_attr)	    // for clearing lines
3437 {
3438     int		retval;
3439 
3440     if (invalid)
3441 	wp->w_lines_valid = 0;
3442 
3443     if (line_count > wp->w_height - row)
3444 	line_count = wp->w_height - row;
3445 
3446     retval = win_do_lines(wp, row, line_count, mayclear, TRUE, clear_attr);
3447     if (retval != MAYBE)
3448 	return retval;
3449 
3450     if (screen_del_lines(0, W_WINROW(wp) + row, line_count,
3451 				   (int)Rows, FALSE, clear_attr, NULL) == FAIL)
3452 	return FAIL;
3453 
3454     /*
3455      * If there are windows or status lines below, try to put them at the
3456      * correct place. If we can't do that, they have to be redrawn.
3457      */
3458     if (wp->w_next || wp->w_status_height || cmdline_row < Rows - 1)
3459     {
3460 	if (screen_ins_lines(0, W_WINROW(wp) + wp->w_height - line_count,
3461 			      line_count, (int)Rows, clear_attr, NULL) == FAIL)
3462 	{
3463 	    wp->w_redr_status = TRUE;
3464 	    win_rest_invalid(wp->w_next);
3465 	}
3466     }
3467     /*
3468      * If this is the last window and there is no status line, redraw the
3469      * command line later.
3470      */
3471     else
3472 	redraw_cmdline = TRUE;
3473     return OK;
3474 }
3475 
3476 /*
3477  * Common code for win_ins_lines() and win_del_lines().
3478  * Returns OK or FAIL when the work has been done.
3479  * Returns MAYBE when not finished yet.
3480  */
3481     static int
3482 win_do_lines(
3483     win_T	*wp,
3484     int		row,
3485     int		line_count,
3486     int		mayclear,
3487     int		del,
3488     int		clear_attr)
3489 {
3490     int		retval;
3491 
3492     if (!redrawing() || line_count <= 0)
3493 	return FAIL;
3494 
3495     // When inserting lines would result in loss of command output, just redraw
3496     // the lines.
3497     if (no_win_do_lines_ins && !del)
3498 	return FAIL;
3499 
3500     // only a few lines left: redraw is faster
3501     if (mayclear && Rows - line_count < 5 && wp->w_width == Columns)
3502     {
3503 	if (!no_win_do_lines_ins)
3504 	    screenclear();	    // will set wp->w_lines_valid to 0
3505 	return FAIL;
3506     }
3507 
3508 #ifdef FEAT_PROP_POPUP
3509     // this doesn't work when there are popups visible
3510     if (popup_visible)
3511 	return FAIL;
3512 #endif
3513 
3514     // Delete all remaining lines
3515     if (row + line_count >= wp->w_height)
3516     {
3517 	screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + wp->w_height,
3518 		wp->w_wincol, (int)W_ENDCOL(wp),
3519 		' ', ' ', 0);
3520 	return OK;
3521     }
3522 
3523     /*
3524      * When scrolling, the message on the command line should be cleared,
3525      * otherwise it will stay there forever.
3526      * Don't do this when avoiding to insert lines.
3527      */
3528     if (!no_win_do_lines_ins)
3529 	clear_cmdline = TRUE;
3530 
3531     /*
3532      * If the terminal can set a scroll region, use that.
3533      * Always do this in a vertically split window.  This will redraw from
3534      * ScreenLines[] when t_CV isn't defined.  That's faster than using
3535      * win_line().
3536      * Don't use a scroll region when we are going to redraw the text, writing
3537      * a character in the lower right corner of the scroll region may cause a
3538      * scroll-up .
3539      */
3540     if (scroll_region || wp->w_width != Columns)
3541     {
3542 	if (scroll_region && (wp->w_width == Columns || *T_CSV != NUL))
3543 	    scroll_region_set(wp, row);
3544 	if (del)
3545 	    retval = screen_del_lines(W_WINROW(wp) + row, 0, line_count,
3546 				    wp->w_height - row, FALSE, clear_attr, wp);
3547 	else
3548 	    retval = screen_ins_lines(W_WINROW(wp) + row, 0, line_count,
3549 					   wp->w_height - row, clear_attr, wp);
3550 	if (scroll_region && (wp->w_width == Columns || *T_CSV != NUL))
3551 	    scroll_region_reset();
3552 	return retval;
3553     }
3554 
3555     if (wp->w_next != NULL && p_tf) // don't delete/insert on fast terminal
3556 	return FAIL;
3557 
3558     return MAYBE;
3559 }
3560 
3561 /*
3562  * window 'wp' and everything after it is messed up, mark it for redraw
3563  */
3564     static void
3565 win_rest_invalid(win_T *wp)
3566 {
3567     while (wp != NULL)
3568     {
3569 	redraw_win_later(wp, NOT_VALID);
3570 	wp->w_redr_status = TRUE;
3571 	wp = wp->w_next;
3572     }
3573     redraw_cmdline = TRUE;
3574 }
3575 
3576 /*
3577  * The rest of the routines in this file perform screen manipulations. The
3578  * given operation is performed physically on the screen. The corresponding
3579  * change is also made to the internal screen image. In this way, the editor
3580  * anticipates the effect of editing changes on the appearance of the screen.
3581  * That way, when we call screenupdate a complete redraw isn't usually
3582  * necessary. Another advantage is that we can keep adding code to anticipate
3583  * screen changes, and in the meantime, everything still works.
3584  */
3585 
3586 /*
3587  * types for inserting or deleting lines
3588  */
3589 #define USE_T_CAL   1
3590 #define USE_T_CDL   2
3591 #define USE_T_AL    3
3592 #define USE_T_CE    4
3593 #define USE_T_DL    5
3594 #define USE_T_SR    6
3595 #define USE_NL	    7
3596 #define USE_T_CD    8
3597 #define USE_REDRAW  9
3598 
3599 /*
3600  * insert lines on the screen and update ScreenLines[]
3601  * 'end' is the line after the scrolled part. Normally it is Rows.
3602  * When scrolling region used 'off' is the offset from the top for the region.
3603  * 'row' and 'end' are relative to the start of the region.
3604  *
3605  * return FAIL for failure, OK for success.
3606  */
3607     int
3608 screen_ins_lines(
3609     int		off,
3610     int		row,
3611     int		line_count,
3612     int		end,
3613     int		clear_attr,
3614     win_T	*wp)	    // NULL or window to use width from
3615 {
3616     int		i;
3617     int		j;
3618     unsigned	temp;
3619     int		cursor_row;
3620     int		cursor_col = 0;
3621     int		type;
3622     int		result_empty;
3623     int		can_ce = can_clear(T_CE);
3624 
3625     /*
3626      * FAIL if
3627      * - there is no valid screen
3628      * - the screen has to be redrawn completely
3629      * - the line count is less than one
3630      * - the line count is more than 'ttyscroll'
3631      * - redrawing for a callback and there is a modeless selection
3632      * - there is a popup window
3633      */
3634      if (!screen_valid(TRUE)
3635 	     || line_count <= 0 || line_count > p_ttyscroll
3636 #ifdef FEAT_CLIPBOARD
3637 	     || (clip_star.state != SELECT_CLEARED
3638 						 && redrawing_for_callback > 0)
3639 #endif
3640 #ifdef FEAT_PROP_POPUP
3641 	     || popup_visible
3642 #endif
3643 	     )
3644 	return FAIL;
3645 
3646     /*
3647      * There are seven ways to insert lines:
3648      * 0. When in a vertically split window and t_CV isn't set, redraw the
3649      *    characters from ScreenLines[].
3650      * 1. Use T_CD (clear to end of display) if it exists and the result of
3651      *	  the insert is just empty lines
3652      * 2. Use T_CAL (insert multiple lines) if it exists and T_AL is not
3653      *	  present or line_count > 1. It looks better if we do all the inserts
3654      *	  at once.
3655      * 3. Use T_CDL (delete multiple lines) if it exists and the result of the
3656      *	  insert is just empty lines and T_CE is not present or line_count >
3657      *	  1.
3658      * 4. Use T_AL (insert line) if it exists.
3659      * 5. Use T_CE (erase line) if it exists and the result of the insert is
3660      *	  just empty lines.
3661      * 6. Use T_DL (delete line) if it exists and the result of the insert is
3662      *	  just empty lines.
3663      * 7. Use T_SR (scroll reverse) if it exists and inserting at row 0 and
3664      *	  the 'da' flag is not set or we have clear line capability.
3665      * 8. redraw the characters from ScreenLines[].
3666      *
3667      * Careful: In a hpterm scroll reverse doesn't work as expected, it moves
3668      * the scrollbar for the window. It does have insert line, use that if it
3669      * exists.
3670      */
3671     result_empty = (row + line_count >= end);
3672     if (wp != NULL && wp->w_width != Columns && *T_CSV == NUL)
3673 	type = USE_REDRAW;
3674     else if (can_clear(T_CD) && result_empty)
3675 	type = USE_T_CD;
3676     else if (*T_CAL != NUL && (line_count > 1 || *T_AL == NUL))
3677 	type = USE_T_CAL;
3678     else if (*T_CDL != NUL && result_empty && (line_count > 1 || !can_ce))
3679 	type = USE_T_CDL;
3680     else if (*T_AL != NUL)
3681 	type = USE_T_AL;
3682     else if (can_ce && result_empty)
3683 	type = USE_T_CE;
3684     else if (*T_DL != NUL && result_empty)
3685 	type = USE_T_DL;
3686     else if (*T_SR != NUL && row == 0 && (*T_DA == NUL || can_ce))
3687 	type = USE_T_SR;
3688     else
3689 	return FAIL;
3690 
3691     /*
3692      * For clearing the lines screen_del_lines() is used. This will also take
3693      * care of t_db if necessary.
3694      */
3695     if (type == USE_T_CD || type == USE_T_CDL ||
3696 					 type == USE_T_CE || type == USE_T_DL)
3697 	return screen_del_lines(off, row, line_count, end, FALSE, 0, wp);
3698 
3699     /*
3700      * If text is retained below the screen, first clear or delete as many
3701      * lines at the bottom of the window as are about to be inserted so that
3702      * the deleted lines won't later surface during a screen_del_lines.
3703      */
3704     if (*T_DB)
3705 	screen_del_lines(off, end - line_count, line_count, end, FALSE, 0, wp);
3706 
3707 #ifdef FEAT_CLIPBOARD
3708     // Remove a modeless selection when inserting lines halfway the screen
3709     // or not the full width of the screen.
3710     if (off + row > 0 || (wp != NULL && wp->w_width != Columns))
3711 	clip_clear_selection(&clip_star);
3712     else
3713 	clip_scroll_selection(-line_count);
3714 #endif
3715 
3716 #ifdef FEAT_GUI_HAIKU
3717     vim_lock_screen();
3718 #endif
3719 
3720 #ifdef FEAT_GUI
3721     // Don't update the GUI cursor here, ScreenLines[] is invalid until the
3722     // scrolling is actually carried out.
3723     gui_dont_update_cursor(row + off <= gui.cursor_row);
3724 #endif
3725 
3726     if (wp != NULL && wp->w_wincol != 0 && *T_CSV != NUL && *T_CCS == NUL)
3727 	cursor_col = wp->w_wincol;
3728 
3729     if (*T_CCS != NUL)	   // cursor relative to region
3730 	cursor_row = row;
3731     else
3732 	cursor_row = row + off;
3733 
3734     /*
3735      * Shift LineOffset[] line_count down to reflect the inserted lines.
3736      * Clear the inserted lines in ScreenLines[].
3737      */
3738     row += off;
3739     end += off;
3740     for (i = 0; i < line_count; ++i)
3741     {
3742 	if (wp != NULL && wp->w_width != Columns)
3743 	{
3744 	    // need to copy part of a line
3745 	    j = end - 1 - i;
3746 	    while ((j -= line_count) >= row)
3747 		linecopy(j + line_count, j, wp);
3748 	    j += line_count;
3749 	    if (can_clear((char_u *)" "))
3750 		lineclear(LineOffset[j] + wp->w_wincol, wp->w_width,
3751 								   clear_attr);
3752 	    else
3753 		lineinvalid(LineOffset[j] + wp->w_wincol, wp->w_width);
3754 	    LineWraps[j] = FALSE;
3755 	}
3756 	else
3757 	{
3758 	    j = end - 1 - i;
3759 	    temp = LineOffset[j];
3760 	    while ((j -= line_count) >= row)
3761 	    {
3762 		LineOffset[j + line_count] = LineOffset[j];
3763 		LineWraps[j + line_count] = LineWraps[j];
3764 	    }
3765 	    LineOffset[j + line_count] = temp;
3766 	    LineWraps[j + line_count] = FALSE;
3767 	    if (can_clear((char_u *)" "))
3768 		lineclear(temp, (int)Columns, clear_attr);
3769 	    else
3770 		lineinvalid(temp, (int)Columns);
3771 	}
3772     }
3773 
3774 #ifdef FEAT_GUI_HAIKU
3775     vim_unlock_screen();
3776 #endif
3777 
3778     screen_stop_highlight();
3779     windgoto(cursor_row, cursor_col);
3780     if (clear_attr != 0)
3781 	screen_start_highlight(clear_attr);
3782 
3783     // redraw the characters
3784     if (type == USE_REDRAW)
3785 	redraw_block(row, end, wp);
3786     else if (type == USE_T_CAL)
3787     {
3788 	term_append_lines(line_count);
3789 	screen_start();		// don't know where cursor is now
3790     }
3791     else
3792     {
3793 	for (i = 0; i < line_count; i++)
3794 	{
3795 	    if (type == USE_T_AL)
3796 	    {
3797 		if (i && cursor_row != 0)
3798 		    windgoto(cursor_row, cursor_col);
3799 		out_str(T_AL);
3800 	    }
3801 	    else  // type == USE_T_SR
3802 		out_str(T_SR);
3803 	    screen_start();	    // don't know where cursor is now
3804 	}
3805     }
3806 
3807     /*
3808      * With scroll-reverse and 'da' flag set we need to clear the lines that
3809      * have been scrolled down into the region.
3810      */
3811     if (type == USE_T_SR && *T_DA)
3812     {
3813 	for (i = 0; i < line_count; ++i)
3814 	{
3815 	    windgoto(off + i, cursor_col);
3816 	    out_str(T_CE);
3817 	    screen_start();	    // don't know where cursor is now
3818 	}
3819     }
3820 
3821 #ifdef FEAT_GUI
3822     gui_can_update_cursor();
3823     if (gui.in_use)
3824 	out_flush();	// always flush after a scroll
3825 #endif
3826     return OK;
3827 }
3828 
3829 /*
3830  * Delete lines on the screen and update ScreenLines[].
3831  * "end" is the line after the scrolled part. Normally it is Rows.
3832  * When scrolling region used "off" is the offset from the top for the region.
3833  * "row" and "end" are relative to the start of the region.
3834  *
3835  * Return OK for success, FAIL if the lines are not deleted.
3836  */
3837     int
3838 screen_del_lines(
3839     int		off,
3840     int		row,
3841     int		line_count,
3842     int		end,
3843     int		force,		// even when line_count > p_ttyscroll
3844     int		clear_attr,	// used for clearing lines
3845     win_T	*wp UNUSED)	// NULL or window to use width from
3846 {
3847     int		j;
3848     int		i;
3849     unsigned	temp;
3850     int		cursor_row;
3851     int		cursor_col = 0;
3852     int		cursor_end;
3853     int		result_empty;	// result is empty until end of region
3854     int		can_delete;	// deleting line codes can be used
3855     int		type;
3856 
3857     /*
3858      * FAIL if
3859      * - there is no valid screen
3860      * - the screen has to be redrawn completely
3861      * - the line count is less than one
3862      * - the line count is more than 'ttyscroll'
3863      * - redrawing for a callback and there is a modeless selection
3864      */
3865     if (!screen_valid(TRUE) || line_count <= 0
3866 					|| (!force && line_count > p_ttyscroll)
3867 #ifdef FEAT_CLIPBOARD
3868 	     || (clip_star.state != SELECT_CLEARED
3869 						 && redrawing_for_callback > 0)
3870 #endif
3871        )
3872 	return FAIL;
3873 
3874     /*
3875      * Check if the rest of the current region will become empty.
3876      */
3877     result_empty = row + line_count >= end;
3878 
3879     /*
3880      * We can delete lines only when 'db' flag not set or when 'ce' option
3881      * available.
3882      */
3883     can_delete = (*T_DB == NUL || can_clear(T_CE));
3884 
3885     /*
3886      * There are six ways to delete lines:
3887      * 0. When in a vertically split window and t_CV isn't set, redraw the
3888      *    characters from ScreenLines[].
3889      * 1. Use T_CD if it exists and the result is empty.
3890      * 2. Use newlines if row == 0 and count == 1 or T_CDL does not exist.
3891      * 3. Use T_CDL (delete multiple lines) if it exists and line_count > 1 or
3892      *	  none of the other ways work.
3893      * 4. Use T_CE (erase line) if the result is empty.
3894      * 5. Use T_DL (delete line) if it exists.
3895      * 6. redraw the characters from ScreenLines[].
3896      */
3897     if (wp != NULL && wp->w_width != Columns && *T_CSV == NUL)
3898 	type = USE_REDRAW;
3899     else if (can_clear(T_CD) && result_empty)
3900 	type = USE_T_CD;
3901     else if (row == 0 && (
3902 #ifndef AMIGA
3903 	// On the Amiga, somehow '\n' on the last line doesn't always scroll
3904 	// up, so use delete-line command
3905 			    line_count == 1 ||
3906 #endif
3907 						*T_CDL == NUL))
3908 	type = USE_NL;
3909     else if (*T_CDL != NUL && line_count > 1 && can_delete)
3910 	type = USE_T_CDL;
3911     else if (can_clear(T_CE) && result_empty
3912 	    && (wp == NULL || wp->w_width == Columns))
3913 	type = USE_T_CE;
3914     else if (*T_DL != NUL && can_delete)
3915 	type = USE_T_DL;
3916     else if (*T_CDL != NUL && can_delete)
3917 	type = USE_T_CDL;
3918     else
3919 	return FAIL;
3920 
3921 #ifdef FEAT_CLIPBOARD
3922     // Remove a modeless selection when deleting lines halfway the screen or
3923     // not the full width of the screen.
3924     if (off + row > 0 || (wp != NULL && wp->w_width != Columns))
3925 	clip_clear_selection(&clip_star);
3926     else
3927 	clip_scroll_selection(line_count);
3928 #endif
3929 
3930 #ifdef FEAT_GUI_HAIKU
3931     vim_lock_screen();
3932 #endif
3933 
3934 #ifdef FEAT_GUI
3935     // Don't update the GUI cursor here, ScreenLines[] is invalid until the
3936     // scrolling is actually carried out.
3937     gui_dont_update_cursor(gui.cursor_row >= row + off
3938 						&& gui.cursor_row < end + off);
3939 #endif
3940 
3941     if (wp != NULL && wp->w_wincol != 0 && *T_CSV != NUL && *T_CCS == NUL)
3942 	cursor_col = wp->w_wincol;
3943 
3944     if (*T_CCS != NUL)	    // cursor relative to region
3945     {
3946 	cursor_row = row;
3947 	cursor_end = end;
3948     }
3949     else
3950     {
3951 	cursor_row = row + off;
3952 	cursor_end = end + off;
3953     }
3954 
3955     /*
3956      * Now shift LineOffset[] line_count up to reflect the deleted lines.
3957      * Clear the inserted lines in ScreenLines[].
3958      */
3959     row += off;
3960     end += off;
3961     for (i = 0; i < line_count; ++i)
3962     {
3963 	if (wp != NULL && wp->w_width != Columns)
3964 	{
3965 	    // need to copy part of a line
3966 	    j = row + i;
3967 	    while ((j += line_count) <= end - 1)
3968 		linecopy(j - line_count, j, wp);
3969 	    j -= line_count;
3970 	    if (can_clear((char_u *)" "))
3971 		lineclear(LineOffset[j] + wp->w_wincol, wp->w_width,
3972 								   clear_attr);
3973 	    else
3974 		lineinvalid(LineOffset[j] + wp->w_wincol, wp->w_width);
3975 	    LineWraps[j] = FALSE;
3976 	}
3977 	else
3978 	{
3979 	    // whole width, moving the line pointers is faster
3980 	    j = row + i;
3981 	    temp = LineOffset[j];
3982 	    while ((j += line_count) <= end - 1)
3983 	    {
3984 		LineOffset[j - line_count] = LineOffset[j];
3985 		LineWraps[j - line_count] = LineWraps[j];
3986 	    }
3987 	    LineOffset[j - line_count] = temp;
3988 	    LineWraps[j - line_count] = FALSE;
3989 	    if (can_clear((char_u *)" "))
3990 		lineclear(temp, (int)Columns, clear_attr);
3991 	    else
3992 		lineinvalid(temp, (int)Columns);
3993 	}
3994     }
3995 
3996 #ifdef FEAT_GUI_HAIKU
3997     vim_unlock_screen();
3998 #endif
3999 
4000     if (screen_attr != clear_attr)
4001 	screen_stop_highlight();
4002     if (clear_attr != 0)
4003 	screen_start_highlight(clear_attr);
4004 
4005     // redraw the characters
4006     if (type == USE_REDRAW)
4007 	redraw_block(row, end, wp);
4008     else if (type == USE_T_CD)	// delete the lines
4009     {
4010 	windgoto(cursor_row, cursor_col);
4011 	out_str(T_CD);
4012 	screen_start();			// don't know where cursor is now
4013     }
4014     else if (type == USE_T_CDL)
4015     {
4016 	windgoto(cursor_row, cursor_col);
4017 	term_delete_lines(line_count);
4018 	screen_start();			// don't know where cursor is now
4019     }
4020     /*
4021      * Deleting lines at top of the screen or scroll region: Just scroll
4022      * the whole screen (scroll region) up by outputting newlines on the
4023      * last line.
4024      */
4025     else if (type == USE_NL)
4026     {
4027 	windgoto(cursor_end - 1, cursor_col);
4028 	for (i = line_count; --i >= 0; )
4029 	    out_char('\n');		// cursor will remain on same line
4030     }
4031     else
4032     {
4033 	for (i = line_count; --i >= 0; )
4034 	{
4035 	    if (type == USE_T_DL)
4036 	    {
4037 		windgoto(cursor_row, cursor_col);
4038 		out_str(T_DL);		// delete a line
4039 	    }
4040 	    else // type == USE_T_CE
4041 	    {
4042 		windgoto(cursor_row + i, cursor_col);
4043 		out_str(T_CE);		// erase a line
4044 	    }
4045 	    screen_start();		// don't know where cursor is now
4046 	}
4047     }
4048 
4049     /*
4050      * If the 'db' flag is set, we need to clear the lines that have been
4051      * scrolled up at the bottom of the region.
4052      */
4053     if (*T_DB && (type == USE_T_DL || type == USE_T_CDL))
4054     {
4055 	for (i = line_count; i > 0; --i)
4056 	{
4057 	    windgoto(cursor_end - i, cursor_col);
4058 	    out_str(T_CE);		// erase a line
4059 	    screen_start();		// don't know where cursor is now
4060 	}
4061     }
4062 
4063 #ifdef FEAT_GUI
4064     gui_can_update_cursor();
4065     if (gui.in_use)
4066 	out_flush();	// always flush after a scroll
4067 #endif
4068 
4069     return OK;
4070 }
4071 
4072 /*
4073  * Return TRUE when postponing displaying the mode message: when not redrawing
4074  * or inside a mapping.
4075  */
4076     int
4077 skip_showmode()
4078 {
4079     // Call char_avail() only when we are going to show something, because it
4080     // takes a bit of time.  redrawing() may also call char_avail_avail().
4081     if (global_busy
4082 	    || msg_silent != 0
4083 	    || !redrawing()
4084 	    || (char_avail() && !KeyTyped))
4085     {
4086 	redraw_mode = TRUE;		// show mode later
4087 	return TRUE;
4088     }
4089     return FALSE;
4090 }
4091 
4092 /*
4093  * Show the current mode and ruler.
4094  *
4095  * If clear_cmdline is TRUE, clear the rest of the cmdline.
4096  * If clear_cmdline is FALSE there may be a message there that needs to be
4097  * cleared only if a mode is shown.
4098  * If redraw_mode is TRUE show or clear the mode.
4099  * Return the length of the message (0 if no message).
4100  */
4101     int
4102 showmode(void)
4103 {
4104     int		need_clear;
4105     int		length = 0;
4106     int		do_mode;
4107     int		attr;
4108     int		nwr_save;
4109     int		sub_attr;
4110 
4111     do_mode = ((p_smd && msg_silent == 0)
4112 	    && ((State & INSERT)
4113 		|| restart_edit != NUL
4114 		|| VIsual_active));
4115     if (do_mode || reg_recording != 0)
4116     {
4117 	if (skip_showmode())
4118 	    return 0;		// show mode later
4119 
4120 	nwr_save = need_wait_return;
4121 
4122 	// wait a bit before overwriting an important message
4123 	check_for_delay(FALSE);
4124 
4125 	// if the cmdline is more than one line high, erase top lines
4126 	need_clear = clear_cmdline;
4127 	if (clear_cmdline && cmdline_row < Rows - 1)
4128 	    msg_clr_cmdline();			// will reset clear_cmdline
4129 
4130 	// Position on the last line in the window, column 0
4131 	msg_pos_mode();
4132 	cursor_off();
4133 	attr = HL_ATTR(HLF_CM);			// Highlight mode
4134 	if (do_mode)
4135 	{
4136 	    msg_puts_attr("--", attr);
4137 #if defined(FEAT_XIM)
4138 	    if (
4139 # ifdef FEAT_GUI_GTK
4140 		    preedit_get_status()
4141 # else
4142 		    im_get_status()
4143 # endif
4144 	       )
4145 # ifdef FEAT_GUI_GTK // most of the time, it's not XIM being used
4146 		msg_puts_attr(" IM", attr);
4147 # else
4148 		msg_puts_attr(" XIM", attr);
4149 # endif
4150 #endif
4151 	    // CTRL-X in Insert mode
4152 	    if (edit_submode != NULL && !shortmess(SHM_COMPLETIONMENU))
4153 	    {
4154 		// These messages can get long, avoid a wrap in a narrow
4155 		// window.  Prefer showing edit_submode_extra.
4156 		length = (Rows - msg_row) * Columns - 3;
4157 		if (edit_submode_extra != NULL)
4158 		    length -= vim_strsize(edit_submode_extra);
4159 		if (length > 0)
4160 		{
4161 		    if (edit_submode_pre != NULL)
4162 			length -= vim_strsize(edit_submode_pre);
4163 		    if (length - vim_strsize(edit_submode) > 0)
4164 		    {
4165 			if (edit_submode_pre != NULL)
4166 			    msg_puts_attr((char *)edit_submode_pre, attr);
4167 			msg_puts_attr((char *)edit_submode, attr);
4168 		    }
4169 		    if (edit_submode_extra != NULL)
4170 		    {
4171 			msg_puts_attr(" ", attr);  // add a space in between
4172 			if ((int)edit_submode_highl < (int)HLF_COUNT)
4173 			    sub_attr = HL_ATTR(edit_submode_highl);
4174 			else
4175 			    sub_attr = attr;
4176 			msg_puts_attr((char *)edit_submode_extra, sub_attr);
4177 		    }
4178 		}
4179 	    }
4180 	    else
4181 	    {
4182 		if (State & VREPLACE_FLAG)
4183 		    msg_puts_attr(_(" VREPLACE"), attr);
4184 		else if (State & REPLACE_FLAG)
4185 		    msg_puts_attr(_(" REPLACE"), attr);
4186 		else if (State & INSERT)
4187 		{
4188 #ifdef FEAT_RIGHTLEFT
4189 		    if (p_ri)
4190 			msg_puts_attr(_(" REVERSE"), attr);
4191 #endif
4192 		    msg_puts_attr(_(" INSERT"), attr);
4193 		}
4194 		else if (restart_edit == 'I' || restart_edit == 'A')
4195 		    msg_puts_attr(_(" (insert)"), attr);
4196 		else if (restart_edit == 'R')
4197 		    msg_puts_attr(_(" (replace)"), attr);
4198 		else if (restart_edit == 'V')
4199 		    msg_puts_attr(_(" (vreplace)"), attr);
4200 #ifdef FEAT_RIGHTLEFT
4201 		if (p_hkmap)
4202 		    msg_puts_attr(_(" Hebrew"), attr);
4203 #endif
4204 #ifdef FEAT_KEYMAP
4205 		if (State & LANGMAP)
4206 		{
4207 # ifdef FEAT_ARABIC
4208 		    if (curwin->w_p_arab)
4209 			msg_puts_attr(_(" Arabic"), attr);
4210 		    else
4211 # endif
4212 			if (get_keymap_str(curwin, (char_u *)" (%s)",
4213 							   NameBuff, MAXPATHL))
4214 			    msg_puts_attr((char *)NameBuff, attr);
4215 		}
4216 #endif
4217 		if ((State & INSERT) && p_paste)
4218 		    msg_puts_attr(_(" (paste)"), attr);
4219 
4220 		if (VIsual_active)
4221 		{
4222 		    char *p;
4223 
4224 		    // Don't concatenate separate words to avoid translation
4225 		    // problems.
4226 		    switch ((VIsual_select ? 4 : 0)
4227 			    + (VIsual_mode == Ctrl_V) * 2
4228 			    + (VIsual_mode == 'V'))
4229 		    {
4230 			case 0:	p = N_(" VISUAL"); break;
4231 			case 1: p = N_(" VISUAL LINE"); break;
4232 			case 2: p = N_(" VISUAL BLOCK"); break;
4233 			case 4: p = N_(" SELECT"); break;
4234 			case 5: p = N_(" SELECT LINE"); break;
4235 			default: p = N_(" SELECT BLOCK"); break;
4236 		    }
4237 		    msg_puts_attr(_(p), attr);
4238 		}
4239 		msg_puts_attr(" --", attr);
4240 	    }
4241 
4242 	    need_clear = TRUE;
4243 	}
4244 	if (reg_recording != 0
4245 		&& edit_submode == NULL)    // otherwise it gets too long
4246 	{
4247 	    recording_mode(attr);
4248 	    need_clear = TRUE;
4249 	}
4250 
4251 	mode_displayed = TRUE;
4252 	if (need_clear || clear_cmdline || redraw_mode)
4253 	    msg_clr_eos();
4254 	msg_didout = FALSE;		// overwrite this message
4255 	length = msg_col;
4256 	msg_col = 0;
4257 	need_wait_return = nwr_save;	// never ask for hit-return for this
4258     }
4259     else if (clear_cmdline && msg_silent == 0)
4260 	// Clear the whole command line.  Will reset "clear_cmdline".
4261 	msg_clr_cmdline();
4262     else if (redraw_mode)
4263     {
4264 	msg_pos_mode();
4265 	msg_clr_eos();
4266     }
4267 
4268 #ifdef FEAT_CMDL_INFO
4269     // In Visual mode the size of the selected area must be redrawn.
4270     if (VIsual_active)
4271 	clear_showcmd();
4272 
4273     // If the last window has no status line, the ruler is after the mode
4274     // message and must be redrawn
4275     if (redrawing() && lastwin->w_status_height == 0)
4276 	win_redr_ruler(lastwin, TRUE, FALSE);
4277 #endif
4278     redraw_cmdline = FALSE;
4279     redraw_mode = FALSE;
4280     clear_cmdline = FALSE;
4281 
4282     return length;
4283 }
4284 
4285 /*
4286  * Position for a mode message.
4287  */
4288     static void
4289 msg_pos_mode(void)
4290 {
4291     msg_col = 0;
4292     msg_row = Rows - 1;
4293 }
4294 
4295 /*
4296  * Delete mode message.  Used when ESC is typed which is expected to end
4297  * Insert mode (but Insert mode didn't end yet!).
4298  * Caller should check "mode_displayed".
4299  */
4300     void
4301 unshowmode(int force)
4302 {
4303     /*
4304      * Don't delete it right now, when not redrawing or inside a mapping.
4305      */
4306     if (!redrawing() || (!force && char_avail() && !KeyTyped))
4307 	redraw_cmdline = TRUE;		// delete mode later
4308     else
4309 	clearmode();
4310 }
4311 
4312 /*
4313  * Clear the mode message.
4314  */
4315     void
4316 clearmode(void)
4317 {
4318     int save_msg_row = msg_row;
4319     int save_msg_col = msg_col;
4320 
4321     msg_pos_mode();
4322     if (reg_recording != 0)
4323 	recording_mode(HL_ATTR(HLF_CM));
4324     msg_clr_eos();
4325 
4326     msg_col = save_msg_col;
4327     msg_row = save_msg_row;
4328 }
4329 
4330     static void
4331 recording_mode(int attr)
4332 {
4333     msg_puts_attr(_("recording"), attr);
4334     if (!shortmess(SHM_RECORDING))
4335     {
4336 	char s[4];
4337 
4338 	sprintf(s, " @%c", reg_recording);
4339 	msg_puts_attr(s, attr);
4340     }
4341 }
4342 
4343 /*
4344  * Draw the tab pages line at the top of the Vim window.
4345  */
4346     void
4347 draw_tabline(void)
4348 {
4349     int		tabcount = 0;
4350     tabpage_T	*tp;
4351     int		tabwidth;
4352     int		col = 0;
4353     int		scol = 0;
4354     int		attr;
4355     win_T	*wp;
4356     win_T	*cwp;
4357     int		wincount;
4358     int		modified;
4359     int		c;
4360     int		len;
4361     int		attr_sel = HL_ATTR(HLF_TPS);
4362     int		attr_nosel = HL_ATTR(HLF_TP);
4363     int		attr_fill = HL_ATTR(HLF_TPF);
4364     char_u	*p;
4365     int		room;
4366     int		use_sep_chars = (t_colors < 8
4367 #ifdef FEAT_GUI
4368 					    && !gui.in_use
4369 #endif
4370 #ifdef FEAT_TERMGUICOLORS
4371 					    && !p_tgc
4372 #endif
4373 					    );
4374 
4375     if (ScreenLines == NULL)
4376 	return;
4377     redraw_tabline = FALSE;
4378 
4379 #ifdef FEAT_GUI_TABLINE
4380     // Take care of a GUI tabline.
4381     if (gui_use_tabline())
4382     {
4383 	gui_update_tabline();
4384 	return;
4385     }
4386 #endif
4387 
4388     if (tabline_height() < 1)
4389 	return;
4390 
4391 #if defined(FEAT_STL_OPT)
4392     clear_TabPageIdxs();
4393 
4394     // Use the 'tabline' option if it's set.
4395     if (*p_tal != NUL)
4396     {
4397 	int	saved_did_emsg = did_emsg;
4398 
4399 	// Check for an error.  If there is one we would loop in redrawing the
4400 	// screen.  Avoid that by making 'tabline' empty.
4401 	did_emsg = FALSE;
4402 	win_redr_custom(NULL, FALSE);
4403 	if (did_emsg)
4404 	    set_string_option_direct((char_u *)"tabline", -1,
4405 					   (char_u *)"", OPT_FREE, SID_ERROR);
4406 	did_emsg |= saved_did_emsg;
4407     }
4408     else
4409 #endif
4410     {
4411 	FOR_ALL_TABPAGES(tp)
4412 	    ++tabcount;
4413 
4414 	tabwidth = (Columns - 1 + tabcount / 2) / tabcount;
4415 	if (tabwidth < 6)
4416 	    tabwidth = 6;
4417 
4418 	attr = attr_nosel;
4419 	tabcount = 0;
4420 	for (tp = first_tabpage; tp != NULL && col < Columns - 4;
4421 							     tp = tp->tp_next)
4422 	{
4423 	    scol = col;
4424 
4425 	    if (tp->tp_topframe == topframe)
4426 		attr = attr_sel;
4427 	    if (use_sep_chars && col > 0)
4428 		screen_putchar('|', 0, col++, attr);
4429 
4430 	    if (tp->tp_topframe != topframe)
4431 		attr = attr_nosel;
4432 
4433 	    screen_putchar(' ', 0, col++, attr);
4434 
4435 	    if (tp == curtab)
4436 	    {
4437 		cwp = curwin;
4438 		wp = firstwin;
4439 	    }
4440 	    else
4441 	    {
4442 		cwp = tp->tp_curwin;
4443 		wp = tp->tp_firstwin;
4444 	    }
4445 
4446 	    modified = FALSE;
4447 	    for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount)
4448 		if (bufIsChanged(wp->w_buffer))
4449 		    modified = TRUE;
4450 	    if (modified || wincount > 1)
4451 	    {
4452 		if (wincount > 1)
4453 		{
4454 		    vim_snprintf((char *)NameBuff, MAXPATHL, "%d", wincount);
4455 		    len = (int)STRLEN(NameBuff);
4456 		    if (col + len >= Columns - 3)
4457 			break;
4458 		    screen_puts_len(NameBuff, len, 0, col,
4459 #if defined(FEAT_SYN_HL)
4460 					 hl_combine_attr(attr, HL_ATTR(HLF_T))
4461 #else
4462 					 attr
4463 #endif
4464 					       );
4465 		    col += len;
4466 		}
4467 		if (modified)
4468 		    screen_puts_len((char_u *)"+", 1, 0, col++, attr);
4469 		screen_putchar(' ', 0, col++, attr);
4470 	    }
4471 
4472 	    room = scol - col + tabwidth - 1;
4473 	    if (room > 0)
4474 	    {
4475 		// Get buffer name in NameBuff[]
4476 		get_trans_bufname(cwp->w_buffer);
4477 		shorten_dir(NameBuff);
4478 		len = vim_strsize(NameBuff);
4479 		p = NameBuff;
4480 		if (has_mbyte)
4481 		    while (len > room)
4482 		    {
4483 			len -= ptr2cells(p);
4484 			MB_PTR_ADV(p);
4485 		    }
4486 		else if (len > room)
4487 		{
4488 		    p += len - room;
4489 		    len = room;
4490 		}
4491 		if (len > Columns - col - 1)
4492 		    len = Columns - col - 1;
4493 
4494 		screen_puts_len(p, (int)STRLEN(p), 0, col, attr);
4495 		col += len;
4496 	    }
4497 	    screen_putchar(' ', 0, col++, attr);
4498 
4499 	    // Store the tab page number in TabPageIdxs[], so that
4500 	    // jump_to_mouse() knows where each one is.
4501 	    ++tabcount;
4502 	    while (scol < col)
4503 		TabPageIdxs[scol++] = tabcount;
4504 	}
4505 
4506 	if (use_sep_chars)
4507 	    c = '_';
4508 	else
4509 	    c = ' ';
4510 	screen_fill(0, 1, col, (int)Columns, c, c, attr_fill);
4511 
4512 	// Put an "X" for closing the current tab if there are several.
4513 	if (first_tabpage->tp_next != NULL)
4514 	{
4515 	    screen_putchar('X', 0, (int)Columns - 1, attr_nosel);
4516 	    TabPageIdxs[Columns - 1] = -999;
4517 	}
4518     }
4519 
4520     // Reset the flag here again, in case evaluating 'tabline' causes it to be
4521     // set.
4522     redraw_tabline = FALSE;
4523 }
4524 
4525 /*
4526  * Get buffer name for "buf" into NameBuff[].
4527  * Takes care of special buffer names and translates special characters.
4528  */
4529     void
4530 get_trans_bufname(buf_T *buf)
4531 {
4532     if (buf_spname(buf) != NULL)
4533 	vim_strncpy(NameBuff, buf_spname(buf), MAXPATHL - 1);
4534     else
4535 	home_replace(buf, buf->b_fname, NameBuff, MAXPATHL, TRUE);
4536     trans_characters(NameBuff, MAXPATHL);
4537 }
4538 
4539 /*
4540  * Get the character to use in a status line.  Get its attributes in "*attr".
4541  */
4542     int
4543 fillchar_status(int *attr, win_T *wp)
4544 {
4545     int fill;
4546 
4547 #ifdef FEAT_TERMINAL
4548     if (bt_terminal(wp->w_buffer))
4549     {
4550 	if (wp == curwin)
4551 	{
4552 	    *attr = HL_ATTR(HLF_ST);
4553 	    fill = fill_stl;
4554 	}
4555 	else
4556 	{
4557 	    *attr = HL_ATTR(HLF_STNC);
4558 	    fill = fill_stlnc;
4559 	}
4560     }
4561     else
4562 #endif
4563     if (wp == curwin)
4564     {
4565 	*attr = HL_ATTR(HLF_S);
4566 	fill = fill_stl;
4567     }
4568     else
4569     {
4570 	*attr = HL_ATTR(HLF_SNC);
4571 	fill = fill_stlnc;
4572     }
4573     // Use fill when there is highlighting, and highlighting of current
4574     // window differs, or the fillchars differ, or this is not the
4575     // current window
4576     if (*attr != 0 && ((HL_ATTR(HLF_S) != HL_ATTR(HLF_SNC)
4577 			|| wp != curwin || ONE_WINDOW)
4578 		    || (fill_stl != fill_stlnc)))
4579 	return fill;
4580     if (wp == curwin)
4581 	return '^';
4582     return '=';
4583 }
4584 
4585 /*
4586  * Get the character to use in a separator between vertically split windows.
4587  * Get its attributes in "*attr".
4588  */
4589     int
4590 fillchar_vsep(int *attr)
4591 {
4592     *attr = HL_ATTR(HLF_C);
4593     if (*attr == 0 && fill_vert == ' ')
4594 	return '|';
4595     else
4596 	return fill_vert;
4597 }
4598 
4599 /*
4600  * Return TRUE if redrawing should currently be done.
4601  */
4602     int
4603 redrawing(void)
4604 {
4605 #ifdef FEAT_EVAL
4606     if (disable_redraw_for_testing)
4607 	return 0;
4608     else
4609 #endif
4610 	return ((!RedrawingDisabled
4611 #ifdef FEAT_EVAL
4612 		    || ignore_redraw_flag_for_testing
4613 #endif
4614 		) && !(p_lz && char_avail() && !KeyTyped && !do_redraw));
4615 }
4616 
4617 /*
4618  * Return TRUE if printing messages should currently be done.
4619  */
4620     int
4621 messaging(void)
4622 {
4623     return (!(p_lz && char_avail() && !KeyTyped));
4624 }
4625 
4626 /*
4627  * Compute columns for ruler and shown command. 'sc_col' is also used to
4628  * decide what the maximum length of a message on the status line can be.
4629  * If there is a status line for the last window, 'sc_col' is independent
4630  * of 'ru_col'.
4631  */
4632 
4633 #define COL_RULER 17	    // columns needed by standard ruler
4634 
4635     void
4636 comp_col(void)
4637 {
4638 #if defined(FEAT_CMDL_INFO)
4639     int last_has_status = (p_ls == 2 || (p_ls == 1 && !ONE_WINDOW));
4640 
4641     sc_col = 0;
4642     ru_col = 0;
4643     if (p_ru)
4644     {
4645 # ifdef FEAT_STL_OPT
4646 	ru_col = (ru_wid ? ru_wid : COL_RULER) + 1;
4647 # else
4648 	ru_col = COL_RULER + 1;
4649 # endif
4650 	// no last status line, adjust sc_col
4651 	if (!last_has_status)
4652 	    sc_col = ru_col;
4653     }
4654     if (p_sc)
4655     {
4656 	sc_col += SHOWCMD_COLS;
4657 	if (!p_ru || last_has_status)	    // no need for separating space
4658 	    ++sc_col;
4659     }
4660     sc_col = Columns - sc_col;
4661     ru_col = Columns - ru_col;
4662     if (sc_col <= 0)		// screen too narrow, will become a mess
4663 	sc_col = 1;
4664     if (ru_col <= 0)
4665 	ru_col = 1;
4666 #else
4667     sc_col = Columns;
4668     ru_col = Columns;
4669 #endif
4670 #ifdef FEAT_EVAL
4671     set_vim_var_nr(VV_ECHOSPACE, sc_col - 1);
4672 #endif
4673 }
4674 
4675 #if defined(FEAT_LINEBREAK) || defined(PROTO)
4676 /*
4677  * Return the width of the 'number' and 'relativenumber' column.
4678  * Caller may need to check if 'number' or 'relativenumber' is set.
4679  * Otherwise it depends on 'numberwidth' and the line count.
4680  */
4681     int
4682 number_width(win_T *wp)
4683 {
4684     int		n;
4685     linenr_T	lnum;
4686 
4687     if (wp->w_p_rnu && !wp->w_p_nu)
4688 	// cursor line shows "0"
4689 	lnum = wp->w_height;
4690     else
4691 	// cursor line shows absolute line number
4692 	lnum = wp->w_buffer->b_ml.ml_line_count;
4693 
4694     if (lnum == wp->w_nrwidth_line_count && wp->w_nuw_cached == wp->w_p_nuw)
4695 	return wp->w_nrwidth_width;
4696     wp->w_nrwidth_line_count = lnum;
4697 
4698     n = 0;
4699     do
4700     {
4701 	lnum /= 10;
4702 	++n;
4703     } while (lnum > 0);
4704 
4705     // 'numberwidth' gives the minimal width plus one
4706     if (n < wp->w_p_nuw - 1)
4707 	n = wp->w_p_nuw - 1;
4708 
4709 # ifdef FEAT_SIGNS
4710     // If 'signcolumn' is set to 'number' and there is a sign to display, then
4711     // the minimal width for the number column is 2.
4712     if (n < 2 && get_first_valid_sign(wp) != NULL
4713 	    && (*wp->w_p_scl == 'n' && *(wp->w_p_scl + 1) == 'u'))
4714 	n = 2;
4715 # endif
4716 
4717     wp->w_nrwidth_width = n;
4718     wp->w_nuw_cached = wp->w_p_nuw;
4719     return n;
4720 }
4721 #endif
4722 
4723 #if defined(FEAT_EVAL) || defined(PROTO)
4724 /*
4725  * Return the current cursor column. This is the actual position on the
4726  * screen. First column is 0.
4727  */
4728     int
4729 screen_screencol(void)
4730 {
4731     return screen_cur_col;
4732 }
4733 
4734 /*
4735  * Return the current cursor row. This is the actual position on the screen.
4736  * First row is 0.
4737  */
4738     int
4739 screen_screenrow(void)
4740 {
4741     return screen_cur_row;
4742 }
4743 #endif
4744 
4745 /*
4746  * Handle setting 'listchars' or 'fillchars'.
4747  * Returns error message, NULL if it's OK.
4748  */
4749     char *
4750 set_chars_option(char_u **varp)
4751 {
4752     int		round, i, len, entries;
4753     char_u	*p, *s;
4754     int		c1 = 0, c2 = 0, c3 = 0;
4755     struct charstab
4756     {
4757 	int	*cp;
4758 	char	*name;
4759     };
4760     static struct charstab filltab[] =
4761     {
4762 	{&fill_stl,	"stl"},
4763 	{&fill_stlnc,	"stlnc"},
4764 	{&fill_vert,	"vert"},
4765 	{&fill_fold,	"fold"},
4766 	{&fill_diff,	"diff"},
4767     };
4768     static struct charstab lcstab[] =
4769     {
4770 	{&lcs_eol,	"eol"},
4771 	{&lcs_ext,	"extends"},
4772 	{&lcs_nbsp,	"nbsp"},
4773 	{&lcs_prec,	"precedes"},
4774 	{&lcs_space,	"space"},
4775 	{&lcs_tab2,	"tab"},
4776 	{&lcs_trail,	"trail"},
4777 #ifdef FEAT_CONCEAL
4778 	{&lcs_conceal,	"conceal"},
4779 #else
4780 	{NULL,		"conceal"},
4781 #endif
4782     };
4783     struct charstab *tab;
4784 
4785     if (varp == &p_lcs)
4786     {
4787 	tab = lcstab;
4788 	entries = sizeof(lcstab) / sizeof(struct charstab);
4789     }
4790     else
4791     {
4792 	tab = filltab;
4793 	entries = sizeof(filltab) / sizeof(struct charstab);
4794     }
4795 
4796     // first round: check for valid value, second round: assign values
4797     for (round = 0; round <= 1; ++round)
4798     {
4799 	if (round > 0)
4800 	{
4801 	    // After checking that the value is valid: set defaults: space for
4802 	    // 'fillchars', NUL for 'listchars'
4803 	    for (i = 0; i < entries; ++i)
4804 		if (tab[i].cp != NULL)
4805 		    *(tab[i].cp) = (varp == &p_lcs ? NUL : ' ');
4806 
4807 	    if (varp == &p_lcs)
4808 	    {
4809 		lcs_tab1 = NUL;
4810 		lcs_tab3 = NUL;
4811 	    }
4812 	    else
4813 		fill_diff = '-';
4814 	}
4815 	p = *varp;
4816 	while (*p)
4817 	{
4818 	    for (i = 0; i < entries; ++i)
4819 	    {
4820 		len = (int)STRLEN(tab[i].name);
4821 		if (STRNCMP(p, tab[i].name, len) == 0
4822 			&& p[len] == ':'
4823 			&& p[len + 1] != NUL)
4824 		{
4825 		    c2 = c3 = 0;
4826 		    s = p + len + 1;
4827 		    c1 = mb_ptr2char_adv(&s);
4828 		    if (mb_char2cells(c1) > 1)
4829 			continue;
4830 		    if (tab[i].cp == &lcs_tab2)
4831 		    {
4832 			if (*s == NUL)
4833 			    continue;
4834 			c2 = mb_ptr2char_adv(&s);
4835 			if (mb_char2cells(c2) > 1)
4836 			    continue;
4837 			if (!(*s == ',' || *s == NUL))
4838 			{
4839 			    c3 = mb_ptr2char_adv(&s);
4840 			    if (mb_char2cells(c3) > 1)
4841 				continue;
4842 			}
4843 		    }
4844 
4845 		    if (*s == ',' || *s == NUL)
4846 		    {
4847 			if (round)
4848 			{
4849 			    if (tab[i].cp == &lcs_tab2)
4850 			    {
4851 				lcs_tab1 = c1;
4852 				lcs_tab2 = c2;
4853 				lcs_tab3 = c3;
4854 			    }
4855 			    else if (tab[i].cp != NULL)
4856 				*(tab[i].cp) = c1;
4857 
4858 			}
4859 			p = s;
4860 			break;
4861 		    }
4862 		}
4863 	    }
4864 
4865 	    if (i == entries)
4866 		return e_invarg;
4867 	    if (*p == ',')
4868 		++p;
4869 	}
4870     }
4871 
4872     return NULL;	// no error
4873 }
4874 
4875