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