robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
50.9 KiB1510 linesraw
1#include <assert.h>
2#include <stdbool.h>
3#include <string.h>
4
5#include "klib/kvec.h"
6#include "nvim/api/extmark.h"
7#include "nvim/api/keysets_defs.h"
8#include "nvim/api/private/defs.h"
9#include "nvim/api/private/dispatch.h"
10#include "nvim/api/private/helpers.h"
11#include "nvim/api/private/validate.h"
12#include "nvim/api/win_config.h"
13#include "nvim/ascii_defs.h"
14#include "nvim/autocmd.h"
15#include "nvim/autocmd_defs.h"
16#include "nvim/buffer.h"
17#include "nvim/buffer_defs.h"
18#include "nvim/charset.h"
19#include "nvim/context.h"
20#include "nvim/decoration_defs.h"
21#include "nvim/drawscreen.h"
22#include "nvim/errors.h"
23#include "nvim/eval/window.h"
24#include "nvim/ex_cmds_defs.h"
25#include "nvim/ex_docmd.h"
26#include "nvim/globals.h"
27#include "nvim/highlight_group.h"
28#include "nvim/macros_defs.h"
29#include "nvim/mbyte.h"
30#include "nvim/memory.h"
31#include "nvim/memory_defs.h"
32#include "nvim/move.h"
33#include "nvim/option.h"
34#include "nvim/option_vars.h"
35#include "nvim/pos_defs.h"
36#include "nvim/strings.h"
37#include "nvim/syntax.h"
38#include "nvim/types_defs.h"
39#include "nvim/ui.h"
40#include "nvim/ui_compositor.h"
41#include "nvim/ui_defs.h"
42#include "nvim/vim_defs.h"
43#include "nvim/window.h"
44#include "nvim/winfloat.h"
45
46#include "api/win_config.c.generated.h"
47
48#define HAS_KEY_X(d, key) HAS_KEY(d, win_config, key)
49
50/// Opens a new split window, floating window, or external window.
51///
52/// - Specify `relative` to create a floating window. Floats are drawn over the split layout,
53///   relative to a position in some other window. See |api-floatwin|.
54///   - Floats must specify `width` and `height`.
55/// - Specify `external` to create an external window. External windows are displayed as separate
56///   top-level windows managed by the |ui-multigrid| UI (not Nvim).
57/// - If `relative` and `external` are omitted, a normal "split" window is created.
58///   - The `win` key decides which window to split. If nil or 0, the split will be adjacent to
59///     the current window. If -1, a top-level split will be created.
60///   - Use `vertical` and `split` to control split direction. For `vertical`, the exact direction
61///     is determined by 'splitright' and 'splitbelow'.
62///   - Split windows cannot have `bufpos`, `row`, `col`, `border`, `title`, `footer`.
63///
64/// With relative=editor (row=0,col=0) refers to the top-left corner of the
65/// screen-grid and (row=Lines-1,col=Columns-1) refers to the bottom-right
66/// corner. Fractional values are allowed, but the builtin implementation
67/// (used by non-multigrid UIs) will always round down to nearest integer.
68///
69/// Out-of-bounds values, and configurations that make the float not fit inside
70/// the main editor, are allowed. The builtin implementation truncates values
71/// so floats are fully within the main screen grid. External GUIs
72/// could let floats hover outside of the main window like a tooltip, but
73/// this should not be used to specify arbitrary WM screen positions.
74///
75/// Examples:
76///
77/// ```lua
78/// -- Window-relative float with 'statusline' enabled:
79/// local w1 = vim.api.nvim_open_win(0, false,
80///   {relative='win', row=3, col=3, width=40, height=4})
81/// vim.wo[w1].statusline = vim.o.statusline
82///
83/// -- Buffer-relative float (travels as buffer is scrolled):
84/// vim.api.nvim_open_win(0, false,
85///   {relative='win', width=40, height=4, bufpos={100,10}})
86///
87/// -- Vertical split left of the current window:
88/// vim.api.nvim_open_win(0, false, { split = 'left', win = 0, })
89/// ```
90///
91/// @param buf Buffer to display, or 0 for current buffer
92/// @param enter  Enter the window (make it the current window)
93/// @param config Map defining the window configuration. Keys:
94///   - anchor: Decides which corner of the float to place at (row,col):
95///      - "NW" northwest (default)
96///      - "NE" northeast
97///      - "SW" southwest
98///      - "SE" southeast
99///   - border: (`string|string[]`, default: 'winborder' option) Window border. The string form
100///     accepts the same values as the 'winborder' option. The array form must have a length of
101///     eight or any divisor of eight, specifying the chars that form the border in a clockwise
102///     fashion starting from the top-left corner. For example, the double-box style can be
103///     specified as:
104///     ```
105///     [ "╔", "═" ,"╗", "║", "╝", "═", "╚", "║" ].
106///     ```
107///     If fewer than eight chars are given, they will be repeated. An ASCII border could be
108///     specified as:
109///     ```
110///     [ "/", "-", \"\\\\\", "|" ],
111///     ```
112///     Or one char for all sides:
113///     ```
114///     [ "x" ].
115///     ```
116///     Empty string can be used to hide a specific border. This example will show only vertical
117///     borders, not horizontal:
118///     ```
119///     [ "", "", "", ">", "", "", "", "<" ]
120///     ```
121///     By default, |hl-FloatBorder| highlight is used, which links to |hl-WinSeparator| when not
122///     defined. Each border side can specify an optional highlight:
123///     ```
124///     [ ["+", "MyCorner"], ["x", "MyBorder"] ].
125///     ```
126///   - bufpos: Places float relative to buffer text (only when
127///       relative="win"). Takes a tuple of zero-indexed `[line, column]`.
128///       `row` and `col` if given are applied relative to this
129///       position, else they default to:
130///       - `row=1` and `col=0` if `anchor` is "NW" or "NE"
131///       - `row=0` and `col=0` if `anchor` is "SW" or "SE"
132///         (thus like a tooltip near the buffer text).
133///   - col: Column position in units of screen cell width, may be fractional.
134///   - external: GUI should display the window as an external
135///       top-level window. Currently accepts no other positioning
136///       configuration together with this.
137///   - fixed: If true when anchor is NW or SW, the float window
138///            would be kept fixed even if the window would be truncated.
139///   - focusable: (default: true) Enable focus by user actions (wincmds, mouse events).
140///     Non-|focusable| windows can be entered by |nvim_set_current_win()|, or by mouse events if
141///     `mouse=true`.
142///   - footer: (`string|string[]?`) Footer in window border: string or list of `[text, highlight]`
143///     tuples. Default highlight group is `FloatFooter`.
144///   - footer_pos: (default: "left") Footer position. One of: "left", "center", "right". The
145///    `footer` field must be set also.
146///   - height: Window height (in character cells). Minimum of 1.
147///   - hide: Hides the floating window. |window-hidden|
148///   - mouse: (default: `focusable` value) If true, mouse events interact with the window
149///     normally; if false, they pass through to the window behind it.
150///   - noautocmd: Block all autocommands for the duration of the call. Cannot be changed by
151///     |nvim_win_set_config()|.
152///   - relative: Sets the window layout to "floating", placed at (row,col) coordinates relative to:
153///      - "cursor"     Cursor position in current window.
154///      - "editor"     The global editor grid.
155///      - "laststatus" 'laststatus' if present, or last row.
156///      - "mouse"      Mouse position.
157///      - "tabline"    Tabline if present, or first row.
158///      - "win"        Window given by the `win` field, or current window.
159///   - row: Row position in units of "screen cell height", may be fractional.
160///   - split: Split direction: "left", "right", "above", "below".
161///   - style: (optional) Configure the appearance of the window:
162///       - ""         No special style.
163///       - "minimal"  Nvim will display the window with many UI options
164///                    disabled. This is useful when displaying a temporary
165///                    float where the text should not be edited. Disables
166///                    'number', 'relativenumber', 'cursorline', 'cursorcolumn',
167///                    'foldcolumn', 'spell' and 'list' options. 'signcolumn'
168///                    is changed to `auto` and 'colorcolumn' is cleared.
169///                    'statuscolumn' is changed to empty. The end-of-buffer
170///                     region is hidden by setting `eob` flag of
171///                    'fillchars' to a space char, and clearing the
172///                    |hl-EndOfBuffer| region in 'winhighlight'.
173///   - title: (optional) Title in window border, string or list.
174///       List should consist of `[text, highlight]` tuples.
175///       If string, or a tuple lacks a highlight, the default highlight group is `FloatTitle`.
176///   - title_pos: (default: "left") Title position. One of: "left", "center", "right". The `title`
177///     field must be set also.
178///   - vertical: Split vertically |:vertical|.
179///   - width: Window width (in character cells). Minimum of 1.
180///   - win: |window-ID| target window. Can be in a different tab page. Determines the window to
181///       split (negative values act like |:topleft|, |:botright|), the relative window for a
182///       `relative="win"` float, or just the target tab page (inferred from the window) for others.
183///   - zindex: (positive integer, default: 50) Stacking order. Floats with higher `zindex` overlay
184///     floats with lower indices. Below 100 is recommended, unless there is a good reason to
185///     overshadow builtin elements. The cursor is dimmed if an unfocused float above the cursor
186///     exceeds the zindex of the current window by 50. These screen elements have hard-coded
187///     z-indices:
188///       - 100: |ins-completion-menu| popupmenu
189///       - 200: message scrollback (|pager|)
190///       - 250: |cmdline-completion| popupmenu (wildoptions=pum)
191///   - _cmdline_offset: (EXPERIMENTAL) When provided, anchor the |cmdline-completion|
192///     popupmenu to this window, with an offset in screen cell width.
193///
194/// @param[out] err Error details, if any
195///
196/// @return |window-ID|, or 0 on error
197Window nvim_open_win(Buffer buf, Boolean enter, Dict(win_config) *config, Error *err)
198  FUNC_API_SINCE(6) FUNC_API_TEXTLOCK
199{
200  buf_T *b = find_buffer_by_handle(buf, err);
201  if (!b) {
202    return 0;
203  }
204
205  bool is_split = HAS_KEY_X(config, split) || HAS_KEY_X(config, vertical);
206  WinConfig fconfig = WIN_CONFIG_INIT;
207  if (!parse_win_config(NULL, config, &fconfig, false, !is_split, err)) {
208    return 0;
209  }
210
211  Window rv = 0;
212  if (fconfig.noautocmd) {
213    block_autocmds();
214  }
215
216  win_T *wp = NULL;
217  tabpage_T *tp = curtab;
218  assert(curwin != NULL);
219  win_T *parent = config->win == 0 ? curwin : NULL;
220  if (config->win > 0) {
221    parent = find_window_by_handle(fconfig.window, err);
222    if (!parent) {
223      // find_window_by_handle has already set the error
224      goto cleanup;
225    } else if (is_split && parent->w_floating) {
226      api_set_error(err, kErrorTypeException, "Cannot split a floating window");
227      goto cleanup;
228    }
229    tp = win_find_tabpage(parent);
230  }
231  if (is_split) {
232    if (!check_split_disallowed_err(parent ? parent : curwin, err)) {
233      goto cleanup;  // error already set
234    }
235
236    if (HAS_KEY_X(config, vertical) && !HAS_KEY_X(config, split)) {
237      if (config->vertical) {
238        fconfig.split = p_spr ? kWinSplitRight : kWinSplitLeft;
239      } else {
240        fconfig.split = p_sb ? kWinSplitBelow : kWinSplitAbove;
241      }
242    }
243    int flags = win_split_flags(fconfig.split, parent == NULL) | WSP_NOENTER;
244    int size = (flags & WSP_VERT) ? fconfig.width : fconfig.height;
245
246    TRY_WRAP(err, {
247      if (parent == NULL || parent == curwin) {
248        wp = win_split_ins(size, flags, NULL, 0, NULL);
249      } else {
250        CtxSwitch switchwin;
251        // `parent` is valid in `tp`, so ctx_switch should not fail.
252        const bool result = ctx_switch(&switchwin, parent, tp, NULL, kCtxNoEvents | kCtxNoDisplay);
253        assert(result);
254        (void)result;
255        wp = win_split_ins(size, flags, NULL, 0, NULL);
256        ctx_restore(&switchwin);
257      }
258    });
259    if (wp) {
260      wp->w_config = fconfig;
261      if (size > 0) {
262        // Without room for the requested size, window sizes may have been equalized instead.
263        // If the size differs from what was requested, try to set it again now.
264        if ((flags & WSP_VERT) && wp->w_width != size) {
265          win_setwidth_win(size, wp, true);
266        } else if (!(flags & WSP_VERT) && wp->w_height != size) {
267          win_setheight_win(size, wp, true);
268        }
269      }
270    }
271  } else {
272    // Unlike check_split_disallowed_err, ignore `split_disallowed`, as opening a float shouldn't
273    // mess with the frame structure. Still check `b_locked_split` to avoid opening more windows
274    // into a closing buffer, though.
275    if (curwin->w_buffer->b_locked_split) {  // Can't instead check `buf` in case win_set_buf fails!
276      api_set_error(err, kErrorTypeException, "E1159: Cannot open a float when closing the buffer");
277      goto cleanup;
278    }
279    wp = win_new_float(NULL, false, fconfig, err);
280  }
281  if (!wp) {
282    if (!ERROR_SET(err)) {
283      api_set_error(err, kErrorTypeException, "Failed to create window");
284    }
285    goto cleanup;
286  }
287
288  if (fconfig._cmdline_offset < INT_MAX) {
289    cmdline_win = wp;
290  }
291
292  // Autocommands may close `wp` or move it to another tabpage, so update and check `tp` after each
293  // event. In each case, `wp` should already be valid in `tp`, so ctx_switch should not fail.
294  // Also, autocommands may free the `buf` to switch to, so store a bufref to check.
295  bufref_T bufref;
296  set_bufref(&bufref, b);
297  if (!fconfig.noautocmd) {
298    CtxSwitch switchwin;
299    const bool result = ctx_switch(&switchwin, wp, tp, NULL, kCtxNoDisplay);
300    assert(result);
301    (void)result;
302    if (apply_autocmds_win(EVENT_WINNEW, NULL, NULL, false, curbuf, wp)) {
303      tp = win_find_tabpage(wp);
304    }
305    ctx_restore(&switchwin);
306  }
307  if (tp && enter) {
308    goto_tabpage_win(tp, wp);
309    tp = win_find_tabpage(wp);
310  }
311  if (tp && bufref_valid(&bufref) && b != wp->w_buffer) {
312    // win_set_buf temporarily makes `wp` the curwin to set the buffer.
313    // If not entering `wp`, block Enter and Leave events. (cringe)
314    const bool au_no_enter_leave = curwin != wp && !fconfig.noautocmd;
315    if (au_no_enter_leave) {
316      autocmd_no_enter++;
317      autocmd_no_leave++;
318    }
319    win_set_buf(wp, b, err);
320    if (!fconfig.noautocmd) {
321      tp = win_find_tabpage(wp);
322    }
323    if (au_no_enter_leave) {
324      autocmd_no_enter--;
325      autocmd_no_leave--;
326    }
327  }
328  if (!tp) {
329    api_clear_error(err);  // may have been set by win_set_buf
330    api_set_error(err, kErrorTypeException, "Window was closed immediately");
331    goto cleanup;
332  }
333
334  if (fconfig.style == kWinStyleMinimal) {
335    win_set_minimal_style(wp);
336    didset_window_options(wp, true);
337    changed_window_setting(wp);
338  }
339  rv = wp->handle;
340
341cleanup:
342  if (fconfig.noautocmd) {
343    unblock_autocmds();
344  }
345  return rv;
346}
347
348static WinSplit win_split_dir(win_T *win)
349{
350  if (win->w_frame == NULL || win->w_frame->fr_parent == NULL) {
351    return kWinSplitLeft;
352  }
353
354  char layout = win->w_frame->fr_parent->fr_layout;
355  if (layout == FR_COL) {
356    return win->w_frame->fr_next ? kWinSplitAbove : kWinSplitBelow;
357  } else {
358    return win->w_frame->fr_next ? kWinSplitLeft : kWinSplitRight;
359  }
360}
361
362static int win_split_flags(WinSplit split, bool toplevel)
363{
364  int flags = 0;
365  if (split == kWinSplitAbove || split == kWinSplitBelow) {
366    flags |= WSP_HOR;
367  } else {
368    flags |= WSP_VERT;
369  }
370  if (split == kWinSplitAbove || split == kWinSplitLeft) {
371    flags |= toplevel ? WSP_TOP : WSP_ABOVE;
372  } else {
373    flags |= toplevel ? WSP_BOT : WSP_BELOW;
374  }
375  return flags;
376}
377
378/// Checks if window `wp` can be moved to tabpage `tp`.
379static bool win_can_move_tp(win_T *wp, tabpage_T *tp, Error *err)
380  FUNC_ATTR_NONNULL_ALL
381{
382  if (one_window(wp, tp == curtab ? NULL : tp)) {
383    api_set_error(err, kErrorTypeException, "Cannot move last non-floating window");
384    return false;
385  }
386  // Like closing, moving windows between tabpages makes win_valid return false. Helpful when e.g:
387  // walking the window list, as w_next/w_prev can unexpectedly refer to windows in another tabpage!
388  // Check related locks, in case they were set to avoid checking win_valid.
389  if (win_locked(wp)) {
390    api_set_error(err, kErrorTypeException, "Cannot move window to another tabpage whilst in use");
391    return false;
392  }
393  if (window_layout_locked_err(CMD_SIZE, err)) {
394    return false;  // error already set
395  }
396  if (textlock || expr_map_locked()) {
397    api_set_error(err, kErrorTypeException, "%s", e_textlock);
398    return false;
399  }
400  if (is_ctx_win(wp)) {
401    api_set_error(err, kErrorTypeException, "Cannot move autocmd window to another tabpage");
402    return false;
403  }
404  return true;
405}
406
407static win_T *win_find_altwin(win_T *win, tabpage_T *tp)
408  FUNC_ATTR_NONNULL_ALL
409{
410  if (win->w_floating) {
411    return win_float_find_altwin(win, tp == curtab ? NULL : tp);
412  } else {
413    int dir;
414    return winframe_find_altwin(win, &dir, tp == curtab ? NULL : tp, NULL);
415  }
416}
417
418/// Configures `win` into a split, also moving it to another tabpage if requested.
419static bool win_config_split(win_T *win, const Dict(win_config) *config, WinConfig *fconfig,
420                             Error *err)
421  FUNC_ATTR_NONNULL_ALL
422{
423  bool was_split = !win->w_floating;
424  bool has_split = HAS_KEY_X(config, split);
425  bool has_vertical = HAS_KEY_X(config, vertical);
426  WinSplit old_split = win_split_dir(win);
427  if (has_vertical && !has_split) {
428    if (config->vertical) {
429      fconfig->split = (old_split == kWinSplitRight || p_spr) ? kWinSplitRight : kWinSplitLeft;
430    } else {
431      fconfig->split = (old_split == kWinSplitBelow || p_sb) ? kWinSplitBelow : kWinSplitAbove;
432    }
433  }
434
435  // If there's no "vertical" or "split" set, or if "split" is unchanged, then we can just change
436  // the size of the window.
437  if ((!has_vertical && !has_split)
438      || (was_split && !HAS_KEY_X(config, win) && old_split == fconfig->split)) {
439    goto resize;
440  }
441
442  win_T *parent = NULL;
443  tabpage_T *parent_tp = NULL;
444  if (config->win == 0) {
445    parent = curwin;
446    parent_tp = curtab;
447  } else if (config->win > 0) {
448    parent = find_window_by_handle(fconfig->window, err);
449    if (!parent) {
450      return false;  // error already set
451    }
452    parent_tp = win_find_tabpage(parent);
453  }
454
455  tabpage_T *win_tp = win_find_tabpage(win);
456  if (parent) {
457    if (parent->w_floating) {
458      api_set_error(err, kErrorTypeException, "Cannot split a floating window");
459      return false;
460    }
461    if (win_tp != parent_tp && !win_can_move_tp(win, win_tp, err)) {
462      return false;  // error already set
463    }
464  }
465
466  if (!check_split_disallowed_err(win, err)) {
467    return false;  // error already set
468  }
469
470  bool to_split_ok = false;
471  // If we are moving curwin to another tabpage, switch windows *before* we remove it from the
472  // window list or remove its frame (if non-floating), so it's valid for autocommands.
473  const bool curwin_moving_tp = win == curwin && parent && win_tp != parent_tp;
474  if (curwin_moving_tp) {
475    win_T *altwin = win_find_altwin(win, win_tp);
476    assert(altwin);  // win_can_move_tp ensures `win` is not the only window
477    win_goto(altwin);
478
479    // Autocommands may have been a real nuisance and messed things up...
480    if (curwin == win) {
481      api_set_error(err, kErrorTypeException, "Failed to switch away from window %d", win->handle);
482      return false;
483    }
484    win_tp = win_find_tabpage(win);
485    if (!win_tp || !win_valid_any_tab(parent)) {
486      api_set_error(err, kErrorTypeException, "Windows to split were closed");
487      goto restore_curwin;
488    }
489    if (was_split == win->w_floating || parent->w_floating) {
490      api_set_error(err, kErrorTypeException, "Floating state of windows to split changed");
491      goto restore_curwin;
492    }
493  }
494
495  int dir = 0;
496  frame_T *unflat_altfr = NULL;
497  win_T *altwin = NULL;
498
499  if (was_split) {
500    // If the window is the last in the tabpage or `fconfig.win` is a handle to itself, we can't
501    // split it.
502    if (win->w_frame->fr_parent == NULL) {
503      // FIXME(willothy): if the window is the last in the tabpage but there is another tabpage and
504      // the target window is in that other tabpage, should we move the window to that tabpage and
505      // close the previous one, or just error?
506      api_set_error(err, kErrorTypeException, "Cannot move last non-floating window");
507      goto restore_curwin;
508    } else if (parent != NULL && parent->handle == win->handle) {
509      int n_frames = 0;
510      for (frame_T *fr = win->w_frame->fr_parent->fr_child; fr != NULL; fr = fr->fr_next) {
511        n_frames++;
512      }
513
514      win_T *neighbor = NULL;
515
516      if (n_frames > 2) {
517        // There are three or more windows in the frame, we need to split a neighboring window.
518        frame_T *frame = win->w_frame->fr_parent;
519
520        if (frame->fr_parent) {
521          //   ┌──────────────┐
522          //   │      A       │
523          //   ├────┬────┬────┤
524          //   │ B  │ C  │ D  │
525          //   └────┴────┴────┘
526          //          ||
527          //          \/
528          // ┌───────────────────┐
529          // │         A         │
530          // ├─────────┬─────────┤
531          // │         │    C    │
532          // │    B    ├─────────┤
533          // │         │    D    │
534          // └─────────┴─────────┘
535          if (fconfig->split == kWinSplitAbove || fconfig->split == kWinSplitLeft) {
536            neighbor = win->w_next;
537          } else {
538            neighbor = win->w_prev;
539          }
540        }
541        // If the frame doesn't have a parent, the old frame was the root frame and we need to
542        // create a top-level split.
543        altwin = winframe_remove(win, &dir, win_tp == curtab ? NULL : win_tp, &unflat_altfr);
544      } else if (n_frames == 2) {
545        // There are two windows in the frame, we can just rotate it.
546        altwin = winframe_remove(win, &dir, win_tp == curtab ? NULL : win_tp, &unflat_altfr);
547        neighbor = altwin;
548      } else {
549        // There is only one window in the frame, we can't split it.
550        api_set_error(err, kErrorTypeException, "Cannot split window into itself");
551        goto restore_curwin;
552      }
553      // Set the parent to whatever the correct neighbor window was determined to be.
554      parent = neighbor;
555    } else {
556      altwin = winframe_remove(win, &dir, win_tp == curtab ? NULL : win_tp, &unflat_altfr);
557    }
558  } else {
559    altwin = win_float_find_altwin(win, win_tp == curtab ? NULL : win_tp);
560  }
561
562  win_remove(win, win_tp == curtab ? NULL : win_tp);
563  if (win_tp == curtab) {
564    last_status(false);  // may need to remove last status line
565    win_comp_pos();  // recompute window positions
566  }
567
568  int flags = win_split_flags(fconfig->split, parent == NULL) | WSP_NOENTER;
569  parent_tp = parent ? win_find_tabpage(parent) : curtab;
570
571  TRY_WRAP(err, {
572    const bool need_switch = parent != NULL && parent != curwin;
573    CtxSwitch switchwin;
574    if (need_switch) {
575      // `parent` is valid in its tabpage, so ctx_switch should not fail.
576      const bool result = ctx_switch(&switchwin, parent, parent_tp, NULL,
577                                     kCtxNoEvents | kCtxNoDisplay);
578      (void)result;
579      assert(result);
580    }
581    to_split_ok = win_split_ins(0, flags, win, 0, unflat_altfr) != NULL;
582    if (!to_split_ok) {
583      // Restore `win` to the window list now, so it's valid for ctx_restore (if used).
584      win_append(win->w_prev, win, win_tp == curtab ? NULL : win_tp);
585    }
586    if (need_switch) {
587      ctx_restore(&switchwin);
588    }
589  });
590  if (!to_split_ok) {
591    if (was_split) {
592      // win_split_ins doesn't change sizes or layout if it fails to insert an existing window, so
593      // just undo winframe_remove.
594      winframe_restore(win, dir, unflat_altfr);
595    }
596    if (!ERROR_SET(err)) {
597      api_set_error(err, kErrorTypeException, "Failed to move window %d into split", win->handle);
598    }
599
600restore_curwin:
601    // If `win` was the original curwin, and autocommands didn't move it outside of curtab, be a
602    // good citizen and try to return to it.
603    if (curwin_moving_tp && win_valid(win)) {
604      win_goto(win);
605    }
606    return false;
607  }
608
609  // If `win` moved tabpages and was the curwin of its old one, select a new curwin for it.
610  if (win_tp != parent_tp && win_tp->tp_curwin == win) {
611    win_tp->tp_curwin = altwin;
612  }
613
614resize:
615  if (HAS_KEY_X(config, width)) {
616    win_setwidth_win(fconfig->width, win, true);
617  }
618  if (HAS_KEY_X(config, height)) {
619    win_setheight_win(fconfig->height, win, true);
620  }
621
622  // Merge configs now. If previously a float, clear fields irrelevant to splits that `fconfig` may
623  // have shallowly copied; don't free them as win_split_ins handled that. If already a split,
624  // clearing isn't needed, as parse_win_config shouldn't allow setting irrelevant fields.
625  if (!was_split) {
626    clear_float_config(fconfig, false);
627  }
628  merge_win_config(&win->w_config, *fconfig);
629  return true;
630}
631
632/// Configures `win` into a float, also moving it to another tabpage if requested.
633static bool win_config_float_tp(win_T *win, const Dict(win_config) *config,
634                                const WinConfig *fconfig, Error *err)
635  FUNC_ATTR_NONNULL_ALL
636{
637  tabpage_T *win_tp = win_find_tabpage(win);
638  win_T *parent = win;
639  tabpage_T *parent_tp = win_tp;
640  if (HAS_KEY_X(config, win)) {
641    parent = find_window_by_handle(fconfig->window, err);
642    if (!parent) {
643      return false;  // error already set
644    }
645    parent_tp = win_find_tabpage(parent);
646  }
647
648  bool curwin_moving_tp = false;
649  win_T *altwin = NULL;
650
651  if (win_tp != parent_tp) {
652    if (!win_can_move_tp(win, win_tp, err)) {
653      return false;  // error already set
654    }
655    altwin = win_find_altwin(win, win_tp);
656    assert(altwin);  // win_can_move_tp ensures `win` is not the only window
657
658    // If we are moving curwin to another tabpage, switch windows *before* we remove it from the
659    // window list or remove its frame (if non-floating), so it's valid for autocommands.
660    if (curwin == win) {
661      curwin_moving_tp = true;
662      win_goto(altwin);
663
664      // Autocommands may have been a real nuisance and messed things up...
665      if (curwin == win) {
666        api_set_error(err, kErrorTypeException, "Failed to switch away from window %d",
667                      win->handle);
668        return false;
669      }
670      win_tp = win_find_tabpage(win);
671      parent_tp = win_find_tabpage(parent);
672
673      if (!win_tp || !parent_tp) {
674        api_set_error(err, kErrorTypeException, "Target windows were closed");
675        goto restore_curwin;
676      }
677      if (win_tp != parent_tp && !win_can_move_tp(win, win_tp, err)) {
678        goto restore_curwin;  // error already set
679      }
680      altwin = win_find_altwin(win, win_tp);
681      assert(altwin);  // win_can_move_tp ensures `win` is not the only window
682    }
683  }
684
685  // Convert the window to a float if needed.
686  if (!win->w_floating) {
687    if (!win_new_float(win, false, *fconfig, err)) {
688restore_curwin:
689      // If `win` was the original curwin, and autocommands didn't move it outside of curtab, be a
690      // good citizen and try to return to it.
691      if (curwin_moving_tp && win_valid(win)) {
692        win_goto(win);
693      }
694      return false;
695    }
696    redraw_later(win, UPD_NOT_VALID);
697  }
698
699  if (win_tp != parent_tp) {
700    win_remove(win, win_tp == curtab ? NULL : win_tp);
701    tabpage_T *append_tp = parent_tp == curtab ? NULL : parent_tp;
702    win_append(lastwin_nofloating(append_tp), win, append_tp);
703
704    // If `win` was the curwin of its old tabpage, select a new curwin for it.
705    if (win_tp != curtab && win_tp->tp_curwin == win) {
706      win_tp->tp_curwin = altwin;
707    }
708
709    // Remove grid if present. More reliable than checking curtab, as tabpage_check_windows may not
710    // run when temporarily switching tabpages, meaning grids may be stale from another tabpage!
711    // (e.g: ctx_switch with kCtxNoDisplay)
712    ui_comp_remove_grid(&win->w_grid_alloc);
713
714    // Redraw tabline, update window's hl attribs, etc. Set must_redraw here, as redraw_later might
715    // not if w_redr_type >= UPD_NOT_VALID was set in the old tabpage.
716    redraw_later(win, UPD_NOT_VALID);
717    set_must_redraw(UPD_NOT_VALID);
718  }
719
720  win_config_float(win, *fconfig);
721  return true;
722}
723
724/// Reconfigures the layout and properties of a window.
725///
726/// - Updates only the given keys; unspecified (`nil`) keys will not be changed.
727/// - Can move a window to another tabpage.
728/// - Can transform a window to/from a float.
729/// - Keys `row` / `col` / `relative` must be specified together.
730/// - Cannot move the last window in a tabpage to a different one.
731///
732/// Example: to convert a floating window to a "normal" split window, specify the `win` field:
733///
734/// ```lua
735/// vim.api.nvim_win_set_config(0, { split = 'above', win = vim.fn.win_getid(1), })
736/// ```
737///
738/// @see |nvim_open_win()|
739///
740/// @param      win  |window-ID|, or 0 for current window
741/// @param      config  Map defining the window configuration, see [nvim_open_win()]
742/// @param[out] err     Error details, if any
743void nvim_win_set_config(Window win, Dict(win_config) *config, Error *err)
744  FUNC_API_SINCE(6)
745{
746  win_T *w = find_window_by_handle(win, err);
747  if (!w) {
748    return;
749  }
750
751  bool was_split = !w->w_floating;
752  bool has_split = HAS_KEY_X(config, split);
753  bool has_vertical = HAS_KEY_X(config, vertical);
754  WinStyle old_style = w->w_config.style;
755  // reuse old values, if not overridden
756  WinConfig fconfig = w->w_config;
757
758  bool to_split = config->relative.size == 0
759                  && !(HAS_KEY_X(config, external) && config->external)
760                  && (has_split || has_vertical || was_split);
761  bool will_float = (!was_split && !to_split) || config->relative.size > 0 || config->external;
762
763  if (!parse_win_config(w, config, &fconfig, !was_split || to_split, will_float, err)) {
764    return;
765  }
766
767  if (to_split) {
768    if (!win_config_split(w, config, &fconfig, err)) {
769      return;
770    }
771  } else {
772    if (!win_config_float_tp(w, config, &fconfig, err)) {
773      return;
774    }
775  }
776
777  if (fconfig.style == kWinStyleMinimal && old_style != fconfig.style) {
778    win_set_minimal_style(w);
779    didset_window_options(w, true);
780    changed_window_setting(w);
781  }
782  if (fconfig._cmdline_offset < INT_MAX) {
783    cmdline_win = w;
784  } else if (w == cmdline_win && fconfig._cmdline_offset == INT_MAX) {
785    cmdline_win = NULL;
786  }
787}
788
789#define PUT_KEY_X(d, key, value) PUT_KEY(d, win_config, key, value)
790static void config_put_bordertext(Dict(win_config) *config, WinConfig *fconfig,
791                                  BorderTextType bordertext_type, Arena *arena)
792{
793  VirtText vt;
794  AlignTextPos align;
795  switch (bordertext_type) {
796  case kBorderTextTitle:
797    vt = fconfig->title_chunks;
798    align = fconfig->title_pos;
799    break;
800  case kBorderTextFooter:
801    vt = fconfig->footer_chunks;
802    align = fconfig->footer_pos;
803    break;
804  }
805
806  Array bordertext = virt_text_to_array(vt, true, arena);
807
808  char *pos;
809  switch (align) {
810  case kAlignLeft:
811    pos = "left";
812    break;
813  case kAlignCenter:
814    pos = "center";
815    break;
816  case kAlignRight:
817    pos = "right";
818    break;
819  }
820
821  switch (bordertext_type) {
822  case kBorderTextTitle:
823    PUT_KEY_X(*config, title, ARRAY_OBJ(bordertext));
824    PUT_KEY_X(*config, title_pos, cstr_as_string(pos));
825    break;
826  case kBorderTextFooter:
827    PUT_KEY_X(*config, footer, ARRAY_OBJ(bordertext));
828    PUT_KEY_X(*config, footer_pos, cstr_as_string(pos));
829  }
830}
831
832/// Gets window config as a dict which can be passed to |nvim_open_win()| as the `config` parameter.
833///
834/// For non-floating windows, `relative` is empty, thus you can check that field to detect if
835/// a window is a floatwin:
836/// ```lua
837/// vim.print(vim.api.nvim_win_get_config(0).relative == '' and 'non-float' or 'float')
838/// -- Or use win_gettype().
839/// vim.print(vim.fn.win_gettype())
840/// ```
841///
842/// @param      win |window-ID|, or 0 for current window
843/// @param[out] err Error details, if any
844/// @return     Map defining the window configuration, see |nvim_open_win()|
845Dict(win_config) nvim_win_get_config(Window win, Arena *arena, Error *err)
846  FUNC_API_SINCE(6)
847{
848  /// Keep in sync with FloatRelative in buffer_defs.h
849  static const char *const float_relative_str[] = {
850    "editor", "win", "cursor", "mouse", "tabline", "laststatus"
851  };
852
853  /// Keep in sync with WinSplit in buffer_defs.h
854  static const char *const win_split_str[] = { "left", "right", "above", "below" };
855
856  /// Keep in sync with WinStyle in buffer_defs.h
857  static const char *const win_style_str[] = { "", "minimal" };
858
859  Dict(win_config) rv = KEYDICT_INIT;
860
861  win_T *wp = find_window_by_handle(win, err);
862  if (!wp) {
863    return rv;
864  }
865
866  WinConfig *config = &wp->w_config;
867
868  PUT_KEY_X(rv, focusable, config->focusable);
869  PUT_KEY_X(rv, external, config->external);
870  PUT_KEY_X(rv, hide, config->hide);
871  PUT_KEY_X(rv, mouse, config->mouse);
872  PUT_KEY_X(rv, style, cstr_as_string(win_style_str[config->style]));
873
874  if (wp->w_floating) {
875    PUT_KEY_X(rv, width, config->width);
876    PUT_KEY_X(rv, height, config->height);
877    if (!config->external) {
878      if (config->relative == kFloatRelativeWindow) {
879        PUT_KEY_X(rv, win, config->window);
880        if (config->bufpos.lnum >= 0) {
881          Array pos = arena_array(arena, 2);
882          ADD_C(pos, INTEGER_OBJ(config->bufpos.lnum));
883          ADD_C(pos, INTEGER_OBJ(config->bufpos.col));
884          PUT_KEY_X(rv, bufpos, pos);
885        }
886      }
887      PUT_KEY_X(rv, anchor, cstr_as_string(float_anchor_str[config->anchor]));
888      PUT_KEY_X(rv, row, config->row);
889      PUT_KEY_X(rv, col, config->col);
890      PUT_KEY_X(rv, zindex, config->zindex);
891    }
892    if (config->border) {
893      Array border = arena_array(arena, 8);
894      for (size_t i = 0; i < 8; i++) {
895        String s = cstrn_as_string(config->border_chars[i], MAX_SCHAR_SIZE);
896
897        int hi_id = config->border_hl_ids[i];
898        char *hi_name = syn_id2name(hi_id);
899        if (hi_name[0]) {
900          Array tuple = arena_array(arena, 2);
901          ADD_C(tuple, STRING_OBJ(s));
902          ADD_C(tuple, CSTR_AS_OBJ(hi_name));
903          ADD_C(border, ARRAY_OBJ(tuple));
904        } else {
905          ADD_C(border, STRING_OBJ(s));
906        }
907      }
908      PUT_KEY_X(rv, border, ARRAY_OBJ(border));
909      if (config->title) {
910        config_put_bordertext(&rv, config, kBorderTextTitle, arena);
911      }
912      if (config->footer) {
913        config_put_bordertext(&rv, config, kBorderTextFooter, arena);
914      }
915    } else {
916      PUT_KEY_X(rv, border, STRING_OBJ(cstr_as_string("none")));
917    }
918  } else if (!config->external) {
919    PUT_KEY_X(rv, width, wp->w_width);
920    PUT_KEY_X(rv, height, wp->w_height);
921    WinSplit split = win_split_dir(wp);
922    PUT_KEY_X(rv, split, cstr_as_string(win_split_str[split]));
923  }
924
925  const char *rel = (wp->w_floating && !config->external
926                     ? float_relative_str[config->relative] : "");
927  PUT_KEY_X(rv, relative, cstr_as_string(rel));
928  if (config->_cmdline_offset < INT_MAX) {
929    PUT_KEY_X(rv, _cmdline_offset, config->_cmdline_offset);
930  }
931
932  return rv;
933}
934
935static bool parse_float_anchor(String anchor, FloatAnchor *out)
936{
937  if (anchor.size == 0) {
938    *out = (FloatAnchor)0;
939  }
940  char *str = anchor.data;
941  if (striequal(str, "NW")) {
942    *out = 0;  //  NW is the default
943  } else if (striequal(str, "NE")) {
944    *out = kFloatAnchorEast;
945  } else if (striequal(str, "SW")) {
946    *out = kFloatAnchorSouth;
947  } else if (striequal(str, "SE")) {
948    *out = kFloatAnchorSouth | kFloatAnchorEast;
949  } else {
950    return false;
951  }
952  return true;
953}
954
955static bool parse_float_relative(String relative, FloatRelative *out)
956{
957  char *str = relative.data;
958  if (striequal(str, "editor")) {
959    *out = kFloatRelativeEditor;
960  } else if (striequal(str, "win")) {
961    *out = kFloatRelativeWindow;
962  } else if (striequal(str, "cursor")) {
963    *out = kFloatRelativeCursor;
964  } else if (striequal(str, "mouse")) {
965    *out = kFloatRelativeMouse;
966  } else if (striequal(str, "tabline")) {
967    *out = kFloatRelativeTabline;
968  } else if (striequal(str, "laststatus")) {
969    *out = kFloatRelativeLaststatus;
970  } else {
971    return false;
972  }
973  return true;
974}
975
976static bool parse_config_split(String split, WinSplit *out)
977{
978  char *str = split.data;
979  if (striequal(str, "left")) {
980    *out = kWinSplitLeft;
981  } else if (striequal(str, "right")) {
982    *out = kWinSplitRight;
983  } else if (striequal(str, "above")) {
984    *out = kWinSplitAbove;
985  } else if (striequal(str, "below")) {
986    *out = kWinSplitBelow;
987  } else {
988    return false;
989  }
990  return true;
991}
992
993static bool parse_float_bufpos(Array bufpos, lpos_T *out)
994{
995  if (bufpos.size != 2 || bufpos.items[0].type != kObjectTypeInteger
996      || bufpos.items[1].type != kObjectTypeInteger) {
997    return false;
998  }
999  out->lnum = (linenr_T)bufpos.items[0].data.integer;
1000  out->col = (colnr_T)bufpos.items[1].data.integer;
1001  return true;
1002}
1003
1004void parse_bordertext(Object bordertext, BorderTextType bordertext_type, WinConfig *fconfig,
1005                      Error *err)
1006{
1007  VALIDATE_EXP(!(bordertext.type != kObjectTypeString && bordertext.type != kObjectTypeArray),
1008               "title/footer", "String or Array", api_typename(bordertext.type), {
1009    return;
1010  });
1011
1012  VALIDATE_EXP(!(bordertext.type == kObjectTypeArray && bordertext.data.array.size == 0),
1013               "title/footer", "non-empty Array", NULL, {
1014    return;
1015  });
1016
1017  bool is_title = bordertext_type == kBorderTextTitle;
1018  bool *is_present = is_title ? &fconfig->title : &fconfig->footer;
1019  VirtText *chunks = is_title ? &fconfig->title_chunks : &fconfig->footer_chunks;
1020  int *width = is_title ? &fconfig->title_width : &fconfig->footer_width;
1021
1022  if (bordertext.type == kObjectTypeString) {
1023    if (bordertext.data.string.size == 0) {
1024      *is_present = false;
1025      return;
1026    }
1027    char *text = transstr(bordertext.data.string.data, true);
1028    kv_init(*chunks);
1029    kv_push(*chunks, ((VirtTextChunk){ .text = text, .hl_id = -1 }));
1030    *width = (int)mb_string2cells(text);
1031  } else {
1032    *chunks = parse_virt_text(bordertext.data.array, err, width, true);
1033    if (ERROR_SET(err)) {
1034      return;
1035    }
1036  }
1037
1038  *is_present = true;
1039}
1040
1041static bool parse_bordertext_pos(win_T *wp, String bordertext_pos, BorderTextType bordertext_type,
1042                                 WinConfig *fconfig, Error *err)
1043{
1044  AlignTextPos *align;
1045  switch (bordertext_type) {
1046  case kBorderTextTitle:
1047    align = &fconfig->title_pos;
1048    break;
1049  case kBorderTextFooter:
1050    align = &fconfig->footer_pos;
1051    break;
1052  }
1053
1054  if (bordertext_pos.size == 0) {
1055    if (!wp) {
1056      *align = kAlignLeft;
1057    }
1058    return true;
1059  }
1060
1061  char *pos = bordertext_pos.data;
1062
1063  if (strequal(pos, "left")) {
1064    *align = kAlignLeft;
1065  } else if (strequal(pos, "center")) {
1066    *align = kAlignCenter;
1067  } else if (strequal(pos, "right")) {
1068    *align = kAlignRight;
1069  } else {
1070    VALIDATE_S(false, (bordertext_type == kBorderTextTitle ? "title_pos" : "footer_pos"), pos, {
1071      return false;
1072    });
1073  }
1074  return true;
1075}
1076
1077void parse_border_style(Object style, WinConfig *fconfig, Error *err)
1078{
1079  struct {
1080    const char *name;
1081    char chars[8][MAX_SCHAR_SIZE];
1082    bool shadow_color;
1083  } defaults[] = {
1084    { opt_winborder_values[1], { "╔", "═", "╗", "║", "╝", "═", "╚", "║" }, false },
1085    { opt_winborder_values[2], { "┌", "─", "┐", "│", "┘", "─", "└", "│" }, false },
1086    { opt_winborder_values[3], { "", "", " ", " ", " ", " ", " ", "" }, true },
1087    { opt_winborder_values[4], { "╭", "─", "╮", "│", "╯", "─", "╰", "│" }, false },
1088    { opt_winborder_values[5], { " ", " ", " ", " ", " ", " ", " ", " " }, false },
1089    { opt_winborder_values[6], { "┏", "━", "┓", "┃", "┛", "━", "┗", "┃" }, false },
1090    { NULL, { { NUL } }, false },
1091  };
1092
1093  char(*chars)[MAX_SCHAR_SIZE] = fconfig->border_chars;
1094  int *hl_ids = fconfig->border_hl_ids;
1095
1096  fconfig->border = true;
1097
1098  if (style.type == kObjectTypeArray) {
1099    Array arr = style.data.array;
1100    size_t size = arr.size;
1101    VALIDATE_EXP(!(!size || size > 8 || (size & (size - 1))),
1102                 "border", "1, 2, 4, or 8 chars", NULL, {
1103      return;
1104    });
1105    for (size_t i = 0; i < size; i++) {
1106      Object iytem = arr.items[i];
1107      String string;
1108      int hl_id = 0;
1109      if (iytem.type == kObjectTypeArray) {
1110        Array iarr = iytem.data.array;
1111        VALIDATE_EXP(!(!iarr.size || iarr.size > 2), "border", "1 or 2-item Array", NULL, {
1112          return;
1113        });
1114        VALIDATE_EXP(iarr.items[0].type == kObjectTypeString, "border", "Array of Strings", NULL, {
1115          return;
1116        });
1117        string = iarr.items[0].data.string;
1118        if (iarr.size == 2) {
1119          hl_id = object_to_hl_id(iarr.items[1], "border char highlight", err);
1120          if (ERROR_SET(err)) {
1121            return;
1122          }
1123        }
1124      } else if (iytem.type == kObjectTypeString) {
1125        string = iytem.data.string;
1126      } else {
1127        VALIDATE_EXP(false, "border", "String or Array", api_typename(iytem.type), {
1128          return;
1129        });
1130      }
1131      VALIDATE_EXP(!(string.size && mb_string2cells_len(string.data, string.size) > 1),
1132                   "border", "only one-cell chars", NULL, {
1133        return;
1134      });
1135      size_t len = MIN(string.size, sizeof(*chars) - 1);
1136      if (len) {
1137        memcpy(chars[i], string.data, len);
1138      }
1139      chars[i][len] = NUL;
1140      hl_ids[i] = hl_id;
1141    }
1142    while (size < 8) {
1143      memcpy(chars + size, chars, sizeof(*chars) * size);
1144      memcpy(hl_ids + size, hl_ids, sizeof(*hl_ids) * size);
1145      size <<= 1;
1146    }
1147    VALIDATE_EXP(!((chars[7][0] && chars[1][0] && !chars[0][0])
1148                   || (chars[1][0] && chars[3][0] && !chars[2][0])
1149                   || (chars[3][0] && chars[5][0] && !chars[4][0])
1150                   || (chars[5][0] && chars[7][0] && !chars[6][0])), "border",
1151                 "corner char between edge chars", NULL, {
1152      return;
1153    });
1154  } else if (style.type == kObjectTypeString) {
1155    String str = style.data.string;
1156    if (str.size == 0 || strequal(str.data, "none")) {
1157      fconfig->border = false;
1158      // border text does not work with border equal none
1159      fconfig->title = false;
1160      fconfig->footer = false;
1161      return;
1162    }
1163    for (size_t i = 0; defaults[i].name; i++) {
1164      if (strequal(str.data, defaults[i].name)) {
1165        memcpy(chars, defaults[i].chars, sizeof(defaults[i].chars));
1166        memset(hl_ids, 0, 8 * sizeof(*hl_ids));
1167        if (defaults[i].shadow_color) {
1168          int hl_blend = SYN_GROUP_STATIC("FloatShadow");
1169          int hl_through = SYN_GROUP_STATIC("FloatShadowThrough");
1170          hl_ids[2] = hl_through;
1171          hl_ids[3] = hl_blend;
1172          hl_ids[4] = hl_blend;
1173          hl_ids[5] = hl_blend;
1174          hl_ids[6] = hl_through;
1175        }
1176        return;
1177      }
1178    }
1179    VALIDATE_S(false, "border", str.data, {
1180      return;
1181    });
1182  }
1183}
1184
1185static void generate_api_error(win_T *wp, const char *attribute, Error *err)
1186{
1187  if (wp != NULL && wp->w_floating) {
1188    api_set_error(err, kErrorTypeValidation,
1189                  "Required: 'relative' when reconfiguring floating window %d",
1190                  wp->handle);
1191  } else {
1192    VALIDATE_CON(false, attribute, "non-float window", {});
1193  }
1194}
1195
1196/// Parses a border style name or custom (comma-separated) style.
1197bool parse_winborder(WinConfig *fconfig, char *border_opt, Error *err)
1198{
1199  if (!fconfig) {
1200    return false;
1201  }
1202  Object style = OBJECT_INIT;
1203
1204  if (strchr(border_opt, ',')) {
1205    Array border_chars = ARRAY_DICT_INIT;
1206    char *p = border_opt;
1207    while (true) {
1208      if (border_chars.size >= 8) {
1209        api_free_array(border_chars);
1210        return false;
1211      }
1212      char *comma = strchr(p, ',');
1213      size_t part_len = comma != NULL ? (size_t)(comma - p) : strlen(p);
1214      ADD(border_chars, STRING_OBJ(cbuf_to_string(p, part_len)));
1215      if (comma == NULL) {
1216        break;
1217      }
1218      p = comma + 1;
1219    }
1220    if (border_chars.size != 8) {
1221      api_free_array(border_chars);
1222      return false;
1223    }
1224
1225    style = ARRAY_OBJ(border_chars);
1226  } else {
1227    style = CSTR_TO_OBJ(border_opt);
1228  }
1229
1230  parse_border_style(style, fconfig, err);
1231  api_free_object(style);
1232  return !ERROR_SET(err);
1233}
1234
1235static bool parse_win_config(win_T *wp, Dict(win_config) *config, WinConfig *fconfig, bool reconf,
1236                             bool will_float, Error *err)
1237{
1238  bool has_relative = false, relative_is_win = false, is_split = false;
1239  if (config->relative.size > 0) {
1240    VALIDATE_S(parse_float_relative(config->relative, &fconfig->relative),
1241               "relative", config->relative.data, {
1242      goto fail;
1243    });
1244
1245    VALIDATE_R(!(config->relative.size > 0 && !(HAS_KEY_X(config, row) && HAS_KEY_X(config, col))
1246                 && !HAS_KEY_X(config, bufpos)), "'relative' requires 'row'/'col' or 'bufpos'", {
1247      goto fail;
1248    });
1249
1250    has_relative = true;
1251    fconfig->external = false;
1252    if (fconfig->relative == kFloatRelativeWindow) {
1253      relative_is_win = true;
1254      fconfig->bufpos.lnum = -1;
1255    }
1256  } else if (!config->external) {
1257    if (HAS_KEY_X(config, vertical) || HAS_KEY_X(config, split)) {
1258      is_split = true;
1259      fconfig->external = false;
1260    } else if (wp == NULL) {  // new win
1261      VALIDATE_R(false, "'relative' or 'external' when creating a float", {
1262        goto fail;
1263      });
1264    }
1265  }
1266
1267  VALIDATE_CON(!(HAS_KEY_X(config, vertical) && !is_split), "vertical", "floating windows", {
1268    goto fail;
1269  });
1270
1271  VALIDATE_CON(!(HAS_KEY_X(config, split) && !is_split), "split", "floating windows", {
1272    goto fail;
1273  });
1274
1275  if (HAS_KEY_X(config, split)) {
1276    VALIDATE_CON(is_split, "split", "floating windows", {
1277      goto fail;
1278    });
1279    VALIDATE_S(parse_config_split(config->split, &fconfig->split), "split", config->split.data, {
1280      goto fail;
1281    });
1282  }
1283
1284  if (HAS_KEY_X(config, anchor)) {
1285    VALIDATE_S(parse_float_anchor(config->anchor, &fconfig->anchor),
1286               "anchor", config->anchor.data, {
1287      goto fail;
1288    });
1289  }
1290
1291  if (HAS_KEY_X(config, row)) {
1292    if (!has_relative || is_split) {
1293      generate_api_error(wp, "row", err);
1294      goto fail;
1295    }
1296    fconfig->row = config->row;
1297  }
1298
1299  if (HAS_KEY_X(config, col)) {
1300    if (!has_relative || is_split) {
1301      generate_api_error(wp, "col", err);
1302      goto fail;
1303    }
1304    fconfig->col = config->col;
1305  }
1306
1307  if (HAS_KEY_X(config, bufpos)) {
1308    if (!has_relative || is_split) {
1309      generate_api_error(wp, "bufpos", err);
1310      goto fail;
1311    } else {
1312      VALIDATE_EXP(parse_float_bufpos(config->bufpos, &fconfig->bufpos),
1313                   "bufpos", "[row, col] array", NULL, {
1314        goto fail;
1315      });
1316
1317      if (!HAS_KEY_X(config, row)) {
1318        fconfig->row = (fconfig->anchor & kFloatAnchorSouth) ? 0 : 1;
1319      }
1320      if (!HAS_KEY_X(config, col)) {
1321        fconfig->col = 0;
1322      }
1323    }
1324  }
1325
1326  if (HAS_KEY_X(config, width)) {
1327    VALIDATE_EXP((config->width > 0), "width", "positive Integer", NULL, {
1328      goto fail;
1329    });
1330    fconfig->width = (int)config->width;
1331  } else if (!reconf && !is_split) {
1332    VALIDATE_R(false, "width", {
1333      goto fail;
1334    });
1335  }
1336
1337  if (HAS_KEY_X(config, height)) {
1338    VALIDATE_EXP((config->height > 0), "height", "positive Integer", NULL, {
1339      goto fail;
1340    });
1341    fconfig->height = (int)config->height;
1342  } else if (!reconf && !is_split) {
1343    VALIDATE_R(false, "height", {
1344      goto fail;
1345    });
1346  }
1347
1348  if (HAS_KEY_X(config, external)) {
1349    fconfig->external = config->external;
1350    VALIDATE_CON(!(has_relative && fconfig->external), "relative", "external", {
1351      goto fail;
1352    });
1353    if (fconfig->external && !ui_has(kUIMultigrid)) {
1354      api_set_error(err, kErrorTypeValidation, "UI doesn't support external windows");
1355      goto fail;
1356    }
1357  }
1358
1359  VALIDATE_CON(!(HAS_KEY_X(config, win) && fconfig->external), "win", "external window", {
1360    goto fail;
1361  });
1362
1363  if (relative_is_win || (HAS_KEY_X(config, win) && !is_split && wp && wp->w_floating
1364                          && fconfig->relative == kFloatRelativeWindow)) {
1365    // When relative=win is given, missing win field means win=0.
1366    win_T *target_win = find_window_by_handle(config->win, err);
1367    if (!target_win) {
1368      goto fail;
1369    }
1370    if (target_win == wp) {
1371      api_set_error(err, kErrorTypeException, "floating window cannot be relative to itself");
1372      goto fail;
1373    }
1374    fconfig->window = target_win->handle;
1375  } else {
1376    // Handle is not validated here, as win_config_split can accept negative values.
1377    if (HAS_KEY_X(config, win)) {
1378      VALIDATE_R(!(!is_split && !has_relative && (!wp || !wp->w_floating)),
1379                 "non-float with 'win' requires 'split' or 'vertical'", {
1380        goto fail;
1381      });
1382
1383      fconfig->window = config->win;
1384    }
1385    // Resolve, but skip validating. E.g: win_config_split accepts negative "win".
1386    if (fconfig->window == 0) {
1387      fconfig->window = curwin->handle;
1388    }
1389  }
1390
1391  if (HAS_KEY_X(config, focusable)) {
1392    fconfig->focusable = config->focusable;
1393    fconfig->mouse = config->focusable;
1394  }
1395
1396  if (HAS_KEY_X(config, mouse)) {
1397    fconfig->mouse = config->mouse;
1398  }
1399
1400  if (HAS_KEY_X(config, zindex)) {
1401    VALIDATE_CON(will_float, "zindex", "non-float window", {
1402      goto fail;
1403    });
1404    VALIDATE_EXP((config->zindex > 0), "zindex", "positive Integer", NULL, {
1405      goto fail;
1406    });
1407    fconfig->zindex = (int)config->zindex;
1408  }
1409
1410  if (HAS_KEY_X(config, title)) {
1411    VALIDATE_CON(will_float, "title", "non-float window", {
1412      goto fail;
1413    });
1414
1415    parse_bordertext(config->title, kBorderTextTitle, fconfig, err);
1416    if (ERROR_SET(err)) {
1417      goto fail;
1418    }
1419
1420    // handles unset 'title_pos' same as empty string
1421    if (!parse_bordertext_pos(wp, config->title_pos, kBorderTextTitle, fconfig, err)) {
1422      goto fail;
1423    }
1424  } else {
1425    VALIDATE_R(!HAS_KEY_X(config, title_pos), "'title' requires 'title_pos'", {
1426      goto fail;
1427    });
1428  }
1429
1430  if (HAS_KEY_X(config, footer)) {
1431    VALIDATE_CON(will_float, "footer", "non-float window", {
1432      goto fail;
1433    });
1434
1435    parse_bordertext(config->footer, kBorderTextFooter, fconfig, err);
1436    if (ERROR_SET(err)) {
1437      goto fail;
1438    }
1439
1440    // handles unset 'footer_pos' same as empty string
1441    if (!parse_bordertext_pos(wp, config->footer_pos, kBorderTextFooter, fconfig, err)) {
1442      goto fail;
1443    }
1444  } else {
1445    VALIDATE_R(!HAS_KEY_X(config, footer_pos), "'footer' requires 'footer_pos'", {
1446      goto fail;
1447    });
1448  }
1449
1450  Object border_style = OBJECT_INIT;
1451  if (HAS_KEY_X(config, border)) {
1452    VALIDATE_CON(will_float, "border", "non-float window", {
1453      goto fail;
1454    });
1455    border_style = config->border;
1456    if (border_style.type != kObjectTypeNil) {
1457      parse_border_style(border_style, fconfig, err);
1458      if (ERROR_SET(err)) {
1459        goto fail;
1460      }
1461    }
1462  } else if (*p_winborder != NUL && (wp == NULL || !wp->w_floating)
1463             && !parse_winborder(fconfig, p_winborder, err)) {
1464    goto fail;
1465  }
1466
1467  if (HAS_KEY_X(config, style)) {
1468    if (config->style.data[0] == NUL) {
1469      fconfig->style = kWinStyleUnused;
1470    } else if (striequal(config->style.data, "minimal")) {
1471      fconfig->style = kWinStyleMinimal;
1472    } else {
1473      VALIDATE_S(false, "style", config->style.data, {
1474        goto fail;
1475      });
1476    }
1477  }
1478
1479  if (HAS_KEY_X(config, noautocmd)) {
1480    if (wp && config->noautocmd != fconfig->noautocmd) {
1481      api_set_error(err, kErrorTypeValidation, "'noautocmd' cannot be changed on existing window");
1482      goto fail;
1483    }
1484    fconfig->noautocmd = config->noautocmd;
1485  }
1486
1487  if (HAS_KEY_X(config, fixed)) {
1488    fconfig->fixed = config->fixed;
1489  }
1490
1491  if (HAS_KEY_X(config, hide)) {
1492    VALIDATE_CON(will_float || !config->hide, "hide", "non-float window", {
1493      goto fail;
1494    });
1495    if (fconfig->hide && !config->hide) {
1496      redraw_later(wp, UPD_NOT_VALID);
1497    }
1498    fconfig->hide = config->hide;
1499  }
1500
1501  if (HAS_KEY_X(config, _cmdline_offset)) {
1502    fconfig->_cmdline_offset = (int)config->_cmdline_offset;
1503  }
1504
1505  return true;
1506
1507fail:
1508  merge_win_config(fconfig, wp != NULL ? wp->w_config : WIN_CONFIG_INIT);
1509  return false;
1510}