xref: /vim-8.2.3635/src/window.c (revision f18e8a96)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read a list of people who contributed.
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 #include "vim.h"
11 
12 static void cmd_with_count(char *cmd, char_u *bufp, size_t bufsize, long Prenum);
13 static void win_init(win_T *newp, win_T *oldp, int flags);
14 static void win_init_some(win_T *newp, win_T *oldp);
15 static void frame_comp_pos(frame_T *topfrp, int *row, int *col);
16 static void frame_setheight(frame_T *curfrp, int height);
17 static void frame_setwidth(frame_T *curfrp, int width);
18 static void win_exchange(long);
19 static void win_rotate(int, int);
20 static void win_totop(int size, int flags);
21 static void win_equal_rec(win_T *next_curwin, int current, frame_T *topfr, int dir, int col, int row, int width, int height);
22 static win_T *win_free_mem(win_T *win, int *dirp, tabpage_T *tp);
23 static frame_T *win_altframe(win_T *win, tabpage_T *tp);
24 static tabpage_T *alt_tabpage(void);
25 static win_T *frame2win(frame_T *frp);
26 static int frame_has_win(frame_T *frp, win_T *wp);
27 static void frame_new_height(frame_T *topfrp, int height, int topfirst, int wfh);
28 static int frame_fixed_height(frame_T *frp);
29 static int frame_fixed_width(frame_T *frp);
30 static void frame_add_statusline(frame_T *frp);
31 static void frame_new_width(frame_T *topfrp, int width, int leftfirst, int wfw);
32 static void frame_add_vsep(frame_T *frp);
33 static int frame_minwidth(frame_T *topfrp, win_T *next_curwin);
34 static void frame_fix_width(win_T *wp);
35 static int win_alloc_firstwin(win_T *oldwin);
36 static void new_frame(win_T *wp);
37 static tabpage_T *alloc_tabpage(void);
38 static int leave_tabpage(buf_T *new_curbuf, int trigger_leave_autocmds);
39 static void enter_tabpage(tabpage_T *tp, buf_T *old_curbuf, int trigger_enter_autocmds, int trigger_leave_autocmds);
40 static void frame_fix_height(win_T *wp);
41 static int frame_minheight(frame_T *topfrp, win_T *next_curwin);
42 static int may_open_tabpage(void);
43 static int win_enter_ext(win_T *wp, int flags);
44 static void win_free(win_T *wp, tabpage_T *tp);
45 static int win_unlisted(win_T *wp);
46 static void win_append(win_T *after, win_T *wp);
47 static void frame_append(frame_T *after, frame_T *frp);
48 static void frame_insert(frame_T *before, frame_T *frp);
49 static void frame_remove(frame_T *frp);
50 static void win_goto_ver(int up, long count);
51 static void win_goto_hor(int left, long count);
52 static void frame_add_height(frame_T *frp, int n);
53 static void last_status_rec(frame_T *fr, int statusline);
54 
55 static void make_snapshot_rec(frame_T *fr, frame_T **frp);
56 static void clear_snapshot(tabpage_T *tp, int idx);
57 static void clear_snapshot_rec(frame_T *fr);
58 static int check_snapshot_rec(frame_T *sn, frame_T *fr);
59 static win_T *restore_snapshot_rec(frame_T *sn, frame_T *fr);
60 
61 static int frame_check_height(frame_T *topfrp, int height);
62 static int frame_check_width(frame_T *topfrp, int width);
63 
64 static win_T *win_alloc(win_T *after, int hidden);
65 
66 #define NOWIN		(win_T *)-1	// non-existing window
67 
68 #define ROWS_AVAIL (Rows - p_ch - tabline_height())
69 
70 // flags for win_enter_ext()
71 #define WEE_UNDO_SYNC			0x01
72 #define WEE_CURWIN_INVALID		0x02
73 #define WEE_TRIGGER_NEW_AUTOCMDS	0x04
74 #define WEE_TRIGGER_ENTER_AUTOCMDS	0x08
75 #define WEE_TRIGGER_LEAVE_AUTOCMDS	0x10
76 #define WEE_ALLOW_PARSE_MESSAGES	0x20
77 
78 static char *m_onlyone = N_("Already only one window");
79 
80 // When non-zero splitting a window is forbidden.  Used to avoid that nasty
81 // autocommands mess up the window structure.
82 static int split_disallowed = 0;
83 
84 // #define WIN_DEBUG
85 #ifdef WIN_DEBUG
86 /*
87  * Call this method to log the current window layout.
88  */
89     static void
90 log_frame_layout(frame_T *frame)
91 {
92     ch_log(NULL, "layout %s, wi: %d, he: %d, wwi: %d, whe: %d, id: %d",
93 	    frame->fr_layout == FR_LEAF ? "LEAF"
94 				  : frame->fr_layout == FR_ROW ? "ROW" : "COL",
95 	    frame->fr_width,
96 	    frame->fr_height,
97 	    frame->fr_win == NULL ? -1 : frame->fr_win->w_width,
98 	    frame->fr_win == NULL ? -1 : frame->fr_win->w_height,
99 	    frame->fr_win == NULL ? -1 : frame->fr_win->w_id);
100     if (frame->fr_child != NULL)
101     {
102 	ch_log(NULL, "children");
103 	log_frame_layout(frame->fr_child);
104 	if (frame->fr_next != NULL)
105 	    ch_log(NULL, "END of children");
106     }
107     if (frame->fr_next != NULL)
108 	log_frame_layout(frame->fr_next);
109 }
110 #endif
111 
112 /*
113  * All CTRL-W window commands are handled here, called from normal_cmd().
114  */
115     void
116 do_window(
117     int		nchar,
118     long	Prenum,
119     int		xchar)	    // extra char from ":wincmd gx" or NUL
120 {
121     long	Prenum1;
122     win_T	*wp;
123 #if defined(FEAT_SEARCHPATH) || defined(FEAT_FIND_ID)
124     char_u	*ptr;
125     linenr_T    lnum = -1;
126 #endif
127 #ifdef FEAT_FIND_ID
128     int		type = FIND_DEFINE;
129     int		len;
130 #endif
131     char_u	cbuf[40];
132 
133     if (ERROR_IF_ANY_POPUP_WINDOW)
134 	return;
135 
136 #ifdef FEAT_CMDWIN
137 # define CHECK_CMDWIN \
138     do { \
139 	if (cmdwin_type != 0) \
140 	{ \
141 	    emsg(_(e_invalid_in_cmdline_window)); \
142 	    return; \
143 	} \
144     } while (0)
145 #else
146 # define CHECK_CMDWIN do { /**/ } while (0)
147 #endif
148 
149     Prenum1 = Prenum == 0 ? 1 : Prenum;
150 
151     switch (nchar)
152     {
153 // split current window in two parts, horizontally
154     case 'S':
155     case Ctrl_S:
156     case 's':
157 		CHECK_CMDWIN;
158 		reset_VIsual_and_resel();	// stop Visual mode
159 #ifdef FEAT_QUICKFIX
160 		// When splitting the quickfix window open a new buffer in it,
161 		// don't replicate the quickfix buffer.
162 		if (bt_quickfix(curbuf))
163 		    goto newwindow;
164 #endif
165 #ifdef FEAT_GUI
166 		need_mouse_correct = TRUE;
167 #endif
168 		(void)win_split((int)Prenum, 0);
169 		break;
170 
171 // split current window in two parts, vertically
172     case Ctrl_V:
173     case 'v':
174 		CHECK_CMDWIN;
175 		reset_VIsual_and_resel();	// stop Visual mode
176 #ifdef FEAT_QUICKFIX
177 		// When splitting the quickfix window open a new buffer in it,
178 		// don't replicate the quickfix buffer.
179 		if (bt_quickfix(curbuf))
180 		    goto newwindow;
181 #endif
182 #ifdef FEAT_GUI
183 		need_mouse_correct = TRUE;
184 #endif
185 		(void)win_split((int)Prenum, WSP_VERT);
186 		break;
187 
188 // split current window and edit alternate file
189     case Ctrl_HAT:
190     case '^':
191 		CHECK_CMDWIN;
192 		reset_VIsual_and_resel();	// stop Visual mode
193 
194 		if (buflist_findnr(Prenum == 0
195 					? curwin->w_alt_fnum : Prenum) == NULL)
196 		{
197 		    if (Prenum == 0)
198 			emsg(_(e_no_alternate_file));
199 		    else
200 			semsg(_("E92: Buffer %ld not found"), Prenum);
201 		    break;
202 		}
203 
204 		if (!curbuf_locked() && win_split(0, 0) == OK)
205 		    (void)buflist_getfile(
206 			    Prenum == 0 ? curwin->w_alt_fnum : Prenum,
207 			    (linenr_T)0, GETF_ALT, FALSE);
208 		break;
209 
210 // open new window
211     case Ctrl_N:
212     case 'n':
213 		CHECK_CMDWIN;
214 		reset_VIsual_and_resel();	// stop Visual mode
215 #ifdef FEAT_QUICKFIX
216 newwindow:
217 #endif
218 		if (Prenum)
219 		    // window height
220 		    vim_snprintf((char *)cbuf, sizeof(cbuf) - 5, "%ld", Prenum);
221 		else
222 		    cbuf[0] = NUL;
223 #if defined(FEAT_QUICKFIX)
224 		if (nchar == 'v' || nchar == Ctrl_V)
225 		    STRCAT(cbuf, "v");
226 #endif
227 		STRCAT(cbuf, "new");
228 		do_cmdline_cmd(cbuf);
229 		break;
230 
231 // quit current window
232     case Ctrl_Q:
233     case 'q':
234 		reset_VIsual_and_resel();	// stop Visual mode
235 		cmd_with_count("quit", cbuf, sizeof(cbuf), Prenum);
236 		do_cmdline_cmd(cbuf);
237 		break;
238 
239 // close current window
240     case Ctrl_C:
241     case 'c':
242 		reset_VIsual_and_resel();	// stop Visual mode
243 		cmd_with_count("close", cbuf, sizeof(cbuf), Prenum);
244 		do_cmdline_cmd(cbuf);
245 		break;
246 
247 #if defined(FEAT_QUICKFIX)
248 // close preview window
249     case Ctrl_Z:
250     case 'z':
251 		CHECK_CMDWIN;
252 		reset_VIsual_and_resel();	// stop Visual mode
253 		do_cmdline_cmd((char_u *)"pclose");
254 		break;
255 
256 // cursor to preview window
257     case 'P':
258 		FOR_ALL_WINDOWS(wp)
259 		    if (wp->w_p_pvw)
260 			break;
261 		if (wp == NULL)
262 		    emsg(_("E441: There is no preview window"));
263 		else
264 		    win_goto(wp);
265 		break;
266 #endif
267 
268 // close all but current window
269     case Ctrl_O:
270     case 'o':
271 		CHECK_CMDWIN;
272 		reset_VIsual_and_resel();	// stop Visual mode
273 		cmd_with_count("only", cbuf, sizeof(cbuf), Prenum);
274 		do_cmdline_cmd(cbuf);
275 		break;
276 
277 // cursor to next window with wrap around
278     case Ctrl_W:
279     case 'w':
280 // cursor to previous window with wrap around
281     case 'W':
282 		CHECK_CMDWIN;
283 		if (ONE_WINDOW && Prenum != 1)	// just one window
284 		    beep_flush();
285 		else
286 		{
287 		    if (Prenum)			// go to specified window
288 		    {
289 			for (wp = firstwin; --Prenum > 0; )
290 			{
291 			    if (wp->w_next == NULL)
292 				break;
293 			    else
294 				wp = wp->w_next;
295 			}
296 		    }
297 		    else
298 		    {
299 			if (nchar == 'W')	    // go to previous window
300 			{
301 			    wp = curwin->w_prev;
302 			    if (wp == NULL)
303 				wp = lastwin;	    // wrap around
304 			}
305 			else			    // go to next window
306 			{
307 			    wp = curwin->w_next;
308 			    if (wp == NULL)
309 				wp = firstwin;	    // wrap around
310 			}
311 		    }
312 		    win_goto(wp);
313 		}
314 		break;
315 
316 // cursor to window below
317     case 'j':
318     case K_DOWN:
319     case Ctrl_J:
320 		CHECK_CMDWIN;
321 		win_goto_ver(FALSE, Prenum1);
322 		break;
323 
324 // cursor to window above
325     case 'k':
326     case K_UP:
327     case Ctrl_K:
328 		CHECK_CMDWIN;
329 		win_goto_ver(TRUE, Prenum1);
330 		break;
331 
332 // cursor to left window
333     case 'h':
334     case K_LEFT:
335     case Ctrl_H:
336     case K_BS:
337 		CHECK_CMDWIN;
338 		win_goto_hor(TRUE, Prenum1);
339 		break;
340 
341 // cursor to right window
342     case 'l':
343     case K_RIGHT:
344     case Ctrl_L:
345 		CHECK_CMDWIN;
346 		win_goto_hor(FALSE, Prenum1);
347 		break;
348 
349 // move window to new tab page
350     case 'T':
351 		CHECK_CMDWIN;
352 		if (one_window())
353 		    msg(_(m_onlyone));
354 		else
355 		{
356 		    tabpage_T	*oldtab = curtab;
357 		    tabpage_T	*newtab;
358 
359 		    // First create a new tab with the window, then go back to
360 		    // the old tab and close the window there.
361 		    wp = curwin;
362 		    if (win_new_tabpage((int)Prenum) == OK
363 						     && valid_tabpage(oldtab))
364 		    {
365 			newtab = curtab;
366 			goto_tabpage_tp(oldtab, TRUE, TRUE);
367 			if (curwin == wp)
368 			    win_close(curwin, FALSE);
369 			if (valid_tabpage(newtab))
370 			    goto_tabpage_tp(newtab, TRUE, TRUE);
371 		    }
372 		}
373 		break;
374 
375 // cursor to top-left window
376     case 't':
377     case Ctrl_T:
378 		win_goto(firstwin);
379 		break;
380 
381 // cursor to bottom-right window
382     case 'b':
383     case Ctrl_B:
384 		win_goto(lastwin);
385 		break;
386 
387 // cursor to last accessed (previous) window
388     case 'p':
389     case Ctrl_P:
390 		if (!win_valid(prevwin))
391 		    beep_flush();
392 		else
393 		    win_goto(prevwin);
394 		break;
395 
396 // exchange current and next window
397     case 'x':
398     case Ctrl_X:
399 		CHECK_CMDWIN;
400 		win_exchange(Prenum);
401 		break;
402 
403 // rotate windows downwards
404     case Ctrl_R:
405     case 'r':
406 		CHECK_CMDWIN;
407 		reset_VIsual_and_resel();	// stop Visual mode
408 		win_rotate(FALSE, (int)Prenum1);    // downwards
409 		break;
410 
411 // rotate windows upwards
412     case 'R':
413 		CHECK_CMDWIN;
414 		reset_VIsual_and_resel();	// stop Visual mode
415 		win_rotate(TRUE, (int)Prenum1);	    // upwards
416 		break;
417 
418 // move window to the very top/bottom/left/right
419     case 'K':
420     case 'J':
421     case 'H':
422     case 'L':
423 		CHECK_CMDWIN;
424 		win_totop((int)Prenum,
425 			((nchar == 'H' || nchar == 'L') ? WSP_VERT : 0)
426 			| ((nchar == 'H' || nchar == 'K') ? WSP_TOP : WSP_BOT));
427 		break;
428 
429 // make all windows the same height
430     case '=':
431 #ifdef FEAT_GUI
432 		need_mouse_correct = TRUE;
433 #endif
434 		win_equal(NULL, FALSE, 'b');
435 		break;
436 
437 // increase current window height
438     case '+':
439 #ifdef FEAT_GUI
440 		need_mouse_correct = TRUE;
441 #endif
442 		win_setheight(curwin->w_height + (int)Prenum1);
443 		break;
444 
445 // decrease current window height
446     case '-':
447 #ifdef FEAT_GUI
448 		need_mouse_correct = TRUE;
449 #endif
450 		win_setheight(curwin->w_height - (int)Prenum1);
451 		break;
452 
453 // set current window height
454     case Ctrl__:
455     case '_':
456 #ifdef FEAT_GUI
457 		need_mouse_correct = TRUE;
458 #endif
459 		win_setheight(Prenum ? (int)Prenum : 9999);
460 		break;
461 
462 // increase current window width
463     case '>':
464 #ifdef FEAT_GUI
465 		need_mouse_correct = TRUE;
466 #endif
467 		win_setwidth(curwin->w_width + (int)Prenum1);
468 		break;
469 
470 // decrease current window width
471     case '<':
472 #ifdef FEAT_GUI
473 		need_mouse_correct = TRUE;
474 #endif
475 		win_setwidth(curwin->w_width - (int)Prenum1);
476 		break;
477 
478 // set current window width
479     case '|':
480 #ifdef FEAT_GUI
481 		need_mouse_correct = TRUE;
482 #endif
483 		win_setwidth(Prenum != 0 ? (int)Prenum : 9999);
484 		break;
485 
486 // jump to tag and split window if tag exists (in preview window)
487 #if defined(FEAT_QUICKFIX)
488     case '}':
489 		CHECK_CMDWIN;
490 		if (Prenum)
491 		    g_do_tagpreview = Prenum;
492 		else
493 		    g_do_tagpreview = p_pvh;
494 #endif
495 		// FALLTHROUGH
496     case ']':
497     case Ctrl_RSB:
498 		CHECK_CMDWIN;
499 		// keep Visual mode, can select words to use as a tag
500 		if (Prenum)
501 		    postponed_split = Prenum;
502 		else
503 		    postponed_split = -1;
504 #ifdef FEAT_QUICKFIX
505 		if (nchar != '}')
506 		    g_do_tagpreview = 0;
507 #endif
508 
509 		// Execute the command right here, required when "wincmd ]"
510 		// was used in a function.
511 		do_nv_ident(Ctrl_RSB, NUL);
512 		break;
513 
514 #ifdef FEAT_SEARCHPATH
515 // edit file name under cursor in a new window
516     case 'f':
517     case 'F':
518     case Ctrl_F:
519 wingotofile:
520 		CHECK_CMDWIN;
521 
522 		ptr = grab_file_name(Prenum1, &lnum);
523 		if (ptr != NULL)
524 		{
525 		    tabpage_T	*oldtab = curtab;
526 		    win_T	*oldwin = curwin;
527 # ifdef FEAT_GUI
528 		    need_mouse_correct = TRUE;
529 # endif
530 		    setpcmark();
531 		    if (win_split(0, 0) == OK)
532 		    {
533 			RESET_BINDING(curwin);
534 			if (do_ecmd(0, ptr, NULL, NULL, ECMD_LASTL,
535 						   ECMD_HIDE, NULL) == FAIL)
536 			{
537 			    // Failed to open the file, close the window
538 			    // opened for it.
539 			    win_close(curwin, FALSE);
540 			    goto_tabpage_win(oldtab, oldwin);
541 			}
542 			else if (nchar == 'F' && lnum >= 0)
543 			{
544 			    curwin->w_cursor.lnum = lnum;
545 			    check_cursor_lnum();
546 			    beginline(BL_SOL | BL_FIX);
547 			}
548 		    }
549 		    vim_free(ptr);
550 		}
551 		break;
552 #endif
553 
554 #ifdef FEAT_FIND_ID
555 // Go to the first occurrence of the identifier under cursor along path in a
556 // new window -- webb
557     case 'i':			    // Go to any match
558     case Ctrl_I:
559 		type = FIND_ANY;
560 		// FALLTHROUGH
561     case 'd':			    // Go to definition, using 'define'
562     case Ctrl_D:
563 		CHECK_CMDWIN;
564 		if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0)
565 		    break;
566 		find_pattern_in_path(ptr, 0, len, TRUE,
567 			Prenum == 0 ? TRUE : FALSE, type,
568 			Prenum1, ACTION_SPLIT, (linenr_T)1, (linenr_T)MAXLNUM);
569 		curwin->w_set_curswant = TRUE;
570 		break;
571 #endif
572 
573 // Quickfix window only: view the result under the cursor in a new split.
574 #if defined(FEAT_QUICKFIX)
575     case K_KENTER:
576     case CAR:
577 		if (bt_quickfix(curbuf))
578 		    qf_view_result(TRUE);
579 		break;
580 #endif
581 
582 // CTRL-W g  extended commands
583     case 'g':
584     case Ctrl_G:
585 		CHECK_CMDWIN;
586 #ifdef USE_ON_FLY_SCROLL
587 		dont_scroll = TRUE;		// disallow scrolling here
588 #endif
589 		++no_mapping;
590 		++allow_keys;   // no mapping for xchar, but allow key codes
591 		if (xchar == NUL)
592 		    xchar = plain_vgetc();
593 		LANGMAP_ADJUST(xchar, TRUE);
594 		--no_mapping;
595 		--allow_keys;
596 #ifdef FEAT_CMDL_INFO
597 		(void)add_to_showcmd(xchar);
598 #endif
599 		switch (xchar)
600 		{
601 #if defined(FEAT_QUICKFIX)
602 		    case '}':
603 			xchar = Ctrl_RSB;
604 			if (Prenum)
605 			    g_do_tagpreview = Prenum;
606 			else
607 			    g_do_tagpreview = p_pvh;
608 #endif
609 			// FALLTHROUGH
610 		    case ']':
611 		    case Ctrl_RSB:
612 			// keep Visual mode, can select words to use as a tag
613 			if (Prenum)
614 			    postponed_split = Prenum;
615 			else
616 			    postponed_split = -1;
617 
618 			// Execute the command right here, required when
619 			// "wincmd g}" was used in a function.
620 			do_nv_ident('g', xchar);
621 			break;
622 
623 #ifdef FEAT_SEARCHPATH
624 		    case 'f':	    // CTRL-W gf: "gf" in a new tab page
625 		    case 'F':	    // CTRL-W gF: "gF" in a new tab page
626 			cmdmod.cmod_tab = tabpage_index(curtab) + 1;
627 			nchar = xchar;
628 			goto wingotofile;
629 #endif
630 		    case 't':	    // CTRL-W gt: go to next tab page
631 			goto_tabpage((int)Prenum);
632 			break;
633 
634 		    case 'T':	    // CTRL-W gT: go to previous tab page
635 			goto_tabpage(-(int)Prenum1);
636 			break;
637 
638 		    case TAB:	    // CTRL-W g<Tab>: go to last used tab page
639 			if (goto_tabpage_lastused() == FAIL)
640 			    beep_flush();
641 			break;
642 
643 		    default:
644 			beep_flush();
645 			break;
646 		}
647 		break;
648 
649     default:	beep_flush();
650 		break;
651     }
652 }
653 
654 /*
655  * Figure out the address type for ":wincmd".
656  */
657     void
658 get_wincmd_addr_type(char_u *arg, exarg_T *eap)
659 {
660     switch (*arg)
661     {
662     case 'S':
663     case Ctrl_S:
664     case 's':
665     case Ctrl_N:
666     case 'n':
667     case 'j':
668     case Ctrl_J:
669     case 'k':
670     case Ctrl_K:
671     case 'T':
672     case Ctrl_R:
673     case 'r':
674     case 'R':
675     case 'K':
676     case 'J':
677     case '+':
678     case '-':
679     case Ctrl__:
680     case '_':
681     case '|':
682     case ']':
683     case Ctrl_RSB:
684     case 'g':
685     case Ctrl_G:
686     case Ctrl_V:
687     case 'v':
688     case 'h':
689     case Ctrl_H:
690     case 'l':
691     case Ctrl_L:
692     case 'H':
693     case 'L':
694     case '>':
695     case '<':
696 #if defined(FEAT_QUICKFIX)
697     case '}':
698 #endif
699 #ifdef FEAT_SEARCHPATH
700     case 'f':
701     case 'F':
702     case Ctrl_F:
703 #endif
704 #ifdef FEAT_FIND_ID
705     case 'i':
706     case Ctrl_I:
707     case 'd':
708     case Ctrl_D:
709 #endif
710 		// window size or any count
711 		eap->addr_type = ADDR_OTHER;
712 		break;
713 
714     case Ctrl_HAT:
715     case '^':
716 		// buffer number
717 		eap->addr_type = ADDR_BUFFERS;
718 		break;
719 
720     case Ctrl_Q:
721     case 'q':
722     case Ctrl_C:
723     case 'c':
724     case Ctrl_O:
725     case 'o':
726     case Ctrl_W:
727     case 'w':
728     case 'W':
729     case 'x':
730     case Ctrl_X:
731 		// window number
732 		eap->addr_type = ADDR_WINDOWS;
733 		break;
734 
735 #if defined(FEAT_QUICKFIX)
736     case Ctrl_Z:
737     case 'z':
738     case 'P':
739 #endif
740     case 't':
741     case Ctrl_T:
742     case 'b':
743     case Ctrl_B:
744     case 'p':
745     case Ctrl_P:
746     case '=':
747     case CAR:
748 		// no count
749 		eap->addr_type = ADDR_NONE;
750 		break;
751     }
752 }
753 
754     static void
755 cmd_with_count(
756     char	*cmd,
757     char_u	*bufp,
758     size_t	bufsize,
759     long	Prenum)
760 {
761     if (Prenum > 0)
762 	vim_snprintf((char *)bufp, bufsize, "%s %ld", cmd, Prenum);
763     else
764 	STRCPY(bufp, cmd);
765 }
766 
767 /*
768  * If "split_disallowed" is set given an error and return FAIL.
769  * Otherwise return OK.
770  */
771     static int
772 check_split_disallowed()
773 {
774     if (split_disallowed > 0)
775     {
776 	emsg(_("E242: Can't split a window while closing another"));
777 	return FAIL;
778     }
779     if (curwin->w_buffer->b_locked_split)
780     {
781 	emsg(_(e_cannot_split_window_when_closing_buffer));
782 	return FAIL;
783     }
784     return OK;
785 }
786 
787 /*
788  * split the current window, implements CTRL-W s and :split
789  *
790  * "size" is the height or width for the new window, 0 to use half of current
791  * height or width.
792  *
793  * "flags":
794  * WSP_ROOM: require enough room for new window
795  * WSP_VERT: vertical split.
796  * WSP_TOP:  open window at the top-left of the shell (help window).
797  * WSP_BOT:  open window at the bottom-right of the shell (quickfix window).
798  * WSP_HELP: creating the help window, keep layout snapshot
799  *
800  * return FAIL for failure, OK otherwise
801  */
802     int
803 win_split(int size, int flags)
804 {
805     if (ERROR_IF_ANY_POPUP_WINDOW)
806 	return FAIL;
807 
808     if (check_split_disallowed() == FAIL)
809 	return FAIL;
810 
811     // When the ":tab" modifier was used open a new tab page instead.
812     if (may_open_tabpage() == OK)
813 	return OK;
814 
815     // Add flags from ":vertical", ":topleft" and ":botright".
816     flags |= cmdmod.cmod_split;
817     if ((flags & WSP_TOP) && (flags & WSP_BOT))
818     {
819 	emsg(_("E442: Can't split topleft and botright at the same time"));
820 	return FAIL;
821     }
822 
823     // When creating the help window make a snapshot of the window layout.
824     // Otherwise clear the snapshot, it's now invalid.
825     if (flags & WSP_HELP)
826 	make_snapshot(SNAP_HELP_IDX);
827     else
828 	clear_snapshot(curtab, SNAP_HELP_IDX);
829 
830     return win_split_ins(size, flags, NULL, 0);
831 }
832 
833 /*
834  * When "new_wp" is NULL: split the current window in two.
835  * When "new_wp" is not NULL: insert this window at the far
836  * top/left/right/bottom.
837  * return FAIL for failure, OK otherwise
838  */
839     int
840 win_split_ins(
841     int		size,
842     int		flags,
843     win_T	*new_wp,
844     int		dir)
845 {
846     win_T	*wp = new_wp;
847     win_T	*oldwin;
848     int		new_size = size;
849     int		i;
850     int		need_status = 0;
851     int		do_equal = FALSE;
852     int		needed;
853     int		available;
854     int		oldwin_height = 0;
855     int		layout;
856     frame_T	*frp, *curfrp, *frp2, *prevfrp;
857     int		before;
858     int		minheight;
859     int		wmh1;
860     int		did_set_fraction = FALSE;
861 
862     if (flags & WSP_TOP)
863 	oldwin = firstwin;
864     else if (flags & WSP_BOT)
865 	oldwin = lastwin;
866     else
867 	oldwin = curwin;
868 
869     // add a status line when p_ls == 1 and splitting the first window
870     if (ONE_WINDOW && p_ls == 1 && oldwin->w_status_height == 0)
871     {
872 	if (VISIBLE_HEIGHT(oldwin) <= p_wmh && new_wp == NULL)
873 	{
874 	    emsg(_(e_not_enough_room));
875 	    return FAIL;
876 	}
877 	need_status = STATUS_HEIGHT;
878     }
879 
880 #ifdef FEAT_GUI
881     // May be needed for the scrollbars that are going to change.
882     if (gui.in_use)
883 	out_flush();
884 #endif
885 
886     if (flags & WSP_VERT)
887     {
888 	int	wmw1;
889 	int	minwidth;
890 
891 	layout = FR_ROW;
892 
893 	/*
894 	 * Check if we are able to split the current window and compute its
895 	 * width.
896 	 */
897 	// Current window requires at least 1 space.
898 	wmw1 = (p_wmw == 0 ? 1 : p_wmw);
899 	needed = wmw1 + 1;
900 	if (flags & WSP_ROOM)
901 	    needed += p_wiw - wmw1;
902 	if (flags & (WSP_BOT | WSP_TOP))
903 	{
904 	    minwidth = frame_minwidth(topframe, NOWIN);
905 	    available = topframe->fr_width;
906 	    needed += minwidth;
907 	}
908 	else if (p_ea)
909 	{
910 	    minwidth = frame_minwidth(oldwin->w_frame, NOWIN);
911 	    prevfrp = oldwin->w_frame;
912 	    for (frp = oldwin->w_frame->fr_parent; frp != NULL;
913 							frp = frp->fr_parent)
914 	    {
915 		if (frp->fr_layout == FR_ROW)
916 		    FOR_ALL_FRAMES(frp2, frp->fr_child)
917 			if (frp2 != prevfrp)
918 			    minwidth += frame_minwidth(frp2, NOWIN);
919 		prevfrp = frp;
920 	    }
921 	    available = topframe->fr_width;
922 	    needed += minwidth;
923 	}
924 	else
925 	{
926 	    minwidth = frame_minwidth(oldwin->w_frame, NOWIN);
927 	    available = oldwin->w_frame->fr_width;
928 	    needed += minwidth;
929 	}
930 	if (available < needed && new_wp == NULL)
931 	{
932 	    emsg(_(e_not_enough_room));
933 	    return FAIL;
934 	}
935 	if (new_size == 0)
936 	    new_size = oldwin->w_width / 2;
937 	if (new_size > available - minwidth - 1)
938 	    new_size = available - minwidth - 1;
939 	if (new_size < wmw1)
940 	    new_size = wmw1;
941 
942 	// if it doesn't fit in the current window, need win_equal()
943 	if (oldwin->w_width - new_size - 1 < p_wmw)
944 	    do_equal = TRUE;
945 
946 	// We don't like to take lines for the new window from a
947 	// 'winfixwidth' window.  Take them from a window to the left or right
948 	// instead, if possible. Add one for the separator.
949 	if (oldwin->w_p_wfw)
950 	    win_setwidth_win(oldwin->w_width + new_size + 1, oldwin);
951 
952 	// Only make all windows the same width if one of them (except oldwin)
953 	// is wider than one of the split windows.
954 	if (!do_equal && p_ea && size == 0 && *p_ead != 'v'
955 					 && oldwin->w_frame->fr_parent != NULL)
956 	{
957 	    frp = oldwin->w_frame->fr_parent->fr_child;
958 	    while (frp != NULL)
959 	    {
960 		if (frp->fr_win != oldwin && frp->fr_win != NULL
961 			&& (frp->fr_win->w_width > new_size
962 			    || frp->fr_win->w_width > oldwin->w_width
963 							      - new_size - 1))
964 		{
965 		    do_equal = TRUE;
966 		    break;
967 		}
968 		frp = frp->fr_next;
969 	    }
970 	}
971     }
972     else
973     {
974 	layout = FR_COL;
975 
976 	/*
977 	 * Check if we are able to split the current window and compute its
978 	 * height.
979 	 */
980 	// Current window requires at least 1 space.
981 	wmh1 = (p_wmh == 0 ? 1 : p_wmh) + WINBAR_HEIGHT(curwin);
982 	needed = wmh1 + STATUS_HEIGHT;
983 	if (flags & WSP_ROOM)
984 	    needed += p_wh - wmh1;
985 	if (flags & (WSP_BOT | WSP_TOP))
986 	{
987 	    minheight = frame_minheight(topframe, NOWIN) + need_status;
988 	    available = topframe->fr_height;
989 	    needed += minheight;
990 	}
991 	else if (p_ea)
992 	{
993 	    minheight = frame_minheight(oldwin->w_frame, NOWIN) + need_status;
994 	    prevfrp = oldwin->w_frame;
995 	    for (frp = oldwin->w_frame->fr_parent; frp != NULL;
996 							frp = frp->fr_parent)
997 	    {
998 		if (frp->fr_layout == FR_COL)
999 		    FOR_ALL_FRAMES(frp2, frp->fr_child)
1000 			if (frp2 != prevfrp)
1001 			    minheight += frame_minheight(frp2, NOWIN);
1002 		prevfrp = frp;
1003 	    }
1004 	    available = topframe->fr_height;
1005 	    needed += minheight;
1006 	}
1007 	else
1008 	{
1009 	    minheight = frame_minheight(oldwin->w_frame, NOWIN) + need_status;
1010 	    available = oldwin->w_frame->fr_height;
1011 	    needed += minheight;
1012 	}
1013 	if (available < needed && new_wp == NULL)
1014 	{
1015 	    emsg(_(e_not_enough_room));
1016 	    return FAIL;
1017 	}
1018 	oldwin_height = oldwin->w_height;
1019 	if (need_status)
1020 	{
1021 	    oldwin->w_status_height = STATUS_HEIGHT;
1022 	    oldwin_height -= STATUS_HEIGHT;
1023 	}
1024 	if (new_size == 0)
1025 	    new_size = oldwin_height / 2;
1026 	if (new_size > available - minheight - STATUS_HEIGHT)
1027 	    new_size = available - minheight - STATUS_HEIGHT;
1028 	if (new_size < wmh1)
1029 	    new_size = wmh1;
1030 
1031 	// if it doesn't fit in the current window, need win_equal()
1032 	if (oldwin_height - new_size - STATUS_HEIGHT < p_wmh)
1033 	    do_equal = TRUE;
1034 
1035 	// We don't like to take lines for the new window from a
1036 	// 'winfixheight' window.  Take them from a window above or below
1037 	// instead, if possible.
1038 	if (oldwin->w_p_wfh)
1039 	{
1040 	    // Set w_fraction now so that the cursor keeps the same relative
1041 	    // vertical position using the old height.
1042 	    set_fraction(oldwin);
1043 	    did_set_fraction = TRUE;
1044 
1045 	    win_setheight_win(oldwin->w_height + new_size + STATUS_HEIGHT,
1046 								      oldwin);
1047 	    oldwin_height = oldwin->w_height;
1048 	    if (need_status)
1049 		oldwin_height -= STATUS_HEIGHT;
1050 	}
1051 
1052 	// Only make all windows the same height if one of them (except oldwin)
1053 	// is higher than one of the split windows.
1054 	if (!do_equal && p_ea && size == 0 && *p_ead != 'h'
1055 	   && oldwin->w_frame->fr_parent != NULL)
1056 	{
1057 	    frp = oldwin->w_frame->fr_parent->fr_child;
1058 	    while (frp != NULL)
1059 	    {
1060 		if (frp->fr_win != oldwin && frp->fr_win != NULL
1061 			&& (frp->fr_win->w_height > new_size
1062 			    || frp->fr_win->w_height > oldwin_height - new_size
1063 							      - STATUS_HEIGHT))
1064 		{
1065 		    do_equal = TRUE;
1066 		    break;
1067 		}
1068 		frp = frp->fr_next;
1069 	    }
1070 	}
1071     }
1072 
1073     /*
1074      * allocate new window structure and link it in the window list
1075      */
1076     if ((flags & WSP_TOP) == 0
1077 	    && ((flags & WSP_BOT)
1078 		|| (flags & WSP_BELOW)
1079 		|| (!(flags & WSP_ABOVE)
1080 		    && ( (flags & WSP_VERT) ? p_spr : p_sb))))
1081     {
1082 	// new window below/right of current one
1083 	if (new_wp == NULL)
1084 	    wp = win_alloc(oldwin, FALSE);
1085 	else
1086 	    win_append(oldwin, wp);
1087     }
1088     else
1089     {
1090 	if (new_wp == NULL)
1091 	    wp = win_alloc(oldwin->w_prev, FALSE);
1092 	else
1093 	    win_append(oldwin->w_prev, wp);
1094     }
1095 
1096     if (new_wp == NULL)
1097     {
1098 	if (wp == NULL)
1099 	    return FAIL;
1100 
1101 	new_frame(wp);
1102 	if (wp->w_frame == NULL)
1103 	{
1104 	    win_free(wp, NULL);
1105 	    return FAIL;
1106 	}
1107 
1108 	// make the contents of the new window the same as the current one
1109 	win_init(wp, curwin, flags);
1110     }
1111 
1112     /*
1113      * Reorganise the tree of frames to insert the new window.
1114      */
1115     if (flags & (WSP_TOP | WSP_BOT))
1116     {
1117 	if ((topframe->fr_layout == FR_COL && (flags & WSP_VERT) == 0)
1118 	    || (topframe->fr_layout == FR_ROW && (flags & WSP_VERT) != 0))
1119 	{
1120 	    curfrp = topframe->fr_child;
1121 	    if (flags & WSP_BOT)
1122 		while (curfrp->fr_next != NULL)
1123 		    curfrp = curfrp->fr_next;
1124 	}
1125 	else
1126 	    curfrp = topframe;
1127 	before = (flags & WSP_TOP);
1128     }
1129     else
1130     {
1131 	curfrp = oldwin->w_frame;
1132 	if (flags & WSP_BELOW)
1133 	    before = FALSE;
1134 	else if (flags & WSP_ABOVE)
1135 	    before = TRUE;
1136 	else if (flags & WSP_VERT)
1137 	    before = !p_spr;
1138 	else
1139 	    before = !p_sb;
1140     }
1141     if (curfrp->fr_parent == NULL || curfrp->fr_parent->fr_layout != layout)
1142     {
1143 	// Need to create a new frame in the tree to make a branch.
1144 	frp = ALLOC_CLEAR_ONE(frame_T);
1145 	*frp = *curfrp;
1146 	curfrp->fr_layout = layout;
1147 	frp->fr_parent = curfrp;
1148 	frp->fr_next = NULL;
1149 	frp->fr_prev = NULL;
1150 	curfrp->fr_child = frp;
1151 	curfrp->fr_win = NULL;
1152 	curfrp = frp;
1153 	if (frp->fr_win != NULL)
1154 	    oldwin->w_frame = frp;
1155 	else
1156 	    FOR_ALL_FRAMES(frp, frp->fr_child)
1157 		frp->fr_parent = curfrp;
1158     }
1159 
1160     if (new_wp == NULL)
1161 	frp = wp->w_frame;
1162     else
1163 	frp = new_wp->w_frame;
1164     frp->fr_parent = curfrp->fr_parent;
1165 
1166     // Insert the new frame at the right place in the frame list.
1167     if (before)
1168 	frame_insert(curfrp, frp);
1169     else
1170 	frame_append(curfrp, frp);
1171 
1172     // Set w_fraction now so that the cursor keeps the same relative
1173     // vertical position.
1174     if (!did_set_fraction)
1175 	set_fraction(oldwin);
1176     wp->w_fraction = oldwin->w_fraction;
1177 
1178     if (flags & WSP_VERT)
1179     {
1180 	wp->w_p_scr = curwin->w_p_scr;
1181 
1182 	if (need_status)
1183 	{
1184 	    win_new_height(oldwin, oldwin->w_height - 1);
1185 	    oldwin->w_status_height = need_status;
1186 	}
1187 	if (flags & (WSP_TOP | WSP_BOT))
1188 	{
1189 	    // set height and row of new window to full height
1190 	    wp->w_winrow = tabline_height();
1191 	    win_new_height(wp, curfrp->fr_height - (p_ls > 0)
1192 							  - WINBAR_HEIGHT(wp));
1193 	    wp->w_status_height = (p_ls > 0);
1194 	}
1195 	else
1196 	{
1197 	    // height and row of new window is same as current window
1198 	    wp->w_winrow = oldwin->w_winrow;
1199 	    win_new_height(wp, VISIBLE_HEIGHT(oldwin));
1200 	    wp->w_status_height = oldwin->w_status_height;
1201 	}
1202 	frp->fr_height = curfrp->fr_height;
1203 
1204 	// "new_size" of the current window goes to the new window, use
1205 	// one column for the vertical separator
1206 	win_new_width(wp, new_size);
1207 	if (before)
1208 	    wp->w_vsep_width = 1;
1209 	else
1210 	{
1211 	    wp->w_vsep_width = oldwin->w_vsep_width;
1212 	    oldwin->w_vsep_width = 1;
1213 	}
1214 	if (flags & (WSP_TOP | WSP_BOT))
1215 	{
1216 	    if (flags & WSP_BOT)
1217 		frame_add_vsep(curfrp);
1218 	    // Set width of neighbor frame
1219 	    frame_new_width(curfrp, curfrp->fr_width
1220 		     - (new_size + ((flags & WSP_TOP) != 0)), flags & WSP_TOP,
1221 								       FALSE);
1222 	}
1223 	else
1224 	    win_new_width(oldwin, oldwin->w_width - (new_size + 1));
1225 	if (before)	// new window left of current one
1226 	{
1227 	    wp->w_wincol = oldwin->w_wincol;
1228 	    oldwin->w_wincol += new_size + 1;
1229 	}
1230 	else		// new window right of current one
1231 	    wp->w_wincol = oldwin->w_wincol + oldwin->w_width + 1;
1232 	frame_fix_width(oldwin);
1233 	frame_fix_width(wp);
1234     }
1235     else
1236     {
1237 	// width and column of new window is same as current window
1238 	if (flags & (WSP_TOP | WSP_BOT))
1239 	{
1240 	    wp->w_wincol = 0;
1241 	    win_new_width(wp, Columns);
1242 	    wp->w_vsep_width = 0;
1243 	}
1244 	else
1245 	{
1246 	    wp->w_wincol = oldwin->w_wincol;
1247 	    win_new_width(wp, oldwin->w_width);
1248 	    wp->w_vsep_width = oldwin->w_vsep_width;
1249 	}
1250 	frp->fr_width = curfrp->fr_width;
1251 
1252 	// "new_size" of the current window goes to the new window, use
1253 	// one row for the status line
1254 	win_new_height(wp, new_size);
1255 	if (flags & (WSP_TOP | WSP_BOT))
1256 	{
1257 	    int new_fr_height = curfrp->fr_height - new_size
1258 							  + WINBAR_HEIGHT(wp) ;
1259 
1260 	    if (!((flags & WSP_BOT) && p_ls == 0))
1261 		new_fr_height -= STATUS_HEIGHT;
1262 	    frame_new_height(curfrp, new_fr_height, flags & WSP_TOP, FALSE);
1263 	}
1264 	else
1265 	    win_new_height(oldwin, oldwin_height - (new_size + STATUS_HEIGHT));
1266 	if (before)	// new window above current one
1267 	{
1268 	    wp->w_winrow = oldwin->w_winrow;
1269 	    wp->w_status_height = STATUS_HEIGHT;
1270 	    oldwin->w_winrow += wp->w_height + STATUS_HEIGHT;
1271 	}
1272 	else		// new window below current one
1273 	{
1274 	    wp->w_winrow = oldwin->w_winrow + VISIBLE_HEIGHT(oldwin)
1275 							       + STATUS_HEIGHT;
1276 	    wp->w_status_height = oldwin->w_status_height;
1277 	    if (!(flags & WSP_BOT))
1278 		oldwin->w_status_height = STATUS_HEIGHT;
1279 	}
1280 	if (flags & WSP_BOT)
1281 	    frame_add_statusline(curfrp);
1282 	frame_fix_height(wp);
1283 	frame_fix_height(oldwin);
1284     }
1285 
1286     if (flags & (WSP_TOP | WSP_BOT))
1287 	(void)win_comp_pos();
1288 
1289      // Both windows need redrawing.  Update all status lines, in case they
1290      // show something related to the window count or position.
1291     redraw_win_later(wp, NOT_VALID);
1292     redraw_win_later(oldwin, NOT_VALID);
1293     status_redraw_all();
1294 
1295     if (need_status)
1296     {
1297 	msg_row = Rows - 1;
1298 	msg_col = sc_col;
1299 	msg_clr_eos_force();	// Old command/ruler may still be there
1300 	comp_col();
1301 	msg_row = Rows - 1;
1302 	msg_col = 0;	// put position back at start of line
1303     }
1304 
1305     /*
1306      * equalize the window sizes.
1307      */
1308     if (do_equal || dir != 0)
1309 	win_equal(wp, TRUE,
1310 		(flags & WSP_VERT) ? (dir == 'v' ? 'b' : 'h')
1311 		: dir == 'h' ? 'b' : 'v');
1312 
1313     // Don't change the window height/width to 'winheight' / 'winwidth' if a
1314     // size was given.
1315     if (flags & WSP_VERT)
1316     {
1317 	i = p_wiw;
1318 	if (size != 0)
1319 	    p_wiw = size;
1320 
1321 # ifdef FEAT_GUI
1322 	// When 'guioptions' includes 'L' or 'R' may have to add scrollbars.
1323 	if (gui.in_use)
1324 	    gui_init_which_components(NULL);
1325 # endif
1326     }
1327     else
1328     {
1329 	i = p_wh;
1330 	if (size != 0)
1331 	    p_wh = size;
1332     }
1333 
1334 #ifdef FEAT_JUMPLIST
1335     // Keep same changelist position in new window.
1336     wp->w_changelistidx = oldwin->w_changelistidx;
1337 #endif
1338 
1339     /*
1340      * make the new window the current window
1341      */
1342     (void)win_enter_ext(wp, WEE_TRIGGER_NEW_AUTOCMDS
1343 		    | WEE_TRIGGER_ENTER_AUTOCMDS | WEE_TRIGGER_LEAVE_AUTOCMDS);
1344     if (flags & WSP_VERT)
1345 	p_wiw = i;
1346     else
1347 	p_wh = i;
1348 
1349     return OK;
1350 }
1351 
1352 
1353 /*
1354  * Initialize window "newp" from window "oldp".
1355  * Used when splitting a window and when creating a new tab page.
1356  * The windows will both edit the same buffer.
1357  * WSP_NEWLOC may be specified in flags to prevent the location list from
1358  * being copied.
1359  */
1360     static void
1361 win_init(win_T *newp, win_T *oldp, int flags UNUSED)
1362 {
1363     int		i;
1364 
1365     newp->w_buffer = oldp->w_buffer;
1366 #ifdef FEAT_SYN_HL
1367     newp->w_s = &(oldp->w_buffer->b_s);
1368 #endif
1369     oldp->w_buffer->b_nwindows++;
1370     newp->w_cursor = oldp->w_cursor;
1371     newp->w_valid = 0;
1372     newp->w_curswant = oldp->w_curswant;
1373     newp->w_set_curswant = oldp->w_set_curswant;
1374     newp->w_topline = oldp->w_topline;
1375 #ifdef FEAT_DIFF
1376     newp->w_topfill = oldp->w_topfill;
1377 #endif
1378     newp->w_leftcol = oldp->w_leftcol;
1379     newp->w_pcmark = oldp->w_pcmark;
1380     newp->w_prev_pcmark = oldp->w_prev_pcmark;
1381     newp->w_alt_fnum = oldp->w_alt_fnum;
1382     newp->w_wrow = oldp->w_wrow;
1383     newp->w_fraction = oldp->w_fraction;
1384     newp->w_prev_fraction_row = oldp->w_prev_fraction_row;
1385 #ifdef FEAT_JUMPLIST
1386     copy_jumplist(oldp, newp);
1387 #endif
1388 #ifdef FEAT_QUICKFIX
1389     if (flags & WSP_NEWLOC)
1390     {
1391 	// Don't copy the location list.
1392 	newp->w_llist = NULL;
1393 	newp->w_llist_ref = NULL;
1394     }
1395     else
1396 	copy_loclist_stack(oldp, newp);
1397 #endif
1398     newp->w_localdir = (oldp->w_localdir == NULL)
1399 				    ? NULL : vim_strsave(oldp->w_localdir);
1400     newp->w_prevdir = (oldp->w_prevdir == NULL)
1401 				    ? NULL : vim_strsave(oldp->w_prevdir);
1402 
1403     // copy tagstack and folds
1404     for (i = 0; i < oldp->w_tagstacklen; i++)
1405     {
1406 	taggy_T	*tag = &newp->w_tagstack[i];
1407 	*tag = oldp->w_tagstack[i];
1408 	if (tag->tagname != NULL)
1409 	    tag->tagname = vim_strsave(tag->tagname);
1410 	if (tag->user_data != NULL)
1411 	    tag->user_data = vim_strsave(tag->user_data);
1412     }
1413     newp->w_tagstackidx = oldp->w_tagstackidx;
1414     newp->w_tagstacklen = oldp->w_tagstacklen;
1415 #ifdef FEAT_FOLDING
1416     copyFoldingState(oldp, newp);
1417 #endif
1418 
1419     win_init_some(newp, oldp);
1420 
1421 #ifdef FEAT_SYN_HL
1422     check_colorcolumn(newp);
1423 #endif
1424 }
1425 
1426 /*
1427  * Initialize window "newp" from window "old".
1428  * Only the essential things are copied.
1429  */
1430     static void
1431 win_init_some(win_T *newp, win_T *oldp)
1432 {
1433     // Use the same argument list.
1434     newp->w_alist = oldp->w_alist;
1435     ++newp->w_alist->al_refcount;
1436     newp->w_arg_idx = oldp->w_arg_idx;
1437 
1438     // copy options from existing window
1439     win_copy_options(oldp, newp);
1440 }
1441 
1442 /*
1443  * Return TRUE if "win" is a global popup or a popup in the current tab page.
1444  */
1445     int
1446 win_valid_popup(win_T *win UNUSED)
1447 {
1448 #ifdef FEAT_PROP_POPUP
1449     win_T	*wp;
1450 
1451     FOR_ALL_POPUPWINS(wp)
1452 	if (wp == win)
1453 	    return TRUE;
1454     FOR_ALL_POPUPWINS_IN_TAB(curtab, wp)
1455 	if (wp == win)
1456 	    return TRUE;
1457 #endif
1458     return FALSE;
1459 }
1460 
1461 /*
1462  * Check if "win" is a pointer to an existing window in the current tab page.
1463  */
1464     int
1465 win_valid(win_T *win)
1466 {
1467     win_T	*wp;
1468 
1469     if (win == NULL)
1470 	return FALSE;
1471     FOR_ALL_WINDOWS(wp)
1472 	if (wp == win)
1473 	    return TRUE;
1474     return win_valid_popup(win);
1475 }
1476 
1477 /*
1478  * Find window "id" in the current tab page.
1479  * Also find popup windows.
1480  * Return NULL if not found.
1481  */
1482     win_T *
1483 win_find_by_id(int id)
1484 {
1485     win_T   *wp;
1486 
1487     FOR_ALL_WINDOWS(wp)
1488 	if (wp->w_id == id)
1489 	    return wp;
1490 #ifdef FEAT_PROP_POPUP
1491     FOR_ALL_POPUPWINS(wp)
1492 	if (wp->w_id == id)
1493 	    return wp;
1494     FOR_ALL_POPUPWINS_IN_TAB(curtab, wp)
1495 	if (wp->w_id == id)
1496 	    return wp;
1497 #endif
1498     return NULL;
1499 }
1500 
1501 /*
1502  * Check if "win" is a pointer to an existing window in any tab page.
1503  */
1504     int
1505 win_valid_any_tab(win_T *win)
1506 {
1507     win_T	*wp;
1508     tabpage_T	*tp;
1509 
1510     if (win == NULL)
1511 	return FALSE;
1512     FOR_ALL_TABPAGES(tp)
1513     {
1514 	FOR_ALL_WINDOWS_IN_TAB(tp, wp)
1515 	{
1516 	    if (wp == win)
1517 		return TRUE;
1518 	}
1519 #ifdef FEAT_PROP_POPUP
1520 	FOR_ALL_POPUPWINS_IN_TAB(tp, wp)
1521 	    if (wp == win)
1522 		return TRUE;
1523 #endif
1524     }
1525     return win_valid_popup(win);
1526 }
1527 
1528 /*
1529  * Return the number of windows.
1530  */
1531     int
1532 win_count(void)
1533 {
1534     win_T	*wp;
1535     int		count = 0;
1536 
1537     FOR_ALL_WINDOWS(wp)
1538 	++count;
1539     return count;
1540 }
1541 
1542 /*
1543  * Make "count" windows on the screen.
1544  * Return actual number of windows on the screen.
1545  * Must be called when there is just one window, filling the whole screen
1546  * (excluding the command line).
1547  */
1548     int
1549 make_windows(
1550     int		count,
1551     int		vertical UNUSED)  // split windows vertically if TRUE
1552 {
1553     int		maxcount;
1554     int		todo;
1555 
1556     if (vertical)
1557     {
1558 	// Each windows needs at least 'winminwidth' lines and a separator
1559 	// column.
1560 	maxcount = (curwin->w_width + curwin->w_vsep_width
1561 					     - (p_wiw - p_wmw)) / (p_wmw + 1);
1562     }
1563     else
1564     {
1565 	// Each window needs at least 'winminheight' lines and a status line.
1566 	maxcount = (VISIBLE_HEIGHT(curwin) + curwin->w_status_height
1567 				  - (p_wh - p_wmh)) / (p_wmh + STATUS_HEIGHT);
1568     }
1569 
1570     if (maxcount < 2)
1571 	maxcount = 2;
1572     if (count > maxcount)
1573 	count = maxcount;
1574 
1575     /*
1576      * add status line now, otherwise first window will be too big
1577      */
1578     if (count > 1)
1579 	last_status(TRUE);
1580 
1581     /*
1582      * Don't execute autocommands while creating the windows.  Must do that
1583      * when putting the buffers in the windows.
1584      */
1585     block_autocmds();
1586 
1587     // todo is number of windows left to create
1588     for (todo = count - 1; todo > 0; --todo)
1589 	if (vertical)
1590 	{
1591 	    if (win_split(curwin->w_width - (curwin->w_width - todo)
1592 			/ (todo + 1) - 1, WSP_VERT | WSP_ABOVE) == FAIL)
1593 		break;
1594 	}
1595 	else
1596 	{
1597 	    if (win_split(curwin->w_height - (curwin->w_height - todo
1598 			    * STATUS_HEIGHT) / (todo + 1)
1599 			- STATUS_HEIGHT, WSP_ABOVE) == FAIL)
1600 		break;
1601 	}
1602 
1603     unblock_autocmds();
1604 
1605     // return actual number of windows
1606     return (count - todo);
1607 }
1608 
1609 /*
1610  * Exchange current and next window
1611  */
1612     static void
1613 win_exchange(long Prenum)
1614 {
1615     frame_T	*frp;
1616     frame_T	*frp2;
1617     win_T	*wp;
1618     win_T	*wp2;
1619     int		temp;
1620 
1621     if (ERROR_IF_ANY_POPUP_WINDOW)
1622 	return;
1623     if (ONE_WINDOW)	    // just one window
1624     {
1625 	beep_flush();
1626 	return;
1627     }
1628 
1629 #ifdef FEAT_GUI
1630     need_mouse_correct = TRUE;
1631 #endif
1632 
1633     /*
1634      * find window to exchange with
1635      */
1636     if (Prenum)
1637     {
1638 	frp = curwin->w_frame->fr_parent->fr_child;
1639 	while (frp != NULL && --Prenum > 0)
1640 	    frp = frp->fr_next;
1641     }
1642     else if (curwin->w_frame->fr_next != NULL)	// Swap with next
1643 	frp = curwin->w_frame->fr_next;
1644     else    // Swap last window in row/col with previous
1645 	frp = curwin->w_frame->fr_prev;
1646 
1647     // We can only exchange a window with another window, not with a frame
1648     // containing windows.
1649     if (frp == NULL || frp->fr_win == NULL || frp->fr_win == curwin)
1650 	return;
1651     wp = frp->fr_win;
1652 
1653 /*
1654  * 1. remove curwin from the list. Remember after which window it was in wp2
1655  * 2. insert curwin before wp in the list
1656  * if wp != wp2
1657  *    3. remove wp from the list
1658  *    4. insert wp after wp2
1659  * 5. exchange the status line height and vsep width.
1660  */
1661     wp2 = curwin->w_prev;
1662     frp2 = curwin->w_frame->fr_prev;
1663     if (wp->w_prev != curwin)
1664     {
1665 	win_remove(curwin, NULL);
1666 	frame_remove(curwin->w_frame);
1667 	win_append(wp->w_prev, curwin);
1668 	frame_insert(frp, curwin->w_frame);
1669     }
1670     if (wp != wp2)
1671     {
1672 	win_remove(wp, NULL);
1673 	frame_remove(wp->w_frame);
1674 	win_append(wp2, wp);
1675 	if (frp2 == NULL)
1676 	    frame_insert(wp->w_frame->fr_parent->fr_child, wp->w_frame);
1677 	else
1678 	    frame_append(frp2, wp->w_frame);
1679     }
1680     temp = curwin->w_status_height;
1681     curwin->w_status_height = wp->w_status_height;
1682     wp->w_status_height = temp;
1683     temp = curwin->w_vsep_width;
1684     curwin->w_vsep_width = wp->w_vsep_width;
1685     wp->w_vsep_width = temp;
1686 
1687     // If the windows are not in the same frame, exchange the sizes to avoid
1688     // messing up the window layout.  Otherwise fix the frame sizes.
1689     if (curwin->w_frame->fr_parent != wp->w_frame->fr_parent)
1690     {
1691 	temp = curwin->w_height;
1692 	curwin->w_height = wp->w_height;
1693 	wp->w_height = temp;
1694 	temp = curwin->w_width;
1695 	curwin->w_width = wp->w_width;
1696 	wp->w_width = temp;
1697     }
1698     else
1699     {
1700 	frame_fix_height(curwin);
1701 	frame_fix_height(wp);
1702 	frame_fix_width(curwin);
1703 	frame_fix_width(wp);
1704     }
1705 
1706     (void)win_comp_pos();		// recompute window positions
1707 
1708     win_enter(wp, TRUE);
1709     redraw_all_later(NOT_VALID);
1710 }
1711 
1712 /*
1713  * rotate windows: if upwards TRUE the second window becomes the first one
1714  *		   if upwards FALSE the first window becomes the second one
1715  */
1716     static void
1717 win_rotate(int upwards, int count)
1718 {
1719     win_T	*wp1;
1720     win_T	*wp2;
1721     frame_T	*frp;
1722     int		n;
1723 
1724     if (ONE_WINDOW)		// nothing to do
1725     {
1726 	beep_flush();
1727 	return;
1728     }
1729 
1730 #ifdef FEAT_GUI
1731     need_mouse_correct = TRUE;
1732 #endif
1733 
1734     // Check if all frames in this row/col have one window.
1735     FOR_ALL_FRAMES(frp, curwin->w_frame->fr_parent->fr_child)
1736 	if (frp->fr_win == NULL)
1737 	{
1738 	    emsg(_("E443: Cannot rotate when another window is split"));
1739 	    return;
1740 	}
1741 
1742     while (count--)
1743     {
1744 	if (upwards)		// first window becomes last window
1745 	{
1746 	    // remove first window/frame from the list
1747 	    frp = curwin->w_frame->fr_parent->fr_child;
1748 	    wp1 = frp->fr_win;
1749 	    win_remove(wp1, NULL);
1750 	    frame_remove(frp);
1751 
1752 	    // find last frame and append removed window/frame after it
1753 	    for ( ; frp->fr_next != NULL; frp = frp->fr_next)
1754 		;
1755 	    win_append(frp->fr_win, wp1);
1756 	    frame_append(frp, wp1->w_frame);
1757 
1758 	    wp2 = frp->fr_win;		// previously last window
1759 	}
1760 	else			// last window becomes first window
1761 	{
1762 	    // find last window/frame in the list and remove it
1763 	    for (frp = curwin->w_frame; frp->fr_next != NULL;
1764 							   frp = frp->fr_next)
1765 		;
1766 	    wp1 = frp->fr_win;
1767 	    wp2 = wp1->w_prev;		    // will become last window
1768 	    win_remove(wp1, NULL);
1769 	    frame_remove(frp);
1770 
1771 	    // append the removed window/frame before the first in the list
1772 	    win_append(frp->fr_parent->fr_child->fr_win->w_prev, wp1);
1773 	    frame_insert(frp->fr_parent->fr_child, frp);
1774 	}
1775 
1776 	// exchange status height and vsep width of old and new last window
1777 	n = wp2->w_status_height;
1778 	wp2->w_status_height = wp1->w_status_height;
1779 	wp1->w_status_height = n;
1780 	frame_fix_height(wp1);
1781 	frame_fix_height(wp2);
1782 	n = wp2->w_vsep_width;
1783 	wp2->w_vsep_width = wp1->w_vsep_width;
1784 	wp1->w_vsep_width = n;
1785 	frame_fix_width(wp1);
1786 	frame_fix_width(wp2);
1787 
1788 	// recompute w_winrow and w_wincol for all windows
1789 	(void)win_comp_pos();
1790     }
1791 
1792     redraw_all_later(NOT_VALID);
1793 }
1794 
1795 /*
1796  * Move the current window to the very top/bottom/left/right of the screen.
1797  */
1798     static void
1799 win_totop(int size, int flags)
1800 {
1801     int		dir;
1802     int		height = curwin->w_height;
1803 
1804     if (ONE_WINDOW)
1805     {
1806 	beep_flush();
1807 	return;
1808     }
1809     if (check_split_disallowed() == FAIL)
1810 	return;
1811 
1812     // Remove the window and frame from the tree of frames.
1813     (void)winframe_remove(curwin, &dir, NULL);
1814     win_remove(curwin, NULL);
1815     last_status(FALSE);	    // may need to remove last status line
1816     (void)win_comp_pos();   // recompute window positions
1817 
1818     // Split a window on the desired side and put the window there.
1819     (void)win_split_ins(size, flags, curwin, dir);
1820     if (!(flags & WSP_VERT))
1821     {
1822 	win_setheight(height);
1823 	if (p_ea)
1824 	    win_equal(curwin, TRUE, 'v');
1825     }
1826 
1827 #if defined(FEAT_GUI)
1828     // When 'guioptions' includes 'L' or 'R' may have to remove or add
1829     // scrollbars.  Have to update them anyway.
1830     gui_may_update_scrollbars();
1831 #endif
1832 }
1833 
1834 /*
1835  * Move window "win1" to below/right of "win2" and make "win1" the current
1836  * window.  Only works within the same frame!
1837  */
1838     void
1839 win_move_after(win_T *win1, win_T *win2)
1840 {
1841     int		height;
1842 
1843     // check if the arguments are reasonable
1844     if (win1 == win2)
1845 	return;
1846 
1847     // check if there is something to do
1848     if (win2->w_next != win1)
1849     {
1850 	if (win1->w_frame->fr_parent != win2->w_frame->fr_parent)
1851 	{
1852 	    iemsg("INTERNAL: trying to move a window into another frame");
1853 	    return;
1854 	}
1855 
1856 	// may need to move the status line/vertical separator of the last
1857 	// window
1858 	if (win1 == lastwin)
1859 	{
1860 	    height = win1->w_prev->w_status_height;
1861 	    win1->w_prev->w_status_height = win1->w_status_height;
1862 	    win1->w_status_height = height;
1863 	    if (win1->w_prev->w_vsep_width == 1)
1864 	    {
1865 		// Remove the vertical separator from the last-but-one window,
1866 		// add it to the last window.  Adjust the frame widths.
1867 		win1->w_prev->w_vsep_width = 0;
1868 		win1->w_prev->w_frame->fr_width -= 1;
1869 		win1->w_vsep_width = 1;
1870 		win1->w_frame->fr_width += 1;
1871 	    }
1872 	}
1873 	else if (win2 == lastwin)
1874 	{
1875 	    height = win1->w_status_height;
1876 	    win1->w_status_height = win2->w_status_height;
1877 	    win2->w_status_height = height;
1878 	    if (win1->w_vsep_width == 1)
1879 	    {
1880 		// Remove the vertical separator from win1, add it to the last
1881 		// window, win2.  Adjust the frame widths.
1882 		win2->w_vsep_width = 1;
1883 		win2->w_frame->fr_width += 1;
1884 		win1->w_vsep_width = 0;
1885 		win1->w_frame->fr_width -= 1;
1886 	    }
1887 	}
1888 	win_remove(win1, NULL);
1889 	frame_remove(win1->w_frame);
1890 	win_append(win2, win1);
1891 	frame_append(win2->w_frame, win1->w_frame);
1892 
1893 	(void)win_comp_pos();	// recompute w_winrow for all windows
1894 	redraw_later(NOT_VALID);
1895     }
1896     win_enter(win1, FALSE);
1897 }
1898 
1899 /*
1900  * Make all windows the same height.
1901  * 'next_curwin' will soon be the current window, make sure it has enough
1902  * rows.
1903  */
1904     void
1905 win_equal(
1906     win_T	*next_curwin,	// pointer to current window to be or NULL
1907     int		current,	// do only frame with current window
1908     int		dir)		// 'v' for vertically, 'h' for horizontally,
1909 				// 'b' for both, 0 for using p_ead
1910 {
1911     if (dir == 0)
1912 	dir = *p_ead;
1913     win_equal_rec(next_curwin == NULL ? curwin : next_curwin, current,
1914 		      topframe, dir, 0, tabline_height(),
1915 					   (int)Columns, topframe->fr_height);
1916 }
1917 
1918 /*
1919  * Set a frame to a new position and height, spreading the available room
1920  * equally over contained frames.
1921  * The window "next_curwin" (if not NULL) should at least get the size from
1922  * 'winheight' and 'winwidth' if possible.
1923  */
1924     static void
1925 win_equal_rec(
1926     win_T	*next_curwin,	// pointer to current window to be or NULL
1927     int		current,	// do only frame with current window
1928     frame_T	*topfr,		// frame to set size off
1929     int		dir,		// 'v', 'h' or 'b', see win_equal()
1930     int		col,		// horizontal position for frame
1931     int		row,		// vertical position for frame
1932     int		width,		// new width of frame
1933     int		height)		// new height of frame
1934 {
1935     int		n, m;
1936     int		extra_sep = 0;
1937     int		wincount, totwincount = 0;
1938     frame_T	*fr;
1939     int		next_curwin_size = 0;
1940     int		room = 0;
1941     int		new_size;
1942     int		has_next_curwin = 0;
1943     int		hnc;
1944 
1945     if (topfr->fr_layout == FR_LEAF)
1946     {
1947 	// Set the width/height of this frame.
1948 	// Redraw when size or position changes
1949 	if (topfr->fr_height != height || topfr->fr_win->w_winrow != row
1950 		|| topfr->fr_width != width || topfr->fr_win->w_wincol != col
1951 	   )
1952 	{
1953 	    topfr->fr_win->w_winrow = row;
1954 	    frame_new_height(topfr, height, FALSE, FALSE);
1955 	    topfr->fr_win->w_wincol = col;
1956 	    frame_new_width(topfr, width, FALSE, FALSE);
1957 	    redraw_all_later(NOT_VALID);
1958 	}
1959     }
1960     else if (topfr->fr_layout == FR_ROW)
1961     {
1962 	topfr->fr_width = width;
1963 	topfr->fr_height = height;
1964 
1965 	if (dir != 'v')			// equalize frame widths
1966 	{
1967 	    // Compute the maximum number of windows horizontally in this
1968 	    // frame.
1969 	    n = frame_minwidth(topfr, NOWIN);
1970 	    // add one for the rightmost window, it doesn't have a separator
1971 	    if (col + width == Columns)
1972 		extra_sep = 1;
1973 	    else
1974 		extra_sep = 0;
1975 	    totwincount = (n + extra_sep) / (p_wmw + 1);
1976 	    has_next_curwin = frame_has_win(topfr, next_curwin);
1977 
1978 	    /*
1979 	     * Compute width for "next_curwin" window and room available for
1980 	     * other windows.
1981 	     * "m" is the minimal width when counting p_wiw for "next_curwin".
1982 	     */
1983 	    m = frame_minwidth(topfr, next_curwin);
1984 	    room = width - m;
1985 	    if (room < 0)
1986 	    {
1987 		next_curwin_size = p_wiw + room;
1988 		room = 0;
1989 	    }
1990 	    else
1991 	    {
1992 		next_curwin_size = -1;
1993 		FOR_ALL_FRAMES(fr, topfr->fr_child)
1994 		{
1995 		    // If 'winfixwidth' set keep the window width if
1996 		    // possible.
1997 		    // Watch out for this window being the next_curwin.
1998 		    if (frame_fixed_width(fr))
1999 		    {
2000 			n = frame_minwidth(fr, NOWIN);
2001 			new_size = fr->fr_width;
2002 			if (frame_has_win(fr, next_curwin))
2003 			{
2004 			    room += p_wiw - p_wmw;
2005 			    next_curwin_size = 0;
2006 			    if (new_size < p_wiw)
2007 				new_size = p_wiw;
2008 			}
2009 			else
2010 			    // These windows don't use up room.
2011 			    totwincount -= (n + (fr->fr_next == NULL
2012 					      ? extra_sep : 0)) / (p_wmw + 1);
2013 			room -= new_size - n;
2014 			if (room < 0)
2015 			{
2016 			    new_size += room;
2017 			    room = 0;
2018 			}
2019 			fr->fr_newwidth = new_size;
2020 		    }
2021 		}
2022 		if (next_curwin_size == -1)
2023 		{
2024 		    if (!has_next_curwin)
2025 			next_curwin_size = 0;
2026 		    else if (totwincount > 1
2027 			    && (room + (totwincount - 2))
2028 						  / (totwincount - 1) > p_wiw)
2029 		    {
2030 			// Can make all windows wider than 'winwidth', spread
2031 			// the room equally.
2032 			next_curwin_size = (room + p_wiw
2033 					    + (totwincount - 1) * p_wmw
2034 					    + (totwincount - 1)) / totwincount;
2035 			room -= next_curwin_size - p_wiw;
2036 		    }
2037 		    else
2038 			next_curwin_size = p_wiw;
2039 		}
2040 	    }
2041 
2042 	    if (has_next_curwin)
2043 		--totwincount;		// don't count curwin
2044 	}
2045 
2046 	FOR_ALL_FRAMES(fr, topfr->fr_child)
2047 	{
2048 	    wincount = 1;
2049 	    if (fr->fr_next == NULL)
2050 		// last frame gets all that remains (avoid roundoff error)
2051 		new_size = width;
2052 	    else if (dir == 'v')
2053 		new_size = fr->fr_width;
2054 	    else if (frame_fixed_width(fr))
2055 	    {
2056 		new_size = fr->fr_newwidth;
2057 		wincount = 0;	    // doesn't count as a sizeable window
2058 	    }
2059 	    else
2060 	    {
2061 		// Compute the maximum number of windows horiz. in "fr".
2062 		n = frame_minwidth(fr, NOWIN);
2063 		wincount = (n + (fr->fr_next == NULL ? extra_sep : 0))
2064 								/ (p_wmw + 1);
2065 		m = frame_minwidth(fr, next_curwin);
2066 		if (has_next_curwin)
2067 		    hnc = frame_has_win(fr, next_curwin);
2068 		else
2069 		    hnc = FALSE;
2070 		if (hnc)	    // don't count next_curwin
2071 		    --wincount;
2072 		if (totwincount == 0)
2073 		    new_size = room;
2074 		else
2075 		    new_size = (wincount * room + ((unsigned)totwincount >> 1))
2076 								/ totwincount;
2077 		if (hnc)	    // add next_curwin size
2078 		{
2079 		    next_curwin_size -= p_wiw - (m - n);
2080 		    new_size += next_curwin_size;
2081 		    room -= new_size - next_curwin_size;
2082 		}
2083 		else
2084 		    room -= new_size;
2085 		new_size += n;
2086 	    }
2087 
2088 	    // Skip frame that is full width when splitting or closing a
2089 	    // window, unless equalizing all frames.
2090 	    if (!current || dir != 'v' || topfr->fr_parent != NULL
2091 		    || (new_size != fr->fr_width)
2092 		    || frame_has_win(fr, next_curwin))
2093 		win_equal_rec(next_curwin, current, fr, dir, col, row,
2094 							    new_size, height);
2095 	    col += new_size;
2096 	    width -= new_size;
2097 	    totwincount -= wincount;
2098 	}
2099     }
2100     else // topfr->fr_layout == FR_COL
2101     {
2102 	topfr->fr_width = width;
2103 	topfr->fr_height = height;
2104 
2105 	if (dir != 'h')			// equalize frame heights
2106 	{
2107 	    // Compute maximum number of windows vertically in this frame.
2108 	    n = frame_minheight(topfr, NOWIN);
2109 	    // add one for the bottom window if it doesn't have a statusline
2110 	    if (row + height == cmdline_row && p_ls == 0)
2111 		extra_sep = 1;
2112 	    else
2113 		extra_sep = 0;
2114 	    totwincount = (n + extra_sep) / (p_wmh + 1);
2115 	    has_next_curwin = frame_has_win(topfr, next_curwin);
2116 
2117 	    /*
2118 	     * Compute height for "next_curwin" window and room available for
2119 	     * other windows.
2120 	     * "m" is the minimal height when counting p_wh for "next_curwin".
2121 	     */
2122 	    m = frame_minheight(topfr, next_curwin);
2123 	    room = height - m;
2124 	    if (room < 0)
2125 	    {
2126 		// The room is less then 'winheight', use all space for the
2127 		// current window.
2128 		next_curwin_size = p_wh + room;
2129 		room = 0;
2130 	    }
2131 	    else
2132 	    {
2133 		next_curwin_size = -1;
2134 		FOR_ALL_FRAMES(fr, topfr->fr_child)
2135 		{
2136 		    // If 'winfixheight' set keep the window height if
2137 		    // possible.
2138 		    // Watch out for this window being the next_curwin.
2139 		    if (frame_fixed_height(fr))
2140 		    {
2141 			n = frame_minheight(fr, NOWIN);
2142 			new_size = fr->fr_height;
2143 			if (frame_has_win(fr, next_curwin))
2144 			{
2145 			    room += p_wh - p_wmh;
2146 			    next_curwin_size = 0;
2147 			    if (new_size < p_wh)
2148 				new_size = p_wh;
2149 			}
2150 			else
2151 			    // These windows don't use up room.
2152 			    totwincount -= (n + (fr->fr_next == NULL
2153 					      ? extra_sep : 0)) / (p_wmh + 1);
2154 			room -= new_size - n;
2155 			if (room < 0)
2156 			{
2157 			    new_size += room;
2158 			    room = 0;
2159 			}
2160 			fr->fr_newheight = new_size;
2161 		    }
2162 		}
2163 		if (next_curwin_size == -1)
2164 		{
2165 		    if (!has_next_curwin)
2166 			next_curwin_size = 0;
2167 		    else if (totwincount > 1
2168 			    && (room + (totwincount - 2))
2169 						   / (totwincount - 1) > p_wh)
2170 		    {
2171 			// can make all windows higher than 'winheight',
2172 			// spread the room equally.
2173 			next_curwin_size = (room + p_wh
2174 					   + (totwincount - 1) * p_wmh
2175 					   + (totwincount - 1)) / totwincount;
2176 			room -= next_curwin_size - p_wh;
2177 		    }
2178 		    else
2179 			next_curwin_size = p_wh;
2180 		}
2181 	    }
2182 
2183 	    if (has_next_curwin)
2184 		--totwincount;		// don't count curwin
2185 	}
2186 
2187 	FOR_ALL_FRAMES(fr, topfr->fr_child)
2188 	{
2189 	    wincount = 1;
2190 	    if (fr->fr_next == NULL)
2191 		// last frame gets all that remains (avoid roundoff error)
2192 		new_size = height;
2193 	    else if (dir == 'h')
2194 		new_size = fr->fr_height;
2195 	    else if (frame_fixed_height(fr))
2196 	    {
2197 		new_size = fr->fr_newheight;
2198 		wincount = 0;	    // doesn't count as a sizeable window
2199 	    }
2200 	    else
2201 	    {
2202 		// Compute the maximum number of windows vert. in "fr".
2203 		n = frame_minheight(fr, NOWIN);
2204 		wincount = (n + (fr->fr_next == NULL ? extra_sep : 0))
2205 								/ (p_wmh + 1);
2206 		m = frame_minheight(fr, next_curwin);
2207 		if (has_next_curwin)
2208 		    hnc = frame_has_win(fr, next_curwin);
2209 		else
2210 		    hnc = FALSE;
2211 		if (hnc)	    // don't count next_curwin
2212 		    --wincount;
2213 		if (totwincount == 0)
2214 		    new_size = room;
2215 		else
2216 		    new_size = (wincount * room + ((unsigned)totwincount >> 1))
2217 								/ totwincount;
2218 		if (hnc)	    // add next_curwin size
2219 		{
2220 		    next_curwin_size -= p_wh - (m - n);
2221 		    new_size += next_curwin_size;
2222 		    room -= new_size - next_curwin_size;
2223 		}
2224 		else
2225 		    room -= new_size;
2226 		new_size += n;
2227 	    }
2228 	    // Skip frame that is full width when splitting or closing a
2229 	    // window, unless equalizing all frames.
2230 	    if (!current || dir != 'h' || topfr->fr_parent != NULL
2231 		    || (new_size != fr->fr_height)
2232 		    || frame_has_win(fr, next_curwin))
2233 		win_equal_rec(next_curwin, current, fr, dir, col, row,
2234 							     width, new_size);
2235 	    row += new_size;
2236 	    height -= new_size;
2237 	    totwincount -= wincount;
2238 	}
2239     }
2240 }
2241 
2242 #ifdef FEAT_JOB_CHANNEL
2243     static void
2244 leaving_window(win_T *win)
2245 {
2246     // Only matters for a prompt window.
2247     if (!bt_prompt(win->w_buffer))
2248 	return;
2249 
2250     // When leaving a prompt window stop Insert mode and perhaps restart
2251     // it when entering that window again.
2252     win->w_buffer->b_prompt_insert = restart_edit;
2253     if (restart_edit != 0 && mode_displayed)
2254 	clear_cmdline = TRUE;		// unshow mode later
2255     restart_edit = NUL;
2256 
2257     // When leaving the window (or closing the window) was done from a
2258     // callback we need to break out of the Insert mode loop and restart Insert
2259     // mode when entering the window again.
2260     if (State & INSERT)
2261     {
2262 	stop_insert_mode = TRUE;
2263 	if (win->w_buffer->b_prompt_insert == NUL)
2264 	    win->w_buffer->b_prompt_insert = 'A';
2265     }
2266 }
2267 
2268     void
2269 entering_window(win_T *win)
2270 {
2271     // Only matters for a prompt window.
2272     if (!bt_prompt(win->w_buffer))
2273 	return;
2274 
2275     // When switching to a prompt buffer that was in Insert mode, don't stop
2276     // Insert mode, it may have been set in leaving_window().
2277     if (win->w_buffer->b_prompt_insert != NUL)
2278 	stop_insert_mode = FALSE;
2279 
2280     // When entering the prompt window restart Insert mode if we were in Insert
2281     // mode when we left it.
2282     restart_edit = win->w_buffer->b_prompt_insert;
2283 }
2284 #endif
2285 
2286 /*
2287  * Close all windows for buffer "buf".
2288  */
2289     void
2290 close_windows(
2291     buf_T	*buf,
2292     int		keep_curwin)	    // don't close "curwin"
2293 {
2294     win_T	*wp;
2295     tabpage_T   *tp, *nexttp;
2296     int		h = tabline_height();
2297     int		count = tabpage_index(NULL);
2298 
2299     ++RedrawingDisabled;
2300 
2301     for (wp = firstwin; wp != NULL && !ONE_WINDOW; )
2302     {
2303 	if (wp->w_buffer == buf && (!keep_curwin || wp != curwin)
2304 		&& !(wp->w_closing || wp->w_buffer->b_locked > 0))
2305 	{
2306 	    if (win_close(wp, FALSE) == FAIL)
2307 		// If closing the window fails give up, to avoid looping
2308 		// forever.
2309 		break;
2310 
2311 	    // Start all over, autocommands may change the window layout.
2312 	    wp = firstwin;
2313 	}
2314 	else
2315 	    wp = wp->w_next;
2316     }
2317 
2318     // Also check windows in other tab pages.
2319     for (tp = first_tabpage; tp != NULL; tp = nexttp)
2320     {
2321 	nexttp = tp->tp_next;
2322 	if (tp != curtab)
2323 	    FOR_ALL_WINDOWS_IN_TAB(tp, wp)
2324 		if (wp->w_buffer == buf
2325 		    && !(wp->w_closing || wp->w_buffer->b_locked > 0))
2326 		{
2327 		    win_close_othertab(wp, FALSE, tp);
2328 
2329 		    // Start all over, the tab page may be closed and
2330 		    // autocommands may change the window layout.
2331 		    nexttp = first_tabpage;
2332 		    break;
2333 		}
2334     }
2335 
2336     --RedrawingDisabled;
2337 
2338     if (count != tabpage_index(NULL))
2339 	apply_autocmds(EVENT_TABCLOSED, NULL, NULL, FALSE, curbuf);
2340 
2341     redraw_tabline = TRUE;
2342     if (h != tabline_height())
2343 	shell_new_rows();
2344 }
2345 
2346 /*
2347  * Return TRUE if the current window is the only window that exists (ignoring
2348  * "aucmd_win").
2349  * Returns FALSE if there is a window, possibly in another tab page.
2350  */
2351     static int
2352 last_window(void)
2353 {
2354     return (one_window() && first_tabpage->tp_next == NULL);
2355 }
2356 
2357 /*
2358  * Return TRUE if there is only one window other than "aucmd_win" in the
2359  * current tab page.
2360  */
2361     int
2362 one_window(void)
2363 {
2364     win_T	*wp;
2365     int		seen_one = FALSE;
2366 
2367     FOR_ALL_WINDOWS(wp)
2368     {
2369 	if (wp != aucmd_win)
2370 	{
2371 	    if (seen_one)
2372 		return FALSE;
2373 	    seen_one = TRUE;
2374 	}
2375     }
2376     return TRUE;
2377 }
2378 
2379 /*
2380  * Close the possibly last window in a tab page.
2381  * Returns TRUE when the window was closed already.
2382  */
2383     static int
2384 close_last_window_tabpage(
2385     win_T	*win,
2386     int		free_buf,
2387     tabpage_T   *prev_curtab)
2388 {
2389     if (ONE_WINDOW)
2390     {
2391 	buf_T	*old_curbuf = curbuf;
2392 
2393 	/*
2394 	 * Closing the last window in a tab page.  First go to another tab
2395 	 * page and then close the window and the tab page.  This avoids that
2396 	 * curwin and curtab are invalid while we are freeing memory, they may
2397 	 * be used in GUI events.
2398 	 * Don't trigger autocommands yet, they may use wrong values, so do
2399 	 * that below.
2400 	 */
2401 	goto_tabpage_tp(alt_tabpage(), FALSE, TRUE);
2402 	redraw_tabline = TRUE;
2403 
2404 	// Safety check: Autocommands may have closed the window when jumping
2405 	// to the other tab page.
2406 	if (valid_tabpage(prev_curtab) && prev_curtab->tp_firstwin == win)
2407 	{
2408 	    int	    h = tabline_height();
2409 
2410 	    win_close_othertab(win, free_buf, prev_curtab);
2411 	    if (h != tabline_height())
2412 		shell_new_rows();
2413 	}
2414 #ifdef FEAT_JOB_CHANNEL
2415 	entering_window(curwin);
2416 #endif
2417 	// Since goto_tabpage_tp above did not trigger *Enter autocommands, do
2418 	// that now.
2419 	apply_autocmds(EVENT_TABCLOSED, NULL, NULL, FALSE, curbuf);
2420 	apply_autocmds(EVENT_WINENTER, NULL, NULL, FALSE, curbuf);
2421 	apply_autocmds(EVENT_TABENTER, NULL, NULL, FALSE, curbuf);
2422 	if (old_curbuf != curbuf)
2423 	    apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
2424 	return TRUE;
2425     }
2426     return FALSE;
2427 }
2428 
2429 /*
2430  * Close the buffer of "win" and unload it if "action" is DOBUF_UNLOAD.
2431  * "action" can also be zero (do nothing) or DOBUF_WIPE.
2432  * "abort_if_last" is passed to close_buffer(): abort closing if all other
2433  * windows are closed.
2434  */
2435     static void
2436 win_close_buffer(win_T *win, int action, int abort_if_last)
2437 {
2438 #ifdef FEAT_SYN_HL
2439     // Free independent synblock before the buffer is freed.
2440     if (win->w_buffer != NULL)
2441 	reset_synblock(win);
2442 #endif
2443 
2444 #ifdef FEAT_QUICKFIX
2445     // When the quickfix/location list window is closed, unlist the buffer.
2446     if (win->w_buffer != NULL && bt_quickfix(win->w_buffer))
2447 	win->w_buffer->b_p_bl = FALSE;
2448 #endif
2449 
2450     // Close the link to the buffer.
2451     if (win->w_buffer != NULL)
2452     {
2453 	bufref_T    bufref;
2454 
2455 	set_bufref(&bufref, curbuf);
2456 	win->w_closing = TRUE;
2457 	close_buffer(win, win->w_buffer, action, abort_if_last, FALSE);
2458 	if (win_valid_any_tab(win))
2459 	    win->w_closing = FALSE;
2460 	// Make sure curbuf is valid. It can become invalid if 'bufhidden' is
2461 	// "wipe".
2462 	if (!bufref_valid(&bufref))
2463 	    curbuf = firstbuf;
2464     }
2465 }
2466 
2467 /*
2468  * Close window "win".  Only works for the current tab page.
2469  * If "free_buf" is TRUE related buffer may be unloaded.
2470  *
2471  * Called by :quit, :close, :xit, :wq and findtag().
2472  * Returns FAIL when the window was not closed.
2473  */
2474     int
2475 win_close(win_T *win, int free_buf)
2476 {
2477     win_T	*wp;
2478     int		other_buffer = FALSE;
2479     int		close_curwin = FALSE;
2480     int		dir;
2481     int		help_window = FALSE;
2482     tabpage_T   *prev_curtab = curtab;
2483     frame_T	*win_frame = win->w_frame->fr_parent;
2484 #ifdef FEAT_DIFF
2485     int		had_diffmode = win->w_p_diff;
2486 #endif
2487 #ifdef MESSAGE_QUEUE
2488     int		did_decrement = FALSE;
2489 #endif
2490 
2491 #if defined(FEAT_TERMINAL) && defined(FEAT_PROP_POPUP)
2492     // Can close a popup window with a terminal if the job has finished.
2493     if (may_close_term_popup() == OK)
2494 	return OK;
2495 #endif
2496     if (ERROR_IF_ANY_POPUP_WINDOW)
2497 	return FAIL;
2498 
2499     if (last_window())
2500     {
2501 	emsg(_("E444: Cannot close last window"));
2502 	return FAIL;
2503     }
2504 
2505     if (win->w_closing || (win->w_buffer != NULL
2506 					       && win->w_buffer->b_locked > 0))
2507 	return FAIL; // window is already being closed
2508     if (win_unlisted(win))
2509     {
2510 	emsg(_(e_autocmd_close));
2511 	return FAIL;
2512     }
2513     if ((firstwin == aucmd_win || lastwin == aucmd_win) && one_window())
2514     {
2515 	emsg(_("E814: Cannot close window, only autocmd window would remain"));
2516 	return FAIL;
2517     }
2518 
2519     // When closing the last window in a tab page first go to another tab page
2520     // and then close the window and the tab page to avoid that curwin and
2521     // curtab are invalid while we are freeing memory.
2522     if (close_last_window_tabpage(win, free_buf, prev_curtab))
2523       return FAIL;
2524 
2525     // When closing the help window, try restoring a snapshot after closing
2526     // the window.  Otherwise clear the snapshot, it's now invalid.
2527     if (bt_help(win->w_buffer))
2528 	help_window = TRUE;
2529     else
2530 	clear_snapshot(curtab, SNAP_HELP_IDX);
2531 
2532     if (win == curwin)
2533     {
2534 #ifdef FEAT_JOB_CHANNEL
2535 	leaving_window(curwin);
2536 #endif
2537 	/*
2538 	 * Guess which window is going to be the new current window.
2539 	 * This may change because of the autocommands (sigh).
2540 	 */
2541 	wp = frame2win(win_altframe(win, NULL));
2542 
2543 	/*
2544 	 * Be careful: If autocommands delete the window or cause this window
2545 	 * to be the last one left, return now.
2546 	 */
2547 	if (wp->w_buffer != curbuf)
2548 	{
2549 	    other_buffer = TRUE;
2550 	    win->w_closing = TRUE;
2551 	    apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf);
2552 	    if (!win_valid(win))
2553 		return FAIL;
2554 	    win->w_closing = FALSE;
2555 	    if (last_window())
2556 		return FAIL;
2557 	}
2558 	win->w_closing = TRUE;
2559 	apply_autocmds(EVENT_WINLEAVE, NULL, NULL, FALSE, curbuf);
2560 	if (!win_valid(win))
2561 	    return FAIL;
2562 	win->w_closing = FALSE;
2563 	if (last_window())
2564 	    return FAIL;
2565 #ifdef FEAT_EVAL
2566 	// autocmds may abort script processing
2567 	if (aborting())
2568 	    return FAIL;
2569 #endif
2570     }
2571 
2572 #ifdef FEAT_GUI
2573     // Avoid trouble with scrollbars that are going to be deleted in
2574     // win_free().
2575     if (gui.in_use)
2576 	out_flush();
2577 #endif
2578 
2579 #ifdef FEAT_PROP_POPUP
2580     if (popup_win_closed(win) && !win_valid(win))
2581 	return FAIL;
2582 #endif
2583     win_close_buffer(win, free_buf ? DOBUF_UNLOAD : 0, TRUE);
2584 
2585     if (only_one_window() && win_valid(win) && win->w_buffer == NULL
2586 	    && (last_window() || curtab != prev_curtab
2587 		|| close_last_window_tabpage(win, free_buf, prev_curtab)))
2588     {
2589 	// Autocommands have closed all windows, quit now.  Restore
2590 	// curwin->w_buffer, otherwise writing viminfo may fail.
2591 	if (curwin->w_buffer == NULL)
2592 	    curwin->w_buffer = curbuf;
2593 	getout(0);
2594     }
2595 
2596     // Autocommands may have moved to another tab page.
2597     if (curtab != prev_curtab && win_valid_any_tab(win)
2598 						      && win->w_buffer == NULL)
2599     {
2600 	// Need to close the window anyway, since the buffer is NULL.
2601 	win_close_othertab(win, FALSE, prev_curtab);
2602 	return FAIL;
2603     }
2604 
2605     // Autocommands may have closed the window already or closed the only
2606     // other window.
2607     if (!win_valid(win) || last_window()
2608 	    || close_last_window_tabpage(win, free_buf, prev_curtab))
2609 	return FAIL;
2610 
2611     // Now we are really going to close the window.  Disallow any autocommand
2612     // to split a window to avoid trouble.
2613     // Also bail out of parse_queued_messages() to avoid it tries to update the
2614     // screen.
2615     ++split_disallowed;
2616 #ifdef MESSAGE_QUEUE
2617     ++dont_parse_messages;
2618 #endif
2619 
2620     // Free the memory used for the window and get the window that received
2621     // the screen space.
2622     wp = win_free_mem(win, &dir, NULL);
2623 
2624     // Make sure curwin isn't invalid.  It can cause severe trouble when
2625     // printing an error message.  For win_equal() curbuf needs to be valid
2626     // too.
2627     if (win == curwin)
2628     {
2629 	curwin = wp;
2630 #ifdef FEAT_QUICKFIX
2631 	if (wp->w_p_pvw || bt_quickfix(wp->w_buffer))
2632 	{
2633 	    /*
2634 	     * If the cursor goes to the preview or the quickfix window, try
2635 	     * finding another window to go to.
2636 	     */
2637 	    for (;;)
2638 	    {
2639 		if (wp->w_next == NULL)
2640 		    wp = firstwin;
2641 		else
2642 		    wp = wp->w_next;
2643 		if (wp == curwin)
2644 		    break;
2645 		if (!wp->w_p_pvw && !bt_quickfix(wp->w_buffer))
2646 		{
2647 		    curwin = wp;
2648 		    break;
2649 		}
2650 	    }
2651 	}
2652 #endif
2653 	curbuf = curwin->w_buffer;
2654 	close_curwin = TRUE;
2655 
2656 	// The cursor position may be invalid if the buffer changed after last
2657 	// using the window.
2658 	check_cursor();
2659     }
2660     if (p_ea && (*p_ead == 'b' || *p_ead == dir))
2661 	// If the frame of the closed window contains the new current window,
2662 	// only resize that frame.  Otherwise resize all windows.
2663 	win_equal(curwin, curwin->w_frame->fr_parent == win_frame, dir);
2664     else
2665 	win_comp_pos();
2666     if (close_curwin)
2667     {
2668 	// Pass WEE_ALLOW_PARSE_MESSAGES to decrement dont_parse_messages
2669 	// before autocommands.
2670 #ifdef MESSAGE_QUEUE
2671 	did_decrement =
2672 #else
2673 	(void)
2674 #endif
2675 	    win_enter_ext(wp,
2676 		WEE_CURWIN_INVALID | WEE_TRIGGER_ENTER_AUTOCMDS
2677 		      | WEE_TRIGGER_LEAVE_AUTOCMDS | WEE_ALLOW_PARSE_MESSAGES);
2678 	if (other_buffer)
2679 	    // careful: after this wp and win may be invalid!
2680 	    apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
2681     }
2682 
2683     --split_disallowed;
2684 #ifdef MESSAGE_QUEUE
2685     if (!did_decrement)
2686 	--dont_parse_messages;
2687 #endif
2688 
2689     /*
2690      * If last window has a status line now and we don't want one,
2691      * remove the status line.
2692      */
2693     last_status(FALSE);
2694 
2695     // After closing the help window, try restoring the window layout from
2696     // before it was opened.
2697     if (help_window)
2698 	restore_snapshot(SNAP_HELP_IDX, close_curwin);
2699 
2700 #ifdef FEAT_DIFF
2701     // If the window had 'diff' set and now there is only one window left in
2702     // the tab page with 'diff' set, and "closeoff" is in 'diffopt', then
2703     // execute ":diffoff!".
2704     if (diffopt_closeoff() && had_diffmode && curtab == prev_curtab)
2705     {
2706 	int	diffcount = 0;
2707 	win_T	*dwin;
2708 
2709 	FOR_ALL_WINDOWS(dwin)
2710 	    if (dwin->w_p_diff)
2711 		++diffcount;
2712 	if (diffcount == 1)
2713 	    do_cmdline_cmd((char_u *)"diffoff!");
2714     }
2715 #endif
2716 
2717 #if defined(FEAT_GUI)
2718     // When 'guioptions' includes 'L' or 'R' may have to remove scrollbars.
2719     if (gui.in_use && !win_hasvertsplit())
2720 	gui_init_which_components(NULL);
2721 #endif
2722 
2723     redraw_all_later(NOT_VALID);
2724     return OK;
2725 }
2726 
2727 /*
2728  * Close window "win" in tab page "tp", which is not the current tab page.
2729  * This may be the last window in that tab page and result in closing the tab,
2730  * thus "tp" may become invalid!
2731  * Caller must check if buffer is hidden and whether the tabline needs to be
2732  * updated.
2733  */
2734     void
2735 win_close_othertab(win_T *win, int free_buf, tabpage_T *tp)
2736 {
2737     win_T	*wp;
2738     int		dir;
2739     tabpage_T   *ptp = NULL;
2740     int		free_tp = FALSE;
2741 
2742     // Get here with win->w_buffer == NULL when win_close() detects the tab
2743     // page changed.
2744     if (win->w_closing || (win->w_buffer != NULL
2745 					       && win->w_buffer->b_locked > 0))
2746 	return; // window is already being closed
2747 
2748     if (win->w_buffer != NULL)
2749 	// Close the link to the buffer.
2750 	close_buffer(win, win->w_buffer, free_buf ? DOBUF_UNLOAD : 0,
2751 								 FALSE, FALSE);
2752 
2753     // Careful: Autocommands may have closed the tab page or made it the
2754     // current tab page.
2755     for (ptp = first_tabpage; ptp != NULL && ptp != tp; ptp = ptp->tp_next)
2756 	;
2757     if (ptp == NULL || tp == curtab)
2758 	return;
2759 
2760     // Autocommands may have closed the window already.
2761     for (wp = tp->tp_firstwin; wp != NULL && wp != win; wp = wp->w_next)
2762 	;
2763     if (wp == NULL)
2764 	return;
2765 
2766     // When closing the last window in a tab page remove the tab page.
2767     if (tp->tp_firstwin == tp->tp_lastwin)
2768     {
2769 	if (tp == first_tabpage)
2770 	    first_tabpage = tp->tp_next;
2771 	else
2772 	{
2773 	    for (ptp = first_tabpage; ptp != NULL && ptp->tp_next != tp;
2774 							   ptp = ptp->tp_next)
2775 		;
2776 	    if (ptp == NULL)
2777 	    {
2778 		internal_error("win_close_othertab()");
2779 		return;
2780 	    }
2781 	    ptp->tp_next = tp->tp_next;
2782 	}
2783 	free_tp = TRUE;
2784     }
2785 
2786     // Free the memory used for the window.
2787     win_free_mem(win, &dir, tp);
2788 
2789     if (free_tp)
2790 	free_tabpage(tp);
2791 }
2792 
2793 /*
2794  * Free the memory used for a window.
2795  * Returns a pointer to the window that got the freed up space.
2796  */
2797     static win_T *
2798 win_free_mem(
2799     win_T	*win,
2800     int		*dirp,		// set to 'v' or 'h' for direction if 'ea'
2801     tabpage_T	*tp)		// tab page "win" is in, NULL for current
2802 {
2803     frame_T	*frp;
2804     win_T	*wp;
2805     tabpage_T	*win_tp = tp == NULL ? curtab : tp;
2806 
2807     // Remove the window and its frame from the tree of frames.
2808     frp = win->w_frame;
2809     wp = winframe_remove(win, dirp, tp);
2810     vim_free(frp);
2811     win_free(win, tp);
2812 
2813     // When deleting the current window in the tab, select a new current
2814     // window.
2815     if (win == win_tp->tp_curwin)
2816 	win_tp->tp_curwin = wp;
2817 
2818     return wp;
2819 }
2820 
2821 #if defined(EXITFREE) || defined(PROTO)
2822     void
2823 win_free_all(void)
2824 {
2825     int		dummy;
2826 
2827     while (first_tabpage->tp_next != NULL)
2828 	tabpage_close(TRUE);
2829 
2830     if (aucmd_win != NULL)
2831     {
2832 	(void)win_free_mem(aucmd_win, &dummy, NULL);
2833 	aucmd_win = NULL;
2834     }
2835 
2836     while (firstwin != NULL)
2837 	(void)win_free_mem(firstwin, &dummy, NULL);
2838 
2839     // No window should be used after this. Set curwin to NULL to crash
2840     // instead of using freed memory.
2841     curwin = NULL;
2842 }
2843 #endif
2844 
2845 /*
2846  * Remove a window and its frame from the tree of frames.
2847  * Returns a pointer to the window that got the freed up space.
2848  */
2849     win_T *
2850 winframe_remove(
2851     win_T	*win,
2852     int		*dirp UNUSED,	// set to 'v' or 'h' for direction if 'ea'
2853     tabpage_T	*tp)		// tab page "win" is in, NULL for current
2854 {
2855     frame_T	*frp, *frp2, *frp3;
2856     frame_T	*frp_close = win->w_frame;
2857     win_T	*wp;
2858 
2859     /*
2860      * If there is only one window there is nothing to remove.
2861      */
2862     if (tp == NULL ? ONE_WINDOW : tp->tp_firstwin == tp->tp_lastwin)
2863 	return NULL;
2864 
2865     /*
2866      * Remove the window from its frame.
2867      */
2868     frp2 = win_altframe(win, tp);
2869     wp = frame2win(frp2);
2870 
2871     // Remove this frame from the list of frames.
2872     frame_remove(frp_close);
2873 
2874     if (frp_close->fr_parent->fr_layout == FR_COL)
2875     {
2876 	// When 'winfixheight' is set, try to find another frame in the column
2877 	// (as close to the closed frame as possible) to distribute the height
2878 	// to.
2879 	if (frp2->fr_win != NULL && frp2->fr_win->w_p_wfh)
2880 	{
2881 	    frp = frp_close->fr_prev;
2882 	    frp3 = frp_close->fr_next;
2883 	    while (frp != NULL || frp3 != NULL)
2884 	    {
2885 		if (frp != NULL)
2886 		{
2887 		    if (!frame_fixed_height(frp))
2888 		    {
2889 			frp2 = frp;
2890 			wp = frame2win(frp2);
2891 			break;
2892 		    }
2893 		    frp = frp->fr_prev;
2894 		}
2895 		if (frp3 != NULL)
2896 		{
2897 		    if (frp3->fr_win != NULL && !frp3->fr_win->w_p_wfh)
2898 		    {
2899 			frp2 = frp3;
2900 			wp = frp3->fr_win;
2901 			break;
2902 		    }
2903 		    frp3 = frp3->fr_next;
2904 		}
2905 	    }
2906 	}
2907 	frame_new_height(frp2, frp2->fr_height + frp_close->fr_height,
2908 			    frp2 == frp_close->fr_next ? TRUE : FALSE, FALSE);
2909 	*dirp = 'v';
2910     }
2911     else
2912     {
2913 	// When 'winfixwidth' is set, try to find another frame in the column
2914 	// (as close to the closed frame as possible) to distribute the width
2915 	// to.
2916 	if (frp2->fr_win != NULL && frp2->fr_win->w_p_wfw)
2917 	{
2918 	    frp = frp_close->fr_prev;
2919 	    frp3 = frp_close->fr_next;
2920 	    while (frp != NULL || frp3 != NULL)
2921 	    {
2922 		if (frp != NULL)
2923 		{
2924 		    if (!frame_fixed_width(frp))
2925 		    {
2926 			frp2 = frp;
2927 			wp = frame2win(frp2);
2928 			break;
2929 		    }
2930 		    frp = frp->fr_prev;
2931 		}
2932 		if (frp3 != NULL)
2933 		{
2934 		    if (frp3->fr_win != NULL && !frp3->fr_win->w_p_wfw)
2935 		    {
2936 			frp2 = frp3;
2937 			wp = frp3->fr_win;
2938 			break;
2939 		    }
2940 		    frp3 = frp3->fr_next;
2941 		}
2942 	    }
2943 	}
2944 	frame_new_width(frp2, frp2->fr_width + frp_close->fr_width,
2945 			    frp2 == frp_close->fr_next ? TRUE : FALSE, FALSE);
2946 	*dirp = 'h';
2947     }
2948 
2949     // If rows/columns go to a window below/right its positions need to be
2950     // updated.  Can only be done after the sizes have been updated.
2951     if (frp2 == frp_close->fr_next)
2952     {
2953 	int row = win->w_winrow;
2954 	int col = win->w_wincol;
2955 
2956 	frame_comp_pos(frp2, &row, &col);
2957     }
2958 
2959     if (frp2->fr_next == NULL && frp2->fr_prev == NULL)
2960     {
2961 	// There is no other frame in this list, move its info to the parent
2962 	// and remove it.
2963 	frp2->fr_parent->fr_layout = frp2->fr_layout;
2964 	frp2->fr_parent->fr_child = frp2->fr_child;
2965 	FOR_ALL_FRAMES(frp, frp2->fr_child)
2966 	    frp->fr_parent = frp2->fr_parent;
2967 	frp2->fr_parent->fr_win = frp2->fr_win;
2968 	if (frp2->fr_win != NULL)
2969 	    frp2->fr_win->w_frame = frp2->fr_parent;
2970 	frp = frp2->fr_parent;
2971 	if (topframe->fr_child == frp2)
2972 	    topframe->fr_child = frp;
2973 	vim_free(frp2);
2974 
2975 	frp2 = frp->fr_parent;
2976 	if (frp2 != NULL && frp2->fr_layout == frp->fr_layout)
2977 	{
2978 	    // The frame above the parent has the same layout, have to merge
2979 	    // the frames into this list.
2980 	    if (frp2->fr_child == frp)
2981 		frp2->fr_child = frp->fr_child;
2982 	    frp->fr_child->fr_prev = frp->fr_prev;
2983 	    if (frp->fr_prev != NULL)
2984 		frp->fr_prev->fr_next = frp->fr_child;
2985 	    for (frp3 = frp->fr_child; ; frp3 = frp3->fr_next)
2986 	    {
2987 		frp3->fr_parent = frp2;
2988 		if (frp3->fr_next == NULL)
2989 		{
2990 		    frp3->fr_next = frp->fr_next;
2991 		    if (frp->fr_next != NULL)
2992 			frp->fr_next->fr_prev = frp3;
2993 		    break;
2994 		}
2995 	    }
2996 	    if (topframe->fr_child == frp)
2997 		topframe->fr_child = frp2;
2998 	    vim_free(frp);
2999 	}
3000     }
3001 
3002     return wp;
3003 }
3004 
3005 /*
3006  * Return a pointer to the frame that will receive the empty screen space that
3007  * is left over after "win" is closed.
3008  *
3009  * If 'splitbelow' or 'splitright' is set, the space goes above or to the left
3010  * by default.  Otherwise, the free space goes below or to the right.  The
3011  * result is that opening a window and then immediately closing it will
3012  * preserve the initial window layout.  The 'wfh' and 'wfw' settings are
3013  * respected when possible.
3014  */
3015     static frame_T *
3016 win_altframe(
3017     win_T	*win,
3018     tabpage_T	*tp)		// tab page "win" is in, NULL for current
3019 {
3020     frame_T	*frp;
3021     frame_T	*other_fr, *target_fr;
3022 
3023     if (tp == NULL ? ONE_WINDOW : tp->tp_firstwin == tp->tp_lastwin)
3024 	return alt_tabpage()->tp_curwin->w_frame;
3025 
3026     frp = win->w_frame;
3027 
3028     if (frp->fr_prev == NULL)
3029 	return frp->fr_next;
3030     if (frp->fr_next == NULL)
3031 	return frp->fr_prev;
3032 
3033     // By default the next window will get the space that was abandoned by this
3034     // window
3035     target_fr = frp->fr_next;
3036     other_fr  = frp->fr_prev;
3037 
3038     // If this is part of a column of windows and 'splitbelow' is true then the
3039     // previous window will get the space.
3040     if (frp->fr_parent != NULL && frp->fr_parent->fr_layout == FR_COL && p_sb)
3041     {
3042 	target_fr = frp->fr_prev;
3043 	other_fr  = frp->fr_next;
3044     }
3045 
3046     // If this is part of a row of windows, and 'splitright' is true then the
3047     // previous window will get the space.
3048     if (frp->fr_parent != NULL && frp->fr_parent->fr_layout == FR_ROW && p_spr)
3049     {
3050 	target_fr = frp->fr_prev;
3051 	other_fr  = frp->fr_next;
3052     }
3053 
3054     // If 'wfh' or 'wfw' is set for the target and not for the alternate
3055     // window, reverse the selection.
3056     if (frp->fr_parent != NULL && frp->fr_parent->fr_layout == FR_ROW)
3057     {
3058 	if (frame_fixed_width(target_fr) && !frame_fixed_width(other_fr))
3059 	    target_fr = other_fr;
3060     }
3061     else
3062     {
3063 	if (frame_fixed_height(target_fr) && !frame_fixed_height(other_fr))
3064 	    target_fr = other_fr;
3065     }
3066 
3067     return target_fr;
3068 }
3069 
3070 /*
3071  * Return the tabpage that will be used if the current one is closed.
3072  */
3073     static tabpage_T *
3074 alt_tabpage(void)
3075 {
3076     tabpage_T	*tp;
3077 
3078     // Use the next tab page if possible.
3079     if (curtab->tp_next != NULL)
3080 	return curtab->tp_next;
3081 
3082     // Find the last but one tab page.
3083     for (tp = first_tabpage; tp->tp_next != curtab; tp = tp->tp_next)
3084 	;
3085     return tp;
3086 }
3087 
3088 /*
3089  * Find the left-upper window in frame "frp".
3090  */
3091     static win_T *
3092 frame2win(frame_T *frp)
3093 {
3094     while (frp->fr_win == NULL)
3095 	frp = frp->fr_child;
3096     return frp->fr_win;
3097 }
3098 
3099 /*
3100  * Return TRUE if frame "frp" contains window "wp".
3101  */
3102     static int
3103 frame_has_win(frame_T *frp, win_T *wp)
3104 {
3105     frame_T	*p;
3106 
3107     if (frp->fr_layout == FR_LEAF)
3108 	return frp->fr_win == wp;
3109 
3110     FOR_ALL_FRAMES(p, frp->fr_child)
3111 	if (frame_has_win(p, wp))
3112 	    return TRUE;
3113     return FALSE;
3114 }
3115 
3116 /*
3117  * Set a new height for a frame.  Recursively sets the height for contained
3118  * frames and windows.  Caller must take care of positions.
3119  */
3120     static void
3121 frame_new_height(
3122     frame_T	*topfrp,
3123     int		height,
3124     int		topfirst,	// resize topmost contained frame first
3125     int		wfh)		// obey 'winfixheight' when there is a choice;
3126 				// may cause the height not to be set
3127 {
3128     frame_T	*frp;
3129     int		extra_lines;
3130     int		h;
3131 
3132     if (topfrp->fr_win != NULL)
3133     {
3134 	// Simple case: just one window.
3135 	win_new_height(topfrp->fr_win,
3136 				    height - topfrp->fr_win->w_status_height
3137 					      - WINBAR_HEIGHT(topfrp->fr_win));
3138     }
3139     else if (topfrp->fr_layout == FR_ROW)
3140     {
3141 	do
3142 	{
3143 	    // All frames in this row get the same new height.
3144 	    FOR_ALL_FRAMES(frp, topfrp->fr_child)
3145 	    {
3146 		frame_new_height(frp, height, topfirst, wfh);
3147 		if (frp->fr_height > height)
3148 		{
3149 		    // Could not fit the windows, make the whole row higher.
3150 		    height = frp->fr_height;
3151 		    break;
3152 		}
3153 	    }
3154 	}
3155 	while (frp != NULL);
3156     }
3157     else    // fr_layout == FR_COL
3158     {
3159 	// Complicated case: Resize a column of frames.  Resize the bottom
3160 	// frame first, frames above that when needed.
3161 
3162 	frp = topfrp->fr_child;
3163 	if (wfh)
3164 	    // Advance past frames with one window with 'wfh' set.
3165 	    while (frame_fixed_height(frp))
3166 	    {
3167 		frp = frp->fr_next;
3168 		if (frp == NULL)
3169 		    return;	    // no frame without 'wfh', give up
3170 	    }
3171 	if (!topfirst)
3172 	{
3173 	    // Find the bottom frame of this column
3174 	    while (frp->fr_next != NULL)
3175 		frp = frp->fr_next;
3176 	    if (wfh)
3177 		// Advance back for frames with one window with 'wfh' set.
3178 		while (frame_fixed_height(frp))
3179 		    frp = frp->fr_prev;
3180 	}
3181 
3182 	extra_lines = height - topfrp->fr_height;
3183 	if (extra_lines < 0)
3184 	{
3185 	    // reduce height of contained frames, bottom or top frame first
3186 	    while (frp != NULL)
3187 	    {
3188 		h = frame_minheight(frp, NULL);
3189 		if (frp->fr_height + extra_lines < h)
3190 		{
3191 		    extra_lines += frp->fr_height - h;
3192 		    frame_new_height(frp, h, topfirst, wfh);
3193 		}
3194 		else
3195 		{
3196 		    frame_new_height(frp, frp->fr_height + extra_lines,
3197 							       topfirst, wfh);
3198 		    break;
3199 		}
3200 		if (topfirst)
3201 		{
3202 		    do
3203 			frp = frp->fr_next;
3204 		    while (wfh && frp != NULL && frame_fixed_height(frp));
3205 		}
3206 		else
3207 		{
3208 		    do
3209 			frp = frp->fr_prev;
3210 		    while (wfh && frp != NULL && frame_fixed_height(frp));
3211 		}
3212 		// Increase "height" if we could not reduce enough frames.
3213 		if (frp == NULL)
3214 		    height -= extra_lines;
3215 	    }
3216 	}
3217 	else if (extra_lines > 0)
3218 	{
3219 	    // increase height of bottom or top frame
3220 	    frame_new_height(frp, frp->fr_height + extra_lines, topfirst, wfh);
3221 	}
3222     }
3223     topfrp->fr_height = height;
3224 }
3225 
3226 /*
3227  * Return TRUE if height of frame "frp" should not be changed because of
3228  * the 'winfixheight' option.
3229  */
3230     static int
3231 frame_fixed_height(frame_T *frp)
3232 {
3233     // frame with one window: fixed height if 'winfixheight' set.
3234     if (frp->fr_win != NULL)
3235 	return frp->fr_win->w_p_wfh;
3236 
3237     if (frp->fr_layout == FR_ROW)
3238     {
3239 	// The frame is fixed height if one of the frames in the row is fixed
3240 	// height.
3241 	FOR_ALL_FRAMES(frp, frp->fr_child)
3242 	    if (frame_fixed_height(frp))
3243 		return TRUE;
3244 	return FALSE;
3245     }
3246 
3247     // frp->fr_layout == FR_COL: The frame is fixed height if all of the
3248     // frames in the row are fixed height.
3249     FOR_ALL_FRAMES(frp, frp->fr_child)
3250 	if (!frame_fixed_height(frp))
3251 	    return FALSE;
3252     return TRUE;
3253 }
3254 
3255 /*
3256  * Return TRUE if width of frame "frp" should not be changed because of
3257  * the 'winfixwidth' option.
3258  */
3259     static int
3260 frame_fixed_width(frame_T *frp)
3261 {
3262     // frame with one window: fixed width if 'winfixwidth' set.
3263     if (frp->fr_win != NULL)
3264 	return frp->fr_win->w_p_wfw;
3265 
3266     if (frp->fr_layout == FR_COL)
3267     {
3268 	// The frame is fixed width if one of the frames in the row is fixed
3269 	// width.
3270 	FOR_ALL_FRAMES(frp, frp->fr_child)
3271 	    if (frame_fixed_width(frp))
3272 		return TRUE;
3273 	return FALSE;
3274     }
3275 
3276     // frp->fr_layout == FR_ROW: The frame is fixed width if all of the
3277     // frames in the row are fixed width.
3278     FOR_ALL_FRAMES(frp, frp->fr_child)
3279 	if (!frame_fixed_width(frp))
3280 	    return FALSE;
3281     return TRUE;
3282 }
3283 
3284 /*
3285  * Add a status line to windows at the bottom of "frp".
3286  * Note: Does not check if there is room!
3287  */
3288     static void
3289 frame_add_statusline(frame_T *frp)
3290 {
3291     win_T	*wp;
3292 
3293     if (frp->fr_layout == FR_LEAF)
3294     {
3295 	wp = frp->fr_win;
3296 	if (wp->w_status_height == 0)
3297 	{
3298 	    if (wp->w_height > 0)	// don't make it negative
3299 		--wp->w_height;
3300 	    wp->w_status_height = STATUS_HEIGHT;
3301 	}
3302     }
3303     else if (frp->fr_layout == FR_ROW)
3304     {
3305 	// Handle all the frames in the row.
3306 	FOR_ALL_FRAMES(frp, frp->fr_child)
3307 	    frame_add_statusline(frp);
3308     }
3309     else // frp->fr_layout == FR_COL
3310     {
3311 	// Only need to handle the last frame in the column.
3312 	for (frp = frp->fr_child; frp->fr_next != NULL; frp = frp->fr_next)
3313 	    ;
3314 	frame_add_statusline(frp);
3315     }
3316 }
3317 
3318 /*
3319  * Set width of a frame.  Handles recursively going through contained frames.
3320  * May remove separator line for windows at the right side (for win_close()).
3321  */
3322     static void
3323 frame_new_width(
3324     frame_T	*topfrp,
3325     int		width,
3326     int		leftfirst,	// resize leftmost contained frame first
3327     int		wfw)		// obey 'winfixwidth' when there is a choice;
3328 				// may cause the width not to be set
3329 {
3330     frame_T	*frp;
3331     int		extra_cols;
3332     int		w;
3333     win_T	*wp;
3334 
3335     if (topfrp->fr_layout == FR_LEAF)
3336     {
3337 	// Simple case: just one window.
3338 	wp = topfrp->fr_win;
3339 	// Find out if there are any windows right of this one.
3340 	for (frp = topfrp; frp->fr_parent != NULL; frp = frp->fr_parent)
3341 	    if (frp->fr_parent->fr_layout == FR_ROW && frp->fr_next != NULL)
3342 		break;
3343 	if (frp->fr_parent == NULL)
3344 	    wp->w_vsep_width = 0;
3345 	win_new_width(wp, width - wp->w_vsep_width);
3346     }
3347     else if (topfrp->fr_layout == FR_COL)
3348     {
3349 	do
3350 	{
3351 	    // All frames in this column get the same new width.
3352 	    FOR_ALL_FRAMES(frp, topfrp->fr_child)
3353 	    {
3354 		frame_new_width(frp, width, leftfirst, wfw);
3355 		if (frp->fr_width > width)
3356 		{
3357 		    // Could not fit the windows, make whole column wider.
3358 		    width = frp->fr_width;
3359 		    break;
3360 		}
3361 	    }
3362 	} while (frp != NULL);
3363     }
3364     else    // fr_layout == FR_ROW
3365     {
3366 	// Complicated case: Resize a row of frames.  Resize the rightmost
3367 	// frame first, frames left of it when needed.
3368 
3369 	frp = topfrp->fr_child;
3370 	if (wfw)
3371 	    // Advance past frames with one window with 'wfw' set.
3372 	    while (frame_fixed_width(frp))
3373 	    {
3374 		frp = frp->fr_next;
3375 		if (frp == NULL)
3376 		    return;	    // no frame without 'wfw', give up
3377 	    }
3378 	if (!leftfirst)
3379 	{
3380 	    // Find the rightmost frame of this row
3381 	    while (frp->fr_next != NULL)
3382 		frp = frp->fr_next;
3383 	    if (wfw)
3384 		// Advance back for frames with one window with 'wfw' set.
3385 		while (frame_fixed_width(frp))
3386 		    frp = frp->fr_prev;
3387 	}
3388 
3389 	extra_cols = width - topfrp->fr_width;
3390 	if (extra_cols < 0)
3391 	{
3392 	    // reduce frame width, rightmost frame first
3393 	    while (frp != NULL)
3394 	    {
3395 		w = frame_minwidth(frp, NULL);
3396 		if (frp->fr_width + extra_cols < w)
3397 		{
3398 		    extra_cols += frp->fr_width - w;
3399 		    frame_new_width(frp, w, leftfirst, wfw);
3400 		}
3401 		else
3402 		{
3403 		    frame_new_width(frp, frp->fr_width + extra_cols,
3404 							      leftfirst, wfw);
3405 		    break;
3406 		}
3407 		if (leftfirst)
3408 		{
3409 		    do
3410 			frp = frp->fr_next;
3411 		    while (wfw && frp != NULL && frame_fixed_width(frp));
3412 		}
3413 		else
3414 		{
3415 		    do
3416 			frp = frp->fr_prev;
3417 		    while (wfw && frp != NULL && frame_fixed_width(frp));
3418 		}
3419 		// Increase "width" if we could not reduce enough frames.
3420 		if (frp == NULL)
3421 		    width -= extra_cols;
3422 	    }
3423 	}
3424 	else if (extra_cols > 0)
3425 	{
3426 	    // increase width of rightmost frame
3427 	    frame_new_width(frp, frp->fr_width + extra_cols, leftfirst, wfw);
3428 	}
3429     }
3430     topfrp->fr_width = width;
3431 }
3432 
3433 /*
3434  * Add the vertical separator to windows at the right side of "frp".
3435  * Note: Does not check if there is room!
3436  */
3437     static void
3438 frame_add_vsep(frame_T *frp)
3439 {
3440     win_T	*wp;
3441 
3442     if (frp->fr_layout == FR_LEAF)
3443     {
3444 	wp = frp->fr_win;
3445 	if (wp->w_vsep_width == 0)
3446 	{
3447 	    if (wp->w_width > 0)	// don't make it negative
3448 		--wp->w_width;
3449 	    wp->w_vsep_width = 1;
3450 	}
3451     }
3452     else if (frp->fr_layout == FR_COL)
3453     {
3454 	// Handle all the frames in the column.
3455 	FOR_ALL_FRAMES(frp, frp->fr_child)
3456 	    frame_add_vsep(frp);
3457     }
3458     else // frp->fr_layout == FR_ROW
3459     {
3460 	// Only need to handle the last frame in the row.
3461 	frp = frp->fr_child;
3462 	while (frp->fr_next != NULL)
3463 	    frp = frp->fr_next;
3464 	frame_add_vsep(frp);
3465     }
3466 }
3467 
3468 /*
3469  * Set frame width from the window it contains.
3470  */
3471     static void
3472 frame_fix_width(win_T *wp)
3473 {
3474     wp->w_frame->fr_width = wp->w_width + wp->w_vsep_width;
3475 }
3476 
3477 /*
3478  * Set frame height from the window it contains.
3479  */
3480     static void
3481 frame_fix_height(win_T *wp)
3482 {
3483     wp->w_frame->fr_height = VISIBLE_HEIGHT(wp) + wp->w_status_height;
3484 }
3485 
3486 /*
3487  * Compute the minimal height for frame "topfrp".
3488  * Uses the 'winminheight' option.
3489  * When "next_curwin" isn't NULL, use p_wh for this window.
3490  * When "next_curwin" is NOWIN, don't use at least one line for the current
3491  * window.
3492  */
3493     static int
3494 frame_minheight(frame_T *topfrp, win_T *next_curwin)
3495 {
3496     frame_T	*frp;
3497     int		m;
3498     int		n;
3499 
3500     if (topfrp->fr_win != NULL)
3501     {
3502 	if (topfrp->fr_win == next_curwin)
3503 	    m = p_wh + topfrp->fr_win->w_status_height;
3504 	else
3505 	{
3506 	    // window: minimal height of the window plus status line
3507 	    m = p_wmh + topfrp->fr_win->w_status_height;
3508 	    if (topfrp->fr_win == curwin && next_curwin == NULL)
3509 	    {
3510 		// Current window is minimal one line high and WinBar is
3511 		// visible.
3512 		if (p_wmh == 0)
3513 		    ++m;
3514 		m += WINBAR_HEIGHT(curwin);
3515 	    }
3516 	}
3517     }
3518     else if (topfrp->fr_layout == FR_ROW)
3519     {
3520 	// get the minimal height from each frame in this row
3521 	m = 0;
3522 	FOR_ALL_FRAMES(frp, topfrp->fr_child)
3523 	{
3524 	    n = frame_minheight(frp, next_curwin);
3525 	    if (n > m)
3526 		m = n;
3527 	}
3528     }
3529     else
3530     {
3531 	// Add up the minimal heights for all frames in this column.
3532 	m = 0;
3533 	FOR_ALL_FRAMES(frp, topfrp->fr_child)
3534 	    m += frame_minheight(frp, next_curwin);
3535     }
3536 
3537     return m;
3538 }
3539 
3540 /*
3541  * Compute the minimal width for frame "topfrp".
3542  * When "next_curwin" isn't NULL, use p_wiw for this window.
3543  * When "next_curwin" is NOWIN, don't use at least one column for the current
3544  * window.
3545  */
3546     static int
3547 frame_minwidth(
3548     frame_T	*topfrp,
3549     win_T	*next_curwin)	// use p_wh and p_wiw for next_curwin
3550 {
3551     frame_T	*frp;
3552     int		m, n;
3553 
3554     if (topfrp->fr_win != NULL)
3555     {
3556 	if (topfrp->fr_win == next_curwin)
3557 	    m = p_wiw + topfrp->fr_win->w_vsep_width;
3558 	else
3559 	{
3560 	    // window: minimal width of the window plus separator column
3561 	    m = p_wmw + topfrp->fr_win->w_vsep_width;
3562 	    // Current window is minimal one column wide
3563 	    if (p_wmw == 0 && topfrp->fr_win == curwin && next_curwin == NULL)
3564 		++m;
3565 	}
3566     }
3567     else if (topfrp->fr_layout == FR_COL)
3568     {
3569 	// get the minimal width from each frame in this column
3570 	m = 0;
3571 	FOR_ALL_FRAMES(frp, topfrp->fr_child)
3572 	{
3573 	    n = frame_minwidth(frp, next_curwin);
3574 	    if (n > m)
3575 		m = n;
3576 	}
3577     }
3578     else
3579     {
3580 	// Add up the minimal widths for all frames in this row.
3581 	m = 0;
3582 	FOR_ALL_FRAMES(frp, topfrp->fr_child)
3583 	    m += frame_minwidth(frp, next_curwin);
3584     }
3585 
3586     return m;
3587 }
3588 
3589 
3590 /*
3591  * Try to close all windows except current one.
3592  * Buffers in the other windows become hidden if 'hidden' is set, or '!' is
3593  * used and the buffer was modified.
3594  *
3595  * Used by ":bdel" and ":only".
3596  */
3597     void
3598 close_others(
3599     int		message,
3600     int		forceit)	    // always hide all other windows
3601 {
3602     win_T	*wp;
3603     win_T	*nextwp;
3604     int		r;
3605 
3606     if (one_window())
3607     {
3608 	if (message && !autocmd_busy)
3609 	    msg(_(m_onlyone));
3610 	return;
3611     }
3612 
3613     // Be very careful here: autocommands may change the window layout.
3614     for (wp = firstwin; win_valid(wp); wp = nextwp)
3615     {
3616 	nextwp = wp->w_next;
3617 	if (wp != curwin)		// don't close current window
3618 	{
3619 
3620 	    // Check if it's allowed to abandon this window
3621 	    r = can_abandon(wp->w_buffer, forceit);
3622 	    if (!win_valid(wp))		// autocommands messed wp up
3623 	    {
3624 		nextwp = firstwin;
3625 		continue;
3626 	    }
3627 	    if (!r)
3628 	    {
3629 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
3630 		if (message && (p_confirm
3631 			     || (cmdmod.cmod_flags & CMOD_CONFIRM)) && p_write)
3632 		{
3633 		    dialog_changed(wp->w_buffer, FALSE);
3634 		    if (!win_valid(wp))		// autocommands messed wp up
3635 		    {
3636 			nextwp = firstwin;
3637 			continue;
3638 		    }
3639 		}
3640 		if (bufIsChanged(wp->w_buffer))
3641 #endif
3642 		    continue;
3643 	    }
3644 	    win_close(wp, !buf_hide(wp->w_buffer)
3645 					       && !bufIsChanged(wp->w_buffer));
3646 	}
3647     }
3648 
3649     if (message && !ONE_WINDOW)
3650 	emsg(_("E445: Other window contains changes"));
3651 }
3652 
3653     static void
3654 win_init_empty(win_T *wp)
3655 {
3656     redraw_win_later(wp, NOT_VALID);
3657     wp->w_lines_valid = 0;
3658     wp->w_cursor.lnum = 1;
3659     wp->w_curswant = wp->w_cursor.col = 0;
3660     wp->w_cursor.coladd = 0;
3661     wp->w_pcmark.lnum = 1;	// pcmark not cleared but set to line 1
3662     wp->w_pcmark.col = 0;
3663     wp->w_prev_pcmark.lnum = 0;
3664     wp->w_prev_pcmark.col = 0;
3665     wp->w_topline = 1;
3666 #ifdef FEAT_DIFF
3667     wp->w_topfill = 0;
3668 #endif
3669     wp->w_botline = 2;
3670 #if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
3671     wp->w_s = &wp->w_buffer->b_s;
3672 #endif
3673 }
3674 
3675 /*
3676  * Init the current window "curwin".
3677  * Called when a new file is being edited.
3678  */
3679     void
3680 curwin_init(void)
3681 {
3682     win_init_empty(curwin);
3683 }
3684 
3685 /*
3686  * Allocate the first window and put an empty buffer in it.
3687  * Called from main().
3688  * Return FAIL when something goes wrong (out of memory).
3689  */
3690     int
3691 win_alloc_first(void)
3692 {
3693     if (win_alloc_firstwin(NULL) == FAIL)
3694 	return FAIL;
3695 
3696     first_tabpage = alloc_tabpage();
3697     if (first_tabpage == NULL)
3698 	return FAIL;
3699     first_tabpage->tp_topframe = topframe;
3700     curtab = first_tabpage;
3701     curtab->tp_firstwin = firstwin;
3702     curtab->tp_lastwin = lastwin;
3703     curtab->tp_curwin = curwin;
3704 
3705     return OK;
3706 }
3707 
3708 /*
3709  * Allocate and init a window that is not a regular window.
3710  * This can only be done after the first window is fully initialized, thus it
3711  * can't be in win_alloc_first().
3712  */
3713     win_T *
3714 win_alloc_popup_win(void)
3715 {
3716     win_T *wp;
3717 
3718     wp = win_alloc(NULL, TRUE);
3719     if (wp != NULL)
3720     {
3721 	// We need to initialize options with something, using the current
3722 	// window makes most sense.
3723 	win_init_some(wp, curwin);
3724 
3725 	RESET_BINDING(wp);
3726 	new_frame(wp);
3727     }
3728     return wp;
3729 }
3730 
3731 /*
3732  * Initialize window "wp" to display buffer "buf".
3733  */
3734     void
3735 win_init_popup_win(win_T *wp, buf_T *buf)
3736 {
3737     wp->w_buffer = buf;
3738     ++buf->b_nwindows;
3739     win_init_empty(wp); // set cursor and topline to safe values
3740 
3741     // Make sure w_localdir and globaldir are NULL to avoid a chdir() in
3742     // win_enter_ext().
3743     VIM_CLEAR(wp->w_localdir);
3744 }
3745 
3746 /*
3747  * Allocate the first window or the first window in a new tab page.
3748  * When "oldwin" is NULL create an empty buffer for it.
3749  * When "oldwin" is not NULL copy info from it to the new window.
3750  * Return FAIL when something goes wrong (out of memory).
3751  */
3752     static int
3753 win_alloc_firstwin(win_T *oldwin)
3754 {
3755     curwin = win_alloc(NULL, FALSE);
3756     if (oldwin == NULL)
3757     {
3758 	// Very first window, need to create an empty buffer for it and
3759 	// initialize from scratch.
3760 	curbuf = buflist_new(NULL, NULL, 1L, BLN_LISTED);
3761 	if (curwin == NULL || curbuf == NULL)
3762 	    return FAIL;
3763 	curwin->w_buffer = curbuf;
3764 #ifdef FEAT_SYN_HL
3765 	curwin->w_s = &(curbuf->b_s);
3766 #endif
3767 	curbuf->b_nwindows = 1;	// there is one window
3768 	curwin->w_alist = &global_alist;
3769 	curwin_init();		// init current window
3770     }
3771     else
3772     {
3773 	// First window in new tab page, initialize it from "oldwin".
3774 	win_init(curwin, oldwin, 0);
3775 
3776 	// We don't want cursor- and scroll-binding in the first window.
3777 	RESET_BINDING(curwin);
3778     }
3779 
3780     new_frame(curwin);
3781     if (curwin->w_frame == NULL)
3782 	return FAIL;
3783     topframe = curwin->w_frame;
3784     topframe->fr_width = Columns;
3785     topframe->fr_height = Rows - p_ch;
3786 
3787     return OK;
3788 }
3789 
3790 /*
3791  * Create a frame for window "wp".
3792  */
3793     static void
3794 new_frame(win_T *wp)
3795 {
3796     frame_T *frp = ALLOC_CLEAR_ONE(frame_T);
3797 
3798     wp->w_frame = frp;
3799     if (frp != NULL)
3800     {
3801 	frp->fr_layout = FR_LEAF;
3802 	frp->fr_win = wp;
3803     }
3804 }
3805 
3806 /*
3807  * Initialize the window and frame size to the maximum.
3808  */
3809     void
3810 win_init_size(void)
3811 {
3812     firstwin->w_height = ROWS_AVAIL;
3813     topframe->fr_height = ROWS_AVAIL;
3814     firstwin->w_width = Columns;
3815     topframe->fr_width = Columns;
3816 }
3817 
3818 /*
3819  * Allocate a new tabpage_T and init the values.
3820  * Returns NULL when out of memory.
3821  */
3822     static tabpage_T *
3823 alloc_tabpage(void)
3824 {
3825     tabpage_T	*tp;
3826 # ifdef FEAT_GUI
3827     int		i;
3828 # endif
3829 
3830 
3831     tp = ALLOC_CLEAR_ONE(tabpage_T);
3832     if (tp == NULL)
3833 	return NULL;
3834 
3835 # ifdef FEAT_EVAL
3836     // init t: variables
3837     tp->tp_vars = dict_alloc();
3838     if (tp->tp_vars == NULL)
3839     {
3840 	vim_free(tp);
3841 	return NULL;
3842     }
3843     init_var_dict(tp->tp_vars, &tp->tp_winvar, VAR_SCOPE);
3844 # endif
3845 
3846 # ifdef FEAT_GUI
3847     for (i = 0; i < 3; i++)
3848 	tp->tp_prev_which_scrollbars[i] = -1;
3849 # endif
3850 # ifdef FEAT_DIFF
3851     tp->tp_diff_invalid = TRUE;
3852 # endif
3853     tp->tp_ch_used = p_ch;
3854 
3855     return tp;
3856 }
3857 
3858     void
3859 free_tabpage(tabpage_T *tp)
3860 {
3861     int idx;
3862 
3863 # ifdef FEAT_DIFF
3864     diff_clear(tp);
3865 # endif
3866 # ifdef FEAT_PROP_POPUP
3867     while (tp->tp_first_popupwin != NULL)
3868 	popup_close_tabpage(tp, tp->tp_first_popupwin->w_id, TRUE);
3869 #endif
3870     for (idx = 0; idx < SNAP_COUNT; ++idx)
3871 	clear_snapshot(tp, idx);
3872 #ifdef FEAT_EVAL
3873     vars_clear(&tp->tp_vars->dv_hashtab);	// free all t: variables
3874     hash_init(&tp->tp_vars->dv_hashtab);
3875     unref_var_dict(tp->tp_vars);
3876 #endif
3877 
3878     if (tp == lastused_tabpage)
3879 	lastused_tabpage = NULL;
3880 
3881     vim_free(tp->tp_localdir);
3882     vim_free(tp->tp_prevdir);
3883 
3884 #ifdef FEAT_PYTHON
3885     python_tabpage_free(tp);
3886 #endif
3887 
3888 #ifdef FEAT_PYTHON3
3889     python3_tabpage_free(tp);
3890 #endif
3891 
3892     vim_free(tp);
3893 }
3894 
3895 /*
3896  * Create a new Tab page with one window.
3897  * It will edit the current buffer, like after ":split".
3898  * When "after" is 0 put it just after the current Tab page.
3899  * Otherwise put it just before tab page "after".
3900  * Return FAIL or OK.
3901  */
3902     int
3903 win_new_tabpage(int after)
3904 {
3905     tabpage_T	*tp = curtab;
3906     tabpage_T	*prev_tp = curtab;
3907     tabpage_T	*newtp;
3908     int		n;
3909 
3910     newtp = alloc_tabpage();
3911     if (newtp == NULL)
3912 	return FAIL;
3913 
3914     // Remember the current windows in this Tab page.
3915     if (leave_tabpage(curbuf, TRUE) == FAIL)
3916     {
3917 	vim_free(newtp);
3918 	return FAIL;
3919     }
3920     curtab = newtp;
3921 
3922     newtp->tp_localdir = (tp->tp_localdir == NULL)
3923 				    ? NULL : vim_strsave(tp->tp_localdir);
3924     // Create a new empty window.
3925     if (win_alloc_firstwin(tp->tp_curwin) == OK)
3926     {
3927 	// Make the new Tab page the new topframe.
3928 	if (after == 1)
3929 	{
3930 	    // New tab page becomes the first one.
3931 	    newtp->tp_next = first_tabpage;
3932 	    first_tabpage = newtp;
3933 	}
3934 	else
3935 	{
3936 	    if (after > 0)
3937 	    {
3938 		// Put new tab page before tab page "after".
3939 		n = 2;
3940 		for (tp = first_tabpage; tp->tp_next != NULL
3941 					       && n < after; tp = tp->tp_next)
3942 		    ++n;
3943 	    }
3944 	    newtp->tp_next = tp->tp_next;
3945 	    tp->tp_next = newtp;
3946 	}
3947 	newtp->tp_firstwin = newtp->tp_lastwin = newtp->tp_curwin = curwin;
3948 
3949 	win_init_size();
3950 	firstwin->w_winrow = tabline_height();
3951 	win_comp_scroll(curwin);
3952 
3953 	newtp->tp_topframe = topframe;
3954 	last_status(FALSE);
3955 
3956 	lastused_tabpage = prev_tp;
3957 
3958 #if defined(FEAT_GUI)
3959 	// When 'guioptions' includes 'L' or 'R' may have to remove or add
3960 	// scrollbars.  Have to update them anyway.
3961 	gui_may_update_scrollbars();
3962 #endif
3963 #ifdef FEAT_JOB_CHANNEL
3964 	entering_window(curwin);
3965 #endif
3966 
3967 	redraw_all_later(NOT_VALID);
3968 	apply_autocmds(EVENT_WINNEW, NULL, NULL, FALSE, curbuf);
3969 	apply_autocmds(EVENT_WINENTER, NULL, NULL, FALSE, curbuf);
3970 	apply_autocmds(EVENT_TABNEW, NULL, NULL, FALSE, curbuf);
3971 	apply_autocmds(EVENT_TABENTER, NULL, NULL, FALSE, curbuf);
3972 	return OK;
3973     }
3974 
3975     // Failed, get back the previous Tab page
3976     enter_tabpage(curtab, curbuf, TRUE, TRUE);
3977     return FAIL;
3978 }
3979 
3980 /*
3981  * Open a new tab page if ":tab cmd" was used.  It will edit the same buffer,
3982  * like with ":split".
3983  * Returns OK if a new tab page was created, FAIL otherwise.
3984  */
3985     static int
3986 may_open_tabpage(void)
3987 {
3988     int		n = (cmdmod.cmod_tab == 0)
3989 				       ? postponed_split_tab : cmdmod.cmod_tab;
3990 
3991     if (n != 0)
3992     {
3993 	cmdmod.cmod_tab = 0;	    // reset it to avoid doing it twice
3994 	postponed_split_tab = 0;
3995 	return win_new_tabpage(n);
3996     }
3997     return FAIL;
3998 }
3999 
4000 /*
4001  * Create up to "maxcount" tabpages with empty windows.
4002  * Returns the number of resulting tab pages.
4003  */
4004     int
4005 make_tabpages(int maxcount)
4006 {
4007     int		count = maxcount;
4008     int		todo;
4009 
4010     // Limit to 'tabpagemax' tabs.
4011     if (count > p_tpm)
4012 	count = p_tpm;
4013 
4014     /*
4015      * Don't execute autocommands while creating the tab pages.  Must do that
4016      * when putting the buffers in the windows.
4017      */
4018     block_autocmds();
4019 
4020     for (todo = count - 1; todo > 0; --todo)
4021 	if (win_new_tabpage(0) == FAIL)
4022 	    break;
4023 
4024     unblock_autocmds();
4025 
4026     // return actual number of tab pages
4027     return (count - todo);
4028 }
4029 
4030 /*
4031  * Return TRUE when "tpc" points to a valid tab page.
4032  */
4033     int
4034 valid_tabpage(tabpage_T *tpc)
4035 {
4036     tabpage_T	*tp;
4037 
4038     FOR_ALL_TABPAGES(tp)
4039 	if (tp == tpc)
4040 	    return TRUE;
4041     return FALSE;
4042 }
4043 
4044 /*
4045  * Return TRUE when "tpc" points to a valid tab page and at least one window is
4046  * valid.
4047  */
4048     int
4049 valid_tabpage_win(tabpage_T *tpc)
4050 {
4051     tabpage_T	*tp;
4052     win_T	*wp;
4053 
4054     FOR_ALL_TABPAGES(tp)
4055     {
4056 	if (tp == tpc)
4057 	{
4058 	    FOR_ALL_WINDOWS_IN_TAB(tp, wp)
4059 	    {
4060 		if (win_valid_any_tab(wp))
4061 		    return TRUE;
4062 	    }
4063 	    return FALSE;
4064 	}
4065     }
4066     // shouldn't happen
4067     return FALSE;
4068 }
4069 
4070 /*
4071  * Close tabpage "tab", assuming it has no windows in it.
4072  * There must be another tabpage or this will crash.
4073  */
4074     void
4075 close_tabpage(tabpage_T *tab)
4076 {
4077     tabpage_T	*ptp;
4078 
4079     if (tab == first_tabpage)
4080     {
4081 	first_tabpage = tab->tp_next;
4082 	ptp = first_tabpage;
4083     }
4084     else
4085     {
4086 	for (ptp = first_tabpage; ptp != NULL && ptp->tp_next != tab;
4087 							    ptp = ptp->tp_next)
4088 	    ;
4089 	assert(ptp != NULL);
4090 	ptp->tp_next = tab->tp_next;
4091     }
4092 
4093     goto_tabpage_tp(ptp, FALSE, FALSE);
4094     free_tabpage(tab);
4095 }
4096 
4097 /*
4098  * Find tab page "n" (first one is 1).  Returns NULL when not found.
4099  */
4100     tabpage_T *
4101 find_tabpage(int n)
4102 {
4103     tabpage_T	*tp;
4104     int		i = 1;
4105 
4106     if (n == 0)
4107 	return curtab;
4108 
4109     for (tp = first_tabpage; tp != NULL && i != n; tp = tp->tp_next)
4110 	++i;
4111     return tp;
4112 }
4113 
4114 /*
4115  * Get index of tab page "tp".  First one has index 1.
4116  * When not found returns number of tab pages plus one.
4117  */
4118     int
4119 tabpage_index(tabpage_T *ftp)
4120 {
4121     int		i = 1;
4122     tabpage_T	*tp;
4123 
4124     for (tp = first_tabpage; tp != NULL && tp != ftp; tp = tp->tp_next)
4125 	++i;
4126     return i;
4127 }
4128 
4129 /*
4130  * Prepare for leaving the current tab page.
4131  * When autocommands change "curtab" we don't leave the tab page and return
4132  * FAIL.
4133  * Careful: When OK is returned need to get a new tab page very very soon!
4134  */
4135     static int
4136 leave_tabpage(
4137     buf_T	*new_curbuf UNUSED,    // what is going to be the new curbuf,
4138 				       // NULL if unknown
4139     int		trigger_leave_autocmds UNUSED)
4140 {
4141     tabpage_T	*tp = curtab;
4142 
4143 #ifdef FEAT_JOB_CHANNEL
4144     leaving_window(curwin);
4145 #endif
4146     reset_VIsual_and_resel();	// stop Visual mode
4147     if (trigger_leave_autocmds)
4148     {
4149 	if (new_curbuf != curbuf)
4150 	{
4151 	    apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf);
4152 	    if (curtab != tp)
4153 		return FAIL;
4154 	}
4155 	apply_autocmds(EVENT_WINLEAVE, NULL, NULL, FALSE, curbuf);
4156 	if (curtab != tp)
4157 	    return FAIL;
4158 	apply_autocmds(EVENT_TABLEAVE, NULL, NULL, FALSE, curbuf);
4159 	if (curtab != tp)
4160 	    return FAIL;
4161     }
4162 #if defined(FEAT_GUI)
4163     // Remove the scrollbars.  They may be added back later.
4164     if (gui.in_use)
4165 	gui_remove_scrollbars();
4166 #endif
4167     tp->tp_curwin = curwin;
4168     tp->tp_prevwin = prevwin;
4169     tp->tp_firstwin = firstwin;
4170     tp->tp_lastwin = lastwin;
4171     tp->tp_old_Rows = Rows;
4172     tp->tp_old_Columns = Columns;
4173     firstwin = NULL;
4174     lastwin = NULL;
4175     return OK;
4176 }
4177 
4178 /*
4179  * Start using tab page "tp".
4180  * Only to be used after leave_tabpage() or freeing the current tab page.
4181  * Only trigger *Enter autocommands when trigger_enter_autocmds is TRUE.
4182  * Only trigger *Leave autocommands when trigger_leave_autocmds is TRUE.
4183  */
4184     static void
4185 enter_tabpage(
4186     tabpage_T	*tp,
4187     buf_T	*old_curbuf UNUSED,
4188     int		trigger_enter_autocmds,
4189     int		trigger_leave_autocmds)
4190 {
4191     int		row;
4192     int		old_off = tp->tp_firstwin->w_winrow;
4193     win_T	*next_prevwin = tp->tp_prevwin;
4194     tabpage_T	*last_tab = curtab;
4195 
4196     curtab = tp;
4197     firstwin = tp->tp_firstwin;
4198     lastwin = tp->tp_lastwin;
4199     topframe = tp->tp_topframe;
4200 
4201     // We would like doing the TabEnter event first, but we don't have a
4202     // valid current window yet, which may break some commands.
4203     // This triggers autocommands, thus may make "tp" invalid.
4204     (void)win_enter_ext(tp->tp_curwin, WEE_CURWIN_INVALID
4205 		  | (trigger_enter_autocmds ? WEE_TRIGGER_ENTER_AUTOCMDS : 0)
4206 		  | (trigger_leave_autocmds ? WEE_TRIGGER_LEAVE_AUTOCMDS : 0));
4207     prevwin = next_prevwin;
4208 
4209     last_status(FALSE);		// status line may appear or disappear
4210     row = win_comp_pos();	// recompute w_winrow for all windows
4211 #ifdef FEAT_DIFF
4212     diff_need_scrollbind = TRUE;
4213 #endif
4214 
4215     // The tabpage line may have appeared or disappeared, may need to resize
4216     // the frames for that.  When the Vim window was resized need to update
4217     // frame sizes too.  Use the stored value of p_ch, so that it can be
4218     // different for each tab page.
4219     if (p_ch != curtab->tp_ch_used)
4220 	clear_cmdline = TRUE;
4221     p_ch = curtab->tp_ch_used;
4222 
4223     // When cmdheight is changed in a tab page with '<C-w>-', cmdline_row is
4224     // changed but p_ch and tp_ch_used are not changed. Thus we also need to
4225     // check cmdline_row.
4226     if ((row < cmdline_row) && (cmdline_row <= Rows - p_ch))
4227 	clear_cmdline = TRUE;
4228 
4229     if (curtab->tp_old_Rows != Rows || (old_off != firstwin->w_winrow
4230 #ifdef FEAT_GUI_TABLINE
4231 			    && !gui_use_tabline()
4232 #endif
4233 		))
4234 	shell_new_rows();
4235     if (curtab->tp_old_Columns != Columns && starting == 0)
4236 	shell_new_columns();	// update window widths
4237 
4238     lastused_tabpage = last_tab;
4239 
4240 #if defined(FEAT_GUI)
4241     // When 'guioptions' includes 'L' or 'R' may have to remove or add
4242     // scrollbars.  Have to update them anyway.
4243     gui_may_update_scrollbars();
4244 #endif
4245 
4246     // Apply autocommands after updating the display, when 'rows' and
4247     // 'columns' have been set correctly.
4248     if (trigger_enter_autocmds)
4249     {
4250 	apply_autocmds(EVENT_TABENTER, NULL, NULL, FALSE, curbuf);
4251 	if (old_curbuf != curbuf)
4252 	    apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
4253     }
4254 
4255     redraw_all_later(NOT_VALID);
4256 }
4257 
4258 /*
4259  * Go to tab page "n".  For ":tab N" and "Ngt".
4260  * When "n" is 9999 go to the last tab page.
4261  */
4262     void
4263 goto_tabpage(int n)
4264 {
4265     tabpage_T	*tp = NULL;  // shut up compiler
4266     tabpage_T	*ttp;
4267     int		i;
4268 
4269     if (text_locked())
4270     {
4271 	// Not allowed when editing the command line.
4272 	text_locked_msg();
4273 	return;
4274     }
4275 
4276     // If there is only one it can't work.
4277     if (first_tabpage->tp_next == NULL)
4278     {
4279 	if (n > 1)
4280 	    beep_flush();
4281 	return;
4282     }
4283 
4284     if (n == 0)
4285     {
4286 	// No count, go to next tab page, wrap around end.
4287 	if (curtab->tp_next == NULL)
4288 	    tp = first_tabpage;
4289 	else
4290 	    tp = curtab->tp_next;
4291     }
4292     else if (n < 0)
4293     {
4294 	// "gT": go to previous tab page, wrap around end.  "N gT" repeats
4295 	// this N times.
4296 	ttp = curtab;
4297 	for (i = n; i < 0; ++i)
4298 	{
4299 	    for (tp = first_tabpage; tp->tp_next != ttp && tp->tp_next != NULL;
4300 		    tp = tp->tp_next)
4301 		;
4302 	    ttp = tp;
4303 	}
4304     }
4305     else if (n == 9999)
4306     {
4307 	// Go to last tab page.
4308 	for (tp = first_tabpage; tp->tp_next != NULL; tp = tp->tp_next)
4309 	    ;
4310     }
4311     else
4312     {
4313 	// Go to tab page "n".
4314 	tp = find_tabpage(n);
4315 	if (tp == NULL)
4316 	{
4317 	    beep_flush();
4318 	    return;
4319 	}
4320     }
4321 
4322     goto_tabpage_tp(tp, TRUE, TRUE);
4323 
4324 #ifdef FEAT_GUI_TABLINE
4325     if (gui_use_tabline())
4326 	gui_mch_set_curtab(tabpage_index(curtab));
4327 #endif
4328 }
4329 
4330 /*
4331  * Go to tabpage "tp".
4332  * Only trigger *Enter autocommands when trigger_enter_autocmds is TRUE.
4333  * Only trigger *Leave autocommands when trigger_leave_autocmds is TRUE.
4334  * Note: doesn't update the GUI tab.
4335  */
4336     void
4337 goto_tabpage_tp(
4338     tabpage_T	*tp,
4339     int		trigger_enter_autocmds,
4340     int		trigger_leave_autocmds)
4341 {
4342     // Don't repeat a message in another tab page.
4343     set_keep_msg(NULL, 0);
4344 
4345     if (tp != curtab && leave_tabpage(tp->tp_curwin->w_buffer,
4346 					trigger_leave_autocmds) == OK)
4347     {
4348 	if (valid_tabpage(tp))
4349 	    enter_tabpage(tp, curbuf, trigger_enter_autocmds,
4350 		    trigger_leave_autocmds);
4351 	else
4352 	    enter_tabpage(curtab, curbuf, trigger_enter_autocmds,
4353 		    trigger_leave_autocmds);
4354     }
4355 }
4356 
4357 /*
4358  * Go to the last accessed tab page, if there is one.
4359  * Return OK or FAIL
4360  */
4361     int
4362 goto_tabpage_lastused(void)
4363 {
4364     if (valid_tabpage(lastused_tabpage))
4365     {
4366 	goto_tabpage_tp(lastused_tabpage, TRUE, TRUE);
4367 	return OK;
4368     }
4369     return FAIL;
4370 }
4371 
4372 /*
4373  * Enter window "wp" in tab page "tp".
4374  * Also updates the GUI tab.
4375  */
4376     void
4377 goto_tabpage_win(tabpage_T *tp, win_T *wp)
4378 {
4379     goto_tabpage_tp(tp, TRUE, TRUE);
4380     if (curtab == tp && win_valid(wp))
4381     {
4382 	win_enter(wp, TRUE);
4383 # ifdef FEAT_GUI_TABLINE
4384 	if (gui_use_tabline())
4385 	    gui_mch_set_curtab(tabpage_index(curtab));
4386 # endif
4387     }
4388 }
4389 
4390 /*
4391  * Move the current tab page to after tab page "nr".
4392  */
4393     void
4394 tabpage_move(int nr)
4395 {
4396     int		n = 1;
4397     tabpage_T	*tp, *tp_dst;
4398 
4399     if (first_tabpage->tp_next == NULL)
4400 	return;
4401 
4402     for (tp = first_tabpage; tp->tp_next != NULL && n < nr; tp = tp->tp_next)
4403 	++n;
4404 
4405     if (tp == curtab || (nr > 0 && tp->tp_next != NULL
4406 						    && tp->tp_next == curtab))
4407 	return;
4408 
4409     tp_dst = tp;
4410 
4411     // Remove the current tab page from the list of tab pages.
4412     if (curtab == first_tabpage)
4413 	first_tabpage = curtab->tp_next;
4414     else
4415     {
4416 	FOR_ALL_TABPAGES(tp)
4417 	    if (tp->tp_next == curtab)
4418 		break;
4419 	if (tp == NULL)	// "cannot happen"
4420 	    return;
4421 	tp->tp_next = curtab->tp_next;
4422     }
4423 
4424     // Re-insert it at the specified position.
4425     if (nr <= 0)
4426     {
4427 	curtab->tp_next = first_tabpage;
4428 	first_tabpage = curtab;
4429     }
4430     else
4431     {
4432 	curtab->tp_next = tp_dst->tp_next;
4433 	tp_dst->tp_next = curtab;
4434     }
4435 
4436     // Need to redraw the tabline.  Tab page contents doesn't change.
4437     redraw_tabline = TRUE;
4438 }
4439 
4440 
4441 /*
4442  * Go to another window.
4443  * When jumping to another buffer, stop Visual mode.  Do this before
4444  * changing windows so we can yank the selection into the '*' register.
4445  * When jumping to another window on the same buffer, adjust its cursor
4446  * position to keep the same Visual area.
4447  */
4448     void
4449 win_goto(win_T *wp)
4450 {
4451 #ifdef FEAT_CONCEAL
4452     win_T	*owp = curwin;
4453 #endif
4454 
4455 #ifdef FEAT_PROP_POPUP
4456     if (ERROR_IF_ANY_POPUP_WINDOW)
4457 	return;
4458     if (popup_is_popup(wp))
4459     {
4460 	emsg(_("E366: Not allowed to enter a popup window"));
4461 	return;
4462     }
4463 #endif
4464     if (text_and_win_locked())
4465     {
4466 	beep_flush();
4467 	text_locked_msg();
4468 	return;
4469     }
4470     if (curbuf_locked())
4471 	return;
4472 
4473     if (wp->w_buffer != curbuf)
4474 	reset_VIsual_and_resel();
4475     else if (VIsual_active)
4476 	wp->w_cursor = curwin->w_cursor;
4477 
4478 #ifdef FEAT_GUI
4479     need_mouse_correct = TRUE;
4480 #endif
4481     win_enter(wp, TRUE);
4482 
4483 #ifdef FEAT_CONCEAL
4484     // Conceal cursor line in previous window, unconceal in current window.
4485     if (win_valid(owp) && owp->w_p_cole > 0 && !msg_scrolled)
4486 	redrawWinline(owp, owp->w_cursor.lnum);
4487     if (curwin->w_p_cole > 0 && !msg_scrolled)
4488 	need_cursor_line_redraw = TRUE;
4489 #endif
4490 }
4491 
4492 #if defined(FEAT_PERL) || defined(FEAT_LUA) || defined(PROTO)
4493 /*
4494  * Find window number "winnr" (counting top to bottom).
4495  */
4496     win_T *
4497 win_find_nr(int winnr)
4498 {
4499     win_T	*wp;
4500 
4501     FOR_ALL_WINDOWS(wp)
4502 	if (--winnr == 0)
4503 	    break;
4504     return wp;
4505 }
4506 #endif
4507 
4508 #if ((defined(FEAT_PYTHON) || defined(FEAT_PYTHON3))) || defined(PROTO)
4509 /*
4510  * Find the tabpage for window "win".
4511  */
4512     tabpage_T *
4513 win_find_tabpage(win_T *win)
4514 {
4515     win_T	*wp;
4516     tabpage_T	*tp;
4517 
4518     FOR_ALL_TAB_WINDOWS(tp, wp)
4519 	    if (wp == win)
4520 		return tp;
4521     return NULL;
4522 }
4523 #endif
4524 
4525 /*
4526  * Get the above or below neighbor window of the specified window.
4527  *   up - TRUE for the above neighbor
4528  *   count - nth neighbor window
4529  * Returns the specified window if the neighbor is not found.
4530  */
4531     win_T *
4532 win_vert_neighbor(tabpage_T *tp, win_T *wp, int up, long count)
4533 {
4534     frame_T	*fr;
4535     frame_T	*nfr;
4536     frame_T	*foundfr;
4537 
4538 #ifdef FEAT_PROP_POPUP
4539     if (popup_is_popup(wp))
4540 	// popups don't have neighbors.
4541 	return NULL;
4542 #endif
4543     foundfr = wp->w_frame;
4544     while (count--)
4545     {
4546 	/*
4547 	 * First go upwards in the tree of frames until we find a upwards or
4548 	 * downwards neighbor.
4549 	 */
4550 	fr = foundfr;
4551 	for (;;)
4552 	{
4553 	    if (fr == tp->tp_topframe)
4554 		goto end;
4555 	    if (up)
4556 		nfr = fr->fr_prev;
4557 	    else
4558 		nfr = fr->fr_next;
4559 	    if (fr->fr_parent->fr_layout == FR_COL && nfr != NULL)
4560 		break;
4561 	    fr = fr->fr_parent;
4562 	}
4563 
4564 	/*
4565 	 * Now go downwards to find the bottom or top frame in it.
4566 	 */
4567 	for (;;)
4568 	{
4569 	    if (nfr->fr_layout == FR_LEAF)
4570 	    {
4571 		foundfr = nfr;
4572 		break;
4573 	    }
4574 	    fr = nfr->fr_child;
4575 	    if (nfr->fr_layout == FR_ROW)
4576 	    {
4577 		// Find the frame at the cursor row.
4578 		while (fr->fr_next != NULL
4579 			&& frame2win(fr)->w_wincol + fr->fr_width
4580 					 <= wp->w_wincol + wp->w_wcol)
4581 		    fr = fr->fr_next;
4582 	    }
4583 	    if (nfr->fr_layout == FR_COL && up)
4584 		while (fr->fr_next != NULL)
4585 		    fr = fr->fr_next;
4586 	    nfr = fr;
4587 	}
4588     }
4589 end:
4590     return foundfr != NULL ? foundfr->fr_win : NULL;
4591 }
4592 
4593 /*
4594  * Move to window above or below "count" times.
4595  */
4596     static void
4597 win_goto_ver(
4598     int		up,		// TRUE to go to win above
4599     long	count)
4600 {
4601     win_T	*win;
4602 
4603 #ifdef FEAT_PROP_POPUP
4604     if (ERROR_IF_TERM_POPUP_WINDOW)
4605 	return;
4606 #endif
4607     win = win_vert_neighbor(curtab, curwin, up, count);
4608     if (win != NULL)
4609 	win_goto(win);
4610 }
4611 
4612 /*
4613  * Get the left or right neighbor window of the specified window.
4614  *   left - TRUE for the left neighbor
4615  *   count - nth neighbor window
4616  * Returns the specified window if the neighbor is not found.
4617  */
4618     win_T *
4619 win_horz_neighbor(tabpage_T *tp, win_T *wp, int left, long count)
4620 {
4621     frame_T	*fr;
4622     frame_T	*nfr;
4623     frame_T	*foundfr;
4624 
4625 #ifdef FEAT_PROP_POPUP
4626     if (popup_is_popup(wp))
4627 	// popups don't have neighbors.
4628 	return NULL;
4629 #endif
4630     foundfr = wp->w_frame;
4631     while (count--)
4632     {
4633 	/*
4634 	 * First go upwards in the tree of frames until we find a left or
4635 	 * right neighbor.
4636 	 */
4637 	fr = foundfr;
4638 	for (;;)
4639 	{
4640 	    if (fr == tp->tp_topframe)
4641 		goto end;
4642 	    if (left)
4643 		nfr = fr->fr_prev;
4644 	    else
4645 		nfr = fr->fr_next;
4646 	    if (fr->fr_parent->fr_layout == FR_ROW && nfr != NULL)
4647 		break;
4648 	    fr = fr->fr_parent;
4649 	}
4650 
4651 	/*
4652 	 * Now go downwards to find the leftmost or rightmost frame in it.
4653 	 */
4654 	for (;;)
4655 	{
4656 	    if (nfr->fr_layout == FR_LEAF)
4657 	    {
4658 		foundfr = nfr;
4659 		break;
4660 	    }
4661 	    fr = nfr->fr_child;
4662 	    if (nfr->fr_layout == FR_COL)
4663 	    {
4664 		// Find the frame at the cursor row.
4665 		while (fr->fr_next != NULL
4666 			&& frame2win(fr)->w_winrow + fr->fr_height
4667 					 <= wp->w_winrow + wp->w_wrow)
4668 		    fr = fr->fr_next;
4669 	    }
4670 	    if (nfr->fr_layout == FR_ROW && left)
4671 		while (fr->fr_next != NULL)
4672 		    fr = fr->fr_next;
4673 	    nfr = fr;
4674 	}
4675     }
4676 end:
4677     return foundfr != NULL ? foundfr->fr_win : NULL;
4678 }
4679 
4680 /*
4681  * Move to left or right window.
4682  */
4683     static void
4684 win_goto_hor(
4685     int		left,		// TRUE to go to left win
4686     long	count)
4687 {
4688     win_T	*win;
4689 
4690 #ifdef FEAT_PROP_POPUP
4691     if (ERROR_IF_TERM_POPUP_WINDOW)
4692 	return;
4693 #endif
4694     win = win_horz_neighbor(curtab, curwin, left, count);
4695     if (win != NULL)
4696 	win_goto(win);
4697 }
4698 
4699 /*
4700  * Make window "wp" the current window.
4701  */
4702     void
4703 win_enter(win_T *wp, int undo_sync)
4704 {
4705     (void)win_enter_ext(wp, (undo_sync ? WEE_UNDO_SYNC : 0)
4706 		    | WEE_TRIGGER_ENTER_AUTOCMDS | WEE_TRIGGER_LEAVE_AUTOCMDS);
4707 }
4708 
4709 /*
4710  * Make window "wp" the current window.
4711  * Can be called with "flags" containing WEE_CURWIN_INVALID, which means that
4712  * curwin has just been closed and isn't valid.
4713  * Returns TRUE when dont_parse_messages was decremented.
4714  */
4715     static int
4716 win_enter_ext(win_T *wp, int flags)
4717 {
4718     int		other_buffer = FALSE;
4719     int		curwin_invalid = (flags & WEE_CURWIN_INVALID);
4720     int		did_decrement = FALSE;
4721 
4722     if (wp == curwin && !curwin_invalid)	// nothing to do
4723 	return FALSE;
4724 
4725 #ifdef FEAT_JOB_CHANNEL
4726     if (!curwin_invalid)
4727 	leaving_window(curwin);
4728 #endif
4729 
4730     if (!curwin_invalid && (flags & WEE_TRIGGER_LEAVE_AUTOCMDS))
4731     {
4732 	/*
4733 	 * Be careful: If autocommands delete the window, return now.
4734 	 */
4735 	if (wp->w_buffer != curbuf)
4736 	{
4737 	    apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf);
4738 	    other_buffer = TRUE;
4739 	    if (!win_valid(wp))
4740 		return FALSE;
4741 	}
4742 	apply_autocmds(EVENT_WINLEAVE, NULL, NULL, FALSE, curbuf);
4743 	if (!win_valid(wp))
4744 	    return FALSE;
4745 #ifdef FEAT_EVAL
4746 	// autocmds may abort script processing
4747 	if (aborting())
4748 	    return FALSE;
4749 #endif
4750     }
4751 
4752     // sync undo before leaving the current buffer
4753     if ((flags & WEE_UNDO_SYNC) && curbuf != wp->w_buffer)
4754 	u_sync(FALSE);
4755 
4756     // Might need to scroll the old window before switching, e.g., when the
4757     // cursor was moved.
4758     update_topline();
4759 
4760     // may have to copy the buffer options when 'cpo' contains 'S'
4761     if (wp->w_buffer != curbuf)
4762 	buf_copy_options(wp->w_buffer, BCO_ENTER | BCO_NOHELP);
4763     if (!curwin_invalid)
4764     {
4765 	prevwin = curwin;	// remember for CTRL-W p
4766 	curwin->w_redr_status = TRUE;
4767     }
4768     curwin = wp;
4769     curbuf = wp->w_buffer;
4770     check_cursor();
4771     if (!virtual_active())
4772 	curwin->w_cursor.coladd = 0;
4773     changed_line_abv_curs();	// assume cursor position needs updating
4774 
4775     // Now it is OK to parse messages again, which may be needed in
4776     // autocommands.
4777 #ifdef MESSAGE_QUEUE
4778     if (flags & WEE_ALLOW_PARSE_MESSAGES)
4779     {
4780 	--dont_parse_messages;
4781 	did_decrement = TRUE;
4782     }
4783 #endif
4784 
4785     if (curwin->w_localdir != NULL || curtab->tp_localdir != NULL)
4786     {
4787 	char_u	*dirname;
4788 
4789 	// Window or tab has a local directory: Save current directory as
4790 	// global directory (unless that was done already) and change to the
4791 	// local directory.
4792 	if (globaldir == NULL)
4793 	{
4794 	    char_u	cwd[MAXPATHL];
4795 
4796 	    if (mch_dirname(cwd, MAXPATHL) == OK)
4797 		globaldir = vim_strsave(cwd);
4798 	}
4799 	if (curwin->w_localdir != NULL)
4800 	    dirname = curwin->w_localdir;
4801 	else
4802 	    dirname = curtab->tp_localdir;
4803 
4804 	if (mch_chdir((char *)dirname) == 0)
4805 	    shorten_fnames(TRUE);
4806     }
4807     else if (globaldir != NULL)
4808     {
4809 	// Window doesn't have a local directory and we are not in the global
4810 	// directory: Change to the global directory.
4811 	vim_ignored = mch_chdir((char *)globaldir);
4812 	VIM_CLEAR(globaldir);
4813 	shorten_fnames(TRUE);
4814     }
4815 
4816 #ifdef FEAT_JOB_CHANNEL
4817     entering_window(curwin);
4818 #endif
4819     // Careful: autocommands may close the window and make "wp" invalid
4820     if (flags & WEE_TRIGGER_NEW_AUTOCMDS)
4821 	apply_autocmds(EVENT_WINNEW, NULL, NULL, FALSE, curbuf);
4822     if (flags & WEE_TRIGGER_ENTER_AUTOCMDS)
4823     {
4824 	apply_autocmds(EVENT_WINENTER, NULL, NULL, FALSE, curbuf);
4825 	if (other_buffer)
4826 	    apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
4827     }
4828 
4829 #ifdef FEAT_TITLE
4830     maketitle();
4831 #endif
4832     curwin->w_redr_status = TRUE;
4833 #ifdef FEAT_TERMINAL
4834     if (bt_terminal(curwin->w_buffer))
4835 	// terminal is likely in another mode
4836 	redraw_mode = TRUE;
4837 #endif
4838     redraw_tabline = TRUE;
4839     if (restart_edit)
4840 	redraw_later(VALID);	// causes status line redraw
4841 
4842     // set window height to desired minimal value
4843     if (curwin->w_height < p_wh && !curwin->w_p_wfh
4844 #ifdef FEAT_PROP_POPUP
4845 	    && !popup_is_popup(curwin)
4846 #endif
4847 	    )
4848 	win_setheight((int)p_wh);
4849     else if (curwin->w_height == 0)
4850 	win_setheight(1);
4851 
4852     // set window width to desired minimal value
4853     if (curwin->w_width < p_wiw && !curwin->w_p_wfw)
4854 	win_setwidth((int)p_wiw);
4855 
4856     setmouse();			// in case jumped to/from help buffer
4857 
4858     // Change directories when the 'acd' option is set.
4859     DO_AUTOCHDIR;
4860 
4861     return did_decrement;
4862 }
4863 
4864 
4865 /*
4866  * Jump to the first open window that contains buffer "buf", if one exists.
4867  * Returns a pointer to the window found, otherwise NULL.
4868  */
4869     win_T *
4870 buf_jump_open_win(buf_T *buf)
4871 {
4872     win_T	*wp = NULL;
4873 
4874     if (curwin->w_buffer == buf)
4875 	wp = curwin;
4876     else
4877 	FOR_ALL_WINDOWS(wp)
4878 	    if (wp->w_buffer == buf)
4879 		break;
4880     if (wp != NULL)
4881 	win_enter(wp, FALSE);
4882     return wp;
4883 }
4884 
4885 /*
4886  * Jump to the first open window in any tab page that contains buffer "buf",
4887  * if one exists.
4888  * Returns a pointer to the window found, otherwise NULL.
4889  */
4890     win_T *
4891 buf_jump_open_tab(buf_T *buf)
4892 {
4893     win_T	*wp = buf_jump_open_win(buf);
4894     tabpage_T	*tp;
4895 
4896     if (wp != NULL)
4897 	return wp;
4898 
4899     FOR_ALL_TABPAGES(tp)
4900 	if (tp != curtab)
4901 	{
4902 	    FOR_ALL_WINDOWS_IN_TAB(tp, wp)
4903 		if (wp->w_buffer == buf)
4904 		    break;
4905 	    if (wp != NULL)
4906 	    {
4907 		goto_tabpage_win(tp, wp);
4908 		if (curwin != wp)
4909 		    wp = NULL;	// something went wrong
4910 		break;
4911 	    }
4912 	}
4913     return wp;
4914 }
4915 
4916 static int last_win_id = LOWEST_WIN_ID - 1;
4917 
4918 /*
4919  * Allocate a window structure and link it in the window list when "hidden" is
4920  * FALSE.
4921  */
4922     static win_T *
4923 win_alloc(win_T *after UNUSED, int hidden UNUSED)
4924 {
4925     win_T	*new_wp;
4926 
4927     /*
4928      * allocate window structure and linesizes arrays
4929      */
4930     new_wp = ALLOC_CLEAR_ONE(win_T);
4931     if (new_wp == NULL)
4932 	return NULL;
4933 
4934     if (win_alloc_lines(new_wp) == FAIL)
4935     {
4936 	vim_free(new_wp);
4937 	return NULL;
4938     }
4939 
4940     new_wp->w_id = ++last_win_id;
4941 
4942 #ifdef FEAT_EVAL
4943     // init w: variables
4944     new_wp->w_vars = dict_alloc();
4945     if (new_wp->w_vars == NULL)
4946     {
4947 	win_free_lsize(new_wp);
4948 	vim_free(new_wp);
4949 	return NULL;
4950     }
4951     init_var_dict(new_wp->w_vars, &new_wp->w_winvar, VAR_SCOPE);
4952 #endif
4953 
4954     // Don't execute autocommands while the window is not properly
4955     // initialized yet.  gui_create_scrollbar() may trigger a FocusGained
4956     // event.
4957     block_autocmds();
4958 
4959     /*
4960      * link the window in the window list
4961      */
4962     if (!hidden)
4963 	win_append(after, new_wp);
4964     new_wp->w_wincol = 0;
4965     new_wp->w_width = Columns;
4966 
4967     // position the display and the cursor at the top of the file.
4968     new_wp->w_topline = 1;
4969 #ifdef FEAT_DIFF
4970     new_wp->w_topfill = 0;
4971 #endif
4972     new_wp->w_botline = 2;
4973     new_wp->w_cursor.lnum = 1;
4974     new_wp->w_scbind_pos = 1;
4975 
4976     // use global option value for global-local options
4977     new_wp->w_p_so = -1;
4978     new_wp->w_p_siso = -1;
4979 
4980     // We won't calculate w_fraction until resizing the window
4981     new_wp->w_fraction = 0;
4982     new_wp->w_prev_fraction_row = -1;
4983 
4984 #ifdef FEAT_GUI
4985     if (gui.in_use)
4986     {
4987 	gui_create_scrollbar(&new_wp->w_scrollbars[SBAR_LEFT],
4988 		SBAR_LEFT, new_wp);
4989 	gui_create_scrollbar(&new_wp->w_scrollbars[SBAR_RIGHT],
4990 		SBAR_RIGHT, new_wp);
4991     }
4992 #endif
4993 #ifdef FEAT_FOLDING
4994     foldInitWin(new_wp);
4995 #endif
4996     unblock_autocmds();
4997 #ifdef FEAT_SEARCH_EXTRA
4998     new_wp->w_match_head = NULL;
4999     new_wp->w_next_match_id = 4;
5000 #endif
5001     return new_wp;
5002 }
5003 
5004 /*
5005  * Remove window 'wp' from the window list and free the structure.
5006  */
5007     static void
5008 win_free(
5009     win_T	*wp,
5010     tabpage_T	*tp)		// tab page "win" is in, NULL for current
5011 {
5012     int		i;
5013     buf_T	*buf;
5014     wininfo_T	*wip;
5015 
5016 #ifdef FEAT_FOLDING
5017     clearFolding(wp);
5018 #endif
5019 
5020     // reduce the reference count to the argument list.
5021     alist_unlink(wp->w_alist);
5022 
5023     // Don't execute autocommands while the window is halfway being deleted.
5024     // gui_mch_destroy_scrollbar() may trigger a FocusGained event.
5025     block_autocmds();
5026 
5027 #ifdef FEAT_LUA
5028     lua_window_free(wp);
5029 #endif
5030 
5031 #ifdef FEAT_MZSCHEME
5032     mzscheme_window_free(wp);
5033 #endif
5034 
5035 #ifdef FEAT_PERL
5036     perl_win_free(wp);
5037 #endif
5038 
5039 #ifdef FEAT_PYTHON
5040     python_window_free(wp);
5041 #endif
5042 
5043 #ifdef FEAT_PYTHON3
5044     python3_window_free(wp);
5045 #endif
5046 
5047 #ifdef FEAT_TCL
5048     tcl_window_free(wp);
5049 #endif
5050 
5051 #ifdef FEAT_RUBY
5052     ruby_window_free(wp);
5053 #endif
5054 
5055     clear_winopt(&wp->w_onebuf_opt);
5056     clear_winopt(&wp->w_allbuf_opt);
5057 
5058 #ifdef FEAT_EVAL
5059     vars_clear(&wp->w_vars->dv_hashtab);	// free all w: variables
5060     hash_init(&wp->w_vars->dv_hashtab);
5061     unref_var_dict(wp->w_vars);
5062 #endif
5063 
5064     {
5065 	tabpage_T	*ttp;
5066 
5067 	if (prevwin == wp)
5068 	    prevwin = NULL;
5069 	FOR_ALL_TABPAGES(ttp)
5070 	    if (ttp->tp_prevwin == wp)
5071 		ttp->tp_prevwin = NULL;
5072     }
5073     win_free_lsize(wp);
5074 
5075     for (i = 0; i < wp->w_tagstacklen; ++i)
5076     {
5077 	vim_free(wp->w_tagstack[i].tagname);
5078 	vim_free(wp->w_tagstack[i].user_data);
5079     }
5080     vim_free(wp->w_localdir);
5081     vim_free(wp->w_prevdir);
5082 
5083     // Remove the window from the b_wininfo lists, it may happen that the
5084     // freed memory is re-used for another window.
5085     FOR_ALL_BUFFERS(buf)
5086 	FOR_ALL_BUF_WININFO(buf, wip)
5087 	    if (wip->wi_win == wp)
5088 	    {
5089 		wininfo_T	*wip2;
5090 
5091 		// If there already is an entry with "wi_win" set to NULL it
5092 		// must be removed, it would never be used.
5093 		// Skip "wip" itself, otherwise Coverity complains.
5094 		for (wip2 = buf->b_wininfo; wip2 != NULL; wip2 = wip2->wi_next)
5095 		    if (wip2 != wip && wip2->wi_win == NULL)
5096 		    {
5097 			if (wip2->wi_next != NULL)
5098 			    wip2->wi_next->wi_prev = wip2->wi_prev;
5099 			if (wip2->wi_prev == NULL)
5100 			    buf->b_wininfo = wip2->wi_next;
5101 			else
5102 			    wip2->wi_prev->wi_next = wip2->wi_next;
5103 			free_wininfo(wip2);
5104 			break;
5105 		    }
5106 
5107 		wip->wi_win = NULL;
5108 	    }
5109 
5110 #ifdef FEAT_SEARCH_EXTRA
5111     clear_matches(wp);
5112 #endif
5113 
5114 #ifdef FEAT_JUMPLIST
5115     free_jumplist(wp);
5116 #endif
5117 
5118 #ifdef FEAT_QUICKFIX
5119     qf_free_all(wp);
5120 #endif
5121 
5122 #ifdef FEAT_GUI
5123     if (gui.in_use)
5124     {
5125 	gui_mch_destroy_scrollbar(&wp->w_scrollbars[SBAR_LEFT]);
5126 	gui_mch_destroy_scrollbar(&wp->w_scrollbars[SBAR_RIGHT]);
5127     }
5128 #endif // FEAT_GUI
5129 
5130 #ifdef FEAT_MENU
5131     remove_winbar(wp);
5132 #endif
5133 #ifdef FEAT_PROP_POPUP
5134     free_callback(&wp->w_close_cb);
5135     free_callback(&wp->w_filter_cb);
5136     for (i = 0; i < 4; ++i)
5137 	VIM_CLEAR(wp->w_border_highlight[i]);
5138     vim_free(wp->w_scrollbar_highlight);
5139     vim_free(wp->w_thumb_highlight);
5140     vim_free(wp->w_popup_title);
5141     list_unref(wp->w_popup_mask);
5142     vim_free(wp->w_popup_mask_cells);
5143 #endif
5144 
5145 #ifdef FEAT_SYN_HL
5146     vim_free(wp->w_p_cc_cols);
5147 #endif
5148 
5149     if (win_valid_any_tab(wp))
5150 	win_remove(wp, tp);
5151     if (autocmd_busy)
5152     {
5153 	wp->w_next = au_pending_free_win;
5154 	au_pending_free_win = wp;
5155     }
5156     else
5157 	vim_free(wp);
5158 
5159     unblock_autocmds();
5160 }
5161 
5162 /*
5163  * Return TRUE if "wp" is not in the list of windows: the autocmd window or a
5164  * popup window.
5165  */
5166     static int
5167 win_unlisted(win_T *wp)
5168 {
5169     return wp == aucmd_win || WIN_IS_POPUP(wp);
5170 }
5171 
5172 #if defined(FEAT_PROP_POPUP) || defined(PROTO)
5173 /*
5174  * Free a popup window.  This does not take the window out of the window list
5175  * and assumes there is only one toplevel frame, no split.
5176  */
5177     void
5178 win_free_popup(win_T *win)
5179 {
5180     if (bt_popup(win->w_buffer))
5181 	win_close_buffer(win, DOBUF_WIPE_REUSE, FALSE);
5182     else
5183 	close_buffer(win, win->w_buffer, 0, FALSE, FALSE);
5184 # if defined(FEAT_TIMERS)
5185     if (win->w_popup_timer != NULL)
5186 	stop_timer(win->w_popup_timer);
5187 # endif
5188     vim_free(win->w_frame);
5189     win_free(win, NULL);
5190 }
5191 #endif
5192 
5193 /*
5194  * Append window "wp" in the window list after window "after".
5195  */
5196     static void
5197 win_append(win_T *after, win_T *wp)
5198 {
5199     win_T	*before;
5200 
5201     if (after == NULL)	    // after NULL is in front of the first
5202 	before = firstwin;
5203     else
5204 	before = after->w_next;
5205 
5206     wp->w_next = before;
5207     wp->w_prev = after;
5208     if (after == NULL)
5209 	firstwin = wp;
5210     else
5211 	after->w_next = wp;
5212     if (before == NULL)
5213 	lastwin = wp;
5214     else
5215 	before->w_prev = wp;
5216 }
5217 
5218 /*
5219  * Remove a window from the window list.
5220  */
5221     void
5222 win_remove(
5223     win_T	*wp,
5224     tabpage_T	*tp)		// tab page "win" is in, NULL for current
5225 {
5226     if (wp->w_prev != NULL)
5227 	wp->w_prev->w_next = wp->w_next;
5228     else if (tp == NULL)
5229 	firstwin = curtab->tp_firstwin = wp->w_next;
5230     else
5231 	tp->tp_firstwin = wp->w_next;
5232 
5233     if (wp->w_next != NULL)
5234 	wp->w_next->w_prev = wp->w_prev;
5235     else if (tp == NULL)
5236 	lastwin = curtab->tp_lastwin = wp->w_prev;
5237     else
5238 	tp->tp_lastwin = wp->w_prev;
5239 }
5240 
5241 /*
5242  * Append frame "frp" in a frame list after frame "after".
5243  */
5244     static void
5245 frame_append(frame_T *after, frame_T *frp)
5246 {
5247     frp->fr_next = after->fr_next;
5248     after->fr_next = frp;
5249     if (frp->fr_next != NULL)
5250 	frp->fr_next->fr_prev = frp;
5251     frp->fr_prev = after;
5252 }
5253 
5254 /*
5255  * Insert frame "frp" in a frame list before frame "before".
5256  */
5257     static void
5258 frame_insert(frame_T *before, frame_T *frp)
5259 {
5260     frp->fr_next = before;
5261     frp->fr_prev = before->fr_prev;
5262     before->fr_prev = frp;
5263     if (frp->fr_prev != NULL)
5264 	frp->fr_prev->fr_next = frp;
5265     else
5266 	frp->fr_parent->fr_child = frp;
5267 }
5268 
5269 /*
5270  * Remove a frame from a frame list.
5271  */
5272     static void
5273 frame_remove(frame_T *frp)
5274 {
5275     if (frp->fr_prev != NULL)
5276 	frp->fr_prev->fr_next = frp->fr_next;
5277     else
5278     {
5279 	frp->fr_parent->fr_child = frp->fr_next;
5280 	// special case: topframe->fr_child == frp
5281 	if (topframe->fr_child == frp)
5282 	    topframe->fr_child = frp->fr_next;
5283     }
5284     if (frp->fr_next != NULL)
5285 	frp->fr_next->fr_prev = frp->fr_prev;
5286 }
5287 
5288 /*
5289  * Allocate w_lines[] for window "wp".
5290  * Return FAIL for failure, OK for success.
5291  */
5292     int
5293 win_alloc_lines(win_T *wp)
5294 {
5295     wp->w_lines_valid = 0;
5296     wp->w_lines = ALLOC_CLEAR_MULT(wline_T, Rows );
5297     if (wp->w_lines == NULL)
5298 	return FAIL;
5299     return OK;
5300 }
5301 
5302 /*
5303  * free lsize arrays for a window
5304  */
5305     void
5306 win_free_lsize(win_T *wp)
5307 {
5308     // TODO: why would wp be NULL here?
5309     if (wp != NULL)
5310 	VIM_CLEAR(wp->w_lines);
5311 }
5312 
5313 /*
5314  * Called from win_new_shellsize() after Rows changed.
5315  * This only does the current tab page, others must be done when made active.
5316  */
5317     void
5318 shell_new_rows(void)
5319 {
5320     int		h = (int)ROWS_AVAIL;
5321 
5322     if (firstwin == NULL)	// not initialized yet
5323 	return;
5324     if (h < frame_minheight(topframe, NULL))
5325 	h = frame_minheight(topframe, NULL);
5326 
5327     // First try setting the heights of windows with 'winfixheight'.  If
5328     // that doesn't result in the right height, forget about that option.
5329     frame_new_height(topframe, h, FALSE, TRUE);
5330     if (!frame_check_height(topframe, h))
5331 	frame_new_height(topframe, h, FALSE, FALSE);
5332 
5333     (void)win_comp_pos();		// recompute w_winrow and w_wincol
5334     compute_cmdrow();
5335     curtab->tp_ch_used = p_ch;
5336 
5337 #if 0
5338     // Disabled: don't want making the screen smaller make a window larger.
5339     if (p_ea)
5340 	win_equal(curwin, FALSE, 'v');
5341 #endif
5342 }
5343 
5344 /*
5345  * Called from win_new_shellsize() after Columns changed.
5346  */
5347     void
5348 shell_new_columns(void)
5349 {
5350     if (firstwin == NULL)	// not initialized yet
5351 	return;
5352 
5353     // First try setting the widths of windows with 'winfixwidth'.  If that
5354     // doesn't result in the right width, forget about that option.
5355     frame_new_width(topframe, (int)Columns, FALSE, TRUE);
5356     if (!frame_check_width(topframe, Columns))
5357 	frame_new_width(topframe, (int)Columns, FALSE, FALSE);
5358 
5359     (void)win_comp_pos();		// recompute w_winrow and w_wincol
5360 #if 0
5361     // Disabled: don't want making the screen smaller make a window larger.
5362     if (p_ea)
5363 	win_equal(curwin, FALSE, 'h');
5364 #endif
5365 }
5366 
5367 #if defined(FEAT_CMDWIN) || defined(PROTO)
5368 /*
5369  * Save the size of all windows in "gap".
5370  */
5371     void
5372 win_size_save(garray_T *gap)
5373 
5374 {
5375     win_T	*wp;
5376 
5377     ga_init2(gap, (int)sizeof(int), 1);
5378     if (ga_grow(gap, win_count() * 2 + 1) == OK)
5379     {
5380 	// first entry is value of 'lines'
5381 	((int *)gap->ga_data)[gap->ga_len++] = Rows;
5382 
5383 	FOR_ALL_WINDOWS(wp)
5384 	{
5385 	    ((int *)gap->ga_data)[gap->ga_len++] =
5386 					       wp->w_width + wp->w_vsep_width;
5387 	    ((int *)gap->ga_data)[gap->ga_len++] = wp->w_height;
5388 	}
5389     }
5390 }
5391 
5392 /*
5393  * Restore window sizes, but only if the number of windows is still the same
5394  * and 'lines' didn't change.
5395  * Does not free the growarray.
5396  */
5397     void
5398 win_size_restore(garray_T *gap)
5399 {
5400     win_T	*wp;
5401     int		i, j;
5402 
5403     if (win_count() * 2 + 1 == gap->ga_len
5404 	    && ((int *)gap->ga_data)[0] == Rows)
5405     {
5406 	// The order matters, because frames contain other frames, but it's
5407 	// difficult to get right. The easy way out is to do it twice.
5408 	for (j = 0; j < 2; ++j)
5409 	{
5410 	    i = 1;
5411 	    FOR_ALL_WINDOWS(wp)
5412 	    {
5413 		frame_setwidth(wp->w_frame, ((int *)gap->ga_data)[i++]);
5414 		win_setheight_win(((int *)gap->ga_data)[i++], wp);
5415 	    }
5416 	}
5417 	// recompute the window positions
5418 	(void)win_comp_pos();
5419     }
5420 }
5421 #endif // FEAT_CMDWIN
5422 
5423 /*
5424  * Update the position for all windows, using the width and height of the
5425  * frames.
5426  * Returns the row just after the last window.
5427  */
5428     int
5429 win_comp_pos(void)
5430 {
5431     int		row = tabline_height();
5432     int		col = 0;
5433 
5434     frame_comp_pos(topframe, &row, &col);
5435     return row;
5436 }
5437 
5438 /*
5439  * Update the position of the windows in frame "topfrp", using the width and
5440  * height of the frames.
5441  * "*row" and "*col" are the top-left position of the frame.  They are updated
5442  * to the bottom-right position plus one.
5443  */
5444     static void
5445 frame_comp_pos(frame_T *topfrp, int *row, int *col)
5446 {
5447     win_T	*wp;
5448     frame_T	*frp;
5449     int		startcol;
5450     int		startrow;
5451     int		h;
5452 
5453     wp = topfrp->fr_win;
5454     if (wp != NULL)
5455     {
5456 	if (wp->w_winrow != *row || wp->w_wincol != *col)
5457 	{
5458 	    // position changed, redraw
5459 	    wp->w_winrow = *row;
5460 	    wp->w_wincol = *col;
5461 	    redraw_win_later(wp, NOT_VALID);
5462 	    wp->w_redr_status = TRUE;
5463 	}
5464 	// WinBar will not show if the window height is zero
5465 	h = VISIBLE_HEIGHT(wp) + wp->w_status_height;
5466 	*row += h > topfrp->fr_height ? topfrp->fr_height : h;
5467 	*col += wp->w_width + wp->w_vsep_width;
5468     }
5469     else
5470     {
5471 	startrow = *row;
5472 	startcol = *col;
5473 	FOR_ALL_FRAMES(frp, topfrp->fr_child)
5474 	{
5475 	    if (topfrp->fr_layout == FR_ROW)
5476 		*row = startrow;	// all frames are at the same row
5477 	    else
5478 		*col = startcol;	// all frames are at the same col
5479 	    frame_comp_pos(frp, row, col);
5480 	}
5481     }
5482 }
5483 
5484 /*
5485  * Set current window height and take care of repositioning other windows to
5486  * fit around it.
5487  */
5488     void
5489 win_setheight(int height)
5490 {
5491     win_setheight_win(height, curwin);
5492 }
5493 
5494 /*
5495  * Set the window height of window "win" and take care of repositioning other
5496  * windows to fit around it.
5497  */
5498     void
5499 win_setheight_win(int height, win_T *win)
5500 {
5501     int		row;
5502 
5503     if (win == curwin)
5504     {
5505 	// Always keep current window at least one line high, even when
5506 	// 'winminheight' is zero.
5507 	if (height < p_wmh)
5508 	    height = p_wmh;
5509 	if (height == 0)
5510 	    height = 1;
5511 	height += WINBAR_HEIGHT(curwin);
5512     }
5513 
5514     frame_setheight(win->w_frame, height + win->w_status_height);
5515 
5516     // recompute the window positions
5517     row = win_comp_pos();
5518 
5519     /*
5520      * If there is extra space created between the last window and the command
5521      * line, clear it.
5522      */
5523     if (full_screen && msg_scrolled == 0 && row < cmdline_row)
5524 	screen_fill(row, cmdline_row, 0, (int)Columns, ' ', ' ', 0);
5525     cmdline_row = row;
5526     msg_row = row;
5527     msg_col = 0;
5528 
5529     redraw_all_later(NOT_VALID);
5530 }
5531 
5532 /*
5533  * Set the height of a frame to "height" and take care that all frames and
5534  * windows inside it are resized.  Also resize frames on the left and right if
5535  * the are in the same FR_ROW frame.
5536  *
5537  * Strategy:
5538  * If the frame is part of a FR_COL frame, try fitting the frame in that
5539  * frame.  If that doesn't work (the FR_COL frame is too small), recursively
5540  * go to containing frames to resize them and make room.
5541  * If the frame is part of a FR_ROW frame, all frames must be resized as well.
5542  * Check for the minimal height of the FR_ROW frame.
5543  * At the top level we can also use change the command line height.
5544  */
5545     static void
5546 frame_setheight(frame_T *curfrp, int height)
5547 {
5548     int		room;		// total number of lines available
5549     int		take;		// number of lines taken from other windows
5550     int		room_cmdline;	// lines available from cmdline
5551     int		run;
5552     frame_T	*frp;
5553     int		h;
5554     int		room_reserved;
5555 
5556     // If the height already is the desired value, nothing to do.
5557     if (curfrp->fr_height == height)
5558 	return;
5559 
5560     if (curfrp->fr_parent == NULL)
5561     {
5562 	// topframe: can only change the command line
5563 	if (height > ROWS_AVAIL)
5564 	    height = ROWS_AVAIL;
5565 	if (height > 0)
5566 	    frame_new_height(curfrp, height, FALSE, FALSE);
5567     }
5568     else if (curfrp->fr_parent->fr_layout == FR_ROW)
5569     {
5570 	// Row of frames: Also need to resize frames left and right of this
5571 	// one.  First check for the minimal height of these.
5572 	h = frame_minheight(curfrp->fr_parent, NULL);
5573 	if (height < h)
5574 	    height = h;
5575 	frame_setheight(curfrp->fr_parent, height);
5576     }
5577     else
5578     {
5579 	/*
5580 	 * Column of frames: try to change only frames in this column.
5581 	 */
5582 	/*
5583 	 * Do this twice:
5584 	 * 1: compute room available, if it's not enough try resizing the
5585 	 *    containing frame.
5586 	 * 2: compute the room available and adjust the height to it.
5587 	 * Try not to reduce the height of a window with 'winfixheight' set.
5588 	 */
5589 	for (run = 1; run <= 2; ++run)
5590 	{
5591 	    room = 0;
5592 	    room_reserved = 0;
5593 	    FOR_ALL_FRAMES(frp, curfrp->fr_parent->fr_child)
5594 	    {
5595 		if (frp != curfrp
5596 			&& frp->fr_win != NULL
5597 			&& frp->fr_win->w_p_wfh)
5598 		    room_reserved += frp->fr_height;
5599 		room += frp->fr_height;
5600 		if (frp != curfrp)
5601 		    room -= frame_minheight(frp, NULL);
5602 	    }
5603 	    if (curfrp->fr_width != Columns)
5604 		room_cmdline = 0;
5605 	    else
5606 	    {
5607 		room_cmdline = Rows - p_ch - (lastwin->w_winrow
5608 						+ VISIBLE_HEIGHT(lastwin)
5609 						+ lastwin->w_status_height);
5610 		if (room_cmdline < 0)
5611 		    room_cmdline = 0;
5612 	    }
5613 
5614 	    if (height <= room + room_cmdline)
5615 		break;
5616 	    if (run == 2 || curfrp->fr_width == Columns)
5617 	    {
5618 		if (height > room + room_cmdline)
5619 		    height = room + room_cmdline;
5620 		break;
5621 	    }
5622 	    frame_setheight(curfrp->fr_parent, height
5623 		+ frame_minheight(curfrp->fr_parent, NOWIN) - (int)p_wmh - 1);
5624 	}
5625 
5626 	/*
5627 	 * Compute the number of lines we will take from others frames (can be
5628 	 * negative!).
5629 	 */
5630 	take = height - curfrp->fr_height;
5631 
5632 	// If there is not enough room, also reduce the height of a window
5633 	// with 'winfixheight' set.
5634 	if (height > room + room_cmdline - room_reserved)
5635 	    room_reserved = room + room_cmdline - height;
5636 	// If there is only a 'winfixheight' window and making the
5637 	// window smaller, need to make the other window taller.
5638 	if (take < 0 && room - curfrp->fr_height < room_reserved)
5639 	    room_reserved = 0;
5640 
5641 	if (take > 0 && room_cmdline > 0)
5642 	{
5643 	    // use lines from cmdline first
5644 	    if (take < room_cmdline)
5645 		room_cmdline = take;
5646 	    take -= room_cmdline;
5647 	    topframe->fr_height += room_cmdline;
5648 	}
5649 
5650 	/*
5651 	 * set the current frame to the new height
5652 	 */
5653 	frame_new_height(curfrp, height, FALSE, FALSE);
5654 
5655 	/*
5656 	 * First take lines from the frames after the current frame.  If
5657 	 * that is not enough, takes lines from frames above the current
5658 	 * frame.
5659 	 */
5660 	for (run = 0; run < 2; ++run)
5661 	{
5662 	    if (run == 0)
5663 		frp = curfrp->fr_next;	// 1st run: start with next window
5664 	    else
5665 		frp = curfrp->fr_prev;	// 2nd run: start with prev window
5666 	    while (frp != NULL && take != 0)
5667 	    {
5668 		h = frame_minheight(frp, NULL);
5669 		if (room_reserved > 0
5670 			&& frp->fr_win != NULL
5671 			&& frp->fr_win->w_p_wfh)
5672 		{
5673 		    if (room_reserved >= frp->fr_height)
5674 			room_reserved -= frp->fr_height;
5675 		    else
5676 		    {
5677 			if (frp->fr_height - room_reserved > take)
5678 			    room_reserved = frp->fr_height - take;
5679 			take -= frp->fr_height - room_reserved;
5680 			frame_new_height(frp, room_reserved, FALSE, FALSE);
5681 			room_reserved = 0;
5682 		    }
5683 		}
5684 		else
5685 		{
5686 		    if (frp->fr_height - take < h)
5687 		    {
5688 			take -= frp->fr_height - h;
5689 			frame_new_height(frp, h, FALSE, FALSE);
5690 		    }
5691 		    else
5692 		    {
5693 			frame_new_height(frp, frp->fr_height - take,
5694 								FALSE, FALSE);
5695 			take = 0;
5696 		    }
5697 		}
5698 		if (run == 0)
5699 		    frp = frp->fr_next;
5700 		else
5701 		    frp = frp->fr_prev;
5702 	    }
5703 	}
5704     }
5705 }
5706 
5707 /*
5708  * Set current window width and take care of repositioning other windows to
5709  * fit around it.
5710  */
5711     void
5712 win_setwidth(int width)
5713 {
5714     win_setwidth_win(width, curwin);
5715 }
5716 
5717     void
5718 win_setwidth_win(int width, win_T *wp)
5719 {
5720     // Always keep current window at least one column wide, even when
5721     // 'winminwidth' is zero.
5722     if (wp == curwin)
5723     {
5724 	if (width < p_wmw)
5725 	    width = p_wmw;
5726 	if (width == 0)
5727 	    width = 1;
5728     }
5729     else if (width < 0)
5730 	width = 0;
5731 
5732     frame_setwidth(wp->w_frame, width + wp->w_vsep_width);
5733 
5734     // recompute the window positions
5735     (void)win_comp_pos();
5736 
5737     redraw_all_later(NOT_VALID);
5738 }
5739 
5740 /*
5741  * Set the width of a frame to "width" and take care that all frames and
5742  * windows inside it are resized.  Also resize frames above and below if the
5743  * are in the same FR_ROW frame.
5744  *
5745  * Strategy is similar to frame_setheight().
5746  */
5747     static void
5748 frame_setwidth(frame_T *curfrp, int width)
5749 {
5750     int		room;		// total number of lines available
5751     int		take;		// number of lines taken from other windows
5752     int		run;
5753     frame_T	*frp;
5754     int		w;
5755     int		room_reserved;
5756 
5757     // If the width already is the desired value, nothing to do.
5758     if (curfrp->fr_width == width)
5759 	return;
5760 
5761     if (curfrp->fr_parent == NULL)
5762 	// topframe: can't change width
5763 	return;
5764 
5765     if (curfrp->fr_parent->fr_layout == FR_COL)
5766     {
5767 	// Column of frames: Also need to resize frames above and below of
5768 	// this one.  First check for the minimal width of these.
5769 	w = frame_minwidth(curfrp->fr_parent, NULL);
5770 	if (width < w)
5771 	    width = w;
5772 	frame_setwidth(curfrp->fr_parent, width);
5773     }
5774     else
5775     {
5776 	/*
5777 	 * Row of frames: try to change only frames in this row.
5778 	 *
5779 	 * Do this twice:
5780 	 * 1: compute room available, if it's not enough try resizing the
5781 	 *    containing frame.
5782 	 * 2: compute the room available and adjust the width to it.
5783 	 */
5784 	for (run = 1; run <= 2; ++run)
5785 	{
5786 	    room = 0;
5787 	    room_reserved = 0;
5788 	    FOR_ALL_FRAMES(frp, curfrp->fr_parent->fr_child)
5789 	    {
5790 		if (frp != curfrp
5791 			&& frp->fr_win != NULL
5792 			&& frp->fr_win->w_p_wfw)
5793 		    room_reserved += frp->fr_width;
5794 		room += frp->fr_width;
5795 		if (frp != curfrp)
5796 		    room -= frame_minwidth(frp, NULL);
5797 	    }
5798 
5799 	    if (width <= room)
5800 		break;
5801 	    if (run == 2 || curfrp->fr_height >= ROWS_AVAIL)
5802 	    {
5803 		if (width > room)
5804 		    width = room;
5805 		break;
5806 	    }
5807 	    frame_setwidth(curfrp->fr_parent, width
5808 		 + frame_minwidth(curfrp->fr_parent, NOWIN) - (int)p_wmw - 1);
5809 	}
5810 
5811 	/*
5812 	 * Compute the number of lines we will take from others frames (can be
5813 	 * negative!).
5814 	 */
5815 	take = width - curfrp->fr_width;
5816 
5817 	// If there is not enough room, also reduce the width of a window
5818 	// with 'winfixwidth' set.
5819 	if (width > room - room_reserved)
5820 	    room_reserved = room - width;
5821 	// If there is only a 'winfixwidth' window and making the
5822 	// window smaller, need to make the other window narrower.
5823 	if (take < 0 && room - curfrp->fr_width < room_reserved)
5824 	    room_reserved = 0;
5825 
5826 	/*
5827 	 * set the current frame to the new width
5828 	 */
5829 	frame_new_width(curfrp, width, FALSE, FALSE);
5830 
5831 	/*
5832 	 * First take lines from the frames right of the current frame.  If
5833 	 * that is not enough, takes lines from frames left of the current
5834 	 * frame.
5835 	 */
5836 	for (run = 0; run < 2; ++run)
5837 	{
5838 	    if (run == 0)
5839 		frp = curfrp->fr_next;	// 1st run: start with next window
5840 	    else
5841 		frp = curfrp->fr_prev;	// 2nd run: start with prev window
5842 	    while (frp != NULL && take != 0)
5843 	    {
5844 		w = frame_minwidth(frp, NULL);
5845 		if (room_reserved > 0
5846 			&& frp->fr_win != NULL
5847 			&& frp->fr_win->w_p_wfw)
5848 		{
5849 		    if (room_reserved >= frp->fr_width)
5850 			room_reserved -= frp->fr_width;
5851 		    else
5852 		    {
5853 			if (frp->fr_width - room_reserved > take)
5854 			    room_reserved = frp->fr_width - take;
5855 			take -= frp->fr_width - room_reserved;
5856 			frame_new_width(frp, room_reserved, FALSE, FALSE);
5857 			room_reserved = 0;
5858 		    }
5859 		}
5860 		else
5861 		{
5862 		    if (frp->fr_width - take < w)
5863 		    {
5864 			take -= frp->fr_width - w;
5865 			frame_new_width(frp, w, FALSE, FALSE);
5866 		    }
5867 		    else
5868 		    {
5869 			frame_new_width(frp, frp->fr_width - take,
5870 								FALSE, FALSE);
5871 			take = 0;
5872 		    }
5873 		}
5874 		if (run == 0)
5875 		    frp = frp->fr_next;
5876 		else
5877 		    frp = frp->fr_prev;
5878 	    }
5879 	}
5880     }
5881 }
5882 
5883 /*
5884  * Check 'winminheight' for a valid value and reduce it if needed.
5885  */
5886     void
5887 win_setminheight(void)
5888 {
5889     int		room;
5890     int		needed;
5891     int		first = TRUE;
5892 
5893     // loop until there is a 'winminheight' that is possible
5894     while (p_wmh > 0)
5895     {
5896 	room = Rows - p_ch;
5897 	needed = min_rows() - 1;  // 1 was added for the cmdline
5898 	if (room >= needed)
5899 	    break;
5900 	--p_wmh;
5901 	if (first)
5902 	{
5903 	    emsg(_(e_not_enough_room));
5904 	    first = FALSE;
5905 	}
5906     }
5907 }
5908 
5909 /*
5910  * Check 'winminwidth' for a valid value and reduce it if needed.
5911  */
5912     void
5913 win_setminwidth(void)
5914 {
5915     int		room;
5916     int		needed;
5917     int		first = TRUE;
5918 
5919     // loop until there is a 'winminheight' that is possible
5920     while (p_wmw > 0)
5921     {
5922 	room = Columns;
5923 	needed = frame_minwidth(topframe, NULL);
5924 	if (room >= needed)
5925 	    break;
5926 	--p_wmw;
5927 	if (first)
5928 	{
5929 	    emsg(_(e_not_enough_room));
5930 	    first = FALSE;
5931 	}
5932     }
5933 }
5934 
5935 /*
5936  * Status line of dragwin is dragged "offset" lines down (negative is up).
5937  */
5938     void
5939 win_drag_status_line(win_T *dragwin, int offset)
5940 {
5941     frame_T	*curfr;
5942     frame_T	*fr;
5943     int		room;
5944     int		row;
5945     int		up;	// if TRUE, drag status line up, otherwise down
5946     int		n;
5947 
5948     fr = dragwin->w_frame;
5949     curfr = fr;
5950     if (fr != topframe)		// more than one window
5951     {
5952 	fr = fr->fr_parent;
5953 	// When the parent frame is not a column of frames, its parent should
5954 	// be.
5955 	if (fr->fr_layout != FR_COL)
5956 	{
5957 	    curfr = fr;
5958 	    if (fr != topframe)	// only a row of windows, may drag statusline
5959 		fr = fr->fr_parent;
5960 	}
5961     }
5962 
5963     // If this is the last frame in a column, may want to resize the parent
5964     // frame instead (go two up to skip a row of frames).
5965     while (curfr != topframe && curfr->fr_next == NULL)
5966     {
5967 	if (fr != topframe)
5968 	    fr = fr->fr_parent;
5969 	curfr = fr;
5970 	if (fr != topframe)
5971 	    fr = fr->fr_parent;
5972     }
5973 
5974     if (offset < 0) // drag up
5975     {
5976 	up = TRUE;
5977 	offset = -offset;
5978 	// sum up the room of the current frame and above it
5979 	if (fr == curfr)
5980 	{
5981 	    // only one window
5982 	    room = fr->fr_height - frame_minheight(fr, NULL);
5983 	}
5984 	else
5985 	{
5986 	    room = 0;
5987 	    for (fr = fr->fr_child; ; fr = fr->fr_next)
5988 	    {
5989 		room += fr->fr_height - frame_minheight(fr, NULL);
5990 		if (fr == curfr)
5991 		    break;
5992 	    }
5993 	}
5994 	fr = curfr->fr_next;		// put fr at frame that grows
5995     }
5996     else    // drag down
5997     {
5998 	up = FALSE;
5999 	/*
6000 	 * Only dragging the last status line can reduce p_ch.
6001 	 */
6002 	room = Rows - cmdline_row;
6003 	if (curfr->fr_next == NULL)
6004 	    room -= 1;
6005 	else
6006 	    room -= p_ch;
6007 	if (room < 0)
6008 	    room = 0;
6009 	// sum up the room of frames below of the current one
6010 	FOR_ALL_FRAMES(fr, curfr->fr_next)
6011 	    room += fr->fr_height - frame_minheight(fr, NULL);
6012 	fr = curfr;			// put fr at window that grows
6013     }
6014 
6015     if (room < offset)		// Not enough room
6016 	offset = room;		// Move as far as we can
6017     if (offset <= 0)
6018 	return;
6019 
6020     /*
6021      * Grow frame fr by "offset" lines.
6022      * Doesn't happen when dragging the last status line up.
6023      */
6024     if (fr != NULL)
6025 	frame_new_height(fr, fr->fr_height + offset, up, FALSE);
6026 
6027     if (up)
6028 	fr = curfr;		// current frame gets smaller
6029     else
6030 	fr = curfr->fr_next;	// next frame gets smaller
6031 
6032     /*
6033      * Now make the other frames smaller.
6034      */
6035     while (fr != NULL && offset > 0)
6036     {
6037 	n = frame_minheight(fr, NULL);
6038 	if (fr->fr_height - offset <= n)
6039 	{
6040 	    offset -= fr->fr_height - n;
6041 	    frame_new_height(fr, n, !up, FALSE);
6042 	}
6043 	else
6044 	{
6045 	    frame_new_height(fr, fr->fr_height - offset, !up, FALSE);
6046 	    break;
6047 	}
6048 	if (up)
6049 	    fr = fr->fr_prev;
6050 	else
6051 	    fr = fr->fr_next;
6052     }
6053     row = win_comp_pos();
6054     screen_fill(row, cmdline_row, 0, (int)Columns, ' ', ' ', 0);
6055     cmdline_row = row;
6056     p_ch = Rows - cmdline_row;
6057     if (p_ch < 1)
6058 	p_ch = 1;
6059     curtab->tp_ch_used = p_ch;
6060     redraw_all_later(SOME_VALID);
6061     showmode();
6062 }
6063 
6064 /*
6065  * Separator line of dragwin is dragged "offset" lines right (negative is left).
6066  */
6067     void
6068 win_drag_vsep_line(win_T *dragwin, int offset)
6069 {
6070     frame_T	*curfr;
6071     frame_T	*fr;
6072     int		room;
6073     int		left;	// if TRUE, drag separator line left, otherwise right
6074     int		n;
6075 
6076     fr = dragwin->w_frame;
6077     if (fr == topframe)		// only one window (cannot happen?)
6078 	return;
6079     curfr = fr;
6080     fr = fr->fr_parent;
6081     // When the parent frame is not a row of frames, its parent should be.
6082     if (fr->fr_layout != FR_ROW)
6083     {
6084 	if (fr == topframe)	// only a column of windows (cannot happen?)
6085 	    return;
6086 	curfr = fr;
6087 	fr = fr->fr_parent;
6088     }
6089 
6090     // If this is the last frame in a row, may want to resize a parent
6091     // frame instead.
6092     while (curfr->fr_next == NULL)
6093     {
6094 	if (fr == topframe)
6095 	    break;
6096 	curfr = fr;
6097 	fr = fr->fr_parent;
6098 	if (fr != topframe)
6099 	{
6100 	    curfr = fr;
6101 	    fr = fr->fr_parent;
6102 	}
6103     }
6104 
6105     if (offset < 0) // drag left
6106     {
6107 	left = TRUE;
6108 	offset = -offset;
6109 	// sum up the room of the current frame and left of it
6110 	room = 0;
6111 	for (fr = fr->fr_child; ; fr = fr->fr_next)
6112 	{
6113 	    room += fr->fr_width - frame_minwidth(fr, NULL);
6114 	    if (fr == curfr)
6115 		break;
6116 	}
6117 	fr = curfr->fr_next;		// put fr at frame that grows
6118     }
6119     else    // drag right
6120     {
6121 	left = FALSE;
6122 	// sum up the room of frames right of the current one
6123 	room = 0;
6124 	FOR_ALL_FRAMES(fr, curfr->fr_next)
6125 	    room += fr->fr_width - frame_minwidth(fr, NULL);
6126 	fr = curfr;			// put fr at window that grows
6127     }
6128 
6129     if (room < offset)		// Not enough room
6130 	offset = room;		// Move as far as we can
6131     if (offset <= 0)		// No room at all, quit.
6132 	return;
6133     if (fr == NULL)
6134 	return;			// Safety check, should not happen.
6135 
6136     // grow frame fr by offset lines
6137     frame_new_width(fr, fr->fr_width + offset, left, FALSE);
6138 
6139     // shrink other frames: current and at the left or at the right
6140     if (left)
6141 	fr = curfr;		// current frame gets smaller
6142     else
6143 	fr = curfr->fr_next;	// next frame gets smaller
6144 
6145     while (fr != NULL && offset > 0)
6146     {
6147 	n = frame_minwidth(fr, NULL);
6148 	if (fr->fr_width - offset <= n)
6149 	{
6150 	    offset -= fr->fr_width - n;
6151 	    frame_new_width(fr, n, !left, FALSE);
6152 	}
6153 	else
6154 	{
6155 	    frame_new_width(fr, fr->fr_width - offset, !left, FALSE);
6156 	    break;
6157 	}
6158 	if (left)
6159 	    fr = fr->fr_prev;
6160 	else
6161 	    fr = fr->fr_next;
6162     }
6163     (void)win_comp_pos();
6164     redraw_all_later(NOT_VALID);
6165 }
6166 
6167 #define FRACTION_MULT	16384L
6168 
6169 /*
6170  * Set wp->w_fraction for the current w_wrow and w_height.
6171  * Has no effect when the window is less than two lines.
6172  */
6173     void
6174 set_fraction(win_T *wp)
6175 {
6176     if (wp->w_height > 1)
6177 	// When cursor is in the first line the percentage is computed as if
6178 	// it's halfway that line.  Thus with two lines it is 25%, with three
6179 	// lines 17%, etc.  Similarly for the last line: 75%, 83%, etc.
6180 	wp->w_fraction = ((long)wp->w_wrow * FRACTION_MULT
6181 				     + FRACTION_MULT / 2) / (long)wp->w_height;
6182 }
6183 
6184 /*
6185  * Set the height of a window.
6186  * "height" excludes any window toolbar.
6187  * This takes care of the things inside the window, not what happens to the
6188  * window position, the frame or to other windows.
6189  */
6190     void
6191 win_new_height(win_T *wp, int height)
6192 {
6193     int		prev_height = wp->w_height;
6194 
6195     // Don't want a negative height.  Happens when splitting a tiny window.
6196     // Will equalize heights soon to fix it.
6197     if (height < 0)
6198 	height = 0;
6199     if (wp->w_height == height)
6200 	return;	    // nothing to do
6201 
6202     if (wp->w_height > 0)
6203     {
6204 	if (wp == curwin)
6205 	    // w_wrow needs to be valid. When setting 'laststatus' this may
6206 	    // call win_new_height() recursively.
6207 	    validate_cursor();
6208 	if (wp->w_height != prev_height)
6209 	    return;  // Recursive call already changed the size, bail out here
6210 		     //	to avoid the following to mess things up.
6211 	if (wp->w_wrow != wp->w_prev_fraction_row)
6212 	    set_fraction(wp);
6213     }
6214 
6215     wp->w_height = height;
6216     wp->w_skipcol = 0;
6217 
6218     // There is no point in adjusting the scroll position when exiting.  Some
6219     // values might be invalid.
6220     if (!exiting)
6221 	scroll_to_fraction(wp, prev_height);
6222 }
6223 
6224     void
6225 scroll_to_fraction(win_T *wp, int prev_height)
6226 {
6227     linenr_T	lnum;
6228     int		sline, line_size;
6229     int		height = wp->w_height;
6230 
6231     // Don't change w_topline in any of these cases:
6232     // - window height is 0
6233     // - 'scrollbind' is set and this isn't the current window
6234     // - window height is sufficient to display the whole buffer and first line
6235     //   is visible.
6236     if (height > 0
6237         && (!wp->w_p_scb || wp == curwin)
6238         && (height < wp->w_buffer->b_ml.ml_line_count || wp->w_topline > 1))
6239     {
6240 	/*
6241 	 * Find a value for w_topline that shows the cursor at the same
6242 	 * relative position in the window as before (more or less).
6243 	 */
6244 	lnum = wp->w_cursor.lnum;
6245 	if (lnum < 1)		// can happen when starting up
6246 	    lnum = 1;
6247 	wp->w_wrow = ((long)wp->w_fraction * (long)height - 1L)
6248 							       / FRACTION_MULT;
6249 	line_size = plines_win_col(wp, lnum, (long)(wp->w_cursor.col)) - 1;
6250 	sline = wp->w_wrow - line_size;
6251 
6252 	if (sline >= 0)
6253 	{
6254 	    // Make sure the whole cursor line is visible, if possible.
6255 	    int rows = plines_win(wp, lnum, FALSE);
6256 
6257 	    if (sline > wp->w_height - rows)
6258 	    {
6259 		sline = wp->w_height - rows;
6260 		wp->w_wrow -= rows - line_size;
6261 	    }
6262 	}
6263 
6264 	if (sline < 0)
6265 	{
6266 	    /*
6267 	     * Cursor line would go off top of screen if w_wrow was this high.
6268 	     * Make cursor line the first line in the window.  If not enough
6269 	     * room use w_skipcol;
6270 	     */
6271 	    wp->w_wrow = line_size;
6272 	    if (wp->w_wrow >= wp->w_height
6273 				       && (wp->w_width - win_col_off(wp)) > 0)
6274 	    {
6275 		wp->w_skipcol += wp->w_width - win_col_off(wp);
6276 		--wp->w_wrow;
6277 		while (wp->w_wrow >= wp->w_height)
6278 		{
6279 		    wp->w_skipcol += wp->w_width - win_col_off(wp)
6280 							   + win_col_off2(wp);
6281 		    --wp->w_wrow;
6282 		}
6283 	    }
6284 	}
6285 	else if (sline > 0)
6286 	{
6287 	    while (sline > 0 && lnum > 1)
6288 	    {
6289 #ifdef FEAT_FOLDING
6290 		hasFoldingWin(wp, lnum, &lnum, NULL, TRUE, NULL);
6291 		if (lnum == 1)
6292 		{
6293 		    // first line in buffer is folded
6294 		    line_size = 1;
6295 		    --sline;
6296 		    break;
6297 		}
6298 #endif
6299 		--lnum;
6300 #ifdef FEAT_DIFF
6301 		if (lnum == wp->w_topline)
6302 		    line_size = plines_win_nofill(wp, lnum, TRUE)
6303 							      + wp->w_topfill;
6304 		else
6305 #endif
6306 		    line_size = plines_win(wp, lnum, TRUE);
6307 		sline -= line_size;
6308 	    }
6309 
6310 	    if (sline < 0)
6311 	    {
6312 		/*
6313 		 * Line we want at top would go off top of screen.  Use next
6314 		 * line instead.
6315 		 */
6316 #ifdef FEAT_FOLDING
6317 		hasFoldingWin(wp, lnum, NULL, &lnum, TRUE, NULL);
6318 #endif
6319 		lnum++;
6320 		wp->w_wrow -= line_size + sline;
6321 	    }
6322 	    else if (sline > 0)
6323 	    {
6324 		// First line of file reached, use that as topline.
6325 		lnum = 1;
6326 		wp->w_wrow -= sline;
6327 	    }
6328 	}
6329 	set_topline(wp, lnum);
6330     }
6331 
6332     if (wp == curwin)
6333     {
6334 	if (get_scrolloff_value())
6335 	    update_topline();
6336 	curs_columns(FALSE);	// validate w_wrow
6337     }
6338     if (prev_height > 0)
6339 	wp->w_prev_fraction_row = wp->w_wrow;
6340 
6341     win_comp_scroll(wp);
6342     redraw_win_later(wp, SOME_VALID);
6343     wp->w_redr_status = TRUE;
6344     invalidate_botline_win(wp);
6345 }
6346 
6347 /*
6348  * Set the width of a window.
6349  */
6350     void
6351 win_new_width(win_T *wp, int width)
6352 {
6353     wp->w_width = width;
6354     wp->w_lines_valid = 0;
6355     changed_line_abv_curs_win(wp);
6356     invalidate_botline_win(wp);
6357     if (wp == curwin)
6358     {
6359 	update_topline();
6360 	curs_columns(TRUE);	// validate w_wrow
6361     }
6362     redraw_win_later(wp, NOT_VALID);
6363     wp->w_redr_status = TRUE;
6364 }
6365 
6366     void
6367 win_comp_scroll(win_T *wp)
6368 {
6369 #if defined(FEAT_EVAL)
6370     int old_w_p_scr = wp->w_p_scr;
6371 #endif
6372 
6373     wp->w_p_scr = ((unsigned)wp->w_height >> 1);
6374     if (wp->w_p_scr == 0)
6375 	wp->w_p_scr = 1;
6376 #if defined(FEAT_EVAL)
6377     if (wp->w_p_scr != old_w_p_scr)
6378     {
6379 	// Used by "verbose set scroll".
6380 	wp->w_p_script_ctx[WV_SCROLL].sc_sid = SID_WINLAYOUT;
6381 	wp->w_p_script_ctx[WV_SCROLL].sc_lnum = 0;
6382     }
6383 #endif
6384 }
6385 
6386 /*
6387  * command_height: called whenever p_ch has been changed
6388  */
6389     void
6390 command_height(void)
6391 {
6392     int		h;
6393     frame_T	*frp;
6394     int		old_p_ch = curtab->tp_ch_used;
6395 
6396     // Use the value of p_ch that we remembered.  This is needed for when the
6397     // GUI starts up, we can't be sure in what order things happen.  And when
6398     // p_ch was changed in another tab page.
6399     curtab->tp_ch_used = p_ch;
6400 
6401     // Find bottom frame with width of screen.
6402     frp = lastwin->w_frame;
6403     while (frp->fr_width != Columns && frp->fr_parent != NULL)
6404 	frp = frp->fr_parent;
6405 
6406     // Avoid changing the height of a window with 'winfixheight' set.
6407     while (frp->fr_prev != NULL && frp->fr_layout == FR_LEAF
6408 						      && frp->fr_win->w_p_wfh)
6409 	frp = frp->fr_prev;
6410 
6411     if (starting != NO_SCREEN)
6412     {
6413 	cmdline_row = Rows - p_ch;
6414 
6415 	if (p_ch > old_p_ch)		    // p_ch got bigger
6416 	{
6417 	    while (p_ch > old_p_ch)
6418 	    {
6419 		if (frp == NULL)
6420 		{
6421 		    emsg(_(e_not_enough_room));
6422 		    p_ch = old_p_ch;
6423 		    curtab->tp_ch_used = p_ch;
6424 		    cmdline_row = Rows - p_ch;
6425 		    break;
6426 		}
6427 		h = frp->fr_height - frame_minheight(frp, NULL);
6428 		if (h > p_ch - old_p_ch)
6429 		    h = p_ch - old_p_ch;
6430 		old_p_ch += h;
6431 		frame_add_height(frp, -h);
6432 		frp = frp->fr_prev;
6433 	    }
6434 
6435 	    // Recompute window positions.
6436 	    (void)win_comp_pos();
6437 
6438 	    // clear the lines added to cmdline
6439 	    if (full_screen)
6440 		screen_fill((int)(cmdline_row), (int)Rows, 0,
6441 						   (int)Columns, ' ', ' ', 0);
6442 	    msg_row = cmdline_row;
6443 	    redraw_cmdline = TRUE;
6444 	    return;
6445 	}
6446 
6447 	if (msg_row < cmdline_row)
6448 	    msg_row = cmdline_row;
6449 	redraw_cmdline = TRUE;
6450     }
6451     frame_add_height(frp, (int)(old_p_ch - p_ch));
6452 
6453     // Recompute window positions.
6454     if (frp != lastwin->w_frame)
6455 	(void)win_comp_pos();
6456 }
6457 
6458 /*
6459  * Resize frame "frp" to be "n" lines higher (negative for less high).
6460  * Also resize the frames it is contained in.
6461  */
6462     static void
6463 frame_add_height(frame_T *frp, int n)
6464 {
6465     frame_new_height(frp, frp->fr_height + n, FALSE, FALSE);
6466     for (;;)
6467     {
6468 	frp = frp->fr_parent;
6469 	if (frp == NULL)
6470 	    break;
6471 	frp->fr_height += n;
6472     }
6473 }
6474 
6475 /*
6476  * Add or remove a status line for the bottom window(s), according to the
6477  * value of 'laststatus'.
6478  */
6479     void
6480 last_status(
6481     int		morewin)	// pretend there are two or more windows
6482 {
6483     // Don't make a difference between horizontal or vertical split.
6484     last_status_rec(topframe, (p_ls == 2
6485 			  || (p_ls == 1 && (morewin || !ONE_WINDOW))));
6486 }
6487 
6488     static void
6489 last_status_rec(frame_T *fr, int statusline)
6490 {
6491     frame_T	*fp;
6492     win_T	*wp;
6493 
6494     if (fr->fr_layout == FR_LEAF)
6495     {
6496 	wp = fr->fr_win;
6497 	if (wp->w_status_height != 0 && !statusline)
6498 	{
6499 	    // remove status line
6500 	    win_new_height(wp, wp->w_height + 1);
6501 	    wp->w_status_height = 0;
6502 	    comp_col();
6503 	}
6504 	else if (wp->w_status_height == 0 && statusline)
6505 	{
6506 	    // Find a frame to take a line from.
6507 	    fp = fr;
6508 	    while (fp->fr_height <= frame_minheight(fp, NULL))
6509 	    {
6510 		if (fp == topframe)
6511 		{
6512 		    emsg(_(e_not_enough_room));
6513 		    return;
6514 		}
6515 		// In a column of frames: go to frame above.  If already at
6516 		// the top or in a row of frames: go to parent.
6517 		if (fp->fr_parent->fr_layout == FR_COL && fp->fr_prev != NULL)
6518 		    fp = fp->fr_prev;
6519 		else
6520 		    fp = fp->fr_parent;
6521 	    }
6522 	    wp->w_status_height = 1;
6523 	    if (fp != fr)
6524 	    {
6525 		frame_new_height(fp, fp->fr_height - 1, FALSE, FALSE);
6526 		frame_fix_height(wp);
6527 		(void)win_comp_pos();
6528 	    }
6529 	    else
6530 		win_new_height(wp, wp->w_height - 1);
6531 	    comp_col();
6532 	    redraw_all_later(SOME_VALID);
6533 	}
6534     }
6535     else if (fr->fr_layout == FR_ROW)
6536     {
6537 	// vertically split windows, set status line for each one
6538 	FOR_ALL_FRAMES(fp, fr->fr_child)
6539 	    last_status_rec(fp, statusline);
6540     }
6541     else
6542     {
6543 	// horizontally split window, set status line for last one
6544 	for (fp = fr->fr_child; fp->fr_next != NULL; fp = fp->fr_next)
6545 	    ;
6546 	last_status_rec(fp, statusline);
6547     }
6548 }
6549 
6550 /*
6551  * Return the number of lines used by the tab page line.
6552  */
6553     int
6554 tabline_height(void)
6555 {
6556 #ifdef FEAT_GUI_TABLINE
6557     // When the GUI has the tabline then this always returns zero.
6558     if (gui_use_tabline())
6559 	return 0;
6560 #endif
6561     switch (p_stal)
6562     {
6563 	case 0: return 0;
6564 	case 1: return (first_tabpage->tp_next == NULL) ? 0 : 1;
6565     }
6566     return 1;
6567 }
6568 
6569 /*
6570  * Return the minimal number of rows that is needed on the screen to display
6571  * the current number of windows.
6572  */
6573     int
6574 min_rows(void)
6575 {
6576     int		total;
6577     tabpage_T	*tp;
6578     int		n;
6579 
6580     if (firstwin == NULL)	// not initialized yet
6581 	return MIN_LINES;
6582 
6583     total = 0;
6584     FOR_ALL_TABPAGES(tp)
6585     {
6586 	n = frame_minheight(tp->tp_topframe, NULL);
6587 	if (total < n)
6588 	    total = n;
6589     }
6590     total += tabline_height();
6591     total += 1;		// count the room for the command line
6592     return total;
6593 }
6594 
6595 /*
6596  * Return TRUE if there is only one window and only one tab page, not
6597  * counting a help or preview window, unless it is the current window.
6598  * Does not count unlisted windows.
6599  */
6600     int
6601 only_one_window(void)
6602 {
6603     int		count = 0;
6604     win_T	*wp;
6605 
6606 #if defined(FEAT_PROP_POPUP)
6607     // If the current window is a popup then there always is another window.
6608     if (popup_is_popup(curwin))
6609 	return FALSE;
6610 #endif
6611 
6612     // If there is another tab page there always is another window.
6613     if (first_tabpage->tp_next != NULL)
6614 	return FALSE;
6615 
6616     FOR_ALL_WINDOWS(wp)
6617 	if (wp->w_buffer != NULL
6618 		&& (!((bt_help(wp->w_buffer) && !bt_help(curbuf))
6619 # ifdef FEAT_QUICKFIX
6620 		    || wp->w_p_pvw
6621 # endif
6622 	     ) || wp == curwin) && wp != aucmd_win)
6623 	    ++count;
6624     return (count <= 1);
6625 }
6626 
6627 /*
6628  * Correct the cursor line number in other windows.  Used after changing the
6629  * current buffer, and before applying autocommands.
6630  * When "do_curwin" is TRUE, also check current window.
6631  */
6632     void
6633 check_lnums(int do_curwin)
6634 {
6635     win_T	*wp;
6636     tabpage_T	*tp;
6637 
6638     FOR_ALL_TAB_WINDOWS(tp, wp)
6639 	if ((do_curwin || wp != curwin) && wp->w_buffer == curbuf)
6640 	{
6641 	    // save the original cursor position and topline
6642 	    wp->w_save_cursor.w_cursor_save = wp->w_cursor;
6643 	    wp->w_save_cursor.w_topline_save = wp->w_topline;
6644 
6645 	    if (wp->w_cursor.lnum > curbuf->b_ml.ml_line_count)
6646 		wp->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6647 	    if (wp->w_topline > curbuf->b_ml.ml_line_count)
6648 		wp->w_topline = curbuf->b_ml.ml_line_count;
6649 
6650 	    // save the corrected cursor position and topline
6651 	    wp->w_save_cursor.w_cursor_corr = wp->w_cursor;
6652 	    wp->w_save_cursor.w_topline_corr = wp->w_topline;
6653 	}
6654 }
6655 
6656 /*
6657  * Reset cursor and topline to its stored values from check_lnums().
6658  * check_lnums() must have been called first!
6659  */
6660     void
6661 reset_lnums()
6662 {
6663     win_T	*wp;
6664     tabpage_T	*tp;
6665 
6666     FOR_ALL_TAB_WINDOWS(tp, wp)
6667 	if (wp->w_buffer == curbuf)
6668 	{
6669 	    // Restore the value if the autocommand didn't change it.
6670 	    if (EQUAL_POS(wp->w_save_cursor.w_cursor_corr, wp->w_cursor))
6671 		wp->w_cursor = wp->w_save_cursor.w_cursor_save;
6672 	    if (wp->w_save_cursor.w_topline_corr == wp->w_topline)
6673 		wp->w_topline = wp->w_save_cursor.w_topline_save;
6674 	}
6675 }
6676 
6677 /*
6678  * A snapshot of the window sizes, to restore them after closing the help
6679  * window.
6680  * Only these fields are used:
6681  * fr_layout
6682  * fr_width
6683  * fr_height
6684  * fr_next
6685  * fr_child
6686  * fr_win (only valid for the old curwin, NULL otherwise)
6687  */
6688 
6689 /*
6690  * Create a snapshot of the current frame sizes.
6691  */
6692     void
6693 make_snapshot(int idx)
6694 {
6695     clear_snapshot(curtab, idx);
6696     make_snapshot_rec(topframe, &curtab->tp_snapshot[idx]);
6697 }
6698 
6699     static void
6700 make_snapshot_rec(frame_T *fr, frame_T **frp)
6701 {
6702     *frp = ALLOC_CLEAR_ONE(frame_T);
6703     if (*frp == NULL)
6704 	return;
6705     (*frp)->fr_layout = fr->fr_layout;
6706     (*frp)->fr_width = fr->fr_width;
6707     (*frp)->fr_height = fr->fr_height;
6708     if (fr->fr_next != NULL)
6709 	make_snapshot_rec(fr->fr_next, &((*frp)->fr_next));
6710     if (fr->fr_child != NULL)
6711 	make_snapshot_rec(fr->fr_child, &((*frp)->fr_child));
6712     if (fr->fr_layout == FR_LEAF && fr->fr_win == curwin)
6713 	(*frp)->fr_win = curwin;
6714 }
6715 
6716 /*
6717  * Remove any existing snapshot.
6718  */
6719     static void
6720 clear_snapshot(tabpage_T *tp, int idx)
6721 {
6722     clear_snapshot_rec(tp->tp_snapshot[idx]);
6723     tp->tp_snapshot[idx] = NULL;
6724 }
6725 
6726     static void
6727 clear_snapshot_rec(frame_T *fr)
6728 {
6729     if (fr != NULL)
6730     {
6731 	clear_snapshot_rec(fr->fr_next);
6732 	clear_snapshot_rec(fr->fr_child);
6733 	vim_free(fr);
6734     }
6735 }
6736 
6737 /*
6738  * Restore a previously created snapshot, if there is any.
6739  * This is only done if the screen size didn't change and the window layout is
6740  * still the same.
6741  */
6742     void
6743 restore_snapshot(
6744     int		idx,
6745     int		close_curwin)	    // closing current window
6746 {
6747     win_T	*wp;
6748 
6749     if (curtab->tp_snapshot[idx] != NULL
6750 	    && curtab->tp_snapshot[idx]->fr_width == topframe->fr_width
6751 	    && curtab->tp_snapshot[idx]->fr_height == topframe->fr_height
6752 	    && check_snapshot_rec(curtab->tp_snapshot[idx], topframe) == OK)
6753     {
6754 	wp = restore_snapshot_rec(curtab->tp_snapshot[idx], topframe);
6755 	win_comp_pos();
6756 	if (wp != NULL && close_curwin)
6757 	    win_goto(wp);
6758 	redraw_all_later(NOT_VALID);
6759     }
6760     clear_snapshot(curtab, idx);
6761 }
6762 
6763 /*
6764  * Check if frames "sn" and "fr" have the same layout, same following frames
6765  * and same children.  And the window pointer is valid.
6766  */
6767     static int
6768 check_snapshot_rec(frame_T *sn, frame_T *fr)
6769 {
6770     if (sn->fr_layout != fr->fr_layout
6771 	    || (sn->fr_next == NULL) != (fr->fr_next == NULL)
6772 	    || (sn->fr_child == NULL) != (fr->fr_child == NULL)
6773 	    || (sn->fr_next != NULL
6774 		&& check_snapshot_rec(sn->fr_next, fr->fr_next) == FAIL)
6775 	    || (sn->fr_child != NULL
6776 		&& check_snapshot_rec(sn->fr_child, fr->fr_child) == FAIL)
6777 	    || (sn->fr_win != NULL && !win_valid(sn->fr_win)))
6778 	return FAIL;
6779     return OK;
6780 }
6781 
6782 /*
6783  * Copy the size of snapshot frame "sn" to frame "fr".  Do the same for all
6784  * following frames and children.
6785  * Returns a pointer to the old current window, or NULL.
6786  */
6787     static win_T *
6788 restore_snapshot_rec(frame_T *sn, frame_T *fr)
6789 {
6790     win_T	*wp = NULL;
6791     win_T	*wp2;
6792 
6793     fr->fr_height = sn->fr_height;
6794     fr->fr_width = sn->fr_width;
6795     if (fr->fr_layout == FR_LEAF)
6796     {
6797 	frame_new_height(fr, fr->fr_height, FALSE, FALSE);
6798 	frame_new_width(fr, fr->fr_width, FALSE, FALSE);
6799 	wp = sn->fr_win;
6800     }
6801     if (sn->fr_next != NULL)
6802     {
6803 	wp2 = restore_snapshot_rec(sn->fr_next, fr->fr_next);
6804 	if (wp2 != NULL)
6805 	    wp = wp2;
6806     }
6807     if (sn->fr_child != NULL)
6808     {
6809 	wp2 = restore_snapshot_rec(sn->fr_child, fr->fr_child);
6810 	if (wp2 != NULL)
6811 	    wp = wp2;
6812     }
6813     return wp;
6814 }
6815 
6816 #if defined(FEAT_GUI) || defined(PROTO)
6817 /*
6818  * Return TRUE if there is any vertically split window.
6819  */
6820     int
6821 win_hasvertsplit(void)
6822 {
6823     frame_T	*fr;
6824 
6825     if (topframe->fr_layout == FR_ROW)
6826 	return TRUE;
6827 
6828     if (topframe->fr_layout == FR_COL)
6829 	FOR_ALL_FRAMES(fr, topframe->fr_child)
6830 	    if (fr->fr_layout == FR_ROW)
6831 		return TRUE;
6832 
6833     return FALSE;
6834 }
6835 #endif
6836 
6837 #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO)
6838     int
6839 get_win_number(win_T *wp, win_T *first_win)
6840 {
6841     int		i = 1;
6842     win_T	*w;
6843 
6844     for (w = first_win; w != NULL && w != wp; w = W_NEXT(w))
6845 	++i;
6846 
6847     if (w == NULL)
6848 	return 0;
6849     else
6850 	return i;
6851 }
6852 
6853     int
6854 get_tab_number(tabpage_T *tp UNUSED)
6855 {
6856     int		i = 1;
6857     tabpage_T	*t;
6858 
6859     for (t = first_tabpage; t != NULL && t != tp; t = t->tp_next)
6860 	++i;
6861 
6862     if (t == NULL)
6863 	return 0;
6864     else
6865 	return i;
6866 }
6867 #endif
6868 
6869 /*
6870  * Return TRUE if "topfrp" and its children are at the right height.
6871  */
6872     static int
6873 frame_check_height(frame_T *topfrp, int height)
6874 {
6875     frame_T *frp;
6876 
6877     if (topfrp->fr_height != height)
6878 	return FALSE;
6879 
6880     if (topfrp->fr_layout == FR_ROW)
6881 	FOR_ALL_FRAMES(frp, topfrp->fr_child)
6882 	    if (frp->fr_height != height)
6883 		return FALSE;
6884 
6885     return TRUE;
6886 }
6887 
6888 /*
6889  * Return TRUE if "topfrp" and its children are at the right width.
6890  */
6891     static int
6892 frame_check_width(frame_T *topfrp, int width)
6893 {
6894     frame_T *frp;
6895 
6896     if (topfrp->fr_width != width)
6897 	return FALSE;
6898 
6899     if (topfrp->fr_layout == FR_COL)
6900 	FOR_ALL_FRAMES(frp, topfrp->fr_child)
6901 	    if (frp->fr_width != width)
6902 		return FALSE;
6903 
6904     return TRUE;
6905 }
6906 
6907 #if defined(FEAT_SYN_HL) || defined(PROTO)
6908 /*
6909  * Simple int comparison function for use with qsort()
6910  */
6911     static int
6912 int_cmp(const void *a, const void *b)
6913 {
6914     return *(const int *)a - *(const int *)b;
6915 }
6916 
6917 /*
6918  * Handle setting 'colorcolumn' or 'textwidth' in window "wp".
6919  * Returns error message, NULL if it's OK.
6920  */
6921     char *
6922 check_colorcolumn(win_T *wp)
6923 {
6924     char_u	*s;
6925     int		col;
6926     int		count = 0;
6927     int		color_cols[256];
6928     int		i;
6929     int		j = 0;
6930 
6931     if (wp->w_buffer == NULL)
6932 	return NULL;  // buffer was closed
6933 
6934     for (s = wp->w_p_cc; *s != NUL && count < 255;)
6935     {
6936 	if (*s == '-' || *s == '+')
6937 	{
6938 	    // -N and +N: add to 'textwidth'
6939 	    col = (*s == '-') ? -1 : 1;
6940 	    ++s;
6941 	    if (!VIM_ISDIGIT(*s))
6942 		return e_invarg;
6943 	    col = col * getdigits(&s);
6944 	    if (wp->w_buffer->b_p_tw == 0)
6945 		goto skip;  // 'textwidth' not set, skip this item
6946 	    col += wp->w_buffer->b_p_tw;
6947 	    if (col < 0)
6948 		goto skip;
6949 	}
6950 	else if (VIM_ISDIGIT(*s))
6951 	    col = getdigits(&s);
6952 	else
6953 	    return e_invarg;
6954 	color_cols[count++] = col - 1;  // 1-based to 0-based
6955 skip:
6956 	if (*s == NUL)
6957 	    break;
6958 	if (*s != ',')
6959 	    return e_invarg;
6960 	if (*++s == NUL)
6961 	    return e_invarg;  // illegal trailing comma as in "set cc=80,"
6962     }
6963 
6964     vim_free(wp->w_p_cc_cols);
6965     if (count == 0)
6966 	wp->w_p_cc_cols = NULL;
6967     else
6968     {
6969 	wp->w_p_cc_cols = ALLOC_MULT(int, count + 1);
6970 	if (wp->w_p_cc_cols != NULL)
6971 	{
6972 	    // sort the columns for faster usage on screen redraw inside
6973 	    // win_line()
6974 	    qsort(color_cols, count, sizeof(int), int_cmp);
6975 
6976 	    for (i = 0; i < count; ++i)
6977 		// skip duplicates
6978 		if (j == 0 || wp->w_p_cc_cols[j - 1] != color_cols[i])
6979 		    wp->w_p_cc_cols[j++] = color_cols[i];
6980 	    wp->w_p_cc_cols[j] = -1;  // end marker
6981 	}
6982     }
6983 
6984     return NULL;  // no error
6985 }
6986 #endif
6987