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