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