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