xref: /vim-8.2.3635/src/screen.c (revision 3d1d6475)
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: 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  * update_screen() is the function that updates all windows and status lines.
40  * It is called form the main loop when must_redraw is non-zero.  It may be
41  * called from other places when an immediate screen update is needed.
42  *
43  * The part of the buffer that is displayed in a window is set with:
44  * - w_topline (first buffer line in window)
45  * - w_topfill (filler lines above the first line)
46  * - w_leftcol (leftmost window cell in window),
47  * - w_skipcol (skipped window cells of first line)
48  *
49  * Commands that only move the cursor around in a window, do not need to take
50  * action to update the display.  The main loop will check if w_topline is
51  * valid and update it (scroll the window) when needed.
52  *
53  * Commands that scroll a window change w_topline and must call
54  * check_cursor() to move the cursor into the visible part of the window, and
55  * call redraw_later(VALID) to have the window displayed by update_screen()
56  * later.
57  *
58  * Commands that change text in the buffer must call changed_bytes() or
59  * changed_lines() to mark the area that changed and will require updating
60  * later.  The main loop will call update_screen(), which will update each
61  * window that shows the changed buffer.  This assumes text above the change
62  * can remain displayed as it is.  Text after the change may need updating for
63  * scrolling, folding and syntax highlighting.
64  *
65  * Commands that change how a window is displayed (e.g., setting 'list') or
66  * invalidate the contents of a window in another way (e.g., change fold
67  * settings), must call redraw_later(NOT_VALID) to have the whole window
68  * redisplayed by update_screen() later.
69  *
70  * Commands that change how a buffer is displayed (e.g., setting 'tabstop')
71  * must call redraw_curbuf_later(NOT_VALID) to have all the windows for the
72  * buffer redisplayed by update_screen() later.
73  *
74  * Commands that change highlighting and possibly cause a scroll too must call
75  * redraw_later(SOME_VALID) to update the whole window but still use scrolling
76  * to avoid redrawing everything.  But the length of displayed lines must not
77  * change, use NOT_VALID then.
78  *
79  * Commands that move the window position must call redraw_later(NOT_VALID).
80  * TODO: should minimize redrawing by scrolling when possible.
81  *
82  * Commands that change everything (e.g., resizing the screen) must call
83  * redraw_all_later(NOT_VALID) or redraw_all_later(CLEAR).
84  *
85  * Things that are handled indirectly:
86  * - When messages scroll the screen up, msg_scrolled will be set and
87  *   update_screen() called to redraw.
88  */
89 
90 #include "vim.h"
91 
92 #define MB_FILLER_CHAR '<'  /* character used when a double-width character
93 			     * doesn't fit. */
94 
95 /*
96  * The attributes that are actually active for writing to the screen.
97  */
98 static int	screen_attr = 0;
99 
100 /*
101  * Positioning the cursor is reduced by remembering the last position.
102  * Mostly used by windgoto() and screen_char().
103  */
104 static int	screen_cur_row, screen_cur_col;	/* last known cursor position */
105 
106 #ifdef FEAT_SEARCH_EXTRA
107 static match_T search_hl;	/* used for 'hlsearch' highlight matching */
108 #endif
109 
110 #if defined(FEAT_MENU) || defined(FEAT_FOLDING)
111 static int text_to_screenline(win_T *wp, char_u *text, int col);
112 #endif
113 #ifdef FEAT_FOLDING
114 static foldinfo_T win_foldinfo;	/* info for 'foldcolumn' */
115 static int compute_foldcolumn(win_T *wp, int col);
116 #endif
117 
118 /* Flag that is set when drawing for a callback, not from the main command
119  * loop. */
120 static int redrawing_for_callback = 0;
121 
122 /*
123  * Buffer for one screen line (characters and attributes).
124  */
125 static schar_T	*current_ScreenLine;
126 
127 static void win_update(win_T *wp);
128 static void win_redr_status(win_T *wp, int ignore_pum);
129 static void win_draw_end(win_T *wp, int c1, int c2, int row, int endrow, hlf_T hl);
130 #ifdef FEAT_FOLDING
131 static void fold_line(win_T *wp, long fold_count, foldinfo_T *foldinfo, linenr_T lnum, int row);
132 static void fill_foldcolumn(char_u *p, win_T *wp, int closed, linenr_T lnum);
133 static void copy_text_attr(int off, char_u *buf, int len, int attr);
134 #endif
135 static int win_line(win_T *, linenr_T, int, int, int nochange);
136 static int char_needs_redraw(int off_from, int off_to, int cols);
137 static void draw_vsep_win(win_T *wp, int row);
138 #ifdef FEAT_STL_OPT
139 static void redraw_custom_statusline(win_T *wp);
140 #endif
141 #ifdef FEAT_SEARCH_EXTRA
142 # define SEARCH_HL_PRIORITY 0
143 static void start_search_hl(void);
144 static void end_search_hl(void);
145 static void init_search_hl(win_T *wp);
146 static void prepare_search_hl(win_T *wp, linenr_T lnum);
147 static void next_search_hl(win_T *win, match_T *shl, linenr_T lnum, colnr_T mincol, matchitem_T *cur);
148 static int next_search_hl_pos(match_T *shl, linenr_T lnum, posmatch_T *pos, colnr_T mincol);
149 #endif
150 static void screen_start_highlight(int attr);
151 static void screen_char(unsigned off, int row, int col);
152 #ifdef FEAT_MBYTE
153 static void screen_char_2(unsigned off, int row, int col);
154 #endif
155 static void screenclear2(void);
156 static void lineclear(unsigned off, int width, int attr);
157 static void lineinvalid(unsigned off, int width);
158 static void linecopy(int to, int from, win_T *wp);
159 static void redraw_block(int row, int end, win_T *wp);
160 static int win_do_lines(win_T *wp, int row, int line_count, int mayclear, int del, int clear_attr);
161 static void win_rest_invalid(win_T *wp);
162 static void msg_pos_mode(void);
163 static void recording_mode(int attr);
164 static void draw_tabline(void);
165 static int fillchar_status(int *attr, win_T *wp);
166 static int fillchar_vsep(int *attr);
167 #ifdef FEAT_MENU
168 static void redraw_win_toolbar(win_T *wp);
169 #endif
170 #ifdef FEAT_STL_OPT
171 static void win_redr_custom(win_T *wp, int draw_ruler);
172 #endif
173 #ifdef FEAT_CMDL_INFO
174 static void win_redr_ruler(win_T *wp, int always, int ignore_pum);
175 #endif
176 
177 /* Ugly global: overrule attribute used by screen_char() */
178 static int screen_char_attr = 0;
179 
180 #if defined(FEAT_SYN_HL) && defined(FEAT_RELTIME)
181 /* Can limit syntax highlight time to 'redrawtime'. */
182 # define SYN_TIME_LIMIT 1
183 #endif
184 
185 #ifdef FEAT_RIGHTLEFT
186 # define HAS_RIGHTLEFT(x) x
187 #else
188 # define HAS_RIGHTLEFT(x) FALSE
189 #endif
190 
191 /*
192  * Redraw the current window later, with update_screen(type).
193  * Set must_redraw only if not already set to a higher value.
194  * e.g. if must_redraw is CLEAR, type NOT_VALID will do nothing.
195  */
196     void
197 redraw_later(int type)
198 {
199     redraw_win_later(curwin, type);
200 }
201 
202     void
203 redraw_win_later(
204     win_T	*wp,
205     int		type)
206 {
207     if (!exiting && wp->w_redr_type < type)
208     {
209 	wp->w_redr_type = type;
210 	if (type >= NOT_VALID)
211 	    wp->w_lines_valid = 0;
212 	if (must_redraw < type)	/* must_redraw is the maximum of all windows */
213 	    must_redraw = type;
214     }
215 }
216 
217 /*
218  * Force a complete redraw later.  Also resets the highlighting.  To be used
219  * after executing a shell command that messes up the screen.
220  */
221     void
222 redraw_later_clear(void)
223 {
224     redraw_all_later(CLEAR);
225 #ifdef FEAT_GUI
226     if (gui.in_use)
227 	/* Use a code that will reset gui.highlight_mask in
228 	 * gui_stop_highlight(). */
229 	screen_attr = HL_ALL + 1;
230     else
231 #endif
232 	/* Use attributes that is very unlikely to appear in text. */
233 	screen_attr = HL_BOLD | HL_UNDERLINE | HL_INVERSE | HL_STRIKETHROUGH;
234 }
235 
236 /*
237  * Mark all windows to be redrawn later.
238  */
239     void
240 redraw_all_later(int type)
241 {
242     win_T	*wp;
243 
244     FOR_ALL_WINDOWS(wp)
245     {
246 	redraw_win_later(wp, type);
247     }
248 }
249 
250 /*
251  * Mark all windows that are editing the current buffer to be updated later.
252  */
253     void
254 redraw_curbuf_later(int type)
255 {
256     redraw_buf_later(curbuf, type);
257 }
258 
259     void
260 redraw_buf_later(buf_T *buf, int type)
261 {
262     win_T	*wp;
263 
264     FOR_ALL_WINDOWS(wp)
265     {
266 	if (wp->w_buffer == buf)
267 	    redraw_win_later(wp, type);
268     }
269 }
270 
271     void
272 redraw_buf_and_status_later(buf_T *buf, int type)
273 {
274     win_T	*wp;
275 
276 #ifdef FEAT_WILDMENU
277     if (wild_menu_showing != 0)
278 	/* Don't redraw while the command line completion is displayed, it
279 	 * would disappear. */
280 	return;
281 #endif
282     FOR_ALL_WINDOWS(wp)
283     {
284 	if (wp->w_buffer == buf)
285 	{
286 	    redraw_win_later(wp, type);
287 	    wp->w_redr_status = TRUE;
288 	}
289     }
290 }
291 
292 /*
293  * Redraw as soon as possible.  When the command line is not scrolled redraw
294  * right away and restore what was on the command line.
295  * Return a code indicating what happened.
296  */
297     int
298 redraw_asap(int type)
299 {
300     int		rows;
301     int		cols = screen_Columns;
302     int		r;
303     int		ret = 0;
304     schar_T	*screenline;	/* copy from ScreenLines[] */
305     sattr_T	*screenattr;	/* copy from ScreenAttrs[] */
306 #ifdef FEAT_MBYTE
307     int		i;
308     u8char_T	*screenlineUC = NULL;	/* copy from ScreenLinesUC[] */
309     u8char_T	*screenlineC[MAX_MCO];	/* copy from ScreenLinesC[][] */
310     schar_T	*screenline2 = NULL;	/* copy from ScreenLines2[] */
311 #endif
312 
313     redraw_later(type);
314     if (msg_scrolled || (State != NORMAL && State != NORMAL_BUSY) || exiting)
315 	return ret;
316 
317     /* Allocate space to save the text displayed in the command line area. */
318     rows = screen_Rows - cmdline_row;
319     screenline = (schar_T *)lalloc(
320 			   (long_u)(rows * cols * sizeof(schar_T)), FALSE);
321     screenattr = (sattr_T *)lalloc(
322 			   (long_u)(rows * cols * sizeof(sattr_T)), FALSE);
323     if (screenline == NULL || screenattr == NULL)
324 	ret = 2;
325 #ifdef FEAT_MBYTE
326     if (enc_utf8)
327     {
328 	screenlineUC = (u8char_T *)lalloc(
329 			  (long_u)(rows * cols * sizeof(u8char_T)), FALSE);
330 	if (screenlineUC == NULL)
331 	    ret = 2;
332 	for (i = 0; i < p_mco; ++i)
333 	{
334 	    screenlineC[i] = (u8char_T *)lalloc(
335 			  (long_u)(rows * cols * sizeof(u8char_T)), FALSE);
336 	    if (screenlineC[i] == NULL)
337 		ret = 2;
338 	}
339     }
340     if (enc_dbcs == DBCS_JPNU)
341     {
342 	screenline2 = (schar_T *)lalloc(
343 			   (long_u)(rows * cols * sizeof(schar_T)), FALSE);
344 	if (screenline2 == NULL)
345 	    ret = 2;
346     }
347 #endif
348 
349     if (ret != 2)
350     {
351 	/* Save the text displayed in the command line area. */
352 	for (r = 0; r < rows; ++r)
353 	{
354 	    mch_memmove(screenline + r * cols,
355 			ScreenLines + LineOffset[cmdline_row + r],
356 			(size_t)cols * sizeof(schar_T));
357 	    mch_memmove(screenattr + r * cols,
358 			ScreenAttrs + LineOffset[cmdline_row + r],
359 			(size_t)cols * sizeof(sattr_T));
360 #ifdef FEAT_MBYTE
361 	    if (enc_utf8)
362 	    {
363 		mch_memmove(screenlineUC + r * cols,
364 			    ScreenLinesUC + LineOffset[cmdline_row + r],
365 			    (size_t)cols * sizeof(u8char_T));
366 		for (i = 0; i < p_mco; ++i)
367 		    mch_memmove(screenlineC[i] + r * cols,
368 				ScreenLinesC[i] + LineOffset[cmdline_row + r],
369 				(size_t)cols * sizeof(u8char_T));
370 	    }
371 	    if (enc_dbcs == DBCS_JPNU)
372 		mch_memmove(screenline2 + r * cols,
373 			    ScreenLines2 + LineOffset[cmdline_row + r],
374 			    (size_t)cols * sizeof(schar_T));
375 #endif
376 	}
377 
378 	update_screen(0);
379 	ret = 3;
380 
381 	if (must_redraw == 0)
382 	{
383 	    int	off = (int)(current_ScreenLine - ScreenLines);
384 
385 	    /* Restore the text displayed in the command line area. */
386 	    for (r = 0; r < rows; ++r)
387 	    {
388 		mch_memmove(current_ScreenLine,
389 			    screenline + r * cols,
390 			    (size_t)cols * sizeof(schar_T));
391 		mch_memmove(ScreenAttrs + off,
392 			    screenattr + r * cols,
393 			    (size_t)cols * sizeof(sattr_T));
394 #ifdef FEAT_MBYTE
395 		if (enc_utf8)
396 		{
397 		    mch_memmove(ScreenLinesUC + off,
398 				screenlineUC + r * cols,
399 				(size_t)cols * sizeof(u8char_T));
400 		    for (i = 0; i < p_mco; ++i)
401 			mch_memmove(ScreenLinesC[i] + off,
402 				    screenlineC[i] + r * cols,
403 				    (size_t)cols * sizeof(u8char_T));
404 		}
405 		if (enc_dbcs == DBCS_JPNU)
406 		    mch_memmove(ScreenLines2 + off,
407 				screenline2 + r * cols,
408 				(size_t)cols * sizeof(schar_T));
409 #endif
410 		screen_line(cmdline_row + r, 0, cols, cols, FALSE);
411 	    }
412 	    ret = 4;
413 	}
414     }
415 
416     vim_free(screenline);
417     vim_free(screenattr);
418 #ifdef FEAT_MBYTE
419     if (enc_utf8)
420     {
421 	vim_free(screenlineUC);
422 	for (i = 0; i < p_mco; ++i)
423 	    vim_free(screenlineC[i]);
424     }
425     if (enc_dbcs == DBCS_JPNU)
426 	vim_free(screenline2);
427 #endif
428 
429     /* Show the intro message when appropriate. */
430     maybe_intro_message();
431 
432     setcursor();
433 
434     return ret;
435 }
436 
437 /*
438  * Invoked after an asynchronous callback is called.
439  * If an echo command was used the cursor needs to be put back where
440  * it belongs. If highlighting was changed a redraw is needed.
441  * If "call_update_screen" is FALSE don't call update_screen() when at the
442  * command line.
443  */
444     void
445 redraw_after_callback(int call_update_screen)
446 {
447     ++redrawing_for_callback;
448 
449     if (State == HITRETURN || State == ASKMORE)
450 	; /* do nothing */
451     else if (State & CMDLINE)
452     {
453 	/* Redrawing only works when the screen didn't scroll. Don't clear
454 	 * wildmenu entries. */
455 	if (msg_scrolled == 0
456 #ifdef FEAT_WILDMENU
457 		&& wild_menu_showing == 0
458 #endif
459 		&& call_update_screen)
460 	    update_screen(0);
461 	/* Redraw in the same position, so that the user can continue
462 	 * editing the command. */
463 	redrawcmdline_ex(FALSE);
464     }
465     else if (State & (NORMAL | INSERT | TERMINAL))
466     {
467 	/* keep the command line if possible */
468 	update_screen(VALID_NO_UPDATE);
469 	setcursor();
470     }
471     cursor_on();
472 #ifdef FEAT_GUI
473     if (gui.in_use && !gui_mch_is_blink_off())
474 	/* Don't update the cursor when it is blinking and off to avoid
475 	 * flicker. */
476 	out_flush_cursor(FALSE, FALSE);
477     else
478 #endif
479 	out_flush();
480 
481     --redrawing_for_callback;
482 }
483 
484 /*
485  * Changed something in the current window, at buffer line "lnum", that
486  * requires that line and possibly other lines to be redrawn.
487  * Used when entering/leaving Insert mode with the cursor on a folded line.
488  * Used to remove the "$" from a change command.
489  * Note that when also inserting/deleting lines w_redraw_top and w_redraw_bot
490  * may become invalid and the whole window will have to be redrawn.
491  */
492     void
493 redrawWinline(
494     linenr_T	lnum,
495     int		invalid UNUSED)	/* window line height is invalid now */
496 {
497 #ifdef FEAT_FOLDING
498     int		i;
499 #endif
500 
501     if (curwin->w_redraw_top == 0 || curwin->w_redraw_top > lnum)
502 	curwin->w_redraw_top = lnum;
503     if (curwin->w_redraw_bot == 0 || curwin->w_redraw_bot < lnum)
504 	curwin->w_redraw_bot = lnum;
505     redraw_later(VALID);
506 
507 #ifdef FEAT_FOLDING
508     if (invalid)
509     {
510 	/* A w_lines[] entry for this lnum has become invalid. */
511 	i = find_wl_entry(curwin, lnum);
512 	if (i >= 0)
513 	    curwin->w_lines[i].wl_valid = FALSE;
514     }
515 #endif
516 }
517 
518     void
519 reset_updating_screen(int may_resize_shell UNUSED)
520 {
521     updating_screen = FALSE;
522 #ifdef FEAT_GUI
523     if (may_resize_shell)
524 	gui_may_resize_shell();
525 #endif
526 #ifdef FEAT_TERMINAL
527     term_check_channel_closed_recently();
528 #endif
529 }
530 
531 /*
532  * Update all windows that are editing the current buffer.
533  */
534     void
535 update_curbuf(int type)
536 {
537     redraw_curbuf_later(type);
538     update_screen(type);
539 }
540 
541 /*
542  * Based on the current value of curwin->w_topline, transfer a screenfull
543  * of stuff from Filemem to ScreenLines[], and update curwin->w_botline.
544  * Return OK when the screen was updated, FAIL if it was not done.
545  */
546     int
547 update_screen(int type_arg)
548 {
549     int		type = type_arg;
550     win_T	*wp;
551     static int	did_intro = FALSE;
552 #if defined(FEAT_SEARCH_EXTRA) || defined(FEAT_CLIPBOARD)
553     int		did_one;
554 #endif
555 #ifdef FEAT_GUI
556     int		did_undraw = FALSE;
557     int		gui_cursor_col;
558     int		gui_cursor_row;
559 #endif
560     int		no_update = FALSE;
561 
562     /* Don't do anything if the screen structures are (not yet) valid. */
563     if (!screen_valid(TRUE))
564 	return FAIL;
565 
566     if (type == VALID_NO_UPDATE)
567     {
568 	no_update = TRUE;
569 	type = 0;
570     }
571 
572     if (must_redraw)
573     {
574 	if (type < must_redraw)	    /* use maximal type */
575 	    type = must_redraw;
576 
577 	/* must_redraw is reset here, so that when we run into some weird
578 	 * reason to redraw while busy redrawing (e.g., asynchronous
579 	 * scrolling), or update_topline() in win_update() will cause a
580 	 * scroll, the screen will be redrawn later or in win_update(). */
581 	must_redraw = 0;
582     }
583 
584     /* May need to update w_lines[]. */
585     if (curwin->w_lines_valid == 0 && type < NOT_VALID
586 #ifdef FEAT_TERMINAL
587 	    && !term_do_update_window(curwin)
588 #endif
589 		)
590 	type = NOT_VALID;
591 
592     /* Postpone the redrawing when it's not needed and when being called
593      * recursively. */
594     if (!redrawing() || updating_screen)
595     {
596 	redraw_later(type);		/* remember type for next time */
597 	must_redraw = type;
598 	if (type > INVERTED_ALL)
599 	    curwin->w_lines_valid = 0;	/* don't use w_lines[].wl_size now */
600 	return FAIL;
601     }
602 
603     updating_screen = TRUE;
604 #ifdef FEAT_SYN_HL
605     ++display_tick;	    /* let syntax code know we're in a next round of
606 			     * display updating */
607 #endif
608     if (no_update)
609 	++no_win_do_lines_ins;
610 
611     /*
612      * if the screen was scrolled up when displaying a message, scroll it down
613      */
614     if (msg_scrolled)
615     {
616 	clear_cmdline = TRUE;
617 	if (msg_scrolled > Rows - 5)	    /* clearing is faster */
618 	    type = CLEAR;
619 	else if (type != CLEAR)
620 	{
621 	    check_for_delay(FALSE);
622 	    if (screen_ins_lines(0, 0, msg_scrolled, (int)Rows, 0, NULL)
623 								       == FAIL)
624 		type = CLEAR;
625 	    FOR_ALL_WINDOWS(wp)
626 	    {
627 		if (W_WINROW(wp) < msg_scrolled)
628 		{
629 		    if (W_WINROW(wp) + wp->w_height > msg_scrolled
630 			    && wp->w_redr_type < REDRAW_TOP
631 			    && wp->w_lines_valid > 0
632 			    && wp->w_topline == wp->w_lines[0].wl_lnum)
633 		    {
634 			wp->w_upd_rows = msg_scrolled - W_WINROW(wp);
635 			wp->w_redr_type = REDRAW_TOP;
636 		    }
637 		    else
638 		    {
639 			wp->w_redr_type = NOT_VALID;
640 			if (W_WINROW(wp) + wp->w_height + wp->w_status_height
641 							       <= msg_scrolled)
642 			    wp->w_redr_status = TRUE;
643 		    }
644 		}
645 	    }
646 	    if (!no_update)
647 		redraw_cmdline = TRUE;
648 	    redraw_tabline = TRUE;
649 	}
650 	msg_scrolled = 0;
651 	need_wait_return = FALSE;
652     }
653 
654     /* reset cmdline_row now (may have been changed temporarily) */
655     compute_cmdrow();
656 
657     /* Check for changed highlighting */
658     if (need_highlight_changed)
659 	highlight_changed();
660 
661     if (type == CLEAR)		/* first clear screen */
662     {
663 	screenclear();		/* will reset clear_cmdline */
664 	type = NOT_VALID;
665 	/* must_redraw may be set indirectly, avoid another redraw later */
666 	must_redraw = 0;
667     }
668 
669     if (clear_cmdline)		/* going to clear cmdline (done below) */
670 	check_for_delay(FALSE);
671 
672 #ifdef FEAT_LINEBREAK
673     /* Force redraw when width of 'number' or 'relativenumber' column
674      * changes. */
675     if (curwin->w_redr_type < NOT_VALID
676 	   && curwin->w_nrwidth != ((curwin->w_p_nu || curwin->w_p_rnu)
677 				    ? number_width(curwin) : 0))
678 	curwin->w_redr_type = NOT_VALID;
679 #endif
680 
681     /*
682      * Only start redrawing if there is really something to do.
683      */
684     if (type == INVERTED)
685 	update_curswant();
686     if (curwin->w_redr_type < type
687 	    && !((type == VALID
688 		    && curwin->w_lines[0].wl_valid
689 #ifdef FEAT_DIFF
690 		    && curwin->w_topfill == curwin->w_old_topfill
691 		    && curwin->w_botfill == curwin->w_old_botfill
692 #endif
693 		    && curwin->w_topline == curwin->w_lines[0].wl_lnum)
694 		|| (type == INVERTED
695 		    && VIsual_active
696 		    && curwin->w_old_cursor_lnum == curwin->w_cursor.lnum
697 		    && curwin->w_old_visual_mode == VIsual_mode
698 		    && (curwin->w_valid & VALID_VIRTCOL)
699 		    && curwin->w_old_curswant == curwin->w_curswant)
700 		))
701 	curwin->w_redr_type = type;
702 
703     /* Redraw the tab pages line if needed. */
704     if (redraw_tabline || type >= NOT_VALID)
705 	draw_tabline();
706 
707 #ifdef FEAT_SYN_HL
708     /*
709      * Correct stored syntax highlighting info for changes in each displayed
710      * buffer.  Each buffer must only be done once.
711      */
712     FOR_ALL_WINDOWS(wp)
713     {
714 	if (wp->w_buffer->b_mod_set)
715 	{
716 	    win_T	*wwp;
717 
718 	    /* Check if we already did this buffer. */
719 	    for (wwp = firstwin; wwp != wp; wwp = wwp->w_next)
720 		if (wwp->w_buffer == wp->w_buffer)
721 		    break;
722 	    if (wwp == wp && syntax_present(wp))
723 		syn_stack_apply_changes(wp->w_buffer);
724 	}
725     }
726 #endif
727 
728     /*
729      * Go from top to bottom through the windows, redrawing the ones that need
730      * it.
731      */
732 #if defined(FEAT_SEARCH_EXTRA) || defined(FEAT_CLIPBOARD)
733     did_one = FALSE;
734 #endif
735 #ifdef FEAT_SEARCH_EXTRA
736     search_hl.rm.regprog = NULL;
737 #endif
738     FOR_ALL_WINDOWS(wp)
739     {
740 	if (wp->w_redr_type != 0)
741 	{
742 	    cursor_off();
743 #if defined(FEAT_SEARCH_EXTRA) || defined(FEAT_CLIPBOARD)
744 	    if (!did_one)
745 	    {
746 		did_one = TRUE;
747 # ifdef FEAT_SEARCH_EXTRA
748 		start_search_hl();
749 # endif
750 # ifdef FEAT_CLIPBOARD
751 		/* When Visual area changed, may have to update selection. */
752 		if (clip_star.available && clip_isautosel_star())
753 		    clip_update_selection(&clip_star);
754 		if (clip_plus.available && clip_isautosel_plus())
755 		    clip_update_selection(&clip_plus);
756 # endif
757 #ifdef FEAT_GUI
758 		/* Remove the cursor before starting to do anything, because
759 		 * scrolling may make it difficult to redraw the text under
760 		 * it. */
761 		if (gui.in_use && wp == curwin)
762 		{
763 		    gui_cursor_col = gui.cursor_col;
764 		    gui_cursor_row = gui.cursor_row;
765 		    gui_undraw_cursor();
766 		    did_undraw = TRUE;
767 		}
768 #endif
769 	    }
770 #endif
771 	    win_update(wp);
772 	}
773 
774 	/* redraw status line after the window to minimize cursor movement */
775 	if (wp->w_redr_status)
776 	{
777 	    cursor_off();
778 	    win_redr_status(wp, TRUE); // any popup menu will be redrawn below
779 	}
780     }
781 #if defined(FEAT_SEARCH_EXTRA)
782     end_search_hl();
783 #endif
784 #ifdef FEAT_INS_EXPAND
785     /* May need to redraw the popup menu. */
786     pum_may_redraw();
787 #endif
788 
789     /* Reset b_mod_set flags.  Going through all windows is probably faster
790      * than going through all buffers (there could be many buffers). */
791     FOR_ALL_WINDOWS(wp)
792 	wp->w_buffer->b_mod_set = FALSE;
793 
794     reset_updating_screen(TRUE);
795 
796     /* Clear or redraw the command line.  Done last, because scrolling may
797      * mess up the command line. */
798     if (clear_cmdline || redraw_cmdline)
799 	showmode();
800 
801     if (no_update)
802 	--no_win_do_lines_ins;
803 
804     /* May put up an introductory message when not editing a file */
805     if (!did_intro)
806 	maybe_intro_message();
807     did_intro = TRUE;
808 
809 #ifdef FEAT_GUI
810     /* Redraw the cursor and update the scrollbars when all screen updating is
811      * done. */
812     if (gui.in_use)
813     {
814 	if (did_undraw && !gui_mch_is_blink_off())
815 	{
816 	    mch_disable_flush();
817 	    out_flush();	/* required before updating the cursor */
818 	    mch_enable_flush();
819 
820 	    /* Put the GUI position where the cursor was, gui_update_cursor()
821 	     * uses that. */
822 	    gui.col = gui_cursor_col;
823 	    gui.row = gui_cursor_row;
824 # ifdef FEAT_MBYTE
825 	    gui.col = mb_fix_col(gui.col, gui.row);
826 # endif
827 	    gui_update_cursor(FALSE, FALSE);
828 	    gui_may_flush();
829 	    screen_cur_col = gui.col;
830 	    screen_cur_row = gui.row;
831 	}
832 	else
833 	    out_flush();
834 	gui_update_scrollbars(FALSE);
835     }
836 #endif
837     return OK;
838 }
839 
840 #if defined(FEAT_SIGNS) || defined(FEAT_GUI) || defined(FEAT_CONCEAL)
841 /*
842  * Prepare for updating one or more windows.
843  * Caller must check for "updating_screen" already set to avoid recursiveness.
844  */
845     static void
846 update_prepare(void)
847 {
848     cursor_off();
849     updating_screen = TRUE;
850 #ifdef FEAT_GUI
851     /* Remove the cursor before starting to do anything, because scrolling may
852      * make it difficult to redraw the text under it. */
853     if (gui.in_use)
854 	gui_undraw_cursor();
855 #endif
856 #ifdef FEAT_SEARCH_EXTRA
857     start_search_hl();
858 #endif
859 }
860 
861 /*
862  * Finish updating one or more windows.
863  */
864     static void
865 update_finish(void)
866 {
867     if (redraw_cmdline)
868 	showmode();
869 
870 # ifdef FEAT_SEARCH_EXTRA
871     end_search_hl();
872 # endif
873 
874     reset_updating_screen(TRUE);
875 
876 # ifdef FEAT_GUI
877     /* Redraw the cursor and update the scrollbars when all screen updating is
878      * done. */
879     if (gui.in_use)
880     {
881 	out_flush_cursor(FALSE, FALSE);
882 	gui_update_scrollbars(FALSE);
883     }
884 # endif
885 }
886 #endif
887 
888 #if defined(FEAT_CONCEAL) || defined(PROTO)
889 /*
890  * Return TRUE if the cursor line in window "wp" may be concealed, according
891  * to the 'concealcursor' option.
892  */
893     int
894 conceal_cursor_line(win_T *wp)
895 {
896     int		c;
897 
898     if (*wp->w_p_cocu == NUL)
899 	return FALSE;
900     if (get_real_state() & VISUAL)
901 	c = 'v';
902     else if (State & INSERT)
903 	c = 'i';
904     else if (State & NORMAL)
905 	c = 'n';
906     else if (State & CMDLINE)
907 	c = 'c';
908     else
909 	return FALSE;
910     return vim_strchr(wp->w_p_cocu, c) != NULL;
911 }
912 
913 /*
914  * Check if the cursor line needs to be redrawn because of 'concealcursor'.
915  */
916     void
917 conceal_check_cursor_line(void)
918 {
919     if (curwin->w_p_cole > 0 && conceal_cursor_line(curwin))
920     {
921 	need_cursor_line_redraw = TRUE;
922 	/* Need to recompute cursor column, e.g., when starting Visual mode
923 	 * without concealing. */
924 	curs_columns(TRUE);
925     }
926 }
927 
928     void
929 update_single_line(win_T *wp, linenr_T lnum)
930 {
931     int		row;
932     int		j;
933 #ifdef SYN_TIME_LIMIT
934     proftime_T	syntax_tm;
935 #endif
936 
937     /* Don't do anything if the screen structures are (not yet) valid. */
938     if (!screen_valid(TRUE) || updating_screen)
939 	return;
940 
941     if (lnum >= wp->w_topline && lnum < wp->w_botline
942 				 && foldedCount(wp, lnum, &win_foldinfo) == 0)
943     {
944 #ifdef SYN_TIME_LIMIT
945 	/* Set the time limit to 'redrawtime'. */
946 	profile_setlimit(p_rdt, &syntax_tm);
947 	syn_set_timeout(&syntax_tm);
948 #endif
949 	update_prepare();
950 
951 	row = 0;
952 	for (j = 0; j < wp->w_lines_valid; ++j)
953 	{
954 	    if (lnum == wp->w_lines[j].wl_lnum)
955 	    {
956 		screen_start();	/* not sure of screen cursor */
957 # ifdef FEAT_SEARCH_EXTRA
958 		init_search_hl(wp);
959 		start_search_hl();
960 		prepare_search_hl(wp, lnum);
961 # endif
962 		win_line(wp, lnum, row, row + wp->w_lines[j].wl_size, FALSE);
963 # if defined(FEAT_SEARCH_EXTRA)
964 		end_search_hl();
965 # endif
966 		break;
967 	    }
968 	    row += wp->w_lines[j].wl_size;
969 	}
970 
971 	update_finish();
972 
973 #ifdef SYN_TIME_LIMIT
974 	syn_set_timeout(NULL);
975 #endif
976     }
977     need_cursor_line_redraw = FALSE;
978 }
979 #endif
980 
981 #if defined(FEAT_SIGNS) || defined(PROTO)
982     void
983 update_debug_sign(buf_T *buf, linenr_T lnum)
984 {
985     win_T	*wp;
986     int		doit = FALSE;
987 
988 # ifdef FEAT_FOLDING
989     win_foldinfo.fi_level = 0;
990 # endif
991 
992     /* update/delete a specific mark */
993     FOR_ALL_WINDOWS(wp)
994     {
995 	if (buf != NULL && lnum > 0)
996 	{
997 	    if (wp->w_buffer == buf && lnum >= wp->w_topline
998 						      && lnum < wp->w_botline)
999 	    {
1000 		if (wp->w_redraw_top == 0 || wp->w_redraw_top > lnum)
1001 		    wp->w_redraw_top = lnum;
1002 		if (wp->w_redraw_bot == 0 || wp->w_redraw_bot < lnum)
1003 		    wp->w_redraw_bot = lnum;
1004 		redraw_win_later(wp, VALID);
1005 	    }
1006 	}
1007 	else
1008 	    redraw_win_later(wp, VALID);
1009 	if (wp->w_redr_type != 0)
1010 	    doit = TRUE;
1011     }
1012 
1013     /* Return when there is nothing to do, screen updating is already
1014      * happening (recursive call), messages on the screen or still starting up.
1015      */
1016     if (!doit || updating_screen
1017 	    || State == ASKMORE || State == HITRETURN
1018 	    || msg_scrolled
1019 #ifdef FEAT_GUI
1020 	    || gui.starting
1021 #endif
1022 	    || starting)
1023 	return;
1024 
1025     /* update all windows that need updating */
1026     update_prepare();
1027 
1028     FOR_ALL_WINDOWS(wp)
1029     {
1030 	if (wp->w_redr_type != 0)
1031 	    win_update(wp);
1032 	if (wp->w_redr_status)
1033 	    win_redr_status(wp, FALSE);
1034     }
1035 
1036     update_finish();
1037 }
1038 #endif
1039 
1040 
1041 #if defined(FEAT_GUI) || defined(PROTO)
1042 /*
1043  * Update a single window, its status line and maybe the command line msg.
1044  * Used for the GUI scrollbar.
1045  */
1046     void
1047 updateWindow(win_T *wp)
1048 {
1049     /* return if already busy updating */
1050     if (updating_screen)
1051 	return;
1052 
1053     update_prepare();
1054 
1055 #ifdef FEAT_CLIPBOARD
1056     /* When Visual area changed, may have to update selection. */
1057     if (clip_star.available && clip_isautosel_star())
1058 	clip_update_selection(&clip_star);
1059     if (clip_plus.available && clip_isautosel_plus())
1060 	clip_update_selection(&clip_plus);
1061 #endif
1062 
1063     win_update(wp);
1064 
1065     /* When the screen was cleared redraw the tab pages line. */
1066     if (redraw_tabline)
1067 	draw_tabline();
1068 
1069     if (wp->w_redr_status
1070 # ifdef FEAT_CMDL_INFO
1071 	    || p_ru
1072 # endif
1073 # ifdef FEAT_STL_OPT
1074 	    || *p_stl != NUL || *wp->w_p_stl != NUL
1075 # endif
1076 	    )
1077 	win_redr_status(wp, FALSE);
1078 
1079     update_finish();
1080 }
1081 #endif
1082 
1083 /*
1084  * Update a single window.
1085  *
1086  * This may cause the windows below it also to be redrawn (when clearing the
1087  * screen or scrolling lines).
1088  *
1089  * How the window is redrawn depends on wp->w_redr_type.  Each type also
1090  * implies the one below it.
1091  * NOT_VALID	redraw the whole window
1092  * SOME_VALID	redraw the whole window but do scroll when possible
1093  * REDRAW_TOP	redraw the top w_upd_rows window lines, otherwise like VALID
1094  * INVERTED	redraw the changed part of the Visual area
1095  * INVERTED_ALL	redraw the whole Visual area
1096  * VALID	1. scroll up/down to adjust for a changed w_topline
1097  *		2. update lines at the top when scrolled down
1098  *		3. redraw changed text:
1099  *		   - if wp->w_buffer->b_mod_set set, update lines between
1100  *		     b_mod_top and b_mod_bot.
1101  *		   - if wp->w_redraw_top non-zero, redraw lines between
1102  *		     wp->w_redraw_top and wp->w_redr_bot.
1103  *		   - continue redrawing when syntax status is invalid.
1104  *		4. if scrolled up, update lines at the bottom.
1105  * This results in three areas that may need updating:
1106  * top:	from first row to top_end (when scrolled down)
1107  * mid: from mid_start to mid_end (update inversion or changed text)
1108  * bot: from bot_start to last row (when scrolled up)
1109  */
1110     static void
1111 win_update(win_T *wp)
1112 {
1113     buf_T	*buf = wp->w_buffer;
1114     int		type;
1115     int		top_end = 0;	/* Below last row of the top area that needs
1116 				   updating.  0 when no top area updating. */
1117     int		mid_start = 999;/* first row of the mid area that needs
1118 				   updating.  999 when no mid area updating. */
1119     int		mid_end = 0;	/* Below last row of the mid area that needs
1120 				   updating.  0 when no mid area updating. */
1121     int		bot_start = 999;/* first row of the bot area that needs
1122 				   updating.  999 when no bot area updating */
1123     int		scrolled_down = FALSE;	/* TRUE when scrolled down when
1124 					   w_topline got smaller a bit */
1125 #ifdef FEAT_SEARCH_EXTRA
1126     matchitem_T *cur;		/* points to the match list */
1127     int		top_to_mod = FALSE;    /* redraw above mod_top */
1128 #endif
1129 
1130     int		row;		/* current window row to display */
1131     linenr_T	lnum;		/* current buffer lnum to display */
1132     int		idx;		/* current index in w_lines[] */
1133     int		srow;		/* starting row of the current line */
1134 
1135     int		eof = FALSE;	/* if TRUE, we hit the end of the file */
1136     int		didline = FALSE; /* if TRUE, we finished the last line */
1137     int		i;
1138     long	j;
1139     static int	recursive = FALSE;	/* being called recursively */
1140     int		old_botline = wp->w_botline;
1141 #ifdef FEAT_FOLDING
1142     long	fold_count;
1143 #endif
1144 #ifdef FEAT_SYN_HL
1145     /* remember what happened to the previous line, to know if
1146      * check_visual_highlight() can be used */
1147 #define DID_NONE 1	/* didn't update a line */
1148 #define DID_LINE 2	/* updated a normal line */
1149 #define DID_FOLD 3	/* updated a folded line */
1150     int		did_update = DID_NONE;
1151     linenr_T	syntax_last_parsed = 0;		/* last parsed text line */
1152 #endif
1153     linenr_T	mod_top = 0;
1154     linenr_T	mod_bot = 0;
1155 #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA)
1156     int		save_got_int;
1157 #endif
1158 #ifdef SYN_TIME_LIMIT
1159     proftime_T	syntax_tm;
1160 #endif
1161 
1162     type = wp->w_redr_type;
1163 
1164     if (type == NOT_VALID)
1165     {
1166 	wp->w_redr_status = TRUE;
1167 	wp->w_lines_valid = 0;
1168     }
1169 
1170     /* Window is zero-height: nothing to draw. */
1171     if (wp->w_height + WINBAR_HEIGHT(wp) == 0)
1172     {
1173 	wp->w_redr_type = 0;
1174 	return;
1175     }
1176 
1177     /* Window is zero-width: Only need to draw the separator. */
1178     if (wp->w_width == 0)
1179     {
1180 	/* draw the vertical separator right of this window */
1181 	draw_vsep_win(wp, 0);
1182 	wp->w_redr_type = 0;
1183 	return;
1184     }
1185 
1186 #ifdef FEAT_TERMINAL
1187     // If this window contains a terminal, redraw works completely differently.
1188     if (term_do_update_window(wp))
1189     {
1190 	term_update_window(wp);
1191 # ifdef FEAT_MENU
1192 	/* Draw the window toolbar, if there is one. */
1193 	if (winbar_height(wp) > 0)
1194 	    redraw_win_toolbar(wp);
1195 # endif
1196 	wp->w_redr_type = 0;
1197 	return;
1198     }
1199 #endif
1200 
1201 #ifdef FEAT_SEARCH_EXTRA
1202     init_search_hl(wp);
1203 #endif
1204 
1205 #ifdef FEAT_LINEBREAK
1206     /* Force redraw when width of 'number' or 'relativenumber' column
1207      * changes. */
1208     i = (wp->w_p_nu || wp->w_p_rnu) ? number_width(wp) : 0;
1209     if (wp->w_nrwidth != i)
1210     {
1211 	type = NOT_VALID;
1212 	wp->w_nrwidth = i;
1213     }
1214     else
1215 #endif
1216 
1217     if (buf->b_mod_set && buf->b_mod_xlines != 0 && wp->w_redraw_top != 0)
1218     {
1219 	/*
1220 	 * When there are both inserted/deleted lines and specific lines to be
1221 	 * redrawn, w_redraw_top and w_redraw_bot may be invalid, just redraw
1222 	 * everything (only happens when redrawing is off for while).
1223 	 */
1224 	type = NOT_VALID;
1225     }
1226     else
1227     {
1228 	/*
1229 	 * Set mod_top to the first line that needs displaying because of
1230 	 * changes.  Set mod_bot to the first line after the changes.
1231 	 */
1232 	mod_top = wp->w_redraw_top;
1233 	if (wp->w_redraw_bot != 0)
1234 	    mod_bot = wp->w_redraw_bot + 1;
1235 	else
1236 	    mod_bot = 0;
1237 	wp->w_redraw_top = 0;	/* reset for next time */
1238 	wp->w_redraw_bot = 0;
1239 	if (buf->b_mod_set)
1240 	{
1241 	    if (mod_top == 0 || mod_top > buf->b_mod_top)
1242 	    {
1243 		mod_top = buf->b_mod_top;
1244 #ifdef FEAT_SYN_HL
1245 		/* Need to redraw lines above the change that may be included
1246 		 * in a pattern match. */
1247 		if (syntax_present(wp))
1248 		{
1249 		    mod_top -= buf->b_s.b_syn_sync_linebreaks;
1250 		    if (mod_top < 1)
1251 			mod_top = 1;
1252 		}
1253 #endif
1254 	    }
1255 	    if (mod_bot == 0 || mod_bot < buf->b_mod_bot)
1256 		mod_bot = buf->b_mod_bot;
1257 
1258 #ifdef FEAT_SEARCH_EXTRA
1259 	    /* When 'hlsearch' is on and using a multi-line search pattern, a
1260 	     * change in one line may make the Search highlighting in a
1261 	     * previous line invalid.  Simple solution: redraw all visible
1262 	     * lines above the change.
1263 	     * Same for a match pattern.
1264 	     */
1265 	    if (search_hl.rm.regprog != NULL
1266 					&& re_multiline(search_hl.rm.regprog))
1267 		top_to_mod = TRUE;
1268 	    else
1269 	    {
1270 		cur = wp->w_match_head;
1271 		while (cur != NULL)
1272 		{
1273 		    if (cur->match.regprog != NULL
1274 					   && re_multiline(cur->match.regprog))
1275 		    {
1276 			top_to_mod = TRUE;
1277 			break;
1278 		    }
1279 		    cur = cur->next;
1280 		}
1281 	    }
1282 #endif
1283 	}
1284 #ifdef FEAT_FOLDING
1285 	if (mod_top != 0 && hasAnyFolding(wp))
1286 	{
1287 	    linenr_T	lnumt, lnumb;
1288 
1289 	    /*
1290 	     * A change in a line can cause lines above it to become folded or
1291 	     * unfolded.  Find the top most buffer line that may be affected.
1292 	     * If the line was previously folded and displayed, get the first
1293 	     * line of that fold.  If the line is folded now, get the first
1294 	     * folded line.  Use the minimum of these two.
1295 	     */
1296 
1297 	    /* Find last valid w_lines[] entry above mod_top.  Set lnumt to
1298 	     * the line below it.  If there is no valid entry, use w_topline.
1299 	     * Find the first valid w_lines[] entry below mod_bot.  Set lnumb
1300 	     * to this line.  If there is no valid entry, use MAXLNUM. */
1301 	    lnumt = wp->w_topline;
1302 	    lnumb = MAXLNUM;
1303 	    for (i = 0; i < wp->w_lines_valid; ++i)
1304 		if (wp->w_lines[i].wl_valid)
1305 		{
1306 		    if (wp->w_lines[i].wl_lastlnum < mod_top)
1307 			lnumt = wp->w_lines[i].wl_lastlnum + 1;
1308 		    if (lnumb == MAXLNUM && wp->w_lines[i].wl_lnum >= mod_bot)
1309 		    {
1310 			lnumb = wp->w_lines[i].wl_lnum;
1311 			/* When there is a fold column it might need updating
1312 			 * in the next line ("J" just above an open fold). */
1313 			if (compute_foldcolumn(wp, 0) > 0)
1314 			    ++lnumb;
1315 		    }
1316 		}
1317 
1318 	    (void)hasFoldingWin(wp, mod_top, &mod_top, NULL, TRUE, NULL);
1319 	    if (mod_top > lnumt)
1320 		mod_top = lnumt;
1321 
1322 	    /* Now do the same for the bottom line (one above mod_bot). */
1323 	    --mod_bot;
1324 	    (void)hasFoldingWin(wp, mod_bot, NULL, &mod_bot, TRUE, NULL);
1325 	    ++mod_bot;
1326 	    if (mod_bot < lnumb)
1327 		mod_bot = lnumb;
1328 	}
1329 #endif
1330 
1331 	/* When a change starts above w_topline and the end is below
1332 	 * w_topline, start redrawing at w_topline.
1333 	 * If the end of the change is above w_topline: do like no change was
1334 	 * made, but redraw the first line to find changes in syntax. */
1335 	if (mod_top != 0 && mod_top < wp->w_topline)
1336 	{
1337 	    if (mod_bot > wp->w_topline)
1338 		mod_top = wp->w_topline;
1339 #ifdef FEAT_SYN_HL
1340 	    else if (syntax_present(wp))
1341 		top_end = 1;
1342 #endif
1343 	}
1344 
1345 	/* When line numbers are displayed need to redraw all lines below
1346 	 * inserted/deleted lines. */
1347 	if (mod_top != 0 && buf->b_mod_xlines != 0 && wp->w_p_nu)
1348 	    mod_bot = MAXLNUM;
1349     }
1350 
1351     /*
1352      * When only displaying the lines at the top, set top_end.  Used when
1353      * window has scrolled down for msg_scrolled.
1354      */
1355     if (type == REDRAW_TOP)
1356     {
1357 	j = 0;
1358 	for (i = 0; i < wp->w_lines_valid; ++i)
1359 	{
1360 	    j += wp->w_lines[i].wl_size;
1361 	    if (j >= wp->w_upd_rows)
1362 	    {
1363 		top_end = j;
1364 		break;
1365 	    }
1366 	}
1367 	if (top_end == 0)
1368 	    /* not found (cannot happen?): redraw everything */
1369 	    type = NOT_VALID;
1370 	else
1371 	    /* top area defined, the rest is VALID */
1372 	    type = VALID;
1373     }
1374 
1375     /* Trick: we want to avoid clearing the screen twice.  screenclear() will
1376      * set "screen_cleared" to TRUE.  The special value MAYBE (which is still
1377      * non-zero and thus not FALSE) will indicate that screenclear() was not
1378      * called. */
1379     if (screen_cleared)
1380 	screen_cleared = MAYBE;
1381 
1382     /*
1383      * If there are no changes on the screen that require a complete redraw,
1384      * handle three cases:
1385      * 1: we are off the top of the screen by a few lines: scroll down
1386      * 2: wp->w_topline is below wp->w_lines[0].wl_lnum: may scroll up
1387      * 3: wp->w_topline is wp->w_lines[0].wl_lnum: find first entry in
1388      *    w_lines[] that needs updating.
1389      */
1390     if ((type == VALID || type == SOME_VALID
1391 				  || type == INVERTED || type == INVERTED_ALL)
1392 #ifdef FEAT_DIFF
1393 	    && !wp->w_botfill && !wp->w_old_botfill
1394 #endif
1395 	    )
1396     {
1397 	if (mod_top != 0 && wp->w_topline == mod_top)
1398 	{
1399 	    /*
1400 	     * w_topline is the first changed line, the scrolling will be done
1401 	     * further down.
1402 	     */
1403 	}
1404 	else if (wp->w_lines[0].wl_valid
1405 		&& (wp->w_topline < wp->w_lines[0].wl_lnum
1406 #ifdef FEAT_DIFF
1407 		    || (wp->w_topline == wp->w_lines[0].wl_lnum
1408 			&& wp->w_topfill > wp->w_old_topfill)
1409 #endif
1410 		   ))
1411 	{
1412 	    /*
1413 	     * New topline is above old topline: May scroll down.
1414 	     */
1415 #ifdef FEAT_FOLDING
1416 	    if (hasAnyFolding(wp))
1417 	    {
1418 		linenr_T ln;
1419 
1420 		/* count the number of lines we are off, counting a sequence
1421 		 * of folded lines as one */
1422 		j = 0;
1423 		for (ln = wp->w_topline; ln < wp->w_lines[0].wl_lnum; ++ln)
1424 		{
1425 		    ++j;
1426 		    if (j >= wp->w_height - 2)
1427 			break;
1428 		    (void)hasFoldingWin(wp, ln, NULL, &ln, TRUE, NULL);
1429 		}
1430 	    }
1431 	    else
1432 #endif
1433 		j = wp->w_lines[0].wl_lnum - wp->w_topline;
1434 	    if (j < wp->w_height - 2)		/* not too far off */
1435 	    {
1436 		i = plines_m_win(wp, wp->w_topline, wp->w_lines[0].wl_lnum - 1);
1437 #ifdef FEAT_DIFF
1438 		/* insert extra lines for previously invisible filler lines */
1439 		if (wp->w_lines[0].wl_lnum != wp->w_topline)
1440 		    i += diff_check_fill(wp, wp->w_lines[0].wl_lnum)
1441 							  - wp->w_old_topfill;
1442 #endif
1443 		if (i < wp->w_height - 2)	/* less than a screen off */
1444 		{
1445 		    /*
1446 		     * Try to insert the correct number of lines.
1447 		     * If not the last window, delete the lines at the bottom.
1448 		     * win_ins_lines may fail when the terminal can't do it.
1449 		     */
1450 		    if (i > 0)
1451 			check_for_delay(FALSE);
1452 		    if (win_ins_lines(wp, 0, i, FALSE, wp == firstwin) == OK)
1453 		    {
1454 			if (wp->w_lines_valid != 0)
1455 			{
1456 			    /* Need to update rows that are new, stop at the
1457 			     * first one that scrolled down. */
1458 			    top_end = i;
1459 			    scrolled_down = TRUE;
1460 
1461 			    /* Move the entries that were scrolled, disable
1462 			     * the entries for the lines to be redrawn. */
1463 			    if ((wp->w_lines_valid += j) > wp->w_height)
1464 				wp->w_lines_valid = wp->w_height;
1465 			    for (idx = wp->w_lines_valid; idx - j >= 0; idx--)
1466 				wp->w_lines[idx] = wp->w_lines[idx - j];
1467 			    while (idx >= 0)
1468 				wp->w_lines[idx--].wl_valid = FALSE;
1469 			}
1470 		    }
1471 		    else
1472 			mid_start = 0;		/* redraw all lines */
1473 		}
1474 		else
1475 		    mid_start = 0;		/* redraw all lines */
1476 	    }
1477 	    else
1478 		mid_start = 0;		/* redraw all lines */
1479 	}
1480 	else
1481 	{
1482 	    /*
1483 	     * New topline is at or below old topline: May scroll up.
1484 	     * When topline didn't change, find first entry in w_lines[] that
1485 	     * needs updating.
1486 	     */
1487 
1488 	    /* try to find wp->w_topline in wp->w_lines[].wl_lnum */
1489 	    j = -1;
1490 	    row = 0;
1491 	    for (i = 0; i < wp->w_lines_valid; i++)
1492 	    {
1493 		if (wp->w_lines[i].wl_valid
1494 			&& wp->w_lines[i].wl_lnum == wp->w_topline)
1495 		{
1496 		    j = i;
1497 		    break;
1498 		}
1499 		row += wp->w_lines[i].wl_size;
1500 	    }
1501 	    if (j == -1)
1502 	    {
1503 		/* if wp->w_topline is not in wp->w_lines[].wl_lnum redraw all
1504 		 * lines */
1505 		mid_start = 0;
1506 	    }
1507 	    else
1508 	    {
1509 		/*
1510 		 * Try to delete the correct number of lines.
1511 		 * wp->w_topline is at wp->w_lines[i].wl_lnum.
1512 		 */
1513 #ifdef FEAT_DIFF
1514 		/* If the topline didn't change, delete old filler lines,
1515 		 * otherwise delete filler lines of the new topline... */
1516 		if (wp->w_lines[0].wl_lnum == wp->w_topline)
1517 		    row += wp->w_old_topfill;
1518 		else
1519 		    row += diff_check_fill(wp, wp->w_topline);
1520 		/* ... but don't delete new filler lines. */
1521 		row -= wp->w_topfill;
1522 #endif
1523 		if (row > 0)
1524 		{
1525 		    check_for_delay(FALSE);
1526 		    if (win_del_lines(wp, 0, row, FALSE, wp == firstwin, 0)
1527 									 == OK)
1528 			bot_start = wp->w_height - row;
1529 		    else
1530 			mid_start = 0;		/* redraw all lines */
1531 		}
1532 		if ((row == 0 || bot_start < 999) && wp->w_lines_valid != 0)
1533 		{
1534 		    /*
1535 		     * Skip the lines (below the deleted lines) that are still
1536 		     * valid and don't need redrawing.	Copy their info
1537 		     * upwards, to compensate for the deleted lines.  Set
1538 		     * bot_start to the first row that needs redrawing.
1539 		     */
1540 		    bot_start = 0;
1541 		    idx = 0;
1542 		    for (;;)
1543 		    {
1544 			wp->w_lines[idx] = wp->w_lines[j];
1545 			/* stop at line that didn't fit, unless it is still
1546 			 * valid (no lines deleted) */
1547 			if (row > 0 && bot_start + row
1548 				 + (int)wp->w_lines[j].wl_size > wp->w_height)
1549 			{
1550 			    wp->w_lines_valid = idx + 1;
1551 			    break;
1552 			}
1553 			bot_start += wp->w_lines[idx++].wl_size;
1554 
1555 			/* stop at the last valid entry in w_lines[].wl_size */
1556 			if (++j >= wp->w_lines_valid)
1557 			{
1558 			    wp->w_lines_valid = idx;
1559 			    break;
1560 			}
1561 		    }
1562 #ifdef FEAT_DIFF
1563 		    /* Correct the first entry for filler lines at the top
1564 		     * when it won't get updated below. */
1565 		    if (wp->w_p_diff && bot_start > 0)
1566 			wp->w_lines[0].wl_size =
1567 			    plines_win_nofill(wp, wp->w_topline, TRUE)
1568 							      + wp->w_topfill;
1569 #endif
1570 		}
1571 	    }
1572 	}
1573 
1574 	/* When starting redraw in the first line, redraw all lines.  When
1575 	 * there is only one window it's probably faster to clear the screen
1576 	 * first. */
1577 	if (mid_start == 0)
1578 	{
1579 	    mid_end = wp->w_height;
1580 	    if (ONE_WINDOW)
1581 	    {
1582 		/* Clear the screen when it was not done by win_del_lines() or
1583 		 * win_ins_lines() above, "screen_cleared" is FALSE or MAYBE
1584 		 * then. */
1585 		if (screen_cleared != TRUE)
1586 		    screenclear();
1587 		/* The screen was cleared, redraw the tab pages line. */
1588 		if (redraw_tabline)
1589 		    draw_tabline();
1590 	    }
1591 	}
1592 
1593 	/* When win_del_lines() or win_ins_lines() caused the screen to be
1594 	 * cleared (only happens for the first window) or when screenclear()
1595 	 * was called directly above, "must_redraw" will have been set to
1596 	 * NOT_VALID, need to reset it here to avoid redrawing twice. */
1597 	if (screen_cleared == TRUE)
1598 	    must_redraw = 0;
1599     }
1600     else
1601     {
1602 	/* Not VALID or INVERTED: redraw all lines. */
1603 	mid_start = 0;
1604 	mid_end = wp->w_height;
1605     }
1606 
1607     if (type == SOME_VALID)
1608     {
1609 	/* SOME_VALID: redraw all lines. */
1610 	mid_start = 0;
1611 	mid_end = wp->w_height;
1612 	type = NOT_VALID;
1613     }
1614 
1615     /* check if we are updating or removing the inverted part */
1616     if ((VIsual_active && buf == curwin->w_buffer)
1617 	    || (wp->w_old_cursor_lnum != 0 && type != NOT_VALID))
1618     {
1619 	linenr_T    from, to;
1620 
1621 	if (VIsual_active)
1622 	{
1623 	    if (VIsual_active
1624 		    && (VIsual_mode != wp->w_old_visual_mode
1625 			|| type == INVERTED_ALL))
1626 	    {
1627 		/*
1628 		 * If the type of Visual selection changed, redraw the whole
1629 		 * selection.  Also when the ownership of the X selection is
1630 		 * gained or lost.
1631 		 */
1632 		if (curwin->w_cursor.lnum < VIsual.lnum)
1633 		{
1634 		    from = curwin->w_cursor.lnum;
1635 		    to = VIsual.lnum;
1636 		}
1637 		else
1638 		{
1639 		    from = VIsual.lnum;
1640 		    to = curwin->w_cursor.lnum;
1641 		}
1642 		/* redraw more when the cursor moved as well */
1643 		if (wp->w_old_cursor_lnum < from)
1644 		    from = wp->w_old_cursor_lnum;
1645 		if (wp->w_old_cursor_lnum > to)
1646 		    to = wp->w_old_cursor_lnum;
1647 		if (wp->w_old_visual_lnum < from)
1648 		    from = wp->w_old_visual_lnum;
1649 		if (wp->w_old_visual_lnum > to)
1650 		    to = wp->w_old_visual_lnum;
1651 	    }
1652 	    else
1653 	    {
1654 		/*
1655 		 * Find the line numbers that need to be updated: The lines
1656 		 * between the old cursor position and the current cursor
1657 		 * position.  Also check if the Visual position changed.
1658 		 */
1659 		if (curwin->w_cursor.lnum < wp->w_old_cursor_lnum)
1660 		{
1661 		    from = curwin->w_cursor.lnum;
1662 		    to = wp->w_old_cursor_lnum;
1663 		}
1664 		else
1665 		{
1666 		    from = wp->w_old_cursor_lnum;
1667 		    to = curwin->w_cursor.lnum;
1668 		    if (from == 0)	/* Visual mode just started */
1669 			from = to;
1670 		}
1671 
1672 		if (VIsual.lnum != wp->w_old_visual_lnum
1673 					|| VIsual.col != wp->w_old_visual_col)
1674 		{
1675 		    if (wp->w_old_visual_lnum < from
1676 						&& wp->w_old_visual_lnum != 0)
1677 			from = wp->w_old_visual_lnum;
1678 		    if (wp->w_old_visual_lnum > to)
1679 			to = wp->w_old_visual_lnum;
1680 		    if (VIsual.lnum < from)
1681 			from = VIsual.lnum;
1682 		    if (VIsual.lnum > to)
1683 			to = VIsual.lnum;
1684 		}
1685 	    }
1686 
1687 	    /*
1688 	     * If in block mode and changed column or curwin->w_curswant:
1689 	     * update all lines.
1690 	     * First compute the actual start and end column.
1691 	     */
1692 	    if (VIsual_mode == Ctrl_V)
1693 	    {
1694 		colnr_T	    fromc, toc;
1695 #if defined(FEAT_VIRTUALEDIT) && defined(FEAT_LINEBREAK)
1696 		int	    save_ve_flags = ve_flags;
1697 
1698 		if (curwin->w_p_lbr)
1699 		    ve_flags = VE_ALL;
1700 #endif
1701 		getvcols(wp, &VIsual, &curwin->w_cursor, &fromc, &toc);
1702 #if defined(FEAT_VIRTUALEDIT) && defined(FEAT_LINEBREAK)
1703 		ve_flags = save_ve_flags;
1704 #endif
1705 		++toc;
1706 		if (curwin->w_curswant == MAXCOL)
1707 		    toc = MAXCOL;
1708 
1709 		if (fromc != wp->w_old_cursor_fcol
1710 			|| toc != wp->w_old_cursor_lcol)
1711 		{
1712 		    if (from > VIsual.lnum)
1713 			from = VIsual.lnum;
1714 		    if (to < VIsual.lnum)
1715 			to = VIsual.lnum;
1716 		}
1717 		wp->w_old_cursor_fcol = fromc;
1718 		wp->w_old_cursor_lcol = toc;
1719 	    }
1720 	}
1721 	else
1722 	{
1723 	    /* Use the line numbers of the old Visual area. */
1724 	    if (wp->w_old_cursor_lnum < wp->w_old_visual_lnum)
1725 	    {
1726 		from = wp->w_old_cursor_lnum;
1727 		to = wp->w_old_visual_lnum;
1728 	    }
1729 	    else
1730 	    {
1731 		from = wp->w_old_visual_lnum;
1732 		to = wp->w_old_cursor_lnum;
1733 	    }
1734 	}
1735 
1736 	/*
1737 	 * There is no need to update lines above the top of the window.
1738 	 */
1739 	if (from < wp->w_topline)
1740 	    from = wp->w_topline;
1741 
1742 	/*
1743 	 * If we know the value of w_botline, use it to restrict the update to
1744 	 * the lines that are visible in the window.
1745 	 */
1746 	if (wp->w_valid & VALID_BOTLINE)
1747 	{
1748 	    if (from >= wp->w_botline)
1749 		from = wp->w_botline - 1;
1750 	    if (to >= wp->w_botline)
1751 		to = wp->w_botline - 1;
1752 	}
1753 
1754 	/*
1755 	 * Find the minimal part to be updated.
1756 	 * Watch out for scrolling that made entries in w_lines[] invalid.
1757 	 * E.g., CTRL-U makes the first half of w_lines[] invalid and sets
1758 	 * top_end; need to redraw from top_end to the "to" line.
1759 	 * A middle mouse click with a Visual selection may change the text
1760 	 * above the Visual area and reset wl_valid, do count these for
1761 	 * mid_end (in srow).
1762 	 */
1763 	if (mid_start > 0)
1764 	{
1765 	    lnum = wp->w_topline;
1766 	    idx = 0;
1767 	    srow = 0;
1768 	    if (scrolled_down)
1769 		mid_start = top_end;
1770 	    else
1771 		mid_start = 0;
1772 	    while (lnum < from && idx < wp->w_lines_valid)	/* find start */
1773 	    {
1774 		if (wp->w_lines[idx].wl_valid)
1775 		    mid_start += wp->w_lines[idx].wl_size;
1776 		else if (!scrolled_down)
1777 		    srow += wp->w_lines[idx].wl_size;
1778 		++idx;
1779 # ifdef FEAT_FOLDING
1780 		if (idx < wp->w_lines_valid && wp->w_lines[idx].wl_valid)
1781 		    lnum = wp->w_lines[idx].wl_lnum;
1782 		else
1783 # endif
1784 		    ++lnum;
1785 	    }
1786 	    srow += mid_start;
1787 	    mid_end = wp->w_height;
1788 	    for ( ; idx < wp->w_lines_valid; ++idx)		/* find end */
1789 	    {
1790 		if (wp->w_lines[idx].wl_valid
1791 			&& wp->w_lines[idx].wl_lnum >= to + 1)
1792 		{
1793 		    /* Only update until first row of this line */
1794 		    mid_end = srow;
1795 		    break;
1796 		}
1797 		srow += wp->w_lines[idx].wl_size;
1798 	    }
1799 	}
1800     }
1801 
1802     if (VIsual_active && buf == curwin->w_buffer)
1803     {
1804 	wp->w_old_visual_mode = VIsual_mode;
1805 	wp->w_old_cursor_lnum = curwin->w_cursor.lnum;
1806 	wp->w_old_visual_lnum = VIsual.lnum;
1807 	wp->w_old_visual_col = VIsual.col;
1808 	wp->w_old_curswant = curwin->w_curswant;
1809     }
1810     else
1811     {
1812 	wp->w_old_visual_mode = 0;
1813 	wp->w_old_cursor_lnum = 0;
1814 	wp->w_old_visual_lnum = 0;
1815 	wp->w_old_visual_col = 0;
1816     }
1817 
1818 #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA)
1819     /* reset got_int, otherwise regexp won't work */
1820     save_got_int = got_int;
1821     got_int = 0;
1822 #endif
1823 #ifdef SYN_TIME_LIMIT
1824     /* Set the time limit to 'redrawtime'. */
1825     profile_setlimit(p_rdt, &syntax_tm);
1826     syn_set_timeout(&syntax_tm);
1827 #endif
1828 #ifdef FEAT_FOLDING
1829     win_foldinfo.fi_level = 0;
1830 #endif
1831 
1832 #ifdef FEAT_MENU
1833     /*
1834      * Draw the window toolbar, if there is one.
1835      * TODO: only when needed.
1836      */
1837     if (winbar_height(wp) > 0)
1838 	redraw_win_toolbar(wp);
1839 #endif
1840 
1841     /*
1842      * Update all the window rows.
1843      */
1844     idx = 0;		/* first entry in w_lines[].wl_size */
1845     row = 0;
1846     srow = 0;
1847     lnum = wp->w_topline;	/* first line shown in window */
1848     for (;;)
1849     {
1850 	/* stop updating when reached the end of the window (check for _past_
1851 	 * the end of the window is at the end of the loop) */
1852 	if (row == wp->w_height)
1853 	{
1854 	    didline = TRUE;
1855 	    break;
1856 	}
1857 
1858 	/* stop updating when hit the end of the file */
1859 	if (lnum > buf->b_ml.ml_line_count)
1860 	{
1861 	    eof = TRUE;
1862 	    break;
1863 	}
1864 
1865 	/* Remember the starting row of the line that is going to be dealt
1866 	 * with.  It is used further down when the line doesn't fit. */
1867 	srow = row;
1868 
1869 	/*
1870 	 * Update a line when it is in an area that needs updating, when it
1871 	 * has changes or w_lines[idx] is invalid.
1872 	 * bot_start may be halfway a wrapped line after using
1873 	 * win_del_lines(), check if the current line includes it.
1874 	 * When syntax folding is being used, the saved syntax states will
1875 	 * already have been updated, we can't see where the syntax state is
1876 	 * the same again, just update until the end of the window.
1877 	 */
1878 	if (row < top_end
1879 		|| (row >= mid_start && row < mid_end)
1880 #ifdef FEAT_SEARCH_EXTRA
1881 		|| top_to_mod
1882 #endif
1883 		|| idx >= wp->w_lines_valid
1884 		|| (row + wp->w_lines[idx].wl_size > bot_start)
1885 		|| (mod_top != 0
1886 		    && (lnum == mod_top
1887 			|| (lnum >= mod_top
1888 			    && (lnum < mod_bot
1889 #ifdef FEAT_SYN_HL
1890 				|| did_update == DID_FOLD
1891 				|| (did_update == DID_LINE
1892 				    && syntax_present(wp)
1893 				    && (
1894 # ifdef FEAT_FOLDING
1895 					(foldmethodIsSyntax(wp)
1896 						      && hasAnyFolding(wp)) ||
1897 # endif
1898 					syntax_check_changed(lnum)))
1899 #endif
1900 #ifdef FEAT_SEARCH_EXTRA
1901 				/* match in fixed position might need redraw
1902 				 * if lines were inserted or deleted */
1903 				|| (wp->w_match_head != NULL
1904 						    && buf->b_mod_xlines != 0)
1905 #endif
1906 				)))))
1907 	{
1908 #ifdef FEAT_SEARCH_EXTRA
1909 	    if (lnum == mod_top)
1910 		top_to_mod = FALSE;
1911 #endif
1912 
1913 	    /*
1914 	     * When at start of changed lines: May scroll following lines
1915 	     * up or down to minimize redrawing.
1916 	     * Don't do this when the change continues until the end.
1917 	     * Don't scroll when dollar_vcol >= 0, keep the "$".
1918 	     */
1919 	    if (lnum == mod_top
1920 		    && mod_bot != MAXLNUM
1921 		    && !(dollar_vcol >= 0 && mod_bot == mod_top + 1))
1922 	    {
1923 		int		old_rows = 0;
1924 		int		new_rows = 0;
1925 		int		xtra_rows;
1926 		linenr_T	l;
1927 
1928 		/* Count the old number of window rows, using w_lines[], which
1929 		 * should still contain the sizes for the lines as they are
1930 		 * currently displayed. */
1931 		for (i = idx; i < wp->w_lines_valid; ++i)
1932 		{
1933 		    /* Only valid lines have a meaningful wl_lnum.  Invalid
1934 		     * lines are part of the changed area. */
1935 		    if (wp->w_lines[i].wl_valid
1936 			    && wp->w_lines[i].wl_lnum == mod_bot)
1937 			break;
1938 		    old_rows += wp->w_lines[i].wl_size;
1939 #ifdef FEAT_FOLDING
1940 		    if (wp->w_lines[i].wl_valid
1941 			    && wp->w_lines[i].wl_lastlnum + 1 == mod_bot)
1942 		    {
1943 			/* Must have found the last valid entry above mod_bot.
1944 			 * Add following invalid entries. */
1945 			++i;
1946 			while (i < wp->w_lines_valid
1947 						  && !wp->w_lines[i].wl_valid)
1948 			    old_rows += wp->w_lines[i++].wl_size;
1949 			break;
1950 		    }
1951 #endif
1952 		}
1953 
1954 		if (i >= wp->w_lines_valid)
1955 		{
1956 		    /* We can't find a valid line below the changed lines,
1957 		     * need to redraw until the end of the window.
1958 		     * Inserting/deleting lines has no use. */
1959 		    bot_start = 0;
1960 		}
1961 		else
1962 		{
1963 		    /* Able to count old number of rows: Count new window
1964 		     * rows, and may insert/delete lines */
1965 		    j = idx;
1966 		    for (l = lnum; l < mod_bot; ++l)
1967 		    {
1968 #ifdef FEAT_FOLDING
1969 			if (hasFoldingWin(wp, l, NULL, &l, TRUE, NULL))
1970 			    ++new_rows;
1971 			else
1972 #endif
1973 #ifdef FEAT_DIFF
1974 			    if (l == wp->w_topline)
1975 			    new_rows += plines_win_nofill(wp, l, TRUE)
1976 							      + wp->w_topfill;
1977 			else
1978 #endif
1979 			    new_rows += plines_win(wp, l, TRUE);
1980 			++j;
1981 			if (new_rows > wp->w_height - row - 2)
1982 			{
1983 			    /* it's getting too much, must redraw the rest */
1984 			    new_rows = 9999;
1985 			    break;
1986 			}
1987 		    }
1988 		    xtra_rows = new_rows - old_rows;
1989 		    if (xtra_rows < 0)
1990 		    {
1991 			/* May scroll text up.  If there is not enough
1992 			 * remaining text or scrolling fails, must redraw the
1993 			 * rest.  If scrolling works, must redraw the text
1994 			 * below the scrolled text. */
1995 			if (row - xtra_rows >= wp->w_height - 2)
1996 			    mod_bot = MAXLNUM;
1997 			else
1998 			{
1999 			    check_for_delay(FALSE);
2000 			    if (win_del_lines(wp, row,
2001 					  -xtra_rows, FALSE, FALSE, 0) == FAIL)
2002 				mod_bot = MAXLNUM;
2003 			    else
2004 				bot_start = wp->w_height + xtra_rows;
2005 			}
2006 		    }
2007 		    else if (xtra_rows > 0)
2008 		    {
2009 			/* May scroll text down.  If there is not enough
2010 			 * remaining text of scrolling fails, must redraw the
2011 			 * rest. */
2012 			if (row + xtra_rows >= wp->w_height - 2)
2013 			    mod_bot = MAXLNUM;
2014 			else
2015 			{
2016 			    check_for_delay(FALSE);
2017 			    if (win_ins_lines(wp, row + old_rows,
2018 					     xtra_rows, FALSE, FALSE) == FAIL)
2019 				mod_bot = MAXLNUM;
2020 			    else if (top_end > row + old_rows)
2021 				/* Scrolled the part at the top that requires
2022 				 * updating down. */
2023 				top_end += xtra_rows;
2024 			}
2025 		    }
2026 
2027 		    /* When not updating the rest, may need to move w_lines[]
2028 		     * entries. */
2029 		    if (mod_bot != MAXLNUM && i != j)
2030 		    {
2031 			if (j < i)
2032 			{
2033 			    int x = row + new_rows;
2034 
2035 			    /* move entries in w_lines[] upwards */
2036 			    for (;;)
2037 			    {
2038 				/* stop at last valid entry in w_lines[] */
2039 				if (i >= wp->w_lines_valid)
2040 				{
2041 				    wp->w_lines_valid = j;
2042 				    break;
2043 				}
2044 				wp->w_lines[j] = wp->w_lines[i];
2045 				/* stop at a line that won't fit */
2046 				if (x + (int)wp->w_lines[j].wl_size
2047 							   > wp->w_height)
2048 				{
2049 				    wp->w_lines_valid = j + 1;
2050 				    break;
2051 				}
2052 				x += wp->w_lines[j++].wl_size;
2053 				++i;
2054 			    }
2055 			    if (bot_start > x)
2056 				bot_start = x;
2057 			}
2058 			else /* j > i */
2059 			{
2060 			    /* move entries in w_lines[] downwards */
2061 			    j -= i;
2062 			    wp->w_lines_valid += j;
2063 			    if (wp->w_lines_valid > wp->w_height)
2064 				wp->w_lines_valid = wp->w_height;
2065 			    for (i = wp->w_lines_valid; i - j >= idx; --i)
2066 				wp->w_lines[i] = wp->w_lines[i - j];
2067 
2068 			    /* The w_lines[] entries for inserted lines are
2069 			     * now invalid, but wl_size may be used above.
2070 			     * Reset to zero. */
2071 			    while (i >= idx)
2072 			    {
2073 				wp->w_lines[i].wl_size = 0;
2074 				wp->w_lines[i--].wl_valid = FALSE;
2075 			    }
2076 			}
2077 		    }
2078 		}
2079 	    }
2080 
2081 #ifdef FEAT_FOLDING
2082 	    /*
2083 	     * When lines are folded, display one line for all of them.
2084 	     * Otherwise, display normally (can be several display lines when
2085 	     * 'wrap' is on).
2086 	     */
2087 	    fold_count = foldedCount(wp, lnum, &win_foldinfo);
2088 	    if (fold_count != 0)
2089 	    {
2090 		fold_line(wp, fold_count, &win_foldinfo, lnum, row);
2091 		++row;
2092 		--fold_count;
2093 		wp->w_lines[idx].wl_folded = TRUE;
2094 		wp->w_lines[idx].wl_lastlnum = lnum + fold_count;
2095 # ifdef FEAT_SYN_HL
2096 		did_update = DID_FOLD;
2097 # endif
2098 	    }
2099 	    else
2100 #endif
2101 	    if (idx < wp->w_lines_valid
2102 		    && wp->w_lines[idx].wl_valid
2103 		    && wp->w_lines[idx].wl_lnum == lnum
2104 		    && lnum > wp->w_topline
2105 		    && !(dy_flags & (DY_LASTLINE | DY_TRUNCATE))
2106 		    && srow + wp->w_lines[idx].wl_size > wp->w_height
2107 #ifdef FEAT_DIFF
2108 		    && diff_check_fill(wp, lnum) == 0
2109 #endif
2110 		    )
2111 	    {
2112 		/* This line is not going to fit.  Don't draw anything here,
2113 		 * will draw "@  " lines below. */
2114 		row = wp->w_height + 1;
2115 	    }
2116 	    else
2117 	    {
2118 #ifdef FEAT_SEARCH_EXTRA
2119 		prepare_search_hl(wp, lnum);
2120 #endif
2121 #ifdef FEAT_SYN_HL
2122 		/* Let the syntax stuff know we skipped a few lines. */
2123 		if (syntax_last_parsed != 0 && syntax_last_parsed + 1 < lnum
2124 						       && syntax_present(wp))
2125 		    syntax_end_parsing(syntax_last_parsed + 1);
2126 #endif
2127 
2128 		/*
2129 		 * Display one line.
2130 		 */
2131 		row = win_line(wp, lnum, srow, wp->w_height, mod_top == 0);
2132 
2133 #ifdef FEAT_FOLDING
2134 		wp->w_lines[idx].wl_folded = FALSE;
2135 		wp->w_lines[idx].wl_lastlnum = lnum;
2136 #endif
2137 #ifdef FEAT_SYN_HL
2138 		did_update = DID_LINE;
2139 		syntax_last_parsed = lnum;
2140 #endif
2141 	    }
2142 
2143 	    wp->w_lines[idx].wl_lnum = lnum;
2144 	    wp->w_lines[idx].wl_valid = TRUE;
2145 
2146 	    /* Past end of the window or end of the screen. Note that after
2147 	     * resizing wp->w_height may be end up too big. That's a problem
2148 	     * elsewhere, but prevent a crash here. */
2149 	    if (row > wp->w_height || row + wp->w_winrow >= Rows)
2150 	    {
2151 		/* we may need the size of that too long line later on */
2152 		if (dollar_vcol == -1)
2153 		    wp->w_lines[idx].wl_size = plines_win(wp, lnum, TRUE);
2154 		++idx;
2155 		break;
2156 	    }
2157 	    if (dollar_vcol == -1)
2158 		wp->w_lines[idx].wl_size = row - srow;
2159 	    ++idx;
2160 #ifdef FEAT_FOLDING
2161 	    lnum += fold_count + 1;
2162 #else
2163 	    ++lnum;
2164 #endif
2165 	}
2166 	else
2167 	{
2168 	    /* This line does not need updating, advance to the next one */
2169 	    row += wp->w_lines[idx++].wl_size;
2170 	    if (row > wp->w_height)	/* past end of screen */
2171 		break;
2172 #ifdef FEAT_FOLDING
2173 	    lnum = wp->w_lines[idx - 1].wl_lastlnum + 1;
2174 #else
2175 	    ++lnum;
2176 #endif
2177 #ifdef FEAT_SYN_HL
2178 	    did_update = DID_NONE;
2179 #endif
2180 	}
2181 
2182 	if (lnum > buf->b_ml.ml_line_count)
2183 	{
2184 	    eof = TRUE;
2185 	    break;
2186 	}
2187     }
2188     /*
2189      * End of loop over all window lines.
2190      */
2191 
2192 #ifdef FEAT_VTP
2193     /* Rewrite the character at the end of the screen line. */
2194     if (use_vtp())
2195     {
2196 	int i;
2197 
2198 	for (i = 0; i < Rows; ++i)
2199 # ifdef FEAT_MBYTE
2200 	    if (enc_utf8)
2201 		if ((*mb_off2cells)(LineOffset[i] + Columns - 2,
2202 					   LineOffset[i] + screen_Columns) > 1)
2203 		    screen_draw_rectangle(i, Columns - 2, 1, 2, FALSE);
2204 		else
2205 		    screen_draw_rectangle(i, Columns - 1, 1, 1, FALSE);
2206 	    else
2207 # endif
2208 		screen_char(LineOffset[i] + Columns - 1, i, Columns - 1);
2209     }
2210 #endif
2211 
2212     if (idx > wp->w_lines_valid)
2213 	wp->w_lines_valid = idx;
2214 
2215 #ifdef FEAT_SYN_HL
2216     /*
2217      * Let the syntax stuff know we stop parsing here.
2218      */
2219     if (syntax_last_parsed != 0 && syntax_present(wp))
2220 	syntax_end_parsing(syntax_last_parsed + 1);
2221 #endif
2222 
2223     /*
2224      * If we didn't hit the end of the file, and we didn't finish the last
2225      * line we were working on, then the line didn't fit.
2226      */
2227     wp->w_empty_rows = 0;
2228 #ifdef FEAT_DIFF
2229     wp->w_filler_rows = 0;
2230 #endif
2231     if (!eof && !didline)
2232     {
2233 	if (lnum == wp->w_topline)
2234 	{
2235 	    /*
2236 	     * Single line that does not fit!
2237 	     * Don't overwrite it, it can be edited.
2238 	     */
2239 	    wp->w_botline = lnum + 1;
2240 	}
2241 #ifdef FEAT_DIFF
2242 	else if (diff_check_fill(wp, lnum) >= wp->w_height - srow)
2243 	{
2244 	    /* Window ends in filler lines. */
2245 	    wp->w_botline = lnum;
2246 	    wp->w_filler_rows = wp->w_height - srow;
2247 	}
2248 #endif
2249 	else if (dy_flags & DY_TRUNCATE)	/* 'display' has "truncate" */
2250 	{
2251 	    int scr_row = W_WINROW(wp) + wp->w_height - 1;
2252 
2253 	    /*
2254 	     * Last line isn't finished: Display "@@@" in the last screen line.
2255 	     */
2256 	    screen_puts_len((char_u *)"@@", 2, scr_row, wp->w_wincol,
2257 							      HL_ATTR(HLF_AT));
2258 	    screen_fill(scr_row, scr_row + 1,
2259 		    (int)wp->w_wincol + 2, (int)W_ENDCOL(wp),
2260 		    '@', ' ', HL_ATTR(HLF_AT));
2261 	    set_empty_rows(wp, srow);
2262 	    wp->w_botline = lnum;
2263 	}
2264 	else if (dy_flags & DY_LASTLINE)	/* 'display' has "lastline" */
2265 	{
2266 	    /*
2267 	     * Last line isn't finished: Display "@@@" at the end.
2268 	     */
2269 	    screen_fill(W_WINROW(wp) + wp->w_height - 1,
2270 		    W_WINROW(wp) + wp->w_height,
2271 		    (int)W_ENDCOL(wp) - 3, (int)W_ENDCOL(wp),
2272 		    '@', '@', HL_ATTR(HLF_AT));
2273 	    set_empty_rows(wp, srow);
2274 	    wp->w_botline = lnum;
2275 	}
2276 	else
2277 	{
2278 	    win_draw_end(wp, '@', ' ', srow, wp->w_height, HLF_AT);
2279 	    wp->w_botline = lnum;
2280 	}
2281     }
2282     else
2283     {
2284 	draw_vsep_win(wp, row);
2285 	if (eof)		/* we hit the end of the file */
2286 	{
2287 	    wp->w_botline = buf->b_ml.ml_line_count + 1;
2288 #ifdef FEAT_DIFF
2289 	    j = diff_check_fill(wp, wp->w_botline);
2290 	    if (j > 0 && !wp->w_botfill)
2291 	    {
2292 		/*
2293 		 * Display filler lines at the end of the file
2294 		 */
2295 		if (char2cells(fill_diff) > 1)
2296 		    i = '-';
2297 		else
2298 		    i = fill_diff;
2299 		if (row + j > wp->w_height)
2300 		    j = wp->w_height - row;
2301 		win_draw_end(wp, i, i, row, row + (int)j, HLF_DED);
2302 		row += j;
2303 	    }
2304 #endif
2305 	}
2306 	else if (dollar_vcol == -1)
2307 	    wp->w_botline = lnum;
2308 
2309 	/* make sure the rest of the screen is blank */
2310 	/* put '~'s on rows that aren't part of the file. */
2311 	win_draw_end(wp, '~', ' ', row, wp->w_height, HLF_EOB);
2312     }
2313 
2314 #ifdef SYN_TIME_LIMIT
2315     syn_set_timeout(NULL);
2316 #endif
2317 
2318     /* Reset the type of redrawing required, the window has been updated. */
2319     wp->w_redr_type = 0;
2320 #ifdef FEAT_DIFF
2321     wp->w_old_topfill = wp->w_topfill;
2322     wp->w_old_botfill = wp->w_botfill;
2323 #endif
2324 
2325     if (dollar_vcol == -1)
2326     {
2327 	/*
2328 	 * There is a trick with w_botline.  If we invalidate it on each
2329 	 * change that might modify it, this will cause a lot of expensive
2330 	 * calls to plines() in update_topline() each time.  Therefore the
2331 	 * value of w_botline is often approximated, and this value is used to
2332 	 * compute the value of w_topline.  If the value of w_botline was
2333 	 * wrong, check that the value of w_topline is correct (cursor is on
2334 	 * the visible part of the text).  If it's not, we need to redraw
2335 	 * again.  Mostly this just means scrolling up a few lines, so it
2336 	 * doesn't look too bad.  Only do this for the current window (where
2337 	 * changes are relevant).
2338 	 */
2339 	wp->w_valid |= VALID_BOTLINE;
2340 	if (wp == curwin && wp->w_botline != old_botline && !recursive)
2341 	{
2342 	    recursive = TRUE;
2343 	    curwin->w_valid &= ~VALID_TOPLINE;
2344 	    update_topline();	/* may invalidate w_botline again */
2345 	    if (must_redraw != 0)
2346 	    {
2347 		/* Don't update for changes in buffer again. */
2348 		i = curbuf->b_mod_set;
2349 		curbuf->b_mod_set = FALSE;
2350 		win_update(curwin);
2351 		must_redraw = 0;
2352 		curbuf->b_mod_set = i;
2353 	    }
2354 	    recursive = FALSE;
2355 	}
2356     }
2357 
2358 #if defined(FEAT_SYN_HL) || defined(FEAT_SEARCH_EXTRA)
2359     /* restore got_int, unless CTRL-C was hit while redrawing */
2360     if (!got_int)
2361 	got_int = save_got_int;
2362 #endif
2363 }
2364 
2365 /*
2366  * Clear the rest of the window and mark the unused lines with "c1".  use "c2"
2367  * as the filler character.
2368  */
2369     static void
2370 win_draw_end(
2371     win_T	*wp,
2372     int		c1,
2373     int		c2,
2374     int		row,
2375     int		endrow,
2376     hlf_T	hl)
2377 {
2378 #if defined(FEAT_FOLDING) || defined(FEAT_SIGNS) || defined(FEAT_CMDWIN)
2379     int		n = 0;
2380 # define FDC_OFF n
2381 #else
2382 # define FDC_OFF 0
2383 #endif
2384 #ifdef FEAT_FOLDING
2385     int		fdc = compute_foldcolumn(wp, 0);
2386 #endif
2387 
2388 #ifdef FEAT_RIGHTLEFT
2389     if (wp->w_p_rl)
2390     {
2391 	/* No check for cmdline window: should never be right-left. */
2392 # ifdef FEAT_FOLDING
2393 	n = fdc;
2394 
2395 	if (n > 0)
2396 	{
2397 	    /* draw the fold column at the right */
2398 	    if (n > wp->w_width)
2399 		n = wp->w_width;
2400 	    screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
2401 		    W_ENDCOL(wp) - n, (int)W_ENDCOL(wp),
2402 		    ' ', ' ', HL_ATTR(HLF_FC));
2403 	}
2404 # endif
2405 # ifdef FEAT_SIGNS
2406 	if (signcolumn_on(wp))
2407 	{
2408 	    int nn = n + 2;
2409 
2410 	    /* draw the sign column left of the fold column */
2411 	    if (nn > wp->w_width)
2412 		nn = wp->w_width;
2413 	    screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
2414 		    W_ENDCOL(wp) - nn, (int)W_ENDCOL(wp) - n,
2415 		    ' ', ' ', HL_ATTR(HLF_SC));
2416 	    n = nn;
2417 	}
2418 # endif
2419 	screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
2420 		wp->w_wincol, W_ENDCOL(wp) - 1 - FDC_OFF,
2421 		c2, c2, HL_ATTR(hl));
2422 	screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
2423 		W_ENDCOL(wp) - 1 - FDC_OFF, W_ENDCOL(wp) - FDC_OFF,
2424 		c1, c2, HL_ATTR(hl));
2425     }
2426     else
2427 #endif
2428     {
2429 #ifdef FEAT_CMDWIN
2430 	if (cmdwin_type != 0 && wp == curwin)
2431 	{
2432 	    /* draw the cmdline character in the leftmost column */
2433 	    n = 1;
2434 	    if (n > wp->w_width)
2435 		n = wp->w_width;
2436 	    screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
2437 		    wp->w_wincol, (int)wp->w_wincol + n,
2438 		    cmdwin_type, ' ', HL_ATTR(HLF_AT));
2439 	}
2440 #endif
2441 #ifdef FEAT_FOLDING
2442 	if (fdc > 0)
2443 	{
2444 	    int	    nn = n + fdc;
2445 
2446 	    /* draw the fold column at the left */
2447 	    if (nn > wp->w_width)
2448 		nn = wp->w_width;
2449 	    screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
2450 		    wp->w_wincol + n, (int)wp->w_wincol + nn,
2451 		    ' ', ' ', HL_ATTR(HLF_FC));
2452 	    n = nn;
2453 	}
2454 #endif
2455 #ifdef FEAT_SIGNS
2456 	if (signcolumn_on(wp))
2457 	{
2458 	    int	    nn = n + 2;
2459 
2460 	    /* draw the sign column after the fold column */
2461 	    if (nn > wp->w_width)
2462 		nn = wp->w_width;
2463 	    screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
2464 		    wp->w_wincol + n, (int)wp->w_wincol + nn,
2465 		    ' ', ' ', HL_ATTR(HLF_SC));
2466 	    n = nn;
2467 	}
2468 #endif
2469 	screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + endrow,
2470 		wp->w_wincol + FDC_OFF, (int)W_ENDCOL(wp),
2471 		c1, c2, HL_ATTR(hl));
2472     }
2473     set_empty_rows(wp, row);
2474 }
2475 
2476 #ifdef FEAT_SYN_HL
2477 static int advance_color_col(int vcol, int **color_cols);
2478 
2479 /*
2480  * Advance **color_cols and return TRUE when there are columns to draw.
2481  */
2482     static int
2483 advance_color_col(int vcol, int **color_cols)
2484 {
2485     while (**color_cols >= 0 && vcol > **color_cols)
2486 	++*color_cols;
2487     return (**color_cols >= 0);
2488 }
2489 #endif
2490 
2491 #if defined(FEAT_MENU) || defined(FEAT_FOLDING)
2492 /*
2493  * Copy "text" to ScreenLines using "attr".
2494  * Returns the next screen column.
2495  */
2496     static int
2497 text_to_screenline(win_T *wp, char_u *text, int col)
2498 {
2499     int		off = (int)(current_ScreenLine - ScreenLines);
2500 
2501 #ifdef FEAT_MBYTE
2502     if (has_mbyte)
2503     {
2504 	int	cells;
2505 	int	u8c, u8cc[MAX_MCO];
2506 	int	i;
2507 	int	idx;
2508 	int	c_len;
2509 	char_u	*p;
2510 # ifdef FEAT_ARABIC
2511 	int	prev_c = 0;		/* previous Arabic character */
2512 	int	prev_c1 = 0;		/* first composing char for prev_c */
2513 # endif
2514 
2515 # ifdef FEAT_RIGHTLEFT
2516 	if (wp->w_p_rl)
2517 	    idx = off;
2518 	else
2519 # endif
2520 	    idx = off + col;
2521 
2522 	/* Store multibyte characters in ScreenLines[] et al. correctly. */
2523 	for (p = text; *p != NUL; )
2524 	{
2525 	    cells = (*mb_ptr2cells)(p);
2526 	    c_len = (*mb_ptr2len)(p);
2527 	    if (col + cells > wp->w_width
2528 # ifdef FEAT_RIGHTLEFT
2529 		    - (wp->w_p_rl ? col : 0)
2530 # endif
2531 		    )
2532 		break;
2533 	    ScreenLines[idx] = *p;
2534 	    if (enc_utf8)
2535 	    {
2536 		u8c = utfc_ptr2char(p, u8cc);
2537 		if (*p < 0x80 && u8cc[0] == 0)
2538 		{
2539 		    ScreenLinesUC[idx] = 0;
2540 #ifdef FEAT_ARABIC
2541 		    prev_c = u8c;
2542 #endif
2543 		}
2544 		else
2545 		{
2546 #ifdef FEAT_ARABIC
2547 		    if (p_arshape && !p_tbidi && ARABIC_CHAR(u8c))
2548 		    {
2549 			/* Do Arabic shaping. */
2550 			int	pc, pc1, nc;
2551 			int	pcc[MAX_MCO];
2552 			int	firstbyte = *p;
2553 
2554 			/* The idea of what is the previous and next
2555 			 * character depends on 'rightleft'. */
2556 			if (wp->w_p_rl)
2557 			{
2558 			    pc = prev_c;
2559 			    pc1 = prev_c1;
2560 			    nc = utf_ptr2char(p + c_len);
2561 			    prev_c1 = u8cc[0];
2562 			}
2563 			else
2564 			{
2565 			    pc = utfc_ptr2char(p + c_len, pcc);
2566 			    nc = prev_c;
2567 			    pc1 = pcc[0];
2568 			}
2569 			prev_c = u8c;
2570 
2571 			u8c = arabic_shape(u8c, &firstbyte, &u8cc[0],
2572 								 pc, pc1, nc);
2573 			ScreenLines[idx] = firstbyte;
2574 		    }
2575 		    else
2576 			prev_c = u8c;
2577 #endif
2578 		    /* Non-BMP character: display as ? or fullwidth ?. */
2579 #ifdef UNICODE16
2580 		    if (u8c >= 0x10000)
2581 			ScreenLinesUC[idx] = (cells == 2) ? 0xff1f : (int)'?';
2582 		    else
2583 #endif
2584 			ScreenLinesUC[idx] = u8c;
2585 		    for (i = 0; i < Screen_mco; ++i)
2586 		    {
2587 			ScreenLinesC[i][idx] = u8cc[i];
2588 			if (u8cc[i] == 0)
2589 			    break;
2590 		    }
2591 		}
2592 		if (cells > 1)
2593 		    ScreenLines[idx + 1] = 0;
2594 	    }
2595 	    else if (enc_dbcs == DBCS_JPNU && *p == 0x8e)
2596 		/* double-byte single width character */
2597 		ScreenLines2[idx] = p[1];
2598 	    else if (cells > 1)
2599 		/* double-width character */
2600 		ScreenLines[idx + 1] = p[1];
2601 	    col += cells;
2602 	    idx += cells;
2603 	    p += c_len;
2604 	}
2605     }
2606     else
2607 #endif
2608     {
2609 	int len = (int)STRLEN(text);
2610 
2611 	if (len > wp->w_width - col)
2612 	    len = wp->w_width - col;
2613 	if (len > 0)
2614 	{
2615 #ifdef FEAT_RIGHTLEFT
2616 	    if (wp->w_p_rl)
2617 		STRNCPY(current_ScreenLine, text, len);
2618 	    else
2619 #endif
2620 		STRNCPY(current_ScreenLine + col, text, len);
2621 	    col += len;
2622 	}
2623     }
2624     return col;
2625 }
2626 #endif
2627 
2628 #ifdef FEAT_FOLDING
2629 /*
2630  * Compute the width of the foldcolumn.  Based on 'foldcolumn' and how much
2631  * space is available for window "wp", minus "col".
2632  */
2633     static int
2634 compute_foldcolumn(win_T *wp, int col)
2635 {
2636     int fdc = wp->w_p_fdc;
2637     int wmw = wp == curwin && p_wmw == 0 ? 1 : p_wmw;
2638     int wwidth = wp->w_width;
2639 
2640     if (fdc > wwidth - (col + wmw))
2641 	fdc = wwidth - (col + wmw);
2642     return fdc;
2643 }
2644 
2645 /*
2646  * Display one folded line.
2647  */
2648     static void
2649 fold_line(
2650     win_T	*wp,
2651     long	fold_count,
2652     foldinfo_T	*foldinfo,
2653     linenr_T	lnum,
2654     int		row)
2655 {
2656     char_u	buf[FOLD_TEXT_LEN];
2657     pos_T	*top, *bot;
2658     linenr_T	lnume = lnum + fold_count - 1;
2659     int		len;
2660     char_u	*text;
2661     int		fdc;
2662     int		col;
2663     int		txtcol;
2664     int		off = (int)(current_ScreenLine - ScreenLines);
2665     int		ri;
2666 
2667     /* Build the fold line:
2668      * 1. Add the cmdwin_type for the command-line window
2669      * 2. Add the 'foldcolumn'
2670      * 3. Add the 'number' or 'relativenumber' column
2671      * 4. Compose the text
2672      * 5. Add the text
2673      * 6. set highlighting for the Visual area an other text
2674      */
2675     col = 0;
2676 
2677     /*
2678      * 1. Add the cmdwin_type for the command-line window
2679      * Ignores 'rightleft', this window is never right-left.
2680      */
2681 #ifdef FEAT_CMDWIN
2682     if (cmdwin_type != 0 && wp == curwin)
2683     {
2684 	ScreenLines[off] = cmdwin_type;
2685 	ScreenAttrs[off] = HL_ATTR(HLF_AT);
2686 #ifdef FEAT_MBYTE
2687 	if (enc_utf8)
2688 	    ScreenLinesUC[off] = 0;
2689 #endif
2690 	++col;
2691     }
2692 #endif
2693 
2694     /*
2695      * 2. Add the 'foldcolumn'
2696      *    Reduce the width when there is not enough space.
2697      */
2698     fdc = compute_foldcolumn(wp, col);
2699     if (fdc > 0)
2700     {
2701 	fill_foldcolumn(buf, wp, TRUE, lnum);
2702 #ifdef FEAT_RIGHTLEFT
2703 	if (wp->w_p_rl)
2704 	{
2705 	    int		i;
2706 
2707 	    copy_text_attr(off + wp->w_width - fdc - col, buf, fdc,
2708 							     HL_ATTR(HLF_FC));
2709 	    /* reverse the fold column */
2710 	    for (i = 0; i < fdc; ++i)
2711 		ScreenLines[off + wp->w_width - i - 1 - col] = buf[i];
2712 	}
2713 	else
2714 #endif
2715 	    copy_text_attr(off + col, buf, fdc, HL_ATTR(HLF_FC));
2716 	col += fdc;
2717     }
2718 
2719 #ifdef FEAT_RIGHTLEFT
2720 # define RL_MEMSET(p, v, l) \
2721     do { \
2722 	if (wp->w_p_rl) \
2723 	    for (ri = 0; ri < l; ++ri) \
2724 	       ScreenAttrs[off + (wp->w_width - (p) - (l)) + ri] = v; \
2725 	 else \
2726 	    for (ri = 0; ri < l; ++ri) \
2727 	       ScreenAttrs[off + (p) + ri] = v; \
2728     } while (0)
2729 #else
2730 # define RL_MEMSET(p, v, l) \
2731     do { \
2732 	for (ri = 0; ri < l; ++ri) \
2733 	    ScreenAttrs[off + (p) + ri] = v; \
2734     } while (0)
2735 #endif
2736 
2737     /* Set all attributes of the 'number' or 'relativenumber' column and the
2738      * text */
2739     RL_MEMSET(col, HL_ATTR(HLF_FL), wp->w_width - col);
2740 
2741 #ifdef FEAT_SIGNS
2742     /* If signs are being displayed, add two spaces. */
2743     if (signcolumn_on(wp))
2744     {
2745 	len = wp->w_width - col;
2746 	if (len > 0)
2747 	{
2748 	    if (len > 2)
2749 		len = 2;
2750 # ifdef FEAT_RIGHTLEFT
2751 	    if (wp->w_p_rl)
2752 		/* the line number isn't reversed */
2753 		copy_text_attr(off + wp->w_width - len - col,
2754 					(char_u *)"  ", len, HL_ATTR(HLF_FL));
2755 	    else
2756 # endif
2757 		copy_text_attr(off + col, (char_u *)"  ", len, HL_ATTR(HLF_FL));
2758 	    col += len;
2759 	}
2760     }
2761 #endif
2762 
2763     /*
2764      * 3. Add the 'number' or 'relativenumber' column
2765      */
2766     if (wp->w_p_nu || wp->w_p_rnu)
2767     {
2768 	len = wp->w_width - col;
2769 	if (len > 0)
2770 	{
2771 	    int	    w = number_width(wp);
2772 	    long    num;
2773 	    char    *fmt = "%*ld ";
2774 
2775 	    if (len > w + 1)
2776 		len = w + 1;
2777 
2778 	    if (wp->w_p_nu && !wp->w_p_rnu)
2779 		/* 'number' + 'norelativenumber' */
2780 		num = (long)lnum;
2781 	    else
2782 	    {
2783 		/* 'relativenumber', don't use negative numbers */
2784 		num = labs((long)get_cursor_rel_lnum(wp, lnum));
2785 		if (num == 0 && wp->w_p_nu && wp->w_p_rnu)
2786 		{
2787 		    /* 'number' + 'relativenumber': cursor line shows absolute
2788 		     * line number */
2789 		    num = lnum;
2790 		    fmt = "%-*ld ";
2791 		}
2792 	    }
2793 
2794 	    sprintf((char *)buf, fmt, w, num);
2795 #ifdef FEAT_RIGHTLEFT
2796 	    if (wp->w_p_rl)
2797 		/* the line number isn't reversed */
2798 		copy_text_attr(off + wp->w_width - len - col, buf, len,
2799 							     HL_ATTR(HLF_FL));
2800 	    else
2801 #endif
2802 		copy_text_attr(off + col, buf, len, HL_ATTR(HLF_FL));
2803 	    col += len;
2804 	}
2805     }
2806 
2807     /*
2808      * 4. Compose the folded-line string with 'foldtext', if set.
2809      */
2810     text = get_foldtext(wp, lnum, lnume, foldinfo, buf);
2811 
2812     txtcol = col;	/* remember where text starts */
2813 
2814     /*
2815      * 5. move the text to current_ScreenLine.  Fill up with "fill_fold".
2816      *    Right-left text is put in columns 0 - number-col, normal text is put
2817      *    in columns number-col - window-width.
2818      */
2819     col = text_to_screenline(wp, text, col);
2820 
2821     /* Fill the rest of the line with the fold filler */
2822 #ifdef FEAT_RIGHTLEFT
2823     if (wp->w_p_rl)
2824 	col -= txtcol;
2825 #endif
2826     while (col < wp->w_width
2827 #ifdef FEAT_RIGHTLEFT
2828 		    - (wp->w_p_rl ? txtcol : 0)
2829 #endif
2830 	    )
2831     {
2832 #ifdef FEAT_MBYTE
2833 	if (enc_utf8)
2834 	{
2835 	    if (fill_fold >= 0x80)
2836 	    {
2837 		ScreenLinesUC[off + col] = fill_fold;
2838 		ScreenLinesC[0][off + col] = 0;
2839 		ScreenLines[off + col] = 0x80; /* avoid storing zero */
2840 	    }
2841 	    else
2842 	    {
2843 		ScreenLinesUC[off + col] = 0;
2844 		ScreenLines[off + col] = fill_fold;
2845 	    }
2846 	    col++;
2847 	}
2848 	else
2849 #endif
2850 	    ScreenLines[off + col++] = fill_fold;
2851     }
2852 
2853     if (text != buf)
2854 	vim_free(text);
2855 
2856     /*
2857      * 6. set highlighting for the Visual area an other text.
2858      * If all folded lines are in the Visual area, highlight the line.
2859      */
2860     if (VIsual_active && wp->w_buffer == curwin->w_buffer)
2861     {
2862 	if (LTOREQ_POS(curwin->w_cursor, VIsual))
2863 	{
2864 	    /* Visual is after curwin->w_cursor */
2865 	    top = &curwin->w_cursor;
2866 	    bot = &VIsual;
2867 	}
2868 	else
2869 	{
2870 	    /* Visual is before curwin->w_cursor */
2871 	    top = &VIsual;
2872 	    bot = &curwin->w_cursor;
2873 	}
2874 	if (lnum >= top->lnum
2875 		&& lnume <= bot->lnum
2876 		&& (VIsual_mode != 'v'
2877 		    || ((lnum > top->lnum
2878 			    || (lnum == top->lnum
2879 				&& top->col == 0))
2880 			&& (lnume < bot->lnum
2881 			    || (lnume == bot->lnum
2882 				&& (bot->col - (*p_sel == 'e'))
2883 		>= (colnr_T)STRLEN(ml_get_buf(wp->w_buffer, lnume, FALSE)))))))
2884 	{
2885 	    if (VIsual_mode == Ctrl_V)
2886 	    {
2887 		/* Visual block mode: highlight the chars part of the block */
2888 		if (wp->w_old_cursor_fcol + txtcol < (colnr_T)wp->w_width)
2889 		{
2890 		    if (wp->w_old_cursor_lcol != MAXCOL
2891 			     && wp->w_old_cursor_lcol + txtcol
2892 						       < (colnr_T)wp->w_width)
2893 			len = wp->w_old_cursor_lcol;
2894 		    else
2895 			len = wp->w_width - txtcol;
2896 		    RL_MEMSET(wp->w_old_cursor_fcol + txtcol, HL_ATTR(HLF_V),
2897 					    len - (int)wp->w_old_cursor_fcol);
2898 		}
2899 	    }
2900 	    else
2901 	    {
2902 		/* Set all attributes of the text */
2903 		RL_MEMSET(txtcol, HL_ATTR(HLF_V), wp->w_width - txtcol);
2904 	    }
2905 	}
2906     }
2907 
2908 #ifdef FEAT_SYN_HL
2909     /* Show colorcolumn in the fold line, but let cursorcolumn override it. */
2910     if (wp->w_p_cc_cols)
2911     {
2912 	int i = 0;
2913 	int j = wp->w_p_cc_cols[i];
2914 	int old_txtcol = txtcol;
2915 
2916 	while (j > -1)
2917 	{
2918 	    txtcol += j;
2919 	    if (wp->w_p_wrap)
2920 		txtcol -= wp->w_skipcol;
2921 	    else
2922 		txtcol -= wp->w_leftcol;
2923 	    if (txtcol >= 0 && txtcol < wp->w_width)
2924 		ScreenAttrs[off + txtcol] = hl_combine_attr(
2925 				    ScreenAttrs[off + txtcol], HL_ATTR(HLF_MC));
2926 	    txtcol = old_txtcol;
2927 	    j = wp->w_p_cc_cols[++i];
2928 	}
2929     }
2930 
2931     /* Show 'cursorcolumn' in the fold line. */
2932     if (wp->w_p_cuc)
2933     {
2934 	txtcol += wp->w_virtcol;
2935 	if (wp->w_p_wrap)
2936 	    txtcol -= wp->w_skipcol;
2937 	else
2938 	    txtcol -= wp->w_leftcol;
2939 	if (txtcol >= 0 && txtcol < wp->w_width)
2940 	    ScreenAttrs[off + txtcol] = hl_combine_attr(
2941 				 ScreenAttrs[off + txtcol], HL_ATTR(HLF_CUC));
2942     }
2943 #endif
2944 
2945     screen_line(row + W_WINROW(wp), wp->w_wincol, (int)wp->w_width,
2946 						     (int)wp->w_width, FALSE);
2947 
2948     /*
2949      * Update w_cline_height and w_cline_folded if the cursor line was
2950      * updated (saves a call to plines() later).
2951      */
2952     if (wp == curwin
2953 	    && lnum <= curwin->w_cursor.lnum
2954 	    && lnume >= curwin->w_cursor.lnum)
2955     {
2956 	curwin->w_cline_row = row;
2957 	curwin->w_cline_height = 1;
2958 	curwin->w_cline_folded = TRUE;
2959 	curwin->w_valid |= (VALID_CHEIGHT|VALID_CROW);
2960     }
2961 }
2962 
2963 /*
2964  * Copy "buf[len]" to ScreenLines["off"] and set attributes to "attr".
2965  */
2966     static void
2967 copy_text_attr(
2968     int		off,
2969     char_u	*buf,
2970     int		len,
2971     int		attr)
2972 {
2973     int		i;
2974 
2975     mch_memmove(ScreenLines + off, buf, (size_t)len);
2976 # ifdef FEAT_MBYTE
2977     if (enc_utf8)
2978 	vim_memset(ScreenLinesUC + off, 0, sizeof(u8char_T) * (size_t)len);
2979 # endif
2980     for (i = 0; i < len; ++i)
2981 	ScreenAttrs[off + i] = attr;
2982 }
2983 
2984 /*
2985  * Fill the foldcolumn at "p" for window "wp".
2986  * Only to be called when 'foldcolumn' > 0.
2987  */
2988     static void
2989 fill_foldcolumn(
2990     char_u	*p,
2991     win_T	*wp,
2992     int		closed,		/* TRUE of FALSE */
2993     linenr_T	lnum)		/* current line number */
2994 {
2995     int		i = 0;
2996     int		level;
2997     int		first_level;
2998     int		empty;
2999     int		fdc = compute_foldcolumn(wp, 0);
3000 
3001     /* Init to all spaces. */
3002     vim_memset(p, ' ', (size_t)fdc);
3003 
3004     level = win_foldinfo.fi_level;
3005     if (level > 0)
3006     {
3007 	/* If there is only one column put more info in it. */
3008 	empty = (fdc == 1) ? 0 : 1;
3009 
3010 	/* If the column is too narrow, we start at the lowest level that
3011 	 * fits and use numbers to indicated the depth. */
3012 	first_level = level - fdc - closed + 1 + empty;
3013 	if (first_level < 1)
3014 	    first_level = 1;
3015 
3016 	for (i = 0; i + empty < fdc; ++i)
3017 	{
3018 	    if (win_foldinfo.fi_lnum == lnum
3019 			      && first_level + i >= win_foldinfo.fi_low_level)
3020 		p[i] = '-';
3021 	    else if (first_level == 1)
3022 		p[i] = '|';
3023 	    else if (first_level + i <= 9)
3024 		p[i] = '0' + first_level + i;
3025 	    else
3026 		p[i] = '>';
3027 	    if (first_level + i == level)
3028 		break;
3029 	}
3030     }
3031     if (closed)
3032 	p[i >= fdc ? i - 1 : i] = '+';
3033 }
3034 #endif /* FEAT_FOLDING */
3035 
3036 /*
3037  * Display line "lnum" of window 'wp' on the screen.
3038  * Start at row "startrow", stop when "endrow" is reached.
3039  * wp->w_virtcol needs to be valid.
3040  *
3041  * Return the number of last row the line occupies.
3042  */
3043     static int
3044 win_line(
3045     win_T	*wp,
3046     linenr_T	lnum,
3047     int		startrow,
3048     int		endrow,
3049     int		nochange UNUSED)	/* not updating for changed text */
3050 {
3051     int		col = 0;		/* visual column on screen */
3052     unsigned	off;			/* offset in ScreenLines/ScreenAttrs */
3053     int		c = 0;			/* init for GCC */
3054     long	vcol = 0;		/* virtual column (for tabs) */
3055 #ifdef FEAT_LINEBREAK
3056     long	vcol_sbr = -1;		/* virtual column after showbreak */
3057 #endif
3058     long	vcol_prev = -1;		/* "vcol" of previous character */
3059     char_u	*line;			/* current line */
3060     char_u	*ptr;			/* current position in "line" */
3061     int		row;			/* row in the window, excl w_winrow */
3062     int		screen_row;		/* row on the screen, incl w_winrow */
3063 
3064     char_u	extra[18];		/* "%ld" and 'fdc' must fit in here */
3065     int		n_extra = 0;		/* number of extra chars */
3066     char_u	*p_extra = NULL;	/* string of extra chars, plus NUL */
3067     char_u	*p_extra_free = NULL;   /* p_extra needs to be freed */
3068     int		c_extra = NUL;		/* extra chars, all the same */
3069     int		extra_attr = 0;		/* attributes when n_extra != 0 */
3070     static char_u *at_end_str = (char_u *)""; /* used for p_extra when
3071 					   displaying lcs_eol at end-of-line */
3072     int		lcs_eol_one = lcs_eol;	/* lcs_eol until it's been used */
3073     int		lcs_prec_todo = lcs_prec;   /* lcs_prec until it's been used */
3074 
3075     /* saved "extra" items for when draw_state becomes WL_LINE (again) */
3076     int		saved_n_extra = 0;
3077     char_u	*saved_p_extra = NULL;
3078     int		saved_c_extra = 0;
3079     int		saved_char_attr = 0;
3080 
3081     int		n_attr = 0;		/* chars with special attr */
3082     int		saved_attr2 = 0;	/* char_attr saved for n_attr */
3083     int		n_attr3 = 0;		/* chars with overruling special attr */
3084     int		saved_attr3 = 0;	/* char_attr saved for n_attr3 */
3085 
3086     int		n_skip = 0;		/* nr of chars to skip for 'nowrap' */
3087 
3088     int		fromcol, tocol;		/* start/end of inverting */
3089     int		fromcol_prev = -2;	/* start of inverting after cursor */
3090     int		noinvcur = FALSE;	/* don't invert the cursor */
3091     pos_T	*top, *bot;
3092     int		lnum_in_visual_area = FALSE;
3093     pos_T	pos;
3094     long	v;
3095 
3096     int		char_attr = 0;		/* attributes for next character */
3097     int		attr_pri = FALSE;	/* char_attr has priority */
3098     int		area_highlighting = FALSE; /* Visual or incsearch highlighting
3099 					      in this line */
3100     int		attr = 0;		/* attributes for area highlighting */
3101     int		area_attr = 0;		/* attributes desired by highlighting */
3102     int		search_attr = 0;	/* attributes desired by 'hlsearch' */
3103 #ifdef FEAT_SYN_HL
3104     int		vcol_save_attr = 0;	/* saved attr for 'cursorcolumn' */
3105     int		syntax_attr = 0;	/* attributes desired by syntax */
3106     int		has_syntax = FALSE;	/* this buffer has syntax highl. */
3107     int		save_did_emsg;
3108     int		eol_hl_off = 0;		/* 1 if highlighted char after EOL */
3109     int		draw_color_col = FALSE;	/* highlight colorcolumn */
3110     int		*color_cols = NULL;	/* pointer to according columns array */
3111 #endif
3112 #ifdef FEAT_SPELL
3113     int		has_spell = FALSE;	/* this buffer has spell checking */
3114 # define SPWORDLEN 150
3115     char_u	nextline[SPWORDLEN * 2];/* text with start of the next line */
3116     int		nextlinecol = 0;	/* column where nextline[] starts */
3117     int		nextline_idx = 0;	/* index in nextline[] where next line
3118 					   starts */
3119     int		spell_attr = 0;		/* attributes desired by spelling */
3120     int		word_end = 0;		/* last byte with same spell_attr */
3121     static linenr_T  checked_lnum = 0;	/* line number for "checked_col" */
3122     static int	checked_col = 0;	/* column in "checked_lnum" up to which
3123 					 * there are no spell errors */
3124     static int	cap_col = -1;		/* column to check for Cap word */
3125     static linenr_T capcol_lnum = 0;	/* line number where "cap_col" used */
3126     int		cur_checked_col = 0;	/* checked column for current line */
3127 #endif
3128     int		extra_check;		/* has syntax or linebreak */
3129 #ifdef FEAT_MBYTE
3130     int		multi_attr = 0;		/* attributes desired by multibyte */
3131     int		mb_l = 1;		/* multi-byte byte length */
3132     int		mb_c = 0;		/* decoded multi-byte character */
3133     int		mb_utf8 = FALSE;	/* screen char is UTF-8 char */
3134     int		u8cc[MAX_MCO];		/* composing UTF-8 chars */
3135 #endif
3136 #ifdef FEAT_DIFF
3137     int		filler_lines;		/* nr of filler lines to be drawn */
3138     int		filler_todo;		/* nr of filler lines still to do + 1 */
3139     hlf_T	diff_hlf = (hlf_T)0;	/* type of diff highlighting */
3140     int		change_start = MAXCOL;	/* first col of changed area */
3141     int		change_end = -1;	/* last col of changed area */
3142 #endif
3143     colnr_T	trailcol = MAXCOL;	/* start of trailing spaces */
3144 #ifdef FEAT_LINEBREAK
3145     int		need_showbreak = FALSE; /* overlong line, skipping first x
3146 					   chars */
3147 #endif
3148 #if defined(FEAT_SIGNS) || defined(FEAT_QUICKFIX) \
3149 	|| defined(FEAT_SYN_HL) || defined(FEAT_DIFF)
3150 # define LINE_ATTR
3151     int		line_attr = 0;		/* attribute for the whole line */
3152 #endif
3153 #ifdef FEAT_SEARCH_EXTRA
3154     matchitem_T *cur;			/* points to the match list */
3155     match_T	*shl;			/* points to search_hl or a match */
3156     int		shl_flag;		/* flag to indicate whether search_hl
3157 					   has been processed or not */
3158     int		pos_inprogress;		/* marks that position match search is
3159 					   in progress */
3160     int		prevcol_hl_flag;	/* flag to indicate whether prevcol
3161 					   equals startcol of search_hl or one
3162 					   of the matches */
3163 #endif
3164 #ifdef FEAT_ARABIC
3165     int		prev_c = 0;		/* previous Arabic character */
3166     int		prev_c1 = 0;		/* first composing char for prev_c */
3167 #endif
3168 #if defined(LINE_ATTR)
3169     int		did_line_attr = 0;
3170 #endif
3171 #ifdef FEAT_TERMINAL
3172     int		get_term_attr = FALSE;
3173     int		term_attr = 0;		/* background for terminal window */
3174 #endif
3175 
3176     /* draw_state: items that are drawn in sequence: */
3177 #define WL_START	0		/* nothing done yet */
3178 #ifdef FEAT_CMDWIN
3179 # define WL_CMDLINE	WL_START + 1	/* cmdline window column */
3180 #else
3181 # define WL_CMDLINE	WL_START
3182 #endif
3183 #ifdef FEAT_FOLDING
3184 # define WL_FOLD	WL_CMDLINE + 1	/* 'foldcolumn' */
3185 #else
3186 # define WL_FOLD	WL_CMDLINE
3187 #endif
3188 #ifdef FEAT_SIGNS
3189 # define WL_SIGN	WL_FOLD + 1	/* column for signs */
3190 #else
3191 # define WL_SIGN	WL_FOLD		/* column for signs */
3192 #endif
3193 #define WL_NR		WL_SIGN + 1	/* line number */
3194 #ifdef FEAT_LINEBREAK
3195 # define WL_BRI		WL_NR + 1	/* 'breakindent' */
3196 #else
3197 # define WL_BRI		WL_NR
3198 #endif
3199 #if defined(FEAT_LINEBREAK) || defined(FEAT_DIFF)
3200 # define WL_SBR		WL_BRI + 1	/* 'showbreak' or 'diff' */
3201 #else
3202 # define WL_SBR		WL_BRI
3203 #endif
3204 #define WL_LINE		WL_SBR + 1	/* text in the line */
3205     int		draw_state = WL_START;	/* what to draw next */
3206 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
3207     int		feedback_col = 0;
3208     int		feedback_old_attr = -1;
3209 #endif
3210 
3211 #ifdef FEAT_CONCEAL
3212     int		syntax_flags	= 0;
3213     int		syntax_seqnr	= 0;
3214     int		prev_syntax_id	= 0;
3215     int		conceal_attr	= HL_ATTR(HLF_CONCEAL);
3216     int		is_concealing	= FALSE;
3217     int		boguscols	= 0;	/* nonexistent columns added to force
3218 					   wrapping */
3219     int		vcol_off	= 0;	/* offset for concealed characters */
3220     int		did_wcol	= FALSE;
3221     int		match_conc	= 0;	/* cchar for match functions */
3222     int		has_match_conc  = 0;	/* match wants to conceal */
3223     int		old_boguscols   = 0;
3224 # define VCOL_HLC (vcol - vcol_off)
3225 # define FIX_FOR_BOGUSCOLS \
3226     { \
3227 	n_extra += vcol_off; \
3228 	vcol -= vcol_off; \
3229 	vcol_off = 0; \
3230 	col -= boguscols; \
3231 	old_boguscols = boguscols; \
3232 	boguscols = 0; \
3233     }
3234 #else
3235 # define VCOL_HLC (vcol)
3236 #endif
3237 
3238     if (startrow > endrow)		/* past the end already! */
3239 	return startrow;
3240 
3241     row = startrow;
3242     screen_row = row + W_WINROW(wp);
3243 
3244     /*
3245      * To speed up the loop below, set extra_check when there is linebreak,
3246      * trailing white space and/or syntax processing to be done.
3247      */
3248 #ifdef FEAT_LINEBREAK
3249     extra_check = wp->w_p_lbr;
3250 #else
3251     extra_check = 0;
3252 #endif
3253 #ifdef FEAT_SYN_HL
3254     if (syntax_present(wp) && !wp->w_s->b_syn_error
3255 # ifdef SYN_TIME_LIMIT
3256 	    && !wp->w_s->b_syn_slow
3257 # endif
3258        )
3259     {
3260 	/* Prepare for syntax highlighting in this line.  When there is an
3261 	 * error, stop syntax highlighting. */
3262 	save_did_emsg = did_emsg;
3263 	did_emsg = FALSE;
3264 	syntax_start(wp, lnum);
3265 	if (did_emsg)
3266 	    wp->w_s->b_syn_error = TRUE;
3267 	else
3268 	{
3269 	    did_emsg = save_did_emsg;
3270 #ifdef SYN_TIME_LIMIT
3271 	    if (!wp->w_s->b_syn_slow)
3272 #endif
3273 	    {
3274 		has_syntax = TRUE;
3275 		extra_check = TRUE;
3276 	    }
3277 	}
3278     }
3279 
3280     /* Check for columns to display for 'colorcolumn'. */
3281     color_cols = wp->w_p_cc_cols;
3282     if (color_cols != NULL)
3283 	draw_color_col = advance_color_col(VCOL_HLC, &color_cols);
3284 #endif
3285 
3286 #ifdef FEAT_TERMINAL
3287     if (term_show_buffer(wp->w_buffer))
3288     {
3289 	extra_check = TRUE;
3290 	get_term_attr = TRUE;
3291 	term_attr = term_get_attr(wp->w_buffer, lnum, -1);
3292     }
3293 #endif
3294 
3295 #ifdef FEAT_SPELL
3296     if (wp->w_p_spell
3297 	    && *wp->w_s->b_p_spl != NUL
3298 	    && wp->w_s->b_langp.ga_len > 0
3299 	    && *(char **)(wp->w_s->b_langp.ga_data) != NULL)
3300     {
3301 	/* Prepare for spell checking. */
3302 	has_spell = TRUE;
3303 	extra_check = TRUE;
3304 
3305 	/* Get the start of the next line, so that words that wrap to the next
3306 	 * line are found too: "et<line-break>al.".
3307 	 * Trick: skip a few chars for C/shell/Vim comments */
3308 	nextline[SPWORDLEN] = NUL;
3309 	if (lnum < wp->w_buffer->b_ml.ml_line_count)
3310 	{
3311 	    line = ml_get_buf(wp->w_buffer, lnum + 1, FALSE);
3312 	    spell_cat_line(nextline + SPWORDLEN, line, SPWORDLEN);
3313 	}
3314 
3315 	/* When a word wrapped from the previous line the start of the current
3316 	 * line is valid. */
3317 	if (lnum == checked_lnum)
3318 	    cur_checked_col = checked_col;
3319 	checked_lnum = 0;
3320 
3321 	/* When there was a sentence end in the previous line may require a
3322 	 * word starting with capital in this line.  In line 1 always check
3323 	 * the first word. */
3324 	if (lnum != capcol_lnum)
3325 	    cap_col = -1;
3326 	if (lnum == 1)
3327 	    cap_col = 0;
3328 	capcol_lnum = 0;
3329     }
3330 #endif
3331 
3332     /*
3333      * handle visual active in this window
3334      */
3335     fromcol = -10;
3336     tocol = MAXCOL;
3337     if (VIsual_active && wp->w_buffer == curwin->w_buffer)
3338     {
3339 					/* Visual is after curwin->w_cursor */
3340 	if (LTOREQ_POS(curwin->w_cursor, VIsual))
3341 	{
3342 	    top = &curwin->w_cursor;
3343 	    bot = &VIsual;
3344 	}
3345 	else				/* Visual is before curwin->w_cursor */
3346 	{
3347 	    top = &VIsual;
3348 	    bot = &curwin->w_cursor;
3349 	}
3350 	lnum_in_visual_area = (lnum >= top->lnum && lnum <= bot->lnum);
3351 	if (VIsual_mode == Ctrl_V)	/* block mode */
3352 	{
3353 	    if (lnum_in_visual_area)
3354 	    {
3355 		fromcol = wp->w_old_cursor_fcol;
3356 		tocol = wp->w_old_cursor_lcol;
3357 	    }
3358 	}
3359 	else				/* non-block mode */
3360 	{
3361 	    if (lnum > top->lnum && lnum <= bot->lnum)
3362 		fromcol = 0;
3363 	    else if (lnum == top->lnum)
3364 	    {
3365 		if (VIsual_mode == 'V')	/* linewise */
3366 		    fromcol = 0;
3367 		else
3368 		{
3369 		    getvvcol(wp, top, (colnr_T *)&fromcol, NULL, NULL);
3370 		    if (gchar_pos(top) == NUL)
3371 			tocol = fromcol + 1;
3372 		}
3373 	    }
3374 	    if (VIsual_mode != 'V' && lnum == bot->lnum)
3375 	    {
3376 		if (*p_sel == 'e' && bot->col == 0
3377 #ifdef FEAT_VIRTUALEDIT
3378 			&& bot->coladd == 0
3379 #endif
3380 		   )
3381 		{
3382 		    fromcol = -10;
3383 		    tocol = MAXCOL;
3384 		}
3385 		else if (bot->col == MAXCOL)
3386 		    tocol = MAXCOL;
3387 		else
3388 		{
3389 		    pos = *bot;
3390 		    if (*p_sel == 'e')
3391 			getvvcol(wp, &pos, (colnr_T *)&tocol, NULL, NULL);
3392 		    else
3393 		    {
3394 			getvvcol(wp, &pos, NULL, NULL, (colnr_T *)&tocol);
3395 			++tocol;
3396 		    }
3397 		}
3398 	    }
3399 	}
3400 
3401 	/* Check if the character under the cursor should not be inverted */
3402 	if (!highlight_match && lnum == curwin->w_cursor.lnum && wp == curwin
3403 #ifdef FEAT_GUI
3404 		&& !gui.in_use
3405 #endif
3406 		)
3407 	    noinvcur = TRUE;
3408 
3409 	/* if inverting in this line set area_highlighting */
3410 	if (fromcol >= 0)
3411 	{
3412 	    area_highlighting = TRUE;
3413 	    attr = HL_ATTR(HLF_V);
3414 #if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3415 	    if ((clip_star.available && !clip_star.owned
3416 						     && clip_isautosel_star())
3417 		    || (clip_plus.available && !clip_plus.owned
3418 						    && clip_isautosel_plus()))
3419 		attr = HL_ATTR(HLF_VNC);
3420 #endif
3421 	}
3422     }
3423 
3424     /*
3425      * handle 'incsearch' and ":s///c" highlighting
3426      */
3427     else if (highlight_match
3428 	    && wp == curwin
3429 	    && lnum >= curwin->w_cursor.lnum
3430 	    && lnum <= curwin->w_cursor.lnum + search_match_lines)
3431     {
3432 	if (lnum == curwin->w_cursor.lnum)
3433 	    getvcol(curwin, &(curwin->w_cursor),
3434 					     (colnr_T *)&fromcol, NULL, NULL);
3435 	else
3436 	    fromcol = 0;
3437 	if (lnum == curwin->w_cursor.lnum + search_match_lines)
3438 	{
3439 	    pos.lnum = lnum;
3440 	    pos.col = search_match_endcol;
3441 	    getvcol(curwin, &pos, (colnr_T *)&tocol, NULL, NULL);
3442 	}
3443 	else
3444 	    tocol = MAXCOL;
3445 	/* do at least one character; happens when past end of line */
3446 	if (fromcol == tocol)
3447 	    tocol = fromcol + 1;
3448 	area_highlighting = TRUE;
3449 	attr = HL_ATTR(HLF_I);
3450     }
3451 
3452 #ifdef FEAT_DIFF
3453     filler_lines = diff_check(wp, lnum);
3454     if (filler_lines < 0)
3455     {
3456 	if (filler_lines == -1)
3457 	{
3458 	    if (diff_find_change(wp, lnum, &change_start, &change_end))
3459 		diff_hlf = HLF_ADD;	/* added line */
3460 	    else if (change_start == 0)
3461 		diff_hlf = HLF_TXD;	/* changed text */
3462 	    else
3463 		diff_hlf = HLF_CHD;	/* changed line */
3464 	}
3465 	else
3466 	    diff_hlf = HLF_ADD;		/* added line */
3467 	filler_lines = 0;
3468 	area_highlighting = TRUE;
3469     }
3470     if (lnum == wp->w_topline)
3471 	filler_lines = wp->w_topfill;
3472     filler_todo = filler_lines;
3473 #endif
3474 
3475 #ifdef LINE_ATTR
3476 # ifdef FEAT_SIGNS
3477     /* If this line has a sign with line highlighting set line_attr. */
3478     v = buf_getsigntype(wp->w_buffer, lnum, SIGN_LINEHL);
3479     if (v != 0)
3480 	line_attr = sign_get_attr((int)v, TRUE);
3481 # endif
3482 # if defined(FEAT_QUICKFIX)
3483     /* Highlight the current line in the quickfix window. */
3484     if (bt_quickfix(wp->w_buffer) && qf_current_entry(wp) == lnum)
3485 	line_attr = HL_ATTR(HLF_QFL);
3486 # endif
3487     if (line_attr != 0)
3488 	area_highlighting = TRUE;
3489 #endif
3490 
3491     line = ml_get_buf(wp->w_buffer, lnum, FALSE);
3492     ptr = line;
3493 
3494 #ifdef FEAT_SPELL
3495     if (has_spell)
3496     {
3497 	/* For checking first word with a capital skip white space. */
3498 	if (cap_col == 0)
3499 	    cap_col = getwhitecols(line);
3500 
3501 	/* To be able to spell-check over line boundaries copy the end of the
3502 	 * current line into nextline[].  Above the start of the next line was
3503 	 * copied to nextline[SPWORDLEN]. */
3504 	if (nextline[SPWORDLEN] == NUL)
3505 	{
3506 	    /* No next line or it is empty. */
3507 	    nextlinecol = MAXCOL;
3508 	    nextline_idx = 0;
3509 	}
3510 	else
3511 	{
3512 	    v = (long)STRLEN(line);
3513 	    if (v < SPWORDLEN)
3514 	    {
3515 		/* Short line, use it completely and append the start of the
3516 		 * next line. */
3517 		nextlinecol = 0;
3518 		mch_memmove(nextline, line, (size_t)v);
3519 		STRMOVE(nextline + v, nextline + SPWORDLEN);
3520 		nextline_idx = v + 1;
3521 	    }
3522 	    else
3523 	    {
3524 		/* Long line, use only the last SPWORDLEN bytes. */
3525 		nextlinecol = v - SPWORDLEN;
3526 		mch_memmove(nextline, line + nextlinecol, SPWORDLEN);
3527 		nextline_idx = SPWORDLEN + 1;
3528 	    }
3529 	}
3530     }
3531 #endif
3532 
3533     if (wp->w_p_list)
3534     {
3535 	if (lcs_space || lcs_trail)
3536 	    extra_check = TRUE;
3537 	/* find start of trailing whitespace */
3538 	if (lcs_trail)
3539 	{
3540 	    trailcol = (colnr_T)STRLEN(ptr);
3541 	    while (trailcol > (colnr_T)0 && VIM_ISWHITE(ptr[trailcol - 1]))
3542 		--trailcol;
3543 	    trailcol += (colnr_T) (ptr - line);
3544 	}
3545     }
3546 
3547     /*
3548      * 'nowrap' or 'wrap' and a single line that doesn't fit: Advance to the
3549      * first character to be displayed.
3550      */
3551     if (wp->w_p_wrap)
3552 	v = wp->w_skipcol;
3553     else
3554 	v = wp->w_leftcol;
3555     if (v > 0)
3556     {
3557 #ifdef FEAT_MBYTE
3558 	char_u	*prev_ptr = ptr;
3559 #endif
3560 	while (vcol < v && *ptr != NUL)
3561 	{
3562 	    c = win_lbr_chartabsize(wp, line, ptr, (colnr_T)vcol, NULL);
3563 	    vcol += c;
3564 #ifdef FEAT_MBYTE
3565 	    prev_ptr = ptr;
3566 #endif
3567 	    MB_PTR_ADV(ptr);
3568 	}
3569 
3570 	/* When:
3571 	 * - 'cuc' is set, or
3572 	 * - 'colorcolumn' is set, or
3573 	 * - 'virtualedit' is set, or
3574 	 * - the visual mode is active,
3575 	 * the end of the line may be before the start of the displayed part.
3576 	 */
3577 	if (vcol < v && (
3578 #ifdef FEAT_SYN_HL
3579 	     wp->w_p_cuc || draw_color_col ||
3580 #endif
3581 #ifdef FEAT_VIRTUALEDIT
3582 	     virtual_active() ||
3583 #endif
3584 	     (VIsual_active && wp->w_buffer == curwin->w_buffer)))
3585 	{
3586 	    vcol = v;
3587 	}
3588 
3589 	/* Handle a character that's not completely on the screen: Put ptr at
3590 	 * that character but skip the first few screen characters. */
3591 	if (vcol > v)
3592 	{
3593 	    vcol -= c;
3594 #ifdef FEAT_MBYTE
3595 	    ptr = prev_ptr;
3596 #else
3597 	    --ptr;
3598 #endif
3599 	    /* If the character fits on the screen, don't need to skip it.
3600 	     * Except for a TAB. */
3601 	    if ((
3602 #ifdef FEAT_MBYTE
3603 			(*mb_ptr2cells)(ptr) >= c ||
3604 #endif
3605 		       *ptr == TAB) && col == 0)
3606 	       n_skip = v - vcol;
3607 	}
3608 
3609 	/*
3610 	 * Adjust for when the inverted text is before the screen,
3611 	 * and when the start of the inverted text is before the screen.
3612 	 */
3613 	if (tocol <= vcol)
3614 	    fromcol = 0;
3615 	else if (fromcol >= 0 && fromcol < vcol)
3616 	    fromcol = vcol;
3617 
3618 #ifdef FEAT_LINEBREAK
3619 	/* When w_skipcol is non-zero, first line needs 'showbreak' */
3620 	if (wp->w_p_wrap)
3621 	    need_showbreak = TRUE;
3622 #endif
3623 #ifdef FEAT_SPELL
3624 	/* When spell checking a word we need to figure out the start of the
3625 	 * word and if it's badly spelled or not. */
3626 	if (has_spell)
3627 	{
3628 	    int		len;
3629 	    colnr_T	linecol = (colnr_T)(ptr - line);
3630 	    hlf_T	spell_hlf = HLF_COUNT;
3631 
3632 	    pos = wp->w_cursor;
3633 	    wp->w_cursor.lnum = lnum;
3634 	    wp->w_cursor.col = linecol;
3635 	    len = spell_move_to(wp, FORWARD, TRUE, TRUE, &spell_hlf);
3636 
3637 	    /* spell_move_to() may call ml_get() and make "line" invalid */
3638 	    line = ml_get_buf(wp->w_buffer, lnum, FALSE);
3639 	    ptr = line + linecol;
3640 
3641 	    if (len == 0 || (int)wp->w_cursor.col > ptr - line)
3642 	    {
3643 		/* no bad word found at line start, don't check until end of a
3644 		 * word */
3645 		spell_hlf = HLF_COUNT;
3646 		word_end = (int)(spell_to_word_end(ptr, wp) - line + 1);
3647 	    }
3648 	    else
3649 	    {
3650 		/* bad word found, use attributes until end of word */
3651 		word_end = wp->w_cursor.col + len + 1;
3652 
3653 		/* Turn index into actual attributes. */
3654 		if (spell_hlf != HLF_COUNT)
3655 		    spell_attr = highlight_attr[spell_hlf];
3656 	    }
3657 	    wp->w_cursor = pos;
3658 
3659 # ifdef FEAT_SYN_HL
3660 	    /* Need to restart syntax highlighting for this line. */
3661 	    if (has_syntax)
3662 		syntax_start(wp, lnum);
3663 # endif
3664 	}
3665 #endif
3666     }
3667 
3668     /*
3669      * Correct highlighting for cursor that can't be disabled.
3670      * Avoids having to check this for each character.
3671      */
3672     if (fromcol >= 0)
3673     {
3674 	if (noinvcur)
3675 	{
3676 	    if ((colnr_T)fromcol == wp->w_virtcol)
3677 	    {
3678 		/* highlighting starts at cursor, let it start just after the
3679 		 * cursor */
3680 		fromcol_prev = fromcol;
3681 		fromcol = -1;
3682 	    }
3683 	    else if ((colnr_T)fromcol < wp->w_virtcol)
3684 		/* restart highlighting after the cursor */
3685 		fromcol_prev = wp->w_virtcol;
3686 	}
3687 	if (fromcol >= tocol)
3688 	    fromcol = -1;
3689     }
3690 
3691 #ifdef FEAT_SEARCH_EXTRA
3692     /*
3693      * Handle highlighting the last used search pattern and matches.
3694      * Do this for both search_hl and the match list.
3695      */
3696     cur = wp->w_match_head;
3697     shl_flag = FALSE;
3698     while (cur != NULL || shl_flag == FALSE)
3699     {
3700 	if (shl_flag == FALSE)
3701 	{
3702 	    shl = &search_hl;
3703 	    shl_flag = TRUE;
3704 	}
3705 	else
3706 	    shl = &cur->hl;
3707 	shl->startcol = MAXCOL;
3708 	shl->endcol = MAXCOL;
3709 	shl->attr_cur = 0;
3710 	shl->is_addpos = FALSE;
3711 	v = (long)(ptr - line);
3712 	if (cur != NULL)
3713 	    cur->pos.cur = 0;
3714 	next_search_hl(wp, shl, lnum, (colnr_T)v,
3715 					       shl == &search_hl ? NULL : cur);
3716 
3717 	/* Need to get the line again, a multi-line regexp may have made it
3718 	 * invalid. */
3719 	line = ml_get_buf(wp->w_buffer, lnum, FALSE);
3720 	ptr = line + v;
3721 
3722 	if (shl->lnum != 0 && shl->lnum <= lnum)
3723 	{
3724 	    if (shl->lnum == lnum)
3725 		shl->startcol = shl->rm.startpos[0].col;
3726 	    else
3727 		shl->startcol = 0;
3728 	    if (lnum == shl->lnum + shl->rm.endpos[0].lnum
3729 						- shl->rm.startpos[0].lnum)
3730 		shl->endcol = shl->rm.endpos[0].col;
3731 	    else
3732 		shl->endcol = MAXCOL;
3733 	    /* Highlight one character for an empty match. */
3734 	    if (shl->startcol == shl->endcol)
3735 	    {
3736 #ifdef FEAT_MBYTE
3737 		if (has_mbyte && line[shl->endcol] != NUL)
3738 		    shl->endcol += (*mb_ptr2len)(line + shl->endcol);
3739 		else
3740 #endif
3741 		    ++shl->endcol;
3742 	    }
3743 	    if ((long)shl->startcol < v)  /* match at leftcol */
3744 	    {
3745 		shl->attr_cur = shl->attr;
3746 		search_attr = shl->attr;
3747 	    }
3748 	    area_highlighting = TRUE;
3749 	}
3750 	if (shl != &search_hl && cur != NULL)
3751 	    cur = cur->next;
3752     }
3753 #endif
3754 
3755 #ifdef FEAT_SYN_HL
3756     /* Cursor line highlighting for 'cursorline' in the current window.  Not
3757      * when Visual mode is active, because it's not clear what is selected
3758      * then. */
3759     if (wp->w_p_cul && lnum == wp->w_cursor.lnum
3760 					 && !(wp == curwin && VIsual_active))
3761     {
3762 	line_attr = HL_ATTR(HLF_CUL);
3763 	area_highlighting = TRUE;
3764     }
3765 #endif
3766 
3767     off = (unsigned)(current_ScreenLine - ScreenLines);
3768     col = 0;
3769 #ifdef FEAT_RIGHTLEFT
3770     if (wp->w_p_rl)
3771     {
3772 	/* Rightleft window: process the text in the normal direction, but put
3773 	 * it in current_ScreenLine[] from right to left.  Start at the
3774 	 * rightmost column of the window. */
3775 	col = wp->w_width - 1;
3776 	off += col;
3777     }
3778 #endif
3779 
3780     /*
3781      * Repeat for the whole displayed line.
3782      */
3783     for (;;)
3784     {
3785 #ifdef FEAT_CONCEAL
3786 	has_match_conc = 0;
3787 #endif
3788 	/* Skip this quickly when working on the text. */
3789 	if (draw_state != WL_LINE)
3790 	{
3791 #ifdef FEAT_CMDWIN
3792 	    if (draw_state == WL_CMDLINE - 1 && n_extra == 0)
3793 	    {
3794 		draw_state = WL_CMDLINE;
3795 		if (cmdwin_type != 0 && wp == curwin)
3796 		{
3797 		    /* Draw the cmdline character. */
3798 		    n_extra = 1;
3799 		    c_extra = cmdwin_type;
3800 		    char_attr = HL_ATTR(HLF_AT);
3801 		}
3802 	    }
3803 #endif
3804 
3805 #ifdef FEAT_FOLDING
3806 	    if (draw_state == WL_FOLD - 1 && n_extra == 0)
3807 	    {
3808 		int fdc = compute_foldcolumn(wp, 0);
3809 
3810 		draw_state = WL_FOLD;
3811 		if (fdc > 0)
3812 		{
3813 		    /* Draw the 'foldcolumn'.  Allocate a buffer, "extra" may
3814 		     * already be in use. */
3815 		    vim_free(p_extra_free);
3816 		    p_extra_free = alloc(12 + 1);
3817 
3818 		    if (p_extra_free != NULL)
3819 		    {
3820 			fill_foldcolumn(p_extra_free, wp, FALSE, lnum);
3821 			n_extra = fdc;
3822 			p_extra_free[n_extra] = NUL;
3823 			p_extra = p_extra_free;
3824 			c_extra = NUL;
3825 			char_attr = HL_ATTR(HLF_FC);
3826 		    }
3827 		}
3828 	    }
3829 #endif
3830 
3831 #ifdef FEAT_SIGNS
3832 	    if (draw_state == WL_SIGN - 1 && n_extra == 0)
3833 	    {
3834 		draw_state = WL_SIGN;
3835 		/* Show the sign column when there are any signs in this
3836 		 * buffer or when using Netbeans. */
3837 		if (signcolumn_on(wp))
3838 		{
3839 		    int	text_sign;
3840 # ifdef FEAT_SIGN_ICONS
3841 		    int	icon_sign;
3842 # endif
3843 
3844 		    /* Draw two cells with the sign value or blank. */
3845 		    c_extra = ' ';
3846 		    char_attr = HL_ATTR(HLF_SC);
3847 		    n_extra = 2;
3848 
3849 		    if (row == startrow
3850 #ifdef FEAT_DIFF
3851 			    + filler_lines && filler_todo <= 0
3852 #endif
3853 			    )
3854 		    {
3855 			text_sign = buf_getsigntype(wp->w_buffer, lnum,
3856 								   SIGN_TEXT);
3857 # ifdef FEAT_SIGN_ICONS
3858 			icon_sign = buf_getsigntype(wp->w_buffer, lnum,
3859 								   SIGN_ICON);
3860 			if (gui.in_use && icon_sign != 0)
3861 			{
3862 			    /* Use the image in this position. */
3863 			    c_extra = SIGN_BYTE;
3864 #  ifdef FEAT_NETBEANS_INTG
3865 			    if (buf_signcount(wp->w_buffer, lnum) > 1)
3866 				c_extra = MULTISIGN_BYTE;
3867 #  endif
3868 			    char_attr = icon_sign;
3869 			}
3870 			else
3871 # endif
3872 			    if (text_sign != 0)
3873 			{
3874 			    p_extra = sign_get_text(text_sign);
3875 			    if (p_extra != NULL)
3876 			    {
3877 				c_extra = NUL;
3878 				n_extra = (int)STRLEN(p_extra);
3879 			    }
3880 			    char_attr = sign_get_attr(text_sign, FALSE);
3881 			}
3882 		    }
3883 		}
3884 	    }
3885 #endif
3886 
3887 	    if (draw_state == WL_NR - 1 && n_extra == 0)
3888 	    {
3889 		draw_state = WL_NR;
3890 		/* Display the absolute or relative line number. After the
3891 		 * first fill with blanks when the 'n' flag isn't in 'cpo' */
3892 		if ((wp->w_p_nu || wp->w_p_rnu)
3893 			&& (row == startrow
3894 #ifdef FEAT_DIFF
3895 			    + filler_lines
3896 #endif
3897 			    || vim_strchr(p_cpo, CPO_NUMCOL) == NULL))
3898 		{
3899 		    /* Draw the line number (empty space after wrapping). */
3900 		    if (row == startrow
3901 #ifdef FEAT_DIFF
3902 			    + filler_lines
3903 #endif
3904 			    )
3905 		    {
3906 			long num;
3907 			char *fmt = "%*ld ";
3908 
3909 			if (wp->w_p_nu && !wp->w_p_rnu)
3910 			    /* 'number' + 'norelativenumber' */
3911 			    num = (long)lnum;
3912 			else
3913 			{
3914 			    /* 'relativenumber', don't use negative numbers */
3915 			    num = labs((long)get_cursor_rel_lnum(wp, lnum));
3916 			    if (num == 0 && wp->w_p_nu && wp->w_p_rnu)
3917 			    {
3918 				/* 'number' + 'relativenumber' */
3919 				num = lnum;
3920 				fmt = "%-*ld ";
3921 			    }
3922 			}
3923 
3924 			sprintf((char *)extra, fmt,
3925 						number_width(wp), num);
3926 			if (wp->w_skipcol > 0)
3927 			    for (p_extra = extra; *p_extra == ' '; ++p_extra)
3928 				*p_extra = '-';
3929 #ifdef FEAT_RIGHTLEFT
3930 			if (wp->w_p_rl)		    /* reverse line numbers */
3931 			    rl_mirror(extra);
3932 #endif
3933 			p_extra = extra;
3934 			c_extra = NUL;
3935 		    }
3936 		    else
3937 			c_extra = ' ';
3938 		    n_extra = number_width(wp) + 1;
3939 		    char_attr = HL_ATTR(HLF_N);
3940 #ifdef FEAT_SYN_HL
3941 		    /* When 'cursorline' is set highlight the line number of
3942 		     * the current line differently.
3943 		     * TODO: Can we use CursorLine instead of CursorLineNr
3944 		     * when CursorLineNr isn't set? */
3945 		    if ((wp->w_p_cul || wp->w_p_rnu)
3946 						 && lnum == wp->w_cursor.lnum)
3947 			char_attr = HL_ATTR(HLF_CLN);
3948 #endif
3949 		}
3950 	    }
3951 
3952 #ifdef FEAT_LINEBREAK
3953 	    if (wp->w_p_brisbr && draw_state == WL_BRI - 1
3954 					     && n_extra == 0 && *p_sbr != NUL)
3955 		/* draw indent after showbreak value */
3956 		draw_state = WL_BRI;
3957 	    else if (wp->w_p_brisbr && draw_state == WL_SBR && n_extra == 0)
3958 		/* After the showbreak, draw the breakindent */
3959 		draw_state = WL_BRI - 1;
3960 
3961 	    /* draw 'breakindent': indent wrapped text accordingly */
3962 	    if (draw_state == WL_BRI - 1 && n_extra == 0)
3963 	    {
3964 		draw_state = WL_BRI;
3965 		/* if need_showbreak is set, breakindent also applies */
3966 		if (wp->w_p_bri && n_extra == 0
3967 					 && (row != startrow || need_showbreak)
3968 # ifdef FEAT_DIFF
3969 			&& filler_lines == 0
3970 # endif
3971 		   )
3972 		{
3973 		    char_attr = 0;
3974 # ifdef FEAT_DIFF
3975 		    if (diff_hlf != (hlf_T)0)
3976 		    {
3977 			char_attr = HL_ATTR(diff_hlf);
3978 #  ifdef FEAT_SYN_HL
3979 			if (wp->w_p_cul && lnum == wp->w_cursor.lnum)
3980 			    char_attr = hl_combine_attr(char_attr,
3981 							    HL_ATTR(HLF_CUL));
3982 #  endif
3983 		    }
3984 # endif
3985 		    p_extra = NULL;
3986 		    c_extra = ' ';
3987 		    n_extra = get_breakindent_win(wp,
3988 				       ml_get_buf(wp->w_buffer, lnum, FALSE));
3989 		    /* Correct end of highlighted area for 'breakindent',
3990 		     * required when 'linebreak' is also set. */
3991 		    if (tocol == vcol)
3992 			tocol += n_extra;
3993 		}
3994 	    }
3995 #endif
3996 
3997 #if defined(FEAT_LINEBREAK) || defined(FEAT_DIFF)
3998 	    if (draw_state == WL_SBR - 1 && n_extra == 0)
3999 	    {
4000 		draw_state = WL_SBR;
4001 # ifdef FEAT_DIFF
4002 		if (filler_todo > 0)
4003 		{
4004 		    /* Draw "deleted" diff line(s). */
4005 		    if (char2cells(fill_diff) > 1)
4006 			c_extra = '-';
4007 		    else
4008 			c_extra = fill_diff;
4009 #  ifdef FEAT_RIGHTLEFT
4010 		    if (wp->w_p_rl)
4011 			n_extra = col + 1;
4012 		    else
4013 #  endif
4014 			n_extra = wp->w_width - col;
4015 		    char_attr = HL_ATTR(HLF_DED);
4016 		}
4017 # endif
4018 # ifdef FEAT_LINEBREAK
4019 		if (*p_sbr != NUL && need_showbreak)
4020 		{
4021 		    /* Draw 'showbreak' at the start of each broken line. */
4022 		    p_extra = p_sbr;
4023 		    c_extra = NUL;
4024 		    n_extra = (int)STRLEN(p_sbr);
4025 		    char_attr = HL_ATTR(HLF_AT);
4026 		    need_showbreak = FALSE;
4027 		    vcol_sbr = vcol + MB_CHARLEN(p_sbr);
4028 		    /* Correct end of highlighted area for 'showbreak',
4029 		     * required when 'linebreak' is also set. */
4030 		    if (tocol == vcol)
4031 			tocol += n_extra;
4032 #ifdef FEAT_SYN_HL
4033 		    /* combine 'showbreak' with 'cursorline' */
4034 		    if (wp->w_p_cul && lnum == wp->w_cursor.lnum)
4035 			char_attr = hl_combine_attr(char_attr,
4036 							    HL_ATTR(HLF_CUL));
4037 #endif
4038 		}
4039 # endif
4040 	    }
4041 #endif
4042 
4043 	    if (draw_state == WL_LINE - 1 && n_extra == 0)
4044 	    {
4045 		draw_state = WL_LINE;
4046 		if (saved_n_extra)
4047 		{
4048 		    /* Continue item from end of wrapped line. */
4049 		    n_extra = saved_n_extra;
4050 		    c_extra = saved_c_extra;
4051 		    p_extra = saved_p_extra;
4052 		    char_attr = saved_char_attr;
4053 		}
4054 		else
4055 		    char_attr = 0;
4056 	    }
4057 	}
4058 
4059 	/* When still displaying '$' of change command, stop at cursor */
4060 	if (dollar_vcol >= 0 && wp == curwin
4061 		   && lnum == wp->w_cursor.lnum && vcol >= (long)wp->w_virtcol
4062 #ifdef FEAT_DIFF
4063 				   && filler_todo <= 0
4064 #endif
4065 		)
4066 	{
4067 	    screen_line(screen_row, wp->w_wincol, col, -(int)wp->w_width,
4068 						    HAS_RIGHTLEFT(wp->w_p_rl));
4069 	    /* Pretend we have finished updating the window.  Except when
4070 	     * 'cursorcolumn' is set. */
4071 #ifdef FEAT_SYN_HL
4072 	    if (wp->w_p_cuc)
4073 		row = wp->w_cline_row + wp->w_cline_height;
4074 	    else
4075 #endif
4076 		row = wp->w_height;
4077 	    break;
4078 	}
4079 
4080 	if (draw_state == WL_LINE && area_highlighting)
4081 	{
4082 	    /* handle Visual or match highlighting in this line */
4083 	    if (vcol == fromcol
4084 #ifdef FEAT_MBYTE
4085 		    || (has_mbyte && vcol + 1 == fromcol && n_extra == 0
4086 			&& (*mb_ptr2cells)(ptr) > 1)
4087 #endif
4088 		    || ((int)vcol_prev == fromcol_prev
4089 			&& vcol_prev < vcol	/* not at margin */
4090 			&& vcol < tocol))
4091 		area_attr = attr;		/* start highlighting */
4092 	    else if (area_attr != 0
4093 		    && (vcol == tocol
4094 			|| (noinvcur && (colnr_T)vcol == wp->w_virtcol)))
4095 		area_attr = 0;			/* stop highlighting */
4096 
4097 #ifdef FEAT_SEARCH_EXTRA
4098 	    if (!n_extra)
4099 	    {
4100 		/*
4101 		 * Check for start/end of search pattern match.
4102 		 * After end, check for start/end of next match.
4103 		 * When another match, have to check for start again.
4104 		 * Watch out for matching an empty string!
4105 		 * Do this for 'search_hl' and the match list (ordered by
4106 		 * priority).
4107 		 */
4108 		v = (long)(ptr - line);
4109 		cur = wp->w_match_head;
4110 		shl_flag = FALSE;
4111 		while (cur != NULL || shl_flag == FALSE)
4112 		{
4113 		    if (shl_flag == FALSE
4114 			    && ((cur != NULL
4115 				    && cur->priority > SEARCH_HL_PRIORITY)
4116 				|| cur == NULL))
4117 		    {
4118 			shl = &search_hl;
4119 			shl_flag = TRUE;
4120 		    }
4121 		    else
4122 			shl = &cur->hl;
4123 		    if (cur != NULL)
4124 			cur->pos.cur = 0;
4125 		    pos_inprogress = TRUE;
4126 		    while (shl->rm.regprog != NULL
4127 					   || (cur != NULL && pos_inprogress))
4128 		    {
4129 			if (shl->startcol != MAXCOL
4130 				&& v >= (long)shl->startcol
4131 				&& v < (long)shl->endcol)
4132 			{
4133 #ifdef FEAT_MBYTE
4134 			    int tmp_col = v + MB_PTR2LEN(ptr);
4135 
4136 			    if (shl->endcol < tmp_col)
4137 				shl->endcol = tmp_col;
4138 #endif
4139 			    shl->attr_cur = shl->attr;
4140 #ifdef FEAT_CONCEAL
4141 			    if (cur != NULL && syn_name2id((char_u *)"Conceal")
4142 							       == cur->hlg_id)
4143 			    {
4144 				has_match_conc =
4145 					     v == (long)shl->startcol ? 2 : 1;
4146 				match_conc = cur->conceal_char;
4147 			    }
4148 			    else
4149 				has_match_conc = match_conc = 0;
4150 #endif
4151 			}
4152 			else if (v == (long)shl->endcol)
4153 			{
4154 			    shl->attr_cur = 0;
4155 			    next_search_hl(wp, shl, lnum, (colnr_T)v,
4156 					       shl == &search_hl ? NULL : cur);
4157 			    pos_inprogress = cur == NULL || cur->pos.cur == 0
4158 							       ? FALSE : TRUE;
4159 
4160 			    /* Need to get the line again, a multi-line regexp
4161 			     * may have made it invalid. */
4162 			    line = ml_get_buf(wp->w_buffer, lnum, FALSE);
4163 			    ptr = line + v;
4164 
4165 			    if (shl->lnum == lnum)
4166 			    {
4167 				shl->startcol = shl->rm.startpos[0].col;
4168 				if (shl->rm.endpos[0].lnum == 0)
4169 				    shl->endcol = shl->rm.endpos[0].col;
4170 				else
4171 				    shl->endcol = MAXCOL;
4172 
4173 				if (shl->startcol == shl->endcol)
4174 				{
4175 				    /* highlight empty match, try again after
4176 				     * it */
4177 #ifdef FEAT_MBYTE
4178 				    if (has_mbyte)
4179 					shl->endcol += (*mb_ptr2len)(line
4180 							       + shl->endcol);
4181 				    else
4182 #endif
4183 					++shl->endcol;
4184 				}
4185 
4186 				/* Loop to check if the match starts at the
4187 				 * current position */
4188 				continue;
4189 			    }
4190 			}
4191 			break;
4192 		    }
4193 		    if (shl != &search_hl && cur != NULL)
4194 			cur = cur->next;
4195 		}
4196 
4197 		/* Use attributes from match with highest priority among
4198 		 * 'search_hl' and the match list. */
4199 		search_attr = search_hl.attr_cur;
4200 		cur = wp->w_match_head;
4201 		shl_flag = FALSE;
4202 		while (cur != NULL || shl_flag == FALSE)
4203 		{
4204 		    if (shl_flag == FALSE
4205 			    && ((cur != NULL
4206 				    && cur->priority > SEARCH_HL_PRIORITY)
4207 				|| cur == NULL))
4208 		    {
4209 			shl = &search_hl;
4210 			shl_flag = TRUE;
4211 		    }
4212 		    else
4213 			shl = &cur->hl;
4214 		    if (shl->attr_cur != 0)
4215 			search_attr = shl->attr_cur;
4216 		    if (shl != &search_hl && cur != NULL)
4217 			cur = cur->next;
4218 		}
4219 		/* Only highlight one character after the last column. */
4220 		if (*ptr == NUL && (did_line_attr >= 1
4221 				    || (wp->w_p_list && lcs_eol_one == -1)))
4222 		    search_attr = 0;
4223 	    }
4224 #endif
4225 
4226 #ifdef FEAT_DIFF
4227 	    if (diff_hlf != (hlf_T)0)
4228 	    {
4229 		if (diff_hlf == HLF_CHD && ptr - line >= change_start
4230 							      && n_extra == 0)
4231 		    diff_hlf = HLF_TXD;		/* changed text */
4232 		if (diff_hlf == HLF_TXD && ptr - line > change_end
4233 							      && n_extra == 0)
4234 		    diff_hlf = HLF_CHD;		/* changed line */
4235 		line_attr = HL_ATTR(diff_hlf);
4236 		if (wp->w_p_cul && lnum == wp->w_cursor.lnum)
4237 		    line_attr = hl_combine_attr(line_attr, HL_ATTR(HLF_CUL));
4238 	    }
4239 #endif
4240 
4241 	    /* Decide which of the highlight attributes to use. */
4242 	    attr_pri = TRUE;
4243 #ifdef LINE_ATTR
4244 	    if (area_attr != 0)
4245 		char_attr = hl_combine_attr(line_attr, area_attr);
4246 	    else if (search_attr != 0)
4247 		char_attr = hl_combine_attr(line_attr, search_attr);
4248 		/* Use line_attr when not in the Visual or 'incsearch' area
4249 		 * (area_attr may be 0 when "noinvcur" is set). */
4250 	    else if (line_attr != 0 && ((fromcol == -10 && tocol == MAXCOL)
4251 				|| vcol < fromcol || vcol_prev < fromcol_prev
4252 				|| vcol >= tocol))
4253 		char_attr = line_attr;
4254 #else
4255 	    if (area_attr != 0)
4256 		char_attr = area_attr;
4257 	    else if (search_attr != 0)
4258 		char_attr = search_attr;
4259 #endif
4260 	    else
4261 	    {
4262 		attr_pri = FALSE;
4263 #ifdef FEAT_SYN_HL
4264 		if (has_syntax)
4265 		    char_attr = syntax_attr;
4266 		else
4267 #endif
4268 		    char_attr = 0;
4269 	    }
4270 	}
4271 
4272 	/*
4273 	 * Get the next character to put on the screen.
4274 	 */
4275 	/*
4276 	 * The "p_extra" points to the extra stuff that is inserted to
4277 	 * represent special characters (non-printable stuff) and other
4278 	 * things.  When all characters are the same, c_extra is used.
4279 	 * "p_extra" must end in a NUL to avoid mb_ptr2len() reads past
4280 	 * "p_extra[n_extra]".
4281 	 * For the '$' of the 'list' option, n_extra == 1, p_extra == "".
4282 	 */
4283 	if (n_extra > 0)
4284 	{
4285 	    if (c_extra != NUL)
4286 	    {
4287 		c = c_extra;
4288 #ifdef FEAT_MBYTE
4289 		mb_c = c;	/* doesn't handle non-utf-8 multi-byte! */
4290 		if (enc_utf8 && utf_char2len(c) > 1)
4291 		{
4292 		    mb_utf8 = TRUE;
4293 		    u8cc[0] = 0;
4294 		    c = 0xc0;
4295 		}
4296 		else
4297 		    mb_utf8 = FALSE;
4298 #endif
4299 	    }
4300 	    else
4301 	    {
4302 		c = *p_extra;
4303 #ifdef FEAT_MBYTE
4304 		if (has_mbyte)
4305 		{
4306 		    mb_c = c;
4307 		    if (enc_utf8)
4308 		    {
4309 			/* If the UTF-8 character is more than one byte:
4310 			 * Decode it into "mb_c". */
4311 			mb_l = utfc_ptr2len(p_extra);
4312 			mb_utf8 = FALSE;
4313 			if (mb_l > n_extra)
4314 			    mb_l = 1;
4315 			else if (mb_l > 1)
4316 			{
4317 			    mb_c = utfc_ptr2char(p_extra, u8cc);
4318 			    mb_utf8 = TRUE;
4319 			    c = 0xc0;
4320 			}
4321 		    }
4322 		    else
4323 		    {
4324 			/* if this is a DBCS character, put it in "mb_c" */
4325 			mb_l = MB_BYTE2LEN(c);
4326 			if (mb_l >= n_extra)
4327 			    mb_l = 1;
4328 			else if (mb_l > 1)
4329 			    mb_c = (c << 8) + p_extra[1];
4330 		    }
4331 		    if (mb_l == 0)  /* at the NUL at end-of-line */
4332 			mb_l = 1;
4333 
4334 		    /* If a double-width char doesn't fit display a '>' in the
4335 		     * last column. */
4336 		    if ((
4337 # ifdef FEAT_RIGHTLEFT
4338 			    wp->w_p_rl ? (col <= 0) :
4339 # endif
4340 				    (col >= wp->w_width - 1))
4341 			    && (*mb_char2cells)(mb_c) == 2)
4342 		    {
4343 			c = '>';
4344 			mb_c = c;
4345 			mb_l = 1;
4346 			mb_utf8 = FALSE;
4347 			multi_attr = HL_ATTR(HLF_AT);
4348 			/* put the pointer back to output the double-width
4349 			 * character at the start of the next line. */
4350 			++n_extra;
4351 			--p_extra;
4352 		    }
4353 		    else
4354 		    {
4355 			n_extra -= mb_l - 1;
4356 			p_extra += mb_l - 1;
4357 		    }
4358 		}
4359 #endif
4360 		++p_extra;
4361 	    }
4362 	    --n_extra;
4363 	}
4364 	else
4365 	{
4366 #ifdef FEAT_LINEBREAK
4367 	    int c0;
4368 #endif
4369 
4370 	    if (p_extra_free != NULL)
4371 		VIM_CLEAR(p_extra_free);
4372 	    /*
4373 	     * Get a character from the line itself.
4374 	     */
4375 	    c = *ptr;
4376 #ifdef FEAT_LINEBREAK
4377 	    c0 = *ptr;
4378 #endif
4379 #ifdef FEAT_MBYTE
4380 	    if (has_mbyte)
4381 	    {
4382 		mb_c = c;
4383 		if (enc_utf8)
4384 		{
4385 		    /* If the UTF-8 character is more than one byte: Decode it
4386 		     * into "mb_c". */
4387 		    mb_l = utfc_ptr2len(ptr);
4388 		    mb_utf8 = FALSE;
4389 		    if (mb_l > 1)
4390 		    {
4391 			mb_c = utfc_ptr2char(ptr, u8cc);
4392 			/* Overlong encoded ASCII or ASCII with composing char
4393 			 * is displayed normally, except a NUL. */
4394 			if (mb_c < 0x80)
4395 			{
4396 			    c = mb_c;
4397 # ifdef FEAT_LINEBREAK
4398 			    c0 = mb_c;
4399 # endif
4400 			}
4401 			mb_utf8 = TRUE;
4402 
4403 			/* At start of the line we can have a composing char.
4404 			 * Draw it as a space with a composing char. */
4405 			if (utf_iscomposing(mb_c))
4406 			{
4407 			    int i;
4408 
4409 			    for (i = Screen_mco - 1; i > 0; --i)
4410 				u8cc[i] = u8cc[i - 1];
4411 			    u8cc[0] = mb_c;
4412 			    mb_c = ' ';
4413 			}
4414 		    }
4415 
4416 		    if ((mb_l == 1 && c >= 0x80)
4417 			    || (mb_l >= 1 && mb_c == 0)
4418 			    || (mb_l > 1 && (!vim_isprintc(mb_c)
4419 # ifdef UNICODE16
4420 							 || mb_c >= 0x10000
4421 # endif
4422 							 )))
4423 		    {
4424 			/*
4425 			 * Illegal UTF-8 byte: display as <xx>.
4426 			 * Non-BMP character : display as ? or fullwidth ?.
4427 			 */
4428 # ifdef UNICODE16
4429 			if (mb_c < 0x10000)
4430 # endif
4431 			{
4432 			    transchar_hex(extra, mb_c);
4433 # ifdef FEAT_RIGHTLEFT
4434 			    if (wp->w_p_rl)		/* reverse */
4435 				rl_mirror(extra);
4436 # endif
4437 			}
4438 # ifdef UNICODE16
4439 			else if (utf_char2cells(mb_c) != 2)
4440 			    STRCPY(extra, "?");
4441 			else
4442 			    /* 0xff1f in UTF-8: full-width '?' */
4443 			    STRCPY(extra, "\357\274\237");
4444 # endif
4445 
4446 			p_extra = extra;
4447 			c = *p_extra;
4448 			mb_c = mb_ptr2char_adv(&p_extra);
4449 			mb_utf8 = (c >= 0x80);
4450 			n_extra = (int)STRLEN(p_extra);
4451 			c_extra = NUL;
4452 			if (area_attr == 0 && search_attr == 0)
4453 			{
4454 			    n_attr = n_extra + 1;
4455 			    extra_attr = HL_ATTR(HLF_8);
4456 			    saved_attr2 = char_attr; /* save current attr */
4457 			}
4458 		    }
4459 		    else if (mb_l == 0)  /* at the NUL at end-of-line */
4460 			mb_l = 1;
4461 #ifdef FEAT_ARABIC
4462 		    else if (p_arshape && !p_tbidi && ARABIC_CHAR(mb_c))
4463 		    {
4464 			/* Do Arabic shaping. */
4465 			int	pc, pc1, nc;
4466 			int	pcc[MAX_MCO];
4467 
4468 			/* The idea of what is the previous and next
4469 			 * character depends on 'rightleft'. */
4470 			if (wp->w_p_rl)
4471 			{
4472 			    pc = prev_c;
4473 			    pc1 = prev_c1;
4474 			    nc = utf_ptr2char(ptr + mb_l);
4475 			    prev_c1 = u8cc[0];
4476 			}
4477 			else
4478 			{
4479 			    pc = utfc_ptr2char(ptr + mb_l, pcc);
4480 			    nc = prev_c;
4481 			    pc1 = pcc[0];
4482 			}
4483 			prev_c = mb_c;
4484 
4485 			mb_c = arabic_shape(mb_c, &c, &u8cc[0], pc, pc1, nc);
4486 		    }
4487 		    else
4488 			prev_c = mb_c;
4489 #endif
4490 		}
4491 		else	/* enc_dbcs */
4492 		{
4493 		    mb_l = MB_BYTE2LEN(c);
4494 		    if (mb_l == 0)  /* at the NUL at end-of-line */
4495 			mb_l = 1;
4496 		    else if (mb_l > 1)
4497 		    {
4498 			/* We assume a second byte below 32 is illegal.
4499 			 * Hopefully this is OK for all double-byte encodings!
4500 			 */
4501 			if (ptr[1] >= 32)
4502 			    mb_c = (c << 8) + ptr[1];
4503 			else
4504 			{
4505 			    if (ptr[1] == NUL)
4506 			    {
4507 				/* head byte at end of line */
4508 				mb_l = 1;
4509 				transchar_nonprint(extra, c);
4510 			    }
4511 			    else
4512 			    {
4513 				/* illegal tail byte */
4514 				mb_l = 2;
4515 				STRCPY(extra, "XX");
4516 			    }
4517 			    p_extra = extra;
4518 			    n_extra = (int)STRLEN(extra) - 1;
4519 			    c_extra = NUL;
4520 			    c = *p_extra++;
4521 			    if (area_attr == 0 && search_attr == 0)
4522 			    {
4523 				n_attr = n_extra + 1;
4524 				extra_attr = HL_ATTR(HLF_8);
4525 				saved_attr2 = char_attr; /* save current attr */
4526 			    }
4527 			    mb_c = c;
4528 			}
4529 		    }
4530 		}
4531 		/* If a double-width char doesn't fit display a '>' in the
4532 		 * last column; the character is displayed at the start of the
4533 		 * next line. */
4534 		if ((
4535 # ifdef FEAT_RIGHTLEFT
4536 			    wp->w_p_rl ? (col <= 0) :
4537 # endif
4538 				(col >= wp->w_width - 1))
4539 			&& (*mb_char2cells)(mb_c) == 2)
4540 		{
4541 		    c = '>';
4542 		    mb_c = c;
4543 		    mb_utf8 = FALSE;
4544 		    mb_l = 1;
4545 		    multi_attr = HL_ATTR(HLF_AT);
4546 		    /* Put pointer back so that the character will be
4547 		     * displayed at the start of the next line. */
4548 		    --ptr;
4549 		}
4550 		else if (*ptr != NUL)
4551 		    ptr += mb_l - 1;
4552 
4553 		/* If a double-width char doesn't fit at the left side display
4554 		 * a '<' in the first column.  Don't do this for unprintable
4555 		 * characters. */
4556 		if (n_skip > 0 && mb_l > 1 && n_extra == 0)
4557 		{
4558 		    n_extra = 1;
4559 		    c_extra = MB_FILLER_CHAR;
4560 		    c = ' ';
4561 		    if (area_attr == 0 && search_attr == 0)
4562 		    {
4563 			n_attr = n_extra + 1;
4564 			extra_attr = HL_ATTR(HLF_AT);
4565 			saved_attr2 = char_attr; /* save current attr */
4566 		    }
4567 		    mb_c = c;
4568 		    mb_utf8 = FALSE;
4569 		    mb_l = 1;
4570 		}
4571 
4572 	    }
4573 #endif
4574 	    ++ptr;
4575 
4576 	    if (extra_check)
4577 	    {
4578 #ifdef FEAT_SPELL
4579 		int	can_spell = TRUE;
4580 #endif
4581 
4582 #ifdef FEAT_TERMINAL
4583 		if (get_term_attr)
4584 		{
4585 		    syntax_attr = term_get_attr(wp->w_buffer, lnum, vcol);
4586 
4587 		    if (!attr_pri)
4588 			char_attr = syntax_attr;
4589 		    else
4590 			char_attr = hl_combine_attr(syntax_attr, char_attr);
4591 		}
4592 #endif
4593 
4594 #ifdef FEAT_SYN_HL
4595 		/* Get syntax attribute, unless still at the start of the line
4596 		 * (double-wide char that doesn't fit). */
4597 		v = (long)(ptr - line);
4598 		if (has_syntax && v > 0)
4599 		{
4600 		    /* Get the syntax attribute for the character.  If there
4601 		     * is an error, disable syntax highlighting. */
4602 		    save_did_emsg = did_emsg;
4603 		    did_emsg = FALSE;
4604 
4605 		    syntax_attr = get_syntax_attr((colnr_T)v - 1,
4606 # ifdef FEAT_SPELL
4607 						has_spell ? &can_spell :
4608 # endif
4609 						NULL, FALSE);
4610 
4611 		    if (did_emsg)
4612 		    {
4613 			wp->w_s->b_syn_error = TRUE;
4614 			has_syntax = FALSE;
4615 		    }
4616 		    else
4617 			did_emsg = save_did_emsg;
4618 #ifdef SYN_TIME_LIMIT
4619 		    if (wp->w_s->b_syn_slow)
4620 			has_syntax = FALSE;
4621 #endif
4622 
4623 		    /* Need to get the line again, a multi-line regexp may
4624 		     * have made it invalid. */
4625 		    line = ml_get_buf(wp->w_buffer, lnum, FALSE);
4626 		    ptr = line + v;
4627 
4628 		    if (!attr_pri)
4629 			char_attr = syntax_attr;
4630 		    else
4631 			char_attr = hl_combine_attr(syntax_attr, char_attr);
4632 # ifdef FEAT_CONCEAL
4633 		    /* no concealing past the end of the line, it interferes
4634 		     * with line highlighting */
4635 		    if (c == NUL)
4636 			syntax_flags = 0;
4637 		    else
4638 			syntax_flags = get_syntax_info(&syntax_seqnr);
4639 # endif
4640 		}
4641 #endif
4642 
4643 #ifdef FEAT_SPELL
4644 		/* Check spelling (unless at the end of the line).
4645 		 * Only do this when there is no syntax highlighting, the
4646 		 * @Spell cluster is not used or the current syntax item
4647 		 * contains the @Spell cluster. */
4648 		if (has_spell && v >= word_end && v > cur_checked_col)
4649 		{
4650 		    spell_attr = 0;
4651 # ifdef FEAT_SYN_HL
4652 		    if (!attr_pri)
4653 			char_attr = syntax_attr;
4654 # endif
4655 		    if (c != 0 && (
4656 # ifdef FEAT_SYN_HL
4657 				!has_syntax ||
4658 # endif
4659 				can_spell))
4660 		    {
4661 			char_u	*prev_ptr, *p;
4662 			int	len;
4663 			hlf_T	spell_hlf = HLF_COUNT;
4664 # ifdef FEAT_MBYTE
4665 			if (has_mbyte)
4666 			{
4667 			    prev_ptr = ptr - mb_l;
4668 			    v -= mb_l - 1;
4669 			}
4670 			else
4671 # endif
4672 			    prev_ptr = ptr - 1;
4673 
4674 			/* Use nextline[] if possible, it has the start of the
4675 			 * next line concatenated. */
4676 			if ((prev_ptr - line) - nextlinecol >= 0)
4677 			    p = nextline + (prev_ptr - line) - nextlinecol;
4678 			else
4679 			    p = prev_ptr;
4680 			cap_col -= (int)(prev_ptr - line);
4681 			len = spell_check(wp, p, &spell_hlf, &cap_col,
4682 								    nochange);
4683 			word_end = v + len;
4684 
4685 			/* In Insert mode only highlight a word that
4686 			 * doesn't touch the cursor. */
4687 			if (spell_hlf != HLF_COUNT
4688 				&& (State & INSERT) != 0
4689 				&& wp->w_cursor.lnum == lnum
4690 				&& wp->w_cursor.col >=
4691 						    (colnr_T)(prev_ptr - line)
4692 				&& wp->w_cursor.col < (colnr_T)word_end)
4693 			{
4694 			    spell_hlf = HLF_COUNT;
4695 			    spell_redraw_lnum = lnum;
4696 			}
4697 
4698 			if (spell_hlf == HLF_COUNT && p != prev_ptr
4699 				       && (p - nextline) + len > nextline_idx)
4700 			{
4701 			    /* Remember that the good word continues at the
4702 			     * start of the next line. */
4703 			    checked_lnum = lnum + 1;
4704 			    checked_col = (int)((p - nextline) + len - nextline_idx);
4705 			}
4706 
4707 			/* Turn index into actual attributes. */
4708 			if (spell_hlf != HLF_COUNT)
4709 			    spell_attr = highlight_attr[spell_hlf];
4710 
4711 			if (cap_col > 0)
4712 			{
4713 			    if (p != prev_ptr
4714 				   && (p - nextline) + cap_col >= nextline_idx)
4715 			    {
4716 				/* Remember that the word in the next line
4717 				 * must start with a capital. */
4718 				capcol_lnum = lnum + 1;
4719 				cap_col = (int)((p - nextline) + cap_col
4720 							       - nextline_idx);
4721 			    }
4722 			    else
4723 				/* Compute the actual column. */
4724 				cap_col += (int)(prev_ptr - line);
4725 			}
4726 		    }
4727 		}
4728 		if (spell_attr != 0)
4729 		{
4730 		    if (!attr_pri)
4731 			char_attr = hl_combine_attr(char_attr, spell_attr);
4732 		    else
4733 			char_attr = hl_combine_attr(spell_attr, char_attr);
4734 		}
4735 #endif
4736 #ifdef FEAT_LINEBREAK
4737 		/*
4738 		 * Found last space before word: check for line break.
4739 		 */
4740 		if (wp->w_p_lbr && c0 == c
4741 				  && VIM_ISBREAK(c) && !VIM_ISBREAK((int)*ptr))
4742 		{
4743 # ifdef FEAT_MBYTE
4744 		    int mb_off = has_mbyte ? (*mb_head_off)(line, ptr - 1) : 0;
4745 # endif
4746 		    char_u *p = ptr - (
4747 # ifdef FEAT_MBYTE
4748 				mb_off +
4749 # endif
4750 				1);
4751 
4752 		    /* TODO: is passing p for start of the line OK? */
4753 		    n_extra = win_lbr_chartabsize(wp, line, p, (colnr_T)vcol,
4754 								    NULL) - 1;
4755 		    if (c == TAB && n_extra + col > wp->w_width)
4756 # ifdef FEAT_VARTABS
4757 			n_extra = tabstop_padding(vcol, wp->w_buffer->b_p_ts,
4758 					      wp->w_buffer->b_p_vts_array) - 1;
4759 # else
4760 			n_extra = (int)wp->w_buffer->b_p_ts
4761 				       - vcol % (int)wp->w_buffer->b_p_ts - 1;
4762 # endif
4763 
4764 # ifdef FEAT_MBYTE
4765 		    c_extra = mb_off > 0 ? MB_FILLER_CHAR : ' ';
4766 # else
4767 		    c_extra = ' ';
4768 # endif
4769 		    if (VIM_ISWHITE(c))
4770 		    {
4771 #ifdef FEAT_CONCEAL
4772 			if (c == TAB)
4773 			    /* See "Tab alignment" below. */
4774 			    FIX_FOR_BOGUSCOLS;
4775 #endif
4776 			if (!wp->w_p_list)
4777 			    c = ' ';
4778 		    }
4779 		}
4780 #endif
4781 
4782 		/* 'list': change char 160 to lcs_nbsp and space to lcs_space.
4783 		 */
4784 		if (wp->w_p_list
4785 			&& (((c == 160
4786 #ifdef FEAT_MBYTE
4787 			      || (mb_utf8 && (mb_c == 160 || mb_c == 0x202f))
4788 #endif
4789 			     ) && lcs_nbsp)
4790 			|| (c == ' ' && lcs_space && ptr - line <= trailcol)))
4791 		{
4792 		    c = (c == ' ') ? lcs_space : lcs_nbsp;
4793 		    if (area_attr == 0 && search_attr == 0)
4794 		    {
4795 			n_attr = 1;
4796 			extra_attr = HL_ATTR(HLF_8);
4797 			saved_attr2 = char_attr; /* save current attr */
4798 		    }
4799 #ifdef FEAT_MBYTE
4800 		    mb_c = c;
4801 		    if (enc_utf8 && utf_char2len(c) > 1)
4802 		    {
4803 			mb_utf8 = TRUE;
4804 			u8cc[0] = 0;
4805 			c = 0xc0;
4806 		    }
4807 		    else
4808 			mb_utf8 = FALSE;
4809 #endif
4810 		}
4811 
4812 		if (trailcol != MAXCOL && ptr > line + trailcol && c == ' ')
4813 		{
4814 		    c = lcs_trail;
4815 		    if (!attr_pri)
4816 		    {
4817 			n_attr = 1;
4818 			extra_attr = HL_ATTR(HLF_8);
4819 			saved_attr2 = char_attr; /* save current attr */
4820 		    }
4821 #ifdef FEAT_MBYTE
4822 		    mb_c = c;
4823 		    if (enc_utf8 && utf_char2len(c) > 1)
4824 		    {
4825 			mb_utf8 = TRUE;
4826 			u8cc[0] = 0;
4827 			c = 0xc0;
4828 		    }
4829 		    else
4830 			mb_utf8 = FALSE;
4831 #endif
4832 		}
4833 	    }
4834 
4835 	    /*
4836 	     * Handling of non-printable characters.
4837 	     */
4838 	    if (!vim_isprintc(c))
4839 	    {
4840 		/*
4841 		 * when getting a character from the file, we may have to
4842 		 * turn it into something else on the way to putting it
4843 		 * into "ScreenLines".
4844 		 */
4845 		if (c == TAB && (!wp->w_p_list || lcs_tab1))
4846 		{
4847 		    int tab_len = 0;
4848 		    long vcol_adjusted = vcol; /* removed showbreak length */
4849 #ifdef FEAT_LINEBREAK
4850 		    /* only adjust the tab_len, when at the first column
4851 		     * after the showbreak value was drawn */
4852 		    if (*p_sbr != NUL && vcol == vcol_sbr && wp->w_p_wrap)
4853 			vcol_adjusted = vcol - MB_CHARLEN(p_sbr);
4854 #endif
4855 		    /* tab amount depends on current column */
4856 #ifdef FEAT_VARTABS
4857 		    tab_len = tabstop_padding(vcol_adjusted,
4858 					      wp->w_buffer->b_p_ts,
4859 					      wp->w_buffer->b_p_vts_array) - 1;
4860 #else
4861 		    tab_len = (int)wp->w_buffer->b_p_ts
4862 			       - vcol_adjusted % (int)wp->w_buffer->b_p_ts - 1;
4863 #endif
4864 
4865 #ifdef FEAT_LINEBREAK
4866 		    if (!wp->w_p_lbr || !wp->w_p_list)
4867 #endif
4868 		    /* tab amount depends on current column */
4869 			n_extra = tab_len;
4870 #ifdef FEAT_LINEBREAK
4871 		    else
4872 		    {
4873 			char_u *p;
4874 			int	len = n_extra;
4875 			int	i;
4876 			int	saved_nextra = n_extra;
4877 
4878 #ifdef FEAT_CONCEAL
4879 			if (vcol_off > 0)
4880 			    /* there are characters to conceal */
4881 			    tab_len += vcol_off;
4882 			/* boguscols before FIX_FOR_BOGUSCOLS macro from above
4883 			 */
4884 			if (wp->w_p_list && lcs_tab1 && old_boguscols > 0
4885 							 && n_extra > tab_len)
4886 			    tab_len += n_extra - tab_len;
4887 #endif
4888 
4889 			/* if n_extra > 0, it gives the number of chars, to
4890 			 * use for a tab, else we need to calculate the width
4891 			 * for a tab */
4892 #ifdef FEAT_MBYTE
4893 			len = (tab_len * mb_char2len(lcs_tab2));
4894 			if (n_extra > 0)
4895 			    len += n_extra - tab_len;
4896 #endif
4897 			c = lcs_tab1;
4898 			p = alloc((unsigned)(len + 1));
4899 			vim_memset(p, ' ', len);
4900 			p[len] = NUL;
4901 			vim_free(p_extra_free);
4902 			p_extra_free = p;
4903 			for (i = 0; i < tab_len; i++)
4904 			{
4905 			    if (*p == NUL)
4906 			    {
4907 				tab_len = i;
4908 				break;
4909 			    }
4910 #ifdef FEAT_MBYTE
4911 			    mb_char2bytes(lcs_tab2, p);
4912 			    p += mb_char2len(lcs_tab2);
4913 			    n_extra += mb_char2len(lcs_tab2)
4914 						 - (saved_nextra > 0 ? 1 : 0);
4915 #else
4916 			    p[i] = lcs_tab2;
4917 #endif
4918 			}
4919 			p_extra = p_extra_free;
4920 #ifdef FEAT_CONCEAL
4921 			/* n_extra will be increased by FIX_FOX_BOGUSCOLS
4922 			 * macro below, so need to adjust for that here */
4923 			if (vcol_off > 0)
4924 			    n_extra -= vcol_off;
4925 #endif
4926 		    }
4927 #endif
4928 #ifdef FEAT_CONCEAL
4929 		    {
4930 			int vc_saved = vcol_off;
4931 
4932 			/* Tab alignment should be identical regardless of
4933 			 * 'conceallevel' value. So tab compensates of all
4934 			 * previous concealed characters, and thus resets
4935 			 * vcol_off and boguscols accumulated so far in the
4936 			 * line. Note that the tab can be longer than
4937 			 * 'tabstop' when there are concealed characters. */
4938 			FIX_FOR_BOGUSCOLS;
4939 
4940 			/* Make sure, the highlighting for the tab char will be
4941 			 * correctly set further below (effectively reverts the
4942 			 * FIX_FOR_BOGSUCOLS macro */
4943 			if (n_extra == tab_len + vc_saved && wp->w_p_list
4944 								  && lcs_tab1)
4945 			    tab_len += vc_saved;
4946 		    }
4947 #endif
4948 #ifdef FEAT_MBYTE
4949 		    mb_utf8 = FALSE;	/* don't draw as UTF-8 */
4950 #endif
4951 		    if (wp->w_p_list)
4952 		    {
4953 			c = lcs_tab1;
4954 #ifdef FEAT_LINEBREAK
4955 			if (wp->w_p_lbr)
4956 			    c_extra = NUL; /* using p_extra from above */
4957 			else
4958 #endif
4959 			    c_extra = lcs_tab2;
4960 			n_attr = tab_len + 1;
4961 			extra_attr = HL_ATTR(HLF_8);
4962 			saved_attr2 = char_attr; /* save current attr */
4963 #ifdef FEAT_MBYTE
4964 			mb_c = c;
4965 			if (enc_utf8 && utf_char2len(c) > 1)
4966 			{
4967 			    mb_utf8 = TRUE;
4968 			    u8cc[0] = 0;
4969 			    c = 0xc0;
4970 			}
4971 #endif
4972 		    }
4973 		    else
4974 		    {
4975 			c_extra = ' ';
4976 			c = ' ';
4977 		    }
4978 		}
4979 		else if (c == NUL
4980 			&& (wp->w_p_list
4981 			    || ((fromcol >= 0 || fromcol_prev >= 0)
4982 				&& tocol > vcol
4983 				&& VIsual_mode != Ctrl_V
4984 				&& (
4985 # ifdef FEAT_RIGHTLEFT
4986 				    wp->w_p_rl ? (col >= 0) :
4987 # endif
4988 				    (col < wp->w_width))
4989 				&& !(noinvcur
4990 				    && lnum == wp->w_cursor.lnum
4991 				    && (colnr_T)vcol == wp->w_virtcol)))
4992 			&& lcs_eol_one > 0)
4993 		{
4994 		    /* Display a '$' after the line or highlight an extra
4995 		     * character if the line break is included. */
4996 #if defined(FEAT_DIFF) || defined(LINE_ATTR)
4997 		    /* For a diff line the highlighting continues after the
4998 		     * "$". */
4999 		    if (
5000 # ifdef FEAT_DIFF
5001 			    diff_hlf == (hlf_T)0
5002 #  ifdef LINE_ATTR
5003 			    &&
5004 #  endif
5005 # endif
5006 # ifdef LINE_ATTR
5007 			    line_attr == 0
5008 # endif
5009 		       )
5010 #endif
5011 		    {
5012 #ifdef FEAT_VIRTUALEDIT
5013 			/* In virtualedit, visual selections may extend
5014 			 * beyond end of line. */
5015 			if (area_highlighting && virtual_active()
5016 				&& tocol != MAXCOL && vcol < tocol)
5017 			    n_extra = 0;
5018 			else
5019 #endif
5020 			{
5021 			    p_extra = at_end_str;
5022 			    n_extra = 1;
5023 			    c_extra = NUL;
5024 			}
5025 		    }
5026 		    if (wp->w_p_list && lcs_eol > 0)
5027 			c = lcs_eol;
5028 		    else
5029 			c = ' ';
5030 		    lcs_eol_one = -1;
5031 		    --ptr;	    /* put it back at the NUL */
5032 		    if (!attr_pri)
5033 		    {
5034 			extra_attr = HL_ATTR(HLF_AT);
5035 			n_attr = 1;
5036 		    }
5037 #ifdef FEAT_MBYTE
5038 		    mb_c = c;
5039 		    if (enc_utf8 && utf_char2len(c) > 1)
5040 		    {
5041 			mb_utf8 = TRUE;
5042 			u8cc[0] = 0;
5043 			c = 0xc0;
5044 		    }
5045 		    else
5046 			mb_utf8 = FALSE;	/* don't draw as UTF-8 */
5047 #endif
5048 		}
5049 		else if (c != NUL)
5050 		{
5051 		    p_extra = transchar(c);
5052 		    if (n_extra == 0)
5053 			n_extra = byte2cells(c) - 1;
5054 #ifdef FEAT_RIGHTLEFT
5055 		    if ((dy_flags & DY_UHEX) && wp->w_p_rl)
5056 			rl_mirror(p_extra);	/* reverse "<12>" */
5057 #endif
5058 		    c_extra = NUL;
5059 #ifdef FEAT_LINEBREAK
5060 		    if (wp->w_p_lbr)
5061 		    {
5062 			char_u *p;
5063 
5064 			c = *p_extra;
5065 			p = alloc((unsigned)n_extra + 1);
5066 			vim_memset(p, ' ', n_extra);
5067 			STRNCPY(p, p_extra + 1, STRLEN(p_extra) - 1);
5068 			p[n_extra] = NUL;
5069 			vim_free(p_extra_free);
5070 			p_extra_free = p_extra = p;
5071 		    }
5072 		    else
5073 #endif
5074 		    {
5075 			n_extra = byte2cells(c) - 1;
5076 			c = *p_extra++;
5077 		    }
5078 		    if (!attr_pri)
5079 		    {
5080 			n_attr = n_extra + 1;
5081 			extra_attr = HL_ATTR(HLF_8);
5082 			saved_attr2 = char_attr; /* save current attr */
5083 		    }
5084 #ifdef FEAT_MBYTE
5085 		    mb_utf8 = FALSE;	/* don't draw as UTF-8 */
5086 #endif
5087 		}
5088 #ifdef FEAT_VIRTUALEDIT
5089 		else if (VIsual_active
5090 			 && (VIsual_mode == Ctrl_V
5091 			     || VIsual_mode == 'v')
5092 			 && virtual_active()
5093 			 && tocol != MAXCOL
5094 			 && vcol < tocol
5095 			 && (
5096 # ifdef FEAT_RIGHTLEFT
5097 			    wp->w_p_rl ? (col >= 0) :
5098 # endif
5099 			    (col < wp->w_width)))
5100 		{
5101 		    c = ' ';
5102 		    --ptr;	    /* put it back at the NUL */
5103 		}
5104 #endif
5105 #if defined(LINE_ATTR)
5106 		else if ((
5107 # ifdef FEAT_DIFF
5108 			    diff_hlf != (hlf_T)0 ||
5109 # endif
5110 # ifdef FEAT_TERMINAL
5111 			    term_attr != 0 ||
5112 # endif
5113 			    line_attr != 0
5114 			) && (
5115 # ifdef FEAT_RIGHTLEFT
5116 			    wp->w_p_rl ? (col >= 0) :
5117 # endif
5118 			    (col
5119 # ifdef FEAT_CONCEAL
5120 				- boguscols
5121 # endif
5122 					    < wp->w_width)))
5123 		{
5124 		    /* Highlight until the right side of the window */
5125 		    c = ' ';
5126 		    --ptr;	    /* put it back at the NUL */
5127 
5128 		    /* Remember we do the char for line highlighting. */
5129 		    ++did_line_attr;
5130 
5131 		    /* don't do search HL for the rest of the line */
5132 		    if (line_attr != 0 && char_attr == search_attr
5133 					&& (did_line_attr > 1
5134 					    || (wp->w_p_list && lcs_eol > 0)))
5135 			char_attr = line_attr;
5136 # ifdef FEAT_DIFF
5137 		    if (diff_hlf == HLF_TXD)
5138 		    {
5139 			diff_hlf = HLF_CHD;
5140 			if (attr == 0 || char_attr != attr)
5141 			{
5142 			    char_attr = HL_ATTR(diff_hlf);
5143 			    if (wp->w_p_cul && lnum == wp->w_cursor.lnum)
5144 				char_attr = hl_combine_attr(char_attr,
5145 							    HL_ATTR(HLF_CUL));
5146 			}
5147 		    }
5148 # endif
5149 # ifdef FEAT_TERMINAL
5150 		    if (term_attr != 0)
5151 		    {
5152 			char_attr = term_attr;
5153 			if (wp->w_p_cul && lnum == wp->w_cursor.lnum)
5154 			    char_attr = hl_combine_attr(char_attr,
5155 							    HL_ATTR(HLF_CUL));
5156 		    }
5157 # endif
5158 		}
5159 #endif
5160 	    }
5161 
5162 #ifdef FEAT_CONCEAL
5163 	    if (   wp->w_p_cole > 0
5164 		&& (wp != curwin || lnum != wp->w_cursor.lnum ||
5165 							conceal_cursor_line(wp) )
5166 		&& ( (syntax_flags & HL_CONCEAL) != 0 || has_match_conc > 0)
5167 		&& !(lnum_in_visual_area
5168 				    && vim_strchr(wp->w_p_cocu, 'v') == NULL))
5169 	    {
5170 		char_attr = conceal_attr;
5171 		if ((prev_syntax_id != syntax_seqnr || has_match_conc > 1)
5172 			&& (syn_get_sub_char() != NUL || match_conc
5173 							 || wp->w_p_cole == 1)
5174 			&& wp->w_p_cole != 3)
5175 		{
5176 		    /* First time at this concealed item: display one
5177 		     * character. */
5178 		    if (match_conc)
5179 			c = match_conc;
5180 		    else if (syn_get_sub_char() != NUL)
5181 			c = syn_get_sub_char();
5182 		    else if (lcs_conceal != NUL)
5183 			c = lcs_conceal;
5184 		    else
5185 			c = ' ';
5186 
5187 		    prev_syntax_id = syntax_seqnr;
5188 
5189 		    if (n_extra > 0)
5190 			vcol_off += n_extra;
5191 		    vcol += n_extra;
5192 		    if (wp->w_p_wrap && n_extra > 0)
5193 		    {
5194 # ifdef FEAT_RIGHTLEFT
5195 			if (wp->w_p_rl)
5196 			{
5197 			    col -= n_extra;
5198 			    boguscols -= n_extra;
5199 			}
5200 			else
5201 # endif
5202 			{
5203 			    boguscols += n_extra;
5204 			    col += n_extra;
5205 			}
5206 		    }
5207 		    n_extra = 0;
5208 		    n_attr = 0;
5209 		}
5210 		else if (n_skip == 0)
5211 		{
5212 		    is_concealing = TRUE;
5213 		    n_skip = 1;
5214 		}
5215 # ifdef FEAT_MBYTE
5216 		mb_c = c;
5217 		if (enc_utf8 && utf_char2len(c) > 1)
5218 		{
5219 		    mb_utf8 = TRUE;
5220 		    u8cc[0] = 0;
5221 		    c = 0xc0;
5222 		}
5223 		else
5224 		    mb_utf8 = FALSE;	/* don't draw as UTF-8 */
5225 # endif
5226 	    }
5227 	    else
5228 	    {
5229 		prev_syntax_id = 0;
5230 		is_concealing = FALSE;
5231 	    }
5232 #endif /* FEAT_CONCEAL */
5233 	}
5234 
5235 #ifdef FEAT_CONCEAL
5236 	/* In the cursor line and we may be concealing characters: correct
5237 	 * the cursor column when we reach its position. */
5238 	if (!did_wcol && draw_state == WL_LINE
5239 		&& wp == curwin && lnum == wp->w_cursor.lnum
5240 		&& conceal_cursor_line(wp)
5241 		&& (int)wp->w_virtcol <= vcol + n_skip)
5242 	{
5243 #  ifdef FEAT_RIGHTLEFT
5244 	    if (wp->w_p_rl)
5245 		wp->w_wcol = wp->w_width - col + boguscols - 1;
5246 	    else
5247 #  endif
5248 		wp->w_wcol = col - boguscols;
5249 	    wp->w_wrow = row;
5250 	    did_wcol = TRUE;
5251 	}
5252 #endif
5253 
5254 	/* Don't override visual selection highlighting. */
5255 	if (n_attr > 0
5256 		&& draw_state == WL_LINE
5257 		&& !attr_pri)
5258 	    char_attr = extra_attr;
5259 
5260 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
5261 	/* XIM don't send preedit_start and preedit_end, but they send
5262 	 * preedit_changed and commit.  Thus Vim can't set "im_is_active", use
5263 	 * im_is_preediting() here. */
5264 	if (p_imst == IM_ON_THE_SPOT
5265 		&& xic != NULL
5266 		&& lnum == wp->w_cursor.lnum
5267 		&& (State & INSERT)
5268 		&& !p_imdisable
5269 		&& im_is_preediting()
5270 		&& draw_state == WL_LINE)
5271 	{
5272 	    colnr_T tcol;
5273 
5274 	    if (preedit_end_col == MAXCOL)
5275 		getvcol(curwin, &(wp->w_cursor), &tcol, NULL, NULL);
5276 	    else
5277 		tcol = preedit_end_col;
5278 	    if ((long)preedit_start_col <= vcol && vcol < (long)tcol)
5279 	    {
5280 		if (feedback_old_attr < 0)
5281 		{
5282 		    feedback_col = 0;
5283 		    feedback_old_attr = char_attr;
5284 		}
5285 		char_attr = im_get_feedback_attr(feedback_col);
5286 		if (char_attr < 0)
5287 		    char_attr = feedback_old_attr;
5288 		feedback_col++;
5289 	    }
5290 	    else if (feedback_old_attr >= 0)
5291 	    {
5292 		char_attr = feedback_old_attr;
5293 		feedback_old_attr = -1;
5294 		feedback_col = 0;
5295 	    }
5296 	}
5297 #endif
5298 	/*
5299 	 * Handle the case where we are in column 0 but not on the first
5300 	 * character of the line and the user wants us to show us a
5301 	 * special character (via 'listchars' option "precedes:<char>".
5302 	 */
5303 	if (lcs_prec_todo != NUL
5304 		&& wp->w_p_list
5305 		&& (wp->w_p_wrap ? wp->w_skipcol > 0 : wp->w_leftcol > 0)
5306 #ifdef FEAT_DIFF
5307 		&& filler_todo <= 0
5308 #endif
5309 		&& draw_state > WL_NR
5310 		&& c != NUL)
5311 	{
5312 	    c = lcs_prec;
5313 	    lcs_prec_todo = NUL;
5314 #ifdef FEAT_MBYTE
5315 	    if (has_mbyte && (*mb_char2cells)(mb_c) > 1)
5316 	    {
5317 		/* Double-width character being overwritten by the "precedes"
5318 		 * character, need to fill up half the character. */
5319 		c_extra = MB_FILLER_CHAR;
5320 		n_extra = 1;
5321 		n_attr = 2;
5322 		extra_attr = HL_ATTR(HLF_AT);
5323 	    }
5324 	    mb_c = c;
5325 	    if (enc_utf8 && utf_char2len(c) > 1)
5326 	    {
5327 		mb_utf8 = TRUE;
5328 		u8cc[0] = 0;
5329 		c = 0xc0;
5330 	    }
5331 	    else
5332 		mb_utf8 = FALSE;	/* don't draw as UTF-8 */
5333 #endif
5334 	    if (!attr_pri)
5335 	    {
5336 		saved_attr3 = char_attr; /* save current attr */
5337 		char_attr = HL_ATTR(HLF_AT); /* later copied to char_attr */
5338 		n_attr3 = 1;
5339 	    }
5340 	}
5341 
5342 	/*
5343 	 * At end of the text line or just after the last character.
5344 	 */
5345 	if (c == NUL
5346 #if defined(LINE_ATTR)
5347 		|| did_line_attr == 1
5348 #endif
5349 		)
5350 	{
5351 #ifdef FEAT_SEARCH_EXTRA
5352 	    long prevcol = (long)(ptr - line) - (c == NUL);
5353 
5354 	    /* we're not really at that column when skipping some text */
5355 	    if ((long)(wp->w_p_wrap ? wp->w_skipcol : wp->w_leftcol) > prevcol)
5356 		++prevcol;
5357 #endif
5358 
5359 	    /* Invert at least one char, used for Visual and empty line or
5360 	     * highlight match at end of line. If it's beyond the last
5361 	     * char on the screen, just overwrite that one (tricky!)  Not
5362 	     * needed when a '$' was displayed for 'list'. */
5363 #ifdef FEAT_SEARCH_EXTRA
5364 	    prevcol_hl_flag = FALSE;
5365 	    if (!search_hl.is_addpos && prevcol == (long)search_hl.startcol)
5366 		prevcol_hl_flag = TRUE;
5367 	    else
5368 	    {
5369 		cur = wp->w_match_head;
5370 		while (cur != NULL)
5371 		{
5372 		    if (!cur->hl.is_addpos && prevcol == (long)cur->hl.startcol)
5373 		    {
5374 			prevcol_hl_flag = TRUE;
5375 			break;
5376 		    }
5377 		    cur = cur->next;
5378 		}
5379 	    }
5380 #endif
5381 	    if (lcs_eol == lcs_eol_one
5382 		    && ((area_attr != 0 && vcol == fromcol
5383 			    && (VIsual_mode != Ctrl_V
5384 				|| lnum == VIsual.lnum
5385 				|| lnum == curwin->w_cursor.lnum)
5386 			    && c == NUL)
5387 #ifdef FEAT_SEARCH_EXTRA
5388 			/* highlight 'hlsearch' match at end of line */
5389 			|| (prevcol_hl_flag == TRUE
5390 # ifdef FEAT_SYN_HL
5391 			    && !(wp->w_p_cul && lnum == wp->w_cursor.lnum
5392 				    && !(wp == curwin && VIsual_active))
5393 # endif
5394 # ifdef FEAT_DIFF
5395 			    && diff_hlf == (hlf_T)0
5396 # endif
5397 # if defined(LINE_ATTR)
5398 			    && did_line_attr <= 1
5399 # endif
5400 			   )
5401 #endif
5402 		       ))
5403 	    {
5404 		int n = 0;
5405 
5406 #ifdef FEAT_RIGHTLEFT
5407 		if (wp->w_p_rl)
5408 		{
5409 		    if (col < 0)
5410 			n = 1;
5411 		}
5412 		else
5413 #endif
5414 		{
5415 		    if (col >= wp->w_width)
5416 			n = -1;
5417 		}
5418 		if (n != 0)
5419 		{
5420 		    /* At the window boundary, highlight the last character
5421 		     * instead (better than nothing). */
5422 		    off += n;
5423 		    col += n;
5424 		}
5425 		else
5426 		{
5427 		    /* Add a blank character to highlight. */
5428 		    ScreenLines[off] = ' ';
5429 #ifdef FEAT_MBYTE
5430 		    if (enc_utf8)
5431 			ScreenLinesUC[off] = 0;
5432 #endif
5433 		}
5434 #ifdef FEAT_SEARCH_EXTRA
5435 		if (area_attr == 0)
5436 		{
5437 		    /* Use attributes from match with highest priority among
5438 		     * 'search_hl' and the match list. */
5439 		    char_attr = search_hl.attr;
5440 		    cur = wp->w_match_head;
5441 		    shl_flag = FALSE;
5442 		    while (cur != NULL || shl_flag == FALSE)
5443 		    {
5444 			if (shl_flag == FALSE
5445 				&& ((cur != NULL
5446 					&& cur->priority > SEARCH_HL_PRIORITY)
5447 				    || cur == NULL))
5448 			{
5449 			    shl = &search_hl;
5450 			    shl_flag = TRUE;
5451 			}
5452 			else
5453 			    shl = &cur->hl;
5454 			if ((ptr - line) - 1 == (long)shl->startcol
5455 				&& (shl == &search_hl || !shl->is_addpos))
5456 			    char_attr = shl->attr;
5457 			if (shl != &search_hl && cur != NULL)
5458 			    cur = cur->next;
5459 		    }
5460 		}
5461 #endif
5462 		ScreenAttrs[off] = char_attr;
5463 #ifdef FEAT_RIGHTLEFT
5464 		if (wp->w_p_rl)
5465 		{
5466 		    --col;
5467 		    --off;
5468 		}
5469 		else
5470 #endif
5471 		{
5472 		    ++col;
5473 		    ++off;
5474 		}
5475 		++vcol;
5476 #ifdef FEAT_SYN_HL
5477 		eol_hl_off = 1;
5478 #endif
5479 	    }
5480 	}
5481 
5482 	/*
5483 	 * At end of the text line.
5484 	 */
5485 	if (c == NUL)
5486 	{
5487 #ifdef FEAT_SYN_HL
5488 	    if (eol_hl_off > 0 && vcol - eol_hl_off == (long)wp->w_virtcol
5489 		    && lnum == wp->w_cursor.lnum)
5490 	    {
5491 		/* highlight last char after line */
5492 		--col;
5493 		--off;
5494 		--vcol;
5495 	    }
5496 
5497 	    /* Highlight 'cursorcolumn' & 'colorcolumn' past end of the line. */
5498 	    if (wp->w_p_wrap)
5499 		v = wp->w_skipcol;
5500 	    else
5501 		v = wp->w_leftcol;
5502 
5503 	    /* check if line ends before left margin */
5504 	    if (vcol < v + col - win_col_off(wp))
5505 		vcol = v + col - win_col_off(wp);
5506 #ifdef FEAT_CONCEAL
5507 	    /* Get rid of the boguscols now, we want to draw until the right
5508 	     * edge for 'cursorcolumn'. */
5509 	    col -= boguscols;
5510 	    boguscols = 0;
5511 #endif
5512 
5513 	    if (draw_color_col)
5514 		draw_color_col = advance_color_col(VCOL_HLC, &color_cols);
5515 
5516 	    if (((wp->w_p_cuc
5517 		      && (int)wp->w_virtcol >= VCOL_HLC - eol_hl_off
5518 		      && (int)wp->w_virtcol <
5519 					wp->w_width * (row - startrow + 1) + v
5520 		      && lnum != wp->w_cursor.lnum)
5521 		    || draw_color_col)
5522 # ifdef FEAT_RIGHTLEFT
5523 		    && !wp->w_p_rl
5524 # endif
5525 		    )
5526 	    {
5527 		int	rightmost_vcol = 0;
5528 		int	i;
5529 
5530 		if (wp->w_p_cuc)
5531 		    rightmost_vcol = wp->w_virtcol;
5532 		if (draw_color_col)
5533 		    /* determine rightmost colorcolumn to possibly draw */
5534 		    for (i = 0; color_cols[i] >= 0; ++i)
5535 			if (rightmost_vcol < color_cols[i])
5536 			    rightmost_vcol = color_cols[i];
5537 
5538 		while (col < wp->w_width)
5539 		{
5540 		    ScreenLines[off] = ' ';
5541 #ifdef FEAT_MBYTE
5542 		    if (enc_utf8)
5543 			ScreenLinesUC[off] = 0;
5544 #endif
5545 		    ++col;
5546 		    if (draw_color_col)
5547 			draw_color_col = advance_color_col(VCOL_HLC,
5548 								 &color_cols);
5549 
5550 		    if (wp->w_p_cuc && VCOL_HLC == (long)wp->w_virtcol)
5551 			ScreenAttrs[off++] = HL_ATTR(HLF_CUC);
5552 		    else if (draw_color_col && VCOL_HLC == *color_cols)
5553 			ScreenAttrs[off++] = HL_ATTR(HLF_MC);
5554 		    else
5555 			ScreenAttrs[off++] = 0;
5556 
5557 		    if (VCOL_HLC >= rightmost_vcol)
5558 			break;
5559 
5560 		    ++vcol;
5561 		}
5562 	    }
5563 #endif
5564 
5565 	    screen_line(screen_row, wp->w_wincol, col,
5566 				  (int)wp->w_width, HAS_RIGHTLEFT(wp->w_p_rl));
5567 	    row++;
5568 
5569 	    /*
5570 	     * Update w_cline_height and w_cline_folded if the cursor line was
5571 	     * updated (saves a call to plines() later).
5572 	     */
5573 	    if (wp == curwin && lnum == curwin->w_cursor.lnum)
5574 	    {
5575 		curwin->w_cline_row = startrow;
5576 		curwin->w_cline_height = row - startrow;
5577 #ifdef FEAT_FOLDING
5578 		curwin->w_cline_folded = FALSE;
5579 #endif
5580 		curwin->w_valid |= (VALID_CHEIGHT|VALID_CROW);
5581 	    }
5582 
5583 	    break;
5584 	}
5585 
5586 	/* line continues beyond line end */
5587 	if (lcs_ext
5588 		&& !wp->w_p_wrap
5589 #ifdef FEAT_DIFF
5590 		&& filler_todo <= 0
5591 #endif
5592 		&& (
5593 #ifdef FEAT_RIGHTLEFT
5594 		    wp->w_p_rl ? col == 0 :
5595 #endif
5596 		    col == wp->w_width - 1)
5597 		&& (*ptr != NUL
5598 		    || (wp->w_p_list && lcs_eol_one > 0)
5599 		    || (n_extra && (c_extra != NUL || *p_extra != NUL))))
5600 	{
5601 	    c = lcs_ext;
5602 	    char_attr = HL_ATTR(HLF_AT);
5603 #ifdef FEAT_MBYTE
5604 	    mb_c = c;
5605 	    if (enc_utf8 && utf_char2len(c) > 1)
5606 	    {
5607 		mb_utf8 = TRUE;
5608 		u8cc[0] = 0;
5609 		c = 0xc0;
5610 	    }
5611 	    else
5612 		mb_utf8 = FALSE;
5613 #endif
5614 	}
5615 
5616 #ifdef FEAT_SYN_HL
5617 	/* advance to the next 'colorcolumn' */
5618 	if (draw_color_col)
5619 	    draw_color_col = advance_color_col(VCOL_HLC, &color_cols);
5620 
5621 	/* Highlight the cursor column if 'cursorcolumn' is set.  But don't
5622 	 * highlight the cursor position itself.
5623 	 * Also highlight the 'colorcolumn' if it is different than
5624 	 * 'cursorcolumn' */
5625 	vcol_save_attr = -1;
5626 	if (draw_state == WL_LINE && !lnum_in_visual_area
5627 		&& search_attr == 0 && area_attr == 0)
5628 	{
5629 	    if (wp->w_p_cuc && VCOL_HLC == (long)wp->w_virtcol
5630 						 && lnum != wp->w_cursor.lnum)
5631 	    {
5632 		vcol_save_attr = char_attr;
5633 		char_attr = hl_combine_attr(char_attr, HL_ATTR(HLF_CUC));
5634 	    }
5635 	    else if (draw_color_col && VCOL_HLC == *color_cols)
5636 	    {
5637 		vcol_save_attr = char_attr;
5638 		char_attr = hl_combine_attr(char_attr, HL_ATTR(HLF_MC));
5639 	    }
5640 	}
5641 #endif
5642 
5643 	/*
5644 	 * Store character to be displayed.
5645 	 * Skip characters that are left of the screen for 'nowrap'.
5646 	 */
5647 	vcol_prev = vcol;
5648 	if (draw_state < WL_LINE || n_skip <= 0)
5649 	{
5650 	    /*
5651 	     * Store the character.
5652 	     */
5653 #if defined(FEAT_RIGHTLEFT) && defined(FEAT_MBYTE)
5654 	    if (has_mbyte && wp->w_p_rl && (*mb_char2cells)(mb_c) > 1)
5655 	    {
5656 		/* A double-wide character is: put first halve in left cell. */
5657 		--off;
5658 		--col;
5659 	    }
5660 #endif
5661 	    ScreenLines[off] = c;
5662 #ifdef FEAT_MBYTE
5663 	    if (enc_dbcs == DBCS_JPNU)
5664 	    {
5665 		if ((mb_c & 0xff00) == 0x8e00)
5666 		    ScreenLines[off] = 0x8e;
5667 		ScreenLines2[off] = mb_c & 0xff;
5668 	    }
5669 	    else if (enc_utf8)
5670 	    {
5671 		if (mb_utf8)
5672 		{
5673 		    int i;
5674 
5675 		    ScreenLinesUC[off] = mb_c;
5676 		    if ((c & 0xff) == 0)
5677 			ScreenLines[off] = 0x80;   /* avoid storing zero */
5678 		    for (i = 0; i < Screen_mco; ++i)
5679 		    {
5680 			ScreenLinesC[i][off] = u8cc[i];
5681 			if (u8cc[i] == 0)
5682 			    break;
5683 		    }
5684 		}
5685 		else
5686 		    ScreenLinesUC[off] = 0;
5687 	    }
5688 	    if (multi_attr)
5689 	    {
5690 		ScreenAttrs[off] = multi_attr;
5691 		multi_attr = 0;
5692 	    }
5693 	    else
5694 #endif
5695 		ScreenAttrs[off] = char_attr;
5696 
5697 #ifdef FEAT_MBYTE
5698 	    if (has_mbyte && (*mb_char2cells)(mb_c) > 1)
5699 	    {
5700 		/* Need to fill two screen columns. */
5701 		++off;
5702 		++col;
5703 		if (enc_utf8)
5704 		    /* UTF-8: Put a 0 in the second screen char. */
5705 		    ScreenLines[off] = 0;
5706 		else
5707 		    /* DBCS: Put second byte in the second screen char. */
5708 		    ScreenLines[off] = mb_c & 0xff;
5709 		if (draw_state > WL_NR
5710 #ifdef FEAT_DIFF
5711 			&& filler_todo <= 0
5712 #endif
5713 			)
5714 		    ++vcol;
5715 		/* When "tocol" is halfway a character, set it to the end of
5716 		 * the character, otherwise highlighting won't stop. */
5717 		if (tocol == vcol)
5718 		    ++tocol;
5719 #ifdef FEAT_RIGHTLEFT
5720 		if (wp->w_p_rl)
5721 		{
5722 		    /* now it's time to backup one cell */
5723 		    --off;
5724 		    --col;
5725 		}
5726 #endif
5727 	    }
5728 #endif
5729 #ifdef FEAT_RIGHTLEFT
5730 	    if (wp->w_p_rl)
5731 	    {
5732 		--off;
5733 		--col;
5734 	    }
5735 	    else
5736 #endif
5737 	    {
5738 		++off;
5739 		++col;
5740 	    }
5741 	}
5742 #ifdef FEAT_CONCEAL
5743 	else if (wp->w_p_cole > 0 && is_concealing)
5744 	{
5745 	    --n_skip;
5746 	    ++vcol_off;
5747 	    if (n_extra > 0)
5748 		vcol_off += n_extra;
5749 	    if (wp->w_p_wrap)
5750 	    {
5751 		/*
5752 		 * Special voodoo required if 'wrap' is on.
5753 		 *
5754 		 * Advance the column indicator to force the line
5755 		 * drawing to wrap early. This will make the line
5756 		 * take up the same screen space when parts are concealed,
5757 		 * so that cursor line computations aren't messed up.
5758 		 *
5759 		 * To avoid the fictitious advance of 'col' causing
5760 		 * trailing junk to be written out of the screen line
5761 		 * we are building, 'boguscols' keeps track of the number
5762 		 * of bad columns we have advanced.
5763 		 */
5764 		if (n_extra > 0)
5765 		{
5766 		    vcol += n_extra;
5767 # ifdef FEAT_RIGHTLEFT
5768 		    if (wp->w_p_rl)
5769 		    {
5770 			col -= n_extra;
5771 			boguscols -= n_extra;
5772 		    }
5773 		    else
5774 # endif
5775 		    {
5776 			col += n_extra;
5777 			boguscols += n_extra;
5778 		    }
5779 		    n_extra = 0;
5780 		    n_attr = 0;
5781 		}
5782 
5783 
5784 # ifdef FEAT_MBYTE
5785 		if (has_mbyte && (*mb_char2cells)(mb_c) > 1)
5786 		{
5787 		    /* Need to fill two screen columns. */
5788 #  ifdef FEAT_RIGHTLEFT
5789 		    if (wp->w_p_rl)
5790 		    {
5791 			--boguscols;
5792 			--col;
5793 		    }
5794 		    else
5795 #  endif
5796 		    {
5797 			++boguscols;
5798 			++col;
5799 		    }
5800 		}
5801 # endif
5802 
5803 # ifdef FEAT_RIGHTLEFT
5804 		if (wp->w_p_rl)
5805 		{
5806 		    --boguscols;
5807 		    --col;
5808 		}
5809 		else
5810 # endif
5811 		{
5812 		    ++boguscols;
5813 		    ++col;
5814 		}
5815 	    }
5816 	    else
5817 	    {
5818 		if (n_extra > 0)
5819 		{
5820 		    vcol += n_extra;
5821 		    n_extra = 0;
5822 		    n_attr = 0;
5823 		}
5824 	    }
5825 
5826 	}
5827 #endif /* FEAT_CONCEAL */
5828 	else
5829 	    --n_skip;
5830 
5831 	/* Only advance the "vcol" when after the 'number' or 'relativenumber'
5832 	 * column. */
5833 	if (draw_state > WL_NR
5834 #ifdef FEAT_DIFF
5835 		&& filler_todo <= 0
5836 #endif
5837 		)
5838 	    ++vcol;
5839 
5840 #ifdef FEAT_SYN_HL
5841 	if (vcol_save_attr >= 0)
5842 	    char_attr = vcol_save_attr;
5843 #endif
5844 
5845 	/* restore attributes after "predeces" in 'listchars' */
5846 	if (draw_state > WL_NR && n_attr3 > 0 && --n_attr3 == 0)
5847 	    char_attr = saved_attr3;
5848 
5849 	/* restore attributes after last 'listchars' or 'number' char */
5850 	if (n_attr > 0 && draw_state == WL_LINE && --n_attr == 0)
5851 	    char_attr = saved_attr2;
5852 
5853 	/*
5854 	 * At end of screen line and there is more to come: Display the line
5855 	 * so far.  If there is no more to display it is caught above.
5856 	 */
5857 	if ((
5858 #ifdef FEAT_RIGHTLEFT
5859 	    wp->w_p_rl ? (col < 0) :
5860 #endif
5861 				    (col >= wp->w_width))
5862 		&& (*ptr != NUL
5863 #ifdef FEAT_DIFF
5864 		    || filler_todo > 0
5865 #endif
5866 		    || (wp->w_p_list && lcs_eol != NUL && p_extra != at_end_str)
5867 		    || (n_extra != 0 && (c_extra != NUL || *p_extra != NUL)))
5868 		)
5869 	{
5870 #ifdef FEAT_CONCEAL
5871 	    screen_line(screen_row, wp->w_wincol, col - boguscols,
5872 				  (int)wp->w_width, HAS_RIGHTLEFT(wp->w_p_rl));
5873 	    boguscols = 0;
5874 #else
5875 	    screen_line(screen_row, wp->w_wincol, col,
5876 				  (int)wp->w_width, HAS_RIGHTLEFT(wp->w_p_rl));
5877 #endif
5878 	    ++row;
5879 	    ++screen_row;
5880 
5881 	    /* When not wrapping and finished diff lines, or when displayed
5882 	     * '$' and highlighting until last column, break here. */
5883 	    if ((!wp->w_p_wrap
5884 #ifdef FEAT_DIFF
5885 		    && filler_todo <= 0
5886 #endif
5887 		    ) || lcs_eol_one == -1)
5888 		break;
5889 
5890 	    /* When the window is too narrow draw all "@" lines. */
5891 	    if (draw_state != WL_LINE
5892 #ifdef FEAT_DIFF
5893 		    && filler_todo <= 0
5894 #endif
5895 		    )
5896 	    {
5897 		win_draw_end(wp, '@', ' ', row, wp->w_height, HLF_AT);
5898 		draw_vsep_win(wp, row);
5899 		row = endrow;
5900 	    }
5901 
5902 	    /* When line got too long for screen break here. */
5903 	    if (row == endrow)
5904 	    {
5905 		++row;
5906 		break;
5907 	    }
5908 
5909 	    if (screen_cur_row == screen_row - 1
5910 #ifdef FEAT_DIFF
5911 		     && filler_todo <= 0
5912 #endif
5913 		     && wp->w_width == Columns)
5914 	    {
5915 		/* Remember that the line wraps, used for modeless copy. */
5916 		LineWraps[screen_row - 1] = TRUE;
5917 
5918 		/*
5919 		 * Special trick to make copy/paste of wrapped lines work with
5920 		 * xterm/screen: write an extra character beyond the end of
5921 		 * the line. This will work with all terminal types
5922 		 * (regardless of the xn,am settings).
5923 		 * Only do this on a fast tty.
5924 		 * Only do this if the cursor is on the current line
5925 		 * (something has been written in it).
5926 		 * Don't do this for the GUI.
5927 		 * Don't do this for double-width characters.
5928 		 * Don't do this for a window not at the right screen border.
5929 		 */
5930 		if (p_tf
5931 #ifdef FEAT_GUI
5932 			 && !gui.in_use
5933 #endif
5934 #ifdef FEAT_MBYTE
5935 			 && !(has_mbyte
5936 			     && ((*mb_off2cells)(LineOffset[screen_row],
5937 				     LineOffset[screen_row] + screen_Columns)
5938 									  == 2
5939 				 || (*mb_off2cells)(LineOffset[screen_row - 1]
5940 							+ (int)Columns - 2,
5941 				     LineOffset[screen_row] + screen_Columns)
5942 									== 2))
5943 #endif
5944 		   )
5945 		{
5946 		    /* First make sure we are at the end of the screen line,
5947 		     * then output the same character again to let the
5948 		     * terminal know about the wrap.  If the terminal doesn't
5949 		     * auto-wrap, we overwrite the character. */
5950 		    if (screen_cur_col != wp->w_width)
5951 			screen_char(LineOffset[screen_row - 1]
5952 						      + (unsigned)Columns - 1,
5953 					  screen_row - 1, (int)(Columns - 1));
5954 
5955 #ifdef FEAT_MBYTE
5956 		    /* When there is a multi-byte character, just output a
5957 		     * space to keep it simple. */
5958 		    if (has_mbyte && MB_BYTE2LEN(ScreenLines[LineOffset[
5959 					screen_row - 1] + (Columns - 1)]) > 1)
5960 			out_char(' ');
5961 		    else
5962 #endif
5963 			out_char(ScreenLines[LineOffset[screen_row - 1]
5964 							    + (Columns - 1)]);
5965 		    /* force a redraw of the first char on the next line */
5966 		    ScreenAttrs[LineOffset[screen_row]] = (sattr_T)-1;
5967 		    screen_start();	/* don't know where cursor is now */
5968 		}
5969 	    }
5970 
5971 	    col = 0;
5972 	    off = (unsigned)(current_ScreenLine - ScreenLines);
5973 #ifdef FEAT_RIGHTLEFT
5974 	    if (wp->w_p_rl)
5975 	    {
5976 		col = wp->w_width - 1;	/* col is not used if breaking! */
5977 		off += col;
5978 	    }
5979 #endif
5980 
5981 	    /* reset the drawing state for the start of a wrapped line */
5982 	    draw_state = WL_START;
5983 	    saved_n_extra = n_extra;
5984 	    saved_p_extra = p_extra;
5985 	    saved_c_extra = c_extra;
5986 	    saved_char_attr = char_attr;
5987 	    n_extra = 0;
5988 	    lcs_prec_todo = lcs_prec;
5989 #ifdef FEAT_LINEBREAK
5990 # ifdef FEAT_DIFF
5991 	    if (filler_todo <= 0)
5992 # endif
5993 		need_showbreak = TRUE;
5994 #endif
5995 #ifdef FEAT_DIFF
5996 	    --filler_todo;
5997 	    /* When the filler lines are actually below the last line of the
5998 	     * file, don't draw the line itself, break here. */
5999 	    if (filler_todo == 0 && wp->w_botfill)
6000 		break;
6001 #endif
6002 	}
6003 
6004     }	/* for every character in the line */
6005 
6006 #ifdef FEAT_SPELL
6007     /* After an empty line check first word for capital. */
6008     if (*skipwhite(line) == NUL)
6009     {
6010 	capcol_lnum = lnum + 1;
6011 	cap_col = 0;
6012     }
6013 #endif
6014 
6015     vim_free(p_extra_free);
6016     return row;
6017 }
6018 
6019 #ifdef FEAT_MBYTE
6020 static int comp_char_differs(int, int);
6021 
6022 /*
6023  * Return if the composing characters at "off_from" and "off_to" differ.
6024  * Only to be used when ScreenLinesUC[off_from] != 0.
6025  */
6026     static int
6027 comp_char_differs(int off_from, int off_to)
6028 {
6029     int	    i;
6030 
6031     for (i = 0; i < Screen_mco; ++i)
6032     {
6033 	if (ScreenLinesC[i][off_from] != ScreenLinesC[i][off_to])
6034 	    return TRUE;
6035 	if (ScreenLinesC[i][off_from] == 0)
6036 	    break;
6037     }
6038     return FALSE;
6039 }
6040 #endif
6041 
6042 /*
6043  * Check whether the given character needs redrawing:
6044  * - the (first byte of the) character is different
6045  * - the attributes are different
6046  * - the character is multi-byte and the next byte is different
6047  * - the character is two cells wide and the second cell differs.
6048  */
6049     static int
6050 char_needs_redraw(int off_from, int off_to, int cols)
6051 {
6052     if (cols > 0
6053 	    && ((ScreenLines[off_from] != ScreenLines[off_to]
6054 		    || ScreenAttrs[off_from] != ScreenAttrs[off_to])
6055 
6056 #ifdef FEAT_MBYTE
6057 		|| (enc_dbcs != 0
6058 		    && MB_BYTE2LEN(ScreenLines[off_from]) > 1
6059 		    && (enc_dbcs == DBCS_JPNU && ScreenLines[off_from] == 0x8e
6060 			? ScreenLines2[off_from] != ScreenLines2[off_to]
6061 			: (cols > 1 && ScreenLines[off_from + 1]
6062 						 != ScreenLines[off_to + 1])))
6063 		|| (enc_utf8
6064 		    && (ScreenLinesUC[off_from] != ScreenLinesUC[off_to]
6065 			|| (ScreenLinesUC[off_from] != 0
6066 			    && comp_char_differs(off_from, off_to))
6067 			|| ((*mb_off2cells)(off_from, off_from + cols) > 1
6068 			    && ScreenLines[off_from + 1]
6069 						  != ScreenLines[off_to + 1])))
6070 #endif
6071 	       ))
6072 	return TRUE;
6073     return FALSE;
6074 }
6075 
6076 #if defined(FEAT_TERMINAL) || defined(PROTO)
6077 /*
6078  * Return the index in ScreenLines[] for the current screen line.
6079  */
6080     int
6081 screen_get_current_line_off()
6082 {
6083     return (int)(current_ScreenLine - ScreenLines);
6084 }
6085 #endif
6086 
6087 /*
6088  * Move one "cooked" screen line to the screen, but only the characters that
6089  * have actually changed.  Handle insert/delete character.
6090  * "coloff" gives the first column on the screen for this line.
6091  * "endcol" gives the columns where valid characters are.
6092  * "clear_width" is the width of the window.  It's > 0 if the rest of the line
6093  * needs to be cleared, negative otherwise.
6094  * "rlflag" is TRUE in a rightleft window:
6095  *    When TRUE and "clear_width" > 0, clear columns 0 to "endcol"
6096  *    When FALSE and "clear_width" > 0, clear columns "endcol" to "clear_width"
6097  */
6098     void
6099 screen_line(
6100     int	    row,
6101     int	    coloff,
6102     int	    endcol,
6103     int	    clear_width,
6104     int	    rlflag UNUSED)
6105 {
6106     unsigned	    off_from;
6107     unsigned	    off_to;
6108 #ifdef FEAT_MBYTE
6109     unsigned	    max_off_from;
6110     unsigned	    max_off_to;
6111 #endif
6112     int		    col = 0;
6113     int		    hl;
6114     int		    force = FALSE;	/* force update rest of the line */
6115     int		    redraw_this		/* bool: does character need redraw? */
6116 #ifdef FEAT_GUI
6117 				= TRUE	/* For GUI when while-loop empty */
6118 #endif
6119 				;
6120     int		    redraw_next;	/* redraw_this for next character */
6121 #ifdef FEAT_MBYTE
6122     int		    clear_next = FALSE;
6123     int		    char_cells;		/* 1: normal char */
6124 					/* 2: occupies two display cells */
6125 # define CHAR_CELLS char_cells
6126 #else
6127 # define CHAR_CELLS 1
6128 #endif
6129 
6130     /* Check for illegal row and col, just in case. */
6131     if (row >= Rows)
6132 	row = Rows - 1;
6133     if (endcol > Columns)
6134 	endcol = Columns;
6135 
6136 # ifdef FEAT_CLIPBOARD
6137     clip_may_clear_selection(row, row);
6138 # endif
6139 
6140     off_from = (unsigned)(current_ScreenLine - ScreenLines);
6141     off_to = LineOffset[row] + coloff;
6142 #ifdef FEAT_MBYTE
6143     max_off_from = off_from + screen_Columns;
6144     max_off_to = LineOffset[row] + screen_Columns;
6145 #endif
6146 
6147 #ifdef FEAT_RIGHTLEFT
6148     if (rlflag)
6149     {
6150 	/* Clear rest first, because it's left of the text. */
6151 	if (clear_width > 0)
6152 	{
6153 	    while (col <= endcol && ScreenLines[off_to] == ' '
6154 		    && ScreenAttrs[off_to] == 0
6155 # ifdef FEAT_MBYTE
6156 				  && (!enc_utf8 || ScreenLinesUC[off_to] == 0)
6157 # endif
6158 						  )
6159 	    {
6160 		++off_to;
6161 		++col;
6162 	    }
6163 	    if (col <= endcol)
6164 		screen_fill(row, row + 1, col + coloff,
6165 					    endcol + coloff + 1, ' ', ' ', 0);
6166 	}
6167 	col = endcol + 1;
6168 	off_to = LineOffset[row] + col + coloff;
6169 	off_from += col;
6170 	endcol = (clear_width > 0 ? clear_width : -clear_width);
6171     }
6172 #endif /* FEAT_RIGHTLEFT */
6173 
6174     redraw_next = char_needs_redraw(off_from, off_to, endcol - col);
6175 
6176     while (col < endcol)
6177     {
6178 #ifdef FEAT_MBYTE
6179 	if (has_mbyte && (col + 1 < endcol))
6180 	    char_cells = (*mb_off2cells)(off_from, max_off_from);
6181 	else
6182 	    char_cells = 1;
6183 #endif
6184 
6185 	redraw_this = redraw_next;
6186 	redraw_next = force || char_needs_redraw(off_from + CHAR_CELLS,
6187 			      off_to + CHAR_CELLS, endcol - col - CHAR_CELLS);
6188 
6189 #ifdef FEAT_GUI
6190 	/* If the next character was bold, then redraw the current character to
6191 	 * remove any pixels that might have spilt over into us.  This only
6192 	 * happens in the GUI.
6193 	 */
6194 	if (redraw_next && gui.in_use)
6195 	{
6196 	    hl = ScreenAttrs[off_to + CHAR_CELLS];
6197 	    if (hl > HL_ALL)
6198 		hl = syn_attr2attr(hl);
6199 	    if (hl & HL_BOLD)
6200 		redraw_this = TRUE;
6201 	}
6202 #endif
6203 
6204 	if (redraw_this)
6205 	{
6206 	    /*
6207 	     * Special handling when 'xs' termcap flag set (hpterm):
6208 	     * Attributes for characters are stored at the position where the
6209 	     * cursor is when writing the highlighting code.  The
6210 	     * start-highlighting code must be written with the cursor on the
6211 	     * first highlighted character.  The stop-highlighting code must
6212 	     * be written with the cursor just after the last highlighted
6213 	     * character.
6214 	     * Overwriting a character doesn't remove it's highlighting.  Need
6215 	     * to clear the rest of the line, and force redrawing it
6216 	     * completely.
6217 	     */
6218 	    if (       p_wiv
6219 		    && !force
6220 #ifdef FEAT_GUI
6221 		    && !gui.in_use
6222 #endif
6223 		    && ScreenAttrs[off_to] != 0
6224 		    && ScreenAttrs[off_from] != ScreenAttrs[off_to])
6225 	    {
6226 		/*
6227 		 * Need to remove highlighting attributes here.
6228 		 */
6229 		windgoto(row, col + coloff);
6230 		out_str(T_CE);		/* clear rest of this screen line */
6231 		screen_start();		/* don't know where cursor is now */
6232 		force = TRUE;		/* force redraw of rest of the line */
6233 		redraw_next = TRUE;	/* or else next char would miss out */
6234 
6235 		/*
6236 		 * If the previous character was highlighted, need to stop
6237 		 * highlighting at this character.
6238 		 */
6239 		if (col + coloff > 0 && ScreenAttrs[off_to - 1] != 0)
6240 		{
6241 		    screen_attr = ScreenAttrs[off_to - 1];
6242 		    term_windgoto(row, col + coloff);
6243 		    screen_stop_highlight();
6244 		}
6245 		else
6246 		    screen_attr = 0;	    /* highlighting has stopped */
6247 	    }
6248 #ifdef FEAT_MBYTE
6249 	    if (enc_dbcs != 0)
6250 	    {
6251 		/* Check if overwriting a double-byte with a single-byte or
6252 		 * the other way around requires another character to be
6253 		 * redrawn.  For UTF-8 this isn't needed, because comparing
6254 		 * ScreenLinesUC[] is sufficient. */
6255 		if (char_cells == 1
6256 			&& col + 1 < endcol
6257 			&& (*mb_off2cells)(off_to, max_off_to) > 1)
6258 		{
6259 		    /* Writing a single-cell character over a double-cell
6260 		     * character: need to redraw the next cell. */
6261 		    ScreenLines[off_to + 1] = 0;
6262 		    redraw_next = TRUE;
6263 		}
6264 		else if (char_cells == 2
6265 			&& col + 2 < endcol
6266 			&& (*mb_off2cells)(off_to, max_off_to) == 1
6267 			&& (*mb_off2cells)(off_to + 1, max_off_to) > 1)
6268 		{
6269 		    /* Writing the second half of a double-cell character over
6270 		     * a double-cell character: need to redraw the second
6271 		     * cell. */
6272 		    ScreenLines[off_to + 2] = 0;
6273 		    redraw_next = TRUE;
6274 		}
6275 
6276 		if (enc_dbcs == DBCS_JPNU)
6277 		    ScreenLines2[off_to] = ScreenLines2[off_from];
6278 	    }
6279 	    /* When writing a single-width character over a double-width
6280 	     * character and at the end of the redrawn text, need to clear out
6281 	     * the right halve of the old character.
6282 	     * Also required when writing the right halve of a double-width
6283 	     * char over the left halve of an existing one. */
6284 	    if (has_mbyte && col + char_cells == endcol
6285 		    && ((char_cells == 1
6286 			    && (*mb_off2cells)(off_to, max_off_to) > 1)
6287 			|| (char_cells == 2
6288 			    && (*mb_off2cells)(off_to, max_off_to) == 1
6289 			    && (*mb_off2cells)(off_to + 1, max_off_to) > 1)))
6290 		clear_next = TRUE;
6291 #endif
6292 
6293 	    ScreenLines[off_to] = ScreenLines[off_from];
6294 #ifdef FEAT_MBYTE
6295 	    if (enc_utf8)
6296 	    {
6297 		ScreenLinesUC[off_to] = ScreenLinesUC[off_from];
6298 		if (ScreenLinesUC[off_from] != 0)
6299 		{
6300 		    int	    i;
6301 
6302 		    for (i = 0; i < Screen_mco; ++i)
6303 			ScreenLinesC[i][off_to] = ScreenLinesC[i][off_from];
6304 		}
6305 	    }
6306 	    if (char_cells == 2)
6307 		ScreenLines[off_to + 1] = ScreenLines[off_from + 1];
6308 #endif
6309 
6310 #if defined(FEAT_GUI) || defined(UNIX)
6311 	    /* The bold trick makes a single column of pixels appear in the
6312 	     * next character.  When a bold character is removed, the next
6313 	     * character should be redrawn too.  This happens for our own GUI
6314 	     * and for some xterms. */
6315 	    if (
6316 # ifdef FEAT_GUI
6317 		    gui.in_use
6318 # endif
6319 # if defined(FEAT_GUI) && defined(UNIX)
6320 		    ||
6321 # endif
6322 # ifdef UNIX
6323 		    term_is_xterm
6324 # endif
6325 		    )
6326 	    {
6327 		hl = ScreenAttrs[off_to];
6328 		if (hl > HL_ALL)
6329 		    hl = syn_attr2attr(hl);
6330 		if (hl & HL_BOLD)
6331 		    redraw_next = TRUE;
6332 	    }
6333 #endif
6334 	    ScreenAttrs[off_to] = ScreenAttrs[off_from];
6335 #ifdef FEAT_MBYTE
6336 	    /* For simplicity set the attributes of second half of a
6337 	     * double-wide character equal to the first half. */
6338 	    if (char_cells == 2)
6339 		ScreenAttrs[off_to + 1] = ScreenAttrs[off_from];
6340 
6341 	    if (enc_dbcs != 0 && char_cells == 2)
6342 		screen_char_2(off_to, row, col + coloff);
6343 	    else
6344 #endif
6345 		screen_char(off_to, row, col + coloff);
6346 	}
6347 	else if (  p_wiv
6348 #ifdef FEAT_GUI
6349 		&& !gui.in_use
6350 #endif
6351 		&& col + coloff > 0)
6352 	{
6353 	    if (ScreenAttrs[off_to] == ScreenAttrs[off_to - 1])
6354 	    {
6355 		/*
6356 		 * Don't output stop-highlight when moving the cursor, it will
6357 		 * stop the highlighting when it should continue.
6358 		 */
6359 		screen_attr = 0;
6360 	    }
6361 	    else if (screen_attr != 0)
6362 		screen_stop_highlight();
6363 	}
6364 
6365 	off_to += CHAR_CELLS;
6366 	off_from += CHAR_CELLS;
6367 	col += CHAR_CELLS;
6368     }
6369 
6370 #ifdef FEAT_MBYTE
6371     if (clear_next)
6372     {
6373 	/* Clear the second half of a double-wide character of which the left
6374 	 * half was overwritten with a single-wide character. */
6375 	ScreenLines[off_to] = ' ';
6376 	if (enc_utf8)
6377 	    ScreenLinesUC[off_to] = 0;
6378 	screen_char(off_to, row, col + coloff);
6379     }
6380 #endif
6381 
6382     if (clear_width > 0
6383 #ifdef FEAT_RIGHTLEFT
6384 		    && !rlflag
6385 #endif
6386 				   )
6387     {
6388 #ifdef FEAT_GUI
6389 	int startCol = col;
6390 #endif
6391 
6392 	/* blank out the rest of the line */
6393 	while (col < clear_width && ScreenLines[off_to] == ' '
6394 						  && ScreenAttrs[off_to] == 0
6395 #ifdef FEAT_MBYTE
6396 				  && (!enc_utf8 || ScreenLinesUC[off_to] == 0)
6397 #endif
6398 						  )
6399 	{
6400 	    ++off_to;
6401 	    ++col;
6402 	}
6403 	if (col < clear_width)
6404 	{
6405 #ifdef FEAT_GUI
6406 	    /*
6407 	     * In the GUI, clearing the rest of the line may leave pixels
6408 	     * behind if the first character cleared was bold.  Some bold
6409 	     * fonts spill over the left.  In this case we redraw the previous
6410 	     * character too.  If we didn't skip any blanks above, then we
6411 	     * only redraw if the character wasn't already redrawn anyway.
6412 	     */
6413 	    if (gui.in_use && (col > startCol || !redraw_this))
6414 	    {
6415 		hl = ScreenAttrs[off_to];
6416 		if (hl > HL_ALL || (hl & HL_BOLD))
6417 		{
6418 		    int prev_cells = 1;
6419 # ifdef FEAT_MBYTE
6420 		    if (enc_utf8)
6421 			/* for utf-8, ScreenLines[char_offset + 1] == 0 means
6422 			 * that its width is 2. */
6423 			prev_cells = ScreenLines[off_to - 1] == 0 ? 2 : 1;
6424 		    else if (enc_dbcs != 0)
6425 		    {
6426 			/* find previous character by counting from first
6427 			 * column and get its width. */
6428 			unsigned off = LineOffset[row];
6429 			unsigned max_off = LineOffset[row] + screen_Columns;
6430 
6431 			while (off < off_to)
6432 			{
6433 			    prev_cells = (*mb_off2cells)(off, max_off);
6434 			    off += prev_cells;
6435 			}
6436 		    }
6437 
6438 		    if (enc_dbcs != 0 && prev_cells > 1)
6439 			screen_char_2(off_to - prev_cells, row,
6440 						   col + coloff - prev_cells);
6441 		    else
6442 # endif
6443 			screen_char(off_to - prev_cells, row,
6444 						   col + coloff - prev_cells);
6445 		}
6446 	    }
6447 #endif
6448 	    screen_fill(row, row + 1, col + coloff, clear_width + coloff,
6449 								 ' ', ' ', 0);
6450 	    off_to += clear_width - col;
6451 	    col = clear_width;
6452 	}
6453     }
6454 
6455     if (clear_width > 0)
6456     {
6457 	/* For a window that's left of another, draw the separator char. */
6458 	if (col + coloff < Columns)
6459 	{
6460 	    int c;
6461 
6462 	    c = fillchar_vsep(&hl);
6463 	    if (ScreenLines[off_to] != (schar_T)c
6464 #ifdef FEAT_MBYTE
6465 		    || (enc_utf8 && (int)ScreenLinesUC[off_to]
6466 						       != (c >= 0x80 ? c : 0))
6467 #endif
6468 		    || ScreenAttrs[off_to] != hl)
6469 	    {
6470 		ScreenLines[off_to] = c;
6471 		ScreenAttrs[off_to] = hl;
6472 #ifdef FEAT_MBYTE
6473 		if (enc_utf8)
6474 		{
6475 		    if (c >= 0x80)
6476 		    {
6477 			ScreenLinesUC[off_to] = c;
6478 			ScreenLinesC[0][off_to] = 0;
6479 		    }
6480 		    else
6481 			ScreenLinesUC[off_to] = 0;
6482 		}
6483 #endif
6484 		screen_char(off_to, row, col + coloff);
6485 	    }
6486 	}
6487 	else
6488 	    LineWraps[row] = FALSE;
6489     }
6490 }
6491 
6492 #if defined(FEAT_RIGHTLEFT) || defined(PROTO)
6493 /*
6494  * Mirror text "str" for right-left displaying.
6495  * Only works for single-byte characters (e.g., numbers).
6496  */
6497     void
6498 rl_mirror(char_u *str)
6499 {
6500     char_u	*p1, *p2;
6501     int		t;
6502 
6503     for (p1 = str, p2 = str + STRLEN(str) - 1; p1 < p2; ++p1, --p2)
6504     {
6505 	t = *p1;
6506 	*p1 = *p2;
6507 	*p2 = t;
6508     }
6509 }
6510 #endif
6511 
6512 /*
6513  * mark all status lines for redraw; used after first :cd
6514  */
6515     void
6516 status_redraw_all(void)
6517 {
6518     win_T	*wp;
6519 
6520     FOR_ALL_WINDOWS(wp)
6521 	if (wp->w_status_height)
6522 	{
6523 	    wp->w_redr_status = TRUE;
6524 	    redraw_later(VALID);
6525 	}
6526 }
6527 
6528 /*
6529  * mark all status lines of the current buffer for redraw
6530  */
6531     void
6532 status_redraw_curbuf(void)
6533 {
6534     win_T	*wp;
6535 
6536     FOR_ALL_WINDOWS(wp)
6537 	if (wp->w_status_height != 0 && wp->w_buffer == curbuf)
6538 	{
6539 	    wp->w_redr_status = TRUE;
6540 	    redraw_later(VALID);
6541 	}
6542 }
6543 
6544 /*
6545  * Redraw all status lines that need to be redrawn.
6546  */
6547     void
6548 redraw_statuslines(void)
6549 {
6550     win_T	*wp;
6551 
6552     FOR_ALL_WINDOWS(wp)
6553 	if (wp->w_redr_status)
6554 	    win_redr_status(wp, FALSE);
6555     if (redraw_tabline)
6556 	draw_tabline();
6557 }
6558 
6559 #if defined(FEAT_WILDMENU) || defined(PROTO)
6560 /*
6561  * Redraw all status lines at the bottom of frame "frp".
6562  */
6563     void
6564 win_redraw_last_status(frame_T *frp)
6565 {
6566     if (frp->fr_layout == FR_LEAF)
6567 	frp->fr_win->w_redr_status = TRUE;
6568     else if (frp->fr_layout == FR_ROW)
6569     {
6570 	for (frp = frp->fr_child; frp != NULL; frp = frp->fr_next)
6571 	    win_redraw_last_status(frp);
6572     }
6573     else /* frp->fr_layout == FR_COL */
6574     {
6575 	frp = frp->fr_child;
6576 	while (frp->fr_next != NULL)
6577 	    frp = frp->fr_next;
6578 	win_redraw_last_status(frp);
6579     }
6580 }
6581 #endif
6582 
6583 /*
6584  * Draw the verticap separator right of window "wp" starting with line "row".
6585  */
6586     static void
6587 draw_vsep_win(win_T *wp, int row)
6588 {
6589     int		hl;
6590     int		c;
6591 
6592     if (wp->w_vsep_width)
6593     {
6594 	/* draw the vertical separator right of this window */
6595 	c = fillchar_vsep(&hl);
6596 	screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + wp->w_height,
6597 		W_ENDCOL(wp), W_ENDCOL(wp) + 1,
6598 		c, ' ', hl);
6599     }
6600 }
6601 
6602 #ifdef FEAT_WILDMENU
6603 static int status_match_len(expand_T *xp, char_u *s);
6604 static int skip_status_match_char(expand_T *xp, char_u *s);
6605 
6606 /*
6607  * Get the length of an item as it will be shown in the status line.
6608  */
6609     static int
6610 status_match_len(expand_T *xp, char_u *s)
6611 {
6612     int	len = 0;
6613 
6614 #ifdef FEAT_MENU
6615     int emenu = (xp->xp_context == EXPAND_MENUS
6616 	    || xp->xp_context == EXPAND_MENUNAMES);
6617 
6618     /* Check for menu separators - replace with '|'. */
6619     if (emenu && menu_is_separator(s))
6620 	return 1;
6621 #endif
6622 
6623     while (*s != NUL)
6624     {
6625 	s += skip_status_match_char(xp, s);
6626 	len += ptr2cells(s);
6627 	MB_PTR_ADV(s);
6628     }
6629 
6630     return len;
6631 }
6632 
6633 /*
6634  * Return the number of characters that should be skipped in a status match.
6635  * These are backslashes used for escaping.  Do show backslashes in help tags.
6636  */
6637     static int
6638 skip_status_match_char(expand_T *xp, char_u *s)
6639 {
6640     if ((rem_backslash(s) && xp->xp_context != EXPAND_HELP)
6641 #ifdef FEAT_MENU
6642 	    || ((xp->xp_context == EXPAND_MENUS
6643 		    || xp->xp_context == EXPAND_MENUNAMES)
6644 			  && (s[0] == '\t' || (s[0] == '\\' && s[1] != NUL)))
6645 #endif
6646 	   )
6647     {
6648 #ifndef BACKSLASH_IN_FILENAME
6649 	if (xp->xp_shell && csh_like_shell() && s[1] == '\\' && s[2] == '!')
6650 	    return 2;
6651 #endif
6652 	return 1;
6653     }
6654     return 0;
6655 }
6656 
6657 /*
6658  * Show wildchar matches in the status line.
6659  * Show at least the "match" item.
6660  * We start at item 'first_match' in the list and show all matches that fit.
6661  *
6662  * If inversion is possible we use it. Else '=' characters are used.
6663  */
6664     void
6665 win_redr_status_matches(
6666     expand_T	*xp,
6667     int		num_matches,
6668     char_u	**matches,	/* list of matches */
6669     int		match,
6670     int		showtail)
6671 {
6672 #define L_MATCH(m) (showtail ? sm_gettail(matches[m]) : matches[m])
6673     int		row;
6674     char_u	*buf;
6675     int		len;
6676     int		clen;		/* length in screen cells */
6677     int		fillchar;
6678     int		attr;
6679     int		i;
6680     int		highlight = TRUE;
6681     char_u	*selstart = NULL;
6682     int		selstart_col = 0;
6683     char_u	*selend = NULL;
6684     static int	first_match = 0;
6685     int		add_left = FALSE;
6686     char_u	*s;
6687 #ifdef FEAT_MENU
6688     int		emenu;
6689 #endif
6690 #if defined(FEAT_MBYTE) || defined(FEAT_MENU)
6691     int		l;
6692 #endif
6693 
6694     if (matches == NULL)	/* interrupted completion? */
6695 	return;
6696 
6697 #ifdef FEAT_MBYTE
6698     if (has_mbyte)
6699 	buf = alloc((unsigned)Columns * MB_MAXBYTES + 1);
6700     else
6701 #endif
6702 	buf = alloc((unsigned)Columns + 1);
6703     if (buf == NULL)
6704 	return;
6705 
6706     if (match == -1)	/* don't show match but original text */
6707     {
6708 	match = 0;
6709 	highlight = FALSE;
6710     }
6711     /* count 1 for the ending ">" */
6712     clen = status_match_len(xp, L_MATCH(match)) + 3;
6713     if (match == 0)
6714 	first_match = 0;
6715     else if (match < first_match)
6716     {
6717 	/* jumping left, as far as we can go */
6718 	first_match = match;
6719 	add_left = TRUE;
6720     }
6721     else
6722     {
6723 	/* check if match fits on the screen */
6724 	for (i = first_match; i < match; ++i)
6725 	    clen += status_match_len(xp, L_MATCH(i)) + 2;
6726 	if (first_match > 0)
6727 	    clen += 2;
6728 	/* jumping right, put match at the left */
6729 	if ((long)clen > Columns)
6730 	{
6731 	    first_match = match;
6732 	    /* if showing the last match, we can add some on the left */
6733 	    clen = 2;
6734 	    for (i = match; i < num_matches; ++i)
6735 	    {
6736 		clen += status_match_len(xp, L_MATCH(i)) + 2;
6737 		if ((long)clen >= Columns)
6738 		    break;
6739 	    }
6740 	    if (i == num_matches)
6741 		add_left = TRUE;
6742 	}
6743     }
6744     if (add_left)
6745 	while (first_match > 0)
6746 	{
6747 	    clen += status_match_len(xp, L_MATCH(first_match - 1)) + 2;
6748 	    if ((long)clen >= Columns)
6749 		break;
6750 	    --first_match;
6751 	}
6752 
6753     fillchar = fillchar_status(&attr, curwin);
6754 
6755     if (first_match == 0)
6756     {
6757 	*buf = NUL;
6758 	len = 0;
6759     }
6760     else
6761     {
6762 	STRCPY(buf, "< ");
6763 	len = 2;
6764     }
6765     clen = len;
6766 
6767     i = first_match;
6768     while ((long)(clen + status_match_len(xp, L_MATCH(i)) + 2) < Columns)
6769     {
6770 	if (i == match)
6771 	{
6772 	    selstart = buf + len;
6773 	    selstart_col = clen;
6774 	}
6775 
6776 	s = L_MATCH(i);
6777 	/* Check for menu separators - replace with '|' */
6778 #ifdef FEAT_MENU
6779 	emenu = (xp->xp_context == EXPAND_MENUS
6780 		|| xp->xp_context == EXPAND_MENUNAMES);
6781 	if (emenu && menu_is_separator(s))
6782 	{
6783 	    STRCPY(buf + len, transchar('|'));
6784 	    l = (int)STRLEN(buf + len);
6785 	    len += l;
6786 	    clen += l;
6787 	}
6788 	else
6789 #endif
6790 	    for ( ; *s != NUL; ++s)
6791 	{
6792 	    s += skip_status_match_char(xp, s);
6793 	    clen += ptr2cells(s);
6794 #ifdef FEAT_MBYTE
6795 	    if (has_mbyte && (l = (*mb_ptr2len)(s)) > 1)
6796 	    {
6797 		STRNCPY(buf + len, s, l);
6798 		s += l - 1;
6799 		len += l;
6800 	    }
6801 	    else
6802 #endif
6803 	    {
6804 		STRCPY(buf + len, transchar_byte(*s));
6805 		len += (int)STRLEN(buf + len);
6806 	    }
6807 	}
6808 	if (i == match)
6809 	    selend = buf + len;
6810 
6811 	*(buf + len++) = ' ';
6812 	*(buf + len++) = ' ';
6813 	clen += 2;
6814 	if (++i == num_matches)
6815 		break;
6816     }
6817 
6818     if (i != num_matches)
6819     {
6820 	*(buf + len++) = '>';
6821 	++clen;
6822     }
6823 
6824     buf[len] = NUL;
6825 
6826     row = cmdline_row - 1;
6827     if (row >= 0)
6828     {
6829 	if (wild_menu_showing == 0)
6830 	{
6831 	    if (msg_scrolled > 0)
6832 	    {
6833 		/* Put the wildmenu just above the command line.  If there is
6834 		 * no room, scroll the screen one line up. */
6835 		if (cmdline_row == Rows - 1)
6836 		{
6837 		    screen_del_lines(0, 0, 1, (int)Rows, TRUE, 0, NULL);
6838 		    ++msg_scrolled;
6839 		}
6840 		else
6841 		{
6842 		    ++cmdline_row;
6843 		    ++row;
6844 		}
6845 		wild_menu_showing = WM_SCROLLED;
6846 	    }
6847 	    else
6848 	    {
6849 		/* Create status line if needed by setting 'laststatus' to 2.
6850 		 * Set 'winminheight' to zero to avoid that the window is
6851 		 * resized. */
6852 		if (lastwin->w_status_height == 0)
6853 		{
6854 		    save_p_ls = p_ls;
6855 		    save_p_wmh = p_wmh;
6856 		    p_ls = 2;
6857 		    p_wmh = 0;
6858 		    last_status(FALSE);
6859 		}
6860 		wild_menu_showing = WM_SHOWN;
6861 	    }
6862 	}
6863 
6864 	screen_puts(buf, row, 0, attr);
6865 	if (selstart != NULL && highlight)
6866 	{
6867 	    *selend = NUL;
6868 	    screen_puts(selstart, row, selstart_col, HL_ATTR(HLF_WM));
6869 	}
6870 
6871 	screen_fill(row, row + 1, clen, (int)Columns, fillchar, fillchar, attr);
6872     }
6873 
6874     win_redraw_last_status(topframe);
6875     vim_free(buf);
6876 }
6877 #endif
6878 
6879 /*
6880  * Redraw the status line of window wp.
6881  *
6882  * If inversion is possible we use it. Else '=' characters are used.
6883  * If "ignore_pum" is TRUE, also redraw statusline when the popup menu is
6884  * displayed.
6885  */
6886     static void
6887 win_redr_status(win_T *wp, int ignore_pum UNUSED)
6888 {
6889     int		row;
6890     char_u	*p;
6891     int		len;
6892     int		fillchar;
6893     int		attr;
6894     int		this_ru_col;
6895     static int  busy = FALSE;
6896 
6897     /* It's possible to get here recursively when 'statusline' (indirectly)
6898      * invokes ":redrawstatus".  Simply ignore the call then. */
6899     if (busy)
6900 	return;
6901     busy = TRUE;
6902 
6903     wp->w_redr_status = FALSE;
6904     if (wp->w_status_height == 0)
6905     {
6906 	/* no status line, can only be last window */
6907 	redraw_cmdline = TRUE;
6908     }
6909     else if (!redrawing()
6910 #ifdef FEAT_INS_EXPAND
6911 	    // don't update status line when popup menu is visible and may be
6912 	    // drawn over it, unless it will be redrawn later
6913 	    || (!ignore_pum && pum_visible())
6914 #endif
6915 	    )
6916     {
6917 	/* Don't redraw right now, do it later. */
6918 	wp->w_redr_status = TRUE;
6919     }
6920 #ifdef FEAT_STL_OPT
6921     else if (*p_stl != NUL || *wp->w_p_stl != NUL)
6922     {
6923 	/* redraw custom status line */
6924 	redraw_custom_statusline(wp);
6925     }
6926 #endif
6927     else
6928     {
6929 	fillchar = fillchar_status(&attr, wp);
6930 
6931 	get_trans_bufname(wp->w_buffer);
6932 	p = NameBuff;
6933 	len = (int)STRLEN(p);
6934 
6935 	if (bt_help(wp->w_buffer)
6936 #ifdef FEAT_QUICKFIX
6937 		|| wp->w_p_pvw
6938 #endif
6939 		|| bufIsChanged(wp->w_buffer)
6940 		|| wp->w_buffer->b_p_ro)
6941 	    *(p + len++) = ' ';
6942 	if (bt_help(wp->w_buffer))
6943 	{
6944 	    STRCPY(p + len, _("[Help]"));
6945 	    len += (int)STRLEN(p + len);
6946 	}
6947 #ifdef FEAT_QUICKFIX
6948 	if (wp->w_p_pvw)
6949 	{
6950 	    STRCPY(p + len, _("[Preview]"));
6951 	    len += (int)STRLEN(p + len);
6952 	}
6953 #endif
6954 	if (bufIsChanged(wp->w_buffer)
6955 #ifdef FEAT_TERMINAL
6956 		&& !bt_terminal(wp->w_buffer)
6957 #endif
6958 		)
6959 	{
6960 	    STRCPY(p + len, "[+]");
6961 	    len += 3;
6962 	}
6963 	if (wp->w_buffer->b_p_ro)
6964 	{
6965 	    STRCPY(p + len, _("[RO]"));
6966 	    len += (int)STRLEN(p + len);
6967 	}
6968 
6969 	this_ru_col = ru_col - (Columns - wp->w_width);
6970 	if (this_ru_col < (wp->w_width + 1) / 2)
6971 	    this_ru_col = (wp->w_width + 1) / 2;
6972 	if (this_ru_col <= 1)
6973 	{
6974 	    p = (char_u *)"<";		/* No room for file name! */
6975 	    len = 1;
6976 	}
6977 	else
6978 #ifdef FEAT_MBYTE
6979 	    if (has_mbyte)
6980 	    {
6981 		int	clen = 0, i;
6982 
6983 		/* Count total number of display cells. */
6984 		clen = mb_string2cells(p, -1);
6985 
6986 		/* Find first character that will fit.
6987 		 * Going from start to end is much faster for DBCS. */
6988 		for (i = 0; p[i] != NUL && clen >= this_ru_col - 1;
6989 					      i += (*mb_ptr2len)(p + i))
6990 		    clen -= (*mb_ptr2cells)(p + i);
6991 		len = clen;
6992 		if (i > 0)
6993 		{
6994 		    p = p + i - 1;
6995 		    *p = '<';
6996 		    ++len;
6997 		}
6998 
6999 	    }
7000 	    else
7001 #endif
7002 	    if (len > this_ru_col - 1)
7003 	    {
7004 		p += len - (this_ru_col - 1);
7005 		*p = '<';
7006 		len = this_ru_col - 1;
7007 	    }
7008 
7009 	row = W_WINROW(wp) + wp->w_height;
7010 	screen_puts(p, row, wp->w_wincol, attr);
7011 	screen_fill(row, row + 1, len + wp->w_wincol,
7012 			this_ru_col + wp->w_wincol, fillchar, fillchar, attr);
7013 
7014 	if (get_keymap_str(wp, (char_u *)"<%s>", NameBuff, MAXPATHL)
7015 		&& (int)(this_ru_col - len) > (int)(STRLEN(NameBuff) + 1))
7016 	    screen_puts(NameBuff, row, (int)(this_ru_col - STRLEN(NameBuff)
7017 						   - 1 + wp->w_wincol), attr);
7018 
7019 #ifdef FEAT_CMDL_INFO
7020 	win_redr_ruler(wp, TRUE, ignore_pum);
7021 #endif
7022     }
7023 
7024     /*
7025      * May need to draw the character below the vertical separator.
7026      */
7027     if (wp->w_vsep_width != 0 && wp->w_status_height != 0 && redrawing())
7028     {
7029 	if (stl_connected(wp))
7030 	    fillchar = fillchar_status(&attr, wp);
7031 	else
7032 	    fillchar = fillchar_vsep(&attr);
7033 	screen_putchar(fillchar, W_WINROW(wp) + wp->w_height, W_ENDCOL(wp),
7034 									attr);
7035     }
7036     busy = FALSE;
7037 }
7038 
7039 #ifdef FEAT_STL_OPT
7040 /*
7041  * Redraw the status line according to 'statusline' and take care of any
7042  * errors encountered.
7043  */
7044     static void
7045 redraw_custom_statusline(win_T *wp)
7046 {
7047     static int	    entered = FALSE;
7048     int		    saved_did_emsg = did_emsg;
7049 
7050     /* When called recursively return.  This can happen when the statusline
7051      * contains an expression that triggers a redraw. */
7052     if (entered)
7053 	return;
7054     entered = TRUE;
7055 
7056     did_emsg = FALSE;
7057     win_redr_custom(wp, FALSE);
7058     if (did_emsg)
7059     {
7060 	/* When there is an error disable the statusline, otherwise the
7061 	 * display is messed up with errors and a redraw triggers the problem
7062 	 * again and again. */
7063 	set_string_option_direct((char_u *)"statusline", -1,
7064 		(char_u *)"", OPT_FREE | (*wp->w_p_stl != NUL
7065 					? OPT_LOCAL : OPT_GLOBAL), SID_ERROR);
7066     }
7067     did_emsg |= saved_did_emsg;
7068     entered = FALSE;
7069 }
7070 #endif
7071 
7072 /*
7073  * Return TRUE if the status line of window "wp" is connected to the status
7074  * line of the window right of it.  If not, then it's a vertical separator.
7075  * Only call if (wp->w_vsep_width != 0).
7076  */
7077     int
7078 stl_connected(win_T *wp)
7079 {
7080     frame_T	*fr;
7081 
7082     fr = wp->w_frame;
7083     while (fr->fr_parent != NULL)
7084     {
7085 	if (fr->fr_parent->fr_layout == FR_COL)
7086 	{
7087 	    if (fr->fr_next != NULL)
7088 		break;
7089 	}
7090 	else
7091 	{
7092 	    if (fr->fr_next != NULL)
7093 		return TRUE;
7094 	}
7095 	fr = fr->fr_parent;
7096     }
7097     return FALSE;
7098 }
7099 
7100 
7101 /*
7102  * Get the value to show for the language mappings, active 'keymap'.
7103  */
7104     int
7105 get_keymap_str(
7106     win_T	*wp,
7107     char_u	*fmt,	    /* format string containing one %s item */
7108     char_u	*buf,	    /* buffer for the result */
7109     int		len)	    /* length of buffer */
7110 {
7111     char_u	*p;
7112 
7113     if (wp->w_buffer->b_p_iminsert != B_IMODE_LMAP)
7114 	return FALSE;
7115 
7116     {
7117 #ifdef FEAT_EVAL
7118 	buf_T	*old_curbuf = curbuf;
7119 	win_T	*old_curwin = curwin;
7120 	char_u	*s;
7121 
7122 	curbuf = wp->w_buffer;
7123 	curwin = wp;
7124 	STRCPY(buf, "b:keymap_name");	/* must be writable */
7125 	++emsg_skip;
7126 	s = p = eval_to_string(buf, NULL, FALSE);
7127 	--emsg_skip;
7128 	curbuf = old_curbuf;
7129 	curwin = old_curwin;
7130 	if (p == NULL || *p == NUL)
7131 #endif
7132 	{
7133 #ifdef FEAT_KEYMAP
7134 	    if (wp->w_buffer->b_kmap_state & KEYMAP_LOADED)
7135 		p = wp->w_buffer->b_p_keymap;
7136 	    else
7137 #endif
7138 		p = (char_u *)"lang";
7139 	}
7140 	if (vim_snprintf((char *)buf, len, (char *)fmt, p) > len - 1)
7141 	    buf[0] = NUL;
7142 #ifdef FEAT_EVAL
7143 	vim_free(s);
7144 #endif
7145     }
7146     return buf[0] != NUL;
7147 }
7148 
7149 #if defined(FEAT_STL_OPT) || defined(PROTO)
7150 /*
7151  * Redraw the status line or ruler of window "wp".
7152  * When "wp" is NULL redraw the tab pages line from 'tabline'.
7153  */
7154     static void
7155 win_redr_custom(
7156     win_T	*wp,
7157     int		draw_ruler)	/* TRUE or FALSE */
7158 {
7159     static int	entered = FALSE;
7160     int		attr;
7161     int		curattr;
7162     int		row;
7163     int		col = 0;
7164     int		maxwidth;
7165     int		width;
7166     int		n;
7167     int		len;
7168     int		fillchar;
7169     char_u	buf[MAXPATHL];
7170     char_u	*stl;
7171     char_u	*p;
7172     struct	stl_hlrec hltab[STL_MAX_ITEM];
7173     struct	stl_hlrec tabtab[STL_MAX_ITEM];
7174     int		use_sandbox = FALSE;
7175     win_T	*ewp;
7176     int		p_crb_save;
7177 
7178     /* There is a tiny chance that this gets called recursively: When
7179      * redrawing a status line triggers redrawing the ruler or tabline.
7180      * Avoid trouble by not allowing recursion. */
7181     if (entered)
7182 	return;
7183     entered = TRUE;
7184 
7185     /* setup environment for the task at hand */
7186     if (wp == NULL)
7187     {
7188 	/* Use 'tabline'.  Always at the first line of the screen. */
7189 	stl = p_tal;
7190 	row = 0;
7191 	fillchar = ' ';
7192 	attr = HL_ATTR(HLF_TPF);
7193 	maxwidth = Columns;
7194 # ifdef FEAT_EVAL
7195 	use_sandbox = was_set_insecurely((char_u *)"tabline", 0);
7196 # endif
7197     }
7198     else
7199     {
7200 	row = W_WINROW(wp) + wp->w_height;
7201 	fillchar = fillchar_status(&attr, wp);
7202 	maxwidth = wp->w_width;
7203 
7204 	if (draw_ruler)
7205 	{
7206 	    stl = p_ruf;
7207 	    /* advance past any leading group spec - implicit in ru_col */
7208 	    if (*stl == '%')
7209 	    {
7210 		if (*++stl == '-')
7211 		    stl++;
7212 		if (atoi((char *)stl))
7213 		    while (VIM_ISDIGIT(*stl))
7214 			stl++;
7215 		if (*stl++ != '(')
7216 		    stl = p_ruf;
7217 	    }
7218 	    col = ru_col - (Columns - wp->w_width);
7219 	    if (col < (wp->w_width + 1) / 2)
7220 		col = (wp->w_width + 1) / 2;
7221 	    maxwidth = wp->w_width - col;
7222 	    if (!wp->w_status_height)
7223 	    {
7224 		row = Rows - 1;
7225 		--maxwidth;	/* writing in last column may cause scrolling */
7226 		fillchar = ' ';
7227 		attr = 0;
7228 	    }
7229 
7230 # ifdef FEAT_EVAL
7231 	    use_sandbox = was_set_insecurely((char_u *)"rulerformat", 0);
7232 # endif
7233 	}
7234 	else
7235 	{
7236 	    if (*wp->w_p_stl != NUL)
7237 		stl = wp->w_p_stl;
7238 	    else
7239 		stl = p_stl;
7240 # ifdef FEAT_EVAL
7241 	    use_sandbox = was_set_insecurely((char_u *)"statusline",
7242 					 *wp->w_p_stl == NUL ? 0 : OPT_LOCAL);
7243 # endif
7244 	}
7245 
7246 	col += wp->w_wincol;
7247     }
7248 
7249     if (maxwidth <= 0)
7250 	goto theend;
7251 
7252     /* Temporarily reset 'cursorbind', we don't want a side effect from moving
7253      * the cursor away and back. */
7254     ewp = wp == NULL ? curwin : wp;
7255     p_crb_save = ewp->w_p_crb;
7256     ewp->w_p_crb = FALSE;
7257 
7258     /* Make a copy, because the statusline may include a function call that
7259      * might change the option value and free the memory. */
7260     stl = vim_strsave(stl);
7261     width = build_stl_str_hl(ewp, buf, sizeof(buf),
7262 				stl, use_sandbox,
7263 				fillchar, maxwidth, hltab, tabtab);
7264     vim_free(stl);
7265     ewp->w_p_crb = p_crb_save;
7266 
7267     /* Make all characters printable. */
7268     p = transstr(buf);
7269     if (p != NULL)
7270     {
7271 	vim_strncpy(buf, p, sizeof(buf) - 1);
7272 	vim_free(p);
7273     }
7274 
7275     /* fill up with "fillchar" */
7276     len = (int)STRLEN(buf);
7277     while (width < maxwidth && len < (int)sizeof(buf) - 1)
7278     {
7279 #ifdef FEAT_MBYTE
7280 	len += (*mb_char2bytes)(fillchar, buf + len);
7281 #else
7282 	buf[len++] = fillchar;
7283 #endif
7284 	++width;
7285     }
7286     buf[len] = NUL;
7287 
7288     /*
7289      * Draw each snippet with the specified highlighting.
7290      */
7291     curattr = attr;
7292     p = buf;
7293     for (n = 0; hltab[n].start != NULL; n++)
7294     {
7295 	len = (int)(hltab[n].start - p);
7296 	screen_puts_len(p, len, row, col, curattr);
7297 	col += vim_strnsize(p, len);
7298 	p = hltab[n].start;
7299 
7300 	if (hltab[n].userhl == 0)
7301 	    curattr = attr;
7302 	else if (hltab[n].userhl < 0)
7303 	    curattr = syn_id2attr(-hltab[n].userhl);
7304 #ifdef FEAT_TERMINAL
7305 	else if (wp != NULL && wp != curwin && bt_terminal(wp->w_buffer)
7306 						   && wp->w_status_height != 0)
7307 	    curattr = highlight_stltermnc[hltab[n].userhl - 1];
7308 	else if (wp != NULL && bt_terminal(wp->w_buffer)
7309 						   && wp->w_status_height != 0)
7310 	    curattr = highlight_stlterm[hltab[n].userhl - 1];
7311 #endif
7312 	else if (wp != NULL && wp != curwin && wp->w_status_height != 0)
7313 	    curattr = highlight_stlnc[hltab[n].userhl - 1];
7314 	else
7315 	    curattr = highlight_user[hltab[n].userhl - 1];
7316     }
7317     screen_puts(p, row, col, curattr);
7318 
7319     if (wp == NULL)
7320     {
7321 	/* Fill the TabPageIdxs[] array for clicking in the tab pagesline. */
7322 	col = 0;
7323 	len = 0;
7324 	p = buf;
7325 	fillchar = 0;
7326 	for (n = 0; tabtab[n].start != NULL; n++)
7327 	{
7328 	    len += vim_strnsize(p, (int)(tabtab[n].start - p));
7329 	    while (col < len)
7330 		TabPageIdxs[col++] = fillchar;
7331 	    p = tabtab[n].start;
7332 	    fillchar = tabtab[n].userhl;
7333 	}
7334 	while (col < Columns)
7335 	    TabPageIdxs[col++] = fillchar;
7336     }
7337 
7338 theend:
7339     entered = FALSE;
7340 }
7341 
7342 #endif /* FEAT_STL_OPT */
7343 
7344 /*
7345  * Output a single character directly to the screen and update ScreenLines.
7346  */
7347     void
7348 screen_putchar(int c, int row, int col, int attr)
7349 {
7350     char_u	buf[MB_MAXBYTES + 1];
7351 
7352 #ifdef FEAT_MBYTE
7353     if (has_mbyte)
7354 	buf[(*mb_char2bytes)(c, buf)] = NUL;
7355     else
7356 #endif
7357     {
7358 	buf[0] = c;
7359 	buf[1] = NUL;
7360     }
7361     screen_puts(buf, row, col, attr);
7362 }
7363 
7364 /*
7365  * Get a single character directly from ScreenLines into "bytes[]".
7366  * Also return its attribute in *attrp;
7367  */
7368     void
7369 screen_getbytes(int row, int col, char_u *bytes, int *attrp)
7370 {
7371     unsigned off;
7372 
7373     /* safety check */
7374     if (ScreenLines != NULL && row < screen_Rows && col < screen_Columns)
7375     {
7376 	off = LineOffset[row] + col;
7377 	*attrp = ScreenAttrs[off];
7378 	bytes[0] = ScreenLines[off];
7379 	bytes[1] = NUL;
7380 
7381 #ifdef FEAT_MBYTE
7382 	if (enc_utf8 && ScreenLinesUC[off] != 0)
7383 	    bytes[utfc_char2bytes(off, bytes)] = NUL;
7384 	else if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
7385 	{
7386 	    bytes[0] = ScreenLines[off];
7387 	    bytes[1] = ScreenLines2[off];
7388 	    bytes[2] = NUL;
7389 	}
7390 	else if (enc_dbcs && MB_BYTE2LEN(bytes[0]) > 1)
7391 	{
7392 	    bytes[1] = ScreenLines[off + 1];
7393 	    bytes[2] = NUL;
7394 	}
7395 #endif
7396     }
7397 }
7398 
7399 #ifdef FEAT_MBYTE
7400 static int screen_comp_differs(int, int*);
7401 
7402 /*
7403  * Return TRUE if composing characters for screen posn "off" differs from
7404  * composing characters in "u8cc".
7405  * Only to be used when ScreenLinesUC[off] != 0.
7406  */
7407     static int
7408 screen_comp_differs(int off, int *u8cc)
7409 {
7410     int	    i;
7411 
7412     for (i = 0; i < Screen_mco; ++i)
7413     {
7414 	if (ScreenLinesC[i][off] != (u8char_T)u8cc[i])
7415 	    return TRUE;
7416 	if (u8cc[i] == 0)
7417 	    break;
7418     }
7419     return FALSE;
7420 }
7421 #endif
7422 
7423 /*
7424  * Put string '*text' on the screen at position 'row' and 'col', with
7425  * attributes 'attr', and update ScreenLines[] and ScreenAttrs[].
7426  * Note: only outputs within one row, message is truncated at screen boundary!
7427  * Note: if ScreenLines[], row and/or col is invalid, nothing is done.
7428  */
7429     void
7430 screen_puts(
7431     char_u	*text,
7432     int		row,
7433     int		col,
7434     int		attr)
7435 {
7436     screen_puts_len(text, -1, row, col, attr);
7437 }
7438 
7439 /*
7440  * Like screen_puts(), but output "text[len]".  When "len" is -1 output up to
7441  * a NUL.
7442  */
7443     void
7444 screen_puts_len(
7445     char_u	*text,
7446     int		textlen,
7447     int		row,
7448     int		col,
7449     int		attr)
7450 {
7451     unsigned	off;
7452     char_u	*ptr = text;
7453     int		len = textlen;
7454     int		c;
7455 #ifdef FEAT_MBYTE
7456     unsigned	max_off;
7457     int		mbyte_blen = 1;
7458     int		mbyte_cells = 1;
7459     int		u8c = 0;
7460     int		u8cc[MAX_MCO];
7461     int		clear_next_cell = FALSE;
7462 # ifdef FEAT_ARABIC
7463     int		prev_c = 0;		/* previous Arabic character */
7464     int		pc, nc, nc1;
7465     int		pcc[MAX_MCO];
7466 # endif
7467 #endif
7468 #if defined(FEAT_MBYTE) || defined(FEAT_GUI) || defined(UNIX)
7469     int		force_redraw_this;
7470     int		force_redraw_next = FALSE;
7471 #endif
7472     int		need_redraw;
7473 
7474     if (ScreenLines == NULL || row >= screen_Rows)	/* safety check */
7475 	return;
7476     off = LineOffset[row] + col;
7477 
7478 #ifdef FEAT_MBYTE
7479     /* When drawing over the right halve of a double-wide char clear out the
7480      * left halve.  Only needed in a terminal. */
7481     if (has_mbyte && col > 0 && col < screen_Columns
7482 # ifdef FEAT_GUI
7483 	    && !gui.in_use
7484 # endif
7485 	    && mb_fix_col(col, row) != col)
7486     {
7487 	ScreenLines[off - 1] = ' ';
7488 	ScreenAttrs[off - 1] = 0;
7489 	if (enc_utf8)
7490 	{
7491 	    ScreenLinesUC[off - 1] = 0;
7492 	    ScreenLinesC[0][off - 1] = 0;
7493 	}
7494 	/* redraw the previous cell, make it empty */
7495 	screen_char(off - 1, row, col - 1);
7496 	/* force the cell at "col" to be redrawn */
7497 	force_redraw_next = TRUE;
7498     }
7499 #endif
7500 
7501 #ifdef FEAT_MBYTE
7502     max_off = LineOffset[row] + screen_Columns;
7503 #endif
7504     while (col < screen_Columns
7505 	    && (len < 0 || (int)(ptr - text) < len)
7506 	    && *ptr != NUL)
7507     {
7508 	c = *ptr;
7509 #ifdef FEAT_MBYTE
7510 	/* check if this is the first byte of a multibyte */
7511 	if (has_mbyte)
7512 	{
7513 	    if (enc_utf8 && len > 0)
7514 		mbyte_blen = utfc_ptr2len_len(ptr, (int)((text + len) - ptr));
7515 	    else
7516 		mbyte_blen = (*mb_ptr2len)(ptr);
7517 	    if (enc_dbcs == DBCS_JPNU && c == 0x8e)
7518 		mbyte_cells = 1;
7519 	    else if (enc_dbcs != 0)
7520 		mbyte_cells = mbyte_blen;
7521 	    else	/* enc_utf8 */
7522 	    {
7523 		if (len >= 0)
7524 		    u8c = utfc_ptr2char_len(ptr, u8cc,
7525 						   (int)((text + len) - ptr));
7526 		else
7527 		    u8c = utfc_ptr2char(ptr, u8cc);
7528 		mbyte_cells = utf_char2cells(u8c);
7529 # ifdef UNICODE16
7530 		/* Non-BMP character: display as ? or fullwidth ?. */
7531 		if (u8c >= 0x10000)
7532 		{
7533 		    u8c = (mbyte_cells == 2) ? 0xff1f : (int)'?';
7534 		    if (attr == 0)
7535 			attr = HL_ATTR(HLF_8);
7536 		}
7537 # endif
7538 # ifdef FEAT_ARABIC
7539 		if (p_arshape && !p_tbidi && ARABIC_CHAR(u8c))
7540 		{
7541 		    /* Do Arabic shaping. */
7542 		    if (len >= 0 && (int)(ptr - text) + mbyte_blen >= len)
7543 		    {
7544 			/* Past end of string to be displayed. */
7545 			nc = NUL;
7546 			nc1 = NUL;
7547 		    }
7548 		    else
7549 		    {
7550 			nc = utfc_ptr2char_len(ptr + mbyte_blen, pcc,
7551 				      (int)((text + len) - ptr - mbyte_blen));
7552 			nc1 = pcc[0];
7553 		    }
7554 		    pc = prev_c;
7555 		    prev_c = u8c;
7556 		    u8c = arabic_shape(u8c, &c, &u8cc[0], nc, nc1, pc);
7557 		}
7558 		else
7559 		    prev_c = u8c;
7560 # endif
7561 		if (col + mbyte_cells > screen_Columns)
7562 		{
7563 		    /* Only 1 cell left, but character requires 2 cells:
7564 		     * display a '>' in the last column to avoid wrapping. */
7565 		    c = '>';
7566 		    mbyte_cells = 1;
7567 		}
7568 	    }
7569 	}
7570 #endif
7571 
7572 #if defined(FEAT_MBYTE) || defined(FEAT_GUI) || defined(UNIX)
7573 	force_redraw_this = force_redraw_next;
7574 	force_redraw_next = FALSE;
7575 #endif
7576 
7577 	need_redraw = ScreenLines[off] != c
7578 #ifdef FEAT_MBYTE
7579 		|| (mbyte_cells == 2
7580 		    && ScreenLines[off + 1] != (enc_dbcs ? ptr[1] : 0))
7581 		|| (enc_dbcs == DBCS_JPNU
7582 		    && c == 0x8e
7583 		    && ScreenLines2[off] != ptr[1])
7584 		|| (enc_utf8
7585 		    && (ScreenLinesUC[off] !=
7586 				(u8char_T)(c < 0x80 && u8cc[0] == 0 ? 0 : u8c)
7587 			|| (ScreenLinesUC[off] != 0
7588 					  && screen_comp_differs(off, u8cc))))
7589 #endif
7590 		|| ScreenAttrs[off] != attr
7591 		|| exmode_active;
7592 
7593 	if (need_redraw
7594 #if defined(FEAT_MBYTE) || defined(FEAT_GUI) || defined(UNIX)
7595 		|| force_redraw_this
7596 #endif
7597 		)
7598 	{
7599 #if defined(FEAT_GUI) || defined(UNIX)
7600 	    /* The bold trick makes a single row of pixels appear in the next
7601 	     * character.  When a bold character is removed, the next
7602 	     * character should be redrawn too.  This happens for our own GUI
7603 	     * and for some xterms. */
7604 	    if (need_redraw && ScreenLines[off] != ' ' && (
7605 # ifdef FEAT_GUI
7606 		    gui.in_use
7607 # endif
7608 # if defined(FEAT_GUI) && defined(UNIX)
7609 		    ||
7610 # endif
7611 # ifdef UNIX
7612 		    term_is_xterm
7613 # endif
7614 		    ))
7615 	    {
7616 		int	n = ScreenAttrs[off];
7617 
7618 		if (n > HL_ALL)
7619 		    n = syn_attr2attr(n);
7620 		if (n & HL_BOLD)
7621 		    force_redraw_next = TRUE;
7622 	    }
7623 #endif
7624 #ifdef FEAT_MBYTE
7625 	    /* When at the end of the text and overwriting a two-cell
7626 	     * character with a one-cell character, need to clear the next
7627 	     * cell.  Also when overwriting the left halve of a two-cell char
7628 	     * with the right halve of a two-cell char.  Do this only once
7629 	     * (mb_off2cells() may return 2 on the right halve). */
7630 	    if (clear_next_cell)
7631 		clear_next_cell = FALSE;
7632 	    else if (has_mbyte
7633 		    && (len < 0 ? ptr[mbyte_blen] == NUL
7634 					     : ptr + mbyte_blen >= text + len)
7635 		    && ((mbyte_cells == 1 && (*mb_off2cells)(off, max_off) > 1)
7636 			|| (mbyte_cells == 2
7637 			    && (*mb_off2cells)(off, max_off) == 1
7638 			    && (*mb_off2cells)(off + 1, max_off) > 1)))
7639 		clear_next_cell = TRUE;
7640 
7641 	    /* Make sure we never leave a second byte of a double-byte behind,
7642 	     * it confuses mb_off2cells(). */
7643 	    if (enc_dbcs
7644 		    && ((mbyte_cells == 1 && (*mb_off2cells)(off, max_off) > 1)
7645 			|| (mbyte_cells == 2
7646 			    && (*mb_off2cells)(off, max_off) == 1
7647 			    && (*mb_off2cells)(off + 1, max_off) > 1)))
7648 		ScreenLines[off + mbyte_blen] = 0;
7649 #endif
7650 	    ScreenLines[off] = c;
7651 	    ScreenAttrs[off] = attr;
7652 #ifdef FEAT_MBYTE
7653 	    if (enc_utf8)
7654 	    {
7655 		if (c < 0x80 && u8cc[0] == 0)
7656 		    ScreenLinesUC[off] = 0;
7657 		else
7658 		{
7659 		    int	    i;
7660 
7661 		    ScreenLinesUC[off] = u8c;
7662 		    for (i = 0; i < Screen_mco; ++i)
7663 		    {
7664 			ScreenLinesC[i][off] = u8cc[i];
7665 			if (u8cc[i] == 0)
7666 			    break;
7667 		    }
7668 		}
7669 		if (mbyte_cells == 2)
7670 		{
7671 		    ScreenLines[off + 1] = 0;
7672 		    ScreenAttrs[off + 1] = attr;
7673 		}
7674 		screen_char(off, row, col);
7675 	    }
7676 	    else if (mbyte_cells == 2)
7677 	    {
7678 		ScreenLines[off + 1] = ptr[1];
7679 		ScreenAttrs[off + 1] = attr;
7680 		screen_char_2(off, row, col);
7681 	    }
7682 	    else if (enc_dbcs == DBCS_JPNU && c == 0x8e)
7683 	    {
7684 		ScreenLines2[off] = ptr[1];
7685 		screen_char(off, row, col);
7686 	    }
7687 	    else
7688 #endif
7689 		screen_char(off, row, col);
7690 	}
7691 #ifdef FEAT_MBYTE
7692 	if (has_mbyte)
7693 	{
7694 	    off += mbyte_cells;
7695 	    col += mbyte_cells;
7696 	    ptr += mbyte_blen;
7697 	    if (clear_next_cell)
7698 	    {
7699 		/* This only happens at the end, display one space next. */
7700 		ptr = (char_u *)" ";
7701 		len = -1;
7702 	    }
7703 	}
7704 	else
7705 #endif
7706 	{
7707 	    ++off;
7708 	    ++col;
7709 	    ++ptr;
7710 	}
7711     }
7712 
7713 #if defined(FEAT_MBYTE) || defined(FEAT_GUI) || defined(UNIX)
7714     /* If we detected the next character needs to be redrawn, but the text
7715      * doesn't extend up to there, update the character here. */
7716     if (force_redraw_next && col < screen_Columns)
7717     {
7718 # ifdef FEAT_MBYTE
7719 	if (enc_dbcs != 0 && dbcs_off2cells(off, max_off) > 1)
7720 	    screen_char_2(off, row, col);
7721 	else
7722 # endif
7723 	    screen_char(off, row, col);
7724     }
7725 #endif
7726 }
7727 
7728 #ifdef FEAT_SEARCH_EXTRA
7729 /*
7730  * Prepare for 'hlsearch' highlighting.
7731  */
7732     static void
7733 start_search_hl(void)
7734 {
7735     if (p_hls && !no_hlsearch)
7736     {
7737 	last_pat_prog(&search_hl.rm);
7738 	search_hl.attr = HL_ATTR(HLF_L);
7739 # ifdef FEAT_RELTIME
7740 	/* Set the time limit to 'redrawtime'. */
7741 	profile_setlimit(p_rdt, &search_hl.tm);
7742 # endif
7743     }
7744 }
7745 
7746 /*
7747  * Clean up for 'hlsearch' highlighting.
7748  */
7749     static void
7750 end_search_hl(void)
7751 {
7752     if (search_hl.rm.regprog != NULL)
7753     {
7754 	vim_regfree(search_hl.rm.regprog);
7755 	search_hl.rm.regprog = NULL;
7756     }
7757 }
7758 
7759 /*
7760  * Init for calling prepare_search_hl().
7761  */
7762     static void
7763 init_search_hl(win_T *wp)
7764 {
7765     matchitem_T *cur;
7766 
7767     /* Setup for match and 'hlsearch' highlighting.  Disable any previous
7768      * match */
7769     cur = wp->w_match_head;
7770     while (cur != NULL)
7771     {
7772 	cur->hl.rm = cur->match;
7773 	if (cur->hlg_id == 0)
7774 	    cur->hl.attr = 0;
7775 	else
7776 	    cur->hl.attr = syn_id2attr(cur->hlg_id);
7777 	cur->hl.buf = wp->w_buffer;
7778 	cur->hl.lnum = 0;
7779 	cur->hl.first_lnum = 0;
7780 # ifdef FEAT_RELTIME
7781 	/* Set the time limit to 'redrawtime'. */
7782 	profile_setlimit(p_rdt, &(cur->hl.tm));
7783 # endif
7784 	cur = cur->next;
7785     }
7786     search_hl.buf = wp->w_buffer;
7787     search_hl.lnum = 0;
7788     search_hl.first_lnum = 0;
7789     /* time limit is set at the toplevel, for all windows */
7790 }
7791 
7792 /*
7793  * Advance to the match in window "wp" line "lnum" or past it.
7794  */
7795     static void
7796 prepare_search_hl(win_T *wp, linenr_T lnum)
7797 {
7798     matchitem_T *cur;		/* points to the match list */
7799     match_T	*shl;		/* points to search_hl or a match */
7800     int		shl_flag;	/* flag to indicate whether search_hl
7801 				   has been processed or not */
7802     int		pos_inprogress;	/* marks that position match search is
7803 				   in progress */
7804     int		n;
7805 
7806     /*
7807      * When using a multi-line pattern, start searching at the top
7808      * of the window or just after a closed fold.
7809      * Do this both for search_hl and the match list.
7810      */
7811     cur = wp->w_match_head;
7812     shl_flag = FALSE;
7813     while (cur != NULL || shl_flag == FALSE)
7814     {
7815 	if (shl_flag == FALSE)
7816 	{
7817 	    shl = &search_hl;
7818 	    shl_flag = TRUE;
7819 	}
7820 	else
7821 	    shl = &cur->hl;
7822 	if (shl->rm.regprog != NULL
7823 		&& shl->lnum == 0
7824 		&& re_multiline(shl->rm.regprog))
7825 	{
7826 	    if (shl->first_lnum == 0)
7827 	    {
7828 # ifdef FEAT_FOLDING
7829 		for (shl->first_lnum = lnum;
7830 			   shl->first_lnum > wp->w_topline; --shl->first_lnum)
7831 		    if (hasFoldingWin(wp, shl->first_lnum - 1,
7832 						      NULL, NULL, TRUE, NULL))
7833 			break;
7834 # else
7835 		shl->first_lnum = wp->w_topline;
7836 # endif
7837 	    }
7838 	    if (cur != NULL)
7839 		cur->pos.cur = 0;
7840 	    pos_inprogress = TRUE;
7841 	    n = 0;
7842 	    while (shl->first_lnum < lnum && (shl->rm.regprog != NULL
7843 					  || (cur != NULL && pos_inprogress)))
7844 	    {
7845 		next_search_hl(wp, shl, shl->first_lnum, (colnr_T)n,
7846 					       shl == &search_hl ? NULL : cur);
7847 		pos_inprogress = cur == NULL || cur->pos.cur == 0
7848 							      ? FALSE : TRUE;
7849 		if (shl->lnum != 0)
7850 		{
7851 		    shl->first_lnum = shl->lnum
7852 				    + shl->rm.endpos[0].lnum
7853 				    - shl->rm.startpos[0].lnum;
7854 		    n = shl->rm.endpos[0].col;
7855 		}
7856 		else
7857 		{
7858 		    ++shl->first_lnum;
7859 		    n = 0;
7860 		}
7861 	    }
7862 	}
7863 	if (shl != &search_hl && cur != NULL)
7864 	    cur = cur->next;
7865     }
7866 }
7867 
7868 /*
7869  * Search for a next 'hlsearch' or match.
7870  * Uses shl->buf.
7871  * Sets shl->lnum and shl->rm contents.
7872  * Note: Assumes a previous match is always before "lnum", unless
7873  * shl->lnum is zero.
7874  * Careful: Any pointers for buffer lines will become invalid.
7875  */
7876     static void
7877 next_search_hl(
7878     win_T	    *win,
7879     match_T	    *shl,	/* points to search_hl or a match */
7880     linenr_T	    lnum,
7881     colnr_T	    mincol,	/* minimal column for a match */
7882     matchitem_T	    *cur)	/* to retrieve match positions if any */
7883 {
7884     linenr_T	l;
7885     colnr_T	matchcol;
7886     long	nmatched;
7887     int		save_called_emsg = called_emsg;
7888 
7889     if (shl->lnum != 0)
7890     {
7891 	/* Check for three situations:
7892 	 * 1. If the "lnum" is below a previous match, start a new search.
7893 	 * 2. If the previous match includes "mincol", use it.
7894 	 * 3. Continue after the previous match.
7895 	 */
7896 	l = shl->lnum + shl->rm.endpos[0].lnum - shl->rm.startpos[0].lnum;
7897 	if (lnum > l)
7898 	    shl->lnum = 0;
7899 	else if (lnum < l || shl->rm.endpos[0].col > mincol)
7900 	    return;
7901     }
7902 
7903     /*
7904      * Repeat searching for a match until one is found that includes "mincol"
7905      * or none is found in this line.
7906      */
7907     called_emsg = FALSE;
7908     for (;;)
7909     {
7910 #ifdef FEAT_RELTIME
7911 	/* Stop searching after passing the time limit. */
7912 	if (profile_passed_limit(&(shl->tm)))
7913 	{
7914 	    shl->lnum = 0;		/* no match found in time */
7915 	    break;
7916 	}
7917 #endif
7918 	/* Three situations:
7919 	 * 1. No useful previous match: search from start of line.
7920 	 * 2. Not Vi compatible or empty match: continue at next character.
7921 	 *    Break the loop if this is beyond the end of the line.
7922 	 * 3. Vi compatible searching: continue at end of previous match.
7923 	 */
7924 	if (shl->lnum == 0)
7925 	    matchcol = 0;
7926 	else if (vim_strchr(p_cpo, CPO_SEARCH) == NULL
7927 		|| (shl->rm.endpos[0].lnum == 0
7928 		    && shl->rm.endpos[0].col <= shl->rm.startpos[0].col))
7929 	{
7930 	    char_u	*ml;
7931 
7932 	    matchcol = shl->rm.startpos[0].col;
7933 	    ml = ml_get_buf(shl->buf, lnum, FALSE) + matchcol;
7934 	    if (*ml == NUL)
7935 	    {
7936 		++matchcol;
7937 		shl->lnum = 0;
7938 		break;
7939 	    }
7940 #ifdef FEAT_MBYTE
7941 	    if (has_mbyte)
7942 		matchcol += mb_ptr2len(ml);
7943 	    else
7944 #endif
7945 		++matchcol;
7946 	}
7947 	else
7948 	    matchcol = shl->rm.endpos[0].col;
7949 
7950 	shl->lnum = lnum;
7951 	if (shl->rm.regprog != NULL)
7952 	{
7953 	    /* Remember whether shl->rm is using a copy of the regprog in
7954 	     * cur->match. */
7955 	    int regprog_is_copy = (shl != &search_hl && cur != NULL
7956 				&& shl == &cur->hl
7957 				&& cur->match.regprog == cur->hl.rm.regprog);
7958 	    int timed_out = FALSE;
7959 
7960 	    nmatched = vim_regexec_multi(&shl->rm, win, shl->buf, lnum,
7961 		    matchcol,
7962 #ifdef FEAT_RELTIME
7963 		    &(shl->tm), &timed_out
7964 #else
7965 		    NULL, NULL
7966 #endif
7967 		    );
7968 	    /* Copy the regprog, in case it got freed and recompiled. */
7969 	    if (regprog_is_copy)
7970 		cur->match.regprog = cur->hl.rm.regprog;
7971 
7972 	    if (called_emsg || got_int || timed_out)
7973 	    {
7974 		/* Error while handling regexp: stop using this regexp. */
7975 		if (shl == &search_hl)
7976 		{
7977 		    /* don't free regprog in the match list, it's a copy */
7978 		    vim_regfree(shl->rm.regprog);
7979 		    set_no_hlsearch(TRUE);
7980 		}
7981 		shl->rm.regprog = NULL;
7982 		shl->lnum = 0;
7983 		got_int = FALSE;  /* avoid the "Type :quit to exit Vim"
7984 				     message */
7985 		break;
7986 	    }
7987 	}
7988 	else if (cur != NULL)
7989 	    nmatched = next_search_hl_pos(shl, lnum, &(cur->pos), matchcol);
7990 	else
7991 	    nmatched = 0;
7992 	if (nmatched == 0)
7993 	{
7994 	    shl->lnum = 0;		/* no match found */
7995 	    break;
7996 	}
7997 	if (shl->rm.startpos[0].lnum > 0
7998 		|| shl->rm.startpos[0].col >= mincol
7999 		|| nmatched > 1
8000 		|| shl->rm.endpos[0].col > mincol)
8001 	{
8002 	    shl->lnum += shl->rm.startpos[0].lnum;
8003 	    break;			/* useful match found */
8004 	}
8005     }
8006 
8007     // Restore called_emsg for assert_fails().
8008     called_emsg = save_called_emsg;
8009 }
8010 
8011 /*
8012  * If there is a match fill "shl" and return one.
8013  * Return zero otherwise.
8014  */
8015     static int
8016 next_search_hl_pos(
8017     match_T	    *shl,	/* points to a match */
8018     linenr_T	    lnum,
8019     posmatch_T	    *posmatch,	/* match positions */
8020     colnr_T	    mincol)	/* minimal column for a match */
8021 {
8022     int	    i;
8023     int	    found = -1;
8024 
8025     for (i = posmatch->cur; i < MAXPOSMATCH; i++)
8026     {
8027 	llpos_T	*pos = &posmatch->pos[i];
8028 
8029 	if (pos->lnum == 0)
8030 	    break;
8031 	if (pos->len == 0 && pos->col < mincol)
8032 	    continue;
8033 	if (pos->lnum == lnum)
8034 	{
8035 	    if (found >= 0)
8036 	    {
8037 		/* if this match comes before the one at "found" then swap
8038 		 * them */
8039 		if (pos->col < posmatch->pos[found].col)
8040 		{
8041 		    llpos_T	tmp = *pos;
8042 
8043 		    *pos = posmatch->pos[found];
8044 		    posmatch->pos[found] = tmp;
8045 		}
8046 	    }
8047 	    else
8048 		found = i;
8049 	}
8050     }
8051     posmatch->cur = 0;
8052     if (found >= 0)
8053     {
8054 	colnr_T	start = posmatch->pos[found].col == 0
8055 					    ? 0 : posmatch->pos[found].col - 1;
8056 	colnr_T	end = posmatch->pos[found].col == 0
8057 				   ? MAXCOL : start + posmatch->pos[found].len;
8058 
8059 	shl->lnum = lnum;
8060 	shl->rm.startpos[0].lnum = 0;
8061 	shl->rm.startpos[0].col = start;
8062 	shl->rm.endpos[0].lnum = 0;
8063 	shl->rm.endpos[0].col = end;
8064 	shl->is_addpos = TRUE;
8065 	posmatch->cur = found + 1;
8066 	return 1;
8067     }
8068     return 0;
8069 }
8070 #endif
8071 
8072       static void
8073 screen_start_highlight(int attr)
8074 {
8075     attrentry_T *aep = NULL;
8076 
8077     screen_attr = attr;
8078     if (full_screen
8079 #ifdef WIN3264
8080 		    && termcap_active
8081 #endif
8082 				       )
8083     {
8084 #ifdef FEAT_GUI
8085 	if (gui.in_use)
8086 	{
8087 	    char	buf[20];
8088 
8089 	    /* The GUI handles this internally. */
8090 	    sprintf(buf, IF_EB("\033|%dh", ESC_STR "|%dh"), attr);
8091 	    OUT_STR(buf);
8092 	}
8093 	else
8094 #endif
8095 	{
8096 	    if (attr > HL_ALL)				/* special HL attr. */
8097 	    {
8098 		if (IS_CTERM)
8099 		    aep = syn_cterm_attr2entry(attr);
8100 		else
8101 		    aep = syn_term_attr2entry(attr);
8102 		if (aep == NULL)	    /* did ":syntax clear" */
8103 		    attr = 0;
8104 		else
8105 		    attr = aep->ae_attr;
8106 	    }
8107 	    if ((attr & HL_BOLD) && *T_MD != NUL)	/* bold */
8108 		out_str(T_MD);
8109 	    else if (aep != NULL && cterm_normal_fg_bold && (
8110 #ifdef FEAT_TERMGUICOLORS
8111 			p_tgc && aep->ae_u.cterm.fg_rgb != CTERMCOLOR
8112 			  ? aep->ae_u.cterm.fg_rgb != INVALCOLOR
8113 			  :
8114 #endif
8115 			    t_colors > 1 && aep->ae_u.cterm.fg_color))
8116 		/* If the Normal FG color has BOLD attribute and the new HL
8117 		 * has a FG color defined, clear BOLD. */
8118 		out_str(T_ME);
8119 	    if ((attr & HL_STANDOUT) && *T_SO != NUL)	/* standout */
8120 		out_str(T_SO);
8121 	    if ((attr & HL_UNDERCURL) && *T_UCS != NUL) /* undercurl */
8122 		out_str(T_UCS);
8123 	    if (((attr & HL_UNDERLINE)	    /* underline or undercurl */
8124 			|| ((attr & HL_UNDERCURL) && *T_UCS == NUL))
8125 		    && *T_US != NUL)
8126 		out_str(T_US);
8127 	    if ((attr & HL_ITALIC) && *T_CZH != NUL)	/* italic */
8128 		out_str(T_CZH);
8129 	    if ((attr & HL_INVERSE) && *T_MR != NUL)	/* inverse (reverse) */
8130 		out_str(T_MR);
8131 	    if ((attr & HL_STRIKETHROUGH) && *T_STS != NUL)	/* strike */
8132 		out_str(T_STS);
8133 
8134 	    /*
8135 	     * Output the color or start string after bold etc., in case the
8136 	     * bold etc. override the color setting.
8137 	     */
8138 	    if (aep != NULL)
8139 	    {
8140 #ifdef FEAT_TERMGUICOLORS
8141 		/* When 'termguicolors' is set but fg or bg is unset,
8142 		 * fall back to the cterm colors.   This helps for SpellBad,
8143 		 * where the GUI uses a red undercurl. */
8144 		if (p_tgc && aep->ae_u.cterm.fg_rgb != CTERMCOLOR)
8145 		{
8146 		    if (aep->ae_u.cterm.fg_rgb != INVALCOLOR)
8147 			term_fg_rgb_color(aep->ae_u.cterm.fg_rgb);
8148 		}
8149 		else
8150 #endif
8151 		if (t_colors > 1)
8152 		{
8153 		    if (aep->ae_u.cterm.fg_color)
8154 			term_fg_color(aep->ae_u.cterm.fg_color - 1);
8155 		}
8156 #ifdef FEAT_TERMGUICOLORS
8157 		if (p_tgc && aep->ae_u.cterm.bg_rgb != CTERMCOLOR)
8158 		{
8159 		    if (aep->ae_u.cterm.bg_rgb != INVALCOLOR)
8160 			term_bg_rgb_color(aep->ae_u.cterm.bg_rgb);
8161 		}
8162 		else
8163 #endif
8164 		if (t_colors > 1)
8165 		{
8166 		    if (aep->ae_u.cterm.bg_color)
8167 			term_bg_color(aep->ae_u.cterm.bg_color - 1);
8168 		}
8169 
8170 		if (!IS_CTERM)
8171 		{
8172 		    if (aep->ae_u.term.start != NULL)
8173 			out_str(aep->ae_u.term.start);
8174 		}
8175 	    }
8176 	}
8177     }
8178 }
8179 
8180       void
8181 screen_stop_highlight(void)
8182 {
8183     int	    do_ME = FALSE;	    /* output T_ME code */
8184 
8185     if (screen_attr != 0
8186 #ifdef WIN3264
8187 			&& termcap_active
8188 #endif
8189 					   )
8190     {
8191 #ifdef FEAT_GUI
8192 	if (gui.in_use)
8193 	{
8194 	    char	buf[20];
8195 
8196 	    /* use internal GUI code */
8197 	    sprintf(buf, IF_EB("\033|%dH", ESC_STR "|%dH"), screen_attr);
8198 	    OUT_STR(buf);
8199 	}
8200 	else
8201 #endif
8202 	{
8203 	    if (screen_attr > HL_ALL)			/* special HL attr. */
8204 	    {
8205 		attrentry_T *aep;
8206 
8207 		if (IS_CTERM)
8208 		{
8209 		    /*
8210 		     * Assume that t_me restores the original colors!
8211 		     */
8212 		    aep = syn_cterm_attr2entry(screen_attr);
8213 		    if (aep != NULL && ((
8214 #ifdef FEAT_TERMGUICOLORS
8215 			    p_tgc && aep->ae_u.cterm.fg_rgb != CTERMCOLOR
8216 				? aep->ae_u.cterm.fg_rgb != INVALCOLOR
8217 				:
8218 #endif
8219 				aep->ae_u.cterm.fg_color) || (
8220 #ifdef FEAT_TERMGUICOLORS
8221 			    p_tgc && aep->ae_u.cterm.bg_rgb != CTERMCOLOR
8222 				? aep->ae_u.cterm.bg_rgb != INVALCOLOR
8223 				:
8224 #endif
8225 				aep->ae_u.cterm.bg_color)))
8226 			do_ME = TRUE;
8227 		}
8228 		else
8229 		{
8230 		    aep = syn_term_attr2entry(screen_attr);
8231 		    if (aep != NULL && aep->ae_u.term.stop != NULL)
8232 		    {
8233 			if (STRCMP(aep->ae_u.term.stop, T_ME) == 0)
8234 			    do_ME = TRUE;
8235 			else
8236 			    out_str(aep->ae_u.term.stop);
8237 		    }
8238 		}
8239 		if (aep == NULL)	    /* did ":syntax clear" */
8240 		    screen_attr = 0;
8241 		else
8242 		    screen_attr = aep->ae_attr;
8243 	    }
8244 
8245 	    /*
8246 	     * Often all ending-codes are equal to T_ME.  Avoid outputting the
8247 	     * same sequence several times.
8248 	     */
8249 	    if (screen_attr & HL_STANDOUT)
8250 	    {
8251 		if (STRCMP(T_SE, T_ME) == 0)
8252 		    do_ME = TRUE;
8253 		else
8254 		    out_str(T_SE);
8255 	    }
8256 	    if ((screen_attr & HL_UNDERCURL) && *T_UCE != NUL)
8257 	    {
8258 		if (STRCMP(T_UCE, T_ME) == 0)
8259 		    do_ME = TRUE;
8260 		else
8261 		    out_str(T_UCE);
8262 	    }
8263 	    if ((screen_attr & HL_UNDERLINE)
8264 			    || ((screen_attr & HL_UNDERCURL) && *T_UCE == NUL))
8265 	    {
8266 		if (STRCMP(T_UE, T_ME) == 0)
8267 		    do_ME = TRUE;
8268 		else
8269 		    out_str(T_UE);
8270 	    }
8271 	    if (screen_attr & HL_ITALIC)
8272 	    {
8273 		if (STRCMP(T_CZR, T_ME) == 0)
8274 		    do_ME = TRUE;
8275 		else
8276 		    out_str(T_CZR);
8277 	    }
8278 	    if (screen_attr & HL_STRIKETHROUGH)
8279 	    {
8280 		if (STRCMP(T_STE, T_ME) == 0)
8281 		    do_ME = TRUE;
8282 		else
8283 		    out_str(T_STE);
8284 	    }
8285 	    if (do_ME || (screen_attr & (HL_BOLD | HL_INVERSE)))
8286 		out_str(T_ME);
8287 
8288 #ifdef FEAT_TERMGUICOLORS
8289 	    if (p_tgc)
8290 	    {
8291 		if (cterm_normal_fg_gui_color != INVALCOLOR)
8292 		    term_fg_rgb_color(cterm_normal_fg_gui_color);
8293 		if (cterm_normal_bg_gui_color != INVALCOLOR)
8294 		    term_bg_rgb_color(cterm_normal_bg_gui_color);
8295 	    }
8296 	    else
8297 #endif
8298 	    {
8299 		if (t_colors > 1)
8300 		{
8301 		    /* set Normal cterm colors */
8302 		    if (cterm_normal_fg_color != 0)
8303 			term_fg_color(cterm_normal_fg_color - 1);
8304 		    if (cterm_normal_bg_color != 0)
8305 			term_bg_color(cterm_normal_bg_color - 1);
8306 		    if (cterm_normal_fg_bold)
8307 			out_str(T_MD);
8308 		}
8309 	    }
8310 	}
8311     }
8312     screen_attr = 0;
8313 }
8314 
8315 /*
8316  * Reset the colors for a cterm.  Used when leaving Vim.
8317  * The machine specific code may override this again.
8318  */
8319     void
8320 reset_cterm_colors(void)
8321 {
8322     if (IS_CTERM)
8323     {
8324 	/* set Normal cterm colors */
8325 #ifdef FEAT_TERMGUICOLORS
8326 	if (p_tgc ? (cterm_normal_fg_gui_color != INVALCOLOR
8327 		 || cterm_normal_bg_gui_color != INVALCOLOR)
8328 		: (cterm_normal_fg_color > 0 || cterm_normal_bg_color > 0))
8329 #else
8330 	if (cterm_normal_fg_color > 0 || cterm_normal_bg_color > 0)
8331 #endif
8332 	{
8333 	    out_str(T_OP);
8334 	    screen_attr = -1;
8335 	}
8336 	if (cterm_normal_fg_bold)
8337 	{
8338 	    out_str(T_ME);
8339 	    screen_attr = -1;
8340 	}
8341     }
8342 }
8343 
8344 /*
8345  * Put character ScreenLines["off"] on the screen at position "row" and "col",
8346  * using the attributes from ScreenAttrs["off"].
8347  */
8348     static void
8349 screen_char(unsigned off, int row, int col)
8350 {
8351     int		attr;
8352 
8353     /* Check for illegal values, just in case (could happen just after
8354      * resizing). */
8355     if (row >= screen_Rows || col >= screen_Columns)
8356 	return;
8357 
8358     /* Outputting a character in the last cell on the screen may scroll the
8359      * screen up.  Only do it when the "xn" termcap property is set, otherwise
8360      * mark the character invalid (update it when scrolled up). */
8361     if (*T_XN == NUL
8362 	    && row == screen_Rows - 1 && col == screen_Columns - 1
8363 #ifdef FEAT_RIGHTLEFT
8364 	    /* account for first command-line character in rightleft mode */
8365 	    && !cmdmsg_rl
8366 #endif
8367        )
8368     {
8369 	ScreenAttrs[off] = (sattr_T)-1;
8370 	return;
8371     }
8372 
8373     /*
8374      * Stop highlighting first, so it's easier to move the cursor.
8375      */
8376     if (screen_char_attr != 0)
8377 	attr = screen_char_attr;
8378     else
8379 	attr = ScreenAttrs[off];
8380     if (screen_attr != attr)
8381 	screen_stop_highlight();
8382 
8383     windgoto(row, col);
8384 
8385     if (screen_attr != attr)
8386 	screen_start_highlight(attr);
8387 
8388 #ifdef FEAT_MBYTE
8389     if (enc_utf8 && ScreenLinesUC[off] != 0)
8390     {
8391 	char_u	    buf[MB_MAXBYTES + 1];
8392 
8393 	if (utf_ambiguous_width(ScreenLinesUC[off]))
8394 	{
8395 	    if (*p_ambw == 'd'
8396 # ifdef FEAT_GUI
8397 		    && !gui.in_use
8398 # endif
8399 		    )
8400 	    {
8401 		/* Clear the two screen cells. If the character is actually
8402 		 * single width it won't change the second cell. */
8403 		out_str((char_u *)"  ");
8404 		term_windgoto(row, col);
8405 	    }
8406 	    /* not sure where the cursor is after drawing the ambiguous width
8407 	     * character */
8408 	    screen_cur_col = 9999;
8409 	}
8410 	else if (utf_char2cells(ScreenLinesUC[off]) > 1)
8411 	    ++screen_cur_col;
8412 
8413 	/* Convert the UTF-8 character to bytes and write it. */
8414 	buf[utfc_char2bytes(off, buf)] = NUL;
8415 	out_str(buf);
8416     }
8417     else
8418 #endif
8419     {
8420 #ifdef FEAT_MBYTE
8421 	out_flush_check();
8422 #endif
8423 	out_char(ScreenLines[off]);
8424 #ifdef FEAT_MBYTE
8425 	/* double-byte character in single-width cell */
8426 	if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
8427 	    out_char(ScreenLines2[off]);
8428 #endif
8429     }
8430 
8431     screen_cur_col++;
8432 }
8433 
8434 #ifdef FEAT_MBYTE
8435 
8436 /*
8437  * Used for enc_dbcs only: Put one double-wide character at ScreenLines["off"]
8438  * on the screen at position 'row' and 'col'.
8439  * The attributes of the first byte is used for all.  This is required to
8440  * output the two bytes of a double-byte character with nothing in between.
8441  */
8442     static void
8443 screen_char_2(unsigned off, int row, int col)
8444 {
8445     /* Check for illegal values (could be wrong when screen was resized). */
8446     if (off + 1 >= (unsigned)(screen_Rows * screen_Columns))
8447 	return;
8448 
8449     /* Outputting the last character on the screen may scrollup the screen.
8450      * Don't to it!  Mark the character invalid (update it when scrolled up) */
8451     if (row == screen_Rows - 1 && col >= screen_Columns - 2)
8452     {
8453 	ScreenAttrs[off] = (sattr_T)-1;
8454 	return;
8455     }
8456 
8457     /* Output the first byte normally (positions the cursor), then write the
8458      * second byte directly. */
8459     screen_char(off, row, col);
8460     out_char(ScreenLines[off + 1]);
8461     ++screen_cur_col;
8462 }
8463 #endif
8464 
8465 /*
8466  * Draw a rectangle of the screen, inverted when "invert" is TRUE.
8467  * This uses the contents of ScreenLines[] and doesn't change it.
8468  */
8469     void
8470 screen_draw_rectangle(
8471     int		row,
8472     int		col,
8473     int		height,
8474     int		width,
8475     int		invert)
8476 {
8477     int		r, c;
8478     int		off;
8479 #ifdef FEAT_MBYTE
8480     int		max_off;
8481 #endif
8482 
8483     /* Can't use ScreenLines unless initialized */
8484     if (ScreenLines == NULL)
8485 	return;
8486 
8487     if (invert)
8488 	screen_char_attr = HL_INVERSE;
8489     for (r = row; r < row + height; ++r)
8490     {
8491 	off = LineOffset[r];
8492 #ifdef FEAT_MBYTE
8493 	max_off = off + screen_Columns;
8494 #endif
8495 	for (c = col; c < col + width; ++c)
8496 	{
8497 #ifdef FEAT_MBYTE
8498 	    if (enc_dbcs != 0 && dbcs_off2cells(off + c, max_off) > 1)
8499 	    {
8500 		screen_char_2(off + c, r, c);
8501 		++c;
8502 	    }
8503 	    else
8504 #endif
8505 	    {
8506 		screen_char(off + c, r, c);
8507 #ifdef FEAT_MBYTE
8508 		if (utf_off2cells(off + c, max_off) > 1)
8509 		    ++c;
8510 #endif
8511 	    }
8512 	}
8513     }
8514     screen_char_attr = 0;
8515 }
8516 
8517 /*
8518  * Redraw the characters for a vertically split window.
8519  */
8520     static void
8521 redraw_block(int row, int end, win_T *wp)
8522 {
8523     int		col;
8524     int		width;
8525 
8526 # ifdef FEAT_CLIPBOARD
8527     clip_may_clear_selection(row, end - 1);
8528 # endif
8529 
8530     if (wp == NULL)
8531     {
8532 	col = 0;
8533 	width = Columns;
8534     }
8535     else
8536     {
8537 	col = wp->w_wincol;
8538 	width = wp->w_width;
8539     }
8540     screen_draw_rectangle(row, col, end - row, width, FALSE);
8541 }
8542 
8543     static void
8544 space_to_screenline(int off, int attr)
8545 {
8546     ScreenLines[off] = ' ';
8547     ScreenAttrs[off] = attr;
8548 # ifdef FEAT_MBYTE
8549     if (enc_utf8)
8550 	ScreenLinesUC[off] = 0;
8551 # endif
8552 }
8553 
8554 /*
8555  * Fill the screen from 'start_row' to 'end_row', from 'start_col' to 'end_col'
8556  * with character 'c1' in first column followed by 'c2' in the other columns.
8557  * Use attributes 'attr'.
8558  */
8559     void
8560 screen_fill(
8561     int	    start_row,
8562     int	    end_row,
8563     int	    start_col,
8564     int	    end_col,
8565     int	    c1,
8566     int	    c2,
8567     int	    attr)
8568 {
8569     int		    row;
8570     int		    col;
8571     int		    off;
8572     int		    end_off;
8573     int		    did_delete;
8574     int		    c;
8575     int		    norm_term;
8576 #if defined(FEAT_GUI) || defined(UNIX)
8577     int		    force_next = FALSE;
8578 #endif
8579 
8580     if (end_row > screen_Rows)		/* safety check */
8581 	end_row = screen_Rows;
8582     if (end_col > screen_Columns)	/* safety check */
8583 	end_col = screen_Columns;
8584     if (ScreenLines == NULL
8585 	    || start_row >= end_row
8586 	    || start_col >= end_col)	/* nothing to do */
8587 	return;
8588 
8589     /* it's a "normal" terminal when not in a GUI or cterm */
8590     norm_term = (
8591 #ifdef FEAT_GUI
8592 	    !gui.in_use &&
8593 #endif
8594 	    !IS_CTERM);
8595     for (row = start_row; row < end_row; ++row)
8596     {
8597 #ifdef FEAT_MBYTE
8598 	if (has_mbyte
8599 # ifdef FEAT_GUI
8600 		&& !gui.in_use
8601 # endif
8602 	   )
8603 	{
8604 	    /* When drawing over the right halve of a double-wide char clear
8605 	     * out the left halve.  When drawing over the left halve of a
8606 	     * double wide-char clear out the right halve.  Only needed in a
8607 	     * terminal. */
8608 	    if (start_col > 0 && mb_fix_col(start_col, row) != start_col)
8609 		screen_puts_len((char_u *)" ", 1, row, start_col - 1, 0);
8610 	    if (end_col < screen_Columns && mb_fix_col(end_col, row) != end_col)
8611 		screen_puts_len((char_u *)" ", 1, row, end_col, 0);
8612 	}
8613 #endif
8614 	/*
8615 	 * Try to use delete-line termcap code, when no attributes or in a
8616 	 * "normal" terminal, where a bold/italic space is just a
8617 	 * space.
8618 	 */
8619 	did_delete = FALSE;
8620 	if (c2 == ' '
8621 		&& end_col == Columns
8622 		&& can_clear(T_CE)
8623 		&& (attr == 0
8624 		    || (norm_term
8625 			&& attr <= HL_ALL
8626 			&& ((attr & ~(HL_BOLD | HL_ITALIC)) == 0))))
8627 	{
8628 	    /*
8629 	     * check if we really need to clear something
8630 	     */
8631 	    col = start_col;
8632 	    if (c1 != ' ')			/* don't clear first char */
8633 		++col;
8634 
8635 	    off = LineOffset[row] + col;
8636 	    end_off = LineOffset[row] + end_col;
8637 
8638 	    /* skip blanks (used often, keep it fast!) */
8639 #ifdef FEAT_MBYTE
8640 	    if (enc_utf8)
8641 		while (off < end_off && ScreenLines[off] == ' '
8642 			  && ScreenAttrs[off] == 0 && ScreenLinesUC[off] == 0)
8643 		    ++off;
8644 	    else
8645 #endif
8646 		while (off < end_off && ScreenLines[off] == ' '
8647 						     && ScreenAttrs[off] == 0)
8648 		    ++off;
8649 	    if (off < end_off)		/* something to be cleared */
8650 	    {
8651 		col = off - LineOffset[row];
8652 		screen_stop_highlight();
8653 		term_windgoto(row, col);/* clear rest of this screen line */
8654 		out_str(T_CE);
8655 		screen_start();		/* don't know where cursor is now */
8656 		col = end_col - col;
8657 		while (col--)		/* clear chars in ScreenLines */
8658 		{
8659 		    space_to_screenline(off, 0);
8660 		    ++off;
8661 		}
8662 	    }
8663 	    did_delete = TRUE;		/* the chars are cleared now */
8664 	}
8665 
8666 	off = LineOffset[row] + start_col;
8667 	c = c1;
8668 	for (col = start_col; col < end_col; ++col)
8669 	{
8670 	    if (ScreenLines[off] != c
8671 #ifdef FEAT_MBYTE
8672 		    || (enc_utf8 && (int)ScreenLinesUC[off]
8673 						       != (c >= 0x80 ? c : 0))
8674 #endif
8675 		    || ScreenAttrs[off] != attr
8676 #if defined(FEAT_GUI) || defined(UNIX)
8677 		    || force_next
8678 #endif
8679 		    )
8680 	    {
8681 #if defined(FEAT_GUI) || defined(UNIX)
8682 		/* The bold trick may make a single row of pixels appear in
8683 		 * the next character.  When a bold character is removed, the
8684 		 * next character should be redrawn too.  This happens for our
8685 		 * own GUI and for some xterms.  */
8686 		if (
8687 # ifdef FEAT_GUI
8688 			gui.in_use
8689 # endif
8690 # if defined(FEAT_GUI) && defined(UNIX)
8691 			||
8692 # endif
8693 # ifdef UNIX
8694 			term_is_xterm
8695 # endif
8696 		   )
8697 		{
8698 		    if (ScreenLines[off] != ' '
8699 			    && (ScreenAttrs[off] > HL_ALL
8700 				|| ScreenAttrs[off] & HL_BOLD))
8701 			force_next = TRUE;
8702 		    else
8703 			force_next = FALSE;
8704 		}
8705 #endif
8706 		ScreenLines[off] = c;
8707 #ifdef FEAT_MBYTE
8708 		if (enc_utf8)
8709 		{
8710 		    if (c >= 0x80)
8711 		    {
8712 			ScreenLinesUC[off] = c;
8713 			ScreenLinesC[0][off] = 0;
8714 		    }
8715 		    else
8716 			ScreenLinesUC[off] = 0;
8717 		}
8718 #endif
8719 		ScreenAttrs[off] = attr;
8720 		if (!did_delete || c != ' ')
8721 		    screen_char(off, row, col);
8722 	    }
8723 	    ++off;
8724 	    if (col == start_col)
8725 	    {
8726 		if (did_delete)
8727 		    break;
8728 		c = c2;
8729 	    }
8730 	}
8731 	if (end_col == Columns)
8732 	    LineWraps[row] = FALSE;
8733 	if (row == Rows - 1)		/* overwritten the command line */
8734 	{
8735 	    redraw_cmdline = TRUE;
8736 	    if (start_col == 0 && end_col == Columns
8737 		    && c1 == ' ' && c2 == ' ' && attr == 0)
8738 		clear_cmdline = FALSE;	/* command line has been cleared */
8739 	    if (start_col == 0)
8740 		mode_displayed = FALSE; /* mode cleared or overwritten */
8741 	}
8742     }
8743 }
8744 
8745 /*
8746  * Check if there should be a delay.  Used before clearing or redrawing the
8747  * screen or the command line.
8748  */
8749     void
8750 check_for_delay(int check_msg_scroll)
8751 {
8752     if ((emsg_on_display || (check_msg_scroll && msg_scroll))
8753 	    && !did_wait_return
8754 	    && emsg_silent == 0)
8755     {
8756 	out_flush();
8757 	ui_delay(1000L, TRUE);
8758 	emsg_on_display = FALSE;
8759 	if (check_msg_scroll)
8760 	    msg_scroll = FALSE;
8761     }
8762 }
8763 
8764 /*
8765  * screen_valid -  allocate screen buffers if size changed
8766  *   If "doclear" is TRUE: clear screen if it has been resized.
8767  *	Returns TRUE if there is a valid screen to write to.
8768  *	Returns FALSE when starting up and screen not initialized yet.
8769  */
8770     int
8771 screen_valid(int doclear)
8772 {
8773     screenalloc(doclear);	   /* allocate screen buffers if size changed */
8774     return (ScreenLines != NULL);
8775 }
8776 
8777 /*
8778  * Resize the shell to Rows and Columns.
8779  * Allocate ScreenLines[] and associated items.
8780  *
8781  * There may be some time between setting Rows and Columns and (re)allocating
8782  * ScreenLines[].  This happens when starting up and when (manually) changing
8783  * the shell size.  Always use screen_Rows and screen_Columns to access items
8784  * in ScreenLines[].  Use Rows and Columns for positioning text etc. where the
8785  * final size of the shell is needed.
8786  */
8787     void
8788 screenalloc(int doclear)
8789 {
8790     int		    new_row, old_row;
8791 #ifdef FEAT_GUI
8792     int		    old_Rows;
8793 #endif
8794     win_T	    *wp;
8795     int		    outofmem = FALSE;
8796     int		    len;
8797     schar_T	    *new_ScreenLines;
8798 #ifdef FEAT_MBYTE
8799     u8char_T	    *new_ScreenLinesUC = NULL;
8800     u8char_T	    *new_ScreenLinesC[MAX_MCO];
8801     schar_T	    *new_ScreenLines2 = NULL;
8802     int		    i;
8803 #endif
8804     sattr_T	    *new_ScreenAttrs;
8805     unsigned	    *new_LineOffset;
8806     char_u	    *new_LineWraps;
8807     short	    *new_TabPageIdxs;
8808     tabpage_T	    *tp;
8809     static int	    entered = FALSE;		/* avoid recursiveness */
8810     static int	    done_outofmem_msg = FALSE;	/* did outofmem message */
8811     int		    retry_count = 0;
8812 
8813 retry:
8814     /*
8815      * Allocation of the screen buffers is done only when the size changes and
8816      * when Rows and Columns have been set and we have started doing full
8817      * screen stuff.
8818      */
8819     if ((ScreenLines != NULL
8820 		&& Rows == screen_Rows
8821 		&& Columns == screen_Columns
8822 #ifdef FEAT_MBYTE
8823 		&& enc_utf8 == (ScreenLinesUC != NULL)
8824 		&& (enc_dbcs == DBCS_JPNU) == (ScreenLines2 != NULL)
8825 		&& p_mco == Screen_mco
8826 #endif
8827 		)
8828 	    || Rows == 0
8829 	    || Columns == 0
8830 	    || (!full_screen && ScreenLines == NULL))
8831 	return;
8832 
8833     /*
8834      * It's possible that we produce an out-of-memory message below, which
8835      * will cause this function to be called again.  To break the loop, just
8836      * return here.
8837      */
8838     if (entered)
8839 	return;
8840     entered = TRUE;
8841 
8842     /*
8843      * Note that the window sizes are updated before reallocating the arrays,
8844      * thus we must not redraw here!
8845      */
8846     ++RedrawingDisabled;
8847 
8848     win_new_shellsize();    /* fit the windows in the new sized shell */
8849 
8850     comp_col();		/* recompute columns for shown command and ruler */
8851 
8852     /*
8853      * We're changing the size of the screen.
8854      * - Allocate new arrays for ScreenLines and ScreenAttrs.
8855      * - Move lines from the old arrays into the new arrays, clear extra
8856      *	 lines (unless the screen is going to be cleared).
8857      * - Free the old arrays.
8858      *
8859      * If anything fails, make ScreenLines NULL, so we don't do anything!
8860      * Continuing with the old ScreenLines may result in a crash, because the
8861      * size is wrong.
8862      */
8863     FOR_ALL_TAB_WINDOWS(tp, wp)
8864 	win_free_lsize(wp);
8865     if (aucmd_win != NULL)
8866 	win_free_lsize(aucmd_win);
8867 
8868     new_ScreenLines = (schar_T *)lalloc((long_u)(
8869 			      (Rows + 1) * Columns * sizeof(schar_T)), FALSE);
8870 #ifdef FEAT_MBYTE
8871     vim_memset(new_ScreenLinesC, 0, sizeof(u8char_T *) * MAX_MCO);
8872     if (enc_utf8)
8873     {
8874 	new_ScreenLinesUC = (u8char_T *)lalloc((long_u)(
8875 			     (Rows + 1) * Columns * sizeof(u8char_T)), FALSE);
8876 	for (i = 0; i < p_mco; ++i)
8877 	    new_ScreenLinesC[i] = (u8char_T *)lalloc_clear((long_u)(
8878 			     (Rows + 1) * Columns * sizeof(u8char_T)), FALSE);
8879     }
8880     if (enc_dbcs == DBCS_JPNU)
8881 	new_ScreenLines2 = (schar_T *)lalloc((long_u)(
8882 			     (Rows + 1) * Columns * sizeof(schar_T)), FALSE);
8883 #endif
8884     new_ScreenAttrs = (sattr_T *)lalloc((long_u)(
8885 			      (Rows + 1) * Columns * sizeof(sattr_T)), FALSE);
8886     new_LineOffset = (unsigned *)lalloc((long_u)(
8887 					 Rows * sizeof(unsigned)), FALSE);
8888     new_LineWraps = (char_u *)lalloc((long_u)(Rows * sizeof(char_u)), FALSE);
8889     new_TabPageIdxs = (short *)lalloc((long_u)(Columns * sizeof(short)), FALSE);
8890 
8891     FOR_ALL_TAB_WINDOWS(tp, wp)
8892     {
8893 	if (win_alloc_lines(wp) == FAIL)
8894 	{
8895 	    outofmem = TRUE;
8896 	    goto give_up;
8897 	}
8898     }
8899     if (aucmd_win != NULL && aucmd_win->w_lines == NULL
8900 					&& win_alloc_lines(aucmd_win) == FAIL)
8901 	outofmem = TRUE;
8902 give_up:
8903 
8904 #ifdef FEAT_MBYTE
8905     for (i = 0; i < p_mco; ++i)
8906 	if (new_ScreenLinesC[i] == NULL)
8907 	    break;
8908 #endif
8909     if (new_ScreenLines == NULL
8910 #ifdef FEAT_MBYTE
8911 	    || (enc_utf8 && (new_ScreenLinesUC == NULL || i != p_mco))
8912 	    || (enc_dbcs == DBCS_JPNU && new_ScreenLines2 == NULL)
8913 #endif
8914 	    || new_ScreenAttrs == NULL
8915 	    || new_LineOffset == NULL
8916 	    || new_LineWraps == NULL
8917 	    || new_TabPageIdxs == NULL
8918 	    || outofmem)
8919     {
8920 	if (ScreenLines != NULL || !done_outofmem_msg)
8921 	{
8922 	    /* guess the size */
8923 	    do_outofmem_msg((long_u)((Rows + 1) * Columns));
8924 
8925 	    /* Remember we did this to avoid getting outofmem messages over
8926 	     * and over again. */
8927 	    done_outofmem_msg = TRUE;
8928 	}
8929 	VIM_CLEAR(new_ScreenLines);
8930 #ifdef FEAT_MBYTE
8931 	VIM_CLEAR(new_ScreenLinesUC);
8932 	for (i = 0; i < p_mco; ++i)
8933 	    VIM_CLEAR(new_ScreenLinesC[i]);
8934 	VIM_CLEAR(new_ScreenLines2);
8935 #endif
8936 	VIM_CLEAR(new_ScreenAttrs);
8937 	VIM_CLEAR(new_LineOffset);
8938 	VIM_CLEAR(new_LineWraps);
8939 	VIM_CLEAR(new_TabPageIdxs);
8940     }
8941     else
8942     {
8943 	done_outofmem_msg = FALSE;
8944 
8945 	for (new_row = 0; new_row < Rows; ++new_row)
8946 	{
8947 	    new_LineOffset[new_row] = new_row * Columns;
8948 	    new_LineWraps[new_row] = FALSE;
8949 
8950 	    /*
8951 	     * If the screen is not going to be cleared, copy as much as
8952 	     * possible from the old screen to the new one and clear the rest
8953 	     * (used when resizing the window at the "--more--" prompt or when
8954 	     * executing an external command, for the GUI).
8955 	     */
8956 	    if (!doclear)
8957 	    {
8958 		(void)vim_memset(new_ScreenLines + new_row * Columns,
8959 				      ' ', (size_t)Columns * sizeof(schar_T));
8960 #ifdef FEAT_MBYTE
8961 		if (enc_utf8)
8962 		{
8963 		    (void)vim_memset(new_ScreenLinesUC + new_row * Columns,
8964 				       0, (size_t)Columns * sizeof(u8char_T));
8965 		    for (i = 0; i < p_mco; ++i)
8966 			(void)vim_memset(new_ScreenLinesC[i]
8967 							  + new_row * Columns,
8968 				       0, (size_t)Columns * sizeof(u8char_T));
8969 		}
8970 		if (enc_dbcs == DBCS_JPNU)
8971 		    (void)vim_memset(new_ScreenLines2 + new_row * Columns,
8972 				       0, (size_t)Columns * sizeof(schar_T));
8973 #endif
8974 		(void)vim_memset(new_ScreenAttrs + new_row * Columns,
8975 					0, (size_t)Columns * sizeof(sattr_T));
8976 		old_row = new_row + (screen_Rows - Rows);
8977 		if (old_row >= 0 && ScreenLines != NULL)
8978 		{
8979 		    if (screen_Columns < Columns)
8980 			len = screen_Columns;
8981 		    else
8982 			len = Columns;
8983 #ifdef FEAT_MBYTE
8984 		    /* When switching to utf-8 don't copy characters, they
8985 		     * may be invalid now.  Also when p_mco changes. */
8986 		    if (!(enc_utf8 && ScreenLinesUC == NULL)
8987 						       && p_mco == Screen_mco)
8988 #endif
8989 			mch_memmove(new_ScreenLines + new_LineOffset[new_row],
8990 				ScreenLines + LineOffset[old_row],
8991 				(size_t)len * sizeof(schar_T));
8992 #ifdef FEAT_MBYTE
8993 		    if (enc_utf8 && ScreenLinesUC != NULL
8994 						       && p_mco == Screen_mco)
8995 		    {
8996 			mch_memmove(new_ScreenLinesUC + new_LineOffset[new_row],
8997 				ScreenLinesUC + LineOffset[old_row],
8998 				(size_t)len * sizeof(u8char_T));
8999 			for (i = 0; i < p_mco; ++i)
9000 			    mch_memmove(new_ScreenLinesC[i]
9001 						    + new_LineOffset[new_row],
9002 				ScreenLinesC[i] + LineOffset[old_row],
9003 				(size_t)len * sizeof(u8char_T));
9004 		    }
9005 		    if (enc_dbcs == DBCS_JPNU && ScreenLines2 != NULL)
9006 			mch_memmove(new_ScreenLines2 + new_LineOffset[new_row],
9007 				ScreenLines2 + LineOffset[old_row],
9008 				(size_t)len * sizeof(schar_T));
9009 #endif
9010 		    mch_memmove(new_ScreenAttrs + new_LineOffset[new_row],
9011 			    ScreenAttrs + LineOffset[old_row],
9012 			    (size_t)len * sizeof(sattr_T));
9013 		}
9014 	    }
9015 	}
9016 	/* Use the last line of the screen for the current line. */
9017 	current_ScreenLine = new_ScreenLines + Rows * Columns;
9018     }
9019 
9020     free_screenlines();
9021 
9022     ScreenLines = new_ScreenLines;
9023 #ifdef FEAT_MBYTE
9024     ScreenLinesUC = new_ScreenLinesUC;
9025     for (i = 0; i < p_mco; ++i)
9026 	ScreenLinesC[i] = new_ScreenLinesC[i];
9027     Screen_mco = p_mco;
9028     ScreenLines2 = new_ScreenLines2;
9029 #endif
9030     ScreenAttrs = new_ScreenAttrs;
9031     LineOffset = new_LineOffset;
9032     LineWraps = new_LineWraps;
9033     TabPageIdxs = new_TabPageIdxs;
9034 
9035     /* It's important that screen_Rows and screen_Columns reflect the actual
9036      * size of ScreenLines[].  Set them before calling anything. */
9037 #ifdef FEAT_GUI
9038     old_Rows = screen_Rows;
9039 #endif
9040     screen_Rows = Rows;
9041     screen_Columns = Columns;
9042 
9043     must_redraw = CLEAR;	/* need to clear the screen later */
9044     if (doclear)
9045 	screenclear2();
9046 
9047 #ifdef FEAT_GUI
9048     else if (gui.in_use
9049 	    && !gui.starting
9050 	    && ScreenLines != NULL
9051 	    && old_Rows != Rows)
9052     {
9053 	(void)gui_redraw_block(0, 0, (int)Rows - 1, (int)Columns - 1, 0);
9054 	/*
9055 	 * Adjust the position of the cursor, for when executing an external
9056 	 * command.
9057 	 */
9058 	if (msg_row >= Rows)		/* Rows got smaller */
9059 	    msg_row = Rows - 1;		/* put cursor at last row */
9060 	else if (Rows > old_Rows)	/* Rows got bigger */
9061 	    msg_row += Rows - old_Rows; /* put cursor in same place */
9062 	if (msg_col >= Columns)		/* Columns got smaller */
9063 	    msg_col = Columns - 1;	/* put cursor at last column */
9064     }
9065 #endif
9066 
9067     entered = FALSE;
9068     --RedrawingDisabled;
9069 
9070     /*
9071      * Do not apply autocommands more than 3 times to avoid an endless loop
9072      * in case applying autocommands always changes Rows or Columns.
9073      */
9074     if (starting == 0 && ++retry_count <= 3)
9075     {
9076 	apply_autocmds(EVENT_VIMRESIZED, NULL, NULL, FALSE, curbuf);
9077 	/* In rare cases, autocommands may have altered Rows or Columns,
9078 	 * jump back to check if we need to allocate the screen again. */
9079 	goto retry;
9080     }
9081 }
9082 
9083     void
9084 free_screenlines(void)
9085 {
9086 #ifdef FEAT_MBYTE
9087     int		i;
9088 
9089     vim_free(ScreenLinesUC);
9090     for (i = 0; i < Screen_mco; ++i)
9091 	vim_free(ScreenLinesC[i]);
9092     vim_free(ScreenLines2);
9093 #endif
9094     vim_free(ScreenLines);
9095     vim_free(ScreenAttrs);
9096     vim_free(LineOffset);
9097     vim_free(LineWraps);
9098     vim_free(TabPageIdxs);
9099 }
9100 
9101     void
9102 screenclear(void)
9103 {
9104     check_for_delay(FALSE);
9105     screenalloc(FALSE);	    /* allocate screen buffers if size changed */
9106     screenclear2();	    /* clear the screen */
9107 }
9108 
9109     static void
9110 screenclear2(void)
9111 {
9112     int	    i;
9113 
9114     if (starting == NO_SCREEN || ScreenLines == NULL
9115 #ifdef FEAT_GUI
9116 	    || (gui.in_use && gui.starting)
9117 #endif
9118 	    )
9119 	return;
9120 
9121 #ifdef FEAT_GUI
9122     if (!gui.in_use)
9123 #endif
9124 	screen_attr = -1;	/* force setting the Normal colors */
9125     screen_stop_highlight();	/* don't want highlighting here */
9126 
9127 #ifdef FEAT_CLIPBOARD
9128     /* disable selection without redrawing it */
9129     clip_scroll_selection(9999);
9130 #endif
9131 
9132     /* blank out ScreenLines */
9133     for (i = 0; i < Rows; ++i)
9134     {
9135 	lineclear(LineOffset[i], (int)Columns, 0);
9136 	LineWraps[i] = FALSE;
9137     }
9138 
9139     if (can_clear(T_CL))
9140     {
9141 	out_str(T_CL);		/* clear the display */
9142 	clear_cmdline = FALSE;
9143 	mode_displayed = FALSE;
9144     }
9145     else
9146     {
9147 	/* can't clear the screen, mark all chars with invalid attributes */
9148 	for (i = 0; i < Rows; ++i)
9149 	    lineinvalid(LineOffset[i], (int)Columns);
9150 	clear_cmdline = TRUE;
9151     }
9152 
9153     screen_cleared = TRUE;	/* can use contents of ScreenLines now */
9154 
9155     win_rest_invalid(firstwin);
9156     redraw_cmdline = TRUE;
9157     redraw_tabline = TRUE;
9158     if (must_redraw == CLEAR)	/* no need to clear again */
9159 	must_redraw = NOT_VALID;
9160     compute_cmdrow();
9161     msg_row = cmdline_row;	/* put cursor on last line for messages */
9162     msg_col = 0;
9163     screen_start();		/* don't know where cursor is now */
9164     msg_scrolled = 0;		/* can't scroll back */
9165     msg_didany = FALSE;
9166     msg_didout = FALSE;
9167 }
9168 
9169 /*
9170  * Clear one line in ScreenLines.
9171  */
9172     static void
9173 lineclear(unsigned off, int width, int attr)
9174 {
9175     (void)vim_memset(ScreenLines + off, ' ', (size_t)width * sizeof(schar_T));
9176 #ifdef FEAT_MBYTE
9177     if (enc_utf8)
9178 	(void)vim_memset(ScreenLinesUC + off, 0,
9179 					  (size_t)width * sizeof(u8char_T));
9180 #endif
9181     (void)vim_memset(ScreenAttrs + off, attr, (size_t)width * sizeof(sattr_T));
9182 }
9183 
9184 /*
9185  * Mark one line in ScreenLines invalid by setting the attributes to an
9186  * invalid value.
9187  */
9188     static void
9189 lineinvalid(unsigned off, int width)
9190 {
9191     (void)vim_memset(ScreenAttrs + off, -1, (size_t)width * sizeof(sattr_T));
9192 }
9193 
9194 /*
9195  * Copy part of a Screenline for vertically split window "wp".
9196  */
9197     static void
9198 linecopy(int to, int from, win_T *wp)
9199 {
9200     unsigned	off_to = LineOffset[to] + wp->w_wincol;
9201     unsigned	off_from = LineOffset[from] + wp->w_wincol;
9202 
9203     mch_memmove(ScreenLines + off_to, ScreenLines + off_from,
9204 	    wp->w_width * sizeof(schar_T));
9205 #ifdef FEAT_MBYTE
9206     if (enc_utf8)
9207     {
9208 	int	i;
9209 
9210 	mch_memmove(ScreenLinesUC + off_to, ScreenLinesUC + off_from,
9211 		wp->w_width * sizeof(u8char_T));
9212 	for (i = 0; i < p_mco; ++i)
9213 	    mch_memmove(ScreenLinesC[i] + off_to, ScreenLinesC[i] + off_from,
9214 		    wp->w_width * sizeof(u8char_T));
9215     }
9216     if (enc_dbcs == DBCS_JPNU)
9217 	mch_memmove(ScreenLines2 + off_to, ScreenLines2 + off_from,
9218 		wp->w_width * sizeof(schar_T));
9219 #endif
9220     mch_memmove(ScreenAttrs + off_to, ScreenAttrs + off_from,
9221 	    wp->w_width * sizeof(sattr_T));
9222 }
9223 
9224 /*
9225  * Return TRUE if clearing with term string "p" would work.
9226  * It can't work when the string is empty or it won't set the right background.
9227  */
9228     int
9229 can_clear(char_u *p)
9230 {
9231     return (*p != NUL && (t_colors <= 1
9232 #ifdef FEAT_GUI
9233 		|| gui.in_use
9234 #endif
9235 #ifdef FEAT_TERMGUICOLORS
9236 		|| (p_tgc && cterm_normal_bg_gui_color == INVALCOLOR)
9237 		|| (!p_tgc && cterm_normal_bg_color == 0)
9238 #else
9239 		|| cterm_normal_bg_color == 0
9240 #endif
9241 		|| *T_UT != NUL));
9242 }
9243 
9244 /*
9245  * Reset cursor position. Use whenever cursor was moved because of outputting
9246  * something directly to the screen (shell commands) or a terminal control
9247  * code.
9248  */
9249     void
9250 screen_start(void)
9251 {
9252     screen_cur_row = screen_cur_col = 9999;
9253 }
9254 
9255 /*
9256  * Move the cursor to position "row","col" in the screen.
9257  * This tries to find the most efficient way to move, minimizing the number of
9258  * characters sent to the terminal.
9259  */
9260     void
9261 windgoto(int row, int col)
9262 {
9263     sattr_T	    *p;
9264     int		    i;
9265     int		    plan;
9266     int		    cost;
9267     int		    wouldbe_col;
9268     int		    noinvcurs;
9269     char_u	    *bs;
9270     int		    goto_cost;
9271     int		    attr;
9272 
9273 #define GOTO_COST   7	/* assume a term_windgoto() takes about 7 chars */
9274 #define HIGHL_COST  5	/* assume unhighlight takes 5 chars */
9275 
9276 #define PLAN_LE	    1
9277 #define PLAN_CR	    2
9278 #define PLAN_NL	    3
9279 #define PLAN_WRITE  4
9280     /* Can't use ScreenLines unless initialized */
9281     if (ScreenLines == NULL)
9282 	return;
9283 
9284     if (col != screen_cur_col || row != screen_cur_row)
9285     {
9286 	/* Check for valid position. */
9287 	if (row < 0)	/* window without text lines? */
9288 	    row = 0;
9289 	if (row >= screen_Rows)
9290 	    row = screen_Rows - 1;
9291 	if (col >= screen_Columns)
9292 	    col = screen_Columns - 1;
9293 
9294 	/* check if no cursor movement is allowed in highlight mode */
9295 	if (screen_attr && *T_MS == NUL)
9296 	    noinvcurs = HIGHL_COST;
9297 	else
9298 	    noinvcurs = 0;
9299 	goto_cost = GOTO_COST + noinvcurs;
9300 
9301 	/*
9302 	 * Plan how to do the positioning:
9303 	 * 1. Use CR to move it to column 0, same row.
9304 	 * 2. Use T_LE to move it a few columns to the left.
9305 	 * 3. Use NL to move a few lines down, column 0.
9306 	 * 4. Move a few columns to the right with T_ND or by writing chars.
9307 	 *
9308 	 * Don't do this if the cursor went beyond the last column, the cursor
9309 	 * position is unknown then (some terminals wrap, some don't )
9310 	 *
9311 	 * First check if the highlighting attributes allow us to write
9312 	 * characters to move the cursor to the right.
9313 	 */
9314 	if (row >= screen_cur_row && screen_cur_col < Columns)
9315 	{
9316 	    /*
9317 	     * If the cursor is in the same row, bigger col, we can use CR
9318 	     * or T_LE.
9319 	     */
9320 	    bs = NULL;			    /* init for GCC */
9321 	    attr = screen_attr;
9322 	    if (row == screen_cur_row && col < screen_cur_col)
9323 	    {
9324 		/* "le" is preferred over "bc", because "bc" is obsolete */
9325 		if (*T_LE)
9326 		    bs = T_LE;		    /* "cursor left" */
9327 		else
9328 		    bs = T_BC;		    /* "backspace character (old) */
9329 		if (*bs)
9330 		    cost = (screen_cur_col - col) * (int)STRLEN(bs);
9331 		else
9332 		    cost = 999;
9333 		if (col + 1 < cost)	    /* using CR is less characters */
9334 		{
9335 		    plan = PLAN_CR;
9336 		    wouldbe_col = 0;
9337 		    cost = 1;		    /* CR is just one character */
9338 		}
9339 		else
9340 		{
9341 		    plan = PLAN_LE;
9342 		    wouldbe_col = col;
9343 		}
9344 		if (noinvcurs)		    /* will stop highlighting */
9345 		{
9346 		    cost += noinvcurs;
9347 		    attr = 0;
9348 		}
9349 	    }
9350 
9351 	    /*
9352 	     * If the cursor is above where we want to be, we can use CR LF.
9353 	     */
9354 	    else if (row > screen_cur_row)
9355 	    {
9356 		plan = PLAN_NL;
9357 		wouldbe_col = 0;
9358 		cost = (row - screen_cur_row) * 2;  /* CR LF */
9359 		if (noinvcurs)		    /* will stop highlighting */
9360 		{
9361 		    cost += noinvcurs;
9362 		    attr = 0;
9363 		}
9364 	    }
9365 
9366 	    /*
9367 	     * If the cursor is in the same row, smaller col, just use write.
9368 	     */
9369 	    else
9370 	    {
9371 		plan = PLAN_WRITE;
9372 		wouldbe_col = screen_cur_col;
9373 		cost = 0;
9374 	    }
9375 
9376 	    /*
9377 	     * Check if any characters that need to be written have the
9378 	     * correct attributes.  Also avoid UTF-8 characters.
9379 	     */
9380 	    i = col - wouldbe_col;
9381 	    if (i > 0)
9382 		cost += i;
9383 	    if (cost < goto_cost && i > 0)
9384 	    {
9385 		/*
9386 		 * Check if the attributes are correct without additionally
9387 		 * stopping highlighting.
9388 		 */
9389 		p = ScreenAttrs + LineOffset[row] + wouldbe_col;
9390 		while (i && *p++ == attr)
9391 		    --i;
9392 		if (i != 0)
9393 		{
9394 		    /*
9395 		     * Try if it works when highlighting is stopped here.
9396 		     */
9397 		    if (*--p == 0)
9398 		    {
9399 			cost += noinvcurs;
9400 			while (i && *p++ == 0)
9401 			    --i;
9402 		    }
9403 		    if (i != 0)
9404 			cost = 999;	/* different attributes, don't do it */
9405 		}
9406 #ifdef FEAT_MBYTE
9407 		if (enc_utf8)
9408 		{
9409 		    /* Don't use an UTF-8 char for positioning, it's slow. */
9410 		    for (i = wouldbe_col; i < col; ++i)
9411 			if (ScreenLinesUC[LineOffset[row] + i] != 0)
9412 			{
9413 			    cost = 999;
9414 			    break;
9415 			}
9416 		}
9417 #endif
9418 	    }
9419 
9420 	    /*
9421 	     * We can do it without term_windgoto()!
9422 	     */
9423 	    if (cost < goto_cost)
9424 	    {
9425 		if (plan == PLAN_LE)
9426 		{
9427 		    if (noinvcurs)
9428 			screen_stop_highlight();
9429 		    while (screen_cur_col > col)
9430 		    {
9431 			out_str(bs);
9432 			--screen_cur_col;
9433 		    }
9434 		}
9435 		else if (plan == PLAN_CR)
9436 		{
9437 		    if (noinvcurs)
9438 			screen_stop_highlight();
9439 		    out_char('\r');
9440 		    screen_cur_col = 0;
9441 		}
9442 		else if (plan == PLAN_NL)
9443 		{
9444 		    if (noinvcurs)
9445 			screen_stop_highlight();
9446 		    while (screen_cur_row < row)
9447 		    {
9448 			out_char('\n');
9449 			++screen_cur_row;
9450 		    }
9451 		    screen_cur_col = 0;
9452 		}
9453 
9454 		i = col - screen_cur_col;
9455 		if (i > 0)
9456 		{
9457 		    /*
9458 		     * Use cursor-right if it's one character only.  Avoids
9459 		     * removing a line of pixels from the last bold char, when
9460 		     * using the bold trick in the GUI.
9461 		     */
9462 		    if (T_ND[0] != NUL && T_ND[1] == NUL)
9463 		    {
9464 			while (i-- > 0)
9465 			    out_char(*T_ND);
9466 		    }
9467 		    else
9468 		    {
9469 			int	off;
9470 
9471 			off = LineOffset[row] + screen_cur_col;
9472 			while (i-- > 0)
9473 			{
9474 			    if (ScreenAttrs[off] != screen_attr)
9475 				screen_stop_highlight();
9476 #ifdef FEAT_MBYTE
9477 			    out_flush_check();
9478 #endif
9479 			    out_char(ScreenLines[off]);
9480 #ifdef FEAT_MBYTE
9481 			    if (enc_dbcs == DBCS_JPNU
9482 						  && ScreenLines[off] == 0x8e)
9483 				out_char(ScreenLines2[off]);
9484 #endif
9485 			    ++off;
9486 			}
9487 		    }
9488 		}
9489 	    }
9490 	}
9491 	else
9492 	    cost = 999;
9493 
9494 	if (cost >= goto_cost)
9495 	{
9496 	    if (noinvcurs)
9497 		screen_stop_highlight();
9498 	    if (row == screen_cur_row && (col > screen_cur_col)
9499 							     && *T_CRI != NUL)
9500 		term_cursor_right(col - screen_cur_col);
9501 	    else
9502 		term_windgoto(row, col);
9503 	}
9504 	screen_cur_row = row;
9505 	screen_cur_col = col;
9506     }
9507 }
9508 
9509 /*
9510  * Set cursor to its position in the current window.
9511  */
9512     void
9513 setcursor(void)
9514 {
9515     setcursor_mayforce(FALSE);
9516 }
9517 
9518 /*
9519  * Set cursor to its position in the current window.
9520  * When "force" is TRUE also when not redrawing.
9521  */
9522     void
9523 setcursor_mayforce(int force)
9524 {
9525     if (force || redrawing())
9526     {
9527 	validate_cursor();
9528 	windgoto(W_WINROW(curwin) + curwin->w_wrow,
9529 		curwin->w_wincol + (
9530 #ifdef FEAT_RIGHTLEFT
9531 		/* With 'rightleft' set and the cursor on a double-wide
9532 		 * character, position it on the leftmost column. */
9533 		curwin->w_p_rl ? ((int)curwin->w_width - curwin->w_wcol - (
9534 # ifdef FEAT_MBYTE
9535 			(has_mbyte
9536 			   && (*mb_ptr2cells)(ml_get_cursor()) == 2
9537 			   && vim_isprintc(gchar_cursor())) ? 2 :
9538 # endif
9539 			1)) :
9540 #endif
9541 							    curwin->w_wcol));
9542     }
9543 }
9544 
9545 
9546 /*
9547  * Insert 'line_count' lines at 'row' in window 'wp'.
9548  * If 'invalid' is TRUE the wp->w_lines[].wl_lnum is invalidated.
9549  * If 'mayclear' is TRUE the screen will be cleared if it is faster than
9550  * scrolling.
9551  * Returns FAIL if the lines are not inserted, OK for success.
9552  */
9553     int
9554 win_ins_lines(
9555     win_T	*wp,
9556     int		row,
9557     int		line_count,
9558     int		invalid,
9559     int		mayclear)
9560 {
9561     int		did_delete;
9562     int		nextrow;
9563     int		lastrow;
9564     int		retval;
9565 
9566     if (invalid)
9567 	wp->w_lines_valid = 0;
9568 
9569     if (wp->w_height < 5)
9570 	return FAIL;
9571 
9572     if (line_count > wp->w_height - row)
9573 	line_count = wp->w_height - row;
9574 
9575     retval = win_do_lines(wp, row, line_count, mayclear, FALSE, 0);
9576     if (retval != MAYBE)
9577 	return retval;
9578 
9579     /*
9580      * If there is a next window or a status line, we first try to delete the
9581      * lines at the bottom to avoid messing what is after the window.
9582      * If this fails and there are following windows, don't do anything to avoid
9583      * messing up those windows, better just redraw.
9584      */
9585     did_delete = FALSE;
9586     if (wp->w_next != NULL || wp->w_status_height)
9587     {
9588 	if (screen_del_lines(0, W_WINROW(wp) + wp->w_height - line_count,
9589 				  line_count, (int)Rows, FALSE, 0, NULL) == OK)
9590 	    did_delete = TRUE;
9591 	else if (wp->w_next)
9592 	    return FAIL;
9593     }
9594     /*
9595      * if no lines deleted, blank the lines that will end up below the window
9596      */
9597     if (!did_delete)
9598     {
9599 	wp->w_redr_status = TRUE;
9600 	redraw_cmdline = TRUE;
9601 	nextrow = W_WINROW(wp) + wp->w_height + wp->w_status_height;
9602 	lastrow = nextrow + line_count;
9603 	if (lastrow > Rows)
9604 	    lastrow = Rows;
9605 	screen_fill(nextrow - line_count, lastrow - line_count,
9606 		  wp->w_wincol, (int)W_ENDCOL(wp),
9607 		  ' ', ' ', 0);
9608     }
9609 
9610     if (screen_ins_lines(0, W_WINROW(wp) + row, line_count, (int)Rows, 0, NULL)
9611 								      == FAIL)
9612     {
9613 	    /* deletion will have messed up other windows */
9614 	if (did_delete)
9615 	{
9616 	    wp->w_redr_status = TRUE;
9617 	    win_rest_invalid(W_NEXT(wp));
9618 	}
9619 	return FAIL;
9620     }
9621 
9622     return OK;
9623 }
9624 
9625 /*
9626  * Delete "line_count" window lines at "row" in window "wp".
9627  * If "invalid" is TRUE curwin->w_lines[] is invalidated.
9628  * If "mayclear" is TRUE the screen will be cleared if it is faster than
9629  * scrolling
9630  * Return OK for success, FAIL if the lines are not deleted.
9631  */
9632     int
9633 win_del_lines(
9634     win_T	*wp,
9635     int		row,
9636     int		line_count,
9637     int		invalid,
9638     int		mayclear,
9639     int		clear_attr)	    /* for clearing lines */
9640 {
9641     int		retval;
9642 
9643     if (invalid)
9644 	wp->w_lines_valid = 0;
9645 
9646     if (line_count > wp->w_height - row)
9647 	line_count = wp->w_height - row;
9648 
9649     retval = win_do_lines(wp, row, line_count, mayclear, TRUE, clear_attr);
9650     if (retval != MAYBE)
9651 	return retval;
9652 
9653     if (screen_del_lines(0, W_WINROW(wp) + row, line_count,
9654 				   (int)Rows, FALSE, clear_attr, NULL) == FAIL)
9655 	return FAIL;
9656 
9657     /*
9658      * If there are windows or status lines below, try to put them at the
9659      * correct place. If we can't do that, they have to be redrawn.
9660      */
9661     if (wp->w_next || wp->w_status_height || cmdline_row < Rows - 1)
9662     {
9663 	if (screen_ins_lines(0, W_WINROW(wp) + wp->w_height - line_count,
9664 			      line_count, (int)Rows, clear_attr, NULL) == FAIL)
9665 	{
9666 	    wp->w_redr_status = TRUE;
9667 	    win_rest_invalid(wp->w_next);
9668 	}
9669     }
9670     /*
9671      * If this is the last window and there is no status line, redraw the
9672      * command line later.
9673      */
9674     else
9675 	redraw_cmdline = TRUE;
9676     return OK;
9677 }
9678 
9679 /*
9680  * Common code for win_ins_lines() and win_del_lines().
9681  * Returns OK or FAIL when the work has been done.
9682  * Returns MAYBE when not finished yet.
9683  */
9684     static int
9685 win_do_lines(
9686     win_T	*wp,
9687     int		row,
9688     int		line_count,
9689     int		mayclear,
9690     int		del,
9691     int		clear_attr)
9692 {
9693     int		retval;
9694 
9695     if (!redrawing() || line_count <= 0)
9696 	return FAIL;
9697 
9698     /* When inserting lines would result in loss of command output, just redraw
9699      * the lines. */
9700     if (no_win_do_lines_ins && !del)
9701 	return FAIL;
9702 
9703     /* only a few lines left: redraw is faster */
9704     if (mayclear && Rows - line_count < 5 && wp->w_width == Columns)
9705     {
9706 	if (!no_win_do_lines_ins)
9707 	    screenclear();	    /* will set wp->w_lines_valid to 0 */
9708 	return FAIL;
9709     }
9710 
9711     /*
9712      * Delete all remaining lines
9713      */
9714     if (row + line_count >= wp->w_height)
9715     {
9716 	screen_fill(W_WINROW(wp) + row, W_WINROW(wp) + wp->w_height,
9717 		wp->w_wincol, (int)W_ENDCOL(wp),
9718 		' ', ' ', 0);
9719 	return OK;
9720     }
9721 
9722     /*
9723      * When scrolling, the message on the command line should be cleared,
9724      * otherwise it will stay there forever.
9725      * Don't do this when avoiding to insert lines.
9726      */
9727     if (!no_win_do_lines_ins)
9728 	clear_cmdline = TRUE;
9729 
9730     /*
9731      * If the terminal can set a scroll region, use that.
9732      * Always do this in a vertically split window.  This will redraw from
9733      * ScreenLines[] when t_CV isn't defined.  That's faster than using
9734      * win_line().
9735      * Don't use a scroll region when we are going to redraw the text, writing
9736      * a character in the lower right corner of the scroll region may cause a
9737      * scroll-up .
9738      */
9739     if (scroll_region || wp->w_width != Columns)
9740     {
9741 	if (scroll_region && (wp->w_width == Columns || *T_CSV != NUL))
9742 	    scroll_region_set(wp, row);
9743 	if (del)
9744 	    retval = screen_del_lines(W_WINROW(wp) + row, 0, line_count,
9745 				    wp->w_height - row, FALSE, clear_attr, wp);
9746 	else
9747 	    retval = screen_ins_lines(W_WINROW(wp) + row, 0, line_count,
9748 					   wp->w_height - row, clear_attr, wp);
9749 	if (scroll_region && (wp->w_width == Columns || *T_CSV != NUL))
9750 	    scroll_region_reset();
9751 	return retval;
9752     }
9753 
9754     if (wp->w_next != NULL && p_tf) /* don't delete/insert on fast terminal */
9755 	return FAIL;
9756 
9757     return MAYBE;
9758 }
9759 
9760 /*
9761  * window 'wp' and everything after it is messed up, mark it for redraw
9762  */
9763     static void
9764 win_rest_invalid(win_T *wp)
9765 {
9766     while (wp != NULL)
9767     {
9768 	redraw_win_later(wp, NOT_VALID);
9769 	wp->w_redr_status = TRUE;
9770 	wp = wp->w_next;
9771     }
9772     redraw_cmdline = TRUE;
9773 }
9774 
9775 /*
9776  * The rest of the routines in this file perform screen manipulations. The
9777  * given operation is performed physically on the screen. The corresponding
9778  * change is also made to the internal screen image. In this way, the editor
9779  * anticipates the effect of editing changes on the appearance of the screen.
9780  * That way, when we call screenupdate a complete redraw isn't usually
9781  * necessary. Another advantage is that we can keep adding code to anticipate
9782  * screen changes, and in the meantime, everything still works.
9783  */
9784 
9785 /*
9786  * types for inserting or deleting lines
9787  */
9788 #define USE_T_CAL   1
9789 #define USE_T_CDL   2
9790 #define USE_T_AL    3
9791 #define USE_T_CE    4
9792 #define USE_T_DL    5
9793 #define USE_T_SR    6
9794 #define USE_NL	    7
9795 #define USE_T_CD    8
9796 #define USE_REDRAW  9
9797 
9798 /*
9799  * insert lines on the screen and update ScreenLines[]
9800  * 'end' is the line after the scrolled part. Normally it is Rows.
9801  * When scrolling region used 'off' is the offset from the top for the region.
9802  * 'row' and 'end' are relative to the start of the region.
9803  *
9804  * return FAIL for failure, OK for success.
9805  */
9806     int
9807 screen_ins_lines(
9808     int		off,
9809     int		row,
9810     int		line_count,
9811     int		end,
9812     int		clear_attr,
9813     win_T	*wp)	    /* NULL or window to use width from */
9814 {
9815     int		i;
9816     int		j;
9817     unsigned	temp;
9818     int		cursor_row;
9819     int		cursor_col = 0;
9820     int		type;
9821     int		result_empty;
9822     int		can_ce = can_clear(T_CE);
9823 
9824     /*
9825      * FAIL if
9826      * - there is no valid screen
9827      * - the screen has to be redrawn completely
9828      * - the line count is less than one
9829      * - the line count is more than 'ttyscroll'
9830      * - redrawing for a callback and there is a modeless selection
9831      */
9832      if (!screen_valid(TRUE) || line_count <= 0 || line_count > p_ttyscroll
9833 #ifdef FEAT_CLIPBOARD
9834 	     || (clip_star.state != SELECT_CLEARED
9835 						 && redrawing_for_callback > 0)
9836 #endif
9837 	     )
9838 	return FAIL;
9839 
9840     /*
9841      * There are seven ways to insert lines:
9842      * 0. When in a vertically split window and t_CV isn't set, redraw the
9843      *    characters from ScreenLines[].
9844      * 1. Use T_CD (clear to end of display) if it exists and the result of
9845      *	  the insert is just empty lines
9846      * 2. Use T_CAL (insert multiple lines) if it exists and T_AL is not
9847      *	  present or line_count > 1. It looks better if we do all the inserts
9848      *	  at once.
9849      * 3. Use T_CDL (delete multiple lines) if it exists and the result of the
9850      *	  insert is just empty lines and T_CE is not present or line_count >
9851      *	  1.
9852      * 4. Use T_AL (insert line) if it exists.
9853      * 5. Use T_CE (erase line) if it exists and the result of the insert is
9854      *	  just empty lines.
9855      * 6. Use T_DL (delete line) if it exists and the result of the insert is
9856      *	  just empty lines.
9857      * 7. Use T_SR (scroll reverse) if it exists and inserting at row 0 and
9858      *	  the 'da' flag is not set or we have clear line capability.
9859      * 8. redraw the characters from ScreenLines[].
9860      *
9861      * Careful: In a hpterm scroll reverse doesn't work as expected, it moves
9862      * the scrollbar for the window. It does have insert line, use that if it
9863      * exists.
9864      */
9865     result_empty = (row + line_count >= end);
9866     if (wp != NULL && wp->w_width != Columns && *T_CSV == NUL)
9867 	type = USE_REDRAW;
9868     else if (can_clear(T_CD) && result_empty)
9869 	type = USE_T_CD;
9870     else if (*T_CAL != NUL && (line_count > 1 || *T_AL == NUL))
9871 	type = USE_T_CAL;
9872     else if (*T_CDL != NUL && result_empty && (line_count > 1 || !can_ce))
9873 	type = USE_T_CDL;
9874     else if (*T_AL != NUL)
9875 	type = USE_T_AL;
9876     else if (can_ce && result_empty)
9877 	type = USE_T_CE;
9878     else if (*T_DL != NUL && result_empty)
9879 	type = USE_T_DL;
9880     else if (*T_SR != NUL && row == 0 && (*T_DA == NUL || can_ce))
9881 	type = USE_T_SR;
9882     else
9883 	return FAIL;
9884 
9885     /*
9886      * For clearing the lines screen_del_lines() is used. This will also take
9887      * care of t_db if necessary.
9888      */
9889     if (type == USE_T_CD || type == USE_T_CDL ||
9890 					 type == USE_T_CE || type == USE_T_DL)
9891 	return screen_del_lines(off, row, line_count, end, FALSE, 0, wp);
9892 
9893     /*
9894      * If text is retained below the screen, first clear or delete as many
9895      * lines at the bottom of the window as are about to be inserted so that
9896      * the deleted lines won't later surface during a screen_del_lines.
9897      */
9898     if (*T_DB)
9899 	screen_del_lines(off, end - line_count, line_count, end, FALSE, 0, wp);
9900 
9901 #ifdef FEAT_CLIPBOARD
9902     /* Remove a modeless selection when inserting lines halfway the screen
9903      * or not the full width of the screen. */
9904     if (off + row > 0 || (wp != NULL && wp->w_width != Columns))
9905 	clip_clear_selection(&clip_star);
9906     else
9907 	clip_scroll_selection(-line_count);
9908 #endif
9909 
9910 #ifdef FEAT_GUI
9911     /* Don't update the GUI cursor here, ScreenLines[] is invalid until the
9912      * scrolling is actually carried out. */
9913     gui_dont_update_cursor(row + off <= gui.cursor_row);
9914 #endif
9915 
9916     if (wp != NULL && wp->w_wincol != 0 && *T_CSV != NUL && *T_CCS == NUL)
9917 	cursor_col = wp->w_wincol;
9918 
9919     if (*T_CCS != NUL)	   /* cursor relative to region */
9920 	cursor_row = row;
9921     else
9922 	cursor_row = row + off;
9923 
9924     /*
9925      * Shift LineOffset[] line_count down to reflect the inserted lines.
9926      * Clear the inserted lines in ScreenLines[].
9927      */
9928     row += off;
9929     end += off;
9930     for (i = 0; i < line_count; ++i)
9931     {
9932 	if (wp != NULL && wp->w_width != Columns)
9933 	{
9934 	    /* need to copy part of a line */
9935 	    j = end - 1 - i;
9936 	    while ((j -= line_count) >= row)
9937 		linecopy(j + line_count, j, wp);
9938 	    j += line_count;
9939 	    if (can_clear((char_u *)" "))
9940 		lineclear(LineOffset[j] + wp->w_wincol, wp->w_width,
9941 								   clear_attr);
9942 	    else
9943 		lineinvalid(LineOffset[j] + wp->w_wincol, wp->w_width);
9944 	    LineWraps[j] = FALSE;
9945 	}
9946 	else
9947 	{
9948 	    j = end - 1 - i;
9949 	    temp = LineOffset[j];
9950 	    while ((j -= line_count) >= row)
9951 	    {
9952 		LineOffset[j + line_count] = LineOffset[j];
9953 		LineWraps[j + line_count] = LineWraps[j];
9954 	    }
9955 	    LineOffset[j + line_count] = temp;
9956 	    LineWraps[j + line_count] = FALSE;
9957 	    if (can_clear((char_u *)" "))
9958 		lineclear(temp, (int)Columns, clear_attr);
9959 	    else
9960 		lineinvalid(temp, (int)Columns);
9961 	}
9962     }
9963 
9964     screen_stop_highlight();
9965     windgoto(cursor_row, cursor_col);
9966     if (clear_attr != 0)
9967 	screen_start_highlight(clear_attr);
9968 
9969     /* redraw the characters */
9970     if (type == USE_REDRAW)
9971 	redraw_block(row, end, wp);
9972     else if (type == USE_T_CAL)
9973     {
9974 	term_append_lines(line_count);
9975 	screen_start();		/* don't know where cursor is now */
9976     }
9977     else
9978     {
9979 	for (i = 0; i < line_count; i++)
9980 	{
9981 	    if (type == USE_T_AL)
9982 	    {
9983 		if (i && cursor_row != 0)
9984 		    windgoto(cursor_row, cursor_col);
9985 		out_str(T_AL);
9986 	    }
9987 	    else  /* type == USE_T_SR */
9988 		out_str(T_SR);
9989 	    screen_start();	    /* don't know where cursor is now */
9990 	}
9991     }
9992 
9993     /*
9994      * With scroll-reverse and 'da' flag set we need to clear the lines that
9995      * have been scrolled down into the region.
9996      */
9997     if (type == USE_T_SR && *T_DA)
9998     {
9999 	for (i = 0; i < line_count; ++i)
10000 	{
10001 	    windgoto(off + i, cursor_col);
10002 	    out_str(T_CE);
10003 	    screen_start();	    /* don't know where cursor is now */
10004 	}
10005     }
10006 
10007 #ifdef FEAT_GUI
10008     gui_can_update_cursor();
10009     if (gui.in_use)
10010 	out_flush();	/* always flush after a scroll */
10011 #endif
10012     return OK;
10013 }
10014 
10015 /*
10016  * Delete lines on the screen and update ScreenLines[].
10017  * "end" is the line after the scrolled part. Normally it is Rows.
10018  * When scrolling region used "off" is the offset from the top for the region.
10019  * "row" and "end" are relative to the start of the region.
10020  *
10021  * Return OK for success, FAIL if the lines are not deleted.
10022  */
10023     int
10024 screen_del_lines(
10025     int		off,
10026     int		row,
10027     int		line_count,
10028     int		end,
10029     int		force,		/* even when line_count > p_ttyscroll */
10030     int		clear_attr,	/* used for clearing lines */
10031     win_T	*wp UNUSED)	/* NULL or window to use width from */
10032 {
10033     int		j;
10034     int		i;
10035     unsigned	temp;
10036     int		cursor_row;
10037     int		cursor_col = 0;
10038     int		cursor_end;
10039     int		result_empty;	/* result is empty until end of region */
10040     int		can_delete;	/* deleting line codes can be used */
10041     int		type;
10042 
10043     /*
10044      * FAIL if
10045      * - there is no valid screen
10046      * - the screen has to be redrawn completely
10047      * - the line count is less than one
10048      * - the line count is more than 'ttyscroll'
10049      * - redrawing for a callback and there is a modeless selection
10050      */
10051     if (!screen_valid(TRUE) || line_count <= 0
10052 					|| (!force && line_count > p_ttyscroll)
10053 #ifdef FEAT_CLIPBOARD
10054 	     || (clip_star.state != SELECT_CLEARED
10055 						 && redrawing_for_callback > 0)
10056 #endif
10057        )
10058 	return FAIL;
10059 
10060     /*
10061      * Check if the rest of the current region will become empty.
10062      */
10063     result_empty = row + line_count >= end;
10064 
10065     /*
10066      * We can delete lines only when 'db' flag not set or when 'ce' option
10067      * available.
10068      */
10069     can_delete = (*T_DB == NUL || can_clear(T_CE));
10070 
10071     /*
10072      * There are six ways to delete lines:
10073      * 0. When in a vertically split window and t_CV isn't set, redraw the
10074      *    characters from ScreenLines[].
10075      * 1. Use T_CD if it exists and the result is empty.
10076      * 2. Use newlines if row == 0 and count == 1 or T_CDL does not exist.
10077      * 3. Use T_CDL (delete multiple lines) if it exists and line_count > 1 or
10078      *	  none of the other ways work.
10079      * 4. Use T_CE (erase line) if the result is empty.
10080      * 5. Use T_DL (delete line) if it exists.
10081      * 6. redraw the characters from ScreenLines[].
10082      */
10083     if (wp != NULL && wp->w_width != Columns && *T_CSV == NUL)
10084 	type = USE_REDRAW;
10085     else if (can_clear(T_CD) && result_empty)
10086 	type = USE_T_CD;
10087 #if defined(__BEOS__) && defined(BEOS_DR8)
10088     /*
10089      * USE_NL does not seem to work in Terminal of DR8 so we set T_DB="" in
10090      * its internal termcap... this works okay for tests which test *T_DB !=
10091      * NUL.  It has the disadvantage that the user cannot use any :set t_*
10092      * command to get T_DB (back) to empty_option, only :set term=... will do
10093      * the trick...
10094      * Anyway, this hack will hopefully go away with the next OS release.
10095      * (Olaf Seibert)
10096      */
10097     else if (row == 0 && T_DB == empty_option
10098 					&& (line_count == 1 || *T_CDL == NUL))
10099 #else
10100     else if (row == 0 && (
10101 #ifndef AMIGA
10102 	/* On the Amiga, somehow '\n' on the last line doesn't always scroll
10103 	 * up, so use delete-line command */
10104 			    line_count == 1 ||
10105 #endif
10106 						*T_CDL == NUL))
10107 #endif
10108 	type = USE_NL;
10109     else if (*T_CDL != NUL && line_count > 1 && can_delete)
10110 	type = USE_T_CDL;
10111     else if (can_clear(T_CE) && result_empty
10112 	    && (wp == NULL || wp->w_width == Columns))
10113 	type = USE_T_CE;
10114     else if (*T_DL != NUL && can_delete)
10115 	type = USE_T_DL;
10116     else if (*T_CDL != NUL && can_delete)
10117 	type = USE_T_CDL;
10118     else
10119 	return FAIL;
10120 
10121 #ifdef FEAT_CLIPBOARD
10122     /* Remove a modeless selection when deleting lines halfway the screen or
10123      * not the full width of the screen. */
10124     if (off + row > 0 || (wp != NULL && wp->w_width != Columns))
10125 	clip_clear_selection(&clip_star);
10126     else
10127 	clip_scroll_selection(line_count);
10128 #endif
10129 
10130 #ifdef FEAT_GUI
10131     /* Don't update the GUI cursor here, ScreenLines[] is invalid until the
10132      * scrolling is actually carried out. */
10133     gui_dont_update_cursor(gui.cursor_row >= row + off
10134 						&& gui.cursor_row < end + off);
10135 #endif
10136 
10137     if (wp != NULL && wp->w_wincol != 0 && *T_CSV != NUL && *T_CCS == NUL)
10138 	cursor_col = wp->w_wincol;
10139 
10140     if (*T_CCS != NUL)	    /* cursor relative to region */
10141     {
10142 	cursor_row = row;
10143 	cursor_end = end;
10144     }
10145     else
10146     {
10147 	cursor_row = row + off;
10148 	cursor_end = end + off;
10149     }
10150 
10151     /*
10152      * Now shift LineOffset[] line_count up to reflect the deleted lines.
10153      * Clear the inserted lines in ScreenLines[].
10154      */
10155     row += off;
10156     end += off;
10157     for (i = 0; i < line_count; ++i)
10158     {
10159 	if (wp != NULL && wp->w_width != Columns)
10160 	{
10161 	    /* need to copy part of a line */
10162 	    j = row + i;
10163 	    while ((j += line_count) <= end - 1)
10164 		linecopy(j - line_count, j, wp);
10165 	    j -= line_count;
10166 	    if (can_clear((char_u *)" "))
10167 		lineclear(LineOffset[j] + wp->w_wincol, wp->w_width,
10168 								   clear_attr);
10169 	    else
10170 		lineinvalid(LineOffset[j] + wp->w_wincol, wp->w_width);
10171 	    LineWraps[j] = FALSE;
10172 	}
10173 	else
10174 	{
10175 	    /* whole width, moving the line pointers is faster */
10176 	    j = row + i;
10177 	    temp = LineOffset[j];
10178 	    while ((j += line_count) <= end - 1)
10179 	    {
10180 		LineOffset[j - line_count] = LineOffset[j];
10181 		LineWraps[j - line_count] = LineWraps[j];
10182 	    }
10183 	    LineOffset[j - line_count] = temp;
10184 	    LineWraps[j - line_count] = FALSE;
10185 	    if (can_clear((char_u *)" "))
10186 		lineclear(temp, (int)Columns, clear_attr);
10187 	    else
10188 		lineinvalid(temp, (int)Columns);
10189 	}
10190     }
10191 
10192     if (screen_attr != clear_attr)
10193 	screen_stop_highlight();
10194     if (clear_attr != 0)
10195 	screen_start_highlight(clear_attr);
10196 
10197     /* redraw the characters */
10198     if (type == USE_REDRAW)
10199 	redraw_block(row, end, wp);
10200     else if (type == USE_T_CD)	/* delete the lines */
10201     {
10202 	windgoto(cursor_row, cursor_col);
10203 	out_str(T_CD);
10204 	screen_start();			/* don't know where cursor is now */
10205     }
10206     else if (type == USE_T_CDL)
10207     {
10208 	windgoto(cursor_row, cursor_col);
10209 	term_delete_lines(line_count);
10210 	screen_start();			/* don't know where cursor is now */
10211     }
10212     /*
10213      * Deleting lines at top of the screen or scroll region: Just scroll
10214      * the whole screen (scroll region) up by outputting newlines on the
10215      * last line.
10216      */
10217     else if (type == USE_NL)
10218     {
10219 	windgoto(cursor_end - 1, cursor_col);
10220 	for (i = line_count; --i >= 0; )
10221 	    out_char('\n');		/* cursor will remain on same line */
10222     }
10223     else
10224     {
10225 	for (i = line_count; --i >= 0; )
10226 	{
10227 	    if (type == USE_T_DL)
10228 	    {
10229 		windgoto(cursor_row, cursor_col);
10230 		out_str(T_DL);		/* delete a line */
10231 	    }
10232 	    else /* type == USE_T_CE */
10233 	    {
10234 		windgoto(cursor_row + i, cursor_col);
10235 		out_str(T_CE);		/* erase a line */
10236 	    }
10237 	    screen_start();		/* don't know where cursor is now */
10238 	}
10239     }
10240 
10241     /*
10242      * If the 'db' flag is set, we need to clear the lines that have been
10243      * scrolled up at the bottom of the region.
10244      */
10245     if (*T_DB && (type == USE_T_DL || type == USE_T_CDL))
10246     {
10247 	for (i = line_count; i > 0; --i)
10248 	{
10249 	    windgoto(cursor_end - i, cursor_col);
10250 	    out_str(T_CE);		/* erase a line */
10251 	    screen_start();		/* don't know where cursor is now */
10252 	}
10253     }
10254 
10255 #ifdef FEAT_GUI
10256     gui_can_update_cursor();
10257     if (gui.in_use)
10258 	out_flush();	/* always flush after a scroll */
10259 #endif
10260 
10261     return OK;
10262 }
10263 
10264 /*
10265  * Show the current mode and ruler.
10266  *
10267  * If clear_cmdline is TRUE, clear the rest of the cmdline.
10268  * If clear_cmdline is FALSE there may be a message there that needs to be
10269  * cleared only if a mode is shown.
10270  * Return the length of the message (0 if no message).
10271  */
10272     int
10273 showmode(void)
10274 {
10275     int		need_clear;
10276     int		length = 0;
10277     int		do_mode;
10278     int		attr;
10279     int		nwr_save;
10280 #ifdef FEAT_INS_EXPAND
10281     int		sub_attr;
10282 #endif
10283 
10284     do_mode = ((p_smd && msg_silent == 0)
10285 	    && ((State & INSERT)
10286 		|| restart_edit != NUL
10287 		|| VIsual_active));
10288     if (do_mode || reg_recording != 0)
10289     {
10290 	/*
10291 	 * Don't show mode right now, when not redrawing or inside a mapping.
10292 	 * Call char_avail() only when we are going to show something, because
10293 	 * it takes a bit of time.
10294 	 */
10295 	if (!redrawing() || (char_avail() && !KeyTyped) || msg_silent != 0)
10296 	{
10297 	    redraw_cmdline = TRUE;		/* show mode later */
10298 	    return 0;
10299 	}
10300 
10301 	nwr_save = need_wait_return;
10302 
10303 	/* wait a bit before overwriting an important message */
10304 	check_for_delay(FALSE);
10305 
10306 	/* if the cmdline is more than one line high, erase top lines */
10307 	need_clear = clear_cmdline;
10308 	if (clear_cmdline && cmdline_row < Rows - 1)
10309 	    msg_clr_cmdline();			/* will reset clear_cmdline */
10310 
10311 	/* Position on the last line in the window, column 0 */
10312 	msg_pos_mode();
10313 	cursor_off();
10314 	attr = HL_ATTR(HLF_CM);			/* Highlight mode */
10315 	if (do_mode)
10316 	{
10317 	    MSG_PUTS_ATTR("--", attr);
10318 #if defined(FEAT_XIM)
10319 	    if (
10320 # ifdef FEAT_GUI_GTK
10321 		    preedit_get_status()
10322 # else
10323 		    im_get_status()
10324 # endif
10325 	       )
10326 # ifdef FEAT_GUI_GTK /* most of the time, it's not XIM being used */
10327 		MSG_PUTS_ATTR(" IM", attr);
10328 # else
10329 		MSG_PUTS_ATTR(" XIM", attr);
10330 # endif
10331 #endif
10332 #if defined(FEAT_HANGULIN) && defined(FEAT_GUI)
10333 	    if (gui.in_use)
10334 	    {
10335 		if (hangul_input_state_get())
10336 		{
10337 		    /* HANGUL */
10338 		    if (enc_utf8)
10339 			MSG_PUTS_ATTR(" \355\225\234\352\270\200", attr);
10340 		    else
10341 			MSG_PUTS_ATTR(" \307\321\261\333", attr);
10342 		}
10343 	    }
10344 #endif
10345 #ifdef FEAT_INS_EXPAND
10346 	    /* CTRL-X in Insert mode */
10347 	    if (edit_submode != NULL && !shortmess(SHM_COMPLETIONMENU))
10348 	    {
10349 		/* These messages can get long, avoid a wrap in a narrow
10350 		 * window.  Prefer showing edit_submode_extra. */
10351 		length = (Rows - msg_row) * Columns - 3;
10352 		if (edit_submode_extra != NULL)
10353 		    length -= vim_strsize(edit_submode_extra);
10354 		if (length > 0)
10355 		{
10356 		    if (edit_submode_pre != NULL)
10357 			length -= vim_strsize(edit_submode_pre);
10358 		    if (length - vim_strsize(edit_submode) > 0)
10359 		    {
10360 			if (edit_submode_pre != NULL)
10361 			    msg_puts_attr(edit_submode_pre, attr);
10362 			msg_puts_attr(edit_submode, attr);
10363 		    }
10364 		    if (edit_submode_extra != NULL)
10365 		    {
10366 			MSG_PUTS_ATTR(" ", attr);  /* add a space in between */
10367 			if ((int)edit_submode_highl < (int)HLF_COUNT)
10368 			    sub_attr = HL_ATTR(edit_submode_highl);
10369 			else
10370 			    sub_attr = attr;
10371 			msg_puts_attr(edit_submode_extra, sub_attr);
10372 		    }
10373 		}
10374 	    }
10375 	    else
10376 #endif
10377 	    {
10378 #ifdef FEAT_VREPLACE
10379 		if (State & VREPLACE_FLAG)
10380 		    MSG_PUTS_ATTR(_(" VREPLACE"), attr);
10381 		else
10382 #endif
10383 		    if (State & REPLACE_FLAG)
10384 		    MSG_PUTS_ATTR(_(" REPLACE"), attr);
10385 		else if (State & INSERT)
10386 		{
10387 #ifdef FEAT_RIGHTLEFT
10388 		    if (p_ri)
10389 			MSG_PUTS_ATTR(_(" REVERSE"), attr);
10390 #endif
10391 		    MSG_PUTS_ATTR(_(" INSERT"), attr);
10392 		}
10393 		else if (restart_edit == 'I' || restart_edit == 'A')
10394 		    MSG_PUTS_ATTR(_(" (insert)"), attr);
10395 		else if (restart_edit == 'R')
10396 		    MSG_PUTS_ATTR(_(" (replace)"), attr);
10397 		else if (restart_edit == 'V')
10398 		    MSG_PUTS_ATTR(_(" (vreplace)"), attr);
10399 #ifdef FEAT_RIGHTLEFT
10400 		if (p_hkmap)
10401 		    MSG_PUTS_ATTR(_(" Hebrew"), attr);
10402 # ifdef FEAT_FKMAP
10403 		if (p_fkmap)
10404 		    MSG_PUTS_ATTR(farsi_text_5, attr);
10405 # endif
10406 #endif
10407 #ifdef FEAT_KEYMAP
10408 		if (State & LANGMAP)
10409 		{
10410 # ifdef FEAT_ARABIC
10411 		    if (curwin->w_p_arab)
10412 			MSG_PUTS_ATTR(_(" Arabic"), attr);
10413 		    else
10414 # endif
10415 			if (get_keymap_str(curwin, (char_u *)" (%s)",
10416 							   NameBuff, MAXPATHL))
10417 			    MSG_PUTS_ATTR(NameBuff, attr);
10418 		}
10419 #endif
10420 		if ((State & INSERT) && p_paste)
10421 		    MSG_PUTS_ATTR(_(" (paste)"), attr);
10422 
10423 		if (VIsual_active)
10424 		{
10425 		    char *p;
10426 
10427 		    /* Don't concatenate separate words to avoid translation
10428 		     * problems. */
10429 		    switch ((VIsual_select ? 4 : 0)
10430 			    + (VIsual_mode == Ctrl_V) * 2
10431 			    + (VIsual_mode == 'V'))
10432 		    {
10433 			case 0:	p = N_(" VISUAL"); break;
10434 			case 1: p = N_(" VISUAL LINE"); break;
10435 			case 2: p = N_(" VISUAL BLOCK"); break;
10436 			case 4: p = N_(" SELECT"); break;
10437 			case 5: p = N_(" SELECT LINE"); break;
10438 			default: p = N_(" SELECT BLOCK"); break;
10439 		    }
10440 		    MSG_PUTS_ATTR(_(p), attr);
10441 		}
10442 		MSG_PUTS_ATTR(" --", attr);
10443 	    }
10444 
10445 	    need_clear = TRUE;
10446 	}
10447 	if (reg_recording != 0
10448 #ifdef FEAT_INS_EXPAND
10449 		&& edit_submode == NULL	    /* otherwise it gets too long */
10450 #endif
10451 		)
10452 	{
10453 	    recording_mode(attr);
10454 	    need_clear = TRUE;
10455 	}
10456 
10457 	mode_displayed = TRUE;
10458 	if (need_clear || clear_cmdline)
10459 	    msg_clr_eos();
10460 	msg_didout = FALSE;		/* overwrite this message */
10461 	length = msg_col;
10462 	msg_col = 0;
10463 	need_wait_return = nwr_save;	/* never ask for hit-return for this */
10464     }
10465     else if (clear_cmdline && msg_silent == 0)
10466 	/* Clear the whole command line.  Will reset "clear_cmdline". */
10467 	msg_clr_cmdline();
10468 
10469 #ifdef FEAT_CMDL_INFO
10470     /* In Visual mode the size of the selected area must be redrawn. */
10471     if (VIsual_active)
10472 	clear_showcmd();
10473 
10474     /* If the last window has no status line, the ruler is after the mode
10475      * message and must be redrawn */
10476     if (redrawing() && lastwin->w_status_height == 0)
10477 	win_redr_ruler(lastwin, TRUE, FALSE);
10478 #endif
10479     redraw_cmdline = FALSE;
10480     clear_cmdline = FALSE;
10481 
10482     return length;
10483 }
10484 
10485 /*
10486  * Position for a mode message.
10487  */
10488     static void
10489 msg_pos_mode(void)
10490 {
10491     msg_col = 0;
10492     msg_row = Rows - 1;
10493 }
10494 
10495 /*
10496  * Delete mode message.  Used when ESC is typed which is expected to end
10497  * Insert mode (but Insert mode didn't end yet!).
10498  * Caller should check "mode_displayed".
10499  */
10500     void
10501 unshowmode(int force)
10502 {
10503     /*
10504      * Don't delete it right now, when not redrawing or inside a mapping.
10505      */
10506     if (!redrawing() || (!force && char_avail() && !KeyTyped))
10507 	redraw_cmdline = TRUE;		/* delete mode later */
10508     else
10509 	clearmode();
10510 }
10511 
10512 /*
10513  * Clear the mode message.
10514  */
10515     void
10516 clearmode(void)
10517 {
10518     int save_msg_row = msg_row;
10519     int save_msg_col = msg_col;
10520 
10521     msg_pos_mode();
10522     if (reg_recording != 0)
10523 	recording_mode(HL_ATTR(HLF_CM));
10524     msg_clr_eos();
10525 
10526     msg_col = save_msg_col;
10527     msg_row = save_msg_row;
10528 }
10529 
10530     static void
10531 recording_mode(int attr)
10532 {
10533     MSG_PUTS_ATTR(_("recording"), attr);
10534     if (!shortmess(SHM_RECORDING))
10535     {
10536 	char_u s[4];
10537 	sprintf((char *)s, " @%c", reg_recording);
10538 	MSG_PUTS_ATTR(s, attr);
10539     }
10540 }
10541 
10542 /*
10543  * Draw the tab pages line at the top of the Vim window.
10544  */
10545     static void
10546 draw_tabline(void)
10547 {
10548     int		tabcount = 0;
10549     tabpage_T	*tp;
10550     int		tabwidth;
10551     int		col = 0;
10552     int		scol = 0;
10553     int		attr;
10554     win_T	*wp;
10555     win_T	*cwp;
10556     int		wincount;
10557     int		modified;
10558     int		c;
10559     int		len;
10560     int		attr_sel = HL_ATTR(HLF_TPS);
10561     int		attr_nosel = HL_ATTR(HLF_TP);
10562     int		attr_fill = HL_ATTR(HLF_TPF);
10563     char_u	*p;
10564     int		room;
10565     int		use_sep_chars = (t_colors < 8
10566 #ifdef FEAT_GUI
10567 					    && !gui.in_use
10568 #endif
10569 #ifdef FEAT_TERMGUICOLORS
10570 					    && !p_tgc
10571 #endif
10572 					    );
10573 
10574     if (ScreenLines == NULL)
10575 	return;
10576     redraw_tabline = FALSE;
10577 
10578 #ifdef FEAT_GUI_TABLINE
10579     /* Take care of a GUI tabline. */
10580     if (gui_use_tabline())
10581     {
10582 	gui_update_tabline();
10583 	return;
10584     }
10585 #endif
10586 
10587     if (tabline_height() < 1)
10588 	return;
10589 
10590 #if defined(FEAT_STL_OPT)
10591 
10592     /* Init TabPageIdxs[] to zero: Clicking outside of tabs has no effect. */
10593     for (scol = 0; scol < Columns; ++scol)
10594 	TabPageIdxs[scol] = 0;
10595 
10596     /* Use the 'tabline' option if it's set. */
10597     if (*p_tal != NUL)
10598     {
10599 	int	saved_did_emsg = did_emsg;
10600 
10601 	/* Check for an error.  If there is one we would loop in redrawing the
10602 	 * screen.  Avoid that by making 'tabline' empty. */
10603 	did_emsg = FALSE;
10604 	win_redr_custom(NULL, FALSE);
10605 	if (did_emsg)
10606 	    set_string_option_direct((char_u *)"tabline", -1,
10607 					   (char_u *)"", OPT_FREE, SID_ERROR);
10608 	did_emsg |= saved_did_emsg;
10609     }
10610     else
10611 #endif
10612     {
10613 	FOR_ALL_TABPAGES(tp)
10614 	    ++tabcount;
10615 
10616 	tabwidth = (Columns - 1 + tabcount / 2) / tabcount;
10617 	if (tabwidth < 6)
10618 	    tabwidth = 6;
10619 
10620 	attr = attr_nosel;
10621 	tabcount = 0;
10622 	scol = 0;
10623 	for (tp = first_tabpage; tp != NULL && col < Columns - 4;
10624 							     tp = tp->tp_next)
10625 	{
10626 	    scol = col;
10627 
10628 	    if (tp->tp_topframe == topframe)
10629 		attr = attr_sel;
10630 	    if (use_sep_chars && col > 0)
10631 		screen_putchar('|', 0, col++, attr);
10632 
10633 	    if (tp->tp_topframe != topframe)
10634 		attr = attr_nosel;
10635 
10636 	    screen_putchar(' ', 0, col++, attr);
10637 
10638 	    if (tp == curtab)
10639 	    {
10640 		cwp = curwin;
10641 		wp = firstwin;
10642 	    }
10643 	    else
10644 	    {
10645 		cwp = tp->tp_curwin;
10646 		wp = tp->tp_firstwin;
10647 	    }
10648 
10649 	    modified = FALSE;
10650 	    for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount)
10651 		if (bufIsChanged(wp->w_buffer))
10652 		    modified = TRUE;
10653 	    if (modified || wincount > 1)
10654 	    {
10655 		if (wincount > 1)
10656 		{
10657 		    vim_snprintf((char *)NameBuff, MAXPATHL, "%d", wincount);
10658 		    len = (int)STRLEN(NameBuff);
10659 		    if (col + len >= Columns - 3)
10660 			break;
10661 		    screen_puts_len(NameBuff, len, 0, col,
10662 #if defined(FEAT_SYN_HL)
10663 					 hl_combine_attr(attr, HL_ATTR(HLF_T))
10664 #else
10665 					 attr
10666 #endif
10667 					       );
10668 		    col += len;
10669 		}
10670 		if (modified)
10671 		    screen_puts_len((char_u *)"+", 1, 0, col++, attr);
10672 		screen_putchar(' ', 0, col++, attr);
10673 	    }
10674 
10675 	    room = scol - col + tabwidth - 1;
10676 	    if (room > 0)
10677 	    {
10678 		/* Get buffer name in NameBuff[] */
10679 		get_trans_bufname(cwp->w_buffer);
10680 		shorten_dir(NameBuff);
10681 		len = vim_strsize(NameBuff);
10682 		p = NameBuff;
10683 #ifdef FEAT_MBYTE
10684 		if (has_mbyte)
10685 		    while (len > room)
10686 		    {
10687 			len -= ptr2cells(p);
10688 			MB_PTR_ADV(p);
10689 		    }
10690 		else
10691 #endif
10692 		    if (len > room)
10693 		{
10694 		    p += len - room;
10695 		    len = room;
10696 		}
10697 		if (len > Columns - col - 1)
10698 		    len = Columns - col - 1;
10699 
10700 		screen_puts_len(p, (int)STRLEN(p), 0, col, attr);
10701 		col += len;
10702 	    }
10703 	    screen_putchar(' ', 0, col++, attr);
10704 
10705 	    /* Store the tab page number in TabPageIdxs[], so that
10706 	     * jump_to_mouse() knows where each one is. */
10707 	    ++tabcount;
10708 	    while (scol < col)
10709 		TabPageIdxs[scol++] = tabcount;
10710 	}
10711 
10712 	if (use_sep_chars)
10713 	    c = '_';
10714 	else
10715 	    c = ' ';
10716 	screen_fill(0, 1, col, (int)Columns, c, c, attr_fill);
10717 
10718 	/* Put an "X" for closing the current tab if there are several. */
10719 	if (first_tabpage->tp_next != NULL)
10720 	{
10721 	    screen_putchar('X', 0, (int)Columns - 1, attr_nosel);
10722 	    TabPageIdxs[Columns - 1] = -999;
10723 	}
10724     }
10725 
10726     /* Reset the flag here again, in case evaluating 'tabline' causes it to be
10727      * set. */
10728     redraw_tabline = FALSE;
10729 }
10730 
10731 /*
10732  * Get buffer name for "buf" into NameBuff[].
10733  * Takes care of special buffer names and translates special characters.
10734  */
10735     void
10736 get_trans_bufname(buf_T *buf)
10737 {
10738     if (buf_spname(buf) != NULL)
10739 	vim_strncpy(NameBuff, buf_spname(buf), MAXPATHL - 1);
10740     else
10741 	home_replace(buf, buf->b_fname, NameBuff, MAXPATHL, TRUE);
10742     trans_characters(NameBuff, MAXPATHL);
10743 }
10744 
10745 /*
10746  * Get the character to use in a status line.  Get its attributes in "*attr".
10747  */
10748     static int
10749 fillchar_status(int *attr, win_T *wp)
10750 {
10751     int fill;
10752 
10753 #ifdef FEAT_TERMINAL
10754     if (bt_terminal(wp->w_buffer))
10755     {
10756 	if (wp == curwin)
10757 	{
10758 	    *attr = HL_ATTR(HLF_ST);
10759 	    fill = fill_stl;
10760 	}
10761 	else
10762 	{
10763 	    *attr = HL_ATTR(HLF_STNC);
10764 	    fill = fill_stlnc;
10765 	}
10766     }
10767     else
10768 #endif
10769     if (wp == curwin)
10770     {
10771 	*attr = HL_ATTR(HLF_S);
10772 	fill = fill_stl;
10773     }
10774     else
10775     {
10776 	*attr = HL_ATTR(HLF_SNC);
10777 	fill = fill_stlnc;
10778     }
10779     /* Use fill when there is highlighting, and highlighting of current
10780      * window differs, or the fillchars differ, or this is not the
10781      * current window */
10782     if (*attr != 0 && ((HL_ATTR(HLF_S) != HL_ATTR(HLF_SNC)
10783 			|| wp != curwin || ONE_WINDOW)
10784 		    || (fill_stl != fill_stlnc)))
10785 	return fill;
10786     if (wp == curwin)
10787 	return '^';
10788     return '=';
10789 }
10790 
10791 /*
10792  * Get the character to use in a separator between vertically split windows.
10793  * Get its attributes in "*attr".
10794  */
10795     static int
10796 fillchar_vsep(int *attr)
10797 {
10798     *attr = HL_ATTR(HLF_C);
10799     if (*attr == 0 && fill_vert == ' ')
10800 	return '|';
10801     else
10802 	return fill_vert;
10803 }
10804 
10805 /*
10806  * Return TRUE if redrawing should currently be done.
10807  */
10808     int
10809 redrawing(void)
10810 {
10811 #ifdef FEAT_EVAL
10812     if (disable_redraw_for_testing)
10813 	return 0;
10814     else
10815 #endif
10816 	return (!RedrawingDisabled
10817 		       && !(p_lz && char_avail() && !KeyTyped && !do_redraw));
10818 }
10819 
10820 /*
10821  * Return TRUE if printing messages should currently be done.
10822  */
10823     int
10824 messaging(void)
10825 {
10826     return (!(p_lz && char_avail() && !KeyTyped));
10827 }
10828 
10829 #ifdef FEAT_MENU
10830 /*
10831  * Draw the window toolbar.
10832  */
10833     static void
10834 redraw_win_toolbar(win_T *wp)
10835 {
10836     vimmenu_T	*menu;
10837     int		item_idx = 0;
10838     int		item_count = 0;
10839     int		col = 0;
10840     int		next_col;
10841     int		off = (int)(current_ScreenLine - ScreenLines);
10842     int		fill_attr = syn_name2attr((char_u *)"ToolbarLine");
10843     int		button_attr = syn_name2attr((char_u *)"ToolbarButton");
10844 
10845     vim_free(wp->w_winbar_items);
10846     for (menu = wp->w_winbar->children; menu != NULL; menu = menu->next)
10847 	++item_count;
10848     wp->w_winbar_items = (winbar_item_T *)alloc_clear(
10849 			   (unsigned)sizeof(winbar_item_T) * (item_count + 1));
10850 
10851     /* TODO: use fewer spaces if there is not enough room */
10852     for (menu = wp->w_winbar->children;
10853 			  menu != NULL && col < wp->w_width; menu = menu->next)
10854     {
10855 	space_to_screenline(off + col, fill_attr);
10856 	if (++col >= wp->w_width)
10857 	    break;
10858 	if (col > 1)
10859 	{
10860 	    space_to_screenline(off + col, fill_attr);
10861 	    if (++col >= wp->w_width)
10862 		break;
10863 	}
10864 
10865 	wp->w_winbar_items[item_idx].wb_startcol = col;
10866 	space_to_screenline(off + col, button_attr);
10867 	if (++col >= wp->w_width)
10868 	    break;
10869 
10870 	next_col = text_to_screenline(wp, menu->name, col);
10871 	while (col < next_col)
10872 	{
10873 	    ScreenAttrs[off + col] = button_attr;
10874 	    ++col;
10875 	}
10876 	wp->w_winbar_items[item_idx].wb_endcol = col;
10877 	wp->w_winbar_items[item_idx].wb_menu = menu;
10878 	++item_idx;
10879 
10880 	if (col >= wp->w_width)
10881 	    break;
10882 	space_to_screenline(off + col, button_attr);
10883 	++col;
10884     }
10885     while (col < wp->w_width)
10886     {
10887 	space_to_screenline(off + col, fill_attr);
10888 	++col;
10889     }
10890     wp->w_winbar_items[item_idx].wb_menu = NULL; /* end marker */
10891 
10892     screen_line(wp->w_winrow, wp->w_wincol, (int)wp->w_width,
10893 						     (int)wp->w_width, FALSE);
10894 }
10895 #endif
10896 
10897 /*
10898  * Show current status info in ruler and various other places
10899  * If always is FALSE, only show ruler if position has changed.
10900  */
10901     void
10902 showruler(int always)
10903 {
10904     if (!always && !redrawing())
10905 	return;
10906 #ifdef FEAT_INS_EXPAND
10907     if (pum_visible())
10908     {
10909 	/* Don't redraw right now, do it later. */
10910 	curwin->w_redr_status = TRUE;
10911 	return;
10912     }
10913 #endif
10914 #if defined(FEAT_STL_OPT)
10915     if ((*p_stl != NUL || *curwin->w_p_stl != NUL) && curwin->w_status_height)
10916     {
10917 	redraw_custom_statusline(curwin);
10918     }
10919     else
10920 #endif
10921 #ifdef FEAT_CMDL_INFO
10922 	win_redr_ruler(curwin, always, FALSE);
10923 #endif
10924 
10925 #ifdef FEAT_TITLE
10926     if (need_maketitle
10927 # ifdef FEAT_STL_OPT
10928 	    || (p_icon && (stl_syntax & STL_IN_ICON))
10929 	    || (p_title && (stl_syntax & STL_IN_TITLE))
10930 # endif
10931        )
10932 	maketitle();
10933 #endif
10934     /* Redraw the tab pages line if needed. */
10935     if (redraw_tabline)
10936 	draw_tabline();
10937 }
10938 
10939 #ifdef FEAT_CMDL_INFO
10940     static void
10941 win_redr_ruler(win_T *wp, int always, int ignore_pum)
10942 {
10943 #define RULER_BUF_LEN 70
10944     char_u	buffer[RULER_BUF_LEN];
10945     int		row;
10946     int		fillchar;
10947     int		attr;
10948     int		empty_line = FALSE;
10949     colnr_T	virtcol;
10950     int		i;
10951     size_t	len;
10952     int		o;
10953     int		this_ru_col;
10954     int		off = 0;
10955     int		width = Columns;
10956 
10957     /* If 'ruler' off or redrawing disabled, don't do anything */
10958     if (!p_ru)
10959 	return;
10960 
10961     /*
10962      * Check if cursor.lnum is valid, since win_redr_ruler() may be called
10963      * after deleting lines, before cursor.lnum is corrected.
10964      */
10965     if (wp->w_cursor.lnum > wp->w_buffer->b_ml.ml_line_count)
10966 	return;
10967 
10968 #ifdef FEAT_INS_EXPAND
10969     /* Don't draw the ruler while doing insert-completion, it might overwrite
10970      * the (long) mode message. */
10971     if (wp == lastwin && lastwin->w_status_height == 0)
10972 	if (edit_submode != NULL)
10973 	    return;
10974     // Don't draw the ruler when the popup menu is visible, it may overlap.
10975     // Except when the popup menu will be redrawn anyway.
10976     if (!ignore_pum && pum_visible())
10977 	return;
10978 #endif
10979 
10980 #ifdef FEAT_STL_OPT
10981     if (*p_ruf)
10982     {
10983 	int	save_called_emsg = called_emsg;
10984 
10985 	called_emsg = FALSE;
10986 	win_redr_custom(wp, TRUE);
10987 	if (called_emsg)
10988 	    set_string_option_direct((char_u *)"rulerformat", -1,
10989 					   (char_u *)"", OPT_FREE, SID_ERROR);
10990 	called_emsg |= save_called_emsg;
10991 	return;
10992     }
10993 #endif
10994 
10995     /*
10996      * Check if not in Insert mode and the line is empty (will show "0-1").
10997      */
10998     if (!(State & INSERT)
10999 		&& *ml_get_buf(wp->w_buffer, wp->w_cursor.lnum, FALSE) == NUL)
11000 	empty_line = TRUE;
11001 
11002     /*
11003      * Only draw the ruler when something changed.
11004      */
11005     validate_virtcol_win(wp);
11006     if (       redraw_cmdline
11007 	    || always
11008 	    || wp->w_cursor.lnum != wp->w_ru_cursor.lnum
11009 	    || wp->w_cursor.col != wp->w_ru_cursor.col
11010 	    || wp->w_virtcol != wp->w_ru_virtcol
11011 #ifdef FEAT_VIRTUALEDIT
11012 	    || wp->w_cursor.coladd != wp->w_ru_cursor.coladd
11013 #endif
11014 	    || wp->w_topline != wp->w_ru_topline
11015 	    || wp->w_buffer->b_ml.ml_line_count != wp->w_ru_line_count
11016 #ifdef FEAT_DIFF
11017 	    || wp->w_topfill != wp->w_ru_topfill
11018 #endif
11019 	    || empty_line != wp->w_ru_empty)
11020     {
11021 	cursor_off();
11022 	if (wp->w_status_height)
11023 	{
11024 	    row = W_WINROW(wp) + wp->w_height;
11025 	    fillchar = fillchar_status(&attr, wp);
11026 	    off = wp->w_wincol;
11027 	    width = wp->w_width;
11028 	}
11029 	else
11030 	{
11031 	    row = Rows - 1;
11032 	    fillchar = ' ';
11033 	    attr = 0;
11034 	    width = Columns;
11035 	    off = 0;
11036 	}
11037 
11038 	/* In list mode virtcol needs to be recomputed */
11039 	virtcol = wp->w_virtcol;
11040 	if (wp->w_p_list && lcs_tab1 == NUL)
11041 	{
11042 	    wp->w_p_list = FALSE;
11043 	    getvvcol(wp, &wp->w_cursor, NULL, &virtcol, NULL);
11044 	    wp->w_p_list = TRUE;
11045 	}
11046 
11047 	/*
11048 	 * Some sprintfs return the length, some return a pointer.
11049 	 * To avoid portability problems we use strlen() here.
11050 	 */
11051 	vim_snprintf((char *)buffer, RULER_BUF_LEN, "%ld,",
11052 		(wp->w_buffer->b_ml.ml_flags & ML_EMPTY)
11053 		    ? 0L
11054 		    : (long)(wp->w_cursor.lnum));
11055 	len = STRLEN(buffer);
11056 	col_print(buffer + len, RULER_BUF_LEN - len,
11057 			empty_line ? 0 : (int)wp->w_cursor.col + 1,
11058 			(int)virtcol + 1);
11059 
11060 	/*
11061 	 * Add a "50%" if there is room for it.
11062 	 * On the last line, don't print in the last column (scrolls the
11063 	 * screen up on some terminals).
11064 	 */
11065 	i = (int)STRLEN(buffer);
11066 	get_rel_pos(wp, buffer + i + 1, RULER_BUF_LEN - i - 1);
11067 	o = i + vim_strsize(buffer + i + 1);
11068 	if (wp->w_status_height == 0)	/* can't use last char of screen */
11069 	    ++o;
11070 	this_ru_col = ru_col - (Columns - width);
11071 	if (this_ru_col < 0)
11072 	    this_ru_col = 0;
11073 	/* Never use more than half the window/screen width, leave the other
11074 	 * half for the filename. */
11075 	if (this_ru_col < (width + 1) / 2)
11076 	    this_ru_col = (width + 1) / 2;
11077 	if (this_ru_col + o < width)
11078 	{
11079 	    /* need at least 3 chars left for get_rel_pos() + NUL */
11080 	    while (this_ru_col + o < width && RULER_BUF_LEN > i + 4)
11081 	    {
11082 #ifdef FEAT_MBYTE
11083 		if (has_mbyte)
11084 		    i += (*mb_char2bytes)(fillchar, buffer + i);
11085 		else
11086 #endif
11087 		    buffer[i++] = fillchar;
11088 		++o;
11089 	    }
11090 	    get_rel_pos(wp, buffer + i, RULER_BUF_LEN - i);
11091 	}
11092 	/* Truncate at window boundary. */
11093 #ifdef FEAT_MBYTE
11094 	if (has_mbyte)
11095 	{
11096 	    o = 0;
11097 	    for (i = 0; buffer[i] != NUL; i += (*mb_ptr2len)(buffer + i))
11098 	    {
11099 		o += (*mb_ptr2cells)(buffer + i);
11100 		if (this_ru_col + o > width)
11101 		{
11102 		    buffer[i] = NUL;
11103 		    break;
11104 		}
11105 	    }
11106 	}
11107 	else
11108 #endif
11109 	if (this_ru_col + (int)STRLEN(buffer) > width)
11110 	    buffer[width - this_ru_col] = NUL;
11111 
11112 	screen_puts(buffer, row, this_ru_col + off, attr);
11113 	i = redraw_cmdline;
11114 	screen_fill(row, row + 1,
11115 		this_ru_col + off + (int)STRLEN(buffer),
11116 		(int)(off + width),
11117 		fillchar, fillchar, attr);
11118 	/* don't redraw the cmdline because of showing the ruler */
11119 	redraw_cmdline = i;
11120 	wp->w_ru_cursor = wp->w_cursor;
11121 	wp->w_ru_virtcol = wp->w_virtcol;
11122 	wp->w_ru_empty = empty_line;
11123 	wp->w_ru_topline = wp->w_topline;
11124 	wp->w_ru_line_count = wp->w_buffer->b_ml.ml_line_count;
11125 #ifdef FEAT_DIFF
11126 	wp->w_ru_topfill = wp->w_topfill;
11127 #endif
11128     }
11129 }
11130 #endif
11131 
11132 #if defined(FEAT_LINEBREAK) || defined(PROTO)
11133 /*
11134  * Return the width of the 'number' and 'relativenumber' column.
11135  * Caller may need to check if 'number' or 'relativenumber' is set.
11136  * Otherwise it depends on 'numberwidth' and the line count.
11137  */
11138     int
11139 number_width(win_T *wp)
11140 {
11141     int		n;
11142     linenr_T	lnum;
11143 
11144     if (wp->w_p_rnu && !wp->w_p_nu)
11145 	/* cursor line shows "0" */
11146 	lnum = wp->w_height;
11147     else
11148 	/* cursor line shows absolute line number */
11149 	lnum = wp->w_buffer->b_ml.ml_line_count;
11150 
11151     if (lnum == wp->w_nrwidth_line_count && wp->w_nuw_cached == wp->w_p_nuw)
11152 	return wp->w_nrwidth_width;
11153     wp->w_nrwidth_line_count = lnum;
11154 
11155     n = 0;
11156     do
11157     {
11158 	lnum /= 10;
11159 	++n;
11160     } while (lnum > 0);
11161 
11162     /* 'numberwidth' gives the minimal width plus one */
11163     if (n < wp->w_p_nuw - 1)
11164 	n = wp->w_p_nuw - 1;
11165 
11166     wp->w_nrwidth_width = n;
11167     wp->w_nuw_cached = wp->w_p_nuw;
11168     return n;
11169 }
11170 #endif
11171 
11172 /*
11173  * Return the current cursor column. This is the actual position on the
11174  * screen. First column is 0.
11175  */
11176     int
11177 screen_screencol(void)
11178 {
11179     return screen_cur_col;
11180 }
11181 
11182 /*
11183  * Return the current cursor row. This is the actual position on the screen.
11184  * First row is 0.
11185  */
11186     int
11187 screen_screenrow(void)
11188 {
11189     return screen_cur_row;
11190 }
11191