xref: /vim-8.2.3635/src/window.c (revision cd67059c)
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     if (trigger_new_autocmds)
4645 	apply_autocmds(EVENT_WINNEW, NULL, NULL, FALSE, curbuf);
4646     if (trigger_enter_autocmds)
4647     {
4648 	apply_autocmds(EVENT_WINENTER, NULL, NULL, FALSE, curbuf);
4649 	if (other_buffer)
4650 	    apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
4651     }
4652 
4653 #ifdef FEAT_TITLE
4654     maketitle();
4655 #endif
4656     curwin->w_redr_status = TRUE;
4657     redraw_tabline = TRUE;
4658     if (restart_edit)
4659 	redraw_later(VALID);	/* causes status line redraw */
4660 
4661     /* set window height to desired minimal value */
4662     if (curwin->w_height < p_wh && !curwin->w_p_wfh
4663 #ifdef FEAT_TEXT_PROP
4664 	    && !popup_is_popup(curwin)
4665 #endif
4666 	    )
4667 	win_setheight((int)p_wh);
4668     else if (curwin->w_height == 0)
4669 	win_setheight(1);
4670 
4671     /* set window width to desired minimal value */
4672     if (curwin->w_width < p_wiw && !curwin->w_p_wfw)
4673 	win_setwidth((int)p_wiw);
4674 
4675 #ifdef FEAT_MOUSE
4676     setmouse();			/* in case jumped to/from help buffer */
4677 #endif
4678 
4679     /* Change directories when the 'acd' option is set. */
4680     DO_AUTOCHDIR;
4681 }
4682 
4683 
4684 /*
4685  * Jump to the first open window that contains buffer "buf", if one exists.
4686  * Returns a pointer to the window found, otherwise NULL.
4687  */
4688     win_T *
4689 buf_jump_open_win(buf_T *buf)
4690 {
4691     win_T	*wp = NULL;
4692 
4693     if (curwin->w_buffer == buf)
4694 	wp = curwin;
4695     else
4696 	FOR_ALL_WINDOWS(wp)
4697 	    if (wp->w_buffer == buf)
4698 		break;
4699     if (wp != NULL)
4700 	win_enter(wp, FALSE);
4701     return wp;
4702 }
4703 
4704 /*
4705  * Jump to the first open window in any tab page that contains buffer "buf",
4706  * if one exists.
4707  * Returns a pointer to the window found, otherwise NULL.
4708  */
4709     win_T *
4710 buf_jump_open_tab(buf_T *buf)
4711 {
4712     win_T	*wp = buf_jump_open_win(buf);
4713     tabpage_T	*tp;
4714 
4715     if (wp != NULL)
4716 	return wp;
4717 
4718     FOR_ALL_TABPAGES(tp)
4719 	if (tp != curtab)
4720 	{
4721 	    for (wp = tp->tp_firstwin; wp != NULL; wp = wp->w_next)
4722 		if (wp->w_buffer == buf)
4723 		    break;
4724 	    if (wp != NULL)
4725 	    {
4726 		goto_tabpage_win(tp, wp);
4727 		if (curwin != wp)
4728 		    wp = NULL;	/* something went wrong */
4729 		break;
4730 	    }
4731 	}
4732     return wp;
4733 }
4734 
4735 static int last_win_id = LOWEST_WIN_ID - 1;
4736 
4737 /*
4738  * Allocate a window structure and link it in the window list when "hidden" is
4739  * FALSE.
4740  */
4741     static win_T *
4742 win_alloc(win_T *after UNUSED, int hidden UNUSED)
4743 {
4744     win_T	*new_wp;
4745 
4746     /*
4747      * allocate window structure and linesizes arrays
4748      */
4749     new_wp = ALLOC_CLEAR_ONE(win_T);
4750     if (new_wp == NULL)
4751 	return NULL;
4752 
4753     if (win_alloc_lines(new_wp) == FAIL)
4754     {
4755 	vim_free(new_wp);
4756 	return NULL;
4757     }
4758 
4759     new_wp->w_id = ++last_win_id;
4760 
4761 #ifdef FEAT_EVAL
4762     /* init w: variables */
4763     new_wp->w_vars = dict_alloc();
4764     if (new_wp->w_vars == NULL)
4765     {
4766 	win_free_lsize(new_wp);
4767 	vim_free(new_wp);
4768 	return NULL;
4769     }
4770     init_var_dict(new_wp->w_vars, &new_wp->w_winvar, VAR_SCOPE);
4771 #endif
4772 
4773     /* Don't execute autocommands while the window is not properly
4774      * initialized yet.  gui_create_scrollbar() may trigger a FocusGained
4775      * event. */
4776     block_autocmds();
4777 
4778     /*
4779      * link the window in the window list
4780      */
4781     if (!hidden)
4782 	win_append(after, new_wp);
4783     new_wp->w_wincol = 0;
4784     new_wp->w_width = Columns;
4785 
4786     /* position the display and the cursor at the top of the file. */
4787     new_wp->w_topline = 1;
4788 #ifdef FEAT_DIFF
4789     new_wp->w_topfill = 0;
4790 #endif
4791     new_wp->w_botline = 2;
4792     new_wp->w_cursor.lnum = 1;
4793     new_wp->w_scbind_pos = 1;
4794 
4795     // use global option value for global-local options
4796     new_wp->w_p_so = -1;
4797     new_wp->w_p_siso = -1;
4798 
4799     /* We won't calculate w_fraction until resizing the window */
4800     new_wp->w_fraction = 0;
4801     new_wp->w_prev_fraction_row = -1;
4802 
4803 #ifdef FEAT_GUI
4804     if (gui.in_use)
4805     {
4806 	gui_create_scrollbar(&new_wp->w_scrollbars[SBAR_LEFT],
4807 		SBAR_LEFT, new_wp);
4808 	gui_create_scrollbar(&new_wp->w_scrollbars[SBAR_RIGHT],
4809 		SBAR_RIGHT, new_wp);
4810     }
4811 #endif
4812 #ifdef FEAT_FOLDING
4813     foldInitWin(new_wp);
4814 #endif
4815     unblock_autocmds();
4816 #ifdef FEAT_SEARCH_EXTRA
4817     new_wp->w_match_head = NULL;
4818     new_wp->w_next_match_id = 4;
4819 #endif
4820     return new_wp;
4821 }
4822 
4823 /*
4824  * Remove window 'wp' from the window list and free the structure.
4825  */
4826     static void
4827 win_free(
4828     win_T	*wp,
4829     tabpage_T	*tp)		/* tab page "win" is in, NULL for current */
4830 {
4831     int		i;
4832     buf_T	*buf;
4833     wininfo_T	*wip;
4834 
4835 #ifdef FEAT_FOLDING
4836     clearFolding(wp);
4837 #endif
4838 
4839     /* reduce the reference count to the argument list. */
4840     alist_unlink(wp->w_alist);
4841 
4842     /* Don't execute autocommands while the window is halfway being deleted.
4843      * gui_mch_destroy_scrollbar() may trigger a FocusGained event. */
4844     block_autocmds();
4845 
4846 #ifdef FEAT_LUA
4847     lua_window_free(wp);
4848 #endif
4849 
4850 #ifdef FEAT_MZSCHEME
4851     mzscheme_window_free(wp);
4852 #endif
4853 
4854 #ifdef FEAT_PERL
4855     perl_win_free(wp);
4856 #endif
4857 
4858 #ifdef FEAT_PYTHON
4859     python_window_free(wp);
4860 #endif
4861 
4862 #ifdef FEAT_PYTHON3
4863     python3_window_free(wp);
4864 #endif
4865 
4866 #ifdef FEAT_TCL
4867     tcl_window_free(wp);
4868 #endif
4869 
4870 #ifdef FEAT_RUBY
4871     ruby_window_free(wp);
4872 #endif
4873 
4874     clear_winopt(&wp->w_onebuf_opt);
4875     clear_winopt(&wp->w_allbuf_opt);
4876 
4877 #ifdef FEAT_EVAL
4878     vars_clear(&wp->w_vars->dv_hashtab);	/* free all w: variables */
4879     hash_init(&wp->w_vars->dv_hashtab);
4880     unref_var_dict(wp->w_vars);
4881 #endif
4882 
4883     {
4884 	tabpage_T	*ttp;
4885 
4886 	if (prevwin == wp)
4887 	    prevwin = NULL;
4888 	FOR_ALL_TABPAGES(ttp)
4889 	    if (ttp->tp_prevwin == wp)
4890 		ttp->tp_prevwin = NULL;
4891     }
4892     win_free_lsize(wp);
4893 
4894     for (i = 0; i < wp->w_tagstacklen; ++i)
4895     {
4896 	vim_free(wp->w_tagstack[i].tagname);
4897 	vim_free(wp->w_tagstack[i].user_data);
4898     }
4899     vim_free(wp->w_localdir);
4900 
4901     /* Remove the window from the b_wininfo lists, it may happen that the
4902      * freed memory is re-used for another window. */
4903     FOR_ALL_BUFFERS(buf)
4904 	for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next)
4905 	    if (wip->wi_win == wp)
4906 		wip->wi_win = NULL;
4907 
4908 #ifdef FEAT_SEARCH_EXTRA
4909     clear_matches(wp);
4910 #endif
4911 
4912 #ifdef FEAT_JUMPLIST
4913     free_jumplist(wp);
4914 #endif
4915 
4916 #ifdef FEAT_QUICKFIX
4917     qf_free_all(wp);
4918 #endif
4919 
4920 #ifdef FEAT_GUI
4921     if (gui.in_use)
4922     {
4923 	gui_mch_destroy_scrollbar(&wp->w_scrollbars[SBAR_LEFT]);
4924 	gui_mch_destroy_scrollbar(&wp->w_scrollbars[SBAR_RIGHT]);
4925     }
4926 #endif /* FEAT_GUI */
4927 
4928 #ifdef FEAT_MENU
4929     remove_winbar(wp);
4930 #endif
4931 #ifdef FEAT_TEXT_PROP
4932     free_callback(&wp->w_close_cb);
4933     free_callback(&wp->w_filter_cb);
4934     for (i = 0; i < 4; ++i)
4935 	VIM_CLEAR(wp->w_border_highlight[i]);
4936     vim_free(wp->w_scrollbar_highlight);
4937     vim_free(wp->w_thumb_highlight);
4938     vim_free(wp->w_popup_title);
4939     list_unref(wp->w_popup_mask);
4940     vim_free(wp->w_popup_mask_cells);
4941 #endif
4942 
4943 #ifdef FEAT_SYN_HL
4944     vim_free(wp->w_p_cc_cols);
4945 #endif
4946 
4947     if (win_valid_any_tab(wp))
4948 	win_remove(wp, tp);
4949     if (autocmd_busy)
4950     {
4951 	wp->w_next = au_pending_free_win;
4952 	au_pending_free_win = wp;
4953     }
4954     else
4955 	vim_free(wp);
4956 
4957     unblock_autocmds();
4958 }
4959 
4960 /*
4961  * Return TRUE if "wp" is not in the list of windows: the autocmd window or a
4962  * popup window.
4963  */
4964     static int
4965 win_unlisted(win_T *wp)
4966 {
4967     return wp == aucmd_win || WIN_IS_POPUP(wp);
4968 }
4969 
4970 #if defined(FEAT_TEXT_PROP) || defined(PROTO)
4971 /*
4972  * Free a popup window.  This does not take the window out of the window list
4973  * and assumes there is only one toplevel frame, no split.
4974  */
4975     void
4976 win_free_popup(win_T *win)
4977 {
4978     if (bt_popup(win->w_buffer))
4979 	win_close_buffer(win, DOBUF_WIPE_REUSE, FALSE);
4980     else
4981 	close_buffer(win, win->w_buffer, 0, FALSE);
4982 # if defined(FEAT_TIMERS)
4983     if (win->w_popup_timer != NULL)
4984 	stop_timer(win->w_popup_timer);
4985 # endif
4986     vim_free(win->w_frame);
4987     win_free(win, NULL);
4988 }
4989 #endif
4990 
4991 /*
4992  * Append window "wp" in the window list after window "after".
4993  */
4994     static void
4995 win_append(win_T *after, win_T *wp)
4996 {
4997     win_T	*before;
4998 
4999     if (after == NULL)	    /* after NULL is in front of the first */
5000 	before = firstwin;
5001     else
5002 	before = after->w_next;
5003 
5004     wp->w_next = before;
5005     wp->w_prev = after;
5006     if (after == NULL)
5007 	firstwin = wp;
5008     else
5009 	after->w_next = wp;
5010     if (before == NULL)
5011 	lastwin = wp;
5012     else
5013 	before->w_prev = wp;
5014 }
5015 
5016 /*
5017  * Remove a window from the window list.
5018  */
5019     void
5020 win_remove(
5021     win_T	*wp,
5022     tabpage_T	*tp)		/* tab page "win" is in, NULL for current */
5023 {
5024     if (wp->w_prev != NULL)
5025 	wp->w_prev->w_next = wp->w_next;
5026     else if (tp == NULL)
5027 	firstwin = curtab->tp_firstwin = wp->w_next;
5028     else
5029 	tp->tp_firstwin = wp->w_next;
5030 
5031     if (wp->w_next != NULL)
5032 	wp->w_next->w_prev = wp->w_prev;
5033     else if (tp == NULL)
5034 	lastwin = curtab->tp_lastwin = wp->w_prev;
5035     else
5036 	tp->tp_lastwin = wp->w_prev;
5037 }
5038 
5039 /*
5040  * Append frame "frp" in a frame list after frame "after".
5041  */
5042     static void
5043 frame_append(frame_T *after, frame_T *frp)
5044 {
5045     frp->fr_next = after->fr_next;
5046     after->fr_next = frp;
5047     if (frp->fr_next != NULL)
5048 	frp->fr_next->fr_prev = frp;
5049     frp->fr_prev = after;
5050 }
5051 
5052 /*
5053  * Insert frame "frp" in a frame list before frame "before".
5054  */
5055     static void
5056 frame_insert(frame_T *before, frame_T *frp)
5057 {
5058     frp->fr_next = before;
5059     frp->fr_prev = before->fr_prev;
5060     before->fr_prev = frp;
5061     if (frp->fr_prev != NULL)
5062 	frp->fr_prev->fr_next = frp;
5063     else
5064 	frp->fr_parent->fr_child = frp;
5065 }
5066 
5067 /*
5068  * Remove a frame from a frame list.
5069  */
5070     static void
5071 frame_remove(frame_T *frp)
5072 {
5073     if (frp->fr_prev != NULL)
5074 	frp->fr_prev->fr_next = frp->fr_next;
5075     else
5076     {
5077 	frp->fr_parent->fr_child = frp->fr_next;
5078 	/* special case: topframe->fr_child == frp */
5079 	if (topframe->fr_child == frp)
5080 	    topframe->fr_child = frp->fr_next;
5081     }
5082     if (frp->fr_next != NULL)
5083 	frp->fr_next->fr_prev = frp->fr_prev;
5084 }
5085 
5086 /*
5087  * Allocate w_lines[] for window "wp".
5088  * Return FAIL for failure, OK for success.
5089  */
5090     int
5091 win_alloc_lines(win_T *wp)
5092 {
5093     wp->w_lines_valid = 0;
5094     wp->w_lines = ALLOC_CLEAR_MULT(wline_T, Rows );
5095     if (wp->w_lines == NULL)
5096 	return FAIL;
5097     return OK;
5098 }
5099 
5100 /*
5101  * free lsize arrays for a window
5102  */
5103     void
5104 win_free_lsize(win_T *wp)
5105 {
5106     /* TODO: why would wp be NULL here? */
5107     if (wp != NULL)
5108 	VIM_CLEAR(wp->w_lines);
5109 }
5110 
5111 /*
5112  * Called from win_new_shellsize() after Rows changed.
5113  * This only does the current tab page, others must be done when made active.
5114  */
5115     void
5116 shell_new_rows(void)
5117 {
5118     int		h = (int)ROWS_AVAIL;
5119 
5120     if (firstwin == NULL)	/* not initialized yet */
5121 	return;
5122     if (h < frame_minheight(topframe, NULL))
5123 	h = frame_minheight(topframe, NULL);
5124 
5125     /* First try setting the heights of windows with 'winfixheight'.  If
5126      * that doesn't result in the right height, forget about that option. */
5127     frame_new_height(topframe, h, FALSE, TRUE);
5128     if (!frame_check_height(topframe, h))
5129 	frame_new_height(topframe, h, FALSE, FALSE);
5130 
5131     (void)win_comp_pos();		/* recompute w_winrow and w_wincol */
5132     compute_cmdrow();
5133     curtab->tp_ch_used = p_ch;
5134 
5135 #if 0
5136     /* Disabled: don't want making the screen smaller make a window larger. */
5137     if (p_ea)
5138 	win_equal(curwin, FALSE, 'v');
5139 #endif
5140 }
5141 
5142 /*
5143  * Called from win_new_shellsize() after Columns changed.
5144  */
5145     void
5146 shell_new_columns(void)
5147 {
5148     if (firstwin == NULL)	/* not initialized yet */
5149 	return;
5150 
5151     /* First try setting the widths of windows with 'winfixwidth'.  If that
5152      * doesn't result in the right width, forget about that option. */
5153     frame_new_width(topframe, (int)Columns, FALSE, TRUE);
5154     if (!frame_check_width(topframe, Columns))
5155 	frame_new_width(topframe, (int)Columns, FALSE, FALSE);
5156 
5157     (void)win_comp_pos();		/* recompute w_winrow and w_wincol */
5158 #if 0
5159     /* Disabled: don't want making the screen smaller make a window larger. */
5160     if (p_ea)
5161 	win_equal(curwin, FALSE, 'h');
5162 #endif
5163 }
5164 
5165 #if defined(FEAT_CMDWIN) || defined(PROTO)
5166 /*
5167  * Save the size of all windows in "gap".
5168  */
5169     void
5170 win_size_save(garray_T *gap)
5171 
5172 {
5173     win_T	*wp;
5174 
5175     ga_init2(gap, (int)sizeof(int), 1);
5176     if (ga_grow(gap, win_count() * 2) == OK)
5177 	FOR_ALL_WINDOWS(wp)
5178 	{
5179 	    ((int *)gap->ga_data)[gap->ga_len++] =
5180 					       wp->w_width + wp->w_vsep_width;
5181 	    ((int *)gap->ga_data)[gap->ga_len++] = wp->w_height;
5182 	}
5183 }
5184 
5185 /*
5186  * Restore window sizes, but only if the number of windows is still the same.
5187  * Does not free the growarray.
5188  */
5189     void
5190 win_size_restore(garray_T *gap)
5191 {
5192     win_T	*wp;
5193     int		i, j;
5194 
5195     if (win_count() * 2 == gap->ga_len)
5196     {
5197 	/* The order matters, because frames contain other frames, but it's
5198 	 * difficult to get right. The easy way out is to do it twice. */
5199 	for (j = 0; j < 2; ++j)
5200 	{
5201 	    i = 0;
5202 	    FOR_ALL_WINDOWS(wp)
5203 	    {
5204 		frame_setwidth(wp->w_frame, ((int *)gap->ga_data)[i++]);
5205 		win_setheight_win(((int *)gap->ga_data)[i++], wp);
5206 	    }
5207 	}
5208 	/* recompute the window positions */
5209 	(void)win_comp_pos();
5210     }
5211 }
5212 #endif /* FEAT_CMDWIN */
5213 
5214 /*
5215  * Update the position for all windows, using the width and height of the
5216  * frames.
5217  * Returns the row just after the last window.
5218  */
5219     int
5220 win_comp_pos(void)
5221 {
5222     int		row = tabline_height();
5223     int		col = 0;
5224 
5225     frame_comp_pos(topframe, &row, &col);
5226     return row;
5227 }
5228 
5229 /*
5230  * Update the position of the windows in frame "topfrp", using the width and
5231  * height of the frames.
5232  * "*row" and "*col" are the top-left position of the frame.  They are updated
5233  * to the bottom-right position plus one.
5234  */
5235     static void
5236 frame_comp_pos(frame_T *topfrp, int *row, int *col)
5237 {
5238     win_T	*wp;
5239     frame_T	*frp;
5240     int		startcol;
5241     int		startrow;
5242     int		h;
5243 
5244     wp = topfrp->fr_win;
5245     if (wp != NULL)
5246     {
5247 	if (wp->w_winrow != *row || wp->w_wincol != *col)
5248 	{
5249 	    /* position changed, redraw */
5250 	    wp->w_winrow = *row;
5251 	    wp->w_wincol = *col;
5252 	    redraw_win_later(wp, NOT_VALID);
5253 	    wp->w_redr_status = TRUE;
5254 	}
5255 	/* WinBar will not show if the window height is zero */
5256 	h = VISIBLE_HEIGHT(wp) + wp->w_status_height;
5257 	*row += h > topfrp->fr_height ? topfrp->fr_height : h;
5258 	*col += wp->w_width + wp->w_vsep_width;
5259     }
5260     else
5261     {
5262 	startrow = *row;
5263 	startcol = *col;
5264 	FOR_ALL_FRAMES(frp, topfrp->fr_child)
5265 	{
5266 	    if (topfrp->fr_layout == FR_ROW)
5267 		*row = startrow;	/* all frames are at the same row */
5268 	    else
5269 		*col = startcol;	/* all frames are at the same col */
5270 	    frame_comp_pos(frp, row, col);
5271 	}
5272     }
5273 }
5274 
5275 /*
5276  * Set current window height and take care of repositioning other windows to
5277  * fit around it.
5278  */
5279     void
5280 win_setheight(int height)
5281 {
5282     win_setheight_win(height, curwin);
5283 }
5284 
5285 /*
5286  * Set the window height of window "win" and take care of repositioning other
5287  * windows to fit around it.
5288  */
5289     void
5290 win_setheight_win(int height, win_T *win)
5291 {
5292     int		row;
5293 
5294     if (win == curwin)
5295     {
5296 	/* Always keep current window at least one line high, even when
5297 	 * 'winminheight' is zero. */
5298 	if (height < p_wmh)
5299 	    height = p_wmh;
5300 	if (height == 0)
5301 	    height = 1;
5302 	height += WINBAR_HEIGHT(curwin);
5303     }
5304 
5305     frame_setheight(win->w_frame, height + win->w_status_height);
5306 
5307     /* recompute the window positions */
5308     row = win_comp_pos();
5309 
5310     /*
5311      * If there is extra space created between the last window and the command
5312      * line, clear it.
5313      */
5314     if (full_screen && msg_scrolled == 0 && row < cmdline_row)
5315 	screen_fill(row, cmdline_row, 0, (int)Columns, ' ', ' ', 0);
5316     cmdline_row = row;
5317     msg_row = row;
5318     msg_col = 0;
5319 
5320     redraw_all_later(NOT_VALID);
5321 }
5322 
5323 /*
5324  * Set the height of a frame to "height" and take care that all frames and
5325  * windows inside it are resized.  Also resize frames on the left and right if
5326  * the are in the same FR_ROW frame.
5327  *
5328  * Strategy:
5329  * If the frame is part of a FR_COL frame, try fitting the frame in that
5330  * frame.  If that doesn't work (the FR_COL frame is too small), recursively
5331  * go to containing frames to resize them and make room.
5332  * If the frame is part of a FR_ROW frame, all frames must be resized as well.
5333  * Check for the minimal height of the FR_ROW frame.
5334  * At the top level we can also use change the command line height.
5335  */
5336     static void
5337 frame_setheight(frame_T *curfrp, int height)
5338 {
5339     int		room;		/* total number of lines available */
5340     int		take;		/* number of lines taken from other windows */
5341     int		room_cmdline;	/* lines available from cmdline */
5342     int		run;
5343     frame_T	*frp;
5344     int		h;
5345     int		room_reserved;
5346 
5347     /* If the height already is the desired value, nothing to do. */
5348     if (curfrp->fr_height == height)
5349 	return;
5350 
5351     if (curfrp->fr_parent == NULL)
5352     {
5353 	/* topframe: can only change the command line */
5354 	if (height > ROWS_AVAIL)
5355 	    height = ROWS_AVAIL;
5356 	if (height > 0)
5357 	    frame_new_height(curfrp, height, FALSE, FALSE);
5358     }
5359     else if (curfrp->fr_parent->fr_layout == FR_ROW)
5360     {
5361 	/* Row of frames: Also need to resize frames left and right of this
5362 	 * one.  First check for the minimal height of these. */
5363 	h = frame_minheight(curfrp->fr_parent, NULL);
5364 	if (height < h)
5365 	    height = h;
5366 	frame_setheight(curfrp->fr_parent, height);
5367     }
5368     else
5369     {
5370 	/*
5371 	 * Column of frames: try to change only frames in this column.
5372 	 */
5373 	/*
5374 	 * Do this twice:
5375 	 * 1: compute room available, if it's not enough try resizing the
5376 	 *    containing frame.
5377 	 * 2: compute the room available and adjust the height to it.
5378 	 * Try not to reduce the height of a window with 'winfixheight' set.
5379 	 */
5380 	for (run = 1; run <= 2; ++run)
5381 	{
5382 	    room = 0;
5383 	    room_reserved = 0;
5384 	    FOR_ALL_FRAMES(frp, curfrp->fr_parent->fr_child)
5385 	    {
5386 		if (frp != curfrp
5387 			&& frp->fr_win != NULL
5388 			&& frp->fr_win->w_p_wfh)
5389 		    room_reserved += frp->fr_height;
5390 		room += frp->fr_height;
5391 		if (frp != curfrp)
5392 		    room -= frame_minheight(frp, NULL);
5393 	    }
5394 	    if (curfrp->fr_width != Columns)
5395 		room_cmdline = 0;
5396 	    else
5397 	    {
5398 		room_cmdline = Rows - p_ch - (lastwin->w_winrow
5399 						+ VISIBLE_HEIGHT(lastwin)
5400 						+ lastwin->w_status_height);
5401 		if (room_cmdline < 0)
5402 		    room_cmdline = 0;
5403 	    }
5404 
5405 	    if (height <= room + room_cmdline)
5406 		break;
5407 	    if (run == 2 || curfrp->fr_width == Columns)
5408 	    {
5409 		if (height > room + room_cmdline)
5410 		    height = room + room_cmdline;
5411 		break;
5412 	    }
5413 	    frame_setheight(curfrp->fr_parent, height
5414 		+ frame_minheight(curfrp->fr_parent, NOWIN) - (int)p_wmh - 1);
5415 	}
5416 
5417 	/*
5418 	 * Compute the number of lines we will take from others frames (can be
5419 	 * negative!).
5420 	 */
5421 	take = height - curfrp->fr_height;
5422 
5423 	/* If there is not enough room, also reduce the height of a window
5424 	 * with 'winfixheight' set. */
5425 	if (height > room + room_cmdline - room_reserved)
5426 	    room_reserved = room + room_cmdline - height;
5427 	/* If there is only a 'winfixheight' window and making the
5428 	 * window smaller, need to make the other window taller. */
5429 	if (take < 0 && room - curfrp->fr_height < room_reserved)
5430 	    room_reserved = 0;
5431 
5432 	if (take > 0 && room_cmdline > 0)
5433 	{
5434 	    /* use lines from cmdline first */
5435 	    if (take < room_cmdline)
5436 		room_cmdline = take;
5437 	    take -= room_cmdline;
5438 	    topframe->fr_height += room_cmdline;
5439 	}
5440 
5441 	/*
5442 	 * set the current frame to the new height
5443 	 */
5444 	frame_new_height(curfrp, height, FALSE, FALSE);
5445 
5446 	/*
5447 	 * First take lines from the frames after the current frame.  If
5448 	 * that is not enough, takes lines from frames above the current
5449 	 * frame.
5450 	 */
5451 	for (run = 0; run < 2; ++run)
5452 	{
5453 	    if (run == 0)
5454 		frp = curfrp->fr_next;	/* 1st run: start with next window */
5455 	    else
5456 		frp = curfrp->fr_prev;	/* 2nd run: start with prev window */
5457 	    while (frp != NULL && take != 0)
5458 	    {
5459 		h = frame_minheight(frp, NULL);
5460 		if (room_reserved > 0
5461 			&& frp->fr_win != NULL
5462 			&& frp->fr_win->w_p_wfh)
5463 		{
5464 		    if (room_reserved >= frp->fr_height)
5465 			room_reserved -= frp->fr_height;
5466 		    else
5467 		    {
5468 			if (frp->fr_height - room_reserved > take)
5469 			    room_reserved = frp->fr_height - take;
5470 			take -= frp->fr_height - room_reserved;
5471 			frame_new_height(frp, room_reserved, FALSE, FALSE);
5472 			room_reserved = 0;
5473 		    }
5474 		}
5475 		else
5476 		{
5477 		    if (frp->fr_height - take < h)
5478 		    {
5479 			take -= frp->fr_height - h;
5480 			frame_new_height(frp, h, FALSE, FALSE);
5481 		    }
5482 		    else
5483 		    {
5484 			frame_new_height(frp, frp->fr_height - take,
5485 								FALSE, FALSE);
5486 			take = 0;
5487 		    }
5488 		}
5489 		if (run == 0)
5490 		    frp = frp->fr_next;
5491 		else
5492 		    frp = frp->fr_prev;
5493 	    }
5494 	}
5495     }
5496 }
5497 
5498 /*
5499  * Set current window width and take care of repositioning other windows to
5500  * fit around it.
5501  */
5502     void
5503 win_setwidth(int width)
5504 {
5505     win_setwidth_win(width, curwin);
5506 }
5507 
5508     void
5509 win_setwidth_win(int width, win_T *wp)
5510 {
5511     /* Always keep current window at least one column wide, even when
5512      * 'winminwidth' is zero. */
5513     if (wp == curwin)
5514     {
5515 	if (width < p_wmw)
5516 	    width = p_wmw;
5517 	if (width == 0)
5518 	    width = 1;
5519     }
5520 
5521     frame_setwidth(wp->w_frame, width + wp->w_vsep_width);
5522 
5523     /* recompute the window positions */
5524     (void)win_comp_pos();
5525 
5526     redraw_all_later(NOT_VALID);
5527 }
5528 
5529 /*
5530  * Set the width of a frame to "width" and take care that all frames and
5531  * windows inside it are resized.  Also resize frames above and below if the
5532  * are in the same FR_ROW frame.
5533  *
5534  * Strategy is similar to frame_setheight().
5535  */
5536     static void
5537 frame_setwidth(frame_T *curfrp, int width)
5538 {
5539     int		room;		/* total number of lines available */
5540     int		take;		/* number of lines taken from other windows */
5541     int		run;
5542     frame_T	*frp;
5543     int		w;
5544     int		room_reserved;
5545 
5546     /* If the width already is the desired value, nothing to do. */
5547     if (curfrp->fr_width == width)
5548 	return;
5549 
5550     if (curfrp->fr_parent == NULL)
5551 	/* topframe: can't change width */
5552 	return;
5553 
5554     if (curfrp->fr_parent->fr_layout == FR_COL)
5555     {
5556 	/* Column of frames: Also need to resize frames above and below of
5557 	 * this one.  First check for the minimal width of these. */
5558 	w = frame_minwidth(curfrp->fr_parent, NULL);
5559 	if (width < w)
5560 	    width = w;
5561 	frame_setwidth(curfrp->fr_parent, width);
5562     }
5563     else
5564     {
5565 	/*
5566 	 * Row of frames: try to change only frames in this row.
5567 	 *
5568 	 * Do this twice:
5569 	 * 1: compute room available, if it's not enough try resizing the
5570 	 *    containing frame.
5571 	 * 2: compute the room available and adjust the width to it.
5572 	 */
5573 	for (run = 1; run <= 2; ++run)
5574 	{
5575 	    room = 0;
5576 	    room_reserved = 0;
5577 	    FOR_ALL_FRAMES(frp, curfrp->fr_parent->fr_child)
5578 	    {
5579 		if (frp != curfrp
5580 			&& frp->fr_win != NULL
5581 			&& frp->fr_win->w_p_wfw)
5582 		    room_reserved += frp->fr_width;
5583 		room += frp->fr_width;
5584 		if (frp != curfrp)
5585 		    room -= frame_minwidth(frp, NULL);
5586 	    }
5587 
5588 	    if (width <= room)
5589 		break;
5590 	    if (run == 2 || curfrp->fr_height >= ROWS_AVAIL)
5591 	    {
5592 		if (width > room)
5593 		    width = room;
5594 		break;
5595 	    }
5596 	    frame_setwidth(curfrp->fr_parent, width
5597 		 + frame_minwidth(curfrp->fr_parent, NOWIN) - (int)p_wmw - 1);
5598 	}
5599 
5600 	/*
5601 	 * Compute the number of lines we will take from others frames (can be
5602 	 * negative!).
5603 	 */
5604 	take = width - curfrp->fr_width;
5605 
5606 	/* If there is not enough room, also reduce the width of a window
5607 	 * with 'winfixwidth' set. */
5608 	if (width > room - room_reserved)
5609 	    room_reserved = room - width;
5610 	/* If there is only a 'winfixwidth' window and making the
5611 	 * window smaller, need to make the other window narrower. */
5612 	if (take < 0 && room - curfrp->fr_width < room_reserved)
5613 	    room_reserved = 0;
5614 
5615 	/*
5616 	 * set the current frame to the new width
5617 	 */
5618 	frame_new_width(curfrp, width, FALSE, FALSE);
5619 
5620 	/*
5621 	 * First take lines from the frames right of the current frame.  If
5622 	 * that is not enough, takes lines from frames left of the current
5623 	 * frame.
5624 	 */
5625 	for (run = 0; run < 2; ++run)
5626 	{
5627 	    if (run == 0)
5628 		frp = curfrp->fr_next;	/* 1st run: start with next window */
5629 	    else
5630 		frp = curfrp->fr_prev;	/* 2nd run: start with prev window */
5631 	    while (frp != NULL && take != 0)
5632 	    {
5633 		w = frame_minwidth(frp, NULL);
5634 		if (room_reserved > 0
5635 			&& frp->fr_win != NULL
5636 			&& frp->fr_win->w_p_wfw)
5637 		{
5638 		    if (room_reserved >= frp->fr_width)
5639 			room_reserved -= frp->fr_width;
5640 		    else
5641 		    {
5642 			if (frp->fr_width - room_reserved > take)
5643 			    room_reserved = frp->fr_width - take;
5644 			take -= frp->fr_width - room_reserved;
5645 			frame_new_width(frp, room_reserved, FALSE, FALSE);
5646 			room_reserved = 0;
5647 		    }
5648 		}
5649 		else
5650 		{
5651 		    if (frp->fr_width - take < w)
5652 		    {
5653 			take -= frp->fr_width - w;
5654 			frame_new_width(frp, w, FALSE, FALSE);
5655 		    }
5656 		    else
5657 		    {
5658 			frame_new_width(frp, frp->fr_width - take,
5659 								FALSE, FALSE);
5660 			take = 0;
5661 		    }
5662 		}
5663 		if (run == 0)
5664 		    frp = frp->fr_next;
5665 		else
5666 		    frp = frp->fr_prev;
5667 	    }
5668 	}
5669     }
5670 }
5671 
5672 /*
5673  * Check 'winminheight' for a valid value and reduce it if needed.
5674  */
5675     void
5676 win_setminheight(void)
5677 {
5678     int		room;
5679     int		needed;
5680     int		first = TRUE;
5681 
5682     // loop until there is a 'winminheight' that is possible
5683     while (p_wmh > 0)
5684     {
5685 	room = Rows - p_ch;
5686 	needed = frame_minheight(topframe, NULL);
5687 	if (room >= needed)
5688 	    break;
5689 	--p_wmh;
5690 	if (first)
5691 	{
5692 	    emsg(_(e_noroom));
5693 	    first = FALSE;
5694 	}
5695     }
5696 }
5697 
5698 /*
5699  * Check 'winminwidth' for a valid value and reduce it if needed.
5700  */
5701     void
5702 win_setminwidth(void)
5703 {
5704     int		room;
5705     int		needed;
5706     int		first = TRUE;
5707 
5708     // loop until there is a 'winminheight' that is possible
5709     while (p_wmw > 0)
5710     {
5711 	room = Columns;
5712 	needed = frame_minwidth(topframe, NULL);
5713 	if (room >= needed)
5714 	    break;
5715 	--p_wmw;
5716 	if (first)
5717 	{
5718 	    emsg(_(e_noroom));
5719 	    first = FALSE;
5720 	}
5721     }
5722 }
5723 
5724 #if defined(FEAT_MOUSE) || defined(PROTO)
5725 
5726 /*
5727  * Status line of dragwin is dragged "offset" lines down (negative is up).
5728  */
5729     void
5730 win_drag_status_line(win_T *dragwin, int offset)
5731 {
5732     frame_T	*curfr;
5733     frame_T	*fr;
5734     int		room;
5735     int		row;
5736     int		up;	/* if TRUE, drag status line up, otherwise down */
5737     int		n;
5738 
5739     fr = dragwin->w_frame;
5740     curfr = fr;
5741     if (fr != topframe)		/* more than one window */
5742     {
5743 	fr = fr->fr_parent;
5744 	/* When the parent frame is not a column of frames, its parent should
5745 	 * be. */
5746 	if (fr->fr_layout != FR_COL)
5747 	{
5748 	    curfr = fr;
5749 	    if (fr != topframe)	/* only a row of windows, may drag statusline */
5750 		fr = fr->fr_parent;
5751 	}
5752     }
5753 
5754     /* If this is the last frame in a column, may want to resize the parent
5755      * frame instead (go two up to skip a row of frames). */
5756     while (curfr != topframe && curfr->fr_next == NULL)
5757     {
5758 	if (fr != topframe)
5759 	    fr = fr->fr_parent;
5760 	curfr = fr;
5761 	if (fr != topframe)
5762 	    fr = fr->fr_parent;
5763     }
5764 
5765     if (offset < 0) /* drag up */
5766     {
5767 	up = TRUE;
5768 	offset = -offset;
5769 	/* sum up the room of the current frame and above it */
5770 	if (fr == curfr)
5771 	{
5772 	    /* only one window */
5773 	    room = fr->fr_height - frame_minheight(fr, NULL);
5774 	}
5775 	else
5776 	{
5777 	    room = 0;
5778 	    for (fr = fr->fr_child; ; fr = fr->fr_next)
5779 	    {
5780 		room += fr->fr_height - frame_minheight(fr, NULL);
5781 		if (fr == curfr)
5782 		    break;
5783 	    }
5784 	}
5785 	fr = curfr->fr_next;		/* put fr at frame that grows */
5786     }
5787     else    /* drag down */
5788     {
5789 	up = FALSE;
5790 	/*
5791 	 * Only dragging the last status line can reduce p_ch.
5792 	 */
5793 	room = Rows - cmdline_row;
5794 	if (curfr->fr_next == NULL)
5795 	    room -= 1;
5796 	else
5797 	    room -= p_ch;
5798 	if (room < 0)
5799 	    room = 0;
5800 	/* sum up the room of frames below of the current one */
5801 	FOR_ALL_FRAMES(fr, curfr->fr_next)
5802 	    room += fr->fr_height - frame_minheight(fr, NULL);
5803 	fr = curfr;			/* put fr at window that grows */
5804     }
5805 
5806     if (room < offset)		/* Not enough room */
5807 	offset = room;		/* Move as far as we can */
5808     if (offset <= 0)
5809 	return;
5810 
5811     /*
5812      * Grow frame fr by "offset" lines.
5813      * Doesn't happen when dragging the last status line up.
5814      */
5815     if (fr != NULL)
5816 	frame_new_height(fr, fr->fr_height + offset, up, FALSE);
5817 
5818     if (up)
5819 	fr = curfr;		/* current frame gets smaller */
5820     else
5821 	fr = curfr->fr_next;	/* next frame gets smaller */
5822 
5823     /*
5824      * Now make the other frames smaller.
5825      */
5826     while (fr != NULL && offset > 0)
5827     {
5828 	n = frame_minheight(fr, NULL);
5829 	if (fr->fr_height - offset <= n)
5830 	{
5831 	    offset -= fr->fr_height - n;
5832 	    frame_new_height(fr, n, !up, FALSE);
5833 	}
5834 	else
5835 	{
5836 	    frame_new_height(fr, fr->fr_height - offset, !up, FALSE);
5837 	    break;
5838 	}
5839 	if (up)
5840 	    fr = fr->fr_prev;
5841 	else
5842 	    fr = fr->fr_next;
5843     }
5844     row = win_comp_pos();
5845     screen_fill(row, cmdline_row, 0, (int)Columns, ' ', ' ', 0);
5846     cmdline_row = row;
5847     p_ch = Rows - cmdline_row;
5848     if (p_ch < 1)
5849 	p_ch = 1;
5850     curtab->tp_ch_used = p_ch;
5851     redraw_all_later(SOME_VALID);
5852     showmode();
5853 }
5854 
5855 /*
5856  * Separator line of dragwin is dragged "offset" lines right (negative is left).
5857  */
5858     void
5859 win_drag_vsep_line(win_T *dragwin, int offset)
5860 {
5861     frame_T	*curfr;
5862     frame_T	*fr;
5863     int		room;
5864     int		left;	/* if TRUE, drag separator line left, otherwise right */
5865     int		n;
5866 
5867     fr = dragwin->w_frame;
5868     if (fr == topframe)		/* only one window (cannot happen?) */
5869 	return;
5870     curfr = fr;
5871     fr = fr->fr_parent;
5872     /* When the parent frame is not a row of frames, its parent should be. */
5873     if (fr->fr_layout != FR_ROW)
5874     {
5875 	if (fr == topframe)	/* only a column of windows (cannot happen?) */
5876 	    return;
5877 	curfr = fr;
5878 	fr = fr->fr_parent;
5879     }
5880 
5881     /* If this is the last frame in a row, may want to resize a parent
5882      * frame instead. */
5883     while (curfr->fr_next == NULL)
5884     {
5885 	if (fr == topframe)
5886 	    break;
5887 	curfr = fr;
5888 	fr = fr->fr_parent;
5889 	if (fr != topframe)
5890 	{
5891 	    curfr = fr;
5892 	    fr = fr->fr_parent;
5893 	}
5894     }
5895 
5896     if (offset < 0) /* drag left */
5897     {
5898 	left = TRUE;
5899 	offset = -offset;
5900 	/* sum up the room of the current frame and left of it */
5901 	room = 0;
5902 	for (fr = fr->fr_child; ; fr = fr->fr_next)
5903 	{
5904 	    room += fr->fr_width - frame_minwidth(fr, NULL);
5905 	    if (fr == curfr)
5906 		break;
5907 	}
5908 	fr = curfr->fr_next;		/* put fr at frame that grows */
5909     }
5910     else    /* drag right */
5911     {
5912 	left = FALSE;
5913 	/* sum up the room of frames right of the current one */
5914 	room = 0;
5915 	FOR_ALL_FRAMES(fr, curfr->fr_next)
5916 	    room += fr->fr_width - frame_minwidth(fr, NULL);
5917 	fr = curfr;			/* put fr at window that grows */
5918     }
5919 
5920     if (room < offset)		/* Not enough room */
5921 	offset = room;		/* Move as far as we can */
5922     if (offset <= 0)		/* No room at all, quit. */
5923 	return;
5924     if (fr == NULL)
5925 	return;			/* Safety check, should not happen. */
5926 
5927     /* grow frame fr by offset lines */
5928     frame_new_width(fr, fr->fr_width + offset, left, FALSE);
5929 
5930     /* shrink other frames: current and at the left or at the right */
5931     if (left)
5932 	fr = curfr;		/* current frame gets smaller */
5933     else
5934 	fr = curfr->fr_next;	/* next frame gets smaller */
5935 
5936     while (fr != NULL && offset > 0)
5937     {
5938 	n = frame_minwidth(fr, NULL);
5939 	if (fr->fr_width - offset <= n)
5940 	{
5941 	    offset -= fr->fr_width - n;
5942 	    frame_new_width(fr, n, !left, FALSE);
5943 	}
5944 	else
5945 	{
5946 	    frame_new_width(fr, fr->fr_width - offset, !left, FALSE);
5947 	    break;
5948 	}
5949 	if (left)
5950 	    fr = fr->fr_prev;
5951 	else
5952 	    fr = fr->fr_next;
5953     }
5954     (void)win_comp_pos();
5955     redraw_all_later(NOT_VALID);
5956 }
5957 #endif /* FEAT_MOUSE */
5958 
5959 #define FRACTION_MULT	16384L
5960 
5961 /*
5962  * Set wp->w_fraction for the current w_wrow and w_height.
5963  * Has no effect when the window is less than two lines.
5964  */
5965     void
5966 set_fraction(win_T *wp)
5967 {
5968     if (wp->w_height > 1)
5969 	// When cursor is in the first line the percentage is computed as if
5970 	// it's halfway that line.  Thus with two lines it is 25%, with three
5971 	// lines 17%, etc.  Similarly for the last line: 75%, 83%, etc.
5972 	wp->w_fraction = ((long)wp->w_wrow * FRACTION_MULT
5973 				     + FRACTION_MULT / 2) / (long)wp->w_height;
5974 }
5975 
5976 /*
5977  * Set the height of a window.
5978  * "height" excludes any window toolbar.
5979  * This takes care of the things inside the window, not what happens to the
5980  * window position, the frame or to other windows.
5981  */
5982     void
5983 win_new_height(win_T *wp, int height)
5984 {
5985     int		prev_height = wp->w_height;
5986 
5987     /* Don't want a negative height.  Happens when splitting a tiny window.
5988      * Will equalize heights soon to fix it. */
5989     if (height < 0)
5990 	height = 0;
5991     if (wp->w_height == height)
5992 	return;	    /* nothing to do */
5993 
5994     if (wp->w_height > 0)
5995     {
5996 	if (wp == curwin)
5997 	    /* w_wrow needs to be valid. When setting 'laststatus' this may
5998 	     * call win_new_height() recursively. */
5999 	    validate_cursor();
6000 	if (wp->w_height != prev_height)
6001 	    return;  /* Recursive call already changed the size, bail out here
6002 			to avoid the following to mess things up. */
6003 	if (wp->w_wrow != wp->w_prev_fraction_row)
6004 	    set_fraction(wp);
6005     }
6006 
6007     wp->w_height = height;
6008     wp->w_skipcol = 0;
6009 
6010     /* There is no point in adjusting the scroll position when exiting.  Some
6011      * values might be invalid. */
6012     if (!exiting)
6013 	scroll_to_fraction(wp, prev_height);
6014 }
6015 
6016     void
6017 scroll_to_fraction(win_T *wp, int prev_height)
6018 {
6019     linenr_T	lnum;
6020     int		sline, line_size;
6021     int		height = wp->w_height;
6022 
6023     // Don't change w_topline in any of these cases:
6024     // - window height is 0
6025     // - 'scrollbind' is set and this isn't the current window
6026     // - window height is sufficient to display the whole buffer and first line
6027     //   is visible.
6028     if (height > 0
6029         && (!wp->w_p_scb || wp == curwin)
6030         && (height < wp->w_buffer->b_ml.ml_line_count || wp->w_topline > 1))
6031     {
6032 	/*
6033 	 * Find a value for w_topline that shows the cursor at the same
6034 	 * relative position in the window as before (more or less).
6035 	 */
6036 	lnum = wp->w_cursor.lnum;
6037 	if (lnum < 1)		/* can happen when starting up */
6038 	    lnum = 1;
6039 	wp->w_wrow = ((long)wp->w_fraction * (long)height - 1L)
6040 							       / FRACTION_MULT;
6041 	line_size = plines_win_col(wp, lnum, (long)(wp->w_cursor.col)) - 1;
6042 	sline = wp->w_wrow - line_size;
6043 
6044 	if (sline >= 0)
6045 	{
6046 	    /* Make sure the whole cursor line is visible, if possible. */
6047 	    int rows = plines_win(wp, lnum, FALSE);
6048 
6049 	    if (sline > wp->w_height - rows)
6050 	    {
6051 		sline = wp->w_height - rows;
6052 		wp->w_wrow -= rows - line_size;
6053 	    }
6054 	}
6055 
6056 	if (sline < 0)
6057 	{
6058 	    /*
6059 	     * Cursor line would go off top of screen if w_wrow was this high.
6060 	     * Make cursor line the first line in the window.  If not enough
6061 	     * room use w_skipcol;
6062 	     */
6063 	    wp->w_wrow = line_size;
6064 	    if (wp->w_wrow >= wp->w_height
6065 				       && (wp->w_width - win_col_off(wp)) > 0)
6066 	    {
6067 		wp->w_skipcol += wp->w_width - win_col_off(wp);
6068 		--wp->w_wrow;
6069 		while (wp->w_wrow >= wp->w_height)
6070 		{
6071 		    wp->w_skipcol += wp->w_width - win_col_off(wp)
6072 							   + win_col_off2(wp);
6073 		    --wp->w_wrow;
6074 		}
6075 	    }
6076 	}
6077 	else if (sline > 0)
6078 	{
6079 	    while (sline > 0 && lnum > 1)
6080 	    {
6081 #ifdef FEAT_FOLDING
6082 		hasFoldingWin(wp, lnum, &lnum, NULL, TRUE, NULL);
6083 		if (lnum == 1)
6084 		{
6085 		    /* first line in buffer is folded */
6086 		    line_size = 1;
6087 		    --sline;
6088 		    break;
6089 		}
6090 #endif
6091 		--lnum;
6092 #ifdef FEAT_DIFF
6093 		if (lnum == wp->w_topline)
6094 		    line_size = plines_win_nofill(wp, lnum, TRUE)
6095 							      + wp->w_topfill;
6096 		else
6097 #endif
6098 		    line_size = plines_win(wp, lnum, TRUE);
6099 		sline -= line_size;
6100 	    }
6101 
6102 	    if (sline < 0)
6103 	    {
6104 		/*
6105 		 * Line we want at top would go off top of screen.  Use next
6106 		 * line instead.
6107 		 */
6108 #ifdef FEAT_FOLDING
6109 		hasFoldingWin(wp, lnum, NULL, &lnum, TRUE, NULL);
6110 #endif
6111 		lnum++;
6112 		wp->w_wrow -= line_size + sline;
6113 	    }
6114 	    else if (sline > 0)
6115 	    {
6116 		// First line of file reached, use that as topline.
6117 		lnum = 1;
6118 		wp->w_wrow -= sline;
6119 	    }
6120 	}
6121 	set_topline(wp, lnum);
6122     }
6123 
6124     if (wp == curwin)
6125     {
6126 	if (get_scrolloff_value())
6127 	    update_topline();
6128 	curs_columns(FALSE);	/* validate w_wrow */
6129     }
6130     if (prev_height > 0)
6131 	wp->w_prev_fraction_row = wp->w_wrow;
6132 
6133     win_comp_scroll(wp);
6134     redraw_win_later(wp, SOME_VALID);
6135     wp->w_redr_status = TRUE;
6136     invalidate_botline_win(wp);
6137 }
6138 
6139 /*
6140  * Set the width of a window.
6141  */
6142     void
6143 win_new_width(win_T *wp, int width)
6144 {
6145     wp->w_width = width;
6146     wp->w_lines_valid = 0;
6147     changed_line_abv_curs_win(wp);
6148     invalidate_botline_win(wp);
6149     if (wp == curwin)
6150     {
6151 	update_topline();
6152 	curs_columns(TRUE);	/* validate w_wrow */
6153     }
6154     redraw_win_later(wp, NOT_VALID);
6155     wp->w_redr_status = TRUE;
6156 }
6157 
6158     void
6159 win_comp_scroll(win_T *wp)
6160 {
6161     wp->w_p_scr = ((unsigned)wp->w_height >> 1);
6162     if (wp->w_p_scr == 0)
6163 	wp->w_p_scr = 1;
6164 }
6165 
6166 /*
6167  * command_height: called whenever p_ch has been changed
6168  */
6169     void
6170 command_height(void)
6171 {
6172     int		h;
6173     frame_T	*frp;
6174     int		old_p_ch = curtab->tp_ch_used;
6175 
6176     /* Use the value of p_ch that we remembered.  This is needed for when the
6177      * GUI starts up, we can't be sure in what order things happen.  And when
6178      * p_ch was changed in another tab page. */
6179     curtab->tp_ch_used = p_ch;
6180 
6181     /* Find bottom frame with width of screen. */
6182     frp = lastwin->w_frame;
6183     while (frp->fr_width != Columns && frp->fr_parent != NULL)
6184 	frp = frp->fr_parent;
6185 
6186     /* Avoid changing the height of a window with 'winfixheight' set. */
6187     while (frp->fr_prev != NULL && frp->fr_layout == FR_LEAF
6188 						      && frp->fr_win->w_p_wfh)
6189 	frp = frp->fr_prev;
6190 
6191     if (starting != NO_SCREEN)
6192     {
6193 	cmdline_row = Rows - p_ch;
6194 
6195 	if (p_ch > old_p_ch)		    /* p_ch got bigger */
6196 	{
6197 	    while (p_ch > old_p_ch)
6198 	    {
6199 		if (frp == NULL)
6200 		{
6201 		    emsg(_(e_noroom));
6202 		    p_ch = old_p_ch;
6203 		    curtab->tp_ch_used = p_ch;
6204 		    cmdline_row = Rows - p_ch;
6205 		    break;
6206 		}
6207 		h = frp->fr_height - frame_minheight(frp, NULL);
6208 		if (h > p_ch - old_p_ch)
6209 		    h = p_ch - old_p_ch;
6210 		old_p_ch += h;
6211 		frame_add_height(frp, -h);
6212 		frp = frp->fr_prev;
6213 	    }
6214 
6215 	    /* Recompute window positions. */
6216 	    (void)win_comp_pos();
6217 
6218 	    /* clear the lines added to cmdline */
6219 	    if (full_screen)
6220 		screen_fill((int)(cmdline_row), (int)Rows, 0,
6221 						   (int)Columns, ' ', ' ', 0);
6222 	    msg_row = cmdline_row;
6223 	    redraw_cmdline = TRUE;
6224 	    return;
6225 	}
6226 
6227 	if (msg_row < cmdline_row)
6228 	    msg_row = cmdline_row;
6229 	redraw_cmdline = TRUE;
6230     }
6231     frame_add_height(frp, (int)(old_p_ch - p_ch));
6232 
6233     /* Recompute window positions. */
6234     if (frp != lastwin->w_frame)
6235 	(void)win_comp_pos();
6236 }
6237 
6238 /*
6239  * Resize frame "frp" to be "n" lines higher (negative for less high).
6240  * Also resize the frames it is contained in.
6241  */
6242     static void
6243 frame_add_height(frame_T *frp, int n)
6244 {
6245     frame_new_height(frp, frp->fr_height + n, FALSE, FALSE);
6246     for (;;)
6247     {
6248 	frp = frp->fr_parent;
6249 	if (frp == NULL)
6250 	    break;
6251 	frp->fr_height += n;
6252     }
6253 }
6254 
6255 /*
6256  * Add or remove a status line for the bottom window(s), according to the
6257  * value of 'laststatus'.
6258  */
6259     void
6260 last_status(
6261     int		morewin)	/* pretend there are two or more windows */
6262 {
6263     /* Don't make a difference between horizontal or vertical split. */
6264     last_status_rec(topframe, (p_ls == 2
6265 			  || (p_ls == 1 && (morewin || !ONE_WINDOW))));
6266 }
6267 
6268     static void
6269 last_status_rec(frame_T *fr, int statusline)
6270 {
6271     frame_T	*fp;
6272     win_T	*wp;
6273 
6274     if (fr->fr_layout == FR_LEAF)
6275     {
6276 	wp = fr->fr_win;
6277 	if (wp->w_status_height != 0 && !statusline)
6278 	{
6279 	    /* remove status line */
6280 	    win_new_height(wp, wp->w_height + 1);
6281 	    wp->w_status_height = 0;
6282 	    comp_col();
6283 	}
6284 	else if (wp->w_status_height == 0 && statusline)
6285 	{
6286 	    /* Find a frame to take a line from. */
6287 	    fp = fr;
6288 	    while (fp->fr_height <= frame_minheight(fp, NULL))
6289 	    {
6290 		if (fp == topframe)
6291 		{
6292 		    emsg(_(e_noroom));
6293 		    return;
6294 		}
6295 		/* In a column of frames: go to frame above.  If already at
6296 		 * the top or in a row of frames: go to parent. */
6297 		if (fp->fr_parent->fr_layout == FR_COL && fp->fr_prev != NULL)
6298 		    fp = fp->fr_prev;
6299 		else
6300 		    fp = fp->fr_parent;
6301 	    }
6302 	    wp->w_status_height = 1;
6303 	    if (fp != fr)
6304 	    {
6305 		frame_new_height(fp, fp->fr_height - 1, FALSE, FALSE);
6306 		frame_fix_height(wp);
6307 		(void)win_comp_pos();
6308 	    }
6309 	    else
6310 		win_new_height(wp, wp->w_height - 1);
6311 	    comp_col();
6312 	    redraw_all_later(SOME_VALID);
6313 	}
6314     }
6315     else if (fr->fr_layout == FR_ROW)
6316     {
6317 	/* vertically split windows, set status line for each one */
6318 	FOR_ALL_FRAMES(fp, fr->fr_child)
6319 	    last_status_rec(fp, statusline);
6320     }
6321     else
6322     {
6323 	/* horizontally split window, set status line for last one */
6324 	for (fp = fr->fr_child; fp->fr_next != NULL; fp = fp->fr_next)
6325 	    ;
6326 	last_status_rec(fp, statusline);
6327     }
6328 }
6329 
6330 /*
6331  * Return the number of lines used by the tab page line.
6332  */
6333     int
6334 tabline_height(void)
6335 {
6336 #ifdef FEAT_GUI_TABLINE
6337     /* When the GUI has the tabline then this always returns zero. */
6338     if (gui_use_tabline())
6339 	return 0;
6340 #endif
6341     switch (p_stal)
6342     {
6343 	case 0: return 0;
6344 	case 1: return (first_tabpage->tp_next == NULL) ? 0 : 1;
6345     }
6346     return 1;
6347 }
6348 
6349 /*
6350  * Return the minimal number of rows that is needed on the screen to display
6351  * the current number of windows.
6352  */
6353     int
6354 min_rows(void)
6355 {
6356     int		total;
6357     tabpage_T	*tp;
6358     int		n;
6359 
6360     if (firstwin == NULL)	/* not initialized yet */
6361 	return MIN_LINES;
6362 
6363     total = 0;
6364     FOR_ALL_TABPAGES(tp)
6365     {
6366 	n = frame_minheight(tp->tp_topframe, NULL);
6367 	if (total < n)
6368 	    total = n;
6369     }
6370     total += tabline_height();
6371     total += 1;		/* count the room for the command line */
6372     return total;
6373 }
6374 
6375 /*
6376  * Return TRUE if there is only one window (in the current tab page), not
6377  * counting a help or preview window, unless it is the current window.
6378  * Does not count unlisted windows.
6379  */
6380     int
6381 only_one_window(void)
6382 {
6383     int		count = 0;
6384     win_T	*wp;
6385 
6386     /* If there is another tab page there always is another window. */
6387     if (first_tabpage->tp_next != NULL)
6388 	return FALSE;
6389 
6390     FOR_ALL_WINDOWS(wp)
6391 	if (wp->w_buffer != NULL
6392 		&& (!((bt_help(wp->w_buffer) && !bt_help(curbuf))
6393 # ifdef FEAT_QUICKFIX
6394 		    || wp->w_p_pvw
6395 # endif
6396 	     ) || wp == curwin) && wp != aucmd_win)
6397 	    ++count;
6398     return (count <= 1);
6399 }
6400 
6401 /*
6402  * Correct the cursor line number in other windows.  Used after changing the
6403  * current buffer, and before applying autocommands.
6404  * When "do_curwin" is TRUE, also check current window.
6405  */
6406     void
6407 check_lnums(int do_curwin)
6408 {
6409     win_T	*wp;
6410     tabpage_T	*tp;
6411 
6412     FOR_ALL_TAB_WINDOWS(tp, wp)
6413 	if ((do_curwin || wp != curwin) && wp->w_buffer == curbuf)
6414 	{
6415 	    // save the original cursor position and topline
6416 	    wp->w_save_cursor.w_cursor_save = wp->w_cursor;
6417 	    wp->w_save_cursor.w_topline_save = wp->w_topline;
6418 
6419 	    if (wp->w_cursor.lnum > curbuf->b_ml.ml_line_count)
6420 		wp->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6421 	    if (wp->w_topline > curbuf->b_ml.ml_line_count)
6422 		wp->w_topline = curbuf->b_ml.ml_line_count;
6423 
6424 	    // save the corrected cursor position and topline
6425 	    wp->w_save_cursor.w_cursor_corr = wp->w_cursor;
6426 	    wp->w_save_cursor.w_topline_corr = wp->w_topline;
6427 	}
6428 }
6429 
6430 /*
6431  * Reset cursor and topline to its stored values from check_lnums().
6432  * check_lnums() must have been called first!
6433  */
6434     void
6435 reset_lnums()
6436 {
6437     win_T	*wp;
6438     tabpage_T	*tp;
6439 
6440     FOR_ALL_TAB_WINDOWS(tp, wp)
6441 	if (wp->w_buffer == curbuf)
6442 	{
6443 	    // Restore the value if the autocommand didn't change it.
6444 	    if (EQUAL_POS(wp->w_save_cursor.w_cursor_corr, wp->w_cursor))
6445 		wp->w_cursor = wp->w_save_cursor.w_cursor_save;
6446 	    if (wp->w_save_cursor.w_topline_corr == wp->w_topline)
6447 		wp->w_topline = wp->w_save_cursor.w_topline_save;
6448 	}
6449 }
6450 
6451 /*
6452  * A snapshot of the window sizes, to restore them after closing the help
6453  * window.
6454  * Only these fields are used:
6455  * fr_layout
6456  * fr_width
6457  * fr_height
6458  * fr_next
6459  * fr_child
6460  * fr_win (only valid for the old curwin, NULL otherwise)
6461  */
6462 
6463 /*
6464  * Create a snapshot of the current frame sizes.
6465  */
6466     void
6467 make_snapshot(int idx)
6468 {
6469     clear_snapshot(curtab, idx);
6470     make_snapshot_rec(topframe, &curtab->tp_snapshot[idx]);
6471 }
6472 
6473     static void
6474 make_snapshot_rec(frame_T *fr, frame_T **frp)
6475 {
6476     *frp = ALLOC_CLEAR_ONE(frame_T);
6477     if (*frp == NULL)
6478 	return;
6479     (*frp)->fr_layout = fr->fr_layout;
6480     (*frp)->fr_width = fr->fr_width;
6481     (*frp)->fr_height = fr->fr_height;
6482     if (fr->fr_next != NULL)
6483 	make_snapshot_rec(fr->fr_next, &((*frp)->fr_next));
6484     if (fr->fr_child != NULL)
6485 	make_snapshot_rec(fr->fr_child, &((*frp)->fr_child));
6486     if (fr->fr_layout == FR_LEAF && fr->fr_win == curwin)
6487 	(*frp)->fr_win = curwin;
6488 }
6489 
6490 /*
6491  * Remove any existing snapshot.
6492  */
6493     static void
6494 clear_snapshot(tabpage_T *tp, int idx)
6495 {
6496     clear_snapshot_rec(tp->tp_snapshot[idx]);
6497     tp->tp_snapshot[idx] = NULL;
6498 }
6499 
6500     static void
6501 clear_snapshot_rec(frame_T *fr)
6502 {
6503     if (fr != NULL)
6504     {
6505 	clear_snapshot_rec(fr->fr_next);
6506 	clear_snapshot_rec(fr->fr_child);
6507 	vim_free(fr);
6508     }
6509 }
6510 
6511 /*
6512  * Restore a previously created snapshot, if there is any.
6513  * This is only done if the screen size didn't change and the window layout is
6514  * still the same.
6515  */
6516     void
6517 restore_snapshot(
6518     int		idx,
6519     int		close_curwin)	    /* closing current window */
6520 {
6521     win_T	*wp;
6522 
6523     if (curtab->tp_snapshot[idx] != NULL
6524 	    && curtab->tp_snapshot[idx]->fr_width == topframe->fr_width
6525 	    && curtab->tp_snapshot[idx]->fr_height == topframe->fr_height
6526 	    && check_snapshot_rec(curtab->tp_snapshot[idx], topframe) == OK)
6527     {
6528 	wp = restore_snapshot_rec(curtab->tp_snapshot[idx], topframe);
6529 	win_comp_pos();
6530 	if (wp != NULL && close_curwin)
6531 	    win_goto(wp);
6532 	redraw_all_later(NOT_VALID);
6533     }
6534     clear_snapshot(curtab, idx);
6535 }
6536 
6537 /*
6538  * Check if frames "sn" and "fr" have the same layout, same following frames
6539  * and same children.  And the window pointer is valid.
6540  */
6541     static int
6542 check_snapshot_rec(frame_T *sn, frame_T *fr)
6543 {
6544     if (sn->fr_layout != fr->fr_layout
6545 	    || (sn->fr_next == NULL) != (fr->fr_next == NULL)
6546 	    || (sn->fr_child == NULL) != (fr->fr_child == NULL)
6547 	    || (sn->fr_next != NULL
6548 		&& check_snapshot_rec(sn->fr_next, fr->fr_next) == FAIL)
6549 	    || (sn->fr_child != NULL
6550 		&& check_snapshot_rec(sn->fr_child, fr->fr_child) == FAIL)
6551 	    || (sn->fr_win != NULL && !win_valid(sn->fr_win)))
6552 	return FAIL;
6553     return OK;
6554 }
6555 
6556 /*
6557  * Copy the size of snapshot frame "sn" to frame "fr".  Do the same for all
6558  * following frames and children.
6559  * Returns a pointer to the old current window, or NULL.
6560  */
6561     static win_T *
6562 restore_snapshot_rec(frame_T *sn, frame_T *fr)
6563 {
6564     win_T	*wp = NULL;
6565     win_T	*wp2;
6566 
6567     fr->fr_height = sn->fr_height;
6568     fr->fr_width = sn->fr_width;
6569     if (fr->fr_layout == FR_LEAF)
6570     {
6571 	frame_new_height(fr, fr->fr_height, FALSE, FALSE);
6572 	frame_new_width(fr, fr->fr_width, FALSE, FALSE);
6573 	wp = sn->fr_win;
6574     }
6575     if (sn->fr_next != NULL)
6576     {
6577 	wp2 = restore_snapshot_rec(sn->fr_next, fr->fr_next);
6578 	if (wp2 != NULL)
6579 	    wp = wp2;
6580     }
6581     if (sn->fr_child != NULL)
6582     {
6583 	wp2 = restore_snapshot_rec(sn->fr_child, fr->fr_child);
6584 	if (wp2 != NULL)
6585 	    wp = wp2;
6586     }
6587     return wp;
6588 }
6589 
6590 #if defined(FEAT_GUI) || defined(PROTO)
6591 /*
6592  * Return TRUE if there is any vertically split window.
6593  */
6594     int
6595 win_hasvertsplit(void)
6596 {
6597     frame_T	*fr;
6598 
6599     if (topframe->fr_layout == FR_ROW)
6600 	return TRUE;
6601 
6602     if (topframe->fr_layout == FR_COL)
6603 	FOR_ALL_FRAMES(fr, topframe->fr_child)
6604 	    if (fr->fr_layout == FR_ROW)
6605 		return TRUE;
6606 
6607     return FALSE;
6608 }
6609 #endif
6610 
6611 #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO)
6612     int
6613 get_win_number(win_T *wp, win_T *first_win)
6614 {
6615     int		i = 1;
6616     win_T	*w;
6617 
6618     for (w = first_win; w != NULL && w != wp; w = W_NEXT(w))
6619 	++i;
6620 
6621     if (w == NULL)
6622 	return 0;
6623     else
6624 	return i;
6625 }
6626 
6627     int
6628 get_tab_number(tabpage_T *tp UNUSED)
6629 {
6630     int		i = 1;
6631     tabpage_T	*t;
6632 
6633     for (t = first_tabpage; t != NULL && t != tp; t = t->tp_next)
6634 	++i;
6635 
6636     if (t == NULL)
6637 	return 0;
6638     else
6639 	return i;
6640 }
6641 #endif
6642 
6643 /*
6644  * Return TRUE if "topfrp" and its children are at the right height.
6645  */
6646     static int
6647 frame_check_height(frame_T *topfrp, int height)
6648 {
6649     frame_T *frp;
6650 
6651     if (topfrp->fr_height != height)
6652 	return FALSE;
6653 
6654     if (topfrp->fr_layout == FR_ROW)
6655 	FOR_ALL_FRAMES(frp, topfrp->fr_child)
6656 	    if (frp->fr_height != height)
6657 		return FALSE;
6658 
6659     return TRUE;
6660 }
6661 
6662 /*
6663  * Return TRUE if "topfrp" and its children are at the right width.
6664  */
6665     static int
6666 frame_check_width(frame_T *topfrp, int width)
6667 {
6668     frame_T *frp;
6669 
6670     if (topfrp->fr_width != width)
6671 	return FALSE;
6672 
6673     if (topfrp->fr_layout == FR_COL)
6674 	FOR_ALL_FRAMES(frp, topfrp->fr_child)
6675 	    if (frp->fr_width != width)
6676 		return FALSE;
6677 
6678     return TRUE;
6679 }
6680 
6681 #if defined(FEAT_SYN_HL) || defined(PROTO)
6682 /*
6683  * Simple int comparison function for use with qsort()
6684  */
6685     static int
6686 int_cmp(const void *a, const void *b)
6687 {
6688     return *(const int *)a - *(const int *)b;
6689 }
6690 
6691 /*
6692  * Handle setting 'colorcolumn' or 'textwidth' in window "wp".
6693  * Returns error message, NULL if it's OK.
6694  */
6695     char *
6696 check_colorcolumn(win_T *wp)
6697 {
6698     char_u	*s;
6699     int		col;
6700     int		count = 0;
6701     int		color_cols[256];
6702     int		i;
6703     int		j = 0;
6704 
6705     if (wp->w_buffer == NULL)
6706 	return NULL;  // buffer was closed
6707 
6708     for (s = wp->w_p_cc; *s != NUL && count < 255;)
6709     {
6710 	if (*s == '-' || *s == '+')
6711 	{
6712 	    // -N and +N: add to 'textwidth'
6713 	    col = (*s == '-') ? -1 : 1;
6714 	    ++s;
6715 	    if (!VIM_ISDIGIT(*s))
6716 		return e_invarg;
6717 	    col = col * getdigits(&s);
6718 	    if (wp->w_buffer->b_p_tw == 0)
6719 		goto skip;  // 'textwidth' not set, skip this item
6720 	    col += wp->w_buffer->b_p_tw;
6721 	    if (col < 0)
6722 		goto skip;
6723 	}
6724 	else if (VIM_ISDIGIT(*s))
6725 	    col = getdigits(&s);
6726 	else
6727 	    return e_invarg;
6728 	color_cols[count++] = col - 1;  // 1-based to 0-based
6729 skip:
6730 	if (*s == NUL)
6731 	    break;
6732 	if (*s != ',')
6733 	    return e_invarg;
6734 	if (*++s == NUL)
6735 	    return e_invarg;  // illegal trailing comma as in "set cc=80,"
6736     }
6737 
6738     vim_free(wp->w_p_cc_cols);
6739     if (count == 0)
6740 	wp->w_p_cc_cols = NULL;
6741     else
6742     {
6743 	wp->w_p_cc_cols = ALLOC_MULT(int, count + 1);
6744 	if (wp->w_p_cc_cols != NULL)
6745 	{
6746 	    // sort the columns for faster usage on screen redraw inside
6747 	    // win_line()
6748 	    qsort(color_cols, count, sizeof(int), int_cmp);
6749 
6750 	    for (i = 0; i < count; ++i)
6751 		// skip duplicates
6752 		if (j == 0 || wp->w_p_cc_cols[j - 1] != color_cols[i])
6753 		    wp->w_p_cc_cols[j++] = color_cols[i];
6754 	    wp->w_p_cc_cols[j] = -1;  // end marker
6755 	}
6756     }
6757 
6758     return NULL;  // no error
6759 }
6760 #endif
6761