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