robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
52.8 KiB1693 linesraw
1/// @file popupmenu.c
2///
3/// Popup menu (PUM)
4
5#include <assert.h>
6#include <stdbool.h>
7#include <stdint.h>
8#include <string.h>
9
10#include "nvim/api/buffer.h"
11#include "nvim/api/private/defs.h"
12#include "nvim/api/private/helpers.h"
13#include "nvim/api/vim.h"
14#include "nvim/api/win_config.h"
15#include "nvim/ascii_defs.h"
16#include "nvim/autocmd.h"
17#include "nvim/buffer.h"
18#include "nvim/buffer_defs.h"
19#include "nvim/charset.h"
20#include "nvim/cmdexpand.h"
21#include "nvim/decoration.h"
22#include "nvim/drawscreen.h"
23#include "nvim/errors.h"
24#include "nvim/eval/typval.h"
25#include "nvim/ex_cmds.h"
26#include "nvim/ex_cmds_defs.h"
27#include "nvim/fuzzy.h"
28#include "nvim/garray.h"
29#include "nvim/garray_defs.h"
30#include "nvim/gettext_defs.h"
31#include "nvim/globals.h"
32#include "nvim/grid.h"
33#include "nvim/grid_defs.h"
34#include "nvim/highlight.h"
35#include "nvim/highlight_defs.h"
36#include "nvim/highlight_group.h"
37#include "nvim/input.h"
38#include "nvim/insexpand.h"
39#include "nvim/keycodes.h"
40#include "nvim/mbyte.h"
41#include "nvim/memory.h"
42#include "nvim/memory_defs.h"
43#include "nvim/menu.h"
44#include "nvim/message.h"
45#include "nvim/mouse.h"
46#include "nvim/move.h"
47#include "nvim/option.h"
48#include "nvim/option_defs.h"
49#include "nvim/option_vars.h"
50#include "nvim/plines.h"
51#include "nvim/popupmenu.h"
52#include "nvim/pos_defs.h"
53#include "nvim/state_defs.h"
54#include "nvim/strings.h"
55#include "nvim/syntax.h"
56#include "nvim/types_defs.h"
57#include "nvim/ui.h"
58#include "nvim/ui_compositor.h"
59#include "nvim/ui_defs.h"
60#include "nvim/vim_defs.h"
61#include "nvim/window.h"
62#include "nvim/winfloat.h"
63
64static pumitem_T *pum_array = NULL;  // items of displayed pum
65static int pum_size;                // nr of items in "pum_array"
66static int pum_selected;            // index of selected item or -1
67static int pum_first = 0;           // index of top item
68
69static int pum_height;              // nr of displayed pum items
70static int pum_width;               // width of displayed pum items
71static int pum_base_width;          // width of pum items base
72static int pum_kind_width;          // width of pum items kind column
73static int pum_extra_width;         // width of extra stuff
74static int pum_scrollbar;           // one when scrollbar present, else zero
75static bool pum_rl;                 // true when popupmenu is drawn 'rightleft'
76
77static int pum_anchor_grid;         // grid where position is defined
78static int pum_row;                 // top row of pum
79static int pum_col;                 // left column of pum, right column if 'rightleft'
80static int pum_win_row_offset;      // The row offset needed to convert to window relative coordinates
81static int pum_win_col_offset;      // The column offset needed to convert to window relative coordinates
82static int pum_left_col;            // left column of pum, before padding or scrollbar
83static int pum_right_col;           // right column of pum, after padding or scrollbar
84static bool pum_above;              // pum is drawn above cursor line
85
86static bool pum_is_visible = false;
87static bool pum_is_drawn = false;
88static bool pum_external = false;
89static bool pum_invalid = false;  // the screen was just cleared
90
91#include "popupmenu.c.generated.h"
92#define PUM_DEF_HEIGHT 10
93
94static void pum_compute_size(void)
95{
96  // Compute the width of the widest match and the widest extra.
97  pum_base_width = 0;
98  pum_kind_width = 0;
99  pum_extra_width = 0;
100  for (int i = 0; i < pum_size; i++) {
101    if (pum_array[i].pum_text != NULL) {
102      int w = vim_strsize(pum_array[i].pum_text);
103      if (pum_base_width < w) {
104        pum_base_width = w;
105      }
106    }
107    if (pum_array[i].pum_kind != NULL) {
108      int w = vim_strsize(pum_array[i].pum_kind) + 1;
109      if (pum_kind_width < w) {
110        pum_kind_width = w;
111      }
112    }
113    if (pum_array[i].pum_extra != NULL) {
114      int w = vim_strsize(pum_array[i].pum_extra) + 1;
115      if (pum_extra_width < w) {
116        pum_extra_width = w;
117      }
118    }
119  }
120}
121
122/// Calculate vertical placement for popup menu.
123/// Sets pum_row and pum_height based on available space.
124static void pum_compute_vertical_placement(int size, win_T *target_win, int pum_win_row,
125                                           int above_row, int below_row, int pum_border_size)
126{
127  int context_lines;
128
129  // Figure out the size and position of the pum.
130  pum_height = MIN(size, PUM_DEF_HEIGHT);
131  if (p_ph > 0 && pum_height > p_ph) {
132    pum_height = (int)p_ph;
133  }
134
135  // Put the pum below "pum_win_row" if possible.
136  // If there are few lines decide on where there is more room.
137  if (pum_win_row + 2 + pum_border_size >= below_row - pum_height
138      && pum_win_row - above_row > (below_row - above_row) / 2) {
139    // pum above "pum_win_row"
140    pum_above = true;
141
142    if ((State & MODE_CMDLINE) && target_win == NULL) {
143      // For cmdline pum, no need for context lines unless target_win is set
144      context_lines = 0;
145    } else {
146      // Leave two lines of context if possible
147      context_lines = MIN(2, target_win->w_wrow - target_win->w_cline_row);
148    }
149
150    if (pum_win_row >= size + context_lines) {
151      pum_row = pum_win_row - size - context_lines;
152      pum_height = size;
153    } else {
154      pum_row = 0;
155      pum_height = pum_win_row - context_lines;
156    }
157    if (p_ph > 0 && pum_height > p_ph) {
158      pum_row += pum_height - (int)p_ph;
159      pum_height = (int)p_ph;
160    }
161
162    if (pum_border_size > 0 && pum_border_size + pum_row + pum_height >= pum_win_row) {
163      if (pum_row < 2) {
164        pum_height -= pum_border_size;
165      } else {
166        pum_row -= pum_border_size;
167      }
168    }
169  } else {
170    // pum below "pum_win_row"
171    pum_above = false;
172
173    if ((State & MODE_CMDLINE) && target_win == NULL) {
174      // for cmdline pum, no need for context lines unless target_win is set
175      context_lines = 0;
176    } else {
177      // Leave three lines of context if possible
178      validate_cheight(target_win);
179      int cline_visible_offset = target_win->w_cline_row +
180                                 target_win->w_cline_height - target_win->w_wrow;
181      context_lines = MIN(3, cline_visible_offset);
182    }
183
184    pum_row = pum_win_row + context_lines;
185    pum_height = MIN(below_row - pum_row, size);
186    if (p_ph > 0 && pum_height > p_ph) {
187      pum_height = (int)p_ph;
188    }
189
190    if (pum_row + pum_height + pum_border_size >= cmdline_row) {
191      pum_height -= pum_border_size;
192    }
193  }
194
195  // If there is a preview window above avoid drawing over it.
196  if (above_row > 0 && pum_row < above_row && pum_height > above_row) {
197    pum_row = above_row;
198    pum_height = pum_win_row - above_row;
199  }
200}
201
202/// Try to set "pum_width" so that it fits within available_width.
203/// Returns true if pum_width was successfully set, FALSE otherwise.
204static bool set_pum_width_aligned_with_cursor(int width, int available_width)
205{
206  bool end_padding = true;
207
208  if (width < p_pw) {
209    width = (int)p_pw;
210    end_padding = false;
211  }
212  if (p_pmw > 0 && width > p_pmw) {
213    width = (int)p_pmw;
214    end_padding = false;
215  }
216
217  pum_width = width + (end_padding && width >= p_pw ? 1 : 0);
218  return available_width >= pum_width;
219}
220
221/// Calculate horizontal placement for popup menu. Sets pum_col and pum_width
222/// based on cursor position and available space.
223static void pum_compute_horizontal_placement(win_T *target_win, int cursor_col, int border_width)
224{
225  int max_col = MAX(Columns, target_win ? (target_win->w_wincol + target_win->w_view_width) : 0);
226  int desired_width = pum_base_width + pum_kind_width + pum_extra_width;
227  int available_width;
228
229  if (pum_rl) {
230    available_width = cursor_col - pum_scrollbar + 1 - border_width;
231  } else {
232    available_width = max_col - cursor_col - pum_scrollbar - border_width;
233  }
234
235  // Align pum with "cursor_col"
236  pum_col = cursor_col;
237  if (set_pum_width_aligned_with_cursor(desired_width, available_width)) {
238    return;
239  }
240
241  // Show the pum truncated, provided it is at least as wide as 'pum_width'
242  if (available_width > p_pw) {
243    pum_width = available_width;
244    return;
245  }
246
247  // Truncated pum is no longer aligned with "cursor_col"
248  if (pum_rl) {
249    available_width = max_col - pum_scrollbar - border_width;
250  } else {
251    available_width += cursor_col;
252  }
253
254  if (available_width > p_pw) {
255    pum_width = (int)p_pw + 1;  // Truncate beyond 'pum_width'
256    if (pum_rl) {
257      pum_col = pum_width + pum_scrollbar + border_width;
258    } else {
259      pum_col = max_col - pum_width - pum_scrollbar - border_width;
260    }
261    return;
262  }
263
264  // Not enough room anywhere, use what we have
265  if (pum_rl) {
266    pum_col = max_col - 1;
267  } else {
268    pum_col = 0;
269  }
270  pum_width = max_col - pum_scrollbar - border_width;
271}
272
273static inline int pum_border_width(void)
274{
275  if (*p_pumborder == NUL || strequal(p_pumborder, opt_winborder_values[7])) {
276    return 0;  // No border
277  }
278  // Shadow (1) only has right+bottom, others (2) have full border
279  return strequal(p_pumborder, opt_winborder_values[3]) ? 1 : 2;
280}
281
282/// Show the popup menu with items "array[size]".
283/// "array" must remain valid until pum_undisplay() is called!
284/// When possible the leftmost character is aligned with cursor column.
285/// The menu appears above the screen line "row" or at "row" + "height" - 1.
286///
287/// @param array
288/// @param size
289/// @param selected index of initially selected item, -1 if out of range
290/// @param array_changed if true, array contains different items since last call
291///                      if false, a new item is selected, but the array
292///                      is the same
293/// @param cmd_startcol only for cmdline mode: column of completed match
294void pum_display(pumitem_T *array, int size, int selected, bool array_changed, int cmd_startcol)
295{
296  int redo_count = 0;
297  int pum_win_row;
298  int cursor_col;
299
300  if (!pum_is_visible) {
301    // To keep the code simple, we only allow changing the
302    // draw mode when the popup menu is not being displayed
303    pum_external = ui_has(kUIPopupmenu)
304                   || ((State & MODE_CMDLINE) && ui_has(kUIWildmenu));
305  }
306
307  pum_rl = (State & MODE_CMDLINE) == 0 && curwin->w_p_rl;
308
309  int border_width = pum_border_width();
310  do {
311    // Mark the pum as visible already here,
312    // to avoid that must_redraw is set when 'cursorcolumn' is on.
313    pum_is_visible = true;
314    pum_is_drawn = true;
315    validate_cursor_col(curwin);
316    int above_row = 0;
317    int below_row = MAX(cmdline_row, curwin->w_winrow + curwin->w_view_height);
318    if (State & MODE_CMDLINE) {
319      below_row = cmdline_row;
320    }
321    win_T *target_win = (State & MODE_CMDLINE) ? cmdline_win : curwin;
322    pum_win_row_offset = 0;
323    pum_win_col_offset = 0;
324
325    // wildoptions=pum
326    if (State & MODE_CMDLINE) {
327      pum_win_row = cmdline_win ? cmdline_win->w_wrow : ui_has(kUICmdline) ? 0 : cmdline_row;
328      cursor_col = (cmdline_win ? cmdline_win->w_config._cmdline_offset : 0) + cmd_startcol;
329      cursor_col %= cmdline_win ? cmdline_win->w_view_width : Columns;
330      pum_anchor_grid = ui_has(kUICmdline) ? -1 : DEFAULT_GRID_HANDLE;
331    } else {
332      // anchor position: the start of the completed word
333      pum_win_row = curwin->w_wrow;
334      int wcol = curwin->w_wcol;
335      // w_wcol does not account for text concealed before the cursor;
336      // shift by the offset win_line() recorded for the cursor line so the
337      // menu lines up with the visible text.
338      if (curwin->w_p_cole > 0 && conceal_cursor_line(curwin)) {
339        wcol -= curwin->w_wcol_conceal_off;
340        if (wcol < 0) {
341          wcol = 0;
342        }
343      }
344      if (pum_rl) {
345        cursor_col = curwin->w_view_width - wcol - 1;
346      } else {
347        cursor_col = wcol;
348      }
349    }
350
351    if (target_win != NULL) {
352      // ext_popupmenu should always anchor to the default grid when multigrid is disabled
353      pum_anchor_grid = target_win->w_grid.target->handle;
354      pum_win_row += target_win->w_grid.row_offset;
355      cursor_col += target_win->w_grid.col_offset;
356      if (target_win->w_grid.target != &default_grid) {
357        pum_win_row += target_win->w_winrow;
358        cursor_col += target_win->w_wincol;
359        if (!ui_has(kUIMultigrid)) {
360          pum_anchor_grid = DEFAULT_GRID_HANDLE;
361        } else {
362          pum_win_row_offset = target_win->w_winrow;
363          pum_win_col_offset = target_win->w_wincol;
364        }
365      }
366    }
367
368    if (pum_external) {
369      if (array_changed) {
370        Arena arena = ARENA_EMPTY;
371        Array arr = arena_array(&arena, (size_t)size);
372        for (int i = 0; i < size; i++) {
373          Array item = arena_array(&arena, 4);
374          ADD_C(item, CSTR_AS_OBJ(array[i].pum_text));
375          ADD_C(item, CSTR_AS_OBJ(array[i].pum_kind));
376          ADD_C(item, CSTR_AS_OBJ(array[i].pum_extra));
377          ADD_C(item, CSTR_AS_OBJ(array[i].pum_info));
378          ADD_C(arr, ARRAY_OBJ(item));
379        }
380        ui_call_popupmenu_show(arr, selected, pum_win_row - pum_win_row_offset,
381                               cursor_col - pum_win_col_offset,
382                               pum_anchor_grid);
383        arena_mem_free(arena_finish(&arena));
384      } else {
385        ui_call_popupmenu_select(selected);
386        return;
387      }
388    }
389
390    win_T *pvwin = NULL;
391    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
392      if (wp->w_p_pvw) {
393        pvwin = wp;
394        break;
395      }
396    }
397
398    if (pvwin != NULL) {
399      if (pvwin->w_winrow < curwin->w_winrow) {
400        above_row = pvwin->w_winrow + pvwin->w_height;
401      } else if (pvwin->w_winrow > curwin->w_winrow + curwin->w_height) {
402        below_row = pvwin->w_winrow;
403      }
404    }
405
406    // Figure out the vertical size and position of the pum.
407    pum_compute_vertical_placement(size, target_win, pum_win_row, above_row, below_row,
408                                   border_width);
409
410    // don't display when we only have room for one line
411    if (border_width == 0 && (pum_height < 1 || (pum_height == 1 && size > 1))) {
412      return;
413    }
414
415    pum_array = array;
416    // Set "pum_size" before returning so that pum_set_event_info() gets the correct size.
417    pum_size = size;
418
419    if (pum_external) {
420      return;
421    }
422
423    pum_compute_size();
424
425    // if there are more items than room we need a scrollbar
426    pum_scrollbar = (pum_height < size) ? 1 : 0;
427
428    // Figure out the horizontal size and position of the pum.
429    pum_compute_horizontal_placement(target_win, cursor_col, border_width);
430
431    // Set selected item and redraw.  If the window size changed need to redo
432    // the positioning.  Limit this to two times, when there is not much
433    // room the window size will keep changing.
434  } while (pum_set_selected(selected, redo_count) && ++redo_count <= 2);
435
436  pum_grid.zindex = (State & MODE_CMDLINE) ? kZIndexCmdlinePopupMenu : kZIndexPopupMenu;
437  pum_redraw();
438}
439
440/// Computes attributes of text on the popup menu.
441/// Returns attributes for every cell, or NULL if all attributes are the same.
442static int *pum_compute_text_attrs(char *text, hlf_T hlf, int user_hlattr)
443{
444  if (*text == NUL || (hlf != HLF_PSI && hlf != HLF_PNI)
445      || (win_hl_attr(curwin, HLF_PMSI) == win_hl_attr(curwin, HLF_PSI)
446          && win_hl_attr(curwin, HLF_PMNI) == win_hl_attr(curwin, HLF_PNI))) {
447    return NULL;
448  }
449
450  char *leader = (State & MODE_CMDLINE) ? cmdline_compl_pattern()
451                                        : ins_compl_leader();
452  if (leader == NULL || *leader == NUL) {
453    return NULL;
454  }
455
456  int *attrs = xmalloc(sizeof(int) * (size_t)vim_strsize(text));
457  bool in_fuzzy = (State & MODE_CMDLINE) ? cmdline_compl_is_fuzzy()
458                                         : (get_cot_flags() & kOptCotFlagFuzzy) != 0;
459  size_t leader_len = strlen(leader);
460
461  garray_T *ga = NULL;
462  int matched_len = -1;
463
464  if (in_fuzzy) {
465    ga = fuzzy_match_str_with_pos(text, leader);
466    if (!ga) {
467      xfree(attrs);
468      return NULL;
469    }
470  }
471
472  const char *ptr = text;
473  int cell_idx = 0;
474  uint32_t char_pos = 0;
475  bool is_select = hlf == HLF_PSI;
476
477  while (*ptr != NUL) {
478    int new_attr = win_hl_attr(curwin, (int)hlf);
479
480    if (ga != NULL) {
481      // Handle fuzzy matching
482      for (int i = 0; i < ga->ga_len; i++) {
483        if (char_pos == ((uint32_t *)ga->ga_data)[i]) {
484          new_attr = win_hl_attr(curwin, is_select ? HLF_PMSI : HLF_PMNI);
485          new_attr = hl_combine_attr(win_hl_attr(curwin, HLF_PMNI), new_attr);
486          new_attr = hl_combine_attr(win_hl_attr(curwin, (int)hlf), new_attr);
487          break;
488        }
489      }
490    } else {
491      if (matched_len < 0 && mb_strnicmp(ptr, leader, leader_len) == 0) {
492        matched_len = (int)leader_len;
493      }
494      if (matched_len > 0) {
495        new_attr = win_hl_attr(curwin, is_select ? HLF_PMSI : HLF_PMNI);
496        new_attr = hl_combine_attr(win_hl_attr(curwin, HLF_PMNI), new_attr);
497        new_attr = hl_combine_attr(win_hl_attr(curwin, (int)hlf), new_attr);
498        matched_len--;
499      }
500    }
501
502    new_attr = hl_combine_attr(win_hl_attr(curwin, HLF_PNI), new_attr);
503
504    if (user_hlattr > 0) {
505      new_attr = hl_combine_attr(new_attr, user_hlattr);
506    }
507
508    int char_cells = utf_ptr2cells(ptr);
509    for (int i = 0; i < char_cells; i++) {
510      attrs[cell_idx + i] = new_attr;
511    }
512    cell_idx += char_cells;
513
514    MB_PTR_ADV(ptr);
515    char_pos++;
516  }
517
518  if (ga != NULL) {
519    ga_clear(ga);
520    xfree(ga);
521  }
522  return attrs;
523}
524
525/// Displays text on the popup menu with specific attributes.
526static void pum_grid_puts_with_attrs(int col, int cells, const char *text, int textlen,
527                                     const int *attrs)
528{
529  const int col_start = col;
530  const char *ptr = text;
531
532  // Render text with proper attributes
533  while (*ptr != NUL && (textlen < 0 || ptr < text + textlen)) {
534    int char_len = utfc_ptr2len(ptr);
535    int attr = attrs[pum_rl ? (col_start + cells - col - 1) : (col - col_start)];
536    grid_line_puts(col, ptr, char_len, attr);
537    col += utf_ptr2cells(ptr);
538    ptr += char_len;
539  }
540}
541
542static inline void pum_align_order(int *order)
543{
544  bool is_default = cia_flags == 0;
545  order[0] = is_default ? CPT_ABBR : cia_flags / 100;
546  order[1] = is_default ? CPT_KIND : (cia_flags / 10) % 10;
547  order[2] = is_default ? CPT_MENU : cia_flags % 10;
548}
549
550static inline char *pum_get_item(int index, int type)
551{
552  switch (type) {
553  case CPT_ABBR:
554    return pum_array[index].pum_text;
555  case CPT_KIND:
556    return pum_array[index].pum_kind;
557  case CPT_MENU:
558    return pum_array[index].pum_extra;
559  }
560  return NULL;
561}
562
563static inline int pum_user_attr_combine(int idx, int type, int attr)
564{
565  int user_attr[] = {
566    pum_array[idx].pum_user_abbr_hlattr,
567    pum_array[idx].pum_user_kind_hlattr,
568  };
569  return user_attr[type] > 0 ? hl_combine_attr(attr, user_attr[type]) : attr;
570}
571
572/// Redraw the popup menu, using "pum_first" and "pum_selected".
573void pum_redraw(void)
574{
575  int row = 0;
576  int attr_scroll = win_hl_attr(curwin, HLF_PSB);
577  int attr_thumb = win_hl_attr(curwin, HLF_PST);
578  char *p = NULL;
579  int thumb_pos = 0;
580  int thumb_height = 1;
581  int n;
582  const schar_T fcs_trunc = pum_rl ? curwin->w_p_fcs_chars.truncrl
583                                   : curwin->w_p_fcs_chars.trunc;
584
585  //                         "word"   "kind"   "extra text"
586  const hlf_T hlfsNorm[3] = { HLF_PNI, HLF_PNK, HLF_PNX };
587  const hlf_T hlfsSel[3] = { HLF_PSI, HLF_PSK, HLF_PSX };
588
589  int grid_width = pum_width;
590  int col_off = 0;
591  bool extra_space = false;
592  if (pum_rl) {
593    col_off = pum_width - 1;
594    assert(!(State & MODE_CMDLINE));
595    int win_end_col = W_ENDCOL(curwin);
596    if (pum_col < win_end_col - 1) {
597      grid_width += 1;
598      extra_space = true;
599    }
600  } else {
601    int min_col = 0;
602    if (pum_col > min_col) {
603      grid_width += 1;
604      col_off = 1;
605      extra_space = true;
606    }
607  }
608  WinConfig fconfig = WIN_CONFIG_INIT;
609  int border_width = pum_border_width();
610  int border_attr = 0;
611  schar_T border_char = 0;
612  schar_T fill_char = schar_from_ascii(' ');
613  bool has_border = border_width > 0;
614  // setup popup menu border if 'pumborder' option is set
615  if (border_width > 0) {
616    Error err = ERROR_INIT;
617    if (!parse_winborder(&fconfig, p_pumborder, &err)) {
618      if (ERROR_SET(&err)) {
619        emsg(err.msg);
620      }
621      api_clear_error(&err);
622      return;
623    }
624
625    // Shadow style: only adds border on right and bottom edges
626    if (strequal(p_pumborder, opt_winborder_values[3])) {
627      fconfig.shadow = true;
628      int blend = SYN_GROUP_STATIC("PmenuShadow");
629      int through = SYN_GROUP_STATIC("PmenuShadowThrough");
630      fconfig.border_hl_ids[2] = through;
631      fconfig.border_hl_ids[3] = blend;
632      fconfig.border_hl_ids[4] = blend;
633      fconfig.border_hl_ids[5] = blend;
634      fconfig.border_hl_ids[6] = through;
635    }
636
637    // convert border highlight IDs to attributes, use PmenuBorder as default
638    for (int i = 0; i < 8; i++) {
639      int attr = hl_attr_active[HLF_PBR];
640      if (fconfig.border_hl_ids[i]) {
641        attr = hl_get_ui_attr(-1, HLF_PBR, fconfig.border_hl_ids[i], false);
642      }
643      fconfig.border_attr[i] = attr;
644    }
645    api_clear_error(&err);
646    if (pum_scrollbar) {
647      border_char = schar_from_str(fconfig.border_chars[3]);
648      border_attr = fconfig.border_attr[3];
649    }
650  }
651
652  if (pum_scrollbar > 0 && (!fconfig.border || fconfig.shadow)) {
653    grid_width++;
654    if (pum_rl) {
655      col_off++;
656    }
657  }
658  pum_grid.blending = p_pb > 0 || fconfig.shadow;
659  grid_assign_handle(&pum_grid);
660
661  pum_left_col = pum_col - col_off;
662  pum_right_col = pum_left_col + grid_width;
663  bool moved = ui_comp_put_grid(&pum_grid, pum_row, pum_left_col,
664                                pum_height + border_width, grid_width + border_width, false,
665                                true);
666  bool invalid_grid = moved || pum_invalid;
667  pum_invalid = false;
668  must_redraw_pum = false;
669
670  if (!pum_grid.chars || pum_grid.rows != pum_height + border_width
671      || pum_grid.cols != grid_width + border_width) {
672    grid_alloc(&pum_grid, pum_height + border_width, grid_width + border_width,
673               !invalid_grid, false);
674    ui_call_grid_resize(pum_grid.handle, pum_grid.cols, pum_grid.rows);
675  } else if (invalid_grid) {
676    grid_invalidate(&pum_grid);
677  }
678  if (ui_has(kUIMultigrid)) {
679    pum_pos_ui_flush(true);
680  }
681
682  int scroll_range = pum_size - pum_height;
683  if (fconfig.border) {
684    grid_draw_border(&pum_grid, &fconfig, NULL, 0, NULL, 0);
685    if (!fconfig.shadow) {
686      row++;
687      col_off++;
688    }
689  }
690
691  // Never display more than we have
692  pum_first = MIN(pum_first, scroll_range);
693
694  if (pum_scrollbar) {
695    thumb_height = pum_height * pum_height / pum_size;
696    if (thumb_height == 0) {
697      thumb_height = 1;
698    }
699    thumb_pos = (pum_first * (pum_height - thumb_height) + scroll_range / 2) / scroll_range;
700  }
701
702  for (int i = 0; i < pum_height; i++) {
703    int idx = i + pum_first;
704    const bool selected = idx == pum_selected;
705    const hlf_T *const hlfs = selected ? hlfsSel : hlfsNorm;
706    const int trunc_attr = win_hl_attr(curwin, selected ? HLF_PSI : HLF_PNI);
707    hlf_T hlf = hlfs[0];  // start with "word" highlight
708    int attr = win_hl_attr(curwin, (int)hlf);
709    attr = hl_combine_attr(win_hl_attr(curwin, HLF_PNI), attr);
710
711    screengrid_line_start(&pum_grid, row, 0);
712
713    // prepend a space if there is room
714    if (extra_space) {
715      if (pum_rl) {
716        grid_line_puts(col_off + 1, " ", 1, attr);
717      } else {
718        grid_line_puts(col_off - 1, " ", 1, attr);
719      }
720    }
721
722    // Display each entry, use two spaces for a Tab.
723    // Do this 3 times and order from p_cia
724    int grid_col = col_off;
725    int totwidth = 0;
726    bool need_fcs_trunc = false;
727    int order[3];
728    int items_width_array[3] = { pum_base_width, pum_kind_width, pum_extra_width };
729    pum_align_order(order);
730    int basic_width = items_width_array[order[0]];  // first item width
731    bool last_isabbr = order[2] == CPT_ABBR;
732    int orig_attr = -1;
733
734    for (int j = 0; j < 3; j++) {
735      int item_type = order[j];
736      hlf = hlfs[item_type];
737      attr = win_hl_attr(curwin, (int)hlf);
738      attr = hl_combine_attr(win_hl_attr(curwin, HLF_PNI), attr);
739      orig_attr = attr;
740      if (item_type < 2) {  // try combine attr with user custom
741        attr = pum_user_attr_combine(idx, item_type, attr);
742      }
743      int width = 0;
744      char *s = NULL;
745      p = pum_get_item(idx, item_type);
746
747      const bool next_isempty = j + 1 >= 3 || pum_get_item(idx, order[j + 1]) == NULL;
748
749      if (p != NULL) {
750        for (;; MB_PTR_ADV(p)) {
751          if (s == NULL) {
752            s = p;
753          }
754          int w = ptr2cells(p);
755          if (*p != NUL && *p != TAB && totwidth + w <= pum_width) {
756            width += w;
757            continue;
758          }
759          const int width_limit = pum_width;
760
761          // Display the text that fits or comes before a Tab.
762          // First convert it to printable characters.
763          char saved = *p;
764
765          if (saved != NUL) {
766            *p = NUL;
767          }
768          char *st = transstr(s, true);
769          if (saved != NUL) {
770            *p = saved;
771          }
772
773          int *attrs = NULL;
774          if (item_type == CPT_ABBR) {
775            attrs = pum_compute_text_attrs(st, hlf,
776                                           pum_array[idx].pum_user_abbr_hlattr);
777          }
778
779          if (pum_rl) {
780            char *rt = reverse_text(st);
781            char *rt_start = rt;
782            int cells = (int)mb_string2cells(rt);
783            int pad = next_isempty ? 0 : 2;
784            if (width_limit - totwidth < cells + pad) {
785              need_fcs_trunc = true;
786            }
787
788            // only draw the text that fits
789            if (grid_col - cells < col_off - width_limit) {
790              do {
791                cells -= utf_ptr2cells(rt);
792                MB_PTR_ADV(rt);
793              } while (grid_col - cells < col_off - width_limit);
794
795              if (grid_col - cells > col_off - width_limit) {
796                // Most left character requires 2-cells but only 1 cell is available on
797                // screen.  Put a '<' on the left of the pum item.
798                *(--rt) = '<';
799                cells++;
800              }
801            }
802
803            if (attrs == NULL) {
804              grid_line_puts(grid_col - cells + 1, rt, -1, attr);
805            } else {
806              pum_grid_puts_with_attrs(grid_col - cells + 1, cells, rt, -1, attrs);
807            }
808
809            xfree(rt_start);
810            xfree(st);
811            grid_col -= width;
812          } else {
813            int cells = (int)mb_string2cells(st);
814            int pad = next_isempty ? 0 : 2;
815            if (width_limit - totwidth < cells + pad) {
816              need_fcs_trunc = true;
817            }
818            if (need_fcs_trunc) {
819              int available_cells = width_limit - totwidth;
820              // Find the truncation point by counting display cells
821              char *p_end = st;
822              int displayed = 0;
823              while (*p_end != NUL) {
824                int char_cells = utf_ptr2cells(p_end);
825                if (displayed + char_cells > available_cells) {
826                  break;
827                }
828                displayed += char_cells;
829                MB_PTR_ADV(p_end);
830              }
831              *p_end = NUL;
832              cells = displayed;
833              width = displayed;
834            }
835
836            if (attrs == NULL) {
837              grid_line_puts(grid_col, st, -1, attr);
838            } else {
839              pum_grid_puts_with_attrs(grid_col, cells, st, -1, attrs);
840            }
841
842            xfree(st);
843            grid_col += width;
844          }
845
846          if (attrs != NULL) {
847            XFREE_CLEAR(attrs);
848          }
849
850          if (*p != TAB) {
851            break;
852          }
853
854          // Display two spaces for a Tab.
855          if (pum_rl) {
856            grid_line_puts(grid_col - 1, "  ", 2, attr);
857            grid_col -= 2;
858          } else {
859            grid_line_puts(grid_col, "  ", 2, attr);
860            grid_col += 2;
861          }
862          totwidth += 2;
863          s = NULL;  // start text at next char
864          width = 0;
865        }
866      }
867
868      if (j > 0) {
869        n = items_width_array[order[1]] + (last_isabbr ? 0 : 1);
870      } else {
871        n = order[j] == CPT_ABBR ? 1 : 0;
872      }
873
874      // Stop when there is nothing more to display.
875      if ((j == 2)
876          || (next_isempty && (j == 1 || (j == 0 && pum_get_item(idx, order[j + 2]) == NULL)))
877          || (basic_width + n >= pum_width)) {
878        break;
879      }
880
881      if (pum_rl) {
882        grid_line_fill(col_off - basic_width - n + 1, grid_col + 1,
883                       schar_from_ascii(' '), orig_attr);
884        grid_col = col_off - basic_width - n;
885      } else {
886        grid_line_fill(grid_col, col_off + basic_width + n,
887                       schar_from_ascii(' '), orig_attr);
888        grid_col = col_off + basic_width + n;
889      }
890      totwidth = basic_width + n;
891    }
892
893    if (pum_rl) {
894      const int lcol = col_off - pum_width + 1;
895      grid_line_fill(lcol, grid_col + 1, schar_from_ascii(' '), orig_attr);
896      if (need_fcs_trunc) {
897        linebuf_char[lcol] = fcs_trunc != NUL ? fcs_trunc : schar_from_ascii('<');
898        linebuf_attr[lcol] = trunc_attr;
899        if (pum_width > 1 && linebuf_char[lcol + 1] == NUL) {
900          linebuf_char[lcol + 1] = schar_from_ascii(' ');
901        }
902      }
903    } else {
904      const int rcol = col_off + pum_width;
905      grid_line_fill(grid_col, rcol, schar_from_ascii(' '), orig_attr);
906      if (need_fcs_trunc) {
907        if (pum_width > 1 && linebuf_char[rcol - 1] == NUL) {
908          linebuf_char[rcol - 2] = schar_from_ascii(' ');
909        }
910        linebuf_char[rcol - 1] = fcs_trunc != NUL ? fcs_trunc : schar_from_ascii('>');
911        linebuf_attr[rcol - 1] = trunc_attr;
912      }
913    }
914
915    if (pum_scrollbar > 0) {
916      bool thumb = i >= thumb_pos && i < thumb_pos + thumb_height;
917      int scrollbar_col = col_off + (pum_rl ? -pum_width : pum_width);
918      bool use_border_style = has_border && !fconfig.shadow;
919      grid_line_put_schar(scrollbar_col,
920                          (use_border_style && !thumb) ? border_char : fill_char,
921                          thumb ? attr_thumb : (use_border_style ? border_attr : attr_scroll));
922    }
923    grid_line_flush();
924    row++;
925  }
926}
927
928/// Set the informational text in the preview buffer when the completion
929/// item does not include a dedicated preview or popup window.
930///
931/// @param[in]  win        Window containing buffer where the text will be set.
932/// @param[in]  info       Informational text to display in the preview buffer.
933/// @param[in]  lnum       Where to start the text. Incremented for each added line.
934/// @param[out] max_width  Maximum width of the displayed text.
935static void pum_preview_set_text(win_T *win, char *info, linenr_T *lnum, int *max_width)
936{
937  Error err = ERROR_INIT;
938  Arena arena = ARENA_EMPTY;
939  Array replacement = ARRAY_DICT_INIT;
940  buf_T *buf = win->w_buffer;
941  buf->b_p_ma = true;
942
943  // Iterate through the string line by line by temporarily replacing newlines with NUL
944  for (char *curr = info, *next; curr; curr = next ? next + 1 : NULL) {
945    if ((next = strchr(curr, '\n'))) {
946      *next = NUL;  // Temporarily replace the newline with a string terminator
947    }
948    // Only skip if this is an empty line AND it's the last line
949    if (*curr == NUL && !next) {
950      break;
951    }
952    // Temporarily disable 'wrap' to avoid 'showbreak/linebreak'
953    // inflating the result when the window is narrow.
954    bool save_wrap = win->w_p_wrap;
955    win->w_p_wrap = false;
956    int line_width = win_linetabsize(win, 0, curr, MAXCOL);
957    win->w_p_wrap = save_wrap;
958    *max_width = MAX(*max_width, line_width);
959    ADD(replacement, STRING_OBJ(cstr_to_string(curr)));
960    (*lnum)++;
961
962    if (next) {
963      *next = '\n';
964    }
965  }
966
967  int original_textlock = textlock;
968  textlock = 0;
969  nvim_buf_set_lines(0, buf->handle, 0, -1, false, replacement, &arena, &err);
970  textlock = original_textlock;
971  if (ERROR_SET(&err)) {
972    emsg(err.msg);
973    api_clear_error(&err);
974  }
975  arena_mem_free(arena_finish(&arena));
976  api_free_array(replacement);
977  buf->b_p_ma = false;
978}
979
980/// adjust floating info preview window position
981static bool pum_adjust_info_position(win_T *wp, int width)
982{
983  int border_width = pum_border_width();
984  int col = pum_col + pum_width + 1 + MAX(border_width, pum_scrollbar);
985  // TODO(glepnir): support config align border by using completepopup
986  // align menu
987  int right_extra = Columns - col;
988  int left_extra = pum_col - 2;
989
990  int max_extra = MAX(right_extra, left_extra);
991  // Close info window if there's insufficient space
992  // TODO(glepnir): Replace the hardcoded value (10) with values from the 'completepopup' width/height options.
993  if (max_extra < 10) {
994    wp->w_config.hide = true;
995    return false;
996  }
997
998  if (right_extra > width) {  // place in right
999    wp->w_config.width = width;
1000    wp->w_config.col = col - 1;
1001  } else if (left_extra > width) {  // place in left
1002    wp->w_config.width = width;
1003    wp->w_config.col = pum_col - wp->w_config.width - 1;
1004  } else {  // either width is enough just use the biggest one.
1005    const bool place_in_right = right_extra > left_extra;
1006    wp->w_config.width = max_extra;
1007    wp->w_config.col = place_in_right ? col - 1 : pum_col - wp->w_config.width - 1;
1008  }
1009  wp->w_config.anchor = 0;  // NW: align top of info window with top of pum
1010  linenr_T count = wp->w_buffer->b_ml.ml_line_count;
1011  wp->w_view_width = wp->w_config.width;
1012  wp->w_config.height = plines_m_win(wp, wp->w_topline, count, Rows);
1013  wp->w_config.row = pum_row;
1014  wp->w_config.hide = false;
1015  win_config_float(wp, wp->w_config);
1016  return true;
1017}
1018
1019/// Used for nvim__complete_set
1020///
1021/// @param selected the selected compl item.
1022/// @param info     Info string.
1023/// @return a win_T pointer.
1024win_T *pum_set_info(int selected, char *info)
1025{
1026  if (!pum_is_visible || !compl_match_curr_select(selected)) {
1027    return NULL;
1028  }
1029  block_autocmds();
1030  RedrawingDisabled++;
1031  no_u_sync++;
1032  win_T *wp = win_float_find(kWinInfo);
1033  if (wp == NULL) {
1034    wp = win_float_special(false, true, kWinInfo);
1035    if (!wp) {
1036      return NULL;
1037    }
1038    wp->w_topline = 1;
1039    wp->w_p_wfb = true;
1040  }
1041  linenr_T lnum = 0;
1042  int max_info_width = 0;
1043  pum_preview_set_text(wp, info, &lnum, &max_info_width);
1044  no_u_sync--;
1045  RedrawingDisabled--;
1046  redraw_later(wp, UPD_NOT_VALID);
1047
1048  if (!pum_adjust_info_position(wp, max_info_width)) {
1049    wp = NULL;
1050  }
1051  unblock_autocmds();
1052  return wp;
1053}
1054
1055/// Set the index of the currently selected item.  The menu will scroll when
1056/// necessary.  When "n" is out of range don't scroll.
1057/// This may be repeated when the preview window is used:
1058/// "repeat" == 0: open preview window normally
1059/// "repeat" == 1: open preview window but don't set the size
1060/// "repeat" == 2: don't open preview window
1061///
1062/// @param n
1063/// @param repeat
1064///
1065/// @returns true when the window was resized and the location of the popup
1066/// menu must be recomputed.
1067static bool pum_set_selected(int n, int repeat)
1068{
1069  bool resized = false;
1070  int context = pum_height / 2;
1071  int prev_selected = pum_selected;
1072
1073  pum_selected = n;
1074  int scroll_offset = pum_selected - pum_height;
1075  unsigned cur_cot_flags = get_cot_flags();
1076  bool use_float = (cur_cot_flags & kOptCotFlagPopup) != 0;
1077
1078  // Close the floating preview window if 'selected' is -1, indicating a return to the original
1079  // state. It is also closed when the selected item has no corresponding info item.
1080  if (use_float && (pum_selected < 0 || pum_array[pum_selected].pum_info == NULL)) {
1081    win_T *wp = win_float_find(kWinInfo);
1082    if (wp) {
1083      wp->w_config.hide = true;
1084      win_config_float(wp, wp->w_config);
1085    }
1086  }
1087
1088  if ((pum_selected >= 0) && (pum_selected < pum_size)) {
1089    if (pum_first > pum_selected - 4) {
1090      // scroll down; when we did a jump it's probably a PageUp then
1091      // scroll a whole page
1092      if (pum_first > pum_selected - 2) {
1093        pum_first -= pum_height - 2;
1094        if (pum_first < 0) {
1095          pum_first = 0;
1096        } else if (pum_first > pum_selected) {
1097          pum_first = pum_selected;
1098        }
1099      } else {
1100        pum_first = pum_selected;
1101      }
1102    } else if (pum_first < scroll_offset + 5) {
1103      // scroll up; when we did a jump it's probably a PageDown then
1104      // scroll a whole page
1105      if (pum_first < scroll_offset + 3) {
1106        pum_first = MAX(pum_first + pum_height - 2, scroll_offset + 1);
1107      } else {
1108        pum_first = scroll_offset + 1;
1109      }
1110    }
1111
1112    // Give a few lines of context when possible.
1113    context = MIN(context, 3);
1114
1115    if (pum_height > 2) {
1116      if (pum_first > pum_selected - context) {
1117        pum_first = MAX(pum_selected - context, 0);  // scroll down
1118      } else if (pum_first < pum_selected + context - pum_height + 1) {
1119        pum_first = pum_selected + context - pum_height + 1;  // up
1120      }
1121    }
1122    // adjust for the number of lines displayed
1123    pum_first = MIN(pum_first, pum_size - pum_height);
1124
1125    // Show extra info in the preview window if there is something and
1126    // 'completeopt' contains "preview" or "popup".
1127    // Skip this when tried twice already.
1128    // Skip this also when there is not much room.
1129    // Skip this for command-window when 'completeopt' contains "preview".
1130    // NOTE: Be very careful not to sync undo!
1131    if ((pum_array[pum_selected].pum_info != NULL)
1132        && (Rows > 10)
1133        && (repeat <= 1)
1134        && (cur_cot_flags & (kOptCotFlagPreview | kOptCotFlagPopup))
1135        && !((cur_cot_flags & kOptCotFlagPreview) && cmdwin_buf != NULL)) {
1136      win_T *curwin_save = curwin;
1137      tabpage_T *curtab_save = curtab;
1138
1139      if (use_float) {
1140        block_autocmds();
1141      }
1142
1143      // Open a preview window.  3 lines by default.  Prefer
1144      // 'previewheight' if set and smaller.
1145      g_do_tagpreview = 3;
1146
1147      if ((p_pvh > 0) && (p_pvh < g_do_tagpreview)) {
1148        g_do_tagpreview = (int)p_pvh;
1149      }
1150      RedrawingDisabled++;
1151      // Prevent undo sync here, if an autocommand syncs undo weird
1152      // things can happen to the undo tree.
1153      no_u_sync++;
1154
1155      if (!use_float) {
1156        resized = prepare_tagpreview(false, false);
1157      } else {
1158        win_T *wp = win_float_find(kWinInfo);
1159        if (wp) {
1160          win_enter(wp, false);
1161        } else {
1162          wp = win_float_special(true, true, kWinInfo);
1163          if (wp) {
1164            resized = true;
1165          }
1166        }
1167      }
1168
1169      no_u_sync--;
1170      RedrawingDisabled--;
1171      g_do_tagpreview = 0;
1172
1173      if (curwin->w_p_pvw || curwin->w_kind == kWinInfo) {
1174        int res = OK;
1175        if (!resized
1176            && (curbuf->b_nwindows == 1)
1177            && (curbuf->b_fname == NULL)
1178            && bt_nofile(curbuf)
1179            && (curbuf->b_p_bh[0] == 'w')) {
1180          // Already a "wipeout" buffer, make it empty.
1181          buf_clear();
1182        } else {
1183          // Don't want to sync undo in the current buffer.
1184          no_u_sync++;
1185          res = do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, 0, NULL);
1186          no_u_sync--;
1187
1188          if (res == OK) {
1189            // Edit a new, empty buffer. Set options for a "wipeout"
1190            // buffer.
1191            set_option_value_give_err(kOptSwapfile, BOOLEAN_OBJ(false), OPT_LOCAL);
1192            set_option_value_give_err(kOptBuflisted, BOOLEAN_OBJ(false), OPT_LOCAL);
1193            set_option_value_give_err(kOptBuftype, STATIC_CSTR_AS_OBJ("nofile"), OPT_LOCAL);
1194            set_option_value_give_err(kOptBufhidden, STATIC_CSTR_AS_OBJ("wipe"), OPT_LOCAL);
1195            set_option_value_give_err(kOptDiff, BOOLEAN_OBJ(false), OPT_LOCAL);
1196          }
1197        }
1198
1199        if (res == OK) {
1200          linenr_T lnum = 0;
1201          int max_info_width = 0;
1202          pum_preview_set_text(curwin, pum_array[pum_selected].pum_info, &lnum, &max_info_width);
1203          // Increase the height of the preview window to show the
1204          // text, but no more than 'previewheight' lines.
1205          if (repeat == 0 && !use_float) {
1206            lnum = MIN(lnum, (linenr_T)p_pvh);
1207
1208            if (curwin->w_height < lnum) {
1209              win_setheight((int)lnum);
1210              resized = true;
1211            }
1212          }
1213
1214          curbuf->b_changed = false;
1215          curbuf->b_p_ma = false;
1216          if (pum_selected != prev_selected) {
1217            curwin->w_topline = 1;
1218          } else if (curwin->w_topline > curbuf->b_ml.ml_line_count) {
1219            curwin->w_topline = curbuf->b_ml.ml_line_count;
1220          }
1221          curwin->w_cursor.lnum = 1;
1222          curwin->w_cursor.col = 0;
1223
1224          if (use_float) {
1225            // adjust floating window by actually height and max info text width
1226            if (!pum_adjust_info_position(curwin, max_info_width) && win_valid(curwin_save)) {
1227              win_enter(curwin_save, false);
1228            }
1229          }
1230
1231          if ((curwin != curwin_save && win_valid(curwin_save))
1232              || (curtab != curtab_save && valid_tabpage(curtab_save))) {
1233            if (curtab != curtab_save && valid_tabpage(curtab_save)) {
1234              goto_tabpage_tp(curtab_save, false, false);
1235            }
1236
1237            // When the first completion is done and the preview
1238            // window is not resized, skip the preview window's
1239            // status line redrawing.
1240            if (ins_compl_active() && !resized) {
1241              curwin->w_redr_status = false;
1242            }
1243
1244            // Return cursor to where we were
1245            validate_cursor(curwin);
1246            redraw_later(curwin, UPD_SOME_VALID);
1247
1248            // When the preview window was resized we need to
1249            // update the view on the buffer.  Only go back to
1250            // the window when needed, otherwise it will always be
1251            // redrawn.
1252            if (resized && win_valid(curwin_save)) {
1253              no_u_sync++;
1254              win_enter(curwin_save, true);
1255              no_u_sync--;
1256              update_topline(curwin);
1257            }
1258
1259            const bool save_pum_is_drawn = pum_is_drawn;
1260
1261            // Update the screen before drawing the popup menu.
1262            // Enable updating the status lines.
1263            // TODO(bfredl): can simplify, get rid of the flag munging?
1264            // or at least eliminate extra redraw before win_enter()?
1265            pum_is_visible = false;
1266            pum_is_drawn = false;
1267            update_screen();
1268            pum_is_visible = true;
1269            pum_is_drawn = save_pum_is_drawn;
1270
1271            if (!resized && win_valid(curwin_save)) {
1272              no_u_sync++;
1273              win_enter(curwin_save, true);
1274              no_u_sync--;
1275            }
1276
1277            // May need to update the screen again when there are
1278            // autocommands involved.
1279            pum_is_visible = false;
1280            pum_is_drawn = false;
1281            update_screen();
1282            pum_is_visible = true;
1283            pum_is_drawn = save_pum_is_drawn;
1284          }
1285        }
1286      }
1287
1288      if (use_float) {
1289        unblock_autocmds();
1290      }
1291    }
1292  }
1293
1294  return resized;
1295}
1296
1297/// Undisplay the popup menu (later).
1298void pum_undisplay(bool immediate)
1299{
1300  pum_is_visible = false;
1301  pum_array = NULL;
1302  must_redraw_pum = false;
1303
1304  if (immediate) {
1305    pum_check_clear();
1306  }
1307}
1308
1309void pum_check_clear(void)
1310{
1311  if (!pum_is_visible && pum_is_drawn) {
1312    if (pum_external) {
1313      ui_call_popupmenu_hide();
1314    } else {
1315      ui_comp_remove_grid(&pum_grid);
1316      if (ui_has(kUIMultigrid)) {
1317        ui_call_win_close(pum_grid.handle);
1318        ui_call_grid_destroy(pum_grid.handle);
1319      }
1320      // TODO(bfredl): consider keeping float grids allocated.
1321      grid_free(&pum_grid);
1322    }
1323    pum_is_drawn = false;
1324    pum_external = false;
1325    win_float_close(kWinInfo);
1326  }
1327}
1328
1329/// Clear the popup menu.  Currently only resets the offset to the first
1330/// displayed item.
1331void pum_clear(void)
1332{
1333  pum_first = 0;
1334}
1335
1336/// @return true if the popup menu is displayed.
1337bool pum_visible(void)
1338{
1339  return pum_is_visible;
1340}
1341
1342/// @return true if the popup menu is displayed and drawn on the grid.
1343bool pum_drawn(void)
1344{
1345  return pum_visible() && !pum_external;
1346}
1347
1348/// Screen was cleared, need to redraw next time
1349void pum_invalidate(void)
1350{
1351  pum_invalid = true;
1352}
1353
1354void pum_recompose(void)
1355{
1356  ui_comp_compose_grid(&pum_grid);
1357}
1358
1359void pum_ext_select_item(int item, bool insert, bool finish)
1360{
1361  if (!pum_visible() || item < -1 || item >= pum_size) {
1362    return;
1363  }
1364  pum_want.active = true;
1365  pum_want.item = item;
1366  pum_want.insert = insert;
1367  pum_want.finish = finish;
1368}
1369
1370/// Gets the height of the menu.
1371///
1372/// @return the height of the popup menu, the number of entries visible.
1373/// Only valid when pum_visible() returns true!
1374int pum_get_height(void)
1375{
1376  if (pum_external) {
1377    int ui_pum_height = ui_pum_get_height();
1378    if (ui_pum_height) {
1379      return ui_pum_height;
1380    }
1381  }
1382  return pum_height;
1383}
1384
1385/// Add size information about the pum to "dict".
1386void pum_set_event_info(dict_T *dict)
1387{
1388  if (!pum_visible()) {
1389    return;
1390  }
1391  double w, h, r, c;
1392  if (!ui_pum_get_pos(&w, &h, &r, &c)) {
1393    w = (double)pum_width;
1394    h = (double)pum_height;
1395    r = (double)pum_row;
1396    c = (double)pum_col;
1397  }
1398  tv_dict_add_float(dict, S_LEN("height"), h);
1399  tv_dict_add_float(dict, S_LEN("width"), w);
1400  tv_dict_add_float(dict, S_LEN("row"), r);
1401  tv_dict_add_float(dict, S_LEN("col"), c);
1402  tv_dict_add_nr(dict, S_LEN("size"), pum_size);
1403  tv_dict_add_bool(dict, S_LEN("scrollbar"),
1404                   pum_scrollbar ? kBoolVarTrue : kBoolVarFalse);
1405}
1406
1407static void pum_position_at_mouse(int min_width)
1408{
1409  int min_row = 0;
1410  int min_col = 0;
1411  int max_row = Rows;
1412  int max_col = Columns;
1413  int grid = mouse_grid;
1414  int row = mouse_row;
1415  int col = mouse_col;
1416  pum_win_row_offset = 0;
1417  pum_win_col_offset = 0;
1418
1419  if (ui_has(kUIMultigrid) && grid == 0) {
1420    mouse_find_win_outer(&grid, &row, &col);
1421  }
1422  if (grid > 1) {
1423    win_T *wp = get_win_by_grid_handle(grid);
1424    if (wp != NULL) {
1425      row += wp->w_winrow;
1426      col += wp->w_wincol;
1427      pum_win_row_offset = wp->w_winrow;
1428      pum_win_col_offset = wp->w_wincol;
1429
1430      if (wp->w_view_height > 0 || wp->w_view_width > 0) {
1431        // When the user has requested a different grid size, let the popupmenu extend to the size
1432        // of it.
1433        max_row = MAX(Rows - wp->w_winrow, wp->w_winrow + wp->w_view_height);
1434        max_col = MAX(Columns - wp->w_wincol, wp->w_wincol + wp->w_view_width);
1435      }
1436    }
1437  }
1438  if (pum_grid.handle != 0 && grid == pum_grid.handle) {
1439    // Repositioning the menu by right-clicking on itself
1440    row += pum_row;
1441    col += pum_left_col;
1442  } else {
1443    pum_anchor_grid = grid;
1444  }
1445
1446  // Both width and height are 1 for shadow border, otherwise 2
1447  int border_width = pum_border_width();
1448  int border_height = border_width;
1449  if (max_row - row > pum_size + border_height || max_row - row > row - min_row) {
1450    // Enough space below the mouse row,
1451    // or there is more space below the mouse row than above.
1452    pum_above = false;
1453    pum_row = row + 1;
1454    if (pum_height + border_height > max_row - pum_row) {
1455      pum_height = max_row - pum_row - border_height;
1456    }
1457  } else {
1458    // Show above the mouse row, reduce height if it does not fit.
1459    pum_above = true;
1460    pum_row = row - pum_size - border_height;
1461    if (pum_row < min_row) {
1462      pum_height += pum_row - min_row;
1463      pum_row = min_row;
1464    }
1465  }
1466
1467  if (pum_rl) {
1468    if (col - min_col + 1 >= pum_base_width + border_width
1469        || col - min_col + 1 > min_width + border_width) {
1470      // Enough space to show at mouse column.
1471      pum_col = col;
1472    } else {
1473      // Not enough space, left align with window.
1474      pum_col = min_col + MIN(pum_base_width + border_width, min_width + border_width) - 1;
1475    }
1476    pum_width = pum_col - min_col + 1 - border_width;
1477  } else {
1478    if (max_col - col >= pum_base_width + border_width
1479        || max_col - col > min_width + border_width) {
1480      // Enough space to show at mouse column.
1481      pum_col = col;
1482    } else {
1483      // Not enough space, right align with window.
1484      pum_col = max_col - MIN(pum_base_width + border_width, min_width + border_width);
1485    }
1486    pum_width = max_col - pum_col - border_width;
1487  }
1488
1489  pum_width = MIN(pum_width, pum_base_width + 1);
1490}
1491
1492/// Select the pum entry at the mouse position.
1493static void pum_select_mouse_pos(void)
1494{
1495  int grid = mouse_grid;
1496  int row = mouse_row;
1497  int col = mouse_col;
1498
1499  if (grid == 0) {
1500    mouse_find_win_outer(&grid, &row, &col);
1501  }
1502
1503  if (grid == pum_grid.handle) {
1504    // Offset by 1 when border width is 2 (non-shadow border)
1505    int border_offset = pum_border_width() == 2 ? 1 : 0;
1506    int item = row - border_offset;
1507    pum_selected = (item >= 0 && item < pum_height) ? item : -1;
1508    return;
1509  }
1510
1511  if (grid != pum_anchor_grid
1512      || col < pum_left_col - pum_win_col_offset
1513      || col >= pum_right_col - pum_win_col_offset) {
1514    pum_selected = -1;
1515    return;
1516  }
1517
1518  int idx = row - (pum_row - pum_win_row_offset);
1519
1520  if (idx < 0 || idx >= pum_height) {
1521    pum_selected = -1;
1522  } else if (*pum_array[idx].pum_text != NUL) {
1523    pum_selected = idx;
1524  }
1525}
1526
1527/// Execute the currently selected popup menu item.
1528static void pum_execute_menu(vimmenu_T *menu, int mode)
1529{
1530  int idx = 0;
1531  exarg_T ea;
1532
1533  for (vimmenu_T *mp = menu->children; mp != NULL; mp = mp->next) {
1534    if ((mp->modes & mp->enabled & mode) && idx++ == pum_selected) {
1535      CLEAR_FIELD(ea);
1536      execute_menu(&ea, mp, -1);
1537      break;
1538    }
1539  }
1540}
1541
1542/// Open the terminal version of the popup menu and don't return until it is closed.
1543void pum_show_popupmenu(vimmenu_T *menu)
1544{
1545  pum_undisplay(true);
1546  pum_size = 0;
1547  int mode = get_menu_mode_flag();
1548
1549  for (vimmenu_T *mp = menu->children; mp != NULL; mp = mp->next) {
1550    if (menu_is_separator(mp->dname) || (mp->modes & mp->enabled & mode)) {
1551      pum_size++;
1552    }
1553  }
1554
1555  // When there are only Terminal mode menus, using "popup Edit" results in
1556  // pum_size being zero.
1557  if (pum_size <= 0) {
1558    emsg(_(e_menu_only_exists_in_another_mode));
1559    return;
1560  }
1561
1562  int idx = 0;
1563  pumitem_T *array = (pumitem_T *)xcalloc((size_t)pum_size, sizeof(pumitem_T));
1564
1565  for (vimmenu_T *mp = menu->children; mp != NULL; mp = mp->next) {
1566    char *s = NULL;
1567    // Make a copy of the text, the menu may be redefined in a callback.
1568    if (menu_is_separator(mp->dname)) {
1569      s = "";
1570    } else if (mp->modes & mp->enabled & mode) {
1571      s = mp->dname;
1572    }
1573    if (s != NULL) {
1574      s = xstrdup(s);
1575      array[idx++].pum_text = s;
1576    }
1577  }
1578
1579  pum_array = array;
1580  pum_compute_size();
1581  pum_scrollbar = 0;
1582  pum_height = pum_size;
1583  pum_rl = curwin->w_p_rl;
1584  pum_position_at_mouse(20);
1585
1586  pum_selected = -1;
1587  pum_first = 0;
1588  if (!p_mousemev) {
1589    // Pretend 'mousemoveevent' is set.
1590    ui_call_option_set(STATIC_CSTR_AS_STRING("mousemoveevent"), BOOLEAN_OBJ(true));
1591  }
1592
1593  while (true) {
1594    pum_is_visible = true;
1595    pum_is_drawn = true;
1596    pum_grid.zindex = kZIndexCmdlinePopupMenu;  // show above cmdline area #23275
1597    pum_redraw();
1598    setcursor_mayforce(curwin, true);
1599
1600    int c = vgetc();
1601
1602    // Bail out when typing Esc, CTRL-C or some callback or <expr> mapping
1603    // closed the popup menu.
1604    if (c == ESC || c == Ctrl_C || pum_array == NULL) {
1605      break;
1606    } else if (c == CAR || c == NL) {
1607      // enter: select current item, if any, and close
1608      pum_execute_menu(menu, mode);
1609      break;
1610    } else if (c == 'k' || c == K_UP || c == K_MOUSEUP) {
1611      // cursor up: select previous item
1612      while (pum_selected > 0) {
1613        pum_selected--;
1614        if (*array[pum_selected].pum_text != NUL) {
1615          break;
1616        }
1617      }
1618    } else if (c == 'j' || c == K_DOWN || c == K_MOUSEDOWN) {
1619      // cursor down: select next item
1620      while (pum_selected < pum_size - 1) {
1621        pum_selected++;
1622        if (*array[pum_selected].pum_text != NUL) {
1623          break;
1624        }
1625      }
1626    } else if (c == K_RIGHTMOUSE) {
1627      // Right mouse down: reposition the menu.
1628      vungetc(c);
1629      break;
1630    } else if (c == K_LEFTDRAG || c == K_RIGHTDRAG || c == K_MOUSEMOVE) {
1631      // mouse moved: select item in the mouse row
1632      pum_select_mouse_pos();
1633    } else if (c == K_LEFTMOUSE || c == K_LEFTMOUSE_NM || c == K_RIGHTRELEASE) {
1634      // left mouse click: select clicked item, if any, and close;
1635      // right mouse release: select clicked item, close if any
1636      pum_select_mouse_pos();
1637      if (pum_selected >= 0) {
1638        pum_execute_menu(menu, mode);
1639        break;
1640      }
1641      if (c == K_LEFTMOUSE || c == K_LEFTMOUSE_NM) {
1642        break;
1643      }
1644    }
1645  }
1646
1647  for (idx = 0; idx < pum_size; idx++) {
1648    xfree(array[idx].pum_text);
1649  }
1650  xfree(array);
1651  pum_undisplay(true);
1652  if (!p_mousemev) {
1653    ui_call_option_set(STATIC_CSTR_AS_STRING("mousemoveevent"), BOOLEAN_OBJ(false));
1654  }
1655}
1656
1657void pum_make_popup(const char *path_name, int use_mouse_pos)
1658{
1659  if (!use_mouse_pos) {
1660    // Hack: set mouse position at the cursor so that the menu pops up
1661    // around there.
1662    mouse_row = curwin->w_grid.row_offset + curwin->w_wrow;
1663    mouse_col = curwin->w_grid.col_offset
1664                + (curwin->w_p_rl ? curwin->w_view_width - curwin->w_wcol - 1
1665                                  : curwin->w_wcol);
1666    if (ui_has(kUIMultigrid)) {
1667      mouse_grid = curwin->w_grid.target->handle;
1668    } else if (curwin->w_grid.target != &default_grid) {
1669      mouse_grid = 0;
1670      mouse_row += curwin->w_winrow;
1671      mouse_col += curwin->w_wincol;
1672    }
1673  }
1674
1675  vimmenu_T *menu = menu_find(path_name);
1676  if (menu != NULL) {
1677    pum_show_popupmenu(menu);
1678  }
1679}
1680
1681void pum_pos_ui_flush(bool force)
1682{
1683  if (force || (ui_has(kUIMultigrid) && pum_is_drawn && !pum_external
1684                && pum_grid.handle != 0 && pum_grid.pending_comp_index_update)) {
1685    const char *anchor = pum_above ? "SW" : "NW";
1686    int row_off = pum_above ? -pum_height : 0;
1687    ui_call_win_float_pos(pum_grid.handle, -1, cstr_as_string(anchor), pum_anchor_grid,
1688                          pum_row - row_off - pum_win_row_offset, pum_left_col - pum_win_col_offset,
1689                          false, pum_grid.zindex, (int)pum_grid.comp_index, pum_grid.comp_row,
1690                          pum_grid.comp_col);
1691    pum_grid.pending_comp_index_update = false;
1692  }
1693}