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