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