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