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