robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
18.1 KiB617 linesraw
1#include <assert.h>
2#include <stdbool.h>
3#include <stdlib.h>
4#include <string.h>
5
6#include "klib/kvec.h"
7#include "nvim/api/private/defs.h"
8#include "nvim/api/private/helpers.h"
9#include "nvim/api/vim.h"
10#include "nvim/api/win_config.h"
11#include "nvim/ascii_defs.h"
12#include "nvim/autocmd.h"
13#include "nvim/buffer.h"
14#include "nvim/buffer_defs.h"
15#include "nvim/charset.h"
16#include "nvim/decoration.h"
17#include "nvim/decoration_defs.h"
18#include "nvim/drawscreen.h"
19#include "nvim/errors.h"
20#include "nvim/fileio.h"
21#include "nvim/globals.h"
22#include "nvim/grid.h"
23#include "nvim/grid_defs.h"
24#include "nvim/highlight.h"
25#include "nvim/highlight_defs.h"
26#include "nvim/highlight_group.h"
27#include "nvim/lua/executor.h"
28#include "nvim/macros_defs.h"
29#include "nvim/mbyte.h"
30#include "nvim/memory.h"
31#include "nvim/message.h"
32#include "nvim/mouse.h"
33#include "nvim/move.h"
34#include "nvim/option.h"
35#include "nvim/option_defs.h"
36#include "nvim/option_vars.h"
37#include "nvim/optionstr.h"
38#include "nvim/os/fs.h"
39#include "nvim/plines.h"
40#include "nvim/pos_defs.h"
41#include "nvim/strings.h"
42#include "nvim/types_defs.h"
43#include "nvim/ui.h"
44#include "nvim/ui_defs.h"
45#include "nvim/vim_defs.h"
46#include "nvim/window.h"
47#include "nvim/winfloat.h"
48
49#include "options_keysets.generated.h"
50#include "winfloat.c.generated.h"
51
52/// Creates a new float, or transforms an existing window to a float.
53///
54/// @param wp      if NULL, allocate a new window, otherwise turn existing window into a float.
55/// @param last    make the window the last one in the window list.
56///                Only used when allocating the autocommand window.
57/// @param config  must already have been validated!
58win_T *win_new_float(win_T *wp, bool last, WinConfig fconfig, Error *err)
59{
60  if (wp == NULL) {
61    tabpage_T *tp = NULL;
62    win_T *tp_last = last ? lastwin : lastwin_nofloating(NULL);
63    if (fconfig.window != 0) {
64      assert(!last);
65      win_T *parent_wp = find_window_by_handle(fconfig.window, err);
66      if (!parent_wp) {
67        return NULL;
68      }
69      tp = win_find_tabpage(parent_wp);
70      if (!tp) {
71        return NULL;
72      }
73      tp_last = lastwin_nofloating(tp == curtab ? NULL : tp);
74    }
75    wp = win_alloc(tp_last, false);
76    win_init(wp, curwin, 0);
77    if (wp->w_p_wbr != NULL && fconfig.height == 1) {
78      if (wp->w_p_wbr != empty_string_option) {
79        free_string_option(wp->w_p_wbr);
80      }
81      wp->w_p_wbr = empty_string_option;
82    }
83    if (wp->w_p_stl && wp->w_p_stl != empty_string_option) {
84      free_string_option(wp->w_p_stl);
85      wp->w_p_stl = empty_string_option;
86    }
87  } else {
88    assert(!last);
89    assert(!wp->w_floating);
90    tabpage_T *win_tp = win_find_tabpage(wp);
91    assert(win_tp);
92    if ((win_tp == curtab && firstwin == wp && lastwin_nofloating(NULL) == wp)
93        || (win_tp != curtab && win_tp->tp_firstwin == wp && lastwin_nofloating(win_tp) == wp)) {
94      api_set_error(err, kErrorTypeException, "Cannot change last window into float");
95      return NULL;
96    }
97    tabpage_T *tp = win_tp == curtab ? NULL : win_tp;
98    int dir;
99    winframe_remove(wp, &dir, tp, NULL);
100    XFREE_CLEAR(wp->w_frame);
101    win_remove(wp, tp);
102    if (win_tp == curtab) {
103      last_status(false);  // may need to remove last status line
104      win_comp_pos();  // recompute window positions
105    }
106    win_append(lastwin_nofloating(tp), wp, tp);
107  }
108  wp->w_floating = true;
109  wp->w_status_height = wp->w_p_stl && *wp->w_p_stl != NUL
110                        && (p_ls == 1 || p_ls == 2) ? STATUS_HEIGHT : 0;
111  wp->w_winbar_height = 0;
112  wp->w_hsep_height = 0;
113  wp->w_vsep_width = 0;
114
115  win_config_float(wp, fconfig);
116  redraw_later(wp, UPD_VALID);
117  return wp;
118}
119
120void win_set_minimal_style(win_T *wp)
121{
122  wp->w_p_nu = false;
123  wp->w_p_rnu = false;
124  wp->w_p_cul = false;
125  wp->w_p_cuc = false;
126  wp->w_p_spell = false;
127  wp->w_p_list = false;
128
129  // Hide EOB region: use " " fillchar and cleared highlighting
130  if (wp->w_p_fcs_chars.eob != ' ') {
131    char *old = wp->w_p_fcs;
132    wp->w_p_fcs = ((*old == NUL)
133                   ? xstrdup("eob: ")
134                   : concat_str(old, ",eob: "));
135    free_string_option(old);
136  }
137
138  // TODO(bfredl): this could use a highlight namespace directly,
139  // and avoid peculiarities around window options
140  char *old = wp->w_p_winhl;
141  wp->w_p_winhl = ((*old == NUL)
142                   ? xstrdup("EndOfBuffer:")
143                   : concat_str(old, ",EndOfBuffer:"));
144  free_string_option(old);
145  parse_winhl_opt(NULL, wp);
146
147  // signcolumn: use 'auto'
148  if (wp->w_p_scl[0] != 'a' || strlen(wp->w_p_scl) >= 8) {
149    free_string_option(wp->w_p_scl);
150    wp->w_p_scl = xstrdup("auto");
151  }
152
153  // foldcolumn: use '0'
154  if (wp->w_p_fdc[0] != '0') {
155    free_string_option(wp->w_p_fdc);
156    wp->w_p_fdc = xstrdup("0");
157  }
158
159  // colorcolumn: cleared
160  if (wp->w_p_cc != NULL && *wp->w_p_cc != NUL) {
161    free_string_option(wp->w_p_cc);
162    wp->w_p_cc = xstrdup("");
163  }
164
165  // statuscolumn: cleared
166  if (wp->w_p_stc != NULL && *wp->w_p_stc != NUL) {
167    free_string_option(wp->w_p_stc);
168    wp->w_p_stc = empty_string_option;
169  }
170
171  // statusline: cleared (for floating windows)
172  if (wp->w_floating && wp->w_p_stl != NULL && *wp->w_p_stl != NUL) {
173    free_string_option(wp->w_p_stl);
174    wp->w_p_stl = empty_string_option;
175    if (wp->w_status_height > 0) {
176      win_config_float(wp, wp->w_config);
177    }
178  }
179}
180
181int win_border_height(win_T *wp)
182{
183  return wp->w_border_adj[0] + wp->w_border_adj[2];
184}
185
186int win_border_width(win_T *wp)
187{
188  return wp->w_border_adj[1] + wp->w_border_adj[3];
189}
190
191void win_config_float(win_T *wp, WinConfig fconfig)
192{
193  // Process statusline changes before applying new height from config
194  bool show_stl = *wp->w_p_stl != NUL && (p_ls == 1 || p_ls == 2);
195  if (wp->w_status_height && !show_stl) {
196    win_remove_status_line(wp, false);
197  } else if (wp->w_status_height == 0 && show_stl) {
198    wp->w_status_height = STATUS_HEIGHT;
199  }
200
201  wp->w_width = MAX(fconfig.width, 1);
202  wp->w_height = MAX(fconfig.height, 1);
203
204  if (fconfig.relative == kFloatRelativeCursor) {
205    validate_cursor(curwin);
206    fconfig.relative = kFloatRelativeWindow;
207    fconfig.row += curwin->w_wrow;
208    fconfig.col += curwin->w_wcol;
209    fconfig.window = curwin->handle;
210  } else if (fconfig.relative == kFloatRelativeMouse) {
211    int row = mouse_row;
212    int col = mouse_col;
213    int grid = mouse_grid;
214    win_T *mouse_win = mouse_find_win_inner(&grid, &row, &col);
215    if (mouse_win != NULL) {
216      fconfig.relative = kFloatRelativeWindow;
217      fconfig.row += row;
218      fconfig.col += col;
219      fconfig.window = mouse_win->handle;
220    }
221  }
222
223  bool change_external = fconfig.external != wp->w_config.external;
224  bool change_border = (fconfig.border != wp->w_config.border
225                        || memcmp(fconfig.border_hl_ids,
226                                  wp->w_config.border_hl_ids,
227                                  sizeof fconfig.border_hl_ids) != 0);
228
229  merge_win_config(&wp->w_config, fconfig);
230
231  bool has_border = wp->w_floating && wp->w_config.border;
232  for (int i = 0; i < 4; i++) {
233    int new_adj = has_border && wp->w_config.border_chars[2 * i + 1][0];
234    if (new_adj != wp->w_border_adj[i]) {
235      change_border = true;
236      wp->w_border_adj[i] = new_adj;
237    }
238  }
239
240  if (!ui_has(kUIMultigrid)) {
241    int above_ch = wp->w_config.zindex < kZIndexMessages ? (int)p_ch : 0;
242    wp->w_height = MIN(wp->w_height, Rows - win_border_height(wp) - above_ch);
243    wp->w_width = MIN(wp->w_width, Columns - win_border_width(wp));
244  }
245
246  win_set_inner_size(wp, true);
247  set_must_redraw(UPD_VALID);
248  wp->w_redr_status = wp->w_status_height;
249  wp->w_pos_changed = true;
250  if (change_external || change_border) {
251    wp->w_hl_needs_update = true;
252    redraw_later(wp, UPD_NOT_VALID);
253  }
254
255  // compute initial position
256  if (wp->w_config.relative == kFloatRelativeWindow) {
257    int row = (int)wp->w_config.row;
258    int col = (int)wp->w_config.col;
259    Error dummy = ERROR_INIT;
260    win_T *parent = find_window_by_handle(wp->w_config.window, &dummy);
261    if (parent) {
262      row += parent->w_winrow;
263      col += parent->w_wincol;
264      grid_adjust(&parent->w_grid, &row, &col);
265      if (wp->w_config.bufpos.lnum >= 0) {
266        pos_T pos = { MIN(wp->w_config.bufpos.lnum + 1, parent->w_buffer->b_ml.ml_line_count),
267                      wp->w_config.bufpos.col, 0 };
268        int trow, tcol, tcolc, tcole;
269        textpos2screenpos(parent, &pos, &trow, &tcol, &tcolc, &tcole, true);
270        row += trow - 1;
271        col += tcol - 1;
272      }
273    }
274    api_clear_error(&dummy);
275    wp->w_winrow = row;
276    wp->w_wincol = col;
277  } else {
278    wp->w_winrow = (int)fconfig.row;
279    wp->w_wincol = (int)fconfig.col;
280  }
281
282  // changing border style while keeping border only requires redrawing border
283  if (fconfig.border) {
284    wp->w_redr_border = true;
285    redraw_later(wp, UPD_VALID);
286  }
287}
288
289static int float_zindex_cmp(const void *a, const void *b)
290{
291  int za = (*(win_T **)a)->w_config.zindex;
292  int zb = (*(win_T **)b)->w_config.zindex;
293  return za == zb ? 0 : za < zb ? 1 : -1;
294}
295
296void win_float_remove(bool bang, int count)
297{
298  kvec_t(win_T *) float_win_arr = KV_INITIAL_VALUE;
299  for (win_T *wp = lastwin; wp && wp->w_floating; wp = wp->w_prev) {
300    if (wp->w_config.hide || wp->w_p_wp) {
301      continue;
302    }
303    kv_push(float_win_arr, wp);
304  }
305  if (float_win_arr.size > 0) {
306    qsort(float_win_arr.items, float_win_arr.size, sizeof(win_T *), float_zindex_cmp);
307  }
308  for (size_t i = 0; i < float_win_arr.size; i++) {
309    win_T *wp = float_win_arr.items[i];
310    if (win_valid(wp) && win_close(wp, false, false) == FAIL) {
311      break;
312    }
313    if (!bang) {
314      count--;
315      if (count == 0) {
316        break;
317      }
318    }
319  }
320  kv_destroy(float_win_arr);
321}
322
323void win_check_anchored_floats(win_T *win)
324{
325  for (win_T *wp = lastwin; wp && wp->w_floating; wp = wp->w_prev) {
326    // float might be anchored to moved window
327    if (wp->w_config.relative == kFloatRelativeWindow
328        && wp->w_config.window == win->handle) {
329      wp->w_pos_changed = true;
330    }
331  }
332}
333
334void win_float_update_statusline(void)
335{
336  for (win_T *wp = lastwin; wp && wp->w_floating; wp = wp->w_prev) {
337    bool has_status = wp->w_status_height > 0;
338    bool should_show = *wp->w_p_stl != NUL && (p_ls == 1 || p_ls == 2);
339    if (should_show != has_status) {
340      win_config_float(wp, wp->w_config);
341    }
342  }
343}
344
345void win_float_anchor_laststatus(void)
346{
347  FOR_ALL_WINDOWS_IN_TAB(win, curtab) {
348    if (win->w_config.relative == kFloatRelativeLaststatus) {
349      win->w_pos_changed = true;
350    }
351  }
352}
353
354void win_reconfig_floats(void)
355{
356  for (win_T *wp = lastwin; wp && wp->w_floating; wp = wp->w_prev) {
357    win_config_float(wp, wp->w_config);
358  }
359}
360
361/// Return true if "win" is floating window in the current tab page.
362///
363/// @param  win  window to check
364bool win_float_valid(const win_T *win)
365  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
366{
367  if (win == NULL) {
368    return false;
369  }
370
371  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
372    if (wp == win) {
373      return wp->w_floating;
374    }
375  }
376  return false;
377}
378
379/// Find the floating window of the given kind in the current tabpage.
380///
381/// @param kind  the window kind to match
382///
383/// @return  the matching window, or NULL
384win_T *win_float_find(WinKind kind)
385  FUNC_ATTR_WARN_UNUSED_RESULT
386{
387  for (win_T *wp = lastwin; wp && wp->w_floating; wp = wp->w_prev) {
388    if (wp->w_kind == kind) {
389      return wp;
390    }
391  }
392  return NULL;
393}
394
395/// Select an alternative window to `win` (assumed floating) in tabpage `tp`.
396///
397/// Useful for finding a window to switch to if `win` is the current window, but is then closed or
398/// moved to a different tabpage.
399///
400/// @param  tp  `win`'s original tabpage, or NULL for current.
401win_T *win_float_find_altwin(const win_T *win, const tabpage_T *tp)
402  FUNC_ATTR_NONNULL_ARG(1)
403{
404  win_T *wp = prevwin;
405  if (tp == NULL) {
406    return (win_valid(wp) && wp != win && wp->w_config.focusable
407            && !wp->w_config.hide) ? wp : firstwin;
408  }
409
410  assert(tp != curtab);
411  wp = tabpage_win_valid(tp, tp->tp_prevwin) ? tp->tp_prevwin : tp->tp_firstwin;
412  return (wp != win && wp->w_config.focusable && !wp->w_config.hide) ? wp : tp->tp_firstwin;
413}
414
415/// Abort win_float_special(): emit any error, tear down the half-built window, unblock autocmds.
416static inline win_T *win_float_special_fail(win_T *wp, Error *err)
417{
418  if (ERROR_SET(err)) {
419    emsg(err->msg);
420    api_clear_error(err);
421  }
422  if (wp) {
423    win_remove(wp, NULL);
424    win_free(wp, NULL);
425  }
426  unblock_autocmds();
427  return NULL;
428}
429
430/// Snapshot a 'previewpopup' preview's anchor: the current cursor's screen cell.
431/// Call before the preview win is "entered" (then it becomes `curwin`).
432void win_float_anchor_preview(win_T *wp)
433  FUNC_ATTR_NONNULL_ALL
434{
435  wp->w_wantline = curwin->w_winrow + curwin->w_wrow;
436  wp->w_wantcol = curwin->w_wincol + curwin->w_wcol;
437}
438
439/// Creates a special floatwin: a 'previewpopup' preview or a pum-info popup.
440///
441/// @param enter    Enter the new window.
442/// @param new_buf  Give the window a new scratch buffer.
443/// @param kind     kWinPreview or kWinInfo.
444win_T *win_float_special(bool enter, bool new_buf, WinKind kind)
445{
446  WinConfig config = WIN_CONFIG_INIT;
447  config.col = curwin->w_wcol;
448  config.row = curwin->w_wrow;
449  config.relative = kFloatRelativeEditor;
450  config.focusable = false;
451  config.mouse = true;
452  config.anchor = 0;  // NW
453  config.noautocmd = true;
454  config.hide = true;
455  config.style = kWinStyleMinimal;
456  Error err = ERROR_INIT;
457  bool preview = kind == kWinPreview;
458  if (preview && !win_previewpopup_config(p_pvp, &config)) {
459    emsg(_(e_invarg));
460    return NULL;
461  }
462
463  block_autocmds();
464  win_T *wp = win_new_float(NULL, false, config, &err);
465  if (!wp) {
466    return win_float_special_fail(wp, &err);
467  }
468
469  if (new_buf) {
470    Buffer b = nvim_create_buf(false, true, &err);
471    if (!b) {
472      return win_float_special_fail(wp, &err);
473    }
474    buf_T *buf = find_buffer_by_handle(b, &err);
475    if (!buf) {
476      return win_float_special_fail(wp, &err);
477    }
478    buf->b_p_bl = false;  // unlist
479    set_option_direct_for(kOptBufhidden, STATIC_CSTR_AS_OBJ("wipe"), OPT_LOCAL, 0,
480                          kOptScopeBuf, buf);
481    win_set_buf(wp, buf, &err);
482    if (ERROR_SET(&err)) {
483      return win_float_special_fail(wp, &err);
484    }
485  }
486  unblock_autocmds();
487  wp->w_p_diff = false;
488  wp->w_p_wrap = true;  // 'wrap' is default on
489  wp->w_p_so = 0;       // 'scrolloff' zero
490
491  if (preview) {
492    wp->w_p_pvw = true;
493    RESET_BINDING(wp);
494    win_float_anchor_preview(wp);
495  }
496  wp->w_kind = kind;
497
498  if (enter) {
499    win_enter(wp, false);
500  }
501  return wp;
502}
503
504/// Closes a specified floating window used for previews or popups.
505/// Searches for and closes a floating window based on given criteria.
506///
507/// @param kind floating window preview kind.
508void win_float_close(WinKind kind)
509{
510  win_T *wp = win_float_find(kind);
511  if (wp) {
512    win_close(wp, false, false);
513  }
514}
515
516/// Re-layout a 'previewpopup' window for its current content: title, size, and anchored position.
517/// No-op if `wp` is not a floating 'previewwindow'.
518void win_float_update_preview(win_T *wp)
519  FUNC_ATTR_NONNULL_ALL
520{
521  if (wp->w_kind != kWinPreview || !wp->w_floating || !wp->w_buffer) {
522    return;
523  }
524
525  // Title is the previewed file's name, only known once it is loaded.
526  if (wp->w_config.border && wp->w_buffer->b_fname != NULL) {
527    char dirname[MAXPATHL];
528    os_dirname(dirname, MAXPATHL);
529    shorten_buf_fname(wp->w_buffer, dirname, false);
530
531    clear_virttext(&wp->w_config.title_chunks);
532    Error err = ERROR_INIT;
533    parse_bordertext(CSTR_AS_OBJ(wp->w_buffer->b_fname), kBorderTextTitle, &wp->w_config, &err);
534    api_clear_error(&err);
535    wp->w_config.title_pos = kAlignCenter;
536  }
537
538  int border_h = win_border_height(wp);
539  int border_w = win_border_width(wp);
540  int row = MIN(MAX(wp->w_wantline, 0), Rows - 1);
541  int col = MIN(MAX(wp->w_wantcol, 0), Columns - 1);
542
543  OptKeyDict_pvp *v = opt_keyset(p_pvp, kOptPreviewpopup, NULL);
544  int want_w = HAS_KEY(v, pvp, width) ? (int)v->width : 0;
545  int want_h = HAS_KEY(v, pvp, height) ? (int)v->height : 0;
546
547  // If a dimension is not given in 'previewpopup', autosize to the content.
548  linenr_T last = wp->w_buffer->b_ml.ml_line_count;
549  if (want_w == 0) {
550    want_w = MAX(win_max_displaywidth(wp, 1, last, Columns), 1);
551  }
552  want_w = MIN(want_w, Columns);
553
554  if (want_h == 0) {
555    int saved_view_width = wp->w_view_width;
556    wp->w_view_width = want_w;
557    want_h = MAX(plines_m_win(wp, 1, last, Rows), 1);
558    wp->w_view_width = saved_view_width;
559  }
560  want_h = MIN(want_h, Rows);
561
562  int need_h = want_h + border_h;
563  int need_w = want_w + border_w;
564  int space_below = Rows - row - 1 - (int)p_ch;
565  int space_above = row - 1;
566  int space_right = Columns - col - 1;
567  int space_left = col;
568  // Prefer below/right; flip only if this side can't fit but the other can.
569  bool below = space_below >= need_h || space_above < need_h;
570  bool right = space_right >= need_w || space_left < need_w;
571  int max_height = (below ? space_below : space_above) - border_h;
572  int max_width = (right ? space_right : space_left) - border_w;
573
574  wp->w_config.height = MAX(1, MIN(want_h, max_height));
575  wp->w_config.width = MAX(1, MIN(want_w, max_width));
576  wp->w_config.anchor = (below ? 0 : kFloatAnchorSouth) | (right ? 0 : kFloatAnchorEast);
577  wp->w_config.row = row + (below ? 1 : 0);
578  wp->w_config.col = col + (right ? 1 : 0);
579  wp->w_config.hide = false;
580  win_config_float(wp, wp->w_config);
581}
582
583/// Applies a 'previewpopup' value ("height:N,width:N,border:style") to `config`.
584///
585/// @return false on an invalid value; caller emits E474.
586bool win_previewpopup_config(const char *value, WinConfig *config)
587  FUNC_ATTR_NONNULL_ALL
588{
589  OptKeyDict_pvp *v = opt_keyset(value, kOptPreviewpopup, NULL);
590
591  if ((HAS_KEY(v, pvp, height) && v->height < 1) || (HAS_KEY(v, pvp, width) && v->width < 1)) {
592    return false;
593  }
594  config->height = HAS_KEY(v, pvp, height) ? (int)v->height : 0;
595  config->width = HAS_KEY(v, pvp, width) ? (int)v->width : 0;
596
597  // Use 'previewpopup' border if set, else fallback to 'winborder'.
598  char *border = NULL;
599  if (HAS_KEY(v, pvp, border)) {
600    border = v->border;
601  } else if (*p_winborder != NUL) {
602    border = p_winborder;
603  }
604  if (border != NULL) {
605    Error err = ERROR_INIT;
606    bool ok = parse_winborder(config, border, &err);
607    api_clear_error(&err);
608    if (!ok) {
609      return false;
610    }
611  }
612
613  if (!config->border) {
614    config->title = false;
615  }
616  return true;
617}