robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
233.5 KiB7944 linesraw
1#include <assert.h>
2#include <inttypes.h>
3#include <limits.h>
4#include <stdbool.h>
5#include <stdlib.h>
6#include <string.h>
7
8#include "klib/kvec.h"
9#include "nvim/api/private/defs.h"
10#include "nvim/api/private/helpers.h"
11#include "nvim/arglist.h"
12#include "nvim/ascii_defs.h"
13#include "nvim/autocmd.h"
14#include "nvim/autocmd_defs.h"
15#include "nvim/buffer.h"
16#include "nvim/buffer_defs.h"
17#include "nvim/charset.h"
18#include "nvim/context.h"
19#include "nvim/cursor.h"
20#include "nvim/decoration.h"
21#include "nvim/diff.h"
22#include "nvim/drawscreen.h"
23#include "nvim/errors.h"
24#include "nvim/eval.h"
25#include "nvim/eval/typval.h"
26#include "nvim/eval/typval_defs.h"
27#include "nvim/eval/vars.h"
28#include "nvim/eval/window.h"
29#include "nvim/ex_cmds.h"
30#include "nvim/ex_cmds2.h"
31#include "nvim/ex_docmd.h"
32#include "nvim/ex_eval.h"
33#include "nvim/ex_getln.h"
34#include "nvim/file_search.h"
35#include "nvim/fileio.h"
36#include "nvim/fold.h"
37#include "nvim/garray.h"
38#include "nvim/gettext_defs.h"
39#include "nvim/globals.h"
40#include "nvim/grid.h"
41#include "nvim/grid_defs.h"
42#include "nvim/hashtab.h"
43#include "nvim/input.h"
44#include "nvim/insert.h"
45#include "nvim/keycodes.h"
46#include "nvim/macros_defs.h"
47#include "nvim/main.h"
48#include "nvim/map_defs.h"
49#include "nvim/mapping.h"
50#include "nvim/mark.h"
51#include "nvim/mark_defs.h"
52#include "nvim/match.h"
53#include "nvim/memory.h"
54#include "nvim/message.h"
55#include "nvim/mouse.h"
56#include "nvim/move.h"
57#include "nvim/normal.h"
58#include "nvim/option.h"
59#include "nvim/option_defs.h"
60#include "nvim/option_vars.h"
61#include "nvim/os/fs.h"
62#include "nvim/os/os_defs.h"
63#include "nvim/path.h"
64#include "nvim/plines.h"
65#include "nvim/popupmenu.h"
66#include "nvim/pos_defs.h"
67#include "nvim/quickfix.h"
68#include "nvim/search.h"
69#include "nvim/state.h"
70#include "nvim/state_defs.h"
71#include "nvim/statusline.h"
72#include "nvim/strings.h"
73#include "nvim/syntax.h"
74#include "nvim/tag.h"
75#include "nvim/terminal.h"
76#include "nvim/types_defs.h"
77#include "nvim/ui.h"
78#include "nvim/ui_compositor.h"
79#include "nvim/ui_defs.h"
80#include "nvim/undo.h"
81#include "nvim/vim_defs.h"
82#include "nvim/window.h"
83#include "nvim/winfloat.h"
84
85#include "window.c.generated.h"
86
87#define NOWIN           ((win_T *)-1)   // non-existing window
88
89#define ROWS_AVAIL (Rows - p_ch - tabline_height() - global_stl_height())
90
91/// flags for win_enter_ext()
92typedef enum {
93  WEE_UNDO_SYNC = 0x01,
94  WEE_CURWIN_INVALID = 0x02,
95  WEE_TRIGGER_NEW_AUTOCMDS = 0x04,
96  WEE_TRIGGER_ENTER_AUTOCMDS = 0x08,
97  WEE_TRIGGER_LEAVE_AUTOCMDS = 0x10,
98} wee_flags_T;
99
100static const char e_cannot_close_last_window[]
101  = N_("E444: Cannot close last window");
102static const char e_cannot_split_window_when_closing_buffer[]
103  = N_("E1159: Cannot split a window when closing the buffer");
104
105static char *m_onlyone = N_("Already only one window");
106
107/// When non-zero splitting a window is forbidden.  Used to avoid that nasty
108/// autocommands mess up the window structure.
109static int split_disallowed = 0;
110
111/// When non-zero closing a window is forbidden.  Used to avoid that nasty
112/// autocommands mess up the window structure.
113static int close_disallowed = 0;
114
115/// When non-zero changing the window frame structure is forbidden.  Used
116/// to avoid that winframe_remove() is called recursively
117static int frame_locked = 0;
118
119/// Disallow changing the window layout (split window, close window, move
120/// window).  Resizing is still allowed.
121/// Used for autocommands that temporarily use another window and need to
122/// make sure the previously selected window is still there.
123/// Must be matched with exactly one call to window_layout_unlock()!
124void window_layout_lock(void)
125{
126  split_disallowed++;
127  close_disallowed++;
128}
129
130void window_layout_unlock(void)
131{
132  split_disallowed--;
133  close_disallowed--;
134}
135
136bool frames_locked(void)
137{
138  return frame_locked;
139}
140
141/// When the window layout cannot be changed give an error and return true.
142/// "cmd" indicates the action being performed and is used to pick the relevant
143/// error message.  When closing window(s) and the command isn't easy to know,
144/// passing CMD_SIZE will also work.
145bool window_layout_locked(cmdidx_T cmd)
146{
147  Error err = ERROR_INIT;
148  const bool locked = window_layout_locked_err(cmd, &err);
149  if (ERROR_SET(&err)) {
150    emsg(_(err.msg));
151    api_clear_error(&err);
152  }
153  return locked;
154}
155
156/// Like `window_layout_locked`, but set `err` to the (untranslated) error message when locked.
157/// @see window_layout_locked
158bool window_layout_locked_err(cmdidx_T cmd, Error *err)
159{
160  if (split_disallowed > 0 || close_disallowed > 0) {
161    if (close_disallowed == 0 && cmd == CMD_tabnew) {
162      api_set_error(err, kErrorTypeException, "%s", e_cannot_split_window_when_closing_buffer);
163    } else {
164      api_set_error(err, kErrorTypeException, "%s",
165                    e_not_allowed_to_change_window_layout_in_this_autocmd);
166    }
167    return true;
168  }
169  return false;
170}
171
172// #define WIN_DEBUG
173#ifdef WIN_DEBUG
174/// Call this method to log the current window layout.
175static void log_frame_layout(frame_T *frame)
176{
177  DLOG("layout %s, wi: %d, he: %d, wwi: %d, whe: %d, id: %d",
178       frame->fr_layout == FR_LEAF ? "LEAF" : frame->fr_layout == FR_ROW ? "ROW" : "COL",
179       frame->fr_width,
180       frame->fr_height,
181       frame->fr_win == NULL ? -1 : frame->fr_win->w_width,
182       frame->fr_win == NULL ? -1 : frame->fr_win->w_height,
183       frame->fr_win == NULL ? -1 : frame->fr_win->handle);
184  if (frame->fr_child != NULL) {
185    DLOG("children");
186    log_frame_layout(frame->fr_child);
187    if (frame->fr_next != NULL) {
188      DLOG("END of children");
189    }
190  }
191  if (frame->fr_next != NULL) {
192    log_frame_layout(frame->fr_next);
193  }
194}
195#endif
196
197/// Check if the current window is allowed to move to a different buffer.
198///
199/// @return If the window has 'winfixbuf', or this function will return false.
200bool check_can_set_curbuf_disabled(void)
201{
202  if (curwin->w_p_wfb) {
203    emsg(_(e_winfixbuf_cannot_go_to_buffer));
204    return false;
205  }
206
207  return true;
208}
209
210/// Check if the current window is allowed to move to a different buffer.
211///
212/// @param forceit If true, do not error. If false and 'winfixbuf' is enabled, error.
213///
214/// @return If the window has 'winfixbuf', then forceit must be true
215///     or this function will return false.
216bool check_can_set_curbuf_forceit(int forceit)
217{
218  if (!forceit && curwin->w_p_wfb) {
219    emsg(_(e_winfixbuf_cannot_go_to_buffer));
220    return false;
221  }
222
223  return true;
224}
225
226/// @return the current window, unless in the cmdline window and "prevwin" is
227/// set, then return "prevwin".
228win_T *prevwin_curwin(void)
229  FUNC_ATTR_WARN_UNUSED_RESULT
230{
231  // In cmdwin, the alternative buffer should be used.
232  return is_in_cmdwin() && prevwin != NULL ? prevwin : curwin;
233}
234
235/// If the 'switchbuf' option contains "useopen" or "usetab", then try to jump
236/// to a window containing "buf".
237/// Returns the pointer to the window that was jumped to or NULL.
238win_T *swbuf_goto_win_with_buf(buf_T *buf)
239{
240  win_T *wp = NULL;
241
242  if (buf == NULL) {
243    return wp;
244  }
245
246  // If 'switchbuf' contains "useopen": jump to first window in the current
247  // tab page containing "buf" if one exists.
248  if (swb_flags & kOptSwbFlagUseopen) {
249    wp = buf_jump_open_win(buf);
250  }
251
252  // If 'switchbuf' contains "usetab": jump to first window in any tab page
253  // containing "buf" if one exists.
254  if (wp == NULL && (swb_flags & kOptSwbFlagUsetab)) {
255    wp = buf_jump_open_tab(buf);
256  }
257
258  return wp;
259}
260
261// 'cmdheight' value explicitly set by the user: window commands are allowed to
262// resize the topframe to values higher than this minimum, but not lower.
263static OptInt min_set_ch = 1;
264
265/// all CTRL-W window commands are handled here, called from normal_cmd().
266///
267/// @param xchar  extra char from ":wincmd gx" or NUL
268void do_window(int nchar, int Prenum, int xchar)
269{
270  int type = FIND_DEFINE;
271  char cbuf[40];
272
273  int Prenum1 = Prenum == 0 ? 1 : Prenum;
274
275  switch (nchar) {
276  // split current window in two parts, horizontally
277  case 'S':
278  case Ctrl_S:
279  case 's':
280    reset_VIsual_and_resel();  // stop Visual mode
281    // When splitting the quickfix window open a new buffer in it,
282    // don't replicate the quickfix buffer.
283    if (bt_quickfix(curbuf)) {
284      goto newwindow;
285    }
286    win_split(Prenum, 0);
287    break;
288
289  // split current window in two parts, vertically
290  case Ctrl_V:
291  case 'v':
292    reset_VIsual_and_resel();  // stop Visual mode
293    // When splitting the quickfix window open a new buffer in it,
294    // don't replicate the quickfix buffer.
295    if (bt_quickfix(curbuf)) {
296      goto newwindow;
297    }
298    win_split(Prenum, WSP_VERT);
299    break;
300
301  // split current window and edit alternate file
302  case Ctrl_HAT:
303  case '^':
304    reset_VIsual_and_resel();  // stop Visual mode
305
306    if (buflist_findnr(Prenum == 0 ? curwin->w_alt_fnum : Prenum) == NULL) {
307      if (Prenum == 0) {
308        emsg(_(e_noalt));
309      } else {
310        semsg(_(e_buffer_nr_not_found), (int64_t)Prenum);
311      }
312      break;
313    }
314
315    if (!curbuf_locked() && win_split(0, 0) == OK) {
316      buflist_getfile(Prenum == 0 ? curwin->w_alt_fnum : Prenum,
317                      0, GETF_ALT, false);
318    }
319    break;
320
321  // open new window
322  case Ctrl_N:
323  case 'n':
324    reset_VIsual_and_resel();  // stop Visual mode
325newwindow:
326    if (Prenum) {
327      // window height
328      vim_snprintf(cbuf, sizeof(cbuf) - 5, "%" PRId64, (int64_t)Prenum);
329    } else {
330      cbuf[0] = NUL;
331    }
332    if (nchar == 'v' || nchar == Ctrl_V) {
333      xstrlcat(cbuf, "v", sizeof(cbuf));
334    }
335    xstrlcat(cbuf, "new", sizeof(cbuf));
336    do_cmdline_cmd(cbuf);
337    break;
338
339  // quit current window
340  case Ctrl_Q:
341  case 'q':
342    reset_VIsual_and_resel();                   // stop Visual mode
343    cmd_with_count("quit", cbuf, sizeof(cbuf), Prenum);
344    do_cmdline_cmd(cbuf);
345    break;
346
347  // close current window
348  case Ctrl_C:
349  case 'c':
350    reset_VIsual_and_resel();                   // stop Visual mode
351    cmd_with_count("close", cbuf, sizeof(cbuf), Prenum);
352    do_cmdline_cmd(cbuf);
353    break;
354
355  // close preview window
356  case Ctrl_Z:
357  case 'z':
358    reset_VIsual_and_resel();  // stop Visual mode
359    do_cmdline_cmd("pclose");
360    break;
361
362  // cursor to preview window
363  case 'P': {
364    win_T *wp = NULL;
365    FOR_ALL_WINDOWS_IN_TAB(wp2, curtab) {
366      if (wp2->w_p_pvw) {
367        wp = wp2;
368        break;
369      }
370    }
371    if (wp == NULL) {
372      emsg(_("E441: There is no preview window"));
373    } else {
374      win_goto(wp);
375    }
376    break;
377  }
378
379  // close all but current window
380  case Ctrl_O:
381  case 'o':
382    reset_VIsual_and_resel();  // stop Visual mode
383    cmd_with_count("only", cbuf, sizeof(cbuf), Prenum);
384    do_cmdline_cmd(cbuf);
385    break;
386
387  // cursor to next window with wrap around
388  case Ctrl_W:
389  case 'w':
390  // cursor to previous window with wrap around
391  case 'W':
392    if (ONE_WINDOW && Prenum != 1) {  // just one window
393      beep_flush();
394    } else {
395      win_T *wp;
396      if (Prenum) {  // go to specified window
397        win_T *last_focusable = firstwin;
398        for (wp = firstwin; --Prenum > 0;) {
399          if (!wp->w_floating || (!wp->w_config.hide && wp->w_config.focusable)) {
400            last_focusable = wp;
401          }
402          if (wp->w_next == NULL) {
403            break;
404          }
405          wp = wp->w_next;
406        }
407        while (wp != NULL && wp->w_floating
408               && (wp->w_config.hide || !wp->w_config.focusable)) {
409          wp = wp->w_next;
410        }
411        if (wp == NULL) {  // went past the last focusable window
412          wp = last_focusable;
413        }
414      } else {
415        if (nchar == 'W') {  // go to previous window
416          wp = curwin->w_prev;
417          if (wp == NULL) {
418            wp = lastwin;  // wrap around
419          }
420          while (wp != NULL && wp->w_floating
421                 && (wp->w_config.hide || !wp->w_config.focusable)) {
422            wp = wp->w_prev;
423          }
424        } else {  // go to next window
425          wp = curwin->w_next;
426          while (wp != NULL && wp->w_floating
427                 && (wp->w_config.hide || !wp->w_config.focusable)) {
428            wp = wp->w_next;
429          }
430          if (wp == NULL) {
431            wp = firstwin;  // wrap around
432          }
433        }
434      }
435      win_goto(wp);
436    }
437    break;
438
439  // cursor to window below
440  case 'j':
441  case K_DOWN:
442  case Ctrl_J:
443    win_goto_ver(false, Prenum1);
444    break;
445
446  // cursor to window above
447  case 'k':
448  case K_UP:
449  case Ctrl_K:
450    win_goto_ver(true, Prenum1);
451    break;
452
453  // cursor to left window
454  case 'h':
455  case K_LEFT:
456  case Ctrl_H:
457  case K_BS:
458    win_goto_hor(true, Prenum1);
459    break;
460
461  // cursor to right window
462  case 'l':
463  case K_RIGHT:
464  case Ctrl_L:
465    win_goto_hor(false, Prenum1);
466    break;
467
468  // move window to new tab page
469  case 'T':
470    if (one_window(curwin, NULL)) {
471      msg(_(m_onlyone), 0);
472    } else {
473      tabpage_T *oldtab = curtab;
474
475      // First create a new tab with the window, then go back to
476      // the old tab and close the window there.
477      win_T *wp = curwin;
478      if (win_new_tabpage(Prenum, NULL, true, NULL) && valid_tabpage(oldtab)) {
479        tabpage_T *newtab = curtab;
480        goto_tabpage_tp(oldtab, true, true);
481        if (curwin == wp) {
482          win_close(curwin, false, false);
483        }
484        if (valid_tabpage(newtab)) {
485          goto_tabpage_tp(newtab, true, true);
486          apply_autocmds(EVENT_TABNEWENTERED, NULL, NULL, false, curbuf);
487        }
488      }
489    }
490    break;
491
492  // cursor to top-left window
493  case 't':
494  case Ctrl_T:
495    win_goto(firstwin);
496    break;
497
498  // cursor to bottom-right window
499  case 'b':
500  case Ctrl_B:
501    win_goto(lastwin_nofloating(NULL));
502    break;
503
504  // cursor to last accessed (previous) window
505  case 'p':
506  case Ctrl_P:
507    if (!win_valid(prevwin) || prevwin->w_config.hide || !prevwin->w_config.focusable) {
508      beep_flush();
509    } else {
510      win_goto(prevwin);
511    }
512    break;
513
514  // exchange current and next window
515  case 'x':
516  case Ctrl_X:
517    win_exchange(Prenum);
518    break;
519
520  // rotate windows downwards
521  case Ctrl_R:
522  case 'r':
523    reset_VIsual_and_resel();  // stop Visual mode
524    win_rotate(false, Prenum1);  // downwards
525    break;
526
527  // rotate windows upwards
528  case 'R':
529    reset_VIsual_and_resel();  // stop Visual mode
530    win_rotate(true, Prenum1);  // upwards
531    break;
532
533  // move window to the very top/bottom/left/right
534  case 'K':
535  case 'J':
536  case 'H':
537  case 'L':
538    if (one_window(curwin, NULL)) {
539      beep_flush();
540    } else {
541      const int dir = ((nchar == 'H' || nchar == 'L') ? WSP_VERT : 0)
542                      | ((nchar == 'H' || nchar == 'K') ? WSP_TOP : WSP_BOT);
543
544      win_splitmove(curwin, Prenum, dir);
545    }
546    break;
547
548  // make all windows the same width and/or height
549  case '=': {
550    int mod = cmdmod.cmod_split & (WSP_VERT | WSP_HOR);
551    win_equal(NULL, false, mod == WSP_VERT ? 'v' : mod == WSP_HOR ? 'h' : 'b');
552    break;
553  }
554
555  // increase current window height
556  case '+':
557    win_setheight(curwin->w_height + Prenum1);
558    break;
559
560  // decrease current window height
561  case '-':
562    win_setheight(curwin->w_height - Prenum1);
563    break;
564
565  // set current window height
566  case Ctrl__:
567  case '_':
568    win_setheight(Prenum ? Prenum : Rows - (int)min_set_ch);
569    break;
570
571  // increase current window width
572  case '>':
573    win_setwidth(curwin->w_width + Prenum1);
574    break;
575
576  // decrease current window width
577  case '<':
578    win_setwidth(curwin->w_width - Prenum1);
579    break;
580
581  // set current window width
582  case '|':
583    win_setwidth(Prenum != 0 ? Prenum : Columns);
584    break;
585
586  // jump to tag and split window if tag exists (in preview window)
587  case '}':
588    if (Prenum) {
589      g_do_tagpreview = Prenum;
590    } else {
591      g_do_tagpreview = (int)p_pvh;
592    }
593    FALLTHROUGH;
594  case ']':
595  case Ctrl_RSB:
596    // Keep visual mode, can select words to use as a tag.
597    if (Prenum) {
598      postponed_split = Prenum;
599    } else {
600      postponed_split = -1;
601    }
602
603    if (nchar != '}') {
604      g_do_tagpreview = 0;
605    }
606
607    // Execute the command right here, required when
608    // "wincmd ]" was used in a function.
609    do_nv_ident(Ctrl_RSB, NUL);
610    postponed_split = 0;
611    break;
612
613  // edit file name under cursor in a new window
614  case 'f':
615  case 'F':
616  case Ctrl_F: {
617wingotofile:
618    if (check_text_or_curbuf_locked(NULL)) {
619      break;
620    }
621
622    linenr_T lnum = -1;
623    char *ptr = grab_file_name(Prenum1, &lnum);
624    if (ptr != NULL) {
625      tabpage_T *oldtab = curtab;
626      win_T *oldwin = curwin;
627      setpcmark();
628
629      // If 'switchbuf' is set to 'useopen' or 'usetab' and the
630      // file is already opened in a window, then jump to it.
631      win_T *wp = NULL;
632      if ((swb_flags & (kOptSwbFlagUseopen | kOptSwbFlagUsetab))
633          && cmdmod.cmod_tab == 0) {
634        wp = swbuf_goto_win_with_buf(buflist_findname_exp(ptr));
635      }
636
637      if (wp == NULL && win_split(0, 0) == OK) {
638        RESET_BINDING(curwin);
639        if (do_ecmd(0, ptr, NULL, NULL, ECMD_LASTL, ECMD_HIDE, NULL) == FAIL) {
640          // Note: if do_ecmd() is aborted resulting in got_int being true, win_close()
641          // unconditionally fails. In such case, the window split for do_ecmd() is
642          // left unclosed, i.e. the current window is just duplicated. To avoid this,
643          // save and load got_int value before and after closing the window.
644          const bool old_got_int = got_int;
645          got_int = false;
646
647          // Failed to open the file, close the window opened for it.
648          win_close(curwin, false, false);
649          got_int = got_int || old_got_int;
650
651          goto_tabpage_win(oldtab, oldwin);
652        } else {
653          wp = curwin;
654        }
655      }
656
657      if (wp != NULL && nchar == 'F' && lnum >= 0) {
658        curwin->w_cursor.lnum = lnum;
659        check_cursor_lnum(curwin);
660        beginline(BL_SOL | BL_FIX);
661      }
662      xfree(ptr);
663    }
664    break;
665  }
666
667  // Go to the first occurrence of the identifier under cursor along path in a
668  // new window -- webb
669  case 'i':                         // Go to any match
670  case Ctrl_I:
671    type = FIND_ANY;
672    FALLTHROUGH;
673  case 'd':                         // Go to definition, using 'define'
674  case Ctrl_D: {
675    size_t len;
676    char *ptr;
677    if ((len = find_ident_under_cursor(&ptr, FIND_IDENT, NULL)) == 0) {
678      break;
679    }
680
681    // Make a copy, if the line was changed it will be freed.
682    ptr = xmemdupz(ptr, len);
683
684    find_pattern_in_path(ptr, 0, len, true, Prenum == 0, type,
685                         Prenum1, ACTION_SPLIT, 1, MAXLNUM, false, false);
686    xfree(ptr);
687    curwin->w_set_curswant = true;
688    break;
689  }
690
691  // Quickfix window only: view the result under the cursor in a new split.
692  case K_KENTER:
693  case CAR:
694    if (bt_quickfix(curbuf)) {
695      qf_view_result(true);
696    }
697    break;
698
699  // CTRL-W g  extended commands
700  case 'g':
701  case Ctrl_G:
702    no_mapping++;
703    allow_keys++;               // no mapping for xchar, but allow key codes
704    if (xchar == NUL) {
705      xchar = plain_vgetc();
706    }
707    LANGMAP_ADJUST(xchar, true);
708    no_mapping--;
709    allow_keys--;
710    add_to_showcmd(xchar);
711
712    switch (xchar) {
713    case '}':
714      xchar = Ctrl_RSB;
715      if (Prenum) {
716        g_do_tagpreview = Prenum;
717      } else {
718        g_do_tagpreview = (int)p_pvh;
719      }
720      FALLTHROUGH;
721    case ']':
722    case Ctrl_RSB:
723      // Keep visual mode, can select words to use as a tag.
724      if (Prenum) {
725        postponed_split = Prenum;
726      } else {
727        postponed_split = -1;
728      }
729
730      // Execute the command right here, required when
731      // "wincmd g}" was used in a function.
732      do_nv_ident('g', xchar);
733      postponed_split = 0;
734      break;
735
736    case 'f':                       // CTRL-W gf: "gf" in a new tab page
737    case 'F':                       // CTRL-W gF: "gF" in a new tab page
738      cmdmod.cmod_tab = tabpage_index(curtab) + 1;
739      nchar = xchar;
740      goto wingotofile;
741
742    case 't':                       // CTRL-W gt: go to next tab page
743      goto_tabpage(Prenum);
744      break;
745
746    case 'T':                       // CTRL-W gT: go to previous tab page
747      goto_tabpage(-Prenum1);
748      break;
749
750    case TAB:                       // CTRL-W g<Tab>: go to last used tab page
751      if (!goto_tabpage_lastused()) {
752        beep_flush();
753      }
754      break;
755
756    case 'e':
757      if (curwin->w_floating || !ui_has(kUIMultigrid)) {
758        beep_flush();
759        break;
760      }
761      WinConfig config = WIN_CONFIG_INIT;
762      config.width = curwin->w_width;
763      config.height = curwin->w_height;
764      config.external = true;
765      Error err = ERROR_INIT;
766      if (!win_new_float(curwin, false, config, &err)) {
767        emsg(err.msg);
768        api_clear_error(&err);
769        beep_flush();
770      }
771      break;
772    default:
773      beep_flush();
774      break;
775    }
776    break;
777
778  default:
779    beep_flush();
780    break;
781  }
782}
783
784static void cmd_with_count(char *cmd, char *bufp, size_t bufsize, int64_t Prenum)
785{
786  size_t len = xstrlcpy(bufp, cmd, bufsize);
787
788  if (Prenum > 0 && len < bufsize) {
789    vim_snprintf(bufp + len, bufsize - len, "%" PRId64, Prenum);
790  }
791}
792
793void win_set_buf(win_T *win, buf_T *buf, Error *err)
794  FUNC_ATTR_NONNULL_ALL
795{
796  const handle_T win_handle = win->handle;
797  tabpage_T *tab = win_find_tabpage(win);
798
799  // no redrawing and don't set the window title
800  RedrawingDisabled++;
801
802  CtxSwitch switchwin;
803  bool win_ok;
804
805  TRY_WRAP(err, {
806    win_ok = ctx_switch(&switchwin, win, tab, NULL, kCtxNoDisplay | kCtxKeepCwd);
807    if (win_ok) {
808      const int save_acd = p_acd;
809      if (!switchwin.cs_same_win) {
810        // Temporarily disable 'autochdir' when setting buffer in another window.
811        p_acd = false;
812      }
813
814      do_buffer(DOBUF_GOTO, DOBUF_FIRST, FORWARD, buf->b_fnum, 0);
815
816      if (!switchwin.cs_same_win) {
817        p_acd = save_acd;
818      }
819    }
820  });
821  if (!win_ok && !ERROR_SET(err)) {
822    api_set_error(err, kErrorTypeException, "Failed to switch to window %d", win_handle);
823  }
824
825  // If window is not current, state logic will not validate its cursor. So do it now.
826  // Still needed if do_buffer returns FAIL (e.g: autocmds abort script after buffer was set).
827  validate_cursor(curwin);
828
829  ctx_restore(&switchwin);
830  RedrawingDisabled--;
831}
832
833/// Return the number of fold columns to display
834int win_fdccol_count(win_T *wp)
835{
836  const char *fdc = wp->w_p_fdc;
837
838  // auto:<NUM>
839  if (strncmp(fdc, "auto", 4) == 0) {
840    const int fdccol = fdc[4] == ':' ? fdc[5] - '0' : 1;
841    int needed_fdccols = getDeepestNesting(wp);
842    return MIN(fdccol, needed_fdccols);
843  }
844  return fdc[0] - '0';
845}
846
847/// Merges two window configs, freeing replaced fields if necessary.
848void merge_win_config(WinConfig *dst, const WinConfig src)
849  FUNC_ATTR_NONNULL_ALL
850{
851  if (dst->title_chunks.items != src.title_chunks.items) {
852    clear_virttext(&dst->title_chunks);
853  }
854  if (dst->footer_chunks.items != src.footer_chunks.items) {
855    clear_virttext(&dst->footer_chunks);
856  }
857  *dst = src;
858}
859
860/// Clear fields in `fconfig` that are only used for floating windows.
861/// Also clears fields unused after configure time, like width/height.
862void clear_float_config(WinConfig *fconfig, bool free_fields)
863  FUNC_ATTR_NONNULL_ALL
864{
865  WinStyle saved_style = fconfig->style;
866  int saved_cmdline_offset = fconfig->_cmdline_offset;
867  if (free_fields) {
868    merge_win_config(fconfig, WIN_CONFIG_INIT);
869  } else {
870    *fconfig = WIN_CONFIG_INIT;
871  }
872  fconfig->style = saved_style;
873  fconfig->_cmdline_offset = saved_cmdline_offset;
874}
875
876void ui_ext_win_position(win_T *wp, bool validate)
877{
878  wp->w_pos_changed = false;
879  if (!wp->w_floating) {
880    if (ui_has(kUIMultigrid)) {
881      // Windows on the default grid don't necessarily have comp_col and comp_row set
882      // But the rest of the calculations relies on it
883      wp->w_grid_alloc.comp_col = wp->w_wincol;
884      wp->w_grid_alloc.comp_row = wp->w_winrow;
885    }
886    ui_call_win_pos(wp->w_grid_alloc.handle, wp->handle, wp->w_winrow,
887                    wp->w_wincol, wp->w_width, wp->w_height);
888    return;
889  }
890
891  WinConfig c = wp->w_config;
892  if (!c.external) {
893    ScreenGrid *grid = &default_grid;
894    Float row = c.row;
895    Float col = c.col;
896    if (c.relative == kFloatRelativeWindow) {
897      Error dummy = ERROR_INIT;
898      win_T *win = find_window_by_handle(c.window, &dummy);
899      api_clear_error(&dummy);
900      if (win != NULL) {
901        // When a floating window is anchored to another window,
902        // update the position of its anchored window first.
903        if (win->w_pos_changed && win->w_grid_alloc.chars != NULL && win_valid(win)) {
904          ui_ext_win_position(win, validate);
905        }
906        int row_off = 0;
907        int col_off = 0;
908        win_grid_alloc(win);
909        grid = grid_adjust(&win->w_grid, &row_off, &col_off);
910        row += row_off;
911        col += col_off;
912        if (c.bufpos.lnum >= 0) {
913          int lnum = MIN(c.bufpos.lnum + 1, win->w_buffer->b_ml.ml_line_count);
914          pos_T pos = { lnum, c.bufpos.col, 0 };
915          int trow, tcol, tcolc, tcole;
916          textpos2screenpos(win, &pos, &trow, &tcol, &tcolc, &tcole, true);
917          row += trow - 1;
918          col += tcol - 1;
919        }
920      }
921    } else if (c.relative == kFloatRelativeLaststatus) {
922      row += Rows - (int)p_ch - last_stl_height(false);
923    } else if (c.relative == kFloatRelativeTabline) {
924      row += tabline_height();
925    }
926
927    bool resort = wp->w_grid_alloc.comp_index != 0
928                  && wp->w_grid_alloc.zindex != wp->w_config.zindex;
929    bool raise = resort && wp->w_grid_alloc.zindex < wp->w_config.zindex;
930    wp->w_grid_alloc.zindex = wp->w_config.zindex;
931    if (resort) {
932      ui_comp_layers_adjust(wp->w_grid_alloc.comp_index, raise);
933    }
934    bool valid = (wp->w_redr_type == 0 || ui_has(kUIMultigrid));
935    if (!valid && !validate) {
936      wp->w_pos_changed = true;
937      return;
938    }
939
940    // TODO(bfredl): ideally, compositor should work like any multigrid UI
941    // and use standard win_pos events.
942    bool east = c.anchor & kFloatAnchorEast;
943    bool south = c.anchor & kFloatAnchorSouth;
944
945    int comp_row = (int)row - (south ? wp->w_height_outer : 0);
946    int comp_col = (int)col - (east ? wp->w_width_outer : 0);
947    int above_ch = wp->w_config.zindex < kZIndexMessages ? (int)p_ch : 0;
948    comp_row += grid->comp_row;
949    comp_col += grid->comp_col;
950    comp_row = MAX(MIN(comp_row, Rows - wp->w_height_outer - above_ch), 0);
951    if (!c.fixed || east) {
952      comp_col = MAX(MIN(comp_col, Columns - wp->w_width_outer), 0);
953    }
954    wp->w_winrow = comp_row;
955    wp->w_wincol = comp_col;
956
957    if (!c.hide) {
958      ui_comp_put_grid(&wp->w_grid_alloc, comp_row, comp_col,
959                       wp->w_height_outer, wp->w_width_outer, valid, false);
960      if (ui_has(kUIMultigrid)) {
961        String anchor = cstr_as_string(float_anchor_str[c.anchor]);
962        ui_call_win_float_pos(wp->w_grid_alloc.handle, wp->handle, anchor,
963                              grid->handle, row, col, c.mouse,
964                              wp->w_grid_alloc.zindex, (int)wp->w_grid_alloc.comp_index,
965                              wp->w_winrow,
966                              wp->w_wincol);
967      }
968      ui_check_cursor_grid(wp->w_grid_alloc.handle);
969      wp->w_grid_alloc.mouse_enabled = wp->w_config.mouse;
970      if (!valid) {
971        wp->w_grid_alloc.valid = false;
972        redraw_later(wp, UPD_NOT_VALID);
973      }
974    } else {
975      if (ui_has(kUIMultigrid)) {
976        ui_call_win_hide(wp->w_grid_alloc.handle);
977      }
978      ui_comp_remove_grid(&wp->w_grid_alloc);
979    }
980  } else {
981    ui_call_win_external_pos(wp->w_grid_alloc.handle, wp->handle);
982  }
983}
984
985void ui_ext_win_viewport(win_T *wp)
986{
987  // NOTE: The win_viewport command is delayed until the next flush when there are pending updates.
988  // This ensures that the updates and the viewport are sent together.
989  if ((wp == curwin || ui_has(kUIMultigrid)) && wp->w_viewport_invalid && wp->w_redr_type == 0) {
990    const linenr_T line_count = wp->w_buffer->b_ml.ml_line_count;
991    // Avoid ml_get errors when producing "scroll_delta".
992    const linenr_T cur_topline = MIN(wp->w_topline, line_count);
993    const linenr_T cur_botline = MIN(wp->w_botline, line_count);
994    int64_t delta = 0;
995    linenr_T last_topline = wp->w_viewport_last_topline;
996    linenr_T last_botline = wp->w_viewport_last_botline;
997    int last_topfill = wp->w_viewport_last_topfill;
998    int64_t last_skipcol = wp->w_viewport_last_skipcol;
999    if (last_topline > line_count) {
1000      delta -= last_topline - line_count;
1001      last_topline = line_count;
1002      last_topfill = 0;
1003      last_skipcol = MAXCOL;
1004    }
1005    last_botline = MIN(last_botline, line_count);
1006    if (cur_topline < last_topline
1007        || (cur_topline == last_topline && wp->w_skipcol < last_skipcol)) {
1008      int64_t vcole = last_skipcol;
1009      linenr_T lnume = last_topline;
1010      if (last_topline > 0 && cur_botline < last_topline) {
1011        // Scrolling too many lines: only give an approximate "scroll_delta".
1012        delta -= last_topline - cur_botline;
1013        lnume = cur_botline;
1014        vcole = 0;
1015      }
1016      delta -= win_text_height(wp, cur_topline, wp->w_skipcol, &lnume, &vcole, NULL, INT64_MAX);
1017    } else if (cur_topline > last_topline
1018               || (cur_topline == last_topline && wp->w_skipcol > last_skipcol)) {
1019      int64_t vcole = wp->w_skipcol;
1020      linenr_T lnume = cur_topline;
1021      if (last_botline > 0 && cur_topline > last_botline) {
1022        // Scrolling too many lines: only give an approximate "scroll_delta".
1023        delta += cur_topline - last_botline;
1024        lnume = last_botline;
1025        vcole = 0;
1026      }
1027      delta += win_text_height(wp, last_topline, last_skipcol, &lnume, &vcole, NULL, INT64_MAX);
1028    }
1029    delta += last_topfill;
1030    delta -= wp->w_topfill;
1031    linenr_T ev_botline = wp->w_botline;
1032    if (ev_botline == line_count + 1 && wp->w_empty_rows == 0) {
1033      // TODO(bfredl): The might be more cases to consider, like how does this
1034      // interact with incomplete final line? Diff filler lines?
1035      ev_botline = line_count;
1036    }
1037    ui_call_win_viewport(wp->w_grid_alloc.handle, wp->handle, wp->w_topline - 1, ev_botline,
1038                         wp->w_cursor.lnum - 1, wp->w_cursor.col, line_count, delta);
1039    wp->w_viewport_invalid = false;
1040    wp->w_viewport_last_topline = wp->w_topline;
1041    wp->w_viewport_last_botline = wp->w_botline;
1042    wp->w_viewport_last_topfill = wp->w_topfill;
1043    wp->w_viewport_last_skipcol = wp->w_skipcol;
1044  }
1045}
1046
1047/// If "split_disallowed" is set, or "wp"'s buffer is closing, give an error and return FAIL.
1048/// Otherwise return OK.
1049int check_split_disallowed(const win_T *wp)
1050  FUNC_ATTR_NONNULL_ALL
1051{
1052  Error err = ERROR_INIT;
1053  const bool ok = check_split_disallowed_err(wp, &err);
1054  if (ERROR_SET(&err)) {
1055    emsg(_(err.msg));
1056    api_clear_error(&err);
1057  }
1058  return ok ? OK : FAIL;
1059}
1060
1061/// Like `check_split_disallowed`, but set `err` to the (untranslated) error message on failure and
1062/// return false. Otherwise return true.
1063/// @see check_split_disallowed
1064bool check_split_disallowed_err(const win_T *wp, Error *err)
1065  FUNC_ATTR_NONNULL_ALL
1066{
1067  if (split_disallowed > 0) {
1068    api_set_error(err, kErrorTypeException, "E242: Can't split a window while closing another");
1069    return false;
1070  }
1071  if (wp->w_buffer->b_locked_split) {
1072    api_set_error(err, kErrorTypeException, "%s", e_cannot_split_window_when_closing_buffer);
1073    return false;
1074  }
1075  return true;
1076}
1077
1078// split the current window, implements CTRL-W s and :split
1079//
1080// "size" is the height or width for the new window, 0 to use half of current
1081// height or width.
1082//
1083// "flags":
1084// WSP_ROOM: require enough room for new window
1085// WSP_VERT: vertical split.
1086// WSP_TOP:  open window at the top-left of the screen (help window).
1087// WSP_BOT:  open window at the bottom-right of the screen (quickfix window).
1088// WSP_HELP: creating the help window, keep layout snapshot
1089// WSP_NOENTER: do not enter the new window or trigger WinNew autocommands
1090//
1091// return FAIL for failure, OK otherwise
1092int win_split(int size, int flags)
1093{
1094  if (check_split_disallowed(curwin) == FAIL) {
1095    return FAIL;
1096  }
1097
1098  // When the ":tab" modifier was used open a new tab page instead.
1099  if (may_open_tabpage() == OK) {
1100    return OK;
1101  }
1102
1103  // Add flags from ":vertical", ":topleft" and ":botright".
1104  flags |= cmdmod.cmod_split;
1105  if ((flags & WSP_TOP) && (flags & WSP_BOT)) {
1106    emsg(_("E442: Can't split topleft and botright at the same time"));
1107    return FAIL;
1108  }
1109
1110  // When creating the help window make a snapshot of the window layout.
1111  // Otherwise clear the snapshot, it's now invalid.
1112  if (flags & WSP_HELP) {
1113    make_snapshot(SNAP_HELP_IDX);
1114  } else {
1115    clear_snapshot(curtab, SNAP_HELP_IDX);
1116  }
1117
1118  if (flags & WSP_QUICKFIX) {
1119    make_snapshot(SNAP_QUICKFIX_IDX);
1120  } else {
1121    clear_snapshot(curtab, SNAP_QUICKFIX_IDX);
1122  }
1123
1124  return win_split_ins(size, flags, NULL, 0, NULL) == NULL ? FAIL : OK;
1125}
1126
1127/// When "new_wp" is NULL: split the current window in two.
1128/// When "new_wp" is not NULL: insert this window at the far
1129/// top/left/right/bottom.
1130/// When "to_flatten" is not NULL: flatten this frame before reorganising frames;
1131/// remains unflattened on failure.
1132///
1133/// On failure, if "new_wp" was not NULL, no changes will have been made to the
1134/// window layout or sizes.
1135/// @return  NULL for failure, or pointer to new window
1136win_T *win_split_ins(int size, int flags, win_T *new_wp, int dir, frame_T *to_flatten)
1137{
1138  win_T *wp = new_wp;
1139
1140  // ctx_win[] should always remain floating
1141  if (new_wp != NULL && is_ctx_win(new_wp)) {
1142    return NULL;
1143  }
1144
1145  if (new_wp == NULL) {
1146    trigger_winnewpre();
1147  }
1148
1149  win_T *oldwin;
1150  if (flags & WSP_TOP) {
1151    oldwin = firstwin;
1152  } else if (flags & WSP_BOT || curwin->w_floating) {
1153    // can't split float, use last nonfloating window instead
1154    oldwin = lastwin_nofloating(NULL);
1155  } else {
1156    oldwin = curwin;
1157  }
1158
1159  int need_status = 0;
1160  int new_size = size;
1161  bool vertical = flags & WSP_VERT;
1162  bool toplevel = flags & (WSP_TOP | WSP_BOT);
1163
1164  // add a status line when p_ls == 1 and splitting the first window
1165  if (one_window(firstwin, NULL) && p_ls == 1 && oldwin->w_status_height == 0) {
1166    if (oldwin->w_height <= p_wmh) {
1167      emsg(_(e_noroom));
1168      return NULL;
1169    }
1170    need_status = STATUS_HEIGHT;
1171    win_float_anchor_laststatus();
1172  }
1173
1174  bool do_equal = false;
1175  int oldwin_height = 0;
1176  const int layout = vertical ? FR_ROW : FR_COL;
1177  bool did_set_fraction = false;
1178
1179  if (vertical) {
1180    // Check if we are able to split the current window and compute its
1181    // width.
1182    // Current window requires at least 1 space.
1183    int wmw1 = (p_wmw == 0 ? 1 : (int)p_wmw);
1184    int needed = wmw1 + 1;
1185    if (flags & WSP_ROOM) {
1186      needed += (int)p_wiw - wmw1;
1187    }
1188    int minwidth;
1189    int available;
1190    if (toplevel) {
1191      minwidth = frame_minwidth(topframe, NOWIN);
1192      available = topframe->fr_width;
1193      needed += minwidth;
1194    } else if (p_ea) {
1195      minwidth = frame_minwidth(oldwin->w_frame, NOWIN);
1196      frame_T *prevfrp = oldwin->w_frame;
1197      for (frame_T *frp = oldwin->w_frame->fr_parent; frp != NULL;
1198           frp = frp->fr_parent) {
1199        if (frp->fr_layout == FR_ROW) {
1200          frame_T *frp2;
1201          FOR_ALL_FRAMES(frp2, frp->fr_child) {
1202            if (frp2 != prevfrp) {
1203              minwidth += frame_minwidth(frp2, NOWIN);
1204            }
1205          }
1206        }
1207        prevfrp = frp;
1208      }
1209      available = topframe->fr_width;
1210      needed += minwidth;
1211    } else {
1212      minwidth = frame_minwidth(oldwin->w_frame, NOWIN);
1213      available = oldwin->w_frame->fr_width;
1214      needed += minwidth;
1215    }
1216    if (available < needed) {
1217      emsg(_(e_noroom));
1218      return NULL;
1219    }
1220    if (new_size == 0) {
1221      new_size = oldwin->w_width / 2;
1222    }
1223    new_size = MAX(MIN(new_size, available - minwidth - 1), wmw1);
1224
1225    // if it doesn't fit in the current window, need win_equal()
1226    if (oldwin->w_width - new_size - 1 < p_wmw) {
1227      do_equal = true;
1228    }
1229
1230    // We don't like to take lines for the new window from a
1231    // 'winfixwidth' window.  Take them from a window to the left or right
1232    // instead, if possible. Add one for the separator.
1233    if (oldwin->w_p_wfw) {
1234      win_setwidth_win(oldwin->w_width + new_size + 1, oldwin, true);
1235    }
1236
1237    // Only make all windows the same width if one of them (except oldwin)
1238    // is wider than one of the split windows.
1239    if (!do_equal && p_ea && size == 0 && *p_ead != 'v'
1240        && oldwin->w_frame->fr_parent != NULL) {
1241      frame_T *frp = oldwin->w_frame->fr_parent->fr_child;
1242      while (frp != NULL) {
1243        if (frp->fr_win != oldwin && frp->fr_win != NULL
1244            && (frp->fr_win->w_width > new_size
1245                || frp->fr_win->w_width > (oldwin->w_width
1246                                           - new_size - 1))) {
1247          do_equal = true;
1248          break;
1249        }
1250        frp = frp->fr_next;
1251      }
1252    }
1253  } else {
1254    // Check if we are able to split the current window and compute its height.
1255    // Current window requires at least 1 space plus space for the window bar.
1256    int wmh1 = MAX((int)p_wmh, 1) + oldwin->w_winbar_height;
1257    int needed = wmh1 + STATUS_HEIGHT;
1258    if (flags & WSP_ROOM) {
1259      needed += (int)p_wh - wmh1 + oldwin->w_winbar_height;
1260    }
1261    if (p_ch < 1) {
1262      needed += 1;  // Adjust for cmdheight=0.
1263    }
1264    int minheight;
1265    int available;
1266    if (toplevel) {
1267      minheight = frame_minheight(topframe, NOWIN) + need_status;
1268      available = topframe->fr_height;
1269      needed += minheight;
1270    } else if (p_ea) {
1271      minheight = frame_minheight(oldwin->w_frame, NOWIN) + need_status;
1272      frame_T *prevfrp = oldwin->w_frame;
1273      for (frame_T *frp = oldwin->w_frame->fr_parent; frp != NULL; frp = frp->fr_parent) {
1274        if (frp->fr_layout == FR_COL) {
1275          frame_T *frp2;
1276          FOR_ALL_FRAMES(frp2, frp->fr_child) {
1277            if (frp2 != prevfrp) {
1278              minheight += frame_minheight(frp2, NOWIN);
1279            }
1280          }
1281        }
1282        prevfrp = frp;
1283      }
1284      available = topframe->fr_height;
1285      needed += minheight;
1286    } else {
1287      minheight = frame_minheight(oldwin->w_frame, NOWIN) + need_status;
1288      available = oldwin->w_frame->fr_height;
1289      needed += minheight;
1290    }
1291    if (available < needed) {
1292      emsg(_(e_noroom));
1293      return NULL;
1294    }
1295    oldwin_height = oldwin->w_height;
1296    if (need_status) {
1297      oldwin->w_status_height = STATUS_HEIGHT;
1298      oldwin_height -= STATUS_HEIGHT;
1299    }
1300    if (new_size == 0) {
1301      new_size = oldwin_height / 2;
1302    }
1303
1304    new_size = MAX(MIN(new_size, available - minheight - STATUS_HEIGHT), wmh1);
1305
1306    // if it doesn't fit in the current window, need win_equal()
1307    if (oldwin_height - new_size - STATUS_HEIGHT < p_wmh) {
1308      do_equal = true;
1309    }
1310
1311    // We don't like to take lines for the new window from a
1312    // 'winfixheight' window.  Take them from a window above or below
1313    // instead, if possible.
1314    if (oldwin->w_p_wfh) {
1315      // Set w_fraction now so that the cursor keeps the same relative
1316      // vertical position using the old height.
1317      set_fraction(oldwin);
1318      did_set_fraction = true;
1319
1320      win_setheight_win(oldwin->w_height + new_size + STATUS_HEIGHT,
1321                        oldwin, true);
1322      // w_height now excludes the status line
1323      oldwin_height = oldwin->w_height;
1324    }
1325
1326    // Only make all windows the same height if one of them (except oldwin)
1327    // is higher than one of the split windows.
1328    if (!do_equal && p_ea && size == 0
1329        && *p_ead != 'h'
1330        && oldwin->w_frame->fr_parent != NULL) {
1331      frame_T *frp = oldwin->w_frame->fr_parent->fr_child;
1332      while (frp != NULL) {
1333        if (frp->fr_win != oldwin && frp->fr_win != NULL
1334            && (frp->fr_win->w_height > new_size
1335                || frp->fr_win->w_height > oldwin_height - new_size - STATUS_HEIGHT)) {
1336          do_equal = true;
1337          break;
1338        }
1339        frp = frp->fr_next;
1340      }
1341    }
1342  }
1343
1344  // allocate new window structure and link it in the window list
1345  if ((flags & WSP_TOP) == 0
1346      && ((flags & WSP_BOT)
1347          || (flags & WSP_BELOW)
1348          || (!(flags & WSP_ABOVE)
1349              && (vertical ? p_spr : p_sb)))) {
1350    // new window below/right of current one
1351    if (new_wp == NULL) {
1352      wp = win_alloc(oldwin, false);
1353    } else {
1354      win_append(oldwin, wp, NULL);
1355    }
1356  } else {
1357    if (new_wp == NULL) {
1358      wp = win_alloc(oldwin->w_prev, false);
1359    } else {
1360      win_append(oldwin->w_prev, wp, NULL);
1361    }
1362  }
1363
1364  if (new_wp == NULL) {
1365    if (wp == NULL) {
1366      return NULL;
1367    }
1368
1369    new_frame(wp);
1370
1371    // make the contents of the new window the same as the current one
1372    win_init(wp, curwin, flags);
1373  } else if (wp->w_floating) {
1374    ui_comp_remove_grid(&wp->w_grid_alloc);
1375    if (ui_has(kUIMultigrid)) {
1376      wp->w_pos_changed = true;
1377    } else {
1378      // No longer a float, a non-multigrid UI shouldn't draw it as such
1379      ui_call_win_hide(wp->w_grid_alloc.handle);
1380      win_free_grid(wp, true);
1381    }
1382
1383    // External windows are independent of tabpages, and may have been the curwin of others.
1384    if (wp->w_config.external) {
1385      FOR_ALL_TABS(tp) {
1386        if (tp != curtab && tp->tp_curwin == wp) {
1387          tp->tp_curwin = tp->tp_firstwin;
1388        }
1389      }
1390    }
1391
1392    wp->w_floating = false;
1393    new_frame(wp);
1394
1395    // non-floating window doesn't store float config or have a border.
1396    clear_float_config(&wp->w_config, true);
1397    CLEAR_FIELD(wp->w_border_adj);
1398  }
1399
1400  // Going to reorganize frames now, make sure they're flat.
1401  if (to_flatten != NULL) {
1402    frame_flatten(to_flatten);
1403  }
1404
1405  bool before;
1406  frame_T *curfrp;
1407
1408  // Reorganise the tree of frames to insert the new window.
1409  if (toplevel) {
1410    if ((topframe->fr_layout == FR_COL && !vertical)
1411        || (topframe->fr_layout == FR_ROW && vertical)) {
1412      curfrp = topframe->fr_child;
1413      if (flags & WSP_BOT) {
1414        while (curfrp->fr_next != NULL) {
1415          curfrp = curfrp->fr_next;
1416        }
1417      }
1418    } else {
1419      curfrp = topframe;
1420    }
1421    before = (flags & WSP_TOP);
1422  } else {
1423    curfrp = oldwin->w_frame;
1424    if (flags & WSP_BELOW) {
1425      before = false;
1426    } else if (flags & WSP_ABOVE) {
1427      before = true;
1428    } else if (vertical) {
1429      before = !p_spr;
1430    } else {
1431      before = !p_sb;
1432    }
1433  }
1434  if (curfrp->fr_parent == NULL || curfrp->fr_parent->fr_layout != layout) {
1435    // Need to create a new frame in the tree to make a branch.
1436    frame_T *frp = xcalloc(1, sizeof(frame_T));
1437    *frp = *curfrp;
1438    curfrp->fr_layout = (char)layout;
1439    frp->fr_parent = curfrp;
1440    frp->fr_next = NULL;
1441    frp->fr_prev = NULL;
1442    curfrp->fr_child = frp;
1443    curfrp->fr_win = NULL;
1444    curfrp = frp;
1445    if (frp->fr_win != NULL) {
1446      oldwin->w_frame = frp;
1447    } else {
1448      FOR_ALL_FRAMES(frp, frp->fr_child) {
1449        frp->fr_parent = curfrp;
1450      }
1451    }
1452  }
1453
1454  frame_T *frp;
1455  if (new_wp == NULL) {
1456    frp = wp->w_frame;
1457  } else {
1458    frp = new_wp->w_frame;
1459  }
1460  frp->fr_parent = curfrp->fr_parent;
1461
1462  // Insert the new frame at the right place in the frame list.
1463  if (before) {
1464    frame_insert(curfrp, frp);
1465  } else {
1466    frame_append(curfrp, frp);
1467  }
1468
1469  // Set w_fraction now so that the cursor keeps the same relative
1470  // vertical position.
1471  if (!did_set_fraction) {
1472    set_fraction(oldwin);
1473  }
1474  wp->w_fraction = oldwin->w_fraction;
1475
1476  if (vertical) {
1477    wp->w_p_scr = curwin->w_p_scr;
1478
1479    if (need_status) {
1480      win_new_height(oldwin, oldwin->w_height - 1);
1481      oldwin->w_status_height = need_status;
1482    }
1483    if (toplevel) {
1484      // set height and row of new window to full height
1485      wp->w_winrow = tabline_height();
1486      win_new_height(wp, curfrp->fr_height - (p_ls == 1 || p_ls == 2));
1487      wp->w_status_height = (p_ls == 1 || p_ls == 2);
1488      wp->w_hsep_height = 0;
1489    } else {
1490      // height and row of new window is same as current window
1491      wp->w_winrow = oldwin->w_winrow;
1492      win_new_height(wp, oldwin->w_height);
1493      wp->w_status_height = oldwin->w_status_height;
1494      wp->w_hsep_height = oldwin->w_hsep_height;
1495    }
1496    frp->fr_height = curfrp->fr_height;
1497
1498    // "new_size" of the current window goes to the new window, use
1499    // one column for the vertical separator
1500    win_new_width(wp, new_size);
1501    if (before) {
1502      wp->w_vsep_width = 1;
1503    } else {
1504      wp->w_vsep_width = oldwin->w_vsep_width;
1505      oldwin->w_vsep_width = 1;
1506    }
1507    if (toplevel) {
1508      if (flags & WSP_BOT) {
1509        frame_set_vsep(curfrp, true);
1510      }
1511      // Set width of neighbor frame
1512      frame_new_width(curfrp, curfrp->fr_width
1513                      - (new_size + ((flags & WSP_TOP) != 0)), flags & WSP_TOP,
1514                      false);
1515    } else {
1516      win_new_width(oldwin, oldwin->w_width - (new_size + 1));
1517    }
1518    if (before) {       // new window left of current one
1519      wp->w_wincol = oldwin->w_wincol;
1520      oldwin->w_wincol += new_size + 1;
1521    } else {  // new window right of current one
1522      wp->w_wincol = oldwin->w_wincol + oldwin->w_width + 1;
1523    }
1524    frame_fix_width(oldwin);
1525    frame_fix_width(wp);
1526  } else {
1527    const bool is_stl_global = global_stl_height() > 0;
1528    // width and column of new window is same as current window
1529    if (toplevel) {
1530      wp->w_wincol = 0;
1531      win_new_width(wp, Columns);
1532      wp->w_vsep_width = 0;
1533    } else {
1534      wp->w_wincol = oldwin->w_wincol;
1535      win_new_width(wp, oldwin->w_width);
1536      wp->w_vsep_width = oldwin->w_vsep_width;
1537    }
1538    frp->fr_width = curfrp->fr_width;
1539
1540    // "new_size" of the current window goes to the new window, use
1541    // one row for the status line
1542    win_new_height(wp, new_size);
1543    const int old_status_height = oldwin->w_status_height;
1544    if (before) {
1545      wp->w_hsep_height = is_stl_global ? 1 : 0;
1546    } else {
1547      wp->w_hsep_height = oldwin->w_hsep_height;
1548      oldwin->w_hsep_height = is_stl_global ? 1 : 0;
1549    }
1550    if (toplevel) {
1551      int new_fr_height = curfrp->fr_height - new_size;
1552      if (is_stl_global) {
1553        if (flags & WSP_BOT) {
1554          frame_add_hsep(curfrp);
1555        } else {
1556          new_fr_height -= 1;
1557        }
1558      } else {
1559        if (!((flags & WSP_BOT) && p_ls == 0)) {
1560          new_fr_height -= STATUS_HEIGHT;
1561        }
1562        if (flags & WSP_BOT) {
1563          frame_add_statusline(curfrp);
1564        }
1565      }
1566      frame_new_height(curfrp, new_fr_height, flags & WSP_TOP, false, false);
1567    } else {
1568      win_new_height(oldwin, oldwin_height - (new_size + STATUS_HEIGHT));
1569    }
1570
1571    if (before) {       // new window above current one
1572      wp->w_winrow = oldwin->w_winrow;
1573      if (is_stl_global) {
1574        wp->w_status_height = 0;
1575        oldwin->w_winrow += wp->w_height + 1;
1576      } else {
1577        wp->w_status_height = STATUS_HEIGHT;
1578        oldwin->w_winrow += wp->w_height + STATUS_HEIGHT;
1579      }
1580    } else {            // new window below current one
1581      if (is_stl_global) {
1582        wp->w_winrow = oldwin->w_winrow + oldwin->w_height + 1;
1583        wp->w_status_height = 0;
1584      } else {
1585        wp->w_winrow = oldwin->w_winrow + oldwin->w_height + STATUS_HEIGHT;
1586        wp->w_status_height = old_status_height;
1587        if (!(flags & WSP_BOT)) {
1588          oldwin->w_status_height = STATUS_HEIGHT;
1589        }
1590      }
1591    }
1592    frame_fix_height(wp);
1593    frame_fix_height(oldwin);
1594  }
1595
1596  if (toplevel) {
1597    win_comp_pos();
1598  }
1599
1600  // Both windows need redrawing.  Update all status lines, in case they
1601  // show something related to the window count or position.
1602  redraw_later(wp, UPD_NOT_VALID);
1603  redraw_later(oldwin, UPD_NOT_VALID);
1604  status_redraw_all();
1605
1606  if (need_status) {
1607    msg_row = Rows - 1;
1608    msg_col = sc_col;
1609    msg_clr_eos_force();        // Old command/ruler may still be there
1610    comp_col();
1611    msg_row = Rows - 1;
1612    msg_col = 0;        // put position back at start of line
1613  }
1614
1615  // equalize the window sizes.
1616  if (do_equal || dir != 0) {
1617    win_equal(wp, true, vertical ? (dir == 'v' ? 'b' : 'h') : (dir == 'h' ? 'b' : 'v'));
1618  } else if (!is_ctx_win(wp)) {
1619    win_fix_scroll(false);
1620  }
1621
1622  int i;
1623
1624  // Don't change the window height/width to 'winheight' / 'winwidth' if a
1625  // size was given.
1626  if (flags & WSP_VERT) {
1627    i = (int)p_wiw;
1628    if (size != 0) {
1629      p_wiw = size;
1630    }
1631  } else {
1632    i = (int)p_wh;
1633    if (size != 0) {
1634      p_wh = size;
1635    }
1636  }
1637
1638  if (!(flags & WSP_NOENTER)) {
1639    // make the new window the current window
1640    win_enter_ext(wp, (new_wp == NULL ? WEE_TRIGGER_NEW_AUTOCMDS : 0) | WEE_TRIGGER_ENTER_AUTOCMDS
1641                  | WEE_TRIGGER_LEAVE_AUTOCMDS);
1642  }
1643  if (vertical) {
1644    p_wiw = i;
1645  } else {
1646    p_wh = i;
1647  }
1648
1649  if (win_valid(oldwin)) {
1650    // Send the window positions to the UI
1651    oldwin->w_pos_changed = true;
1652  }
1653
1654  return wp;
1655}
1656
1657// Initialize window "newp" from window "oldp".
1658// Used when splitting a window and when creating a new tab page.
1659// The windows will both edit the same buffer.
1660// WSP_NEWLOC may be specified in flags to prevent the location list from
1661// being copied.
1662void win_init(win_T *newp, win_T *oldp, int flags)
1663{
1664  newp->w_buffer = oldp->w_buffer;
1665  newp->w_s = &(oldp->w_buffer->b_s);
1666  oldp->w_buffer->b_nwindows++;
1667  newp->w_cursor = oldp->w_cursor;
1668  newp->w_valid = 0;
1669  newp->w_curswant = oldp->w_curswant;
1670  newp->w_set_curswant = oldp->w_set_curswant;
1671  newp->w_topline = oldp->w_topline;
1672  newp->w_topfill = oldp->w_topfill;
1673  newp->w_leftcol = oldp->w_leftcol;
1674  newp->w_pcmark = oldp->w_pcmark;
1675  newp->w_prev_pcmark = oldp->w_prev_pcmark;
1676  newp->w_alt_fnum = oldp->w_alt_fnum;
1677  newp->w_wrow = oldp->w_wrow;
1678  newp->w_fraction = oldp->w_fraction;
1679  newp->w_prev_fraction_row = oldp->w_prev_fraction_row;
1680  copy_jumplist(oldp, newp);
1681  if (flags & WSP_NEWLOC) {
1682    // Don't copy the location list.
1683    newp->w_llist = NULL;
1684    newp->w_llist_ref = NULL;
1685  } else {
1686    copy_loclist_stack(oldp, newp);
1687  }
1688  newp->w_localdir = (oldp->w_localdir == NULL)
1689                     ? NULL : xstrdup(oldp->w_localdir);
1690  newp->w_prevdir = (oldp->w_prevdir == NULL)
1691                    ? NULL : xstrdup(oldp->w_prevdir);
1692
1693  if (*p_spk != 'c') {
1694    if (*p_spk == 't') {
1695      newp->w_skipcol = oldp->w_skipcol;
1696    }
1697    newp->w_botline = oldp->w_botline;
1698    newp->w_prev_height = oldp->w_height;
1699    newp->w_prev_winrow = oldp->w_winrow;
1700  }
1701
1702  // copy tagstack and folds
1703  for (int i = 0; i < oldp->w_tagstacklen; i++) {
1704    taggy_T *tag = &newp->w_tagstack[i];
1705    *tag = oldp->w_tagstack[i];
1706    if (tag->tagname != NULL) {
1707      tag->tagname = xstrdup(tag->tagname);
1708    }
1709    if (tag->user_data != NULL) {
1710      tag->user_data = xstrdup(tag->user_data);
1711    }
1712  }
1713  newp->w_tagstackidx = oldp->w_tagstackidx;
1714  newp->w_tagstacklen = oldp->w_tagstacklen;
1715
1716  // Keep same changelist position in new window.
1717  newp->w_changelistidx = oldp->w_changelistidx;
1718
1719  copyFoldingState(oldp, newp);
1720
1721  win_init_some(newp, oldp);
1722
1723  newp->w_winbar_height = oldp->w_winbar_height;
1724}
1725
1726// Initialize window "newp" from window "old".
1727// Only the essential things are copied.
1728static void win_init_some(win_T *newp, win_T *oldp)
1729{
1730  // Use the same argument list.
1731  newp->w_alist = oldp->w_alist;
1732  newp->w_alist->al_refcount++;
1733  newp->w_arg_idx = oldp->w_arg_idx;
1734
1735  // copy options from existing window
1736  win_copy_options(oldp, newp);
1737}
1738
1739/// Check if "win" is a pointer to an existing window in the current tabpage.
1740///
1741/// @param  win  window to check
1742bool win_valid(const win_T *win) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1743{
1744  return tabpage_win_valid(curtab, win);
1745}
1746
1747/// Check if "win" is a pointer to an existing window in tabpage "tp".
1748///
1749/// @param  win  window to check
1750bool tabpage_win_valid(const tabpage_T *tp, const win_T *win)
1751  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1752{
1753  if (win == NULL) {
1754    return false;
1755  }
1756
1757  FOR_ALL_WINDOWS_IN_TAB(wp, tp) {
1758    if (wp == win) {
1759      return true;
1760    }
1761  }
1762  return false;
1763}
1764
1765// Find window "handle" in the current tab page.
1766// Return NULL if not found.
1767win_T *win_find_by_handle(handle_T handle)
1768  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1769{
1770  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
1771    if (wp->handle == handle) {
1772      return wp;
1773    }
1774  }
1775  return NULL;
1776}
1777
1778/// Check if "win" is a pointer to an existing window in any tabpage.
1779///
1780/// @param  win  window to check
1781bool win_valid_any_tab(win_T *win) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1782{
1783  if (win == NULL) {
1784    return false;
1785  }
1786
1787  FOR_ALL_TAB_WINDOWS(tp, wp) {
1788    if (wp == win) {
1789      return true;
1790    }
1791  }
1792  return false;
1793}
1794
1795// Return the number of windows.
1796int win_count(void)
1797{
1798  int count = 0;
1799
1800  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
1801    count++;
1802  }
1803  return count;
1804}
1805
1806/// Make "count" windows on the screen.
1807/// Must be called when there is just one window, filling the whole screen.
1808/// (excluding the command line).
1809///
1810/// @param vertical  split windows vertically if true.
1811///
1812/// @return actual number of windows on the screen.
1813int make_windows(int count, bool vertical)
1814{
1815  int maxcount;
1816
1817  if (vertical) {
1818    // Each window needs at least 'winminwidth' lines and a separator column.
1819    maxcount = (int)(curwin->w_width + curwin->w_vsep_width
1820                     - (p_wiw - p_wmw)) / ((int)p_wmw + 1);
1821  } else {
1822    // Each window needs at least 'winminheight' lines.
1823    // If statusline isn't global, each window also needs a statusline.
1824    // If 'winbar' is set, each window also needs a winbar.
1825    maxcount = (int)(curwin->w_height + curwin->w_hsep_height + curwin->w_status_height
1826                     - (p_wh - p_wmh)) / ((int)p_wmh + STATUS_HEIGHT + global_winbar_height());
1827  }
1828
1829  maxcount = MAX(maxcount, 2);
1830  count = MIN(count, maxcount);
1831
1832  // add status line now, otherwise first window will be too big
1833  if (count > 1) {
1834    last_status(true);
1835  }
1836
1837  // Don't execute autocommands while creating the windows.  Must do that
1838  // when putting the buffers in the windows.
1839  block_autocmds();
1840
1841  int todo;
1842
1843  // todo is number of windows left to create
1844  for (todo = count - 1; todo > 0; todo--) {
1845    if (vertical) {
1846      if (win_split(curwin->w_width - (curwin->w_width - todo)
1847                    / (todo + 1) - 1, WSP_VERT | WSP_ABOVE) == FAIL) {
1848        break;
1849      }
1850    } else {
1851      if (win_split(curwin->w_height - (curwin->w_height - todo
1852                                        * STATUS_HEIGHT) / (todo + 1)
1853                    - STATUS_HEIGHT, WSP_ABOVE) == FAIL) {
1854        break;
1855      }
1856    }
1857  }
1858
1859  unblock_autocmds();
1860
1861  // return actual number of windows
1862  return count - todo;
1863}
1864
1865// Exchange current and next window
1866static void win_exchange(int Prenum)
1867{
1868  if (curwin->w_floating) {
1869    emsg(e_floatexchange);
1870    return;
1871  }
1872
1873  if (one_window(curwin, NULL)) {
1874    // just one window
1875    beep_flush();
1876    return;
1877  }
1878  if (text_or_buf_locked()) {
1879    beep_flush();
1880    return;
1881  }
1882
1883  frame_T *frp;
1884
1885  // find window to exchange with
1886  if (Prenum) {
1887    frp = curwin->w_frame->fr_parent->fr_child;
1888    while (frp != NULL && --Prenum > 0) {
1889      frp = frp->fr_next;
1890    }
1891  } else if (curwin->w_frame->fr_next != NULL) {  // Swap with next
1892    frp = curwin->w_frame->fr_next;
1893  } else {  // Swap last window in row/col with previous
1894    frp = curwin->w_frame->fr_prev;
1895  }
1896
1897  // We can only exchange a window with another window, not with a frame
1898  // containing windows.
1899  if (frp == NULL || frp->fr_win == NULL || frp->fr_win == curwin) {
1900    return;
1901  }
1902  win_T *wp = frp->fr_win;
1903
1904  // 1. remove curwin from the list. Remember after which window it was in wp2
1905  // 2. insert curwin before wp in the list
1906  // if wp != wp2
1907  //    3. remove wp from the list
1908  //    4. insert wp after wp2
1909  // 5. exchange the status line height, winbar height, hsep height and vsep width.
1910  win_T *wp2 = curwin->w_prev;
1911  frame_T *frp2 = curwin->w_frame->fr_prev;
1912  if (wp->w_prev != curwin) {
1913    win_remove(curwin, NULL);
1914    frame_remove(curwin->w_frame);
1915    win_append(wp->w_prev, curwin, NULL);
1916    frame_insert(frp, curwin->w_frame);
1917  }
1918  if (wp != wp2) {
1919    win_remove(wp, NULL);
1920    frame_remove(wp->w_frame);
1921    win_append(wp2, wp, NULL);
1922    if (frp2 == NULL) {
1923      frame_insert(wp->w_frame->fr_parent->fr_child, wp->w_frame);
1924    } else {
1925      frame_append(frp2, wp->w_frame);
1926    }
1927  }
1928  int temp = curwin->w_status_height;
1929  curwin->w_status_height = wp->w_status_height;
1930  wp->w_status_height = temp;
1931  temp = curwin->w_vsep_width;
1932  curwin->w_vsep_width = wp->w_vsep_width;
1933  wp->w_vsep_width = temp;
1934  temp = curwin->w_hsep_height;
1935  curwin->w_hsep_height = wp->w_hsep_height;
1936  wp->w_hsep_height = temp;
1937
1938  frame_fix_height(curwin);
1939  frame_fix_height(wp);
1940  frame_fix_width(curwin);
1941  frame_fix_width(wp);
1942
1943  win_comp_pos();                 // recompute window positions
1944
1945  if (wp->w_buffer != curbuf) {
1946    reset_VIsual_and_resel();
1947  } else if (Visual.active) {
1948    wp->w_cursor = curwin->w_cursor;
1949  }
1950
1951  win_enter(wp, true);
1952  redraw_later(curwin, UPD_NOT_VALID);
1953}
1954
1955// rotate windows: if upwards true the second window becomes the first one
1956//                 if upwards false the first window becomes the second one
1957static void win_rotate(bool upwards, int count)
1958{
1959  if (curwin->w_floating) {
1960    emsg(e_floatexchange);
1961    return;
1962  }
1963
1964  if (count <= 0 || one_window(curwin, NULL)) {
1965    // nothing to do
1966    beep_flush();
1967    return;
1968  }
1969
1970  // Check if all frames in this row/col have one window.
1971  frame_T *frp;
1972  FOR_ALL_FRAMES(frp, curwin->w_frame->fr_parent->fr_child) {
1973    if (frp->fr_win == NULL) {
1974      emsg(_("E443: Cannot rotate when another window is split"));
1975      return;
1976    }
1977  }
1978
1979  win_T *wp1 = NULL;
1980  win_T *wp2 = NULL;
1981
1982  while (count--) {
1983    if (upwards) {              // first window becomes last window
1984      // remove first window/frame from the list
1985      frp = curwin->w_frame->fr_parent->fr_child;
1986      assert(frp != NULL);
1987      wp1 = frp->fr_win;
1988      win_remove(wp1, NULL);
1989      frame_remove(frp);
1990      assert(frp->fr_parent->fr_child);
1991
1992      // find last frame and append removed window/frame after it
1993      for (; frp->fr_next != NULL; frp = frp->fr_next) {}
1994      win_append(frp->fr_win, wp1, NULL);
1995      frame_append(frp, wp1->w_frame);
1996
1997      wp2 = frp->fr_win;                // previously last window
1998    } else {                  // last window becomes first window
1999      // find last window/frame in the list and remove it
2000      for (frp = curwin->w_frame; frp->fr_next != NULL;
2001           frp = frp->fr_next) {}
2002      wp1 = frp->fr_win;
2003      wp2 = wp1->w_prev;                    // will become last window
2004      win_remove(wp1, NULL);
2005      frame_remove(frp);
2006      assert(frp->fr_parent->fr_child);
2007
2008      // append the removed window/frame before the first in the list
2009      win_append(frp->fr_parent->fr_child->fr_win->w_prev, wp1, NULL);
2010      frame_insert(frp->fr_parent->fr_child, frp);
2011    }
2012
2013    // exchange status height, winbar height, hsep height and vsep width of old and new last window
2014    int n = wp2->w_status_height;
2015    wp2->w_status_height = wp1->w_status_height;
2016    wp1->w_status_height = n;
2017    n = wp2->w_hsep_height;
2018    wp2->w_hsep_height = wp1->w_hsep_height;
2019    wp1->w_hsep_height = n;
2020    frame_fix_height(wp1);
2021    frame_fix_height(wp2);
2022    n = wp2->w_vsep_width;
2023    wp2->w_vsep_width = wp1->w_vsep_width;
2024    wp1->w_vsep_width = n;
2025    frame_fix_width(wp1);
2026    frame_fix_width(wp2);
2027
2028    // recompute w_winrow and w_wincol for all windows
2029    win_comp_pos();
2030  }
2031
2032  wp1->w_pos_changed = true;
2033  wp2->w_pos_changed = true;
2034
2035  redraw_all_later(UPD_NOT_VALID);
2036}
2037
2038/// Move "wp" into a new split in a given direction, possibly relative to the
2039/// current window.
2040/// "wp" must be valid in the current tabpage.
2041/// Returns FAIL for failure, OK otherwise.
2042int win_splitmove(win_T *wp, int size, int flags)
2043{
2044  int dir = 0;
2045  int height = wp->w_height;
2046
2047  if (one_window(wp, NULL)) {
2048    return OK;  // nothing to do
2049  }
2050  if (is_ctx_win(wp) || check_split_disallowed(wp) == FAIL) {
2051    return FAIL;
2052  }
2053
2054  frame_T *unflat_altfr = NULL;
2055  if (wp->w_floating) {
2056    win_remove(wp, NULL);
2057  } else {
2058    // Remove the window and frame from the tree of frames.  Don't flatten any
2059    // frames yet so we can restore things if win_split_ins fails.
2060    winframe_remove(wp, &dir, NULL, &unflat_altfr);
2061    assert(unflat_altfr != NULL);
2062    win_remove(wp, NULL);
2063    last_status(false);  // may need to remove last status line
2064    win_comp_pos();  // recompute window positions
2065  }
2066
2067  // Split a window on the desired side and put "wp" there.
2068  if (win_split_ins(size, flags, wp, dir, unflat_altfr) == NULL) {
2069    if (!wp->w_floating) {
2070      assert(unflat_altfr != NULL);
2071      // win_split_ins doesn't change sizes or layout if it fails to insert an
2072      // existing window, so just undo winframe_remove.
2073      winframe_restore(wp, dir, unflat_altfr);
2074    }
2075    win_append(wp->w_prev, wp, NULL);
2076    return FAIL;
2077  }
2078
2079  // If splitting horizontally, try to preserve height.
2080  // Note that win_split_ins autocommands may have immediately closed "wp", or made it floating!
2081  if (size == 0 && !(flags & WSP_VERT) && win_valid(wp) && !wp->w_floating) {
2082    win_setheight_win(height, wp, true);
2083    if (p_ea) {
2084      // Equalize windows.  Note that win_split_ins autocommands may have
2085      // made a window other than "wp" current.
2086      win_equal(curwin, curwin == wp, 'v');
2087    }
2088  }
2089
2090  return OK;
2091}
2092
2093// Move window "win1" to below/right of "win2" and make "win1" the current
2094// window.  Only works within the same frame!
2095void win_move_after(win_T *win1, win_T *win2)
2096{
2097  // check if the arguments are reasonable
2098  if (win1 == win2) {
2099    return;
2100  }
2101
2102  // check if there is something to do
2103  if (win2->w_next != win1) {
2104    if (win1->w_frame->fr_parent != win2->w_frame->fr_parent) {
2105      iemsg("INTERNAL: trying to move a window into another frame");
2106      return;
2107    }
2108
2109    // may need to move the status line, window bar, horizontal or vertical separator of the last
2110    // window
2111    if (win1 == lastwin) {
2112      int height = win1->w_prev->w_status_height;
2113      win1->w_prev->w_status_height = win1->w_status_height;
2114      win1->w_status_height = height;
2115
2116      height = win1->w_prev->w_hsep_height;
2117      win1->w_prev->w_hsep_height = win1->w_hsep_height;
2118      win1->w_hsep_height = height;
2119
2120      if (win1->w_prev->w_vsep_width == 1) {
2121        // Remove the vertical separator from the last-but-one window,
2122        // add it to the last window.  Adjust the frame widths.
2123        win1->w_prev->w_vsep_width = 0;
2124        win1->w_prev->w_frame->fr_width -= 1;
2125        win1->w_vsep_width = 1;
2126        win1->w_frame->fr_width += 1;
2127      }
2128    } else if (win2 == lastwin) {
2129      int height = win1->w_status_height;
2130      win1->w_status_height = win2->w_status_height;
2131      win2->w_status_height = height;
2132
2133      height = win1->w_hsep_height;
2134      win1->w_hsep_height = win2->w_hsep_height;
2135      win2->w_hsep_height = height;
2136
2137      if (win1->w_vsep_width == 1) {
2138        // Remove the vertical separator from win1, add it to the last
2139        // window, win2.  Adjust the frame widths.
2140        win2->w_vsep_width = 1;
2141        win2->w_frame->fr_width += 1;
2142        win1->w_vsep_width = 0;
2143        win1->w_frame->fr_width -= 1;
2144      }
2145    }
2146    win_remove(win1, NULL);
2147    frame_remove(win1->w_frame);
2148    win_append(win2, win1, NULL);
2149    frame_append(win2->w_frame, win1->w_frame);
2150
2151    win_comp_pos();  // recompute w_winrow for all windows
2152    redraw_later(curwin, UPD_NOT_VALID);
2153  }
2154  win1->w_pos_changed = true;
2155  win2->w_pos_changed = true;
2156
2157  win_enter(win1, false);
2158}
2159
2160/// Compute maximum number of windows that can fit within "height" in frame "fr".
2161static int get_maximum_wincount(frame_T *fr, int height)
2162{
2163  if (fr->fr_layout != FR_COL) {
2164    return (height / ((int)p_wmh + STATUS_HEIGHT + frame2win(fr)->w_winbar_height));
2165  } else if (global_winbar_height()) {
2166    // If winbar is globally enabled, no need to check each window for it.
2167    return (height / ((int)p_wmh + STATUS_HEIGHT + 1));
2168  }
2169
2170  frame_T *frp;
2171  int total_wincount = 0;
2172
2173  // First, try to fit all child frames of "fr" into "height"
2174  FOR_ALL_FRAMES(frp, fr->fr_child) {
2175    win_T *wp = frame2win(frp);
2176
2177    if (height < (p_wmh + STATUS_HEIGHT + wp->w_winbar_height)) {
2178      break;
2179    }
2180    height -= (int)p_wmh + STATUS_HEIGHT + wp->w_winbar_height;
2181    total_wincount += 1;
2182  }
2183
2184  // If we still have enough room for more windows, just use the default winbar height (which is 0)
2185  // in order to get the amount of windows that'd fit in the remaining space
2186  total_wincount += height / ((int)p_wmh + STATUS_HEIGHT);
2187
2188  return total_wincount;
2189}
2190
2191/// Make all windows the same height.
2192/// 'next_curwin' will soon be the current window, make sure it has enough rows.
2193///
2194/// @param next_curwin  pointer to current window to be or NULL
2195/// @param current  do only frame with current window
2196/// @param dir  'v' for vertically, 'h' for horizontally, 'b' for both, 0 for using p_ead
2197void win_equal(win_T *next_curwin, bool current, int dir)
2198{
2199  if (dir == 0) {
2200    dir = (unsigned char)(*p_ead);
2201  }
2202  win_equal_rec(next_curwin == NULL ? curwin : next_curwin, current,
2203                topframe, dir, 0, tabline_height(),
2204                Columns, topframe->fr_height);
2205  if (!is_ctx_win(next_curwin)) {
2206    win_fix_scroll(true);
2207  }
2208}
2209
2210/// Set a frame to a new position and height, spreading the available room
2211/// equally over contained frames.
2212/// The window "next_curwin" (if not NULL) should at least get the size from
2213/// 'winheight' and 'winwidth' if possible.
2214///
2215/// @param next_curwin  pointer to current window to be or NULL
2216/// @param current      do only frame with current window
2217/// @param topfr        frame to set size off
2218/// @param dir          'v', 'h' or 'b', see win_equal()
2219/// @param col          horizontal position for frame
2220/// @param row          vertical position for frame
2221/// @param width        new width of frame
2222/// @param height       new height of frame
2223static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int dir, int col,
2224                          int row, int width, int height)
2225{
2226  int extra_sep = 0;
2227  int totwincount = 0;
2228  int next_curwin_size = 0;
2229  int room = 0;
2230  bool has_next_curwin = false;
2231
2232  if (topfr->fr_layout == FR_LEAF) {
2233    // Set the width/height of this frame.
2234    // Redraw when size or position changes
2235    if (topfr->fr_height != height || topfr->fr_win->w_winrow != row
2236        || topfr->fr_width != width
2237        || topfr->fr_win->w_wincol != col) {
2238      topfr->fr_win->w_winrow = row;
2239      frame_new_height(topfr, height, false, false, false);
2240      topfr->fr_win->w_wincol = col;
2241      frame_new_width(topfr, width, false, false);
2242      redraw_all_later(UPD_NOT_VALID);
2243    }
2244  } else if (topfr->fr_layout == FR_ROW) {
2245    topfr->fr_width = width;
2246    topfr->fr_height = height;
2247
2248    if (dir != 'v') {                   // equalize frame widths
2249      // Compute the maximum number of windows horizontally in this
2250      // frame.
2251      int n = frame_minwidth(topfr, NOWIN);
2252      // add one for the rightmost window, it doesn't have a separator
2253      if (col + width == Columns) {
2254        extra_sep = 1;
2255      } else {
2256        extra_sep = 0;
2257      }
2258      totwincount = (n + extra_sep) / ((int)p_wmw + 1);
2259      has_next_curwin = frame_has_win(topfr, next_curwin);
2260
2261      // Compute width for "next_curwin" window and room available for
2262      // other windows.
2263      // "m" is the minimal width when counting p_wiw for "next_curwin".
2264      int m = frame_minwidth(topfr, next_curwin);
2265      room = width - m;
2266      if (room < 0) {
2267        next_curwin_size = (int)p_wiw + room;
2268        room = 0;
2269      } else {
2270        next_curwin_size = -1;
2271        frame_T *fr;
2272        FOR_ALL_FRAMES(fr, topfr->fr_child) {
2273          if (!frame_fixed_width(fr)) {
2274            continue;
2275          }
2276          // If 'winfixwidth' set keep the window width if possible.
2277          // Watch out for this window being the next_curwin.
2278          n = frame_minwidth(fr, NOWIN);
2279          int new_size = fr->fr_width;
2280          if (frame_has_win(fr, next_curwin)) {
2281            room += (int)p_wiw - (int)p_wmw;
2282            next_curwin_size = 0;
2283            new_size = MAX(new_size, (int)p_wiw);
2284          } else {
2285            // These windows don't use up room.
2286            totwincount -= (n + (fr->fr_next == NULL ? extra_sep : 0)) / ((int)p_wmw + 1);
2287          }
2288          room -= new_size - n;
2289          if (room < 0) {
2290            new_size += room;
2291            room = 0;
2292          }
2293          fr->fr_newwidth = new_size;
2294        }
2295        if (next_curwin_size == -1) {
2296          if (!has_next_curwin) {
2297            next_curwin_size = 0;
2298          } else if (totwincount > 1
2299                     && (room + (totwincount - 2))
2300                     / (totwincount - 1) > p_wiw) {
2301            // Can make all windows wider than 'winwidth', spread
2302            // the room equally.
2303            next_curwin_size = (int)(room + p_wiw
2304                                     + (totwincount - 1) * p_wmw
2305                                     + (totwincount - 1)) / totwincount;
2306            room -= next_curwin_size - (int)p_wiw;
2307          } else {
2308            next_curwin_size = (int)p_wiw;
2309          }
2310        }
2311      }
2312
2313      if (has_next_curwin) {
2314        totwincount--;                  // don't count curwin
2315      }
2316    }
2317
2318    frame_T *fr;
2319    FOR_ALL_FRAMES(fr, topfr->fr_child) {
2320      int wincount = 1;
2321      int new_size;
2322      if (fr->fr_next == NULL) {
2323        // last frame gets all that remains (avoid roundoff error)
2324        new_size = width;
2325      } else if (dir == 'v') {
2326        new_size = fr->fr_width;
2327      } else if (frame_fixed_width(fr)) {
2328        new_size = fr->fr_newwidth;
2329        wincount = 0;               // doesn't count as a sizeable window
2330      } else {
2331        // Compute the maximum number of windows horiz. in "fr".
2332        int n = frame_minwidth(fr, NOWIN);
2333        wincount = (n + (fr->fr_next == NULL ? extra_sep : 0)) / ((int)p_wmw + 1);
2334        int m = frame_minwidth(fr, next_curwin);
2335        bool hnc = has_next_curwin && frame_has_win(fr, next_curwin);
2336        if (hnc) {                    // don't count next_curwin
2337          wincount--;
2338        }
2339        if (totwincount == 0) {
2340          new_size = room;
2341        } else {
2342          new_size = (wincount * room + (totwincount / 2)) / totwincount;
2343        }
2344        if (hnc) {                  // add next_curwin size
2345          next_curwin_size -= (int)p_wiw - (m - n);
2346          next_curwin_size = MAX(next_curwin_size, 0);
2347          new_size += next_curwin_size;
2348          room -= new_size - next_curwin_size;
2349        } else {
2350          room -= new_size;
2351        }
2352        new_size += n;
2353      }
2354
2355      // Skip frame that is full width when splitting or closing a
2356      // window, unless equalizing all frames.
2357      if (!current || dir != 'v' || topfr->fr_parent != NULL
2358          || (new_size != fr->fr_width)
2359          || frame_has_win(fr, next_curwin)) {
2360        win_equal_rec(next_curwin, current, fr, dir, col, row,
2361                      new_size, height);
2362      }
2363      col += new_size;
2364      width -= new_size;
2365      totwincount -= wincount;
2366    }
2367  } else {  // topfr->fr_layout == FR_COL
2368    topfr->fr_width = width;
2369    topfr->fr_height = height;
2370
2371    if (dir != 'h') {                   // equalize frame heights
2372      // Compute maximum number of windows vertically in this frame.
2373      int n = frame_minheight(topfr, NOWIN);
2374      // add one for the bottom window if it doesn't have a statusline or separator
2375      if (row + height >= cmdline_row && p_ls == 0) {
2376        extra_sep = STATUS_HEIGHT;
2377      } else if (global_stl_height() > 0) {
2378        extra_sep = 1;
2379      } else {
2380        extra_sep = 0;
2381      }
2382      totwincount = get_maximum_wincount(topfr, n + extra_sep);
2383      has_next_curwin = frame_has_win(topfr, next_curwin);
2384
2385      // Compute height for "next_curwin" window and room available for
2386      // other windows.
2387      // "m" is the minimal height when counting p_wh for "next_curwin".
2388      int m = frame_minheight(topfr, next_curwin);
2389      room = height - m;
2390      if (room < 0) {
2391        // The room is less than 'winheight', use all space for the
2392        // current window.
2393        next_curwin_size = (int)p_wh + room;
2394        room = 0;
2395      } else {
2396        next_curwin_size = -1;
2397        frame_T *fr;
2398        FOR_ALL_FRAMES(fr, topfr->fr_child) {
2399          if (!frame_fixed_height(fr)) {
2400            continue;
2401          }
2402          // If 'winfixheight' set keep the window height if possible.
2403          // Watch out for this window being the next_curwin.
2404          n = frame_minheight(fr, NOWIN);
2405          int new_size = fr->fr_height;
2406          if (frame_has_win(fr, next_curwin)) {
2407            room += (int)p_wh - (int)p_wmh;
2408            next_curwin_size = 0;
2409            new_size = MAX(new_size, (int)p_wh);
2410          } else {
2411            // These windows don't use up room.
2412            totwincount -= get_maximum_wincount(fr, (n + (fr->fr_next == NULL ? extra_sep : 0)));
2413          }
2414          room -= new_size - n;
2415          if (room < 0) {
2416            new_size += room;
2417            room = 0;
2418          }
2419          fr->fr_newheight = new_size;
2420        }
2421        if (next_curwin_size == -1) {
2422          if (!has_next_curwin) {
2423            next_curwin_size = 0;
2424          } else if (totwincount > 1
2425                     && (room + (totwincount - 2))
2426                     / (totwincount - 1) > p_wh) {
2427            // can make all windows higher than 'winheight',
2428            // spread the room equally.
2429            next_curwin_size = (int)(room + p_wh
2430                                     + (totwincount - 1) * p_wmh
2431                                     + (totwincount - 1)) / totwincount;
2432            room -= next_curwin_size - (int)p_wh;
2433          } else {
2434            next_curwin_size = (int)p_wh;
2435          }
2436        }
2437      }
2438
2439      if (has_next_curwin) {
2440        totwincount--;                  // don't count curwin
2441      }
2442    }
2443
2444    frame_T *fr;
2445    FOR_ALL_FRAMES(fr, topfr->fr_child) {
2446      int new_size;
2447      int wincount = 1;
2448      if (fr->fr_next == NULL) {
2449        // last frame gets all that remains (avoid roundoff error)
2450        new_size = height;
2451      } else if (dir == 'h') {
2452        new_size = fr->fr_height;
2453      } else if (frame_fixed_height(fr)) {
2454        new_size = fr->fr_newheight;
2455        wincount = 0;               // doesn't count as a sizeable window
2456      } else {
2457        // Compute the maximum number of windows vert. in "fr".
2458        int n = frame_minheight(fr, NOWIN);
2459        wincount = get_maximum_wincount(fr, (n + (fr->fr_next == NULL ? extra_sep : 0)));
2460        int m = frame_minheight(fr, next_curwin);
2461        bool hnc = has_next_curwin && frame_has_win(fr, next_curwin);
2462        if (hnc) {                    // don't count next_curwin
2463          wincount--;
2464        }
2465        if (totwincount == 0) {
2466          new_size = room;
2467        } else {
2468          new_size = (wincount * room + (totwincount / 2)) / totwincount;
2469        }
2470        if (hnc) {                  // add next_curwin size
2471          next_curwin_size -= (int)p_wh - (m - n);
2472          new_size += next_curwin_size;
2473          room -= new_size - next_curwin_size;
2474        } else {
2475          room -= new_size;
2476        }
2477        new_size += n;
2478      }
2479      // Skip frame that is full width when splitting or closing a
2480      // window, unless equalizing all frames.
2481      if (!current || dir != 'h' || topfr->fr_parent != NULL
2482          || (new_size != fr->fr_height)
2483          || frame_has_win(fr, next_curwin)) {
2484        win_equal_rec(next_curwin, current, fr, dir, col, row,
2485                      width, new_size);
2486      }
2487      row += new_size;
2488      height -= new_size;
2489      totwincount -= wincount;
2490    }
2491  }
2492}
2493
2494/// Called when `win` stops being curwin: closing, switching, or leaving its tabpage. Pairs with
2495/// entering_window(). Only matters for a prompt buffer...
2496///
2497/// @see win_enter
2498void leaving_window(win_T *const win)
2499  FUNC_ATTR_NONNULL_ALL
2500{
2501  // Not for a ctx window: it shows its buffer only temporarily.
2502  if (!bt_prompt(win->w_buffer) || is_ctx_win(win)) {
2503    return;
2504  }
2505
2506  // When leaving a prompt window stop Insert mode and perhaps restart
2507  // it when entering that window again.
2508  win->w_buffer->b_prompt_insert = restart_edit;
2509  if (restart_edit != NUL && mode_displayed) {
2510    clear_cmdline = true;  // unshow mode later
2511  }
2512  restart_edit = NUL;
2513
2514  // When leaving the window (or closing the window) was done from a
2515  // callback we need to break out of the Insert mode loop and restart Insert
2516  // mode when entering the window again.
2517  if ((State & MODE_INSERT) && !Ins.stop_insert_mode) {
2518    Ins.stop_insert_mode = true;
2519    if (win->w_buffer->b_prompt_insert == NUL) {
2520      win->w_buffer->b_prompt_insert = 'A';
2521    }
2522  }
2523}
2524
2525/// Called when `win` becomes curwin: switching to it, entering its tabpage, or ctx_restore().
2526/// Pairs with leaving_window(). Only matters for a prompt buffer...
2527///
2528/// @see win_enter
2529void entering_window(win_T *const win)
2530  FUNC_ATTR_NONNULL_ALL
2531{
2532  // Not for a ctx window: it shows its buffer only temporarily.
2533  if (!bt_prompt(win->w_buffer) || is_ctx_win(win)) {
2534    return;
2535  }
2536
2537  // When switching to a prompt buffer that was in Insert mode, don't stop
2538  // Insert mode, it may have been set in leaving_window().
2539  if (win->w_buffer->b_prompt_insert != NUL) {
2540    Ins.stop_insert_mode = false;
2541  }
2542
2543  // When entering the prompt window restart Insert mode if we were in Insert
2544  // mode when we left it and not already in Insert mode.
2545  if ((State & MODE_INSERT) == 0) {
2546    restart_edit = win->w_buffer->b_prompt_insert;
2547  }
2548}
2549
2550void win_init_empty(win_T *wp)
2551{
2552  redraw_later(wp, UPD_NOT_VALID);
2553  wp->w_lines_valid = 0;
2554  wp->w_cursor.lnum = 1;
2555  wp->w_curswant = wp->w_cursor.col = 0;
2556  wp->w_cursor.coladd = 0;
2557  wp->w_pcmark.lnum = 1;        // pcmark not cleared but set to line 1
2558  wp->w_pcmark.col = 0;
2559  wp->w_prev_pcmark.lnum = 0;
2560  wp->w_prev_pcmark.col = 0;
2561  wp->w_topline = 1;
2562  wp->w_topfill = 0;
2563  wp->w_botline = 2;
2564  wp->w_valid = 0;
2565  wp->w_s = &wp->w_buffer->b_s;
2566}
2567
2568/// Init the current window "curwin".
2569/// Called when a new file is being edited.
2570void curwin_init(void)
2571{
2572  win_init_empty(curwin);
2573}
2574
2575/// Closes all windows for buffer `buf` unless there is only one non-floating window.
2576///
2577/// @param keep_curwin  don't close `curwin`
2578void close_windows(buf_T *buf, bool keep_curwin)
2579{
2580  RedrawingDisabled++;
2581
2582  // Start from lastwin to close floating windows with the same buffer first.
2583  // When the ctx window is involved win_close() may need to print an error message.
2584  for (win_T *wp = lastwin; wp != NULL && (is_ctx_win(lastwin) || !one_window(wp, NULL));) {
2585    if (wp->w_buffer == buf && (!keep_curwin || wp != curwin)
2586        && !(win_locked(wp) || wp->w_buffer->b_locked > 0)) {
2587      if (window_layout_locked(CMD_SIZE)) {
2588        goto theend;  // Only give one error message.
2589      }
2590      if (win_close(wp, false, false) == FAIL) {
2591        // If closing the window fails give up, to avoid looping forever.
2592        break;
2593      }
2594
2595      // Start all over, autocommands may change the window layout.
2596      wp = lastwin;
2597    } else {
2598      wp = wp->w_prev;
2599    }
2600  }
2601
2602  tabpage_T *nexttp;
2603
2604  // Also check windows in other tab pages.
2605  for (tabpage_T *tp = first_tabpage; tp != NULL; tp = nexttp) {
2606    nexttp = tp->tp_next;
2607    if (tp != curtab) {
2608      // Start from tp_lastwin to close floating windows with the same buffer first.
2609      for (win_T *wp = tp->tp_lastwin; wp != NULL; wp = wp->w_prev) {
2610        if (wp->w_buffer == buf
2611            && !(win_locked(wp) || wp->w_buffer->b_locked > 0)) {
2612          if (window_layout_locked(CMD_SIZE)) {
2613            goto theend;  // Only give one error message.
2614          }
2615          if (!win_close_othertab(wp, false, tp, false)) {
2616            // If closing the window fails give up, to avoid looping forever.
2617            goto theend;
2618          }
2619
2620          // Start all over, the tab page may be closed and
2621          // autocommands may change the window layout.
2622          nexttp = first_tabpage;
2623          break;
2624        }
2625      }
2626    }
2627  }
2628
2629theend:
2630  RedrawingDisabled--;
2631}
2632
2633/// Check if "win" is the last non-floating window that exists.
2634bool last_window(win_T *win) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2635{
2636  return one_window(win, NULL) && first_tabpage->tp_next == NULL;
2637}
2638
2639/// Check if "win" is the only non-floating window in tabpage "tp", or NULL for current tabpage.
2640///
2641/// This should be used in place of ONE_WINDOW when necessary,
2642/// with "firstwin" or the affected window as argument depending on the situation.
2643bool one_window(win_T *win, tabpage_T *tp)
2644  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1)
2645{
2646  win_T *first = tp ? tp->tp_firstwin : firstwin;
2647  assert((!tp || tp != curtab) && !first->w_floating);
2648  return first == win && (win->w_next == NULL || win->w_next->w_floating);
2649}
2650
2651/// Check if floating windows in tabpage `tp` can be closed.
2652/// Do not call this when the ctx window is in use!
2653///
2654/// @param tp tabpage to check. Must be NULL for the current tabpage.
2655/// @return true if all floating windows can be closed
2656static bool can_close_floating_windows(tabpage_T *tp)
2657{
2658  assert(tp != curtab && (tp || !is_ctx_win(lastwin)));
2659  for (win_T *wp = tp ? tp->tp_lastwin : lastwin; wp->w_floating; wp = wp->w_prev) {
2660    buf_T *buf = wp->w_buffer;
2661    int need_hide = (bufIsChanged(buf) && buf->b_nwindows <= 1);
2662
2663    if (need_hide && !buf_hide(buf)) {
2664      return false;
2665    }
2666  }
2667  return true;
2668}
2669
2670/// Close the possibly last window in a tab page.
2671///
2672/// @param  win          window to close
2673/// @param  free_buf     whether to free the window's current buffer
2674/// @param  prev_curtab  previous tabpage that will be closed if "win" is the
2675///                      last window in the tabpage
2676///
2677/// @return false if there are other windows and nothing is done, true otherwise.
2678static bool close_last_window_tabpage(win_T *win, bool free_buf, tabpage_T *prev_curtab)
2679  FUNC_ATTR_NONNULL_ARG(1)
2680{
2681  if (!ONE_WINDOW) {
2682    return false;
2683  }
2684
2685  buf_T *old_curbuf = curbuf;
2686  tabpage_T *save_lastused = lastused_tabpage;
2687
2688  Terminal *term = win->w_buffer ? win->w_buffer->terminal : NULL;
2689  if (term) {
2690    // Don't free terminal buffers
2691    free_buf = false;
2692  }
2693
2694  // Closing the last window in a tab page.  First go to another tab
2695  // page and then close the window and the tab page.  This avoids that
2696  // curwin and curtab are invalid while we are freeing memory, they may
2697  // be used in GUI events.
2698  // Don't trigger *Enter autocommands yet, they may use wrong values, so do
2699  // that below.
2700  // Do trigger *Leave autocommands, unless win->w_buffer is NULL, in which
2701  // case they have already been triggered.
2702  goto_tabpage_tp(alt_tabpage(), false, win->w_buffer != NULL);
2703
2704  // Safety check: Autocommands may have switched back to the old tab page
2705  // or closed the window when jumping to the other tab page.
2706  if (curtab != prev_curtab && valid_tabpage(prev_curtab) && prev_curtab->tp_firstwin == win) {
2707    win_close_othertab(win, free_buf, prev_curtab, false);
2708  }
2709
2710  // Entering the other tab page made the closed one the last used tab page.
2711  // Restore the previous one when it is still there.
2712  if (valid_tabpage(save_lastused) && save_lastused != curtab) {
2713    lastused_tabpage = save_lastused;
2714  }
2715  entering_window(curwin);
2716
2717  // Since goto_tabpage_tp above did not trigger *Enter autocommands, do
2718  // that now.
2719  apply_autocmds(EVENT_WINENTER, NULL, NULL, false, curbuf);
2720  apply_autocmds(EVENT_TABENTER, NULL, NULL, false, curbuf);
2721  if (old_curbuf != curbuf) {
2722    apply_autocmds(EVENT_BUFENTER, NULL, NULL, false, curbuf);
2723  }
2724  return true;
2725}
2726
2727/// Close the buffer of "win" and unload it if "action" is DOBUF_UNLOAD.
2728/// "action" can also be zero (do nothing).
2729/// "abort_if_last" is passed to close_buffer(): abort closing if all other
2730/// windows are closed.
2731///
2732/// @return  @see close_buffer().
2733static bool win_close_buffer(win_T *win, int action, bool abort_if_last)
2734  FUNC_ATTR_NONNULL_ALL
2735{
2736  // Free independent synblock before the buffer is freed.
2737  if (win->w_buffer != NULL) {
2738    reset_synblock(win);
2739  }
2740
2741  // When a quickfix/location list window is closed and the buffer is
2742  // displayed in only one window, then unlist the buffer.
2743  if (win->w_buffer != NULL && bt_quickfix(win->w_buffer)
2744      && win->w_buffer->b_nwindows == 1) {
2745    win->w_buffer->b_p_bl = false;
2746  }
2747
2748  bool retval = false;
2749  // Close the link to the buffer.
2750  if (win->w_buffer != NULL) {
2751    bufref_T bufref;
2752    set_bufref(&bufref, curbuf);
2753    win->w_locked++;
2754    retval = close_buffer(win, win->w_buffer, action, abort_if_last, true, true);
2755    if (win_valid_any_tab(win)) {
2756      win->w_locked--;
2757    }
2758
2759    // Make sure curbuf is valid. It can become invalid if 'bufhidden' is
2760    // "wipe".
2761    if (!bufref_valid(&bufref)) {
2762      curbuf = firstbuf;
2763    }
2764  }
2765
2766  return retval;
2767}
2768
2769/// When failing to close a window after already calling close_buffer() on it,
2770/// call this to make the window have a buffer again.
2771///
2772/// @param bufref         reference to win->w_buffer before calling close_buffer()
2773static void win_unclose_buffer(win_T *win, bufref_T *bufref)
2774{
2775  if (win->w_buffer == NULL) {
2776    // If the buffer was removed from the window we have to give it any buffer.
2777    win->w_buffer = firstbuf;
2778    firstbuf->b_nwindows++;
2779    if (win == curwin) {
2780      curbuf = curwin->w_buffer;
2781    }
2782    win_init_empty(win);
2783  }
2784}
2785
2786// Close window "win".  Only works for the current tab page.
2787// If "free_buf" is true related buffer may be unloaded.
2788//
2789// Called by :quit, :close, :xit, :wq and findtag().
2790// Returns FAIL when the window was not closed.
2791int win_close(win_T *win, bool free_buf, bool force)
2792  FUNC_ATTR_NONNULL_ALL
2793{
2794  tabpage_T *prev_curtab = curtab;
2795  frame_T *win_frame = win->w_floating ? NULL : win->w_frame->fr_parent;
2796  const bool had_diffmode = win->w_p_diff;
2797
2798  if (last_window(win)) {
2799    emsg(_(e_cannot_close_last_window));
2800    return FAIL;
2801  }
2802  if (!win->w_floating && window_layout_locked(CMD_close)) {
2803    return FAIL;
2804  }
2805
2806  if (win_locked(win)
2807      || (win->w_buffer != NULL && win->w_buffer->b_locked > 0)) {
2808    return FAIL;     // window is already being closed
2809  }
2810  if (is_ctx_win(win)) {
2811    emsg(_(e_autocmd_close));
2812    return FAIL;
2813  }
2814  if (lastwin->w_floating && one_window(win, NULL)) {
2815    if (is_ctx_win(lastwin)) {
2816      emsg(_("E814: Cannot close window, only autocmd window would remain"));
2817      return FAIL;
2818    }
2819    if (force || can_close_floating_windows(NULL)) {
2820      // close the last window until the there are no floating windows
2821      while (lastwin->w_floating) {
2822        // `force` flag isn't actually used when closing a floating window.
2823        if (win_close(lastwin, !buf_hide(lastwin->w_buffer), true) == FAIL) {
2824          // If closing the window fails give up, to avoid looping forever.
2825          return FAIL;
2826        }
2827      }
2828      if (!win_valid_any_tab(win)) {
2829        return FAIL;  // window already closed by autocommands
2830      }
2831      // Autocommands may have closed all other tabpages; check again.
2832      if (last_window(win)) {
2833        emsg(_(e_cannot_close_last_window));
2834        return FAIL;
2835      }
2836    } else {
2837      emsg(e_floatonly);
2838      return FAIL;
2839    }
2840  }
2841
2842  // When closing the last window in a tab page first go to another tab page
2843  // and then close the window and the tab page to avoid that curwin and
2844  // curtab are invalid while we are freeing memory.
2845  if (close_last_window_tabpage(win, free_buf, prev_curtab)) {
2846    return FAIL;
2847  }
2848
2849  bool help_window = false;
2850  bool quickfix_window = false;
2851
2852  // When closing the help window, try restoring a snapshot after closing
2853  // the window.  Otherwise clear the snapshot, it's now invalid.
2854  if (bt_help(win->w_buffer)) {
2855    help_window = true;
2856  } else {
2857    clear_snapshot(curtab, SNAP_HELP_IDX);
2858  }
2859
2860  if (bt_quickfix(win->w_buffer)) {
2861    quickfix_window = true;
2862  } else {
2863    clear_snapshot(curtab, SNAP_QUICKFIX_IDX);
2864  }
2865
2866  bool other_buffer = false;
2867
2868  if (win == curwin) {
2869    leaving_window(curwin);
2870
2871    // Guess which window is going to be the new current window.
2872    // This may change because of the autocommands (sigh).
2873    win_T *wp = win->w_floating ? win_float_find_altwin(win, NULL)
2874                                : frame2win(win_altframe(win, NULL));
2875
2876    // Be careful: If autocommands delete the window or cause this window
2877    // to be the last one left, return now.
2878    if (wp->w_buffer != curbuf) {
2879      reset_VIsual_and_resel();  // stop Visual mode
2880
2881      other_buffer = true;
2882      if (!win_valid(win)) {
2883        return FAIL;
2884      }
2885      win->w_locked++;
2886      apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, false, curbuf);
2887      if (!win_valid(win)) {
2888        return FAIL;
2889      }
2890      win->w_locked--;
2891      if (last_window(win)) {
2892        return FAIL;
2893      }
2894    }
2895    win->w_locked++;
2896    apply_autocmds(EVENT_WINLEAVE, NULL, NULL, false, curbuf);
2897    if (!win_valid(win)) {
2898      return FAIL;
2899    }
2900    win->w_locked--;
2901    if (last_window(win)) {
2902      return FAIL;
2903    }
2904    // autocmds may abort script processing
2905    if (aborting()) {
2906      return FAIL;
2907    }
2908  }
2909
2910  // Fire WinClosed just before starting to free window-related resources.
2911  do_autocmd_winclosed(win);
2912  // autocmd may have freed the window already.
2913  if (!win_valid_any_tab(win)) {
2914    return OK;
2915  }
2916
2917  bufref_T bufref;
2918  set_bufref(&bufref, win->w_buffer);
2919
2920  win_close_buffer(win, free_buf ? DOBUF_UNLOAD : 0, true);
2921
2922  if (win_valid(win) && win->w_buffer == NULL
2923      && !win->w_floating && last_window(win)) {
2924    // Autocommands have closed all windows, quit now.  Restore
2925    // curwin->w_buffer, otherwise writing ShaDa file may fail.
2926    if (curwin->w_buffer == NULL) {
2927      curwin->w_buffer = curbuf;
2928    }
2929    getout(0);
2930  }
2931  // Autocommands may have moved to another tab page.
2932  if (curtab != prev_curtab && win_valid_any_tab(win)
2933      && win->w_buffer == NULL) {
2934    // Need to close the window anyway, since the buffer is NULL.
2935    win_close_othertab(win, false, prev_curtab, force);
2936    return FAIL;
2937  }
2938
2939  // Autocommands may have closed the window already, or closed the only
2940  // other window or moved to another tab page.
2941  if (!win_valid(win)) {
2942    return FAIL;
2943  }
2944  if (one_window(win, NULL) && (first_tabpage->tp_next == NULL || lastwin->w_floating)) {
2945    if (first_tabpage->tp_next != NULL) {
2946      emsg(e_floatonly);
2947    }
2948    win_unclose_buffer(win, &bufref);
2949    return FAIL;
2950  }
2951  if (close_last_window_tabpage(win, free_buf, prev_curtab)) {
2952    return FAIL;
2953  }
2954
2955  // Now we are really going to close the window.  Disallow any autocommand
2956  // to split a window to avoid trouble.
2957  split_disallowed++;
2958
2959  bool was_floating = win->w_floating;
2960  if (ui_has(kUIMultigrid)) {
2961    ui_call_win_close(win->w_grid_alloc.handle);
2962  }
2963
2964  if (win->w_floating) {
2965    ui_comp_remove_grid(&win->w_grid_alloc);
2966    assert(first_tabpage != NULL);  // suppress clang "Dereference of NULL pointer"
2967    if (win->w_config.external) {
2968      FOR_ALL_TABS(tp) {
2969        if (tp != curtab && tp->tp_curwin == win) {
2970          // NB: an autocmd can still abort the closing of this window,
2971          // but carrying out this change anyway shouldn't be a catastrophe.
2972          tp->tp_curwin = tp->tp_firstwin;
2973        }
2974      }
2975    }
2976  }
2977
2978  // About to free the window. Remember its final buffer for terminal_check_size,
2979  // which may have changed since the last set_bufref. (e.g: close_buffer autocmds)
2980  set_bufref(&bufref, win->w_buffer);
2981
2982  if (win->w_buffer != NULL) {
2983    win->w_buffer->b_nwindows--;
2984  }
2985
2986  bool had_cmdline_ruler = p_ru && win == curwin && win->w_status_height == 0;
2987  // Free the memory used for the window and get the window that received
2988  // the screen space.
2989  int dir;
2990  win_T *wp = win_free_mem(win, &dir, NULL);
2991
2992  if (help_window || quickfix_window) {
2993    // Closing the help window moves the cursor back to the current window
2994    // of the snapshot.
2995    win_T *prev_win = get_snapshot_curwin(help_window ? SNAP_HELP_IDX : SNAP_QUICKFIX_IDX);
2996    if (win_valid(prev_win)) {
2997      wp = prev_win;
2998    }
2999  }
3000
3001  bool close_curwin = false;
3002
3003  // Make sure curwin isn't invalid.  It can cause severe trouble when
3004  // printing an error message.  For win_equal() curbuf needs to be valid
3005  // too.
3006  if (win == curwin) {
3007    curwin = wp;
3008    if (wp->w_p_pvw || bt_quickfix(wp->w_buffer)) {
3009      // If the cursor goes to the preview or the quickfix window, try
3010      // finding another window to go to.
3011      while (true) {
3012        if (wp->w_next == NULL) {
3013          wp = firstwin;
3014        } else {
3015          wp = wp->w_next;
3016        }
3017        if (wp == curwin) {
3018          break;
3019        }
3020        if (!wp->w_p_pvw && !bt_quickfix(wp->w_buffer)
3021            && !(wp->w_floating && (wp->w_config.hide || !wp->w_config.focusable))) {
3022          curwin = wp;
3023          break;
3024        }
3025      }
3026    }
3027    curbuf = curwin->w_buffer;
3028    close_curwin = true;
3029
3030    // The cursor position may be invalid if the buffer changed after last
3031    // using the window.
3032    check_cursor(curwin);
3033  }
3034
3035  if (!was_floating) {
3036    // If last window has a status line now and we don't want one,
3037    // remove the status line. Do this before win_equal(), because
3038    // it may change the height of a window.
3039    last_status(false);
3040
3041    if (!curwin->w_floating && p_ea && (*p_ead == 'b' || *p_ead == dir)) {
3042      // If the frame of the closed window contains the new current window,
3043      // only resize that frame.  Otherwise resize all windows.
3044      win_equal(curwin, curwin->w_frame->fr_parent == win_frame, dir);
3045    } else {
3046      win_comp_pos();
3047      win_fix_scroll(false);
3048    }
3049  } else if (had_cmdline_ruler && wp->w_status_height > 0) {
3050    redraw_cmdline = true;  // clear cmdline 'ruler'
3051  }
3052  if (bufref.br_buf && bufref_valid(&bufref) && bufref.br_buf->terminal) {
3053    terminal_check_size(bufref.br_buf->terminal);
3054  }
3055
3056  if (close_curwin) {
3057    win_enter_ext(wp, WEE_CURWIN_INVALID | WEE_TRIGGER_ENTER_AUTOCMDS
3058                  | WEE_TRIGGER_LEAVE_AUTOCMDS);
3059    if (other_buffer) {
3060      // careful: after this wp and win may be invalid!
3061      apply_autocmds(EVENT_BUFENTER, NULL, NULL, false, curbuf);
3062    }
3063  }
3064
3065  if (ONE_WINDOW && curwin->w_locked && curbuf->b_locked_split
3066      && first_tabpage->tp_next != NULL) {
3067    // The new curwin is the last window in the current tab page, and it is
3068    // already being closed.  Trigger TabLeave now, as after its buffer is
3069    // removed it's no longer safe to do that.
3070    apply_autocmds(EVENT_TABLEAVE, NULL, NULL, false, curbuf);
3071  }
3072
3073  split_disallowed--;
3074
3075  // After closing the help or quickfix window, try restoring the window
3076  // layout from before it was opened.
3077  if (help_window || quickfix_window) {
3078    restore_snapshot(help_window ? SNAP_HELP_IDX : SNAP_QUICKFIX_IDX, close_curwin);
3079  }
3080
3081  // If the window had 'diff' set and now there is only one window left in
3082  // the tab page with 'diff' set, and "closeoff" is in 'diffopt', then
3083  // execute ":diffoff!".
3084  if (diffopt_closeoff() && had_diffmode && curtab == prev_curtab) {
3085    int diffcount = 0;
3086
3087    FOR_ALL_WINDOWS_IN_TAB(dwin, curtab) {
3088      if (dwin->w_p_diff) {
3089        diffcount++;
3090      }
3091    }
3092    if (diffcount == 1) {
3093      do_cmdline_cmd("diffoff!");
3094    }
3095  }
3096
3097  curwin->w_pos_changed = true;
3098  if (!was_floating) {
3099    // TODO(bfredl): how about no?
3100    redraw_all_later(UPD_NOT_VALID);
3101  }
3102  return OK;
3103}
3104
3105static void trigger_winnewpre(void)
3106{
3107  window_layout_lock();
3108  apply_autocmds(EVENT_WINNEWPRE, NULL, NULL, false, NULL);
3109  window_layout_unlock();
3110}
3111
3112static void do_autocmd_winclosed(win_T *win)
3113  FUNC_ATTR_NONNULL_ALL
3114{
3115  static bool recursive = false;
3116  if (recursive || !has_event(EVENT_WINCLOSED)) {
3117    return;
3118  }
3119  recursive = true;
3120  char winid[NUMBUFLEN];
3121  vim_snprintf(winid, sizeof(winid), "%d", win->handle);
3122  apply_autocmds_win(EVENT_WINCLOSED, winid, winid, false, win->w_buffer, win);
3123  recursive = false;
3124}
3125
3126void trigger_tabclosedpre(tabpage_T *tp)
3127{
3128  static bool recursive = false;
3129  tabpage_T *ptp = curtab;
3130
3131  // Quickly return when no TabClosedPre autocommands to be executed or
3132  // already executing
3133  if (!has_event(EVENT_TABCLOSEDPRE) || recursive) {
3134    return;
3135  }
3136
3137  if (valid_tabpage(tp)) {
3138    goto_tabpage_tp(tp, false, false);
3139  }
3140  recursive = true;
3141  window_layout_lock();
3142  apply_autocmds(EVENT_TABCLOSEDPRE, NULL, NULL, false, NULL);
3143  window_layout_unlock();
3144  recursive = false;
3145  // tabpage may have been modified or deleted by autocmds
3146  if (valid_tabpage(ptp)) {
3147    // try to recover the tabpage first
3148    goto_tabpage_tp(ptp, false, false);
3149  } else {
3150    // fall back to the first tabpage
3151    goto_tabpage_tp(first_tabpage, false, false);
3152  }
3153}
3154
3155// Close window "win" in tab page "tp", which is not the current tab page.
3156// This may be the last window in that tab page and result in closing the tab,
3157// thus "tp" may become invalid!
3158// Caller must check if buffer is hidden and whether the tabline needs to be
3159// updated.
3160// @return false when the window was not closed as a direct result of this call
3161//         (e.g: not via autocmds).
3162bool win_close_othertab(win_T *win, int free_buf, tabpage_T *tp, bool force)
3163  FUNC_ATTR_NONNULL_ALL
3164{
3165  assert(tp != curtab);
3166
3167  // Commands that may call win_close_othertab() already check this, but
3168  // check here again just in case.
3169  if (window_layout_locked(CMD_SIZE)) {
3170    return false;
3171  }
3172  // Get here with win->w_buffer == NULL when win_close() detects the tab page
3173  // changed.
3174  if (win_locked(win)
3175      || (win->w_buffer != NULL && win->w_buffer->b_locked > 0)) {
3176    return false;  // window is already being closed
3177  }
3178  if (is_ctx_win(win)) {
3179    emsg(_(e_autocmd_close));
3180    return false;
3181  }
3182
3183  // Check if closing this window would leave only floating windows.
3184  if (tp->tp_lastwin->w_floating && one_window(win, tp)) {
3185    if (force || can_close_floating_windows(tp)) {
3186      // close the last window until the there are no floating windows
3187      while (tp->tp_lastwin->w_floating) {
3188        // `force` flag isn't actually used when closing a floating window.
3189        if (!win_close_othertab(tp->tp_lastwin, !buf_hide(tp->tp_lastwin->w_buffer), tp, true)) {
3190          // If closing the window fails give up, to avoid looping forever.
3191          goto leave_open;
3192        }
3193      }
3194      if (!win_valid_any_tab(win)) {
3195        return false;  // window already closed by autocommands
3196      }
3197    } else {
3198      emsg(e_floatonly);
3199      goto leave_open;
3200    }
3201  }
3202
3203  // Fire WinClosed just before starting to free window-related resources.
3204  // If the buffer is NULL, it isn't safe to trigger autocommands,
3205  // and win_close() should have already triggered WinClosed.
3206  if (win->w_buffer != NULL) {
3207    do_autocmd_winclosed(win);
3208    // autocmd may have freed the window already.
3209    if (!win_valid_any_tab(win)) {
3210      return false;
3211    }
3212  }
3213
3214  if (tp->tp_firstwin == tp->tp_lastwin && !tp->tp_did_tabclosedpre) {
3215    trigger_tabclosedpre(tp);
3216    // autocmd may have freed the window already.
3217    if (!win_valid_any_tab(win)) {
3218      return false;
3219    }
3220  }
3221
3222  bufref_T bufref;
3223  set_bufref(&bufref, win->w_buffer);
3224
3225  if (win->w_buffer != NULL) {
3226    // Close the link to the buffer.
3227    close_buffer(win, win->w_buffer, free_buf ? DOBUF_UNLOAD : 0, false, true, true);
3228  }
3229
3230  // Careful: Autocommands may have closed the tab page or made it the
3231  // current tab page.
3232  if (!valid_tabpage(tp) || tp == curtab) {
3233    goto leave_open;
3234  }
3235  // Autocommands may have closed the window already, or nvim_win_set_config
3236  // moved it to a different tab page.
3237  if (!tabpage_win_valid(tp, win)) {
3238    goto leave_open;
3239  }
3240  // Autocommands may again cause closing this window to leave only floats.
3241  // Check again; we'll not bother closing floating windows this time.
3242  if (tp->tp_lastwin->w_floating && one_window(win, tp)) {
3243    emsg(e_floatonly);
3244    goto leave_open;
3245  }
3246
3247  int free_tp_idx = 0;
3248
3249  // When closing the last window in a tab page remove the tab page.
3250  if (tp->tp_firstwin == tp->tp_lastwin) {
3251    free_tp_idx = tabpage_index(tp);
3252    int h = tabline_height();
3253
3254    if (tp == first_tabpage) {
3255      first_tabpage = tp->tp_next;
3256    } else {
3257      tabpage_T *ptp;
3258      for (ptp = first_tabpage; ptp != NULL && ptp->tp_next != tp;
3259           ptp = ptp->tp_next) {
3260        // loop
3261      }
3262      if (ptp == NULL) {
3263        internal_error("win_close_othertab()");
3264        return false;
3265      }
3266      ptp->tp_next = tp->tp_next;
3267    }
3268    redraw_tabline = true;
3269    if (h != tabline_height()) {
3270      win_new_screen_rows();
3271    }
3272  }
3273
3274  if (ui_has(kUIMultigrid)) {
3275    ui_call_win_close(win->w_grid_alloc.handle);
3276  }
3277  if (win->w_floating) {
3278    ui_comp_remove_grid(&win->w_grid_alloc);
3279  }
3280
3281  // About to free the window. Remember its final buffer for terminal_check_size/TabClosed,
3282  // which may have changed since the last set_bufref. (e.g: close_buffer autocmds)
3283  set_bufref(&bufref, win->w_buffer);
3284
3285  if (win->w_buffer != NULL) {
3286    win->w_buffer->b_nwindows--;
3287  }
3288
3289  // Free the memory used for the window.
3290  int dir;
3291  win_free_mem(win, &dir, tp);
3292
3293  if (bufref.br_buf && bufref_valid(&bufref) && bufref.br_buf->terminal) {
3294    terminal_check_size(bufref.br_buf->terminal);
3295  }
3296  if (free_tp_idx > 0) {
3297    free_tabpage(tp);
3298
3299    if (has_event(EVENT_TABCLOSED)) {
3300      char prev_idx[NUMBUFLEN];
3301      vim_snprintf(prev_idx, NUMBUFLEN, "%i", free_tp_idx);
3302      apply_autocmds(EVENT_TABCLOSED, prev_idx, prev_idx, false,
3303                     bufref.br_buf && bufref_valid(&bufref) ? bufref.br_buf : curbuf);
3304    }
3305  }
3306  return true;
3307
3308leave_open:
3309  if (win_valid_any_tab(win)) {
3310    win_unclose_buffer(win, &bufref);
3311  }
3312  return false;
3313}
3314
3315/// Free the memory used for a window.
3316///
3317/// @param dirp  set to 'v' or 'h' for direction if 'ea'
3318/// @param tp    tab page "win" is in, NULL for current
3319///
3320/// @return      a pointer to the window that got the freed up space.
3321static win_T *win_free_mem(win_T *win, int *dirp, tabpage_T *tp)
3322  FUNC_ATTR_NONNULL_ARG(1)
3323{
3324  win_T *wp;
3325  tabpage_T *win_tp = tp == NULL ? curtab : tp;
3326
3327  if (!win->w_floating) {
3328    // Remove the window and its frame from the tree of frames.
3329    frame_T *frp = win->w_frame;
3330    wp = winframe_remove(win, dirp, tp, NULL);
3331    xfree(frp);
3332  } else {
3333    *dirp = 'h';  // Dummy value.
3334    wp = win_float_find_altwin(win, tp);
3335  }
3336  win_free(win, tp);
3337
3338  // When deleting the current window in the tab, select a new current
3339  // window.
3340  if (win == win_tp->tp_curwin) {
3341    win_tp->tp_curwin = wp;
3342  }
3343  // Avoid executing cmdline_win logic after it is closed.
3344  if (win == cmdline_win) {
3345    cmdline_win = NULL;
3346  }
3347
3348  return wp;
3349}
3350
3351#ifdef EXITFREE
3352void win_free_all(void)
3353{
3354  // avoid an error for switching tabpage with the cmdline window open
3355  cmdwin_type = 0;
3356  cmdwin_buf = NULL;
3357
3358  while (first_tabpage->tp_next != NULL) {
3359    tabpage_close(true);
3360  }
3361
3362  while (lastwin != NULL && lastwin->w_floating) {
3363    win_T *wp = lastwin;
3364    win_remove(lastwin, NULL);
3365    int dummy;
3366    win_free_mem(wp, &dummy, NULL);
3367    for (int i = 0; i < CTX_WIN_COUNT; i++) {
3368      if (ctx_win[i].cw_win == wp) {
3369        ctx_win[i].cw_win = NULL;
3370      }
3371    }
3372  }
3373
3374  for (int i = 0; i < CTX_WIN_COUNT; i++) {
3375    if (ctx_win[i].cw_win != NULL) {
3376      int dummy;
3377      win_free_mem(ctx_win[i].cw_win, &dummy, NULL);
3378      ctx_win[i].cw_win = NULL;
3379    }
3380  }
3381
3382  kv_destroy(ctx_win_vec);
3383
3384  while (firstwin != NULL) {
3385    int dummy;
3386    win_free_mem(firstwin, &dummy, NULL);
3387  }
3388
3389  // No window should be used after this. Set curwin to NULL to crash
3390  // instead of using freed memory.
3391  curwin = NULL;
3392}
3393
3394#endif
3395
3396/// Remove a window and its frame from the tree of frames.
3397///
3398/// @param dirp  set to 'v' or 'h' for direction if 'ea'
3399/// @param tp    tab page "win" is in, NULL for current
3400/// @param unflat_altfr if not NULL, set to pointer of frame that got
3401///                     the space, and it is not flattened
3402///
3403/// @return      a pointer to the window that got the freed up space.
3404win_T *winframe_remove(win_T *win, int *dirp, tabpage_T *tp, frame_T **unflat_altfr)
3405  FUNC_ATTR_NONNULL_ARG(1, 2)
3406{
3407  frame_T *altfr;
3408  win_T *wp = winframe_find_altwin(win, dirp, tp, &altfr);
3409  if (wp == NULL) {
3410    return NULL;
3411  }
3412
3413  frame_T *frp_close = win->w_frame;
3414
3415  frame_locked++;
3416
3417  // Save the position of the containing frame (which will also contain the
3418  // altframe) before we remove anything, to recompute window positions later.
3419  const win_T *const topleft = frame2win(frp_close->fr_parent);
3420  int row = topleft->w_winrow;
3421  int col = topleft->w_wincol;
3422
3423  // If this is a rightmost window, remove vertical separators to the left.
3424  if (win->w_vsep_width == 0 && frp_close->fr_parent->fr_layout == FR_ROW
3425      && frp_close->fr_prev != NULL) {
3426    frame_set_vsep(frp_close->fr_prev, false);
3427  }
3428
3429  // Remove this frame from the list of frames.
3430  frame_remove(frp_close);
3431
3432  if (*dirp == 'v') {
3433    frame_new_height(altfr, altfr->fr_height + frp_close->fr_height,
3434                     altfr == frp_close->fr_next, false, false);
3435  } else {
3436    assert(*dirp == 'h');
3437    frame_new_width(altfr, altfr->fr_width + frp_close->fr_width,
3438                    altfr == frp_close->fr_next, false);
3439  }
3440
3441  // If the altframe wasn't adjacent and left/above, resizing it will have
3442  // changed window positions within the parent frame.  Recompute them.
3443  if (altfr != frp_close->fr_prev) {
3444    frame_comp_pos(frp_close->fr_parent, &row, &col);
3445  }
3446
3447  if (unflat_altfr == NULL) {
3448    frame_flatten(altfr);
3449  } else {
3450    *unflat_altfr = altfr;
3451  }
3452
3453  frame_locked--;
3454
3455  return wp;
3456}
3457
3458/// Find the window that will get the freed space from a call to `winframe_remove`.
3459/// Makes no changes to the window layout.
3460///
3461/// @param dirp  set to 'v' or 'h' for the direction where "altfr" will be resized
3462///              to fill the space
3463/// @param tp    tab page "win" is in, NULL for current
3464/// @param altfr if not NULL, set to pointer of frame that will get the space
3465///
3466/// @return      a pointer to the window that will get the freed up space, or NULL
3467///              if there is no other non-float to receive the space.
3468win_T *winframe_find_altwin(win_T *win, int *dirp, tabpage_T *tp, frame_T **altfr)
3469  FUNC_ATTR_NONNULL_ARG(1, 2)
3470{
3471  assert(tp == NULL || tp != curtab);
3472
3473  // If there is only one non-floating window there is nothing to remove.
3474  if (one_window(win, tp)) {
3475    return NULL;
3476  }
3477
3478  frame_T *frp_close = win->w_frame;
3479
3480  // Find the window and frame that gets the space.
3481  frame_T *frp2 = win_altframe(win, tp);
3482  win_T *wp = frame2win(frp2);
3483
3484  if (frp_close->fr_parent->fr_layout == FR_COL) {
3485    // When 'winfixheight' is set, try to find another frame in the column
3486    // (as close to the closed frame as possible) to distribute the height
3487    // to.
3488    if (frp2->fr_win != NULL && frp2->fr_win->w_p_wfh) {
3489      frame_T *frp = frp_close->fr_prev;
3490      frame_T *frp3 = frp_close->fr_next;
3491      while (frp != NULL || frp3 != NULL) {
3492        if (frp != NULL) {
3493          if (!frame_fixed_height(frp)) {
3494            frp2 = frp;
3495            wp = frame2win(frp2);
3496            break;
3497          }
3498          frp = frp->fr_prev;
3499        }
3500        if (frp3 != NULL) {
3501          if (frp3->fr_win != NULL && !frp3->fr_win->w_p_wfh) {
3502            frp2 = frp3;
3503            wp = frp3->fr_win;
3504            break;
3505          }
3506          frp3 = frp3->fr_next;
3507        }
3508      }
3509    }
3510    *dirp = 'v';
3511  } else {
3512    // When 'winfixwidth' is set, try to find another frame in the column
3513    // (as close to the closed frame as possible) to distribute the width
3514    // to.
3515    if (frp2->fr_win != NULL && frp2->fr_win->w_p_wfw) {
3516      frame_T *frp = frp_close->fr_prev;
3517      frame_T *frp3 = frp_close->fr_next;
3518      while (frp != NULL || frp3 != NULL) {
3519        if (frp != NULL) {
3520          if (!frame_fixed_width(frp)) {
3521            frp2 = frp;
3522            wp = frame2win(frp2);
3523            break;
3524          }
3525          frp = frp->fr_prev;
3526        }
3527        if (frp3 != NULL) {
3528          if (frp3->fr_win != NULL && !frp3->fr_win->w_p_wfw) {
3529            frp2 = frp3;
3530            wp = frp3->fr_win;
3531            break;
3532          }
3533          frp3 = frp3->fr_next;
3534        }
3535      }
3536    }
3537    *dirp = 'h';
3538  }
3539
3540  assert(wp != win && frp2 != frp_close);
3541  if (altfr != NULL) {
3542    *altfr = frp2;
3543  }
3544
3545  return wp;
3546}
3547
3548/// Flatten "frp" into its parent frame if it's the only child, also merging its
3549/// list with the grandparent if they share the same layout.
3550/// Frees "frp" if flattened; also "frp->fr_parent" if it has the same layout.
3551static void frame_flatten(frame_T *frp)
3552  FUNC_ATTR_NONNULL_ALL
3553{
3554  if (frp->fr_next != NULL || frp->fr_prev != NULL) {
3555    return;
3556  }
3557
3558  // There is no other frame in this list, move its info to the parent
3559  // and remove it.
3560  frp->fr_parent->fr_layout = frp->fr_layout;
3561  frp->fr_parent->fr_child = frp->fr_child;
3562  frame_T *frp2;
3563  FOR_ALL_FRAMES(frp2, frp->fr_child) {
3564    frp2->fr_parent = frp->fr_parent;
3565  }
3566  frp->fr_parent->fr_win = frp->fr_win;
3567  if (frp->fr_win != NULL) {
3568    frp->fr_win->w_frame = frp->fr_parent;
3569  }
3570  frp2 = frp->fr_parent;
3571  if (topframe->fr_child == frp) {
3572    topframe->fr_child = frp2;
3573  }
3574  xfree(frp);
3575
3576  frp = frp2->fr_parent;
3577  if (frp != NULL && frp->fr_layout == frp2->fr_layout) {
3578    // The frame above the parent has the same layout, have to merge
3579    // the frames into this list.
3580    if (frp->fr_child == frp2) {
3581      frp->fr_child = frp2->fr_child;
3582    }
3583    assert(frp2->fr_child);
3584    frp2->fr_child->fr_prev = frp2->fr_prev;
3585    if (frp2->fr_prev != NULL) {
3586      frp2->fr_prev->fr_next = frp2->fr_child;
3587    }
3588    for (frame_T *frp3 = frp2->fr_child;; frp3 = frp3->fr_next) {
3589      frp3->fr_parent = frp;
3590      if (frp3->fr_next == NULL) {
3591        frp3->fr_next = frp2->fr_next;
3592        if (frp2->fr_next != NULL) {
3593          frp2->fr_next->fr_prev = frp3;
3594        }
3595        break;
3596      }
3597    }
3598    if (topframe->fr_child == frp2) {
3599      topframe->fr_child = frp;
3600    }
3601    xfree(frp2);
3602  }
3603}
3604
3605/// Undo changes from a prior call to winframe_remove, also restoring lost
3606/// vertical separators and statuslines, and changed window positions for
3607/// windows within "unflat_altfr".
3608/// Caller must ensure no other changes were made to the layout or window sizes!
3609void winframe_restore(win_T *wp, int dir, frame_T *unflat_altfr)
3610  FUNC_ATTR_NONNULL_ALL
3611{
3612  frame_T *frp = wp->w_frame;
3613
3614  // Put "wp"'s frame back where it was.
3615  if (frp->fr_prev != NULL) {
3616    frame_append(frp->fr_prev, frp);
3617  } else {
3618    frame_insert(frp->fr_next, frp);
3619  }
3620
3621  // Vertical separators to the left may have been lost.  Restore them.
3622  if (wp->w_vsep_width == 0 && frp->fr_parent->fr_layout == FR_ROW && frp->fr_prev != NULL) {
3623    frame_set_vsep(frp->fr_prev, true);
3624  }
3625
3626  // Statuslines or horizontal separators above may have been lost.  Restore them.
3627  if (frp->fr_parent->fr_layout == FR_COL && frp->fr_prev != NULL) {
3628    if (global_stl_height() == 0 && wp->w_status_height == 0) {
3629      frame_add_statusline(frp->fr_prev);
3630    } else if (global_stl_height() > 0 && wp->w_hsep_height == 0) {
3631      frame_add_hsep(frp->fr_prev);
3632    }
3633  }
3634
3635  // Restore the lost room that was redistributed to the altframe.  Also
3636  // adjusts window sizes to fit restored statuslines/separators, if needed.
3637  if (dir == 'v') {
3638    frame_new_height(unflat_altfr, unflat_altfr->fr_height - frp->fr_height,
3639                     unflat_altfr == frp->fr_next, false, false);
3640  } else if (dir == 'h') {
3641    frame_new_width(unflat_altfr, unflat_altfr->fr_width - frp->fr_width,
3642                    unflat_altfr == frp->fr_next, false);
3643  }
3644
3645  // Recompute window positions within the parent frame to restore them.
3646  // Positions were unchanged if the altframe was adjacent and left/above.
3647  if (unflat_altfr != frp->fr_prev) {
3648    const win_T *const topleft = frame2win(frp->fr_parent);
3649    int row = topleft->w_winrow;
3650    int col = topleft->w_wincol;
3651
3652    frame_comp_pos(frp->fr_parent, &row, &col);
3653  }
3654}
3655
3656/// If 'splitbelow' or 'splitright' is set, the space goes above or to the left
3657/// by default.  Otherwise, the free space goes below or to the right.  The
3658/// result is that opening a window and then immediately closing it will
3659/// preserve the initial window layout.  The 'wfh' and 'wfw' settings are
3660/// respected when possible.
3661///
3662/// @param  tp  tab page "win" is in, NULL for current
3663///
3664/// @return a pointer to the frame that will receive the empty screen space that
3665/// is left over after "win" is closed.
3666static frame_T *win_altframe(win_T *win, tabpage_T *tp)
3667  FUNC_ATTR_NONNULL_ARG(1)
3668{
3669  assert(tp == NULL || tp != curtab);
3670
3671  if (one_window(win, tp)) {
3672    return alt_tabpage()->tp_curwin->w_frame;
3673  }
3674
3675  frame_T *frp = win->w_frame;
3676
3677  if (frp->fr_prev == NULL) {
3678    return frp->fr_next;
3679  }
3680  if (frp->fr_next == NULL) {
3681    return frp->fr_prev;
3682  }
3683
3684  // By default the next window will get the space that was abandoned by this
3685  // window
3686  frame_T *target_fr = frp->fr_next;
3687  frame_T *other_fr = frp->fr_prev;
3688
3689  // If this is part of a column of windows and 'splitbelow' is true then the
3690  // previous window will get the space.
3691  if (frp->fr_parent != NULL && frp->fr_parent->fr_layout == FR_COL && p_sb) {
3692    target_fr = frp->fr_prev;
3693    other_fr = frp->fr_next;
3694  }
3695
3696  // If this is part of a row of windows, and 'splitright' is true then the
3697  // previous window will get the space.
3698  if (frp->fr_parent != NULL && frp->fr_parent->fr_layout == FR_ROW && p_spr) {
3699    target_fr = frp->fr_prev;
3700    other_fr = frp->fr_next;
3701  }
3702
3703  // If 'wfh' or 'wfw' is set for the target and not for the alternate
3704  // window, reverse the selection.
3705  if (frp->fr_parent != NULL && frp->fr_parent->fr_layout == FR_ROW) {
3706    if (frame_fixed_width(target_fr) && !frame_fixed_width(other_fr)) {
3707      target_fr = other_fr;
3708    }
3709  } else {
3710    if (frame_fixed_height(target_fr) && !frame_fixed_height(other_fr)) {
3711      target_fr = other_fr;
3712    }
3713  }
3714
3715  return target_fr;
3716}
3717
3718// Return the tabpage that will be used if the current one is closed.
3719static tabpage_T *alt_tabpage(void)
3720{
3721  // Use the last accessed tab page, if possible.
3722  if ((tcl_flags & kOptTclFlagUselast) && valid_tabpage(lastused_tabpage)) {
3723    return lastused_tabpage;
3724  }
3725
3726  // Use the next tab page, if possible.
3727  bool forward = curtab->tp_next != NULL
3728                 && ((tcl_flags & kOptTclFlagLeft) == 0 || curtab == first_tabpage);
3729
3730  tabpage_T *tp;
3731  if (forward) {
3732    tp = curtab->tp_next;
3733  } else {
3734    // Use the previous tab page.
3735    for (tp = first_tabpage; tp->tp_next != curtab; tp = tp->tp_next) {}
3736  }
3737
3738  return tp;
3739}
3740
3741// Find the left-upper window in frame "frp".
3742win_T *frame2win(frame_T *frp)
3743  FUNC_ATTR_NONNULL_ALL
3744{
3745  while (frp->fr_win == NULL) {
3746    frp = frp->fr_child;
3747  }
3748  return frp->fr_win;
3749}
3750
3751/// Check that the frame "frp" contains the window "wp".
3752///
3753/// @param  frp  frame
3754/// @param  wp   window
3755static bool frame_has_win(const frame_T *frp, const win_T *wp)
3756  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1)
3757{
3758  if (frp->fr_layout == FR_LEAF) {
3759    return frp->fr_win == wp;
3760  }
3761  const frame_T *p;
3762  FOR_ALL_FRAMES(p, frp->fr_child) {
3763    if (frame_has_win(p, wp)) {
3764      return true;
3765    }
3766  }
3767  return false;
3768}
3769
3770/// Check if current window is at the bottom
3771/// Returns true if there are no windows below current window
3772static bool is_bottom_win(win_T *wp)
3773  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
3774{
3775  for (frame_T *frp = wp->w_frame; frp->fr_parent != NULL; frp = frp->fr_parent) {
3776    if (frp->fr_parent->fr_layout == FR_COL && frp->fr_next != NULL) {
3777      return false;
3778    }
3779  }
3780  return true;
3781}
3782
3783/// Set a new height for a frame.  Recursively sets the height for contained
3784/// frames and windows.  Caller must take care of positions.
3785///
3786/// @param topfirst  resize topmost contained frame first.
3787/// @param wfh       obey 'winfixheight' when there is a choice;
3788///                  may cause the height not to be set.
3789/// @param set_ch    set 'cmdheight' to resize topframe.
3790void frame_new_height(frame_T *topfrp, int height, bool topfirst, bool wfh, bool set_ch)
3791  FUNC_ATTR_NONNULL_ALL
3792{
3793  if (topfrp->fr_parent == NULL && set_ch) {
3794    // topframe: update the command line height, with side effects.
3795    OptInt new_ch = MAX(min_set_ch, p_ch + topfrp->fr_height - height);
3796    if (new_ch != p_ch) {
3797      const OptInt save_ch = min_set_ch;
3798      set_option_value(kOptCmdheight, INTEGER_OBJ(new_ch), 0, true, NULL);
3799      min_set_ch = save_ch;
3800    }
3801    height = (int)MIN(ROWS_AVAIL, height);
3802  }
3803  if (topfrp->fr_win != NULL) {
3804    // Simple case: just one window.
3805    win_T *wp = topfrp->fr_win;
3806    if (is_bottom_win(wp)) {
3807      wp->w_hsep_height = 0;
3808    }
3809    win_new_height(wp, height - wp->w_hsep_height - wp->w_status_height);
3810  } else if (topfrp->fr_layout == FR_ROW) {
3811    frame_T *frp;
3812    do {
3813      // All frames in this row get the same new height.
3814      FOR_ALL_FRAMES(frp, topfrp->fr_child) {
3815        frame_new_height(frp, height, topfirst, wfh, set_ch);
3816        if (frp->fr_height > height) {
3817          // Could not fit the windows, make the whole row higher.
3818          height = frp->fr_height;
3819          break;
3820        }
3821      }
3822    } while (frp != NULL);
3823  } else {  // fr_layout == FR_COL
3824    // Complicated case: Resize a column of frames.  Resize the bottom
3825    // frame first, frames above that when needed.
3826
3827    frame_T *frp = topfrp->fr_child;
3828    if (wfh) {
3829      // Advance past frames with one window with 'wfh' set.
3830      while (frame_fixed_height(frp)) {
3831        frp = frp->fr_next;
3832        if (frp == NULL) {
3833          return;                   // no frame without 'wfh', give up
3834        }
3835      }
3836    }
3837    if (!topfirst) {
3838      // Find the bottom frame of this column
3839      while (frp->fr_next != NULL) {
3840        frp = frp->fr_next;
3841      }
3842      if (wfh) {
3843        // Advance back for frames with one window with 'wfh' set.
3844        while (frame_fixed_height(frp)) {
3845          frp = frp->fr_prev;
3846        }
3847      }
3848    }
3849
3850    int extra_lines = height - topfrp->fr_height;
3851    if (extra_lines < 0) {
3852      // reduce height of contained frames, bottom or top frame first
3853      while (frp != NULL) {
3854        int h = frame_minheight(frp, NULL);
3855        if (frp->fr_height + extra_lines < h) {
3856          extra_lines += frp->fr_height - h;
3857          frame_new_height(frp, h, topfirst, wfh, set_ch);
3858        } else {
3859          frame_new_height(frp, frp->fr_height + extra_lines, topfirst, wfh, set_ch);
3860          break;
3861        }
3862        if (topfirst) {
3863          do {
3864            frp = frp->fr_next;
3865          } while (wfh && frp != NULL && frame_fixed_height(frp));
3866        } else {
3867          do {
3868            frp = frp->fr_prev;
3869          } while (wfh && frp != NULL && frame_fixed_height(frp));
3870        }
3871        // Increase "height" if we could not reduce enough frames.
3872        if (frp == NULL) {
3873          height -= extra_lines;
3874        }
3875      }
3876    } else if (extra_lines > 0) {
3877      // increase height of bottom or top frame
3878      frame_new_height(frp, frp->fr_height + extra_lines, topfirst, wfh, set_ch);
3879    }
3880  }
3881  topfrp->fr_height = height;
3882}
3883
3884/// Return true if height of frame "frp" should not be changed because of
3885/// the 'winfixheight' option.
3886///
3887/// @param  frp  frame
3888///
3889/// @return true if the frame has a fixed height
3890static bool frame_fixed_height(frame_T *frp)
3891  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
3892{
3893  // frame with one window: fixed height if 'winfixheight' set.
3894  if (frp->fr_win != NULL) {
3895    return frp->fr_win->w_p_wfh;
3896  }
3897  if (frp->fr_layout == FR_ROW) {
3898    // The frame is fixed height if one of the frames in the row is fixed
3899    // height.
3900    FOR_ALL_FRAMES(frp, frp->fr_child) {
3901      if (frame_fixed_height(frp)) {
3902        return true;
3903      }
3904    }
3905    return false;
3906  }
3907
3908  // frp->fr_layout == FR_COL: The frame is fixed height if all of the
3909  // frames in the row are fixed height.
3910  FOR_ALL_FRAMES(frp, frp->fr_child) {
3911    if (!frame_fixed_height(frp)) {
3912      return false;
3913    }
3914  }
3915  return true;
3916}
3917
3918/// Return true if width of frame "frp" should not be changed because of
3919/// the 'winfixwidth' option.
3920///
3921/// @param  frp  frame
3922///
3923/// @return true if the frame has a fixed width
3924static bool frame_fixed_width(frame_T *frp)
3925  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
3926{
3927  // frame with one window: fixed width if 'winfixwidth' set.
3928  if (frp->fr_win != NULL) {
3929    return frp->fr_win->w_p_wfw;
3930  }
3931  if (frp->fr_layout == FR_COL) {
3932    // The frame is fixed width if one of the frames in the row is fixed
3933    // width.
3934    FOR_ALL_FRAMES(frp, frp->fr_child) {
3935      if (frame_fixed_width(frp)) {
3936        return true;
3937      }
3938    }
3939    return false;
3940  }
3941
3942  // frp->fr_layout == FR_ROW: The frame is fixed width if all of the
3943  // frames in the row are fixed width.
3944  FOR_ALL_FRAMES(frp, frp->fr_child) {
3945    if (!frame_fixed_width(frp)) {
3946      return false;
3947    }
3948  }
3949  return true;
3950}
3951
3952// Add a status line to windows at the bottom of "frp".
3953// Note: Does not check if there is room!
3954static void frame_add_statusline(frame_T *frp)
3955{
3956  if (frp->fr_layout == FR_LEAF) {
3957    win_T *wp = frp->fr_win;
3958    wp->w_status_height = STATUS_HEIGHT;
3959  } else if (frp->fr_layout == FR_ROW) {
3960    // Handle all the frames in the row.
3961    FOR_ALL_FRAMES(frp, frp->fr_child) {
3962      frame_add_statusline(frp);
3963    }
3964  } else {
3965    assert(frp->fr_layout == FR_COL);
3966    // Only need to handle the last frame in the column.
3967    for (frp = frp->fr_child; frp->fr_next != NULL; frp = frp->fr_next) {}
3968    frame_add_statusline(frp);
3969  }
3970}
3971
3972/// Set width of a frame.  Handles recursively going through contained frames.
3973/// May remove separator line for windows at the right side (for win_close()).
3974///
3975/// @param leftfirst  resize leftmost contained frame first.
3976/// @param wfw        obey 'winfixwidth' when there is a choice;
3977///                   may cause the width not to be set.
3978static void frame_new_width(frame_T *topfrp, int width, bool leftfirst, bool wfw)
3979{
3980  if (topfrp->fr_layout == FR_LEAF) {
3981    // Simple case: just one window.
3982    win_T *wp = topfrp->fr_win;
3983    // Find out if there are any windows right of this one.
3984    frame_T *frp;
3985    for (frp = topfrp; frp->fr_parent != NULL; frp = frp->fr_parent) {
3986      if (frp->fr_parent->fr_layout == FR_ROW && frp->fr_next != NULL) {
3987        break;
3988      }
3989    }
3990    if (frp->fr_parent == NULL) {
3991      wp->w_vsep_width = 0;
3992    }
3993    win_new_width(wp, width - wp->w_vsep_width);
3994  } else if (topfrp->fr_layout == FR_COL) {
3995    frame_T *frp;
3996    do {
3997      // All frames in this column get the same new width.
3998      FOR_ALL_FRAMES(frp, topfrp->fr_child) {
3999        frame_new_width(frp, width, leftfirst, wfw);
4000        if (frp->fr_width > width) {
4001          // Could not fit the windows, make whole column wider.
4002          width = frp->fr_width;
4003          break;
4004        }
4005      }
4006    } while (frp != NULL);
4007  } else {  // fr_layout == FR_ROW
4008    // Complicated case: Resize a row of frames.  Resize the rightmost
4009    // frame first, frames left of it when needed.
4010
4011    frame_T *frp = topfrp->fr_child;
4012    if (wfw) {
4013      // Advance past frames with one window with 'wfw' set.
4014      while (frame_fixed_width(frp)) {
4015        frp = frp->fr_next;
4016        if (frp == NULL) {
4017          return;                   // no frame without 'wfw', give up
4018        }
4019      }
4020    }
4021    if (!leftfirst) {
4022      // Find the rightmost frame of this row
4023      while (frp->fr_next != NULL) {
4024        frp = frp->fr_next;
4025      }
4026      if (wfw) {
4027        // Advance back for frames with one window with 'wfw' set.
4028        while (frame_fixed_width(frp)) {
4029          frp = frp->fr_prev;
4030        }
4031      }
4032    }
4033
4034    int extra_cols = width - topfrp->fr_width;
4035    if (extra_cols < 0) {
4036      // reduce frame width, rightmost frame first
4037      while (frp != NULL) {
4038        int w = frame_minwidth(frp, NULL);
4039        if (frp->fr_width + extra_cols < w) {
4040          extra_cols += frp->fr_width - w;
4041          frame_new_width(frp, w, leftfirst, wfw);
4042        } else {
4043          frame_new_width(frp, frp->fr_width + extra_cols,
4044                          leftfirst, wfw);
4045          break;
4046        }
4047        if (leftfirst) {
4048          do {
4049            frp = frp->fr_next;
4050          } while (wfw && frp != NULL && frame_fixed_width(frp));
4051        } else {
4052          do {
4053            frp = frp->fr_prev;
4054          } while (wfw && frp != NULL && frame_fixed_width(frp));
4055        }
4056        // Increase "width" if we could not reduce enough frames.
4057        if (frp == NULL) {
4058          width -= extra_cols;
4059        }
4060      }
4061    } else if (extra_cols > 0) {
4062      // increase width of rightmost frame
4063      frame_new_width(frp, frp->fr_width + extra_cols, leftfirst, wfw);
4064    }
4065  }
4066  topfrp->fr_width = width;
4067}
4068
4069/// Add or remove the vertical separator of windows to the right side of "frp".
4070/// Note: Does not check if there is room!
4071static void frame_set_vsep(const frame_T *frp, bool add)
4072  FUNC_ATTR_NONNULL_ARG(1)
4073{
4074  if (frp->fr_layout == FR_LEAF) {
4075    win_T *wp = frp->fr_win;
4076    if (add && wp->w_vsep_width == 0) {
4077      if (wp->w_width > 0) {            // don't make it negative
4078        win_new_width(wp, wp->w_width - 1);
4079      }
4080      wp->w_vsep_width = 1;
4081    } else if (!add && wp->w_vsep_width == 1) {
4082      win_new_width(wp, wp->w_width + 1);
4083      wp->w_vsep_width = 0;
4084    }
4085  } else if (frp->fr_layout == FR_COL) {
4086    // Handle all the frames in the column.
4087    FOR_ALL_FRAMES(frp, frp->fr_child) {
4088      frame_set_vsep(frp, add);
4089    }
4090  } else {
4091    assert(frp->fr_layout == FR_ROW);
4092    // Only need to handle the last frame in the row.
4093    frp = frp->fr_child;
4094    while (frp->fr_next != NULL) {
4095      frp = frp->fr_next;
4096    }
4097    frame_set_vsep(frp, add);
4098  }
4099}
4100
4101/// Add the horizontal separator to windows at the bottom of "frp".
4102/// Note: Does not check if there is room or whether the windows have a statusline!
4103static void frame_add_hsep(const frame_T *frp)
4104  FUNC_ATTR_NONNULL_ARG(1)
4105{
4106  if (frp->fr_layout == FR_LEAF) {
4107    win_T *wp = frp->fr_win;
4108    wp->w_hsep_height = 1;
4109  } else if (frp->fr_layout == FR_ROW) {
4110    // Handle all the frames in the row.
4111    FOR_ALL_FRAMES(frp, frp->fr_child) {
4112      frame_add_hsep(frp);
4113    }
4114  } else {
4115    assert(frp->fr_layout == FR_COL);
4116    // Only need to handle the last frame in the column.
4117    frp = frp->fr_child;
4118    while (frp->fr_next != NULL) {
4119      frp = frp->fr_next;
4120    }
4121    frame_add_hsep(frp);
4122  }
4123}
4124
4125// Set frame width from the window it contains.
4126static void frame_fix_width(win_T *wp)
4127{
4128  wp->w_frame->fr_width = wp->w_width + wp->w_vsep_width;
4129}
4130
4131// Set frame height from the window it contains.
4132static void frame_fix_height(win_T *wp)
4133  FUNC_ATTR_NONNULL_ALL
4134{
4135  wp->w_frame->fr_height = wp->w_height + wp->w_hsep_height + wp->w_status_height;
4136}
4137
4138/// Compute the minimal height for frame "topfrp". Uses the 'winminheight' option.
4139/// When "next_curwin" isn't NULL, use p_wh for this window.
4140/// When "next_curwin" is NOWIN, don't use at least one line for the current window.
4141static int frame_minheight(frame_T *topfrp, win_T *next_curwin)
4142{
4143  int m;
4144
4145  if (topfrp->fr_win != NULL) {
4146    // Combined height of window bar and separator column or status line.
4147    int extra_height = topfrp->fr_win->w_winbar_height + topfrp->fr_win->w_hsep_height
4148                       + topfrp->fr_win->w_status_height;
4149
4150    if (topfrp->fr_win == next_curwin) {
4151      m = (int)p_wh + extra_height;
4152    } else {
4153      m = (int)p_wmh + extra_height;
4154      if (topfrp->fr_win == curwin && next_curwin == NULL) {
4155        // Current window is minimal one line high.
4156        if (p_wmh == 0) {
4157          m++;
4158        }
4159      }
4160    }
4161  } else if (topfrp->fr_layout == FR_ROW) {
4162    // get the minimal height from each frame in this row
4163    m = 0;
4164    frame_T *frp;
4165    FOR_ALL_FRAMES(frp, topfrp->fr_child) {
4166      int n = frame_minheight(frp, next_curwin);
4167      if (n > m) {
4168        m = n;
4169      }
4170    }
4171  } else {
4172    // Add up the minimal heights for all frames in this column.
4173    m = 0;
4174    frame_T *frp;
4175    FOR_ALL_FRAMES(frp, topfrp->fr_child) {
4176      m += frame_minheight(frp, next_curwin);
4177    }
4178  }
4179
4180  return m;
4181}
4182
4183/// Compute the minimal width for frame "topfrp".
4184/// When "next_curwin" isn't NULL, use p_wiw for this window.
4185/// When "next_curwin" is NOWIN, don't use at least one column for the current
4186/// window.
4187///
4188/// @param next_curwin  use p_wh and p_wiw for next_curwin
4189static int frame_minwidth(frame_T *topfrp, win_T *next_curwin)
4190{
4191  int m;
4192
4193  if (topfrp->fr_win != NULL) {
4194    if (topfrp->fr_win == next_curwin) {
4195      m = (int)p_wiw + topfrp->fr_win->w_vsep_width;
4196    } else {
4197      // window: minimal width of the window plus separator column
4198      m = (int)p_wmw + topfrp->fr_win->w_vsep_width;
4199      // Current window is minimal one column wide
4200      if (p_wmw == 0 && topfrp->fr_win == curwin && next_curwin == NULL) {
4201        m++;
4202      }
4203    }
4204  } else if (topfrp->fr_layout == FR_COL) {
4205    // get the minimal width from each frame in this column
4206    m = 0;
4207    frame_T *frp;
4208    FOR_ALL_FRAMES(frp, topfrp->fr_child) {
4209      int n = frame_minwidth(frp, next_curwin);
4210      m = MAX(m, n);
4211    }
4212  } else {
4213    // Add up the minimal widths for all frames in this row.
4214    m = 0;
4215    frame_T *frp;
4216    FOR_ALL_FRAMES(frp, topfrp->fr_child) {
4217      m += frame_minwidth(frp, next_curwin);
4218    }
4219  }
4220
4221  return m;
4222}
4223
4224/// Try to close all windows except current one.
4225/// Buffers in the other windows become hidden if 'hidden' is set, or '!' is
4226/// used and the buffer was modified.
4227///
4228/// Used by ":tabclose" and ":only".
4229///
4230/// @param message       if true, display error messages
4231/// @param forceit       always hide all other windows
4232/// @param ignore_pinned if true, also close pinned windows (for :tabclose)
4233void close_others(int message, int forceit, bool ignore_pinned)
4234{
4235  win_T *const old_curwin = curwin;
4236
4237  if (curwin->w_floating) {
4238    if (message && !autocmd_busy) {
4239      emsg(e_floatonly);
4240    }
4241    return;
4242  }
4243
4244  if (one_window(firstwin, NULL) && !lastwin->w_floating) {
4245    if (message && !autocmd_busy) {
4246      msg(_(m_onlyone), 0);
4247    }
4248    return;
4249  }
4250
4251  // Be very careful here: autocommands may change the window layout.
4252  win_T *nextwp;
4253  for (win_T *wp = firstwin; win_valid(wp); wp = nextwp) {
4254    nextwp = wp->w_next;
4255
4256    // autocommands messed this one up
4257    if (old_curwin != curwin && win_valid(old_curwin)) {
4258      curwin = old_curwin;
4259      curbuf = curwin->w_buffer;
4260    }
4261
4262    // don't close current window or pinned windows
4263    if (wp == curwin || (wp->w_p_wp && !ignore_pinned)) {
4264      continue;
4265    }
4266
4267    // autoccommands messed this one up
4268    if (!buf_valid(wp->w_buffer) && win_valid(wp)) {
4269      wp->w_buffer = NULL;
4270      win_close(wp, false, false);
4271      continue;
4272    }
4273    // Check if it's allowed to abandon this window
4274    int r = can_abandon(wp->w_buffer, forceit);
4275    if (!win_valid(wp)) {             // autocommands messed wp up
4276      nextwp = firstwin;
4277      continue;
4278    }
4279    if (!r) {
4280      if (message && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) && p_write) {
4281        dialog_changed(wp->w_buffer, false);
4282        if (!win_valid(wp)) {                 // autocommands messed wp up
4283          nextwp = firstwin;
4284          continue;
4285        }
4286      }
4287      if (bufIsChanged(wp->w_buffer)) {
4288        continue;
4289      }
4290    }
4291    win_close(wp, !buf_hide(wp->w_buffer) && !bufIsChanged(wp->w_buffer), false);
4292  }
4293
4294  if (message && !ONE_WINDOW) {
4295    // Check if remaining windows are non-pinned
4296    bool has_non_pinned = false;
4297    for (win_T *wp = firstwin; wp != NULL; wp = wp->w_next) {
4298      if (wp != curwin && !wp->w_p_wp) {
4299        has_non_pinned = true;
4300        break;
4301      }
4302    }
4303    if (has_non_pinned) {
4304      emsg(_("E445: Other window contains changes"));
4305    }
4306  }
4307}
4308
4309/// Store the relevant window pointers for tab page "tp".  To be used before
4310/// use_tabpage().
4311void unuse_tabpage(tabpage_T *tp)
4312{
4313  tp->tp_topframe = topframe;
4314  tp->tp_firstwin = firstwin;
4315  tp->tp_lastwin = lastwin;
4316  tp->tp_curwin = curwin;
4317  // Set this tab's stored cmdheight so use_tabpage() can restore it later.
4318  // command_height() and win_new_screen_rows() also keep tp_ch_used in sync for the current tab
4319  // between tab switches; this catches the no-display ctx_switch() path which bypasses them.
4320  tp->tp_ch_used = p_ch;
4321}
4322
4323// When switching tabpage, handle other side-effects in command_height(), but
4324// avoid setting frame sizes which are still correct.
4325static bool command_frame_height = true;
4326
4327/// Set the relevant pointers to use tab page "tp".  May want to call
4328/// unuse_tabpage() first.
4329void use_tabpage(tabpage_T *tp)
4330{
4331  curtab = tp;
4332  topframe = curtab->tp_topframe;
4333  firstwin = curtab->tp_firstwin;
4334  lastwin = curtab->tp_lastwin;
4335  curwin = curtab->tp_curwin;
4336  // Restore this tab's cmdheight. Layout adjustment (OptionSet, frame resize) is the caller's
4337  // responsibility, see enter_tabpage().
4338  p_ch = curtab->tp_ch_used;
4339}
4340
4341// Allocate the first window and put an empty buffer in it.
4342// Only called from main().
4343void win_alloc_first(void)
4344{
4345  if (win_alloc_firstwin(NULL) == FAIL) {
4346    // allocating first buffer before any autocmds should not fail.
4347    abort();
4348  }
4349
4350  first_tabpage = alloc_tabpage();
4351  curtab = first_tabpage;
4352  unuse_tabpage(first_tabpage);
4353}
4354
4355// Init `ctx_win[idx]`. This can only be done after the first window
4356// is fully initialized, thus it can't be in win_alloc_first().
4357void win_alloc_ctx_win(int idx)
4358{
4359  Error err = ERROR_INIT;
4360  WinConfig fconfig = WIN_CONFIG_INIT;
4361  fconfig.width = Columns;
4362  fconfig.height = 5;
4363  fconfig.focusable = false;
4364  fconfig.mouse = false;
4365  fconfig.hide = true;
4366  ctx_win[idx].cw_win = win_new_float(NULL, true, fconfig, &err);
4367  ctx_win[idx].cw_win->w_buffer->b_nwindows--;
4368  RESET_BINDING(ctx_win[idx].cw_win);
4369}
4370
4371// Allocate the first window or the first window in a new tab page.
4372// When "oldwin" is NULL create an empty buffer for it.
4373// When "oldwin" is not NULL copy info from it to the new window.
4374// Return FAIL when something goes wrong (out of memory).
4375static int win_alloc_firstwin(win_T *oldwin)
4376{
4377  curwin = win_alloc(NULL, false);
4378  if (oldwin == NULL) {
4379    // Very first window, need to create an empty buffer for it and
4380    // initialize from scratch.
4381    curbuf = buflist_new(NULL, NULL, 1, BLN_LISTED);
4382    if (curbuf == NULL) {
4383      return FAIL;
4384    }
4385    curwin->w_buffer = curbuf;
4386    curwin->w_s = &(curbuf->b_s);
4387    curbuf->b_nwindows = 1;     // there is one window
4388    curwin->w_alist = &global_alist;
4389    curwin_init();              // init current window
4390  } else {
4391    // First window in new tab page, initialize it from "oldwin".
4392    win_init(curwin, oldwin, 0);
4393
4394    // We don't want cursor- and scroll-binding in the first window.
4395    RESET_BINDING(curwin);
4396  }
4397
4398  new_frame(curwin);
4399  topframe = curwin->w_frame;
4400  topframe->fr_width = Columns;
4401  topframe->fr_height = Rows - (int)p_ch - global_stl_height();
4402
4403  return OK;
4404}
4405
4406// Create a frame for window "wp".
4407static void new_frame(win_T *wp)
4408{
4409  frame_T *frp = xcalloc(1, sizeof(frame_T));
4410
4411  wp->w_frame = frp;
4412  frp->fr_layout = FR_LEAF;
4413  frp->fr_win = wp;
4414}
4415
4416// Initialize the window and frame size to the maximum.
4417void win_init_size(void)
4418{
4419  firstwin->w_height = (int)ROWS_AVAIL;
4420  firstwin->w_prev_height = (int)ROWS_AVAIL;
4421  firstwin->w_view_height = firstwin->w_height - firstwin->w_winbar_height;
4422  firstwin->w_height_outer = firstwin->w_height;
4423  firstwin->w_winrow_off = firstwin->w_winbar_height;
4424  topframe->fr_height = (int)ROWS_AVAIL;
4425  firstwin->w_width = Columns;
4426  firstwin->w_view_width = firstwin->w_width;
4427  firstwin->w_width_outer = firstwin->w_width;
4428  topframe->fr_width = Columns;
4429}
4430
4431// Allocate a new tabpage_T and init the values.
4432static tabpage_T *alloc_tabpage(void)
4433{
4434  static int last_tp_handle = 0;
4435  tabpage_T *tp = xcalloc(1, sizeof(tabpage_T));
4436  tp->handle = ++last_tp_handle;
4437  pmap_put(int)(&tabpage_handles, tp->handle, tp);
4438
4439  // Init t: variables.
4440  tp->tp_vars = tv_dict_alloc();
4441  init_var_dict(tp->tp_vars, &tp->tp_winvar, VAR_SCOPE);
4442  tp->tp_diff_invalid = true;
4443  tp->tp_ch_used = p_ch;
4444
4445  return tp;
4446}
4447
4448void free_tabpage(tabpage_T *tp)
4449{
4450  pmap_del(int)(&tabpage_handles, tp->handle, NULL);
4451  diff_clear(tp);
4452  for (int idx = 0; idx < SNAP_COUNT; idx++) {
4453    clear_snapshot(tp, idx);
4454  }
4455  vars_clear(&tp->tp_vars->dv_hashtab);         // free all t: variables
4456  hash_init(&tp->tp_vars->dv_hashtab);
4457  unref_var_dict(tp->tp_vars);
4458
4459  if (tp == lastused_tabpage) {
4460    lastused_tabpage = NULL;
4461  }
4462
4463  xfree(tp->tp_localdir);
4464  xfree(tp->tp_prevdir);
4465  xfree(tp);
4466}
4467
4468/// Create a new tabpage with one window.
4469///
4470/// It will edit the current buffer, like after :split.
4471///
4472/// Does not trigger WinNewPre, since the window structures
4473/// are not completely setup yet and could cause dereferencing
4474/// NULL pointers
4475///
4476/// NOTE: `first` and the return value may have already been freed by autocmds!
4477///
4478/// @param after Put new tabpage after tabpage "after", or after the current
4479///              tabpage in case of 0.
4480/// @param filename Will be passed to apply_autocmds().
4481/// @param enter Whether to enter the new tabpage.
4482/// @param first If not NULL, set to the window opened for the new tabpage.
4483/// @return pointer to new tabpage on success, NULL otherwise.
4484tabpage_T *win_new_tabpage(int after, char *filename, bool enter, win_T **first)
4485{
4486  tabpage_T *old_curtab = curtab;
4487
4488  if (window_layout_locked(CMD_tabnew)) {
4489    return NULL;
4490  }
4491
4492  tabpage_T *newtp = alloc_tabpage();
4493
4494  // Remember the current windows in this Tab page.
4495  // Avoid side-effects via unuse_tabpage when not entering.
4496  if (enter) {
4497    if (leave_tabpage(curbuf, true) == FAIL) {
4498      xfree(newtp);
4499      return NULL;
4500    }
4501  } else {
4502    unuse_tabpage(curtab);
4503    // Save this to tell if we need to make room for the tabline.
4504    curtab->tp_old_Rows_avail = ROWS_AVAIL;
4505    firstwin = NULL;
4506    lastwin = NULL;
4507  }
4508
4509  newtp->tp_localdir = old_curtab->tp_localdir
4510                       ? xstrdup(old_curtab->tp_localdir) : NULL;
4511
4512  curtab = newtp;
4513
4514  // Create a new empty window.
4515  const int result = win_alloc_firstwin(old_curtab->tp_curwin);
4516  assert(result == OK);  // does not fail for first window of new tabpage
4517  (void)result;
4518  if (first) {
4519    *first = curwin;
4520  }
4521
4522  // Make the new Tab page the new topframe.
4523  if (after == 1) {
4524    // New tab page becomes the first one.
4525    newtp->tp_next = first_tabpage;
4526    first_tabpage = newtp;
4527  } else {
4528    tabpage_T *tp = old_curtab;
4529
4530    if (after > 0) {
4531      // Put new tab page before tab page "after".
4532      int n = 2;
4533      for (tp = first_tabpage; tp->tp_next != NULL
4534           && n < after; tp = tp->tp_next) {
4535        n++;
4536      }
4537    }
4538    newtp->tp_next = tp->tp_next;
4539    tp->tp_next = newtp;
4540  }
4541  newtp->tp_firstwin = newtp->tp_lastwin = newtp->tp_curwin = curwin;
4542
4543  win_init_size();
4544  firstwin->w_winrow = tabline_height();
4545  firstwin->w_prev_winrow = firstwin->w_winrow;
4546  win_comp_scroll(curwin);
4547
4548  newtp->tp_topframe = topframe;
4549  last_status(false);
4550
4551  if (curbuf->terminal) {
4552    terminal_check_size(curbuf->terminal);
4553  }
4554
4555  if (enter) {
4556    redraw_all_later(UPD_NOT_VALID);
4557    tabpage_check_windows(old_curtab);
4558    lastused_tabpage = old_curtab;
4559    entering_window(curwin);
4560
4561    apply_autocmds(EVENT_WINNEW, NULL, NULL, false, curbuf);
4562    apply_autocmds(EVENT_WINENTER, NULL, NULL, false, curbuf);
4563    apply_autocmds(EVENT_TABNEW, filename, filename, false, curbuf);
4564    apply_autocmds(EVENT_TABENTER, NULL, NULL, false, curbuf);
4565  } else {
4566    unuse_tabpage(curtab);
4567    use_tabpage(old_curtab);
4568    // Tabline maybe added, or its contents changed.
4569    redraw_tabline = true;
4570    if (curtab->tp_old_Rows_avail != ROWS_AVAIL) {
4571      win_new_screen_rows();
4572    }
4573
4574    // Trigger autocommands in the context of the new window. Let ctx_switch handle stuff
4575    // like temporarily resetting Visual.active.
4576    CtxSwitch switchwin;
4577    const bool sw_ok = ctx_switch(&switchwin, newtp->tp_curwin, newtp, NULL, kCtxNoDisplay);
4578    assert(sw_ok);  // tp_curwin is valid in newtp
4579    (void)sw_ok;
4580
4581    apply_autocmds(EVENT_WINNEW, NULL, NULL, false, curbuf);
4582    apply_autocmds(EVENT_TABNEW, filename, filename, false, curbuf);
4583
4584    ctx_restore(&switchwin);
4585  }
4586
4587  return newtp;
4588}
4589
4590// Open a new tab page if ":tab cmd" was used.  It will edit the same buffer,
4591// like with ":split".
4592// Returns OK if a new tab page was created, FAIL otherwise.
4593static int may_open_tabpage(void)
4594{
4595  int n = (cmdmod.cmod_tab == 0) ? postponed_split_tab : cmdmod.cmod_tab;
4596
4597  if (n == 0) {
4598    return FAIL;
4599  }
4600
4601  cmdmod.cmod_tab = 0;         // reset it to avoid doing it twice
4602  postponed_split_tab = 0;
4603  int status = win_new_tabpage(n, NULL, true, NULL) ? OK : FAIL;
4604  if (status == OK) {
4605    apply_autocmds(EVENT_TABNEWENTERED, NULL, NULL, false, curbuf);
4606  }
4607  return status;
4608}
4609
4610// Create up to "maxcount" tabpages with empty windows.
4611// Returns the number of resulting tab pages.
4612int make_tabpages(int maxcount)
4613{
4614  int count = maxcount;
4615
4616  // Limit to 'tabpagemax' tabs.
4617  count = MIN(count, (int)p_tpm);
4618
4619  // Don't execute autocommands while creating the tab pages.  Must do that
4620  // when putting the buffers in the windows.
4621  block_autocmds();
4622
4623  int todo;
4624  for (todo = count - 1; todo > 0; todo--) {
4625    if (!win_new_tabpage(0, NULL, true, NULL)) {
4626      break;
4627    }
4628  }
4629
4630  unblock_autocmds();
4631
4632  // return actual number of tab pages
4633  return count - todo;
4634}
4635
4636/// Check that tpc points to a valid tab page.
4637///
4638/// @param[in]  tpc  Tabpage to check.
4639bool valid_tabpage(tabpage_T *tpc) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4640{
4641  FOR_ALL_TABS(tp) {
4642    if (tp == tpc) {
4643      return true;
4644    }
4645  }
4646  return false;
4647}
4648
4649/// Returns true when `tpc` is valid and at least one window is valid.
4650int valid_tabpage_win(tabpage_T *tpc)
4651{
4652  FOR_ALL_TABS(tp) {
4653    if (tp == tpc) {
4654      FOR_ALL_WINDOWS_IN_TAB(wp, tp) {
4655        if (win_valid_any_tab(wp)) {
4656          return true;
4657        }
4658      }
4659      return false;
4660    }
4661  }
4662  // shouldn't happen
4663  return false;
4664}
4665
4666/// Close tabpage `tab`, assuming it has no windows in it.
4667/// There must be another tabpage or this will crash.
4668void close_tabpage(tabpage_T *tab)
4669{
4670  tabpage_T *ptp;
4671
4672  if (tab == first_tabpage) {
4673    first_tabpage = tab->tp_next;
4674    ptp = first_tabpage;
4675  } else {
4676    for (ptp = first_tabpage; ptp != NULL && ptp->tp_next != tab;
4677         ptp = ptp->tp_next) {
4678      // do nothing
4679    }
4680    assert(ptp != NULL);
4681    ptp->tp_next = tab->tp_next;
4682  }
4683
4684  goto_tabpage_tp(ptp, false, false);
4685  free_tabpage(tab);
4686}
4687
4688// Find tab page "n" (first one is 1).  Returns NULL when not found.
4689tabpage_T *find_tabpage(int n)
4690{
4691  tabpage_T *tp;
4692  int i = 1;
4693
4694  if (n == 0) {
4695    return curtab;
4696  }
4697
4698  for (tp = first_tabpage; tp != NULL && i != n; tp = tp->tp_next) {
4699    i++;
4700  }
4701  return tp;
4702}
4703
4704// Get index of tab page "tp".  First one has index 1.
4705// When not found returns number of tab pages plus one.
4706int tabpage_index(tabpage_T *ftp)
4707{
4708  int i = 1;
4709  tabpage_T *tp;
4710
4711  for (tp = first_tabpage; tp != NULL && tp != ftp; tp = tp->tp_next) {
4712    i++;
4713  }
4714  return i;
4715}
4716
4717/// Prepare for leaving the current tab page.
4718/// When autocommands change "curtab" we don't leave the tab page and return
4719/// FAIL.
4720/// Careful: When OK is returned need to get a new tab page very very soon!
4721///
4722/// @param new_curbuf              what is going to be the new curbuf,
4723///                                NULL if unknown.
4724/// @param trigger_leave_autocmds  when true trigger *Leave autocommands.
4725static int leave_tabpage(buf_T *new_curbuf, bool trigger_leave_autocmds)
4726{
4727  tabpage_T *tp = curtab;
4728
4729  leaving_window(curwin);
4730  reset_VIsual_and_resel();     // stop Visual mode
4731  if (trigger_leave_autocmds) {
4732    if (new_curbuf != curbuf) {
4733      apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, false, curbuf);
4734      if (curtab != tp) {
4735        return FAIL;
4736      }
4737    }
4738    apply_autocmds(EVENT_WINLEAVE, NULL, NULL, false, curbuf);
4739    if (curtab != tp) {
4740      return FAIL;
4741    }
4742    apply_autocmds(EVENT_TABLEAVE, NULL, NULL, false, curbuf);
4743    if (curtab != tp) {
4744      return FAIL;
4745    }
4746  }
4747
4748  reset_dragwin();
4749  tp->tp_curwin = curwin;
4750  tp->tp_prevwin = prevwin;
4751  tp->tp_firstwin = firstwin;
4752  tp->tp_lastwin = lastwin;
4753  tp->tp_old_Rows_avail = ROWS_AVAIL;
4754  if (tp->tp_old_Columns != -1) {
4755    tp->tp_old_Columns = Columns;
4756  }
4757  firstwin = NULL;
4758  lastwin = NULL;
4759  return OK;
4760}
4761
4762/// Start using tab page "tp".
4763/// Only to be used after leave_tabpage() or freeing the current tab page.
4764///
4765/// @param trigger_enter_autocmds  when true trigger *Enter autocommands.
4766/// @param trigger_leave_autocmds  when true trigger *Leave autocommands.
4767static void enter_tabpage(tabpage_T *tp, buf_T *old_curbuf, bool trigger_enter_autocmds,
4768                          bool trigger_leave_autocmds)
4769{
4770  int old_off = tp->tp_firstwin->w_winrow;
4771  win_T *next_prevwin = tp->tp_prevwin;
4772  tabpage_T *old_curtab = curtab;
4773  OptInt prev_p_ch = p_ch;
4774
4775  use_tabpage(tp);
4776
4777  if (old_curtab != curtab && p_ch != prev_p_ch) {
4778    tabpage_check_windows(old_curtab);
4779    // use_tabpage() loaded a different cmdheight for the new tab. Fire OptionSet and adjust
4780    // the cmdline row without touching frame sizes (the new tab's frames are already correct).
4781    OptInt new_ch = p_ch;
4782    p_ch = prev_p_ch;
4783    command_frame_height = false;
4784    set_option_value(kOptCmdheight, INTEGER_OBJ(new_ch), 0, true, NULL);
4785    command_frame_height = true;
4786  } else if (old_curtab != curtab) {
4787    tabpage_check_windows(old_curtab);
4788  }
4789
4790  // We would like doing the TabEnter event first, but we don't have a
4791  // valid current window yet, which may break some commands.
4792  // This triggers autocommands, thus may make "tp" invalid.
4793  win_enter_ext(tp->tp_curwin, WEE_CURWIN_INVALID
4794                | (trigger_enter_autocmds ? WEE_TRIGGER_ENTER_AUTOCMDS : 0)
4795                | (trigger_leave_autocmds ? WEE_TRIGGER_LEAVE_AUTOCMDS : 0));
4796  prevwin = next_prevwin;
4797
4798  last_status(false);  // status line may appear or disappear
4799  win_float_update_statusline();
4800  win_comp_pos();      // recompute w_winrow for all windows
4801  diff_need_scrollbind = true;
4802
4803  // If there was a click in a window, it won't be usable for a following
4804  // drag.
4805  reset_dragwin();
4806
4807  // The tabpage line may have appeared or disappeared, may need to resize the frames for that.
4808  // When the Vim window was resized or ROWS_AVAIL changed need to update frame sizes too.
4809  if (curtab->tp_old_Rows_avail != ROWS_AVAIL || (old_off != firstwin->w_winrow)) {
4810    win_new_screen_rows();
4811  }
4812  if (curtab->tp_old_Columns != Columns) {
4813    if (starting == 0) {
4814      win_new_screen_cols();  // update window widths
4815      curtab->tp_old_Columns = Columns;
4816    } else {
4817      curtab->tp_old_Columns = -1;  // update window widths later
4818    }
4819  }
4820
4821  lastused_tabpage = old_curtab;
4822
4823  // Apply autocommands after updating the display, when 'rows' and
4824  // 'columns' have been set correctly.
4825  if (trigger_enter_autocmds) {
4826    apply_autocmds(EVENT_TABENTER, NULL, NULL, false, curbuf);
4827    if (old_curbuf != curbuf) {
4828      apply_autocmds(EVENT_BUFENTER, NULL, NULL, false, curbuf);
4829    }
4830  }
4831
4832  redraw_all_later(UPD_NOT_VALID);
4833}
4834
4835/// tells external UI that windows and inline floats in old_curtab are invisible
4836/// and that floats in curtab is now visible.
4837///
4838/// External floats are considered independent of tabpages. This is
4839/// implemented by always moving them to curtab.
4840static void tabpage_check_windows(tabpage_T *old_curtab)
4841{
4842  win_T *next_wp;
4843  for (win_T *wp = old_curtab->tp_firstwin; wp; wp = next_wp) {
4844    next_wp = wp->w_next;
4845    if (wp->w_floating) {
4846      if (wp->w_config.external) {
4847        win_remove(wp, old_curtab);
4848        win_append(lastwin_nofloating(NULL), wp, NULL);
4849      } else {
4850        ui_comp_remove_grid(&wp->w_grid_alloc);
4851      }
4852    }
4853    wp->w_pos_changed = true;
4854  }
4855
4856  for (win_T *wp = firstwin; wp; wp = wp->w_next) {
4857    if (wp->w_floating && !wp->w_config.external) {
4858      win_config_float(wp, wp->w_config);
4859    }
4860    wp->w_pos_changed = true;
4861  }
4862}
4863
4864// Go to tab page "n".  For ":tab N" and "Ngt".
4865// When "n" is 9999 go to the last tab page.
4866void goto_tabpage(int n)
4867{
4868  if (text_locked()) {
4869    // Not allowed when editing the command line.
4870    text_locked_msg();
4871    return;
4872  }
4873
4874  // If there is only one it can't work.
4875  if (first_tabpage->tp_next == NULL) {
4876    if (n > 1) {
4877      beep_flush();
4878    }
4879    return;
4880  }
4881
4882  tabpage_T *tp = NULL;  // shut up compiler
4883
4884  if (n == 0) {
4885    // No count, go to next tab page, wrap around end.
4886    if (curtab->tp_next == NULL) {
4887      tp = first_tabpage;
4888    } else {
4889      tp = curtab->tp_next;
4890    }
4891  } else if (n < 0) {
4892    // "gT": go to previous tab page, wrap around end.  "N gT" repeats
4893    // this N times.
4894    tabpage_T *ttp = curtab;
4895    for (int i = n; i < 0; i++) {
4896      for (tp = first_tabpage; tp->tp_next != ttp && tp->tp_next != NULL;
4897           tp = tp->tp_next) {}
4898      ttp = tp;
4899    }
4900  } else if (n == 9999) {
4901    // Go to last tab page.
4902    for (tp = first_tabpage; tp->tp_next != NULL; tp = tp->tp_next) {}
4903  } else {
4904    // Go to tab page "n".
4905    tp = find_tabpage(n);
4906    if (tp == NULL) {
4907      beep_flush();
4908      return;
4909    }
4910  }
4911
4912  goto_tabpage_tp(tp, true, true);
4913}
4914
4915/// Go to tabpage "tp".
4916/// Note: doesn't update the GUI tab.
4917///
4918/// @param trigger_enter_autocmds  when true trigger *Enter autocommands.
4919/// @param trigger_leave_autocmds  when true trigger *Leave autocommands.
4920void goto_tabpage_tp(tabpage_T *tp, bool trigger_enter_autocmds, bool trigger_leave_autocmds)
4921{
4922  // Don't repeat a message in another tab page.
4923  set_keep_msg(NULL, 0);
4924
4925  skip_win_fix_scroll = true;
4926  if (tp != curtab && leave_tabpage(tp->tp_curwin->w_buffer,
4927                                    trigger_leave_autocmds) == OK) {
4928    if (valid_tabpage(tp)) {
4929      enter_tabpage(tp, curbuf, trigger_enter_autocmds,
4930                    trigger_leave_autocmds);
4931    } else {
4932      enter_tabpage(curtab, curbuf, trigger_enter_autocmds,
4933                    trigger_leave_autocmds);
4934    }
4935  }
4936  skip_win_fix_scroll = false;
4937}
4938
4939/// Go to the last accessed tab page, if there is one.
4940/// @return true if the tab page is valid, false otherwise.
4941bool goto_tabpage_lastused(void)
4942{
4943  if (!valid_tabpage(lastused_tabpage)) {
4944    return false;
4945  }
4946
4947  goto_tabpage_tp(lastused_tabpage, true, true);
4948  return true;
4949}
4950
4951// Enter window "wp" in tab page "tp".
4952// Also updates the GUI tab.
4953void goto_tabpage_win(tabpage_T *tp, win_T *wp)
4954{
4955  goto_tabpage_tp(tp, true, true);
4956  if (curtab == tp && win_valid(wp)) {
4957    win_enter(wp, true);
4958  }
4959}
4960
4961// Move the current tab page to after tab page "nr".
4962void tabpage_move(int nr)
4963{
4964  assert(curtab != NULL);
4965
4966  if (first_tabpage->tp_next == NULL) {
4967    return;
4968  }
4969
4970  if (tabpage_move_disallowed) {
4971    return;
4972  }
4973
4974  int n = 1;
4975  tabpage_T *tp;
4976
4977  for (tp = first_tabpage; tp->tp_next != NULL && n < nr; tp = tp->tp_next) {
4978    n++;
4979  }
4980
4981  if (tp == curtab || (nr > 0 && tp->tp_next != NULL
4982                       && tp->tp_next == curtab)) {
4983    return;
4984  }
4985
4986  int old_nr = tabpage_index(curtab);
4987  tabpage_T *tp_dst = tp;
4988
4989  // Remove the current tab page from the list of tab pages.
4990  if (curtab == first_tabpage) {
4991    first_tabpage = curtab->tp_next;
4992  } else {
4993    tp = NULL;
4994    FOR_ALL_TABS(tp2) {
4995      if (tp2->tp_next == curtab) {
4996        tp = tp2;
4997        break;
4998      }
4999    }
5000    if (tp == NULL) {   // "cannot happen"
5001      return;
5002    }
5003    tp->tp_next = curtab->tp_next;
5004  }
5005
5006  // Re-insert it at the specified position.
5007  if (nr <= 0) {
5008    curtab->tp_next = first_tabpage;
5009    first_tabpage = curtab;
5010  } else {
5011    curtab->tp_next = tp_dst->tp_next;
5012    tp_dst->tp_next = curtab;
5013  }
5014
5015  // Need to redraw the tabline.  Tab page contents doesn't change.
5016  redraw_tabline = true;
5017
5018  if (has_event(EVENT_TABMOVED)) {
5019    char prev_idx[NUMBUFLEN];
5020    vim_snprintf(prev_idx, NUMBUFLEN, "%i", old_nr);
5021    MAXSIZE_TEMP_DICT(data, 2);
5022    PUT_C(data, "tabnr_old", INTEGER_OBJ(old_nr));
5023    PUT_C(data, "tabnr_new", INTEGER_OBJ(tabpage_index(curtab)));
5024    aucmd_defer(EVENT_TABMOVED, prev_idx, NULL, AUGROUP_ALL, curbuf, NULL, &DICT_OBJ(data));
5025  }
5026}
5027
5028/// Go to another window.
5029/// When jumping to another buffer, stop Visual mode.  Do this before
5030/// changing windows so we can yank the selection into the '*' register.
5031/// (note: this may trigger ModeChanged autocommand!)
5032/// When jumping to another window on the same buffer, adjust its cursor
5033/// position to keep the same Visual area.
5034void win_goto(win_T *wp)
5035{
5036  win_T *owp = curwin;
5037
5038  if (text_or_buf_locked()) {
5039    beep_flush();
5040    return;
5041  }
5042
5043  if (wp->w_buffer != curbuf) {
5044    // careful: triggers ModeChanged autocommand
5045    reset_VIsual_and_resel();
5046  } else if (Visual.active) {
5047    wp->w_cursor = curwin->w_cursor;
5048  }
5049
5050  // autocommand may have made wp invalid
5051  if (!win_valid(wp)) {
5052    return;
5053  }
5054
5055  win_enter(wp, true);
5056
5057  // Conceal cursor line in previous window, unconceal in current window.
5058  if (win_valid(owp) && owp->w_p_cole > 0 && !msg_scrolled) {
5059    redrawWinline(owp, owp->w_cursor.lnum);
5060  }
5061  if (curwin->w_p_cole > 0 && !msg_scrolled) {
5062    redrawWinline(curwin, curwin->w_cursor.lnum);
5063  }
5064}
5065
5066// Find the tabpage for window "win".
5067tabpage_T *win_find_tabpage(win_T *win)
5068{
5069  FOR_ALL_TAB_WINDOWS(tp, wp) {
5070    if (wp == win) {
5071      return tp;
5072    }
5073  }
5074  return NULL;
5075}
5076
5077/// Get the above or below neighbor window of the specified window.
5078///
5079/// Returns the specified window if the neighbor is not found.
5080/// Returns the previous window if the specifiecied window is a floating window.
5081///
5082/// @param up     true for the above neighbor
5083/// @param count  nth neighbor window
5084///
5085/// @return       found window
5086win_T *win_vert_neighbor(tabpage_T *tp, win_T *wp, bool up, int count)
5087{
5088  frame_T *foundfr = wp->w_frame;
5089
5090  if (wp->w_floating) {
5091    return win_valid(prevwin) && !prevwin->w_floating ? prevwin : firstwin;
5092  }
5093
5094  while (count--) {
5095    frame_T *nfr;
5096    // First go upwards in the tree of frames until we find an upwards or
5097    // downwards neighbor.
5098    frame_T *fr = foundfr;
5099    while (true) {
5100      if (fr == tp->tp_topframe) {
5101        goto end;
5102      }
5103      if (up) {
5104        nfr = fr->fr_prev;
5105      } else {
5106        nfr = fr->fr_next;
5107      }
5108      if (fr->fr_parent->fr_layout == FR_COL && nfr != NULL) {
5109        break;
5110      }
5111      fr = fr->fr_parent;
5112    }
5113
5114    // Now go downwards to find the bottom or top frame in it.
5115    while (true) {
5116      if (nfr->fr_layout == FR_LEAF) {
5117        foundfr = nfr;
5118        break;
5119      }
5120      fr = nfr->fr_child;
5121      if (nfr->fr_layout == FR_ROW) {
5122        // Find the frame at the cursor row.
5123        while (fr->fr_next != NULL
5124               && frame2win(fr)->w_wincol + fr->fr_width
5125               <= wp->w_wincol + wp->w_wcol) {
5126          fr = fr->fr_next;
5127        }
5128      }
5129      if (nfr->fr_layout == FR_COL && up) {
5130        while (fr->fr_next != NULL) {
5131          fr = fr->fr_next;
5132        }
5133      }
5134      nfr = fr;
5135    }
5136  }
5137end:
5138  return foundfr != NULL ? foundfr->fr_win : NULL;
5139}
5140
5141/// Move to window above or below "count" times.
5142///
5143/// @param up     true to go to win above
5144/// @param count  go count times into direction
5145static void win_goto_ver(bool up, int count)
5146{
5147  win_T *win = win_vert_neighbor(curtab, curwin, up, count);
5148  if (win != NULL) {
5149    win_goto(win);
5150  }
5151}
5152
5153/// Get the left or right neighbor window of the specified window.
5154///
5155/// Returns the specified window if the neighbor is not found.
5156/// Returns the previous window if the specifiecied window is a floating window.
5157///
5158/// @param left  true for the left neighbor
5159/// @param count nth neighbor window
5160///
5161/// @return      found window
5162win_T *win_horz_neighbor(tabpage_T *tp, win_T *wp, bool left, int count)
5163{
5164  frame_T *foundfr = wp->w_frame;
5165
5166  if (wp->w_floating) {
5167    return win_valid(prevwin) && !prevwin->w_floating ? prevwin : firstwin;
5168  }
5169
5170  while (count--) {
5171    frame_T *nfr;
5172    // First go upwards in the tree of frames until we find a left or
5173    // right neighbor.
5174    frame_T *fr = foundfr;
5175    while (true) {
5176      if (fr == tp->tp_topframe) {
5177        goto end;
5178      }
5179      if (left) {
5180        nfr = fr->fr_prev;
5181      } else {
5182        nfr = fr->fr_next;
5183      }
5184      if (fr->fr_parent->fr_layout == FR_ROW && nfr != NULL) {
5185        break;
5186      }
5187      fr = fr->fr_parent;
5188    }
5189
5190    // Now go downwards to find the leftmost or rightmost frame in it.
5191    while (true) {
5192      if (nfr->fr_layout == FR_LEAF) {
5193        foundfr = nfr;
5194        break;
5195      }
5196      fr = nfr->fr_child;
5197      if (nfr->fr_layout == FR_COL) {
5198        // Find the frame at the cursor row.
5199        while (fr->fr_next != NULL
5200               && frame2win(fr)->w_winrow + fr->fr_height
5201               <= wp->w_winrow + wp->w_wrow) {
5202          fr = fr->fr_next;
5203        }
5204      }
5205      if (nfr->fr_layout == FR_ROW && left) {
5206        while (fr->fr_next != NULL) {
5207          fr = fr->fr_next;
5208        }
5209      }
5210      nfr = fr;
5211    }
5212  }
5213end:
5214  return foundfr != NULL ? foundfr->fr_win : NULL;
5215}
5216
5217/// Move to left or right window.
5218///
5219/// @param left   true to go to left window
5220/// @param count  go count times into direction
5221static void win_goto_hor(bool left, int count)
5222{
5223  win_T *win = win_horz_neighbor(curtab, curwin, left, count);
5224  if (win != NULL) {
5225    win_goto(win);
5226  }
5227}
5228
5229/// Make window `wp` the current window.
5230///
5231/// @warning Autocmds may close the window immediately, so caller must check
5232///          win_valid(wp).
5233void win_enter(win_T *wp, bool undo_sync)
5234{
5235  win_enter_ext(wp, (undo_sync ? WEE_UNDO_SYNC : 0)
5236                | WEE_TRIGGER_ENTER_AUTOCMDS | WEE_TRIGGER_LEAVE_AUTOCMDS);
5237}
5238
5239/// Make window "wp" the current window.
5240///
5241/// @param flags  if contains WEE_CURWIN_INVALID, it means curwin has just been
5242///               closed and isn't valid.
5243static void win_enter_ext(win_T *const wp, const int flags)
5244{
5245  bool other_buffer = false;
5246  const bool curwin_invalid = (flags & WEE_CURWIN_INVALID);
5247
5248  if (wp == curwin && !curwin_invalid) {        // nothing to do
5249    return;
5250  }
5251
5252  if (!curwin_invalid) {
5253    leaving_window(curwin);
5254  }
5255
5256  if (!curwin_invalid && (flags & WEE_TRIGGER_LEAVE_AUTOCMDS)) {
5257    // Be careful: If autocommands delete the window, return now.
5258    if (wp->w_buffer != curbuf) {
5259      apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, false, curbuf);
5260      other_buffer = true;
5261      if (!win_valid(wp)) {
5262        return;
5263      }
5264    }
5265    apply_autocmds(EVENT_WINLEAVE, NULL, NULL, false, curbuf);
5266    if (!win_valid(wp)) {
5267      return;
5268    }
5269    // autocmds may abort script processing
5270    if (aborting()) {
5271      return;
5272    }
5273  }
5274
5275  // sync undo before leaving the current buffer
5276  if ((flags & WEE_UNDO_SYNC) && curbuf != wp->w_buffer) {
5277    u_sync(false);
5278  }
5279
5280  // Might need to scroll the old window before switching, e.g., when the
5281  // cursor was moved.
5282  if (*p_spk == 'c' && !curwin_invalid) {
5283    update_topline(curwin);
5284  }
5285
5286  // may have to copy the buffer options when 'cpo' contains 'S'
5287  if (wp->w_buffer != curbuf) {
5288    buf_copy_options(wp->w_buffer, BCO_ENTER | BCO_NOHELP);
5289  }
5290  if (!curwin_invalid) {
5291    prevwin = curwin;           // remember for CTRL-W p
5292    curwin->w_redr_status = true;
5293  }
5294  curwin = wp;
5295  curbuf = wp->w_buffer;
5296
5297  check_cursor(curwin);
5298  if (!virtual_active(curwin)) {
5299    curwin->w_cursor.coladd = 0;
5300  }
5301  if (*p_spk == 'c') {
5302    changed_line_abv_curs();      // assume cursor position needs updating
5303  } else {
5304    // Make sure the cursor position is valid, either by moving the cursor
5305    // or by scrolling the text.
5306    win_fix_cursor(get_real_state() & (MODE_NORMAL|MODE_CMDLINE|MODE_TERMINAL));
5307  }
5308
5309  update_cwd(kCdCauseWindow);
5310
5311  entering_window(curwin);
5312  // Careful: autocommands may close the window and make "wp" invalid
5313  if (flags & WEE_TRIGGER_NEW_AUTOCMDS) {
5314    apply_autocmds(EVENT_WINNEW, NULL, NULL, false, curbuf);
5315  }
5316  if (flags & WEE_TRIGGER_ENTER_AUTOCMDS) {
5317    apply_autocmds(EVENT_WINENTER, NULL, NULL, false, curbuf);
5318    if (other_buffer) {
5319      apply_autocmds(EVENT_BUFENTER, NULL, NULL, false, curbuf);
5320    }
5321  }
5322
5323  maketitle();
5324  curwin->w_redr_status = true;
5325  redraw_tabline = true;
5326  if (restart_edit) {
5327    redraw_later(curwin, UPD_VALID);  // causes status line redraw
5328  }
5329
5330  // change background color according to NormalNC,
5331  // but only if actually defined (otherwise no extra redraw)
5332  if (curwin->w_hl_attr_normal != curwin->w_hl_attr_normalnc) {
5333    // TODO(bfredl): eventually we should be smart enough
5334    // to only recompose the window, not redraw it.
5335    redraw_later(curwin, UPD_NOT_VALID);
5336  }
5337  if (prevwin) {
5338    if (prevwin->w_hl_attr_normal != prevwin->w_hl_attr_normalnc) {
5339      redraw_later(prevwin, UPD_NOT_VALID);
5340    }
5341  }
5342
5343  // set window height to desired minimal value
5344  if (curwin->w_height < p_wh && !curwin->w_p_wfh && !curwin->w_floating) {
5345    win_setheight((int)p_wh);
5346  } else if (curwin->w_height == 0) {
5347    win_setheight(1);
5348  }
5349
5350  // set window width to desired minimal value
5351  if (curwin->w_width < p_wiw && !curwin->w_p_wfw && !curwin->w_floating) {
5352    win_setwidth((int)p_wiw);
5353  }
5354
5355  setmouse();                   // in case jumped to/from help buffer
5356
5357  // Change directories when the 'acd' option is set.
5358  do_autochdir();
5359}
5360
5361/// Applies the effective current-directory of the current window (its window-local, buffer-local,
5362/// tab-local or the global directory). Called after setting curbuf/curwin.
5363///
5364/// @param cause What caused the switch, reported by the DirChanged event.
5365void update_cwd(CdCause cause)
5366{
5367  // New directory is either the local directory of the window, buffer, tab or NULL.
5368  char *new_dir;
5369  CdScope scope;
5370
5371  if (curbuf->b_localdir) {
5372    new_dir = curbuf->b_localdir;
5373    scope = kCdScopeBuffer;
5374  } else if (curwin->w_localdir) {
5375    new_dir = curwin->w_localdir;
5376    scope = kCdScopeWindow;
5377  } else if (curtab->tp_localdir) {
5378    new_dir = curtab->tp_localdir;
5379    scope = kCdScopeTabpage;
5380  } else {
5381    new_dir = NULL;
5382    scope = kCdScopeGlobal;
5383  }
5384
5385  char cwd[MAXPATHL];
5386  if (os_dirname(cwd, MAXPATHL) != OK) {
5387    cwd[0] = NUL;
5388  }
5389
5390  if (new_dir) {
5391    // Window/buffer/tab has a local directory: Save current directory as global
5392    // (unless that was done already) and change to the local directory.
5393    if (globaldir == NULL) {
5394      if (cwd[0] != NUL) {
5395        globaldir = xstrdup(cwd);
5396      }
5397    }
5398    bool dir_differs = !path_equal(new_dir, cwd, kPathCmpLiteral);
5399    if (!p_acd && dir_differs) {
5400      do_autocmd_dirchanged(new_dir, scope, cause, true);
5401    }
5402    if (os_chdir(new_dir) == 0) {
5403      if (!p_acd && dir_differs) {
5404        do_autocmd_dirchanged(new_dir, scope, cause, false);
5405      }
5406    }
5407    last_chdir_reason = NULL;
5408    shorten_fnames(true);
5409  } else if (globaldir != NULL) {
5410    // Window nor buffer have a local directory and we are not in the global
5411    // directory: Change to the global directory.
5412    bool dir_differs = !path_equal(globaldir, cwd, kPathCmpLiteral);
5413    if (!p_acd && dir_differs) {
5414      do_autocmd_dirchanged(globaldir, kCdScopeGlobal, cause, true);
5415    }
5416    if (os_chdir(globaldir) == 0) {
5417      if (!p_acd && dir_differs) {
5418        do_autocmd_dirchanged(globaldir, kCdScopeGlobal, cause, false);
5419      }
5420    }
5421    XFREE_CLEAR(globaldir);
5422    last_chdir_reason = NULL;
5423    shorten_fnames(true);
5424  }
5425}
5426
5427/// Jump to the first open window that contains buffer "buf", if one exists.
5428/// Returns a pointer to the window found, otherwise NULL.
5429win_T *buf_jump_open_win(buf_T *buf)
5430{
5431  if (curwin->w_buffer == buf) {
5432    win_enter(curwin, false);
5433    return curwin;
5434  }
5435  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
5436    if (wp->w_buffer == buf) {
5437      win_enter(wp, false);
5438      return wp;
5439    }
5440  }
5441
5442  return NULL;
5443}
5444
5445/// Jump to the first open window in any tab page that contains buffer "buf",
5446/// if one exists. First search in the windows present in the current tab page.
5447/// @return the found window, or NULL.
5448win_T *buf_jump_open_tab(buf_T *buf)
5449{
5450  // First try the current tab page.
5451  {
5452    win_T *wp = buf_jump_open_win(buf);
5453    if (wp != NULL) {
5454      return wp;
5455    }
5456  }
5457
5458  FOR_ALL_TABS(tp) {
5459    // Skip the current tab since we already checked it.
5460    if (tp == curtab) {
5461      continue;
5462    }
5463    FOR_ALL_WINDOWS_IN_TAB(wp, tp) {
5464      if (wp->w_buffer == buf) {
5465        goto_tabpage_win(tp, wp);
5466
5467        // If we the current window didn't switch,
5468        // something went wrong.
5469        if (curwin != wp) {
5470          wp = NULL;
5471        }
5472
5473        // Return the window we switched to.
5474        return wp;
5475      }
5476    }
5477  }
5478
5479  // If we made it this far, we didn't find the buffer.
5480  return NULL;
5481}
5482
5483static int last_win_id = LOWEST_WIN_ID - 1;
5484
5485/// @param hidden  allocate a window structure and link it in the window if
5486//                 false.
5487win_T *win_alloc(win_T *after, bool hidden)
5488{
5489  // allocate window structure and linesizes arrays
5490  win_T *new_wp = xcalloc(1, sizeof(win_T));
5491
5492  new_wp->handle = ++last_win_id;
5493  pmap_put(int)(&window_handles, new_wp->handle, new_wp);
5494
5495  new_wp->w_grid_alloc.mouse_enabled = true;
5496
5497  grid_assign_handle(&new_wp->w_grid_alloc);
5498
5499  // Init w: variables.
5500  new_wp->w_vars = tv_dict_alloc();
5501  init_var_dict(new_wp->w_vars, &new_wp->w_winvar, VAR_SCOPE);
5502
5503  // Don't execute autocommands while the window is not properly
5504  // initialized yet.  gui_create_scrollbar() may trigger a FocusGained
5505  // event.
5506  block_autocmds();
5507  // link the window in the window list
5508  if (!hidden) {
5509    tabpage_T *tp = NULL;
5510    if (after) {
5511      tp = win_find_tabpage(after);
5512      if (tp == curtab) {
5513        tp = NULL;
5514      }
5515    }
5516    win_append(after, new_wp, tp);
5517  }
5518
5519  new_wp->w_wincol = 0;
5520  new_wp->w_width = Columns;
5521
5522  // position the display and the cursor at the top of the file.
5523  new_wp->w_topline = 1;
5524  new_wp->w_topfill = 0;
5525  new_wp->w_botline = 2;
5526  new_wp->w_cursor.lnum = 1;
5527  new_wp->w_scbind_pos = 1;
5528  new_wp->w_floating = false;
5529  new_wp->w_kind = kWinNormal;
5530  new_wp->w_config = WIN_CONFIG_INIT;
5531  new_wp->w_viewport_invalid = true;
5532  new_wp->w_viewport_last_topline = 1;
5533
5534  new_wp->w_ns_hl = -1;
5535
5536  Set(uint32_t) ns_set = SET_INIT;
5537  new_wp->w_ns_set = ns_set;
5538
5539  // use global option for global-local options
5540  new_wp->w_allbuf_opt.wo_so = new_wp->w_p_so = -1;
5541  new_wp->w_allbuf_opt.wo_sop = new_wp->w_p_sop = -1;
5542  new_wp->w_allbuf_opt.wo_siso = new_wp->w_p_siso = -1;
5543
5544  // We won't calculate w_fraction until resizing the window
5545  new_wp->w_fraction = 0;
5546  new_wp->w_prev_fraction_row = -1;
5547
5548  foldInitWin(new_wp);
5549  unblock_autocmds();
5550  new_wp->w_next_match_id = 1000;  // up to 1000 can be picked by the user
5551  return new_wp;
5552}
5553
5554// Free one WinInfo.
5555void free_wininfo(WinInfo *wip, buf_T *bp)
5556{
5557  if (wip->wi_optset) {
5558    clear_winopt(&wip->wi_opt);
5559    deleteFoldRecurse(bp, &wip->wi_folds);
5560  }
5561  xfree(wip);
5562}
5563
5564/// Remove window 'wp' from the window list and free the structure.
5565///
5566/// @param tp  tab page "win" is in, NULL for current
5567void win_free(win_T *wp, tabpage_T *tp)
5568{
5569  pmap_del(int)(&window_handles, wp->handle, NULL);
5570  clearFolding(wp);
5571
5572  // reduce the reference count to the argument list.
5573  alist_unlink(wp->w_alist);
5574
5575  // Don't execute autocommands while the window is halfway being deleted.
5576  block_autocmds();
5577
5578  set_destroy(uint32_t, &wp->w_ns_set);
5579
5580  clear_winopt(&wp->w_onebuf_opt);
5581  clear_winopt(&wp->w_allbuf_opt);
5582
5583  xfree(wp->w_p_lcs_chars.multispace);
5584  xfree(wp->w_p_lcs_chars.leadmultispace);
5585
5586  vars_clear(&wp->w_vars->dv_hashtab);          // free all w: variables
5587  hash_init(&wp->w_vars->dv_hashtab);
5588  unref_var_dict(wp->w_vars);
5589
5590  if (prevwin == wp) {
5591    prevwin = NULL;
5592  }
5593  FOR_ALL_TABS(ttp) {
5594    if (ttp->tp_prevwin == wp) {
5595      ttp->tp_prevwin = NULL;
5596    }
5597  }
5598
5599  xfree(wp->w_lines);
5600
5601  for (int i = 0; i < wp->w_tagstacklen; i++) {
5602    tagstack_clear_entry(&wp->w_tagstack[i]);
5603  }
5604
5605  xfree(wp->w_localdir);
5606  xfree(wp->w_prevdir);
5607
5608  stl_clear_click_defs(wp->w_status_click_defs, wp->w_status_click_defs_size);
5609  xfree(wp->w_status_click_defs);
5610
5611  stl_clear_click_defs(wp->w_winbar_click_defs, wp->w_winbar_click_defs_size);
5612  xfree(wp->w_winbar_click_defs);
5613
5614  StcClicks lnum_click_defs;
5615  map_foreach_value(wp->w_statuscol_click_defs, lnum_click_defs, {
5616    for (uint32_t i = 0; i < lnum_click_defs.set.h.n_keys; i++) {
5617      StcClick row_click_defs = lnum_click_defs.values[i];
5618      stl_clear_click_defs(row_click_defs.def, row_click_defs.size);
5619      xfree(row_click_defs.def);
5620    }
5621    map_destroy(int, &lnum_click_defs);
5622  })
5623  map_destroy(int, wp->w_statuscol_click_defs);
5624
5625  // Remove the window from the b_wininfo lists, it may happen that the
5626  // freed memory is re-used for another window.
5627  FOR_ALL_BUFFERS(buf) {
5628    WinInfo *wip_wp = NULL;
5629    size_t pos_wip = kv_size(buf->b_wininfo);
5630    size_t pos_null = kv_size(buf->b_wininfo);
5631    for (size_t i = 0; i < kv_size(buf->b_wininfo); i++) {
5632      WinInfo *wip = kv_A(buf->b_wininfo, i);
5633      if (wip->wi_win == wp) {
5634        wip_wp = wip;
5635        pos_wip = i;
5636      } else if (wip->wi_win == NULL) {
5637        pos_null = i;
5638      }
5639    }
5640
5641    if (wip_wp) {
5642      wip_wp->wi_win = NULL;
5643      // Discard saved options if the style is minimal.
5644      if (wp->w_config.style == kWinStyleMinimal && wip_wp->wi_optset) {
5645        clear_winopt(&wip_wp->wi_opt);
5646        deleteFoldRecurse(buf, &wip_wp->wi_folds);
5647        wip_wp->wi_optset = false;
5648      }
5649      // If there already is an entry with "wi_win" set to NULL, only
5650      // the first entry with NULL will ever be used, delete the other one.
5651      if (pos_null < kv_size(buf->b_wininfo)) {
5652        size_t pos_delete = MAX(pos_null, pos_wip);
5653        free_wininfo(kv_A(buf->b_wininfo, pos_delete), buf);
5654        kv_shift(buf->b_wininfo, pos_delete, 1);
5655      }
5656    }
5657  }
5658
5659  // free the border text
5660  clear_virttext(&wp->w_config.title_chunks);
5661  clear_virttext(&wp->w_config.footer_chunks);
5662
5663  clear_matches(wp);
5664
5665  free_jumplist(wp);
5666
5667  qf_free_all(wp);
5668
5669  xfree(wp->w_p_cc_cols);
5670
5671  win_free_grid(wp, false);
5672
5673  if (win_valid_any_tab(wp)) {
5674    win_remove(wp, tp);
5675  }
5676  if (autocmd_busy) {
5677    wp->w_next = au_pending_free_win;
5678    au_pending_free_win = wp;
5679  } else {
5680    xfree(wp);
5681  }
5682
5683  unblock_autocmds();
5684}
5685
5686void win_free_grid(win_T *wp, bool reinit)
5687{
5688  if (wp->w_grid_alloc.handle != 0 && ui_has(kUIMultigrid)) {
5689    ui_call_grid_destroy(wp->w_grid_alloc.handle);
5690  }
5691  grid_free(&wp->w_grid_alloc);
5692  if (reinit) {
5693    // if a float is turned into a split, the grid data structure will be reused
5694    CLEAR_FIELD(wp->w_grid_alloc);
5695  }
5696}
5697
5698/// Append window "wp" in the window list after window "after".
5699///
5700/// @param tp  tab page "win" (and "after", if not NULL) is in, NULL for current
5701void win_append(win_T *after, win_T *wp, tabpage_T *tp)
5702  FUNC_ATTR_NONNULL_ARG(2)
5703{
5704  assert(tp == NULL || tp != curtab);
5705
5706  win_T **first = tp == NULL ? &firstwin : &tp->tp_firstwin;
5707  win_T **last = tp == NULL ? &lastwin : &tp->tp_lastwin;
5708
5709  // after NULL is in front of the first
5710  win_T *before = after == NULL ? *first : after->w_next;
5711
5712  wp->w_next = before;
5713  wp->w_prev = after;
5714  if (after == NULL) {
5715    *first = wp;
5716  } else {
5717    after->w_next = wp;
5718  }
5719  if (before == NULL) {
5720    *last = wp;
5721  } else {
5722    before->w_prev = wp;
5723  }
5724}
5725
5726/// Remove a window from the window list.
5727///
5728/// @param tp  tab page "win" is in, NULL for current
5729void win_remove(win_T *wp, tabpage_T *tp)
5730  FUNC_ATTR_NONNULL_ARG(1)
5731{
5732  assert(tp == NULL || tp != curtab);
5733
5734  if (wp->w_prev != NULL) {
5735    wp->w_prev->w_next = wp->w_next;
5736  } else if (tp == NULL) {
5737    firstwin = curtab->tp_firstwin = wp->w_next;
5738  } else {
5739    tp->tp_firstwin = wp->w_next;
5740  }
5741  if (wp->w_next != NULL) {
5742    wp->w_next->w_prev = wp->w_prev;
5743  } else if (tp == NULL) {
5744    lastwin = curtab->tp_lastwin = wp->w_prev;
5745  } else {
5746    tp->tp_lastwin = wp->w_prev;
5747  }
5748}
5749
5750// Append frame "frp" in a frame list after frame "after".
5751static void frame_append(frame_T *after, frame_T *frp)
5752{
5753  frp->fr_next = after->fr_next;
5754  after->fr_next = frp;
5755  if (frp->fr_next != NULL) {
5756    frp->fr_next->fr_prev = frp;
5757  }
5758  frp->fr_prev = after;
5759}
5760
5761// Insert frame "frp" in a frame list before frame "before".
5762static void frame_insert(frame_T *before, frame_T *frp)
5763{
5764  frp->fr_next = before;
5765  frp->fr_prev = before->fr_prev;
5766  before->fr_prev = frp;
5767  if (frp->fr_prev != NULL) {
5768    frp->fr_prev->fr_next = frp;
5769  } else {
5770    frp->fr_parent->fr_child = frp;
5771  }
5772}
5773
5774// Remove a frame from a frame list.
5775static void frame_remove(frame_T *frp)
5776{
5777  if (frp->fr_prev != NULL) {
5778    frp->fr_prev->fr_next = frp->fr_next;
5779  } else {
5780    frp->fr_parent->fr_child = frp->fr_next;
5781  }
5782  if (frp->fr_next != NULL) {
5783    frp->fr_next->fr_prev = frp->fr_prev;
5784  }
5785}
5786
5787void win_new_screensize(void)
5788{
5789  static int old_Rows = 0;
5790  static int old_Columns = 0;
5791
5792  if (old_Rows != Rows) {
5793    // If 'window' uses the whole screen, keep it using that.
5794    // Don't change it when set with "-w size" on the command line.
5795    if (p_window == old_Rows - 1 || (old_Rows == 0 && !option_was_set(kOptWindow))) {
5796      p_window = Rows - 1;
5797    }
5798    old_Rows = Rows;
5799    win_new_screen_rows();  // update window sizes
5800  }
5801  if (old_Columns != Columns) {
5802    old_Columns = Columns;
5803    win_new_screen_cols();  // update window sizes
5804  }
5805}
5806/// Called from win_new_screensize() after Rows changed.
5807///
5808/// This only does the current tab page, others must be done when made active.
5809void win_new_screen_rows(void)
5810{
5811  if (firstwin == NULL) {       // not initialized yet
5812    return;
5813  }
5814  int h = MAX((int)ROWS_AVAIL, frame_minheight(topframe, NULL));
5815
5816  // First try setting the heights of windows with 'winfixheight'.  If
5817  // that doesn't result in the right height, forget about that option.
5818  frame_new_height(topframe, h, false, true, false);
5819  if (!frame_check_height(topframe, h)) {
5820    frame_new_height(topframe, h, false, false, false);
5821  }
5822
5823  win_comp_pos();  // recompute w_winrow and w_wincol
5824  win_reconfig_floats();  // The size of floats might change
5825  compute_cmdrow();
5826  curtab->tp_ch_used = p_ch;
5827
5828  if (!skip_win_fix_scroll) {
5829    win_fix_scroll(true);
5830  }
5831}
5832
5833/// Called from win_new_screensize() after Columns changed.
5834void win_new_screen_cols(void)
5835{
5836  if (firstwin == NULL) {       // not initialized yet
5837    return;
5838  }
5839
5840  // First try setting the widths of windows with 'winfixwidth'.  If that
5841  // doesn't result in the right width, forget about that option.
5842  frame_new_width(topframe, Columns, false, true);
5843  if (!frame_check_width(topframe, Columns)) {
5844    frame_new_width(topframe, Columns, false, false);
5845  }
5846
5847  win_comp_pos();  // recompute w_winrow and w_wincol
5848  win_reconfig_floats();  // The size of floats might change
5849}
5850
5851/// Make a snapshot of all the window scroll positions and sizes of the current
5852/// tab page.
5853void snapshot_windows_scroll_size(void)
5854{
5855  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
5856    wp->w_last_topline = wp->w_topline;
5857    wp->w_last_topfill = wp->w_topfill;
5858    wp->w_last_leftcol = wp->w_leftcol;
5859    wp->w_last_skipcol = wp->w_skipcol;
5860    wp->w_last_width = wp->w_width;
5861    wp->w_last_height = wp->w_height;
5862  }
5863}
5864
5865static bool did_initial_scroll_size_snapshot = false;
5866
5867void may_make_initial_scroll_size_snapshot(void)
5868{
5869  if (!did_initial_scroll_size_snapshot) {
5870    did_initial_scroll_size_snapshot = true;
5871    snapshot_windows_scroll_size();
5872  }
5873}
5874
5875/// Create a dictionary with information about size and scroll changes in a
5876/// window.
5877/// Returns the dictionary with refcount set to one.
5878/// Returns NULL on internal error.
5879static dict_T *make_win_info_dict(int width, int height, int topline, int topfill, int leftcol,
5880                                  int skipcol)
5881{
5882  dict_T *const d = tv_dict_alloc();
5883  d->dv_refcount = 1;
5884
5885  // not actually looping, for breaking out on error
5886  while (true) {
5887    typval_T tv = {
5888      .v_lock = VAR_UNLOCKED,
5889      .v_type = VAR_NUMBER,
5890    };
5891
5892    tv.vval.v_number = width;
5893    if (tv_dict_add_tv(d, S_LEN("width"), &tv) == FAIL) {
5894      break;
5895    }
5896    tv.vval.v_number = height;
5897    if (tv_dict_add_tv(d, S_LEN("height"), &tv) == FAIL) {
5898      break;
5899    }
5900    tv.vval.v_number = topline;
5901    if (tv_dict_add_tv(d, S_LEN("topline"), &tv) == FAIL) {
5902      break;
5903    }
5904    tv.vval.v_number = topfill;
5905    if (tv_dict_add_tv(d, S_LEN("topfill"), &tv) == FAIL) {
5906      break;
5907    }
5908    tv.vval.v_number = leftcol;
5909    if (tv_dict_add_tv(d, S_LEN("leftcol"), &tv) == FAIL) {
5910      break;
5911    }
5912    tv.vval.v_number = skipcol;
5913    if (tv_dict_add_tv(d, S_LEN("skipcol"), &tv) == FAIL) {
5914      break;
5915    }
5916    return d;
5917  }
5918  tv_dict_unref(d);
5919  return NULL;
5920}
5921
5922/// This function is used for three purposes:
5923/// 1. Goes over all windows in the current tab page and sets:
5924///    "size_count" to the nr of windows with size changes.
5925///    "first_scroll_win" to the first window with any relevant changes.
5926///    "first_size_win" to the first window with size changes.
5927///
5928/// 2. When the first three arguments are NULL and "winlist" is not NULL,
5929///    "winlist" is set to the list of window IDs with size changes.
5930///
5931/// 3. When the first three arguments are NULL and "v_event" is not NULL,
5932///    information about changed windows is added to "v_event".
5933static void check_window_scroll_resize(int *size_count, win_T **first_scroll_win,
5934                                       win_T **first_size_win, list_T *winlist, dict_T *v_event)
5935{
5936  // int listidx = 0;
5937  int tot_width = 0;
5938  int tot_height = 0;
5939  int tot_topline = 0;
5940  int tot_topfill = 0;
5941  int tot_leftcol = 0;
5942  int tot_skipcol = 0;
5943
5944  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
5945    // Skip floating windows that do not have a snapshot (usually because they are newly-created),
5946    // as unlike split windows, creating floating windows doesn't cause other windows to resize.
5947    if (wp->w_floating && wp->w_last_topline == 0) {
5948      wp->w_last_topline = wp->w_topline;
5949      wp->w_last_topfill = wp->w_topfill;
5950      wp->w_last_leftcol = wp->w_leftcol;
5951      wp->w_last_skipcol = wp->w_skipcol;
5952      wp->w_last_width = wp->w_width;
5953      wp->w_last_height = wp->w_height;
5954      continue;
5955    }
5956
5957    const bool ignore_scroll = event_ignored(EVENT_WINSCROLLED, wp->w_p_eiw);
5958    const bool size_changed = !event_ignored(EVENT_WINRESIZED, wp->w_p_eiw)
5959                              && (wp->w_last_width != wp->w_width
5960                                  || wp->w_last_height != wp->w_height);
5961    if (size_changed) {
5962      if (winlist != NULL) {
5963        // Add this window to the list of changed windows.
5964        typval_T tv = {
5965          .v_lock = VAR_UNLOCKED,
5966          .v_type = VAR_NUMBER,
5967          .vval.v_number = wp->handle,
5968        };
5969        // tv_list_set_item(winlist, listidx++, &tv);
5970        tv_list_append_owned_tv(winlist, tv);
5971      } else if (size_count != NULL) {
5972        assert(first_size_win != NULL && first_scroll_win != NULL);
5973        (*size_count)++;
5974        if (*first_size_win == NULL) {
5975          *first_size_win = wp;
5976        }
5977        // For WinScrolled the first window with a size change is used
5978        // even when it didn't scroll.
5979        if (*first_scroll_win == NULL && !ignore_scroll) {
5980          *first_scroll_win = wp;
5981        }
5982      }
5983    }
5984
5985    const bool scroll_changed = !ignore_scroll
5986                                && (wp->w_last_topline != wp->w_topline
5987                                    || wp->w_last_topfill != wp->w_topfill
5988                                    || wp->w_last_leftcol != wp->w_leftcol
5989                                    || wp->w_last_skipcol != wp->w_skipcol);
5990    if (scroll_changed && first_scroll_win != NULL && *first_scroll_win == NULL) {
5991      *first_scroll_win = wp;
5992    }
5993
5994    if ((size_changed || scroll_changed) && v_event != NULL) {
5995      // Add info about this window to the v:event dictionary.
5996      int width = wp->w_width - wp->w_last_width;
5997      int height = wp->w_height - wp->w_last_height;
5998      int topline = wp->w_topline - wp->w_last_topline;
5999      int topfill = wp->w_topfill - wp->w_last_topfill;
6000      int leftcol = wp->w_leftcol - wp->w_last_leftcol;
6001      int skipcol = wp->w_skipcol - wp->w_last_skipcol;
6002      dict_T *d = make_win_info_dict(width, height, topline,
6003                                     topfill, leftcol, skipcol);
6004      if (d == NULL) {
6005        break;
6006      }
6007      char winid[NUMBUFLEN];
6008      int key_len = vim_snprintf(winid, sizeof(winid), "%d", wp->handle);
6009      if (tv_dict_add_dict(v_event, winid, (size_t)key_len, d) == FAIL) {
6010        tv_dict_unref(d);
6011        break;
6012      }
6013      d->dv_refcount--;
6014
6015      tot_width += abs(width);
6016      tot_height += abs(height);
6017      tot_topline += abs(topline);
6018      tot_topfill += abs(topfill);
6019      tot_leftcol += abs(leftcol);
6020      tot_skipcol += abs(skipcol);
6021    }
6022  }
6023
6024  if (v_event != NULL) {
6025    dict_T *alldict = make_win_info_dict(tot_width, tot_height, tot_topline,
6026                                         tot_topfill, tot_leftcol, tot_skipcol);
6027    if (alldict != NULL) {
6028      if (tv_dict_add_dict(v_event, S_LEN("all"), alldict) == FAIL) {
6029        tv_dict_unref(alldict);
6030      } else {
6031        alldict->dv_refcount--;
6032      }
6033    }
6034  }
6035}
6036
6037/// Trigger WinScrolled and/or WinResized if any window in the current tab page
6038/// scrolled or changed size.
6039void may_trigger_win_scrolled_resized(void)
6040{
6041  static bool recursive = false;
6042  const bool do_resize = has_event(EVENT_WINRESIZED);
6043  const bool do_scroll = has_event(EVENT_WINSCROLLED);
6044
6045  if (recursive
6046      || !(do_scroll || do_resize)
6047      || !did_initial_scroll_size_snapshot) {
6048    return;
6049  }
6050
6051  int size_count = 0;
6052  win_T *first_scroll_win = NULL;
6053  win_T *first_size_win = NULL;
6054  check_window_scroll_resize(&size_count, &first_scroll_win, &first_size_win, NULL, NULL);
6055  bool trigger_resize = do_resize && size_count > 0;
6056  bool trigger_scroll = do_scroll && first_scroll_win != NULL;
6057  if (!trigger_resize && !trigger_scroll) {
6058    return;  // no relevant changes
6059  }
6060
6061  list_T *windows_list = NULL;
6062  if (trigger_resize) {
6063    // Create the list for v:event.windows before making the snapshot.
6064    // windows_list = tv_list_alloc_with_items(size_count);
6065    windows_list = tv_list_alloc(size_count);
6066    check_window_scroll_resize(NULL, NULL, NULL, windows_list, NULL);
6067  }
6068
6069  dict_T *scroll_dict = NULL;
6070  if (trigger_scroll) {
6071    // Create the dict with entries for v:event before making the snapshot.
6072    scroll_dict = tv_dict_alloc();
6073    scroll_dict->dv_refcount = 1;
6074    check_window_scroll_resize(NULL, NULL, NULL, NULL, scroll_dict);
6075  }
6076
6077  // WinScrolled/WinResized are triggered only once, even when multiple
6078  // windows scrolled or changed size.  Store the current values before
6079  // triggering the event, if a scroll or resize happens as a side effect
6080  // then WinScrolled/WinResized is triggered for that later.
6081  snapshot_windows_scroll_size();
6082
6083  recursive = true;
6084
6085  // Save window info before autocmds since they can free windows
6086  char resize_winid[NUMBUFLEN];
6087  win_T *resize_win = NULL;
6088  bufref_T resize_bufref;
6089  if (trigger_resize) {
6090    resize_win = first_size_win;
6091    vim_snprintf(resize_winid, sizeof(resize_winid), "%d", resize_win->handle);
6092    set_bufref(&resize_bufref, resize_win->w_buffer);
6093  }
6094
6095  char scroll_winid[NUMBUFLEN];
6096  win_T *scroll_win = NULL;
6097  bufref_T scroll_bufref;
6098  if (trigger_scroll) {
6099    scroll_win = first_scroll_win;
6100    vim_snprintf(scroll_winid, sizeof(scroll_winid), "%d", scroll_win->handle);
6101    set_bufref(&scroll_bufref, scroll_win->w_buffer);
6102  }
6103
6104  // If both are to be triggered do WinResized first.
6105  if (trigger_resize && windows_list != NULL) {
6106    save_v_event_T save_v_event;
6107    dict_T *v_event = get_v_event(&save_v_event);
6108
6109    if (tv_dict_add_list(v_event, S_LEN("windows"), windows_list) == OK) {
6110      tv_dict_set_keys_readonly(v_event);
6111      buf_T *buf = bufref_valid(&resize_bufref) ? resize_bufref.br_buf : curbuf;
6112      // May have been freed by an earlier autocmd.
6113      win_T *win = win_valid_any_tab(resize_win) ? resize_win : curwin;
6114      apply_autocmds_win(EVENT_WINRESIZED, resize_winid, resize_winid, false, buf, win);
6115    }
6116    restore_v_event(v_event, &save_v_event);
6117  }
6118
6119  if (trigger_scroll && scroll_dict != NULL) {
6120    save_v_event_T save_v_event;
6121    dict_T *v_event = get_v_event(&save_v_event);
6122
6123    // Move the entries from scroll_dict to v_event.
6124    tv_dict_extend(v_event, scroll_dict, "move");
6125    tv_dict_set_keys_readonly(v_event);
6126    tv_dict_unref(scroll_dict);
6127
6128    buf_T *buf = bufref_valid(&scroll_bufref) ? scroll_bufref.br_buf : curbuf;
6129    // May have been freed by the WinResized autocmds above.
6130    win_T *win = win_valid_any_tab(scroll_win) ? scroll_win : curwin;
6131    apply_autocmds_win(EVENT_WINSCROLLED, scroll_winid, scroll_winid, false, buf, win);
6132
6133    restore_v_event(v_event, &save_v_event);
6134  }
6135
6136  recursive = false;
6137}
6138
6139// Save the size of all windows in "gap".
6140void win_size_save(garray_T *gap)
6141{
6142  ga_init(gap, (int)sizeof(int), 1);
6143  ga_grow(gap, win_count() * 2 + 1);
6144  // first entry is the total lines available for windows
6145  ((int *)gap->ga_data)[gap->ga_len++] =
6146    (int)ROWS_AVAIL + global_stl_height() - last_stl_height(false);
6147
6148  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
6149    ((int *)gap->ga_data)[gap->ga_len++] =
6150      wp->w_width + wp->w_vsep_width;
6151    ((int *)gap->ga_data)[gap->ga_len++] = wp->w_height;
6152  }
6153}
6154
6155// Restore window sizes, but only if the number of windows is still the same
6156// and total lines available for windows didn't change.
6157// Does not free the growarray.
6158void win_size_restore(garray_T *gap)
6159  FUNC_ATTR_NONNULL_ALL
6160{
6161  if (win_count() * 2 + 1 == gap->ga_len
6162      && ((int *)gap->ga_data)[0] ==
6163      ROWS_AVAIL + global_stl_height() - last_stl_height(false)) {
6164    // The order matters, because frames contain other frames, but it's
6165    // difficult to get right. The easy way out is to do it twice.
6166    for (int j = 0; j < 2; j++) {
6167      int i = 1;
6168      FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
6169        int width = ((int *)gap->ga_data)[i++];
6170        int height = ((int *)gap->ga_data)[i++];
6171        if (!wp->w_floating) {
6172          frame_setwidth(wp->w_frame, width, true);
6173          win_setheight_win(height, wp, true);
6174        }
6175      }
6176    }
6177    // recompute the window positions
6178    win_comp_pos();
6179  }
6180}
6181
6182// Update the position for all windows, using the width and height of the frames.
6183// Returns the row just after the last window and global statusline (if there is one).
6184int win_comp_pos(void)
6185{
6186  int row = tabline_height();
6187  int col = 0;
6188
6189  frame_comp_pos(topframe, &row, &col);
6190
6191  for (win_T *wp = lastwin; wp && wp->w_floating; wp = wp->w_prev) {
6192    // float might be anchored to moved window
6193    if (wp->w_config.relative == kFloatRelativeWindow) {
6194      wp->w_pos_changed = true;
6195    }
6196  }
6197
6198  return row + global_stl_height();
6199}
6200
6201// Update the position of the windows in frame "topfrp", using the width and
6202// height of the frames.
6203// "*row" and "*col" are the top-left position of the frame.  They are updated
6204// to the bottom-right position plus one.
6205static void frame_comp_pos(frame_T *topfrp, int *row, int *col)
6206{
6207  win_T *wp = topfrp->fr_win;
6208  if (wp != NULL) {
6209    if (wp->w_winrow != *row
6210        || wp->w_wincol != *col) {
6211      // position changed, redraw
6212      wp->w_winrow = *row;
6213      wp->w_wincol = *col;
6214      redraw_later(wp, UPD_NOT_VALID);
6215      wp->w_redr_status = true;
6216      wp->w_pos_changed = true;
6217    }
6218    const int h = wp->w_height + wp->w_hsep_height + wp->w_status_height;
6219    *row += h > topfrp->fr_height ? topfrp->fr_height : h;
6220    *col += wp->w_width + wp->w_vsep_width;
6221  } else {
6222    int startrow = *row;
6223    int startcol = *col;
6224    frame_T *frp;
6225    FOR_ALL_FRAMES(frp, topfrp->fr_child) {
6226      if (topfrp->fr_layout == FR_ROW) {
6227        *row = startrow;  // all frames are at the same row
6228      } else {
6229        *col = startcol;  // all frames are at the same col
6230      }
6231      frame_comp_pos(frp, row, col);
6232    }
6233  }
6234}
6235
6236// Set current window height and take care of repositioning other windows to
6237// fit around it.
6238void win_setheight(int height)
6239{
6240  win_setheight_win(height, curwin, true);
6241}
6242
6243// Set the window height of window "win" and take care of repositioning other
6244// windows to fit around it.
6245// from_top: keep the top edge anchored (take space from the window below first).
6246void win_setheight_win(int height, win_T *win, bool from_top)
6247{
6248  // Always keep current window at least one line high, even when 'winminheight' is zero.
6249  // Keep window at least two lines high if 'winbar' is enabled.
6250  height = MAX(height, (int)(win == curwin ? MAX(p_wmh, 1) : p_wmh) + win->w_winbar_height);
6251
6252  if (win->w_floating) {
6253    win->w_config.height = MAX(height, 1);
6254    win_config_float(win, win->w_config);
6255    redraw_later(win, UPD_VALID);
6256  } else {
6257    frame_setheight(win->w_frame, height + win->w_hsep_height + win->w_status_height,
6258                    from_top);
6259
6260    // recompute the window positions
6261    win_comp_pos();
6262    win_fix_scroll(true);
6263
6264    redraw_all_later(UPD_NOT_VALID);
6265    redraw_cmdline = true;
6266  }
6267}
6268
6269// Set the height of a frame to "height" and take care that all frames and
6270// windows inside it are resized.  Also resize frames on the left and right if
6271// the are in the same FR_ROW frame.
6272//
6273// Strategy:
6274// If the frame is part of a FR_COL frame, try fitting the frame in that
6275// frame.  If that doesn't work (the FR_COL frame is too small), recursively
6276// go to containing frames to resize them and make room.
6277// If the frame is part of a FR_ROW frame, all frames must be resized as well.
6278// Check for the minimal height of the FR_ROW frame.
6279// At the top level we can also use change the command line height.
6280static void frame_setheight(frame_T *curfrp, int height, bool from_top)
6281{
6282  // If the height already is the desired value, nothing to do.
6283  if (curfrp->fr_height == height) {
6284    return;
6285  }
6286
6287  if (curfrp->fr_parent == NULL) {
6288    // topframe: can only change the command line height
6289    if (height > 0) {
6290      frame_new_height(curfrp, height, false, false, true);
6291    }
6292  } else if (curfrp->fr_parent->fr_layout == FR_ROW) {
6293    // Row of frames: Also need to resize frames left and right of this
6294    // one.  First check for the minimal height of these.
6295    int h = frame_minheight(curfrp->fr_parent, NULL);
6296    height = MAX(height, h);
6297    frame_setheight(curfrp->fr_parent, height, from_top);
6298  } else {
6299    // Column of frames: try to change only frames in this column.
6300
6301    int room;                     // total number of lines available
6302    int room_cmdline;             // lines available from cmdline
6303    int room_reserved;
6304
6305    // Do this twice:
6306    // 1: compute room available, if it's not enough try resizing the
6307    //    containing frame.
6308    // 2: compute the room available and adjust the height to it.
6309    // Try not to reduce the height of a window with 'winfixheight' set.
6310    for (int run = 1; run <= 2; run++) {
6311      room = 0;
6312      room_reserved = 0;
6313      frame_T *frp;
6314      FOR_ALL_FRAMES(frp, curfrp->fr_parent->fr_child) {
6315        if (frp != curfrp
6316            && frp->fr_win != NULL
6317            && frp->fr_win->w_p_wfh) {
6318          room_reserved += frp->fr_height;
6319        }
6320        room += frp->fr_height;
6321        if (frp != curfrp) {
6322          room -= frame_minheight(frp, NULL);
6323        }
6324      }
6325      // For bottom-anchored resize, treat cmdline room as zero.
6326      if (!from_top || curfrp->fr_width != Columns) {
6327        room_cmdline = 0;
6328      } else {
6329        win_T *wp = lastwin_nofloating(NULL);
6330        room_cmdline = Rows - (int)p_ch - global_stl_height()
6331                       - (wp->w_winrow + wp->w_height + wp->w_hsep_height + wp->w_status_height);
6332        room_cmdline = MAX(room_cmdline, 0);
6333      }
6334
6335      if (height <= room + room_cmdline) {
6336        break;
6337      }
6338      if (run == 2 || curfrp->fr_width == Columns) {
6339        height = room + room_cmdline;
6340        break;
6341      }
6342      frame_setheight(curfrp->fr_parent, height
6343                      + frame_minheight(curfrp->fr_parent, NOWIN) - (int)p_wmh - 1,
6344                      from_top);
6345      // NOTREACHED
6346    }
6347
6348    // Compute the number of lines we will take from others frames (can be
6349    // negative!).
6350    int take = height - curfrp->fr_height;
6351
6352    // If there is not enough room, also reduce the height of a window
6353    // with 'winfixheight' set.
6354    if (height > room + room_cmdline - room_reserved) {
6355      room_reserved = room + room_cmdline - height;
6356    }
6357    // If there is only a 'winfixheight' window and making the
6358    // window smaller, need to make the other window taller.
6359    if (take < 0 && room - curfrp->fr_height <= room_reserved) {
6360      room_reserved = 0;
6361    }
6362
6363    if (take > 0 && room_cmdline > 0) {
6364      // use lines from cmdline first
6365      room_cmdline = MIN(room_cmdline, take),
6366      take -= room_cmdline;
6367      topframe->fr_height += room_cmdline;
6368    }
6369
6370    // set the current frame to the new height
6371    frame_new_height(curfrp, height, false, false, true);
6372
6373    // First take lines from the frames after the current frame.  If
6374    // that is not enough, takes lines from frames above the current
6375    // frame.
6376    for (int run = 0; run < 2; run++) {
6377      // 1st run: from the non-anchored side
6378      // 2nd run: the anchored side
6379      bool forward = (run == 0) == from_top;
6380      frame_T *frp = forward ? curfrp->fr_next : curfrp->fr_prev;
6381
6382      while (frp != NULL && take != 0) {
6383        int h = frame_minheight(frp, NULL);
6384        if (room_reserved > 0
6385            && frp->fr_win != NULL
6386            && frp->fr_win->w_p_wfh) {
6387          if (room_reserved >= frp->fr_height) {
6388            room_reserved -= frp->fr_height;
6389          } else {
6390            if (frp->fr_height - room_reserved > take) {
6391              room_reserved = frp->fr_height - take;
6392            }
6393            take -= frp->fr_height - room_reserved;
6394            frame_new_height(frp, room_reserved, false, false, true);
6395            room_reserved = 0;
6396          }
6397        } else {
6398          if (frp->fr_height - take < h) {
6399            take -= frp->fr_height - h;
6400            frame_new_height(frp, h, false, false, true);
6401          } else {
6402            frame_new_height(frp, frp->fr_height - take, false, false, true);
6403            take = 0;
6404          }
6405        }
6406        frp = forward ? frp->fr_next : frp->fr_prev;
6407      }
6408    }
6409  }
6410}
6411
6412// Set current window width and take care of repositioning other windows to
6413// fit around it.
6414void win_setwidth(int width)
6415{
6416  win_setwidth_win(width, curwin, true);
6417}
6418
6419void win_setwidth_win(int width, win_T *wp, bool from_left)
6420{
6421  // Always keep current window at least one column wide, even when
6422  // 'winminwidth' is zero.
6423  if (wp == curwin) {
6424    width = MAX(MAX(width, (int)p_wmw), 1);
6425  } else if (width < 0) {
6426    width = 0;
6427  }
6428  if (wp->w_floating) {
6429    wp->w_config.width = width;
6430    win_config_float(wp, wp->w_config);
6431    redraw_later(wp, UPD_NOT_VALID);
6432  } else {
6433    frame_setwidth(wp->w_frame, width + wp->w_vsep_width, from_left);
6434
6435    // recompute the window positions
6436    win_comp_pos();
6437    redraw_all_later(UPD_NOT_VALID);
6438  }
6439}
6440
6441// Set the width of a frame to "width" and take care that all frames and
6442// windows inside it are resized.  Also resize frames above and below if the
6443// are in the same FR_ROW frame.
6444//
6445// Strategy is similar to frame_setheight().
6446static void frame_setwidth(frame_T *curfrp, int width, bool from_left)
6447{
6448  // If the width already is the desired value, nothing to do.
6449  if (curfrp->fr_width == width) {
6450    return;
6451  }
6452
6453  if (curfrp->fr_parent == NULL) {
6454    // topframe: can't change width
6455    return;
6456  }
6457
6458  if (curfrp->fr_parent->fr_layout == FR_COL) {
6459    // Column of frames: Also need to resize frames above and below of
6460    // this one.  First check for the minimal width of these.
6461    int w = frame_minwidth(curfrp->fr_parent, NULL);
6462    width = MAX(width, w);
6463    frame_setwidth(curfrp->fr_parent, width, from_left);
6464  } else {
6465    // Row of frames: try to change only frames in this row.
6466    //
6467    // Do this twice:
6468    // 1: compute room available, if it's not enough try resizing the
6469    //    containing frame.
6470    // 2: compute the room available and adjust the width to it.
6471
6472    int room;  // total number of lines available
6473    int room_reserved;
6474    for (int run = 1; run <= 2; run++) {
6475      room = 0;
6476      room_reserved = 0;
6477      frame_T *frp;
6478      FOR_ALL_FRAMES(frp, curfrp->fr_parent->fr_child) {
6479        if (frp != curfrp
6480            && frp->fr_win != NULL
6481            && frp->fr_win->w_p_wfw) {
6482          room_reserved += frp->fr_width;
6483        }
6484        room += frp->fr_width;
6485        if (frp != curfrp) {
6486          room -= frame_minwidth(frp, NULL);
6487        }
6488      }
6489
6490      if (width <= room) {
6491        break;
6492      }
6493      if (run == 2 || curfrp->fr_height >= ROWS_AVAIL) {
6494        width = room;
6495        break;
6496      }
6497      frame_setwidth(curfrp->fr_parent, width
6498                     + frame_minwidth(curfrp->fr_parent, NOWIN) - (int)p_wmw - 1, from_left);
6499    }
6500
6501    // Compute the number of lines we will take from others frames (can be
6502    // negative!).
6503    int take = width - curfrp->fr_width;
6504
6505    // If there is not enough room, also reduce the width of a window
6506    // with 'winfixwidth' set.
6507    if (width > room - room_reserved) {
6508      room_reserved = room - width;
6509    }
6510    // If there is only a 'winfixwidth' window and making the
6511    // window smaller, need to make the other window narrower.
6512    if (take < 0 && room - curfrp->fr_width < room_reserved) {
6513      room_reserved = 0;
6514    }
6515
6516    // set the current frame to the new width
6517    frame_new_width(curfrp, width, false, false);
6518
6519    // First take lines from the frames right of the current frame.  If
6520    // that is not enough, takes lines from frames left of the current
6521    // frame.
6522    for (int run = 0; run < 2; run++) {
6523      // 1st run: from the non-anchored side
6524      // 2nd run: the anchored side
6525      bool forward = (run == 0) == from_left;
6526      frame_T *frp = forward ? curfrp->fr_next : curfrp->fr_prev;
6527
6528      while (frp != NULL && take != 0) {
6529        int w = frame_minwidth(frp, NULL);
6530        if (room_reserved > 0
6531            && frp->fr_win != NULL
6532            && frp->fr_win->w_p_wfw) {
6533          if (room_reserved >= frp->fr_width) {
6534            room_reserved -= frp->fr_width;
6535          } else {
6536            if (frp->fr_width - room_reserved > take) {
6537              room_reserved = frp->fr_width - take;
6538            }
6539            take -= frp->fr_width - room_reserved;
6540            frame_new_width(frp, room_reserved, false, false);
6541            room_reserved = 0;
6542          }
6543        } else {
6544          if (frp->fr_width - take < w) {
6545            take -= frp->fr_width - w;
6546            frame_new_width(frp, w, false, false);
6547          } else {
6548            frame_new_width(frp, frp->fr_width - take, false, false);
6549            take = 0;
6550          }
6551        }
6552        frp = forward ? frp->fr_next : frp->fr_prev;
6553      }
6554    }
6555  }
6556}
6557
6558// Check 'winminheight' for a valid value and reduce it if needed.
6559const char *did_set_winminheight(optset_T *args FUNC_ATTR_UNUSED)
6560{
6561  bool first = true;
6562
6563  // loop until there is a 'winminheight' that is possible
6564  while (p_wmh > 0) {
6565    const int room = Rows - (int)p_ch;
6566    const int needed = min_rows_for_all_tabpages();
6567    if (room >= needed) {
6568      break;
6569    }
6570    p_wmh--;
6571    if (first) {
6572      emsg(_(e_noroom));
6573      first = false;
6574    }
6575  }
6576  return NULL;
6577}
6578
6579// Check 'winminwidth' for a valid value and reduce it if needed.
6580const char *did_set_winminwidth(optset_T *args FUNC_ATTR_UNUSED)
6581{
6582  bool first = true;
6583
6584  // loop until there is a 'winminheight' that is possible
6585  while (p_wmw > 0) {
6586    const int room = Columns;
6587    const int needed = frame_minwidth(topframe, NULL);
6588    if (room >= needed) {
6589      break;
6590    }
6591    p_wmw--;
6592    if (first) {
6593      emsg(_(e_noroom));
6594      first = false;
6595    }
6596  }
6597  return NULL;
6598}
6599
6600/// Status line of dragwin is dragged "offset" lines down (negative is up).
6601void win_drag_status_line(win_T *dragwin, int offset)
6602{
6603  frame_T *fr = dragwin->w_frame;
6604  frame_T *curfr = fr;
6605  if (fr != topframe) {         // more than one window
6606    fr = fr->fr_parent;
6607    // When the parent frame is not a column of frames, its parent should
6608    // be.
6609    if (fr->fr_layout != FR_COL) {
6610      curfr = fr;
6611      if (fr != topframe) {     // only a row of windows, may drag statusline
6612        fr = fr->fr_parent;
6613      }
6614    }
6615  }
6616
6617  // If this is the last frame in a column, may want to resize the parent
6618  // frame instead (go two up to skip a row of frames).
6619  while (curfr != topframe && curfr->fr_next == NULL) {
6620    if (fr != topframe) {
6621      fr = fr->fr_parent;
6622    }
6623    curfr = fr;
6624    if (fr != topframe) {
6625      fr = fr->fr_parent;
6626    }
6627  }
6628
6629  int room;
6630  const bool up = offset < 0;  // if true, drag status line up, otherwise down
6631
6632  if (up) {  // drag up
6633    offset = -offset;
6634    // sum up the room of the current frame and above it
6635    if (fr == curfr) {
6636      // only one window
6637      room = fr->fr_height - frame_minheight(fr, NULL);
6638    } else {
6639      room = 0;
6640      for (fr = fr->fr_child;; fr = fr->fr_next) {
6641        room += fr->fr_height - frame_minheight(fr, NULL);
6642        if (fr == curfr) {
6643          break;
6644        }
6645      }
6646    }
6647    fr = curfr->fr_next;                // put fr at frame that grows
6648  } else {  // drag down
6649    // Only dragging the last status line can reduce p_ch.
6650    room = Rows - cmdline_row;
6651    if (curfr->fr_next != NULL) {
6652      room -= (int)p_ch + global_stl_height();
6653    } else if (min_set_ch > 0) {
6654      room--;
6655    }
6656    room = MAX(room, 0);
6657    // sum up the room of frames below of the current one
6658    FOR_ALL_FRAMES(fr, curfr->fr_next) {
6659      room += fr->fr_height - frame_minheight(fr, NULL);
6660    }
6661    fr = curfr;  // put fr at window that grows
6662  }
6663
6664  // If not enough room then move as far as we can
6665  offset = MIN(offset, room);
6666  if (offset <= 0) {
6667    return;
6668  }
6669
6670  // Grow frame fr by "offset" lines.
6671  // Doesn't happen when dragging the last status line up.
6672  if (fr != NULL) {
6673    frame_new_height(fr, fr->fr_height + offset, up, false, true);
6674  }
6675
6676  if (up) {
6677    fr = curfr;                 // current frame gets smaller
6678  } else {
6679    fr = curfr->fr_next;        // next frame gets smaller
6680  }
6681  // Now make the other frames smaller.
6682  while (fr != NULL && offset > 0) {
6683    int n = frame_minheight(fr, NULL);
6684    if (fr->fr_height - offset <= n) {
6685      offset -= fr->fr_height - n;
6686      frame_new_height(fr, n, !up, false, true);
6687    } else {
6688      frame_new_height(fr, fr->fr_height - offset, !up, false, true);
6689      break;
6690    }
6691    if (up) {
6692      fr = fr->fr_prev;
6693    } else {
6694      fr = fr->fr_next;
6695    }
6696  }
6697  win_comp_pos();
6698  win_fix_scroll(true);
6699
6700  redraw_all_later(UPD_SOME_VALID);
6701  showmode();
6702}
6703
6704// Separator line of dragwin is dragged "offset" lines right (negative is left).
6705void win_drag_vsep_line(win_T *dragwin, int offset)
6706{
6707  frame_T *fr = dragwin->w_frame;
6708  if (fr == topframe) {         // only one window (cannot happen?)
6709    return;
6710  }
6711  frame_T *curfr = fr;
6712  fr = fr->fr_parent;
6713  // When the parent frame is not a row of frames, its parent should be.
6714  if (fr->fr_layout != FR_ROW) {
6715    if (fr == topframe) {       // only a column of windows (cannot happen?)
6716      return;
6717    }
6718    curfr = fr;
6719    fr = fr->fr_parent;
6720  }
6721
6722  // If this is the last frame in a row, may want to resize a parent
6723  // frame instead.
6724  while (curfr->fr_next == NULL) {
6725    if (fr == topframe) {
6726      break;
6727    }
6728    curfr = fr;
6729    fr = fr->fr_parent;
6730    if (fr != topframe) {
6731      curfr = fr;
6732      fr = fr->fr_parent;
6733    }
6734  }
6735
6736  int room;
6737  const bool left = offset < 0;  // if true, drag separator line left, otherwise right
6738
6739  if (left) {  // drag left
6740    offset = -offset;
6741    // sum up the room of the current frame and left of it
6742    room = 0;
6743    for (fr = fr->fr_child;; fr = fr->fr_next) {
6744      room += fr->fr_width - frame_minwidth(fr, NULL);
6745      if (fr == curfr) {
6746        break;
6747      }
6748    }
6749    fr = curfr->fr_next;                // put fr at frame that grows
6750  } else {  // drag right
6751    // sum up the room of frames right of the current one
6752    room = 0;
6753    FOR_ALL_FRAMES(fr, curfr->fr_next) {
6754      room += fr->fr_width - frame_minwidth(fr, NULL);
6755    }
6756    fr = curfr;  // put fr at window that grows
6757  }
6758
6759  // If not enough room then move as far as we can
6760  offset = MIN(offset, room);
6761
6762  // No room at all, quit.
6763  if (offset <= 0) {
6764    return;
6765  }
6766
6767  if (fr == NULL) {
6768    // This can happen when calling win_move_separator() on the rightmost
6769    // window.  Just don't do anything.
6770    return;
6771  }
6772
6773  // grow frame fr by offset lines
6774  frame_new_width(fr, fr->fr_width + offset, left, false);
6775
6776  // shrink other frames: current and at the left or at the right
6777  if (left) {
6778    fr = curfr;                 // current frame gets smaller
6779  } else {
6780    fr = curfr->fr_next;        // next frame gets smaller
6781  }
6782  while (fr != NULL && offset > 0) {
6783    int n = frame_minwidth(fr, NULL);
6784    if (fr->fr_width - offset <= n) {
6785      offset -= fr->fr_width - n;
6786      frame_new_width(fr, n, !left, false);
6787    } else {
6788      frame_new_width(fr, fr->fr_width - offset, !left, false);
6789      break;
6790    }
6791    if (left) {
6792      fr = fr->fr_prev;
6793    } else {
6794      fr = fr->fr_next;
6795    }
6796  }
6797  win_comp_pos();
6798  redraw_all_later(UPD_NOT_VALID);
6799}
6800
6801#define FRACTION_MULT   16384
6802
6803// Set wp->w_fraction for the current w_wrow and w_height.
6804// Has no effect when the window is less than two lines.
6805void set_fraction(win_T *wp)
6806{
6807  if (wp->w_view_height > 1) {
6808    // When cursor is in the first line the percentage is computed as if
6809    // it's halfway that line.  Thus with two lines it is 25%, with three
6810    // lines 17%, etc.  Similarly for the last line: 75%, 83%, etc.
6811    wp->w_fraction = (wp->w_wrow * FRACTION_MULT + FRACTION_MULT / 2) / wp->w_view_height;
6812  }
6813}
6814
6815/// Handle scroll position, depending on 'splitkeep'.  Replaces the
6816/// scroll_to_fraction() call from win_new_height() if 'splitkeep' is "screen"
6817/// or "topline".  Instead we iterate over all windows in a tabpage and
6818/// calculate the new scroll position.
6819/// TODO(vim): Ensure this also works with wrapped lines.
6820/// Requires a not fully visible cursor line to be allowed at the bottom of
6821/// a window ("zb"), probably only when 'smoothscroll' is also set.
6822void win_fix_scroll(bool resize)
6823{
6824  if (*p_spk == 'c') {
6825    return;  // 'splitkeep' is "cursor"
6826  }
6827
6828  skip_update_topline = true;
6829  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
6830    // Skip when window height has not changed or when floating.
6831    if (!wp->w_floating && wp->w_height != wp->w_prev_height) {
6832      // Cursor position in this window may now be invalid.  It is kept
6833      // potentially invalid until the window is made the current window.
6834      wp->w_do_win_fix_cursor = true;
6835
6836      // If window has moved update botline to keep the same screenlines.
6837      if (*p_spk == 's' && wp->w_winrow != wp->w_prev_winrow
6838          && wp->w_botline - 1 <= wp->w_buffer->b_ml.ml_line_count) {
6839        int diff = (wp->w_winrow - wp->w_prev_winrow)
6840                   + (wp->w_height - wp->w_prev_height);
6841        pos_T cursor = wp->w_cursor;
6842        wp->w_cursor.lnum = wp->w_botline - 1;
6843
6844        // Add difference in height and row to botline.
6845        if (diff > 0) {
6846          cursor_down_inner(wp, diff, false);
6847        } else {
6848          cursor_up_inner(wp, -diff, false);
6849        }
6850
6851        // Scroll to put the new cursor position at the bottom of the
6852        // screen.
6853        wp->w_fraction = FRACTION_MULT;
6854        scroll_to_fraction(wp, wp->w_prev_height);
6855        wp->w_cursor = cursor;
6856        wp->w_valid &= ~VALID_WCOL;
6857      } else if (wp == curwin) {
6858        wp->w_valid &= ~VALID_CROW;
6859      }
6860
6861      invalidate_botline_win(wp);
6862      validate_botline_win(wp);
6863    }
6864    wp->w_prev_height = wp->w_height;
6865    wp->w_prev_winrow = wp->w_winrow;
6866  }
6867  skip_update_topline = false;
6868  // Ensure cursor is valid when not in normal mode or when resized.
6869  if (!(get_real_state() & (MODE_NORMAL|MODE_CMDLINE|MODE_TERMINAL))) {
6870    win_fix_cursor(false);
6871  } else if (resize) {
6872    win_fix_cursor(true);
6873  }
6874}
6875
6876/// Make sure the cursor position is valid for 'splitkeep'.
6877/// If it is not, put the cursor position in the jumplist and move it.
6878/// If we are not in normal mode ("normal" is false), make it valid by scrolling
6879/// instead.
6880static void win_fix_cursor(bool normal)
6881{
6882  win_T *wp = curwin;
6883
6884  if (!wp->w_do_win_fix_cursor
6885      || wp->w_buffer->b_ml.ml_line_count < wp->w_view_height) {
6886    return;
6887  }
6888
6889  wp->w_do_win_fix_cursor = false;
6890  // Determine valid cursor range.
6891  int so = (int)MIN(wp->w_view_height / 2, get_scrolloff_value(wp));
6892  linenr_T lnum = wp->w_cursor.lnum;
6893
6894  wp->w_cursor.lnum = wp->w_topline;
6895  cursor_down_inner(wp, so, false);
6896  linenr_T top = wp->w_cursor.lnum;
6897
6898  wp->w_cursor.lnum = wp->w_botline - 1;
6899  cursor_up_inner(wp, so, false);
6900  linenr_T bot = wp->w_cursor.lnum;
6901
6902  wp->w_cursor.lnum = lnum;
6903  // Check if cursor position is above or below valid cursor range.
6904  linenr_T nlnum = 0;
6905  if (lnum > bot && (wp->w_botline - wp->w_buffer->b_ml.ml_line_count) != 1) {
6906    nlnum = bot;
6907  } else if (lnum < top && wp->w_topline != 1) {
6908    nlnum = (so == wp->w_view_height / 2) ? bot : top;
6909  }
6910
6911  if (nlnum != 0) {  // Cursor is invalid for current scroll position.
6912    if (normal) {    // Save to jumplist and set cursor to avoid scrolling.
6913      setmark('\'');
6914      wp->w_cursor.lnum = nlnum;
6915    } else {         // Scroll instead when not in normal mode.
6916      wp->w_fraction = (nlnum == bot) ? FRACTION_MULT : 0;
6917      scroll_to_fraction(wp, wp->w_prev_height);
6918      validate_botline_win(curwin);
6919    }
6920  }
6921}
6922
6923// Set the height of a window.
6924// "height" excludes any window toolbar.
6925// This takes care of the things inside the window, not what happens to the
6926// window position, the frame or to other windows.
6927void win_new_height(win_T *wp, int height)
6928{
6929  // Don't want a negative height.  Happens when splitting a tiny window.
6930  // Will equalize heights soon to fix it.
6931  height = MAX(height, 0);
6932  if (wp->w_height == height) {
6933    return;  // nothing to do
6934  }
6935
6936  wp->w_height = height;
6937  wp->w_pos_changed = true;
6938  win_set_inner_size(wp, true);
6939}
6940
6941void scroll_to_fraction(win_T *wp, int prev_height)
6942{
6943  int height = wp->w_view_height;
6944
6945  // Don't change w_topline in any of these cases:
6946  // - window height is 0
6947  // - 'scrollbind' is set and this isn't the current window
6948  // - window height is sufficient to display the whole buffer and first line
6949  //   is visible.
6950  if (height > 0
6951      && (!wp->w_p_scb || wp == curwin)
6952      && (height < wp->w_buffer->b_ml.ml_line_count
6953          || wp->w_topline > 1)) {
6954    // Find a value for w_topline that shows the cursor at the same
6955    // relative position in the window as before (more or less).
6956    linenr_T lnum = wp->w_cursor.lnum;
6957    // can happen when starting up
6958    lnum = MAX(lnum, 1);
6959    wp->w_wrow = (wp->w_fraction * height - 1) / FRACTION_MULT;
6960    int line_size = plines_win_col(wp, lnum, wp->w_cursor.col) - 1;
6961    int sline = wp->w_wrow - line_size;
6962
6963    if (sline >= 0) {
6964      // Make sure the whole cursor line is visible, if possible.
6965      const int rows = plines_win(wp, lnum, false);
6966
6967      if (sline > wp->w_view_height - rows) {
6968        sline = wp->w_view_height - rows;
6969        wp->w_wrow -= rows - line_size;
6970      }
6971    }
6972
6973    if (sline < 0) {
6974      // Cursor line would go off top of screen if w_wrow was this high.
6975      // Make cursor line the first line in the window.  If not enough
6976      // room use w_skipcol;
6977      wp->w_wrow = line_size;
6978      if (wp->w_wrow >= wp->w_view_height
6979          && (wp->w_view_width - win_col_off(wp)) > 0) {
6980        // The cursor must be visible, override the scroll position.
6981        colnr_T skipcol = wp->w_view_width - win_col_off(wp);
6982        wp->w_wrow--;
6983        while (wp->w_wrow >= wp->w_view_height) {
6984          skipcol += wp->w_view_width - win_col_off(wp) + win_col_off2(wp);
6985          wp->w_wrow--;
6986        }
6987        wp->w_skipcol = skipcol;
6988      }
6989    } else if (sline > 0) {
6990      while (sline > 0 && lnum > 1) {
6991        hasFolding(wp, lnum, &lnum, NULL);
6992        if (lnum == 1) {
6993          // first line in buffer is folded
6994          line_size = !decor_conceal_line(wp, lnum - 1, false);
6995          sline--;
6996          break;
6997        }
6998        lnum--;
6999        if (lnum == wp->w_topline) {
7000          line_size = plines_win_nofill(wp, lnum, true)
7001                      + wp->w_topfill;
7002        } else {
7003          line_size = plines_win(wp, lnum, true);
7004        }
7005        sline -= line_size;
7006      }
7007
7008      if (sline < 0) {
7009        // Line we want at top would go off top of screen.  Use next
7010        // line instead.
7011        hasFolding(wp, lnum, NULL, &lnum);
7012        lnum++;
7013        wp->w_wrow -= line_size + sline;
7014      } else if (sline > 0) {
7015        // First line of file reached, use that as topline.
7016        lnum = 1;
7017        wp->w_wrow -= sline;
7018      }
7019    }
7020    set_topline(wp, lnum);
7021  }
7022
7023  if (wp == curwin) {
7024    curs_columns(wp, false);        // validate w_wrow
7025  }
7026  if (prev_height > 0) {
7027    wp->w_prev_fraction_row = wp->w_wrow;
7028  }
7029
7030  redraw_later(wp, UPD_SOME_VALID);
7031  invalidate_botline_win(wp);
7032}
7033
7034void win_set_inner_size(win_T *wp, bool valid_cursor)
7035{
7036  int width = wp->w_width_request;
7037  if (width == 0) {
7038    width = wp->w_width;
7039  }
7040
7041  int prev_height = wp->w_view_height;
7042  int height = wp->w_height_request;
7043  if (height == 0) {
7044    height = MAX(0, wp->w_height - wp->w_winbar_height);
7045  }
7046
7047  if (height != prev_height) {
7048    if (height > 0 && valid_cursor) {
7049      if (wp == curwin && (*p_spk == 'c' || wp->w_floating)) {
7050        // w_wrow needs to be valid. When setting 'laststatus' this may
7051        // call win_new_height() recursively.
7052        validate_cursor(curwin);
7053      }
7054      if (wp->w_view_height != prev_height) {
7055        return;  // Recursive call already changed the size, bail out.
7056      }
7057      if (wp->w_wrow != wp->w_prev_fraction_row) {
7058        set_fraction(wp);
7059      }
7060    }
7061    wp->w_view_height = height;
7062    win_comp_scroll(wp);
7063
7064    // There is no point in adjusting the scroll position when exiting.  Some
7065    // values might be invalid.
7066    if (valid_cursor && !exiting && (*p_spk == 'c' || wp->w_floating)) {
7067      // With 'smoothscroll' w_skipcol is the scroll position, keep it.
7068      // Otherwise it only keeps the cursor visible and is computed again.
7069      if (!wp->w_p_sms) {
7070        wp->w_skipcol = 0;
7071      }
7072      scroll_to_fraction(wp, prev_height);
7073    }
7074    redraw_later(wp, UPD_SOME_VALID);
7075  }
7076
7077  if (width != wp->w_view_width) {
7078    wp->w_view_width = width;
7079    wp->w_lines_valid = 0;
7080    if (valid_cursor) {
7081      changed_line_abv_curs_win(wp);
7082      invalidate_botline_win(wp);
7083      if (wp == curwin && (*p_spk == 'c' || wp->w_floating)) {
7084        curs_columns(wp, true);  // validate w_wrow
7085      }
7086    }
7087    redraw_later(wp, UPD_NOT_VALID);
7088  }
7089
7090  if (wp->w_buffer->terminal) {
7091    terminal_check_size(wp->w_buffer->terminal);
7092  }
7093
7094  int float_stl_height = wp->w_floating && wp->w_status_height ? STATUS_HEIGHT : 0;
7095  wp->w_height_outer = (wp->w_view_height + win_border_height(wp) + wp->w_winbar_height +
7096                        float_stl_height);
7097  wp->w_width_outer = (wp->w_view_width + win_border_width(wp));
7098  wp->w_winrow_off = wp->w_border_adj[0] + wp->w_winbar_height;
7099  wp->w_wincol_off = wp->w_border_adj[3];
7100
7101  if (ui_has(kUIMultigrid)) {
7102    ui_call_win_viewport_margins(wp->w_grid_alloc.handle, wp->handle,
7103                                 wp->w_winrow_off, wp->w_border_adj[2],
7104                                 wp->w_wincol_off, wp->w_border_adj[1]);
7105  }
7106
7107  wp->w_redr_status = true;
7108
7109  // Must keep grid dimensions updated during redraw.
7110  if (updating_screen) {
7111    win_grid_alloc(wp);
7112  }
7113}
7114
7115/// Set the width of a window.
7116void win_new_width(win_T *wp, int width)
7117{
7118  // Should we give an error if width < 0?
7119  wp->w_width = width < 0 ? 0 : width;
7120  wp->w_pos_changed = true;
7121  win_set_inner_size(wp, true);
7122}
7123
7124OptInt win_default_scroll(win_T *wp)
7125{
7126  return MAX(wp->w_view_height / 2, 1);
7127}
7128
7129void win_comp_scroll(win_T *wp)
7130{
7131  const OptInt old_w_p_scr = wp->w_p_scr;
7132  wp->w_p_scr = win_default_scroll(wp);
7133
7134  if (wp->w_p_scr != old_w_p_scr) {
7135    // Used by "verbose set scroll".
7136    wp->w_p_script_ctx[kWinOptScroll].sc_sid = SID_WINLAYOUT;
7137    wp->w_p_script_ctx[kWinOptScroll].sc_lnum = 0;
7138  }
7139}
7140
7141/// command_height: called whenever p_ch has been changed.
7142void command_height(void)
7143{
7144  int old_p_ch = (int)curtab->tp_ch_used;
7145
7146  // Find bottom frame with width of screen.
7147  frame_T *frp = lastwin_nofloating(NULL)->w_frame;
7148  while (frp->fr_width != Columns && frp->fr_parent != NULL) {
7149    frp = frp->fr_parent;
7150  }
7151
7152  // Avoid changing the height of a window with 'winfixheight' set.
7153  while (frp->fr_prev != NULL && frp->fr_layout == FR_LEAF && frp->fr_win->w_p_wfh) {
7154    frp = frp->fr_prev;
7155  }
7156
7157  while (p_ch > old_p_ch && command_frame_height) {
7158    if (frp == NULL) {
7159      emsg(_(e_noroom));
7160      p_ch = old_p_ch;
7161      break;
7162    }
7163    int h = MIN((int)(p_ch - old_p_ch), frp->fr_height - frame_minheight(frp, NULL));
7164    frame_add_height(frp, -h);
7165    old_p_ch += h;
7166    frp = frp->fr_prev;
7167  }
7168  if (p_ch < old_p_ch && command_frame_height && frp != NULL) {
7169    frame_add_height(frp, (int)(old_p_ch - p_ch));
7170  }
7171
7172  // Recompute window positions.
7173  win_comp_pos();
7174  win_fix_scroll(true);
7175  cmdline_row = Rows - (int)p_ch;
7176  redraw_cmdline = true;
7177
7178  // Clear the cmdheight area.
7179  if (msg_scrolled == 0 && full_screen) {
7180    GridView *grid = &default_gridview;
7181    if (!ui_has(kUIMessages)) {
7182      msg_grid_validate();
7183      grid = &msg_grid_adj;
7184    }
7185    grid_clear(grid, cmdline_row, Rows, 0, Columns, 0);
7186    msg_row = cmdline_row;
7187  }
7188
7189  // Use the value of p_ch that we remembered.  This is needed for when the
7190  // GUI starts up, we can't be sure in what order things happen.  And when
7191  // p_ch was changed in another tab page.
7192  curtab->tp_ch_used = p_ch;
7193  min_set_ch = p_ch;
7194}
7195
7196// Resize frame "frp" to be "n" lines higher (negative for less high).
7197// Also resize the frames it is contained in.
7198static void frame_add_height(frame_T *frp, int n)
7199{
7200  frame_new_height(frp, frp->fr_height + n, false, false, false);
7201  while (true) {
7202    frp = frp->fr_parent;
7203    if (frp == NULL) {
7204      break;
7205    }
7206    frp->fr_height += n;
7207  }
7208}
7209
7210/// Add or remove a status line from window(s), according to the
7211/// value of 'laststatus'.
7212///
7213/// @param morewin  pretend there are two or more windows if true.
7214void last_status(bool morewin)
7215{
7216  // Don't make a difference between horizontal or vertical split.
7217  last_status_rec(topframe, last_stl_height(morewin) > 0, global_stl_height() > 0);
7218  win_float_anchor_laststatus();
7219}
7220
7221// Remove status line from window, replacing it with a horizontal separator if needed.
7222void win_remove_status_line(win_T *wp, bool add_hsep)
7223{
7224  wp->w_status_height = 0;
7225  if (add_hsep) {
7226    wp->w_hsep_height = 1;
7227  } else {
7228    win_new_height(wp, (wp->w_floating ? wp->w_view_height : wp->w_height) + STATUS_HEIGHT);
7229  }
7230  comp_col();
7231
7232  stl_clear_click_defs(wp->w_status_click_defs, wp->w_status_click_defs_size);
7233  xfree(wp->w_status_click_defs);
7234  wp->w_status_click_defs_size = 0;
7235  wp->w_status_click_defs = NULL;
7236}
7237
7238// Look for a horizontally resizable frame, starting with frame "fr".
7239// Returns NULL if there are no resizable frames.
7240static frame_T *find_horizontally_resizable_frame(frame_T *fr)
7241{
7242  frame_T *fp = fr;
7243
7244  while (fp->fr_height <= frame_minheight(fp, NULL)) {
7245    if (fp == topframe) {
7246      return NULL;
7247    }
7248    // In a column of frames: go to frame above.  If already at
7249    // the top or in a row of frames: go to parent.
7250    if (fp->fr_parent->fr_layout == FR_COL && fp->fr_prev != NULL) {
7251      fp = fp->fr_prev;
7252    } else {
7253      fp = fp->fr_parent;
7254    }
7255  }
7256
7257  return fp;
7258}
7259
7260// Look for resizable frames and take lines from them to make room for the statusline.
7261// @return Success or failure.
7262static bool resize_frame_for_status(frame_T *fr)
7263{
7264  win_T *wp = fr->fr_win;
7265  frame_T *fp = find_horizontally_resizable_frame(fr);
7266
7267  if (fp == NULL) {
7268    emsg(_(e_noroom));
7269    return false;
7270  } else if (fp != fr) {
7271    int old_height = fr->fr_height;
7272
7273    frame_setheight(fr, old_height + 1, false);
7274    if (fr->fr_height == old_height) {
7275      emsg(_(e_noroom));
7276      return false;
7277    }
7278    win_comp_pos();
7279  } else {
7280    win_new_height(wp, wp->w_height - 1);
7281  }
7282
7283  return true;
7284}
7285
7286// Look for resizable frames and take lines from them to make room for the winbar.
7287// @return Success or failure.
7288static bool resize_frame_for_winbar(frame_T *fr)
7289{
7290  int old_height = fr->fr_height;
7291
7292  frame_setheight(fr, old_height + 1, false);
7293  if (fr->fr_height == old_height) {
7294    emsg(_(e_noroom));
7295    return false;
7296  }
7297  win_comp_pos();
7298
7299  return true;
7300}
7301
7302static void last_status_rec(frame_T *fr, bool statusline, bool is_stl_global)
7303{
7304  if (fr->fr_layout == FR_LEAF) {
7305    win_T *wp = fr->fr_win;
7306    bool is_last = is_bottom_win(wp);
7307
7308    if (is_last) {
7309      if (wp->w_status_height != 0 && (!statusline || is_stl_global)) {
7310        win_remove_status_line(wp, false);
7311      } else if (wp->w_status_height == 0 && !is_stl_global && statusline) {
7312        // Add statusline to window if needed
7313        wp->w_status_height = STATUS_HEIGHT;
7314        if (!resize_frame_for_status(fr)) {
7315          return;
7316        }
7317        comp_col();
7318      }
7319      // Set prev_height when difference is due to 'laststatus'.
7320      if (abs(wp->w_height - wp->w_prev_height) == 1) {
7321        wp->w_prev_height = wp->w_height;
7322      }
7323    } else if (wp->w_status_height != 0 && is_stl_global) {
7324      // If statusline is global and the window has a statusline, replace it with a horizontal
7325      // separator
7326      win_remove_status_line(wp, true);
7327    } else if (wp->w_status_height == 0 && !is_stl_global) {
7328      // If statusline isn't global and the window doesn't have a statusline, re-add it
7329      wp->w_status_height = STATUS_HEIGHT;
7330      wp->w_hsep_height = 0;
7331      comp_col();
7332    }
7333  } else {
7334    // For a column or row frame, recursively call this function for all child frames
7335    frame_T *fp;
7336    FOR_ALL_FRAMES(fp, fr->fr_child) {
7337      last_status_rec(fp, statusline, is_stl_global);
7338    }
7339  }
7340}
7341
7342/// Add or remove window bar from window "wp".
7343///
7344/// @param make_room Whether to resize frames to make room for winbar.
7345/// @param valid_cursor Whether the cursor is valid and should be used while
7346///                     resizing.
7347///
7348/// @return Success status.
7349int set_winbar_win(win_T *wp, bool make_room, bool valid_cursor)
7350{
7351  // Require the local value to be set in order to show winbar on a floating window.
7352  int winbar_height = wp->w_floating ? ((*wp->w_p_wbr != NUL) ? 1 : 0)
7353                                     : ((*p_wbr != NUL || *wp->w_p_wbr != NUL) ? 1 : 0);
7354
7355  if (wp->w_winbar_height != winbar_height) {
7356    if (winbar_height == 1 && wp->w_view_height <= 1) {
7357      if (wp->w_floating) {
7358        emsg(_(e_noroom));
7359        return NOTDONE;
7360      } else if (!make_room || !resize_frame_for_winbar(wp->w_frame)) {
7361        return FAIL;
7362      }
7363    }
7364    wp->w_winbar_height = winbar_height;
7365    win_set_inner_size(wp, valid_cursor);
7366
7367    if (winbar_height == 0) {
7368      // When removing winbar, deallocate the w_winbar_click_defs array
7369      stl_clear_click_defs(wp->w_winbar_click_defs, wp->w_winbar_click_defs_size);
7370      xfree(wp->w_winbar_click_defs);
7371      wp->w_winbar_click_defs_size = 0;
7372      wp->w_winbar_click_defs = NULL;
7373    }
7374  }
7375
7376  return OK;
7377}
7378
7379/// Add or remove window bars from all windows in the current tab.
7380///
7381/// @param make_room Whether to resize frames to make room for winbar.
7382/// @param valid_cursor Whether the cursor is valid and should be used while resizing.
7383/// @return false if a window failed to make room for winbar.
7384static bool set_winbar_curtab(bool make_room, bool valid_cursor)
7385{
7386  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
7387    if (set_winbar_win(wp, make_room, valid_cursor) == FAIL) {
7388      return false;
7389    }
7390  }
7391  return true;
7392}
7393
7394/// Add or remove window bars from all windows in tab depending on the value of 'winbar'.
7395///
7396/// @param make_room Whether to resize frames to make room for winbar.
7397void set_winbar(bool make_room)
7398{
7399  set_winbar_curtab(make_room, true);
7400}
7401
7402/// Add or remove window bars from all windows in all tabs depending on the value of 'winbar'.
7403///
7404/// @param make_room Whether to resize frames to make room for winbar.
7405void set_winbar_all(bool make_room)
7406{
7407  (void)set_winbar_curtab(make_room, true);
7408
7409  FOR_ALL_TABS(tp) {
7410    if (tp == curtab) {
7411      continue;
7412    }
7413
7414    CtxSwitch switchwin;
7415    // Use a no-display switch so the hidden tab's frame and window globals are active.
7416    if (ctx_switch(&switchwin, tp->tp_curwin, tp, NULL, kCtxNoEvents | kCtxNoDisplay)) {
7417      (void)set_winbar_curtab(make_room, false);
7418    }
7419    ctx_restore(&switchwin);
7420  }
7421}
7422
7423/// Return the number of lines used by the tab page line.
7424int tabline_height(void)
7425{
7426  if (ui_has(kUITabline)) {
7427    return 0;
7428  }
7429  assert(first_tabpage);
7430  switch (p_stal) {
7431  case 0:
7432    return 0;
7433  case 1:
7434    return (first_tabpage->tp_next == NULL) ? 0 : 1;
7435  }
7436  return 1;
7437}
7438
7439/// Return the number of lines used by default by the window bar.
7440int global_winbar_height(void)
7441{
7442  return *p_wbr != NUL ? 1 : 0;
7443}
7444
7445/// Return the number of lines used by the global statusline
7446int global_stl_height(void)
7447{
7448  return (p_ls == 3) ? STATUS_HEIGHT : 0;
7449}
7450
7451/// Return the height of the last window's statusline, or the global statusline if set.
7452///
7453/// @param morewin  pretend there are two or more windows if true.
7454int last_stl_height(bool morewin)
7455{
7456  return (p_ls > 1 || (p_ls == 1 && (morewin || !one_window(firstwin, NULL)))) ? STATUS_HEIGHT : 0;
7457}
7458
7459/// Return the minimal number of rows that is needed on the screen to display
7460/// the current number of windows for the given tab page.
7461int min_rows(tabpage_T *tp) FUNC_ATTR_NONNULL_ALL
7462{
7463  if (firstwin == NULL) {       // not initialized yet
7464    return MIN_LINES;
7465  }
7466
7467  int total = frame_minheight(tp->tp_topframe, NULL);
7468  total += tabline_height() + global_stl_height();
7469  if ((tp == curtab ? p_ch : tp->tp_ch_used) > 0) {
7470    total++;  // count the room for the command line
7471  }
7472  return total;
7473}
7474
7475/// Return the minimal number of rows that is needed on the screen to display
7476/// the current number of windows for all tab pages.
7477int min_rows_for_all_tabpages(void)
7478{
7479  if (firstwin == NULL) {       // not initialized yet
7480    return MIN_LINES;
7481  }
7482
7483  int total = 0;
7484  FOR_ALL_TABS(tp) {
7485    int n = frame_minheight(tp->tp_topframe, NULL);
7486    if ((tp == curtab ? p_ch : tp->tp_ch_used) > 0) {
7487      n++;  // count the room for the command line
7488    }
7489    total = MAX(total, n);
7490  }
7491  total += tabline_height() + global_stl_height();
7492  return total;
7493}
7494
7495/// Check that there is only one window (and only one tab page), not counting a
7496/// help or preview window, unless it is the current window. Does not count
7497/// "ctx_win". Does not count floats unless it is current.
7498bool only_one_window(void) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
7499{
7500  // If there is another tab page there always is another window.
7501  if (first_tabpage->tp_next != NULL) {
7502    return false;
7503  }
7504
7505  int count = 0;
7506  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
7507    if (wp->w_buffer != NULL
7508        && (!((bt_help(wp->w_buffer) && !bt_help(curbuf)) || wp->w_floating
7509              || wp->w_p_pvw) || wp == curwin) && !is_ctx_win(wp)) {
7510      count++;
7511    }
7512  }
7513  return count <= 1;
7514}
7515
7516/// Implementation of check_lnums() and check_lnums_nested().
7517static void check_lnums_both(bool do_curwin, bool nested)
7518{
7519  FOR_ALL_TAB_WINDOWS(tp, wp) {
7520    if ((do_curwin || wp != curwin) && wp->w_buffer == curbuf) {
7521      if (!nested) {
7522        // save the original cursor position and topline
7523        wp->w_save_cursor.w_cursor_save = wp->w_cursor;
7524        wp->w_save_cursor.w_topline_save = wp->w_topline;
7525      }
7526
7527      bool need_adjust = wp->w_cursor.lnum > curbuf->b_ml.ml_line_count;
7528      if (need_adjust) {
7529        wp->w_cursor.lnum = curbuf->b_ml.ml_line_count;
7530      }
7531      if (need_adjust || !nested) {
7532        // save the (corrected) cursor position
7533        wp->w_save_cursor.w_cursor_corr = wp->w_cursor;
7534      }
7535
7536      need_adjust = wp->w_topline > curbuf->b_ml.ml_line_count;
7537      if (need_adjust) {
7538        wp->w_topline = curbuf->b_ml.ml_line_count;
7539      }
7540      if (need_adjust || !nested) {
7541        // save the (corrected) topline
7542        wp->w_save_cursor.w_topline_corr = wp->w_topline;
7543      }
7544    }
7545  }
7546}
7547
7548/// Correct the cursor line number in other windows.  Used after changing the
7549/// current buffer, and before applying autocommands.
7550///
7551/// @param do_curwin  when true, also check current window.
7552void check_lnums(bool do_curwin)
7553{
7554  check_lnums_both(do_curwin, false);
7555}
7556
7557/// Like check_lnums() but for when check_lnums() was already called.
7558void check_lnums_nested(bool do_curwin)
7559{
7560  check_lnums_both(do_curwin, true);
7561}
7562
7563/// Reset cursor and topline to its stored values from check_lnums().
7564/// check_lnums() must have been called first!
7565void reset_lnums(void)
7566{
7567  FOR_ALL_TAB_WINDOWS(tp, wp) {
7568    if (wp->w_buffer == curbuf) {
7569      // Restore the value if the autocommand didn't change it and it was set.
7570      // Note: This triggers e.g. on BufReadPre, when the buffer is not yet
7571      //       loaded, so cannot validate the buffer line
7572      if (equalpos(wp->w_save_cursor.w_cursor_corr, wp->w_cursor)
7573          && wp->w_save_cursor.w_cursor_save.lnum != 0) {
7574        wp->w_cursor = wp->w_save_cursor.w_cursor_save;
7575      }
7576      if (wp->w_save_cursor.w_topline_corr == wp->w_topline
7577          && wp->w_save_cursor.w_topline_save != 0) {
7578        wp->w_topline = wp->w_save_cursor.w_topline_save;
7579      }
7580      if (wp->w_save_cursor.w_topline_save > wp->w_buffer->b_ml.ml_line_count) {
7581        wp->w_valid &= ~VALID_TOPLINE;
7582      }
7583    }
7584  }
7585}
7586
7587// A snapshot of the window sizes, to restore them after closing the help
7588// window.
7589// Only these fields are used:
7590// fr_layout
7591// fr_width
7592// fr_height
7593// fr_next
7594// fr_child
7595// fr_win (only valid for the old curwin, NULL otherwise)
7596
7597// Create a snapshot of the current frame sizes.
7598void make_snapshot(int idx)
7599{
7600  clear_snapshot(curtab, idx);
7601  make_snapshot_rec(topframe, &curtab->tp_snapshot[idx]);
7602}
7603
7604static void make_snapshot_rec(frame_T *fr, frame_T **frp)
7605{
7606  *frp = xcalloc(1, sizeof(frame_T));
7607  (*frp)->fr_layout = fr->fr_layout;
7608  (*frp)->fr_width = fr->fr_width;
7609  (*frp)->fr_height = fr->fr_height;
7610  if (fr->fr_next != NULL) {
7611    make_snapshot_rec(fr->fr_next, &((*frp)->fr_next));
7612  }
7613  if (fr->fr_child != NULL) {
7614    make_snapshot_rec(fr->fr_child, &((*frp)->fr_child));
7615  }
7616  if (fr->fr_layout == FR_LEAF && fr->fr_win == curwin) {
7617    (*frp)->fr_win = curwin;
7618  }
7619}
7620
7621// Remove any existing snapshot.
7622static void clear_snapshot(tabpage_T *tp, int idx)
7623{
7624  clear_snapshot_rec(tp->tp_snapshot[idx]);
7625  tp->tp_snapshot[idx] = NULL;
7626}
7627
7628static void clear_snapshot_rec(frame_T *fr)
7629{
7630  if (fr == NULL) {
7631    return;
7632  }
7633  clear_snapshot_rec(fr->fr_next);
7634  clear_snapshot_rec(fr->fr_child);
7635  xfree(fr);
7636}
7637
7638/// Traverse a snapshot to find the previous curwin.
7639static win_T *get_snapshot_curwin_rec(frame_T *ft)
7640{
7641  win_T *wp;
7642
7643  if (ft->fr_next != NULL) {
7644    if ((wp = get_snapshot_curwin_rec(ft->fr_next)) != NULL) {
7645      return wp;
7646    }
7647  }
7648  if (ft->fr_child != NULL) {
7649    if ((wp = get_snapshot_curwin_rec(ft->fr_child)) != NULL) {
7650      return wp;
7651    }
7652  }
7653
7654  return ft->fr_win;
7655}
7656
7657/// @return  the current window stored in the snapshot or NULL.
7658static win_T *get_snapshot_curwin(int idx)
7659{
7660  if (curtab->tp_snapshot[idx] == NULL) {
7661    return NULL;
7662  }
7663
7664  return get_snapshot_curwin_rec(curtab->tp_snapshot[idx]);
7665}
7666
7667/// Restore a previously created snapshot, if there is any.
7668/// This is only done if the screen size didn't change and the window layout is
7669/// still the same.
7670///
7671/// @param close_curwin  closing current window
7672void restore_snapshot(int idx, int close_curwin)
7673{
7674  if (curtab->tp_snapshot[idx] != NULL
7675      && curtab->tp_snapshot[idx]->fr_width == topframe->fr_width
7676      && curtab->tp_snapshot[idx]->fr_height == topframe->fr_height
7677      && check_snapshot_rec(curtab->tp_snapshot[idx], topframe) == OK) {
7678    win_T *wp = restore_snapshot_rec(curtab->tp_snapshot[idx], topframe);
7679    win_comp_pos();
7680    if (wp != NULL && close_curwin) {
7681      win_goto(wp);
7682    }
7683    redraw_all_later(UPD_NOT_VALID);
7684  }
7685  clear_snapshot(curtab, idx);
7686}
7687
7688/// Check if frames "sn" and "fr" have the same layout, same following frames
7689/// and same children.  And the window pointer is valid.
7690static int check_snapshot_rec(frame_T *sn, frame_T *fr)
7691{
7692  if (sn->fr_layout != fr->fr_layout
7693      || (sn->fr_next == NULL) != (fr->fr_next == NULL)
7694      || (sn->fr_child == NULL) != (fr->fr_child == NULL)
7695      || (sn->fr_next != NULL
7696          && check_snapshot_rec(sn->fr_next, fr->fr_next) == FAIL)
7697      || (sn->fr_child != NULL
7698          && check_snapshot_rec(sn->fr_child, fr->fr_child) == FAIL)
7699      || (sn->fr_win != NULL && !win_valid(sn->fr_win))) {
7700    return FAIL;
7701  }
7702  return OK;
7703}
7704
7705// Copy the size of snapshot frame "sn" to frame "fr".  Do the same for all
7706// following frames and children.
7707// Returns a pointer to the old current window, or NULL.
7708static win_T *restore_snapshot_rec(frame_T *sn, frame_T *fr)
7709{
7710  win_T *wp = NULL;
7711
7712  fr->fr_height = sn->fr_height;
7713  fr->fr_width = sn->fr_width;
7714  if (fr->fr_layout == FR_LEAF) {
7715    frame_new_height(fr, fr->fr_height, false, false, false);
7716    frame_new_width(fr, fr->fr_width, false, false);
7717    wp = sn->fr_win;
7718  }
7719  if (sn->fr_next != NULL) {
7720    win_T *wp2 = restore_snapshot_rec(sn->fr_next, fr->fr_next);
7721    if (wp2 != NULL) {
7722      wp = wp2;
7723    }
7724  }
7725  if (sn->fr_child != NULL) {
7726    win_T *wp2 = restore_snapshot_rec(sn->fr_child, fr->fr_child);
7727    if (wp2 != NULL) {
7728      wp = wp2;
7729    }
7730  }
7731  return wp;
7732}
7733
7734/// Check that "topfrp" and its children are at the right height.
7735///
7736/// @param  topfrp  top frame pointer
7737/// @param  height  expected height
7738static bool frame_check_height(const frame_T *topfrp, int height)
7739  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
7740{
7741  if (topfrp->fr_height != height) {
7742    return false;
7743  }
7744  if (topfrp->fr_layout == FR_ROW) {
7745    const frame_T *frp;
7746    FOR_ALL_FRAMES(frp, topfrp->fr_child) {
7747      if (frp->fr_height != height) {
7748        return false;
7749      }
7750    }
7751  }
7752  return true;
7753}
7754
7755/// Check that "topfrp" and its children are at the right width.
7756///
7757/// @param  topfrp  top frame pointer
7758/// @param  width   expected width
7759static bool frame_check_width(const frame_T *topfrp, int width)
7760  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
7761{
7762  if (topfrp->fr_width != width) {
7763    return false;
7764  }
7765  if (topfrp->fr_layout == FR_COL) {
7766    const frame_T *frp;
7767    FOR_ALL_FRAMES(frp, topfrp->fr_child) {
7768      if (frp->fr_width != width) {
7769        return false;
7770      }
7771    }
7772  }
7773  return true;
7774}
7775
7776/// Simple int comparison function for use with qsort()
7777static int int_cmp(const void *pa, const void *pb)
7778{
7779  const int a = *(const int *)pa;
7780  const int b = *(const int *)pb;
7781  return a == b ? 0 : a < b ? -1 : 1;
7782}
7783
7784/// Check "cc" as 'colorcolumn' and update the members of "wp".
7785/// This is called when 'colorcolumn' or 'textwidth' is changed.
7786///
7787/// @param cc  when NULL: use "wp->w_p_cc"
7788/// @param wp  when NULL: only parse "cc"
7789///
7790/// @return error message, NULL if it's OK.
7791const char *check_colorcolumn(char *cc, win_T *wp)
7792{
7793  if (wp != NULL && wp->w_buffer == NULL) {
7794    return NULL;      // buffer was closed
7795  }
7796
7797  char *s = empty_string_option;
7798  if (cc != NULL) {
7799    s = cc;
7800  } else if (wp != NULL) {
7801    s = wp->w_p_cc;
7802  }
7803
7804  OptInt tw;
7805  if (wp != NULL) {
7806    tw = wp->w_buffer->b_p_tw;
7807  } else {
7808    // buffer-local value not set, assume zero
7809    tw = 0;
7810  }
7811
7812  unsigned count = 0;
7813  int color_cols[256];
7814  while (*s != NUL && count < 255) {
7815    int col;
7816    if (*s == '-' || *s == '+') {
7817      // -N and +N: add to 'textwidth'
7818      col = (*s == '-') ? -1 : 1;
7819      s++;
7820      if (!ascii_isdigit(*s)) {
7821        return e_invarg;
7822      }
7823      col = col * getdigits_int(&s, true, 0);
7824      if (tw == 0) {
7825        goto skip;          // 'textwidth' not set, skip this item
7826      }
7827      assert((col >= 0 && tw <= INT_MAX - col && tw + col >= INT_MIN)
7828             || (col < 0 && tw >= INT_MIN - col && tw + col <= INT_MAX));
7829      col += (int)tw;
7830      if (col < 0) {
7831        goto skip;
7832      }
7833    } else if (ascii_isdigit(*s)) {
7834      col = getdigits_int(&s, true, 0);
7835    } else {
7836      return e_invarg;
7837    }
7838    color_cols[count++] = col - 1;      // 1-based to 0-based
7839skip:
7840    if (*s == NUL) {
7841      break;
7842    }
7843    if (*s != ',') {
7844      return e_invarg;
7845    }
7846    if (*++s == NUL) {
7847      return e_invarg;        // illegal trailing comma as in "set cc=80,"
7848    }
7849  }
7850
7851  if (wp == NULL) {
7852    return NULL;  // only parse "cc"
7853  }
7854
7855  xfree(wp->w_p_cc_cols);
7856  if (count == 0) {
7857    wp->w_p_cc_cols = NULL;
7858  } else {
7859    wp->w_p_cc_cols = xmalloc(sizeof(int) * (count + 1));
7860    // sort the columns for faster usage on screen redraw inside
7861    // win_line()
7862    qsort(color_cols, count, sizeof(int), int_cmp);
7863
7864    int j = 0;
7865    for (unsigned i = 0; i < count; i++) {
7866      // skip duplicates
7867      if (j == 0 || wp->w_p_cc_cols[j - 1] != color_cols[i]) {
7868        wp->w_p_cc_cols[j++] = color_cols[i];
7869      }
7870    }
7871    wp->w_p_cc_cols[j] = -1;        // end marker
7872  }
7873
7874  return NULL;    // no error
7875}
7876
7877int get_last_winid(void)
7878{
7879  return last_win_id;
7880}
7881
7882/// Don't let autocommands close the given window
7883int win_locked(win_T *wp)
7884{
7885  return wp->w_locked;
7886}
7887
7888void win_get_tabwin(handle_T id, int *tabnr, int *winnr)
7889{
7890  *tabnr = 0;
7891  *winnr = 0;
7892
7893  int tnum = 1;
7894  int wnum = 1;
7895  FOR_ALL_TABS(tp) {
7896    FOR_ALL_WINDOWS_IN_TAB(wp, tp) {
7897      if (wp->handle == id) {
7898        if (win_has_winnr(wp, tp)) {
7899          *winnr = wnum;
7900          *tabnr = tnum;
7901        }
7902        return;
7903      }
7904      wnum += win_has_winnr(wp, tp);
7905    }
7906    tnum++;
7907    wnum = 1;
7908  }
7909}
7910
7911void win_ui_flush(bool validate)
7912{
7913  FOR_ALL_TAB_WINDOWS(tp, wp) {
7914    if ((wp->w_pos_changed || wp->w_grid_alloc.pending_comp_index_update)
7915        && wp->w_grid_alloc.chars != NULL) {
7916      if (tp == curtab) {
7917        ui_ext_win_position(wp, validate);
7918      } else {
7919        ui_call_win_hide(wp->w_grid_alloc.handle);
7920        wp->w_pos_changed = false;
7921      }
7922      wp->w_grid_alloc.pending_comp_index_update = false;
7923    }
7924    if (tp == curtab) {
7925      ui_ext_win_viewport(wp);
7926    }
7927  }
7928  // The popupmenu could also have moved or changed its comp_index
7929  pum_pos_ui_flush(false);
7930
7931  // And the message
7932  msg_ui_flush();
7933}
7934
7935/// @return last non-floating window in `tp`, or NULL for current tabpage.
7936win_T *lastwin_nofloating(tabpage_T *tp)
7937{
7938  assert(tp != curtab || !tp);
7939  win_T *res = tp ? tp->tp_lastwin : lastwin;
7940  while (res->w_floating) {
7941    res = res->w_prev;
7942  }
7943  return res;
7944}