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