robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
130.4 KiB4482 linesraw
1// cmdexpand.c: functions for command-line completion
2
3#include <assert.h>
4#include <stdbool.h>
5#include <stdint.h>
6#include <stdio.h>
7#include <stdlib.h>
8#include <string.h>
9#include <uv.h>
10
11#include "nvim/api/private/defs.h"
12#include "nvim/api/private/helpers.h"
13#include "nvim/arglist.h"
14#include "nvim/ascii_defs.h"
15#include "nvim/autocmd.h"
16#include "nvim/buffer.h"
17#include "nvim/buffer_defs.h"
18#include "nvim/charset.h"
19#include "nvim/cmdexpand.h"
20#include "nvim/cmdhist.h"
21#include "nvim/drawscreen.h"
22#include "nvim/errors.h"
23#include "nvim/eval.h"
24#include "nvim/eval/funcs.h"
25#include "nvim/eval/typval.h"
26#include "nvim/eval/typval_defs.h"
27#include "nvim/eval/userfunc.h"
28#include "nvim/eval/vars.h"
29#include "nvim/ex_cmds.h"
30#include "nvim/ex_cmds_defs.h"
31#include "nvim/ex_docmd.h"
32#include "nvim/ex_getln.h"
33#include "nvim/fuzzy.h"
34#include "nvim/garray.h"
35#include "nvim/garray_defs.h"
36#include "nvim/gettext_defs.h"
37#include "nvim/globals.h"
38#include "nvim/grid.h"
39#include "nvim/hashtab.h"
40#include "nvim/hashtab_defs.h"
41#include "nvim/help.h"
42#include "nvim/highlight.h"
43#include "nvim/highlight_defs.h"
44#include "nvim/highlight_group.h"
45#include "nvim/input.h"
46#include "nvim/insexpand.h"
47#include "nvim/keycodes.h"
48#include "nvim/lua/executor.h"
49#include "nvim/macros_defs.h"
50#include "nvim/mapping.h"
51#include "nvim/mbyte.h"
52#include "nvim/mbyte_defs.h"
53#include "nvim/memline.h"
54#include "nvim/memory.h"
55#include "nvim/menu.h"
56#include "nvim/message.h"
57#include "nvim/option.h"
58#include "nvim/option_vars.h"
59#include "nvim/os/fs.h"
60#include "nvim/os/lang.h"
61#include "nvim/os/os.h"
62#include "nvim/os/os_defs.h"
63#include "nvim/path.h"
64#include "nvim/popupmenu.h"
65#include "nvim/profile.h"
66#include "nvim/regexp.h"
67#include "nvim/runtime.h"
68#include "nvim/runtime_defs.h"
69#include "nvim/search.h"
70#include "nvim/sign.h"
71#include "nvim/statusline.h"
72#include "nvim/strings.h"
73#include "nvim/syntax.h"
74#include "nvim/tag.h"
75#include "nvim/types_defs.h"
76#include "nvim/ui.h"
77#include "nvim/ui_defs.h"
78#include "nvim/usercmd.h"
79#include "nvim/vim_defs.h"
80#include "nvim/window.h"
81
82/// Type used by call_user_expand_func
83typedef void *(*user_expand_func_T)(const char *, int, typval_T *);
84
85#include "cmdexpand.c.generated.h"
86
87static bool cmd_showtail;  ///< Only show path tail in lists ?
88static bool may_expand_pattern = false;
89static pos_T pre_incsearch_pos;  ///< Cursor position when incsearch started
90
91/// "compl_match_array" points the currently displayed list of entries in the
92/// popup menu.  It is NULL when there is no popup menu.
93static pumitem_T *compl_match_array = NULL;
94static int compl_match_arraysize;
95/// First column in cmdline of the matched item for completion.
96static int compl_startcol;
97static int compl_selected;
98/// cmdline before expansion
99static String cmdline_orig = STRING_INIT;
100
101#define SHOW_MATCH(m) (showtail ? showmatches_gettail(matches[m], false) : matches[m])
102
103/// Returns true if fuzzy completion is supported for a given cmdline completion
104/// context.
105static bool cmdline_fuzzy_completion_supported(const expand_T *const xp)
106  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
107{
108  switch (xp->xp_context) {
109  case EXPAND_BOOL_SETTINGS:
110  case EXPAND_COLORS:
111  case EXPAND_COMPILER:
112  case EXPAND_DIRECTORIES:
113  case EXPAND_DIRS_IN_CDPATH:
114  case EXPAND_FILES:
115  case EXPAND_FILES_IN_PATH:
116  case EXPAND_FILETYPE:
117  case EXPAND_FILETYPECMD:
118  case EXPAND_FINDFUNC:
119  case EXPAND_HELP:
120  case EXPAND_KEYMAP:
121  case EXPAND_LUA:
122  case EXPAND_OLD_SETTING:
123  case EXPAND_STRING_SETTING:
124  case EXPAND_SETTING_SUBTRACT:
125  case EXPAND_OWNSYNTAX:
126  case EXPAND_PACKADD:
127  case EXPAND_RUNTIME:
128  case EXPAND_SHELLCMD:
129  case EXPAND_SHELLCMDLINE:
130  case EXPAND_TAGS:
131  case EXPAND_TAGS_LISTFILES:
132  case EXPAND_USER_LIST:
133  case EXPAND_USER_LUA:
134    return false;
135
136  default:
137    break;
138  }
139
140  return wop_flags & kOptWopFlagFuzzy;
141}
142
143/// Returns true if fuzzy completion for cmdline completion is enabled and
144/// "fuzzystr" is not empty.  If search pattern is empty, then don't use fuzzy
145/// matching.
146bool cmdline_fuzzy_complete(const char *const fuzzystr)
147  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
148{
149  return (wop_flags & kOptWopFlagFuzzy) && *fuzzystr != NUL;
150}
151
152/// Sort function for the completion matches.
153/// <SNR> functions should be sorted to the end.
154static int sort_func_compare(const void *s1, const void *s2)
155{
156  char *p1 = *(char **)s1;
157  char *p2 = *(char **)s2;
158
159  if (*p1 != '<' && *p2 == '<') {
160    return -1;
161  }
162  if (*p1 == '<' && *p2 != '<') {
163    return 1;
164  }
165  return strcmp(p1, p2);
166}
167
168/// Escape special characters in the cmdline completion matches.
169static void wildescape(expand_T *xp, const char *str, int numfiles, char **files)
170{
171  char *p;
172  const int vse_what = xp->xp_context == EXPAND_BUFFERS ? VSE_BUFFER : VSE_NONE;
173
174  if (xp->xp_context == EXPAND_FILES
175      || xp->xp_context == EXPAND_FILES_IN_PATH
176      || xp->xp_context == EXPAND_SHELLCMD
177      || xp->xp_context == EXPAND_BUFFERS
178      || xp->xp_context == EXPAND_DIRECTORIES
179      || xp->xp_context == EXPAND_DIRS_IN_CDPATH) {
180    // Insert a backslash into a file name before a space, \, %, #
181    // and wildmatch characters, except '~'.
182    for (int i = 0; i < numfiles; i++) {
183      // for ":set path=" we need to escape spaces twice
184      if (xp->xp_backslash & XP_BS_THREE) {
185        char *pat = (xp->xp_backslash & XP_BS_COMMA) ? " ," : " ";
186        p = vim_strsave_escaped(files[i], pat);
187        xfree(files[i]);
188        files[i] = p;
189#ifdef BACKSLASH_IN_FILENAME
190        p = vim_strsave_escaped(files[i], " ");
191        xfree(files[i]);
192        files[i] = p;
193#endif
194      } else if (xp->xp_backslash & XP_BS_COMMA) {
195        if (vim_strchr(files[i], ',') != NULL) {
196          p = vim_strsave_escaped(files[i], ",");
197          xfree(files[i]);
198          files[i] = p;
199        }
200      }
201#ifdef BACKSLASH_IN_FILENAME
202      p = vim_strsave_fnameescape(files[i], vse_what);
203#else
204      p = vim_strsave_fnameescape(files[i], xp->xp_shell ? VSE_SHELL : vse_what);
205#endif
206      xfree(files[i]);
207      files[i] = p;
208
209      // If 'str' starts with "\~", replace "~" at start of
210      // files[i] with "\~".
211      if (str[0] == '\\' && str[1] == '~' && files[i][0] == '~') {
212        escape_fname(&files[i]);
213      }
214    }
215    xp->xp_backslash = XP_BS_NONE;
216
217    // If the first file starts with a '+' escape it.  Otherwise it
218    // could be seen as "+cmd".
219    if (*files[0] == '+') {
220      escape_fname(&files[0]);
221    }
222  } else if (xp->xp_context == EXPAND_TAGS) {
223    // Insert a backslash before characters in a tag name that
224    // would terminate the ":tag" command.
225    for (int i = 0; i < numfiles; i++) {
226      p = vim_strsave_escaped(files[i], "\\|\"");
227      xfree(files[i]);
228      files[i] = p;
229    }
230  }
231}
232
233/// Escape special characters in the cmdline completion matches.
234static void ExpandEscape(expand_T *xp, char *str, int numfiles, char **files, int options)
235{
236  // May change home directory back to "~"
237  if (options & WILD_HOME_REPLACE) {
238    tilde_replace(str, numfiles, files);
239  }
240
241  if (options & WILD_ESCAPE) {
242    wildescape(xp, str, numfiles, files);
243  }
244}
245
246/// Return FAIL if this is not an appropriate context in which to do
247/// completion of anything, return OK if it is (even if there are no matches).
248/// For the caller, this means that the character is just passed through like a
249/// normal character (instead of being expanded).  This allows :s/^I^D etc.
250///
251/// @param options  extra options for ExpandOne()
252/// @param escape  if true, escape the returned matches
253int nextwild(expand_T *xp, int type, int options, bool escape)
254{
255  CmdlineInfo *const ccline = get_cmdline_info();
256  char *p;
257  bool from_wildtrigger_func = options & WILD_FUNC_TRIGGER;
258  bool wild_navigate = (type == WILD_NEXT || type == WILD_PREV
259                        || type == WILD_PAGEUP || type == WILD_PAGEDOWN
260                        || type == WILD_PUM_WANT);
261
262  if (xp->xp_numfiles == -1) {
263    pre_incsearch_pos = xp->xp_pre_incsearch_pos;
264    if (ccline->input_fn && ccline->xp_context == EXPAND_COMMANDS) {
265      // Expand commands typed in input() function
266      set_cmd_context(xp, ccline->cmdbuff, ccline->cmdlen, ccline->cmdpos, false);
267    } else {
268      may_expand_pattern = options & WILD_MAY_EXPAND_PATTERN;
269      set_expand_context(xp);
270      may_expand_pattern = false;
271    }
272    if (xp->xp_context == EXPAND_LUA) {
273      nlua_expand_pat(xp);
274    }
275    cmd_showtail = expand_showtail(xp);
276  }
277
278  if (xp->xp_context == EXPAND_UNSUCCESSFUL) {
279    beep_flush();
280    return OK;      // Something illegal on command line
281  }
282  if (xp->xp_context == EXPAND_NOTHING) {
283    // Caller can use the character as a normal char instead
284    return FAIL;
285  }
286
287  int i = (int)(xp->xp_pattern - ccline->cmdbuff);
288  assert(ccline->cmdpos >= i);
289  xp->xp_pattern_len = (size_t)ccline->cmdpos - (size_t)i;
290
291  // Skip showing matches if prefix is invalid during wildtrigger()
292  if (from_wildtrigger_func && xp->xp_context == EXPAND_COMMANDS
293      && xp->xp_pattern_len == 0) {
294    return FAIL;
295  }
296
297  // If cmd_silent is set then don't show the dots, because redrawcmd() below
298  // won't remove them.
299  if (!cmd_silent && !from_wildtrigger_func && !wild_navigate
300      && !(ui_has(kUICmdline) || ui_has(kUIWildmenu))) {
301    msg_puts("...");  // show that we are busy
302    ui_flush();
303  }
304
305  if (wild_navigate) {
306    // Get next/previous match for a previous expanded pattern.
307    p = ExpandOne(xp, NULL, NULL, 0, type);
308  } else {
309    char *tmp;
310    if (cmdline_fuzzy_completion_supported(xp)
311        || xp->xp_context == EXPAND_PATTERN_IN_BUF) {
312      // Don't modify the search string
313      tmp = xstrnsave(xp->xp_pattern, xp->xp_pattern_len);
314    } else {
315      tmp = addstar(xp->xp_pattern, xp->xp_pattern_len, xp->xp_context);
316    }
317    // Translate string into pattern and expand it.
318    const int use_options = (options
319                             | WILD_USE_COMPLETESLASH
320                             | WILD_HOME_REPLACE
321                             | WILD_ADD_SLASH
322                             | WILD_SILENT
323                             | (escape ? WILD_ESCAPE : 0)
324                             | (p_wic ? WILD_ICASE : 0));
325    p = ExpandOne(xp, tmp, xstrnsave(&ccline->cmdbuff[i], xp->xp_pattern_len),
326                  use_options, type);
327    xfree(tmp);
328    // Longest match: make sure it is not shorter, happens with :help.
329    if (p != NULL && type == WILD_LONGEST) {
330      int j;
331      for (j = 0; (size_t)j < xp->xp_pattern_len; j++) {
332        char c = ccline->cmdbuff[i + j];
333        if (c == '*' || c == '?') {
334          break;
335        }
336      }
337      if ((int)strlen(p) < j) {
338        XFREE_CLEAR(p);
339      }
340    }
341  }
342
343  // Save cmdline before inserting selected item
344  if (!wild_navigate && ccline->cmdbuff != NULL) {
345    xfree(cmdline_orig.data);
346    cmdline_orig = cstrn_to_string(ccline->cmdbuff, (size_t)ccline->cmdlen);
347  }
348
349  if (p != NULL && !got_int && !(options & (WILD_NOSELECT | WILD_NOINSERT))) {
350    size_t plen = strlen(p);
351    int difflen = (int)plen - (int)(xp->xp_pattern_len);
352    if (ccline->cmdlen + difflen + 4 > ccline->cmdbufflen) {
353      realloc_cmdbuff(ccline->cmdlen + difflen + 4);
354      xp->xp_pattern = ccline->cmdbuff + i;
355    }
356    assert(ccline->cmdpos <= ccline->cmdlen);
357    memmove(&ccline->cmdbuff[ccline->cmdpos + difflen],
358            &ccline->cmdbuff[ccline->cmdpos],
359            (size_t)ccline->cmdlen - (size_t)ccline->cmdpos + 1);
360    memmove(&ccline->cmdbuff[i], p, plen);
361    ccline->cmdlen += difflen;
362    ccline->cmdpos += difflen;
363  }
364
365  redrawcmd();
366  cursorcmd();
367
368  // When expanding a ":map" command and no matches are found, assume that
369  // the key is supposed to be inserted literally
370  if (xp->xp_context == EXPAND_MAPPINGS && p == NULL) {
371    return FAIL;
372  }
373
374  if (xp->xp_numfiles <= 0 && p == NULL) {
375    beep_flush();
376  } else if (xp->xp_numfiles == 1 && !(options & (WILD_NOSELECT | WILD_NOINSERT))
377             && !wild_navigate) {
378    // free expanded pattern
379    ExpandOne(xp, NULL, NULL, 0, WILD_FREE);
380  }
381
382  xfree(p);
383
384  return OK;
385}
386
387/// Create completion popup menu with items from "matches".
388static void cmdline_pum_create(const CmdlineInfo *ccline, expand_T *xp, char **matches,
389                               int numMatches, bool showtail, bool cmdline_unchanged)
390  FUNC_ATTR_NONNULL_ARG(1, 2)
391{
392  assert(numMatches >= 0);
393  // Add all the completion matches
394  compl_match_array = xmalloc(sizeof(pumitem_T) * (size_t)numMatches);
395  compl_match_arraysize = numMatches;
396  for (int i = 0; i < numMatches; i++) {
397    compl_match_array[i] = (pumitem_T){
398      .pum_text = (xp->xp_files_abbr != NULL && xp->xp_files_abbr[i] != NULL)
399                  ? xp->xp_files_abbr[i] : SHOW_MATCH(i),
400      .pum_info = xp->xp_files_info != NULL ? xp->xp_files_info[i] : NULL,
401      .pum_extra = xp->xp_files_menu != NULL ? xp->xp_files_menu[i] : NULL,
402      .pum_kind = xp->xp_files_kind != NULL ? xp->xp_files_kind[i] : NULL,
403      .pum_user_abbr_hlattr = -1,
404      .pum_user_kind_hlattr = -1,
405    };
406  }
407
408  // Compute the popup menu starting column
409  char *endpos = showtail ? showmatches_gettail(xp->xp_pattern, cmdline_unchanged) : xp->xp_pattern;
410  if (ui_has(kUICmdline) && cmdline_win == NULL) {
411    compl_startcol = (int)(endpos - ccline->cmdbuff);
412  } else {
413    compl_startcol = cmd_screencol((int)(endpos - ccline->cmdbuff));
414  }
415}
416
417void cmdline_pum_display(bool changed_array)
418{
419  pum_display(compl_match_array, compl_match_arraysize, compl_selected,
420              changed_array, compl_startcol);
421}
422
423/// Returns true if the cmdline completion popup menu is being displayed.
424bool cmdline_pum_active(void)
425{
426  return pum_visible() && compl_match_array != NULL;
427}
428
429/// Remove the cmdline completion popup menu (if present), free the list of items.
430void cmdline_pum_remove(bool defer_redraw)
431{
432  pum_undisplay(!defer_redraw);
433  XFREE_CLEAR(compl_match_array);
434  compl_match_arraysize = 0;
435}
436
437void cmdline_pum_cleanup(CmdlineInfo *cclp)
438{
439  cmdline_pum_remove(false);
440  wildmenu_cleanup(cclp);
441}
442
443/// Returns the current cmdline completion pattern.
444char *cmdline_compl_pattern(void)
445{
446  expand_T *xp = get_cmdline_info()->xpc;
447  return xp == NULL ? NULL : xp->xp_orig;
448}
449
450/// Returns true if fuzzy cmdline completion is active, false otherwise.
451bool cmdline_compl_is_fuzzy(void)
452{
453  expand_T *xp = get_cmdline_info()->xpc;
454  return xp != NULL && cmdline_fuzzy_completion_supported(xp);
455}
456
457/// Checks whether popup menu should be used for cmdline completion wildmenu.
458///
459/// @param wildmenu  whether wildmenu is needed by current 'wildmode' part
460static bool cmdline_compl_use_pum(bool need_wildmenu)
461{
462  return ((need_wildmenu && (wop_flags & kOptWopFlagPum)
463           && !(ui_has(kUICmdline) && cmdline_win == NULL))
464          || ui_has(kUIWildmenu) || (ui_has(kUICmdline) && ui_has(kUIPopupmenu)));
465}
466
467/// Return the number of characters that should be skipped in the wildmenu
468/// These are backslashes used for escaping.  Do show backslashes in help tags
469/// and in search pattern completion matches.
470static int skip_wildmenu_char(expand_T *xp, char *s)
471{
472  if ((rem_backslash(s) && xp->xp_context != EXPAND_HELP
473       && xp->xp_context != EXPAND_PATTERN_IN_BUF)
474      || ((xp->xp_context == EXPAND_MENUS || xp->xp_context == EXPAND_MENUNAMES)
475          && (s[0] == '\t' || (s[0] == '\\' && s[1] != NUL)))) {
476#ifndef BACKSLASH_IN_FILENAME
477    // TODO(bfredl): Why in the actual fuck are we special casing the
478    // shell variety deep in the redraw logic? Shell special snowflakiness
479    // should already be eliminated multiple layers before reaching the
480    // screen infracstructure.
481    if (xp->xp_shell && csh_like_shell() && s[1] == '\\' && s[2] == '!') {
482      return 2;
483    }
484#endif
485    return 1;
486  }
487  return 0;
488}
489
490/// Get the length of an item as it will be shown in the status line.
491static int wildmenu_match_len(expand_T *xp, char *s)
492{
493  int len = 0;
494
495  int emenu = (xp->xp_context == EXPAND_MENUS
496               || xp->xp_context == EXPAND_MENUNAMES);
497
498  // Check for menu separators - replace with '|'.
499  if (emenu && menu_is_separator(s)) {
500    return 1;
501  }
502
503  while (*s != NUL) {
504    s += skip_wildmenu_char(xp, s);
505    len += ptr2cells(s);
506    MB_PTR_ADV(s);
507  }
508
509  return len;
510}
511
512/// Show wildchar matches in the status line.
513/// Show at least the "match" item.
514/// We start at item "first_match" in the list and show all matches that fit.
515///
516/// If inversion is possible we use it. Else '=' characters are used.
517///
518/// @param matches  list of matches
519static void redraw_wildmenu(expand_T *xp, int num_matches, char **matches, int match, bool showtail)
520{
521  bool highlight = true;
522  char *selstart = NULL;
523  int selstart_col = 0;
524  char *selend = NULL;
525  static int first_match = 0;
526  bool add_left = false;
527  int i, l;
528
529  if (matches == NULL) {        // interrupted completion?
530    return;
531  }
532
533  char *buf = xmalloc((size_t)Columns * MB_MAXBYTES + 1);
534
535  if (match == -1) {    // don't show match but original text
536    match = 0;
537    highlight = false;
538  }
539  // count 1 for the ending ">"
540  int clen = wildmenu_match_len(xp, SHOW_MATCH(match)) + 3;  // length in screen cells
541  if (match == 0) {
542    first_match = 0;
543  } else if (match < first_match) {
544    // jumping left, as far as we can go
545    first_match = match;
546    add_left = true;
547  } else {
548    // check if match fits on the screen
549    for (i = first_match; i < match; i++) {
550      clen += wildmenu_match_len(xp, SHOW_MATCH(i)) + 2;
551    }
552    if (first_match > 0) {
553      clen += 2;
554    }
555    // jumping right, put match at the left
556    if (clen > Columns) {
557      first_match = match;
558      // if showing the last match, we can add some on the left
559      clen = 2;
560      for (i = match; i < num_matches; i++) {
561        clen += wildmenu_match_len(xp, SHOW_MATCH(i)) + 2;
562        if (clen >= Columns) {
563          break;
564        }
565      }
566      if (i == num_matches) {
567        add_left = true;
568      }
569    }
570  }
571  if (add_left) {
572    while (first_match > 0) {
573      clen += wildmenu_match_len(xp, SHOW_MATCH(first_match - 1)) + 2;
574      if (clen >= Columns) {
575        break;
576      }
577      first_match--;
578    }
579  }
580
581  int len;
582  hlf_T group;
583  schar_T fillchar = fillchar_status(&group, curwin);
584  int attr = win_hl_attr(curwin, (int)group);
585
586  if (first_match == 0) {
587    *buf = NUL;
588    len = 0;
589  } else {
590    STRCPY(buf, "< ");
591    len = 2;
592  }
593  clen = len;
594
595  i = first_match;
596  while (clen + wildmenu_match_len(xp, SHOW_MATCH(i)) + 2 < Columns) {
597    if (i == match) {
598      selstart = buf + len;
599      selstart_col = clen;
600    }
601
602    char *s = SHOW_MATCH(i);
603    // Check for menu separators - replace with '|'
604    int emenu = (xp->xp_context == EXPAND_MENUS || xp->xp_context == EXPAND_MENUNAMES);
605    if (emenu && menu_is_separator(s)) {
606      STRCPY(buf + len, transchar('|'));
607      l = (int)strlen(buf + len);
608      len += l;
609      clen += l;
610    } else {
611      for (; *s != NUL; s++) {
612        s += skip_wildmenu_char(xp, s);
613        clen += ptr2cells(s);
614        if ((l = utfc_ptr2len(s)) > 1) {
615          strncpy(buf + len, s, (size_t)l);  // NOLINT(runtime/printf)
616          s += l - 1;
617          len += l;
618        } else {
619          STRCPY(buf + len, transchar_byte((uint8_t)(*s)));
620          len += (int)strlen(buf + len);
621        }
622      }
623    }
624    if (i == match) {
625      selend = buf + len;
626    }
627
628    *(buf + len++) = ' ';
629    *(buf + len++) = ' ';
630    clen += 2;
631    if (++i == num_matches) {
632      break;
633    }
634  }
635
636  if (i != num_matches) {
637    *(buf + len++) = '>';
638    clen++;
639  }
640
641  buf[len] = NUL;
642
643  int row = cmdline_row - 1;
644  if (row >= 0) {
645    if (wild_menu_showing == 0) {
646      if (msg_scrolled > 0) {
647        // Put the wildmenu just above the command line.  If there is
648        // no room, scroll the screen one line up.
649        if (cmdline_row == Rows - 1) {
650          msg_scroll_up(false, false);
651          msg_scrolled++;
652        } else {
653          cmdline_row++;
654          row++;
655        }
656        wild_menu_showing = WM_SCROLLED;
657      } else {
658        // Create status line if needed by setting 'laststatus' to 2.
659        // Set 'winminheight' to zero to avoid that the window is
660        // resized.
661        if (lastwin->w_status_height == 0 && global_stl_height() == 0) {
662          save_p_ls = (int)p_ls;
663          save_p_wmh = (int)p_wmh;
664          p_ls = 2;
665          p_wmh = 0;
666          last_status(false);
667        }
668        wild_menu_showing = WM_SHOWN;
669      }
670    }
671
672    // Tricky: wildmenu can be drawn either over a status line, or at empty
673    // scrolled space in the message output
674    grid_line_start((wild_menu_showing == WM_SCROLLED) ? &msg_grid_adj : &default_gridview, row);
675
676    grid_line_puts(0, buf, -1, attr);
677    if (selstart != NULL && highlight) {
678      *selend = NUL;
679      grid_line_puts(selstart_col, selstart, -1, HL_ATTR(HLF_WM));
680    }
681
682    grid_line_fill(clen, Columns, fillchar, attr);
683
684    grid_line_flush();
685  }
686
687  win_redraw_last_status(topframe);
688  xfree(buf);
689}
690
691/// Get the next or prev cmdline completion match. The index of the match is set
692/// in "xp->xp_selected"
693static char *get_next_or_prev_match(int mode, expand_T *xp)
694{
695  // When no matches found, return NULL
696  if (xp->xp_numfiles <= 0) {
697    return NULL;
698  }
699
700  int findex = xp->xp_selected;
701
702  if (mode == WILD_PREV) {
703    // Select the last entry if at original text
704    if (findex == -1) {
705      findex = xp->xp_numfiles;
706    }
707    // Otherwise select the previous entry
708    findex--;
709  } else if (mode == WILD_NEXT) {
710    // Select the next entry
711    findex++;
712  } else if (mode == WILD_PAGEUP || mode == WILD_PAGEDOWN) {
713    // Get the height of popup menu (used for both PAGEUP and PAGEDOWN)
714    int ht = pum_get_height();
715    if (ht > 3) {
716      ht -= 2;
717    }
718
719    if (mode == WILD_PAGEUP) {
720      if (findex == 0) {
721        // at the first entry, don't select any entries
722        findex = -1;
723      } else if (findex < 0) {
724        // no entry is selected. select the last entry
725        findex = xp->xp_numfiles - 1;
726      } else {
727        // go up by the pum height
728        findex = MAX(findex - ht, 0);
729      }
730    } else {  // mode == WILD_PAGEDOWN
731      if (findex == xp->xp_numfiles - 1) {
732        // at the last entry, don't select any entries
733        findex = -1;
734      } else if (findex < 0) {
735        // no entry is selected. select the first entry
736        findex = 0;
737      } else {
738        // go down by the pum height
739        findex = MIN(findex + ht, xp->xp_numfiles - 1);
740      }
741    }
742  } else {  // mode == WILD_PUM_WANT
743    assert(pum_want.active);
744    findex = pum_want.item;
745  }
746
747  // Handle wrapping around
748  if (findex < 0 || findex >= xp->xp_numfiles) {
749    // If original text exists, return to it when wrapping around
750    if (xp->xp_orig != NULL) {
751      findex = -1;
752    } else {
753      // Wrap around to opposite end
754      findex = (findex < 0) ? xp->xp_numfiles - 1 : 0;
755    }
756  }
757
758  // Display matches on screen
759  if (p_wmnu) {
760    if (compl_match_array) {
761      compl_selected = findex;
762      cmdline_pum_display(false);
763    } else if (cmdline_compl_use_pum(true)) {
764      cmdline_pum_create(get_cmdline_info(), xp, xp->xp_files, xp->xp_numfiles,
765                         cmd_showtail, false);
766      compl_selected = findex;
767      pum_clear();
768      cmdline_pum_display(true);
769    } else {
770      redraw_wildmenu(xp, xp->xp_numfiles, xp->xp_files, findex, cmd_showtail);
771    }
772  }
773
774  xp->xp_selected = findex;
775  // Return the original text or the selected match
776  return xstrdup(findex == -1 ? xp->xp_orig : xp->xp_files[findex]);
777}
778
779/// Start the command-line expansion and get the matches.
780static char *ExpandOne_start(int mode, expand_T *xp, char *str, int options)
781{
782  int non_suf_match;  // number without matching suffix
783  char *ss = NULL;
784
785  // Do the expansion.
786  if (ExpandFromContext(xp, str, &xp->xp_files, &xp->xp_numfiles, options) == FAIL) {
787#ifdef FNAME_ILLEGAL
788    // Illegal file name has been silently skipped.  But when there
789    // are wildcards, the real problem is that there was no match,
790    // causing the pattern to be added, which has illegal characters.
791    if (!(options & WILD_SILENT) && (options & WILD_LIST_NOTFOUND)) {
792      semsg(_(e_nomatch2), str);
793    }
794#endif
795  } else if (xp->xp_numfiles == 0) {
796    if (!(options & WILD_SILENT)) {
797      semsg(_(e_nomatch2), str);
798    }
799  } else {
800    // Escape the matches for use on the command line.
801    ExpandEscape(xp, str, xp->xp_numfiles, xp->xp_files, options);
802
803    // Check for matching suffixes in file names.
804    if (mode != WILD_ALL && mode != WILD_ALL_KEEP && mode != WILD_LONGEST) {
805      if (xp->xp_numfiles) {
806        non_suf_match = xp->xp_numfiles;
807      } else {
808        non_suf_match = 1;
809      }
810      if ((xp->xp_context == EXPAND_FILES
811           || xp->xp_context == EXPAND_DIRECTORIES)
812          && xp->xp_numfiles > 1) {
813        // More than one match; check suffix.
814        // The files will have been sorted on matching suffix in
815        // expand_wildcards, only need to check the first two.
816        non_suf_match = 0;
817        for (int i = 0; i < 2; i++) {
818          if (match_suffix(xp->xp_files[i])) {
819            non_suf_match++;
820          }
821        }
822      }
823      if (non_suf_match != 1) {
824        // Can we ever get here unless it's while expanding
825        // interactively?  If not, we can get rid of this all
826        // together. Don't really want to wait for this message
827        // (and possibly have to hit return to continue!).
828        if (!(options & WILD_SILENT)) {
829          emsg(_(e_toomany));
830        } else if (!(options & WILD_NO_BEEP)) {
831          beep_flush();
832        }
833      }
834      if (!(non_suf_match != 1 && mode == WILD_EXPAND_FREE)) {
835        ss = xstrdup(xp->xp_files[0]);
836      }
837    }
838  }
839
840  return ss;
841}
842
843/// Return the longest common part in the list of cmdline completion matches.
844static char *find_longest_match(expand_T *xp, int options)
845{
846  size_t len = 0;
847
848  for (size_t mb_len; xp->xp_files[0][len]; len += mb_len) {
849    mb_len = (size_t)utfc_ptr2len(&xp->xp_files[0][len]);
850    int c0 = utf_ptr2char(&xp->xp_files[0][len]);
851    int i;
852    for (i = 1; i < xp->xp_numfiles; i++) {
853      int ci = utf_ptr2char(&xp->xp_files[i][len]);
854
855      if (p_fic && (xp->xp_context == EXPAND_DIRECTORIES
856                    || xp->xp_context == EXPAND_FILES
857                    || xp->xp_context == EXPAND_SHELLCMD
858                    || xp->xp_context == EXPAND_BUFFERS)) {
859        if (mb_tolower(c0) != mb_tolower(ci)) {
860          break;
861        }
862      } else if (c0 != ci) {
863        break;
864      }
865    }
866    if (i < xp->xp_numfiles) {
867      if (!(options & WILD_NO_BEEP)) {
868        vim_beep(kOptBoFlagWildmode);
869      }
870      break;
871    }
872  }
873
874  return xmemdupz(xp->xp_files[0], len);
875}
876
877void free_xp_files_extra(expand_T *xp, int numfiles)
878{
879  if (xp->xp_files_abbr != NULL) {
880    FreeWild(numfiles, xp->xp_files_abbr);
881    xp->xp_files_abbr = NULL;
882  }
883  if (xp->xp_files_kind != NULL) {
884    FreeWild(numfiles, xp->xp_files_kind);
885    xp->xp_files_kind = NULL;
886  }
887  if (xp->xp_files_menu != NULL) {
888    FreeWild(numfiles, xp->xp_files_menu);
889    xp->xp_files_menu = NULL;
890  }
891  if (xp->xp_files_info != NULL) {
892    FreeWild(numfiles, xp->xp_files_info);
893    xp->xp_files_info = NULL;
894  }
895}
896
897/// Do wildcard expansion on the string "str".
898/// Chars that should not be expanded must be preceded with a backslash.
899/// Return a pointer to allocated memory containing the new string.
900/// Return NULL for failure.
901///
902/// "orig" is the originally expanded string, copied to allocated memory.  It
903/// should either be kept in "xp->xp_orig" or freed.  When "mode" is WILD_NEXT
904/// or WILD_PREV "orig" should be NULL.
905///
906/// Results are cached in xp->xp_files and xp->xp_numfiles, except when "mode"
907/// is WILD_EXPAND_FREE or WILD_ALL.
908///
909/// mode = WILD_FREE:        just free previously expanded matches
910/// mode = WILD_EXPAND_FREE: normal expansion, do not keep matches
911/// mode = WILD_EXPAND_KEEP: normal expansion, keep matches
912/// mode = WILD_NEXT:        use next match in multiple match, wrap to first
913/// mode = WILD_PREV:        use previous match in multiple match, wrap to first
914/// mode = WILD_ALL:         return all matches concatenated
915/// mode = WILD_LONGEST:     return longest matched part
916/// mode = WILD_ALL_KEEP:    get all matches, keep matches
917/// mode = WILD_APPLY:       apply the item selected in the cmdline completion
918///                          popup menu and close the menu.
919/// mode = WILD_CANCEL:      cancel and close the cmdline completion popup and
920///                          use the original text.
921/// mode = WILD_PUM_WANT:    use the match at index pum_want.item
922///
923/// options = WILD_LIST_NOTFOUND:    list entries without a match
924/// options = WILD_HOME_REPLACE:     do home_replace() for buffer names
925/// options = WILD_USE_NL:           Use '\n' for WILD_ALL
926/// options = WILD_NO_BEEP:          Don't beep for multiple matches
927/// options = WILD_ADD_SLASH:        add a slash after directory names
928/// options = WILD_KEEP_ALL:         don't remove 'wildignore' entries
929/// options = WILD_SILENT:           don't print warning messages
930/// options = WILD_ESCAPE:           put backslash before special chars
931/// options = WILD_ICASE:            ignore case for files
932///
933/// The variables xp->xp_context and xp->xp_backslash must have been set!
934///
935/// @param orig  allocated copy of original of expanded string
936char *ExpandOne(expand_T *xp, char *str, char *orig, int options, int mode)
937{
938  char *ss = NULL;
939  bool orig_saved = false;
940
941  // first handle the case of using an old match
942  if (mode == WILD_NEXT || mode == WILD_PREV
943      || mode == WILD_PAGEUP || mode == WILD_PAGEDOWN
944      || mode == WILD_PUM_WANT) {
945    return get_next_or_prev_match(mode, xp);
946  }
947
948  if (mode == WILD_CANCEL) {
949    ss = xstrdup(xp->xp_orig ? xp->xp_orig : "");
950  } else if (mode == WILD_APPLY) {
951    ss = xstrdup(xp->xp_selected == -1
952                 ? (xp->xp_orig ? xp->xp_orig : "")
953                 : xp->xp_files[xp->xp_selected]);
954  }
955
956  // free old names
957  if (xp->xp_numfiles != -1 && mode != WILD_ALL && mode != WILD_LONGEST) {
958    FreeWild(xp->xp_numfiles, xp->xp_files);
959    free_xp_files_extra(xp, xp->xp_numfiles);
960    xp->xp_numfiles = -1;
961    XFREE_CLEAR(xp->xp_orig);
962
963    // The entries from xp_files may be used in the PUM, remove it.
964    if (compl_match_array != NULL) {
965      cmdline_pum_remove(false);
966    }
967  }
968  xp->xp_selected = (options & WILD_NOSELECT) ? -1 : 0;
969
970  if (mode == WILD_FREE) {      // only release file name
971    return NULL;
972  }
973
974  if (xp->xp_numfiles == -1 && mode != WILD_APPLY && mode != WILD_CANCEL) {
975    xfree(xp->xp_orig);
976    xp->xp_orig = orig;
977    orig_saved = true;
978
979    ss = ExpandOne_start(mode, xp, str, options);
980  }
981
982  // Find longest common part
983  if (mode == WILD_LONGEST && xp->xp_numfiles > 0) {
984    ss = find_longest_match(xp, options);
985    xp->xp_selected = -1;  // next p_wc gets first one
986  }
987
988  // Concatenate all matching names.  Unless interrupted, this can be slow
989  // and the result probably won't be used.
990  if (mode == WILD_ALL && xp->xp_numfiles > 0 && !got_int) {
991    size_t ss_size = 0;
992    char *prefix = "";
993    char *suffix = (options & WILD_USE_NL) ? "\n" : " ";
994    const int n = xp->xp_numfiles - 1;
995
996    if (xp->xp_prefix == XP_PREFIX_NO) {
997      prefix = "no";
998      ss_size = STRLEN_LITERAL("no") * (size_t)n;
999    } else if (xp->xp_prefix == XP_PREFIX_INV) {
1000      prefix = "inv";
1001      ss_size = STRLEN_LITERAL("inv") * (size_t)n;
1002    }
1003
1004    for (int i = 0; i < xp->xp_numfiles; i++) {
1005      ss_size += strlen(xp->xp_files[i]) + 1;  // +1 for the suffix
1006    }
1007    ss_size++;  // +1 for the NUL
1008
1009    ss = xmalloc(ss_size);
1010    *ss = NUL;
1011    char *ssp = ss;
1012    for (int i = 0; i < xp->xp_numfiles; i++) {
1013      if (i > 0) {
1014        ssp = xstpcpy(ssp, prefix);
1015      }
1016      ssp = xstpcpy(ssp, xp->xp_files[i]);
1017      if (i < n) {
1018        ssp = xstpcpy(ssp, suffix);
1019      }
1020      assert(ssp < ss + ss_size);
1021    }
1022  }
1023
1024  if (mode == WILD_EXPAND_FREE || mode == WILD_ALL) {
1025    ExpandCleanup(xp);
1026  }
1027
1028  // Free "orig" if it wasn't stored in "xp->xp_orig".
1029  if (!orig_saved) {
1030    xfree(orig);
1031  }
1032
1033  return ss;
1034}
1035
1036/// Prepare an expand structure for use.
1037void ExpandInit(expand_T *xp)
1038  FUNC_ATTR_NONNULL_ALL
1039{
1040  CLEAR_POINTER(xp);
1041  xp->xp_backslash = XP_BS_NONE;
1042  xp->xp_prefix = XP_PREFIX_NONE;
1043  xp->xp_numfiles = -1;
1044}
1045
1046/// Cleanup an expand structure after use.
1047void ExpandCleanup(expand_T *xp)
1048{
1049  if (xp->xp_numfiles >= 0) {
1050    free_xp_files_extra(xp, xp->xp_numfiles);
1051    FreeWild(xp->xp_numfiles, xp->xp_files);
1052    xp->xp_numfiles = -1;
1053  }
1054  XFREE_CLEAR(xp->xp_orig);
1055}
1056
1057void clear_cmdline_orig(void)
1058{
1059  API_CLEAR_STRING(cmdline_orig);
1060}
1061
1062/// Display one line of completion matches. Multiple matches are displayed in
1063/// each line (used by wildmode=list and CTRL-D)
1064///
1065/// @param matches      list of completion match names
1066/// @param numMatches   number of completion matches in "matches"
1067/// @param lines        number of output lines
1068/// @param linenr       line number of matches to display
1069/// @param maxlen       maximum number of characters in each line
1070/// @param showtail     display only the tail of the full path of a file name
1071static void showmatches_oneline(expand_T *xp, char **matches, int numMatches, int lines, int linenr,
1072                                int maxlen, bool showtail)
1073{
1074  char *p;
1075  int lastlen = 999;
1076  for (int j = linenr; j < numMatches; j += lines) {
1077    if (xp->xp_context == EXPAND_TAGS_LISTFILES) {
1078      msg_outtrans(matches[j], HLF_D, false);
1079      p = matches[j] + strlen(matches[j]) + 1;
1080      msg_advance(maxlen + 1);
1081      msg_puts(p);
1082      msg_advance(maxlen + 3);
1083      msg_outtrans_long(p + 2, HLF_D);
1084      break;
1085    }
1086    for (int i = maxlen - lastlen; --i >= 0;) {
1087      msg_putchar(' ');
1088    }
1089    bool isdir;
1090    if (xp->xp_context == EXPAND_FILES
1091        || xp->xp_context == EXPAND_SHELLCMD
1092        || xp->xp_context == EXPAND_BUFFERS) {
1093      // highlight directories
1094      if (xp->xp_numfiles != -1) {
1095        // Expansion was done before and special characters
1096        // were escaped, need to halve backslashes.  Also
1097        // $HOME has been replaced with ~/.
1098        char *exp_path = expand_env_save_opt(matches[j], true, NULL);
1099        char *path = exp_path != NULL ? exp_path : matches[j];
1100        char *halved_slash = backslash_halve_save(path);
1101        isdir = os_isdir(halved_slash);
1102        xfree(exp_path);
1103        if (halved_slash != path) {
1104          xfree(halved_slash);
1105        }
1106      } else {
1107        // Expansion was done here, file names are literal.
1108        isdir = os_isdir(matches[j]);
1109      }
1110      if (showtail) {
1111        p = SHOW_MATCH(j);
1112      } else {
1113        home_replace(NULL, matches[j], NameBuff, MAXPATHL, true);
1114        p = NameBuff;
1115      }
1116    } else {
1117      isdir = false;
1118      p = SHOW_MATCH(j);
1119    }
1120    lastlen = msg_outtrans(p, isdir ? HLF_D : 0, false);
1121  }
1122  if (msg_col > 0) {  // when not wrapped around
1123    msg_clr_eos();
1124    msg_putchar('\n');
1125  }
1126}
1127
1128/// Show the matches in a popup menu, with the first one selected unless
1129/// "noselect" is set.
1130static inline void show_pum_matches(CmdlineInfo *ccline, expand_T *xp, char **matches,
1131                                    int numMatches, bool showtail, bool noselect,
1132                                    bool cmdline_unchanged)
1133{
1134  cmdline_pum_create(ccline, xp, matches, numMatches, showtail, cmdline_unchanged);
1135  compl_selected = noselect ? -1 : 0;
1136  pum_clear();
1137  cmdline_pum_display(true);
1138}
1139
1140/// Display completion matches.
1141/// Returns EXPAND_NOTHING when the character that triggered expansion should be
1142///   inserted as a normal character.
1143int showmatches(expand_T *xp, bool display_wildmenu, bool display_list, int wim_flags_arg)
1144{
1145  CmdlineInfo *const ccline = get_cmdline_info();
1146  int numMatches;
1147  char **matches;
1148  int maxlen;
1149  int lines;
1150  int columns;
1151  bool showtail;
1152  bool noselect = (wim_flags_arg & kOptWimFlagNoselect);
1153  bool noinsert = (wim_flags_arg & kOptWimFlagNoinsert);
1154  bool cmdline_unchanged = noselect || noinsert;
1155
1156  if (xp->xp_numfiles == -1) {
1157    set_expand_context(xp);
1158    if (xp->xp_context == EXPAND_LUA) {
1159      nlua_expand_pat(xp);
1160    }
1161    int retval = expand_cmdline(xp, ccline->cmdbuff, ccline->cmdpos,
1162                                &numMatches, &matches);
1163    if (retval != EXPAND_OK) {
1164      return retval;
1165    }
1166    showtail = expand_showtail(xp);
1167  } else {
1168    numMatches = xp->xp_numfiles;
1169    matches = xp->xp_files;
1170    showtail = cmd_showtail;
1171  }
1172
1173  if (cmdline_compl_use_pum(display_wildmenu && !display_list)) {
1174    show_pum_matches(ccline, xp, matches, numMatches, showtail, noselect, cmdline_unchanged);
1175    return EXPAND_OK;
1176  }
1177
1178  if (display_list) {
1179    msg_didany = false;                 // lines_left will be set
1180    msg_start();                        // prepare for paging
1181    if (!ui_has(kUIMessages)) {
1182      msg_putchar('\n');
1183    }
1184    ui_flush();
1185    cmdline_row = msg_row;
1186    msg_didany = false;                 // lines_left will be set again
1187    msg_ext_set_kind("wildlist");
1188    msg_start();                        // prepare for paging
1189  }
1190
1191  if (got_int) {
1192    got_int = false;  // only interrupt the completion, not the cmd line
1193  } else if (display_wildmenu && !display_list) {
1194    redraw_wildmenu(xp, numMatches, matches, noselect ? -1 : 0,
1195                    showtail);  // display statusbar menu
1196  } else if (display_list) {
1197    // find the length of the longest file name
1198    maxlen = 0;
1199    for (int i = 0; i < numMatches; i++) {
1200      int len;
1201      if (!showtail && (xp->xp_context == EXPAND_FILES
1202                        || xp->xp_context == EXPAND_SHELLCMD
1203                        || xp->xp_context == EXPAND_BUFFERS)) {
1204        home_replace(NULL, matches[i], NameBuff, MAXPATHL, true);
1205        len = vim_strsize(NameBuff);
1206      } else {
1207        len = vim_strsize(SHOW_MATCH(i));
1208      }
1209      maxlen = MAX(maxlen, len);
1210    }
1211
1212    if (xp->xp_context == EXPAND_TAGS_LISTFILES) {
1213      lines = numMatches;
1214    } else {
1215      // compute the number of columns and lines for the listing
1216      maxlen += 2;          // two spaces between file names
1217      columns = (Columns + 2) / maxlen;
1218      if (columns < 1) {
1219        columns = 1;
1220      }
1221      lines = (numMatches + columns - 1) / columns;
1222    }
1223
1224    if (xp->xp_context == EXPAND_TAGS_LISTFILES) {
1225      msg_puts_hl(_("tagname"), HLF_T, false);
1226      msg_clr_eos();
1227      msg_advance(maxlen - 3);
1228      msg_puts_hl(_(" kind file\n"), HLF_T, false);
1229    }
1230
1231    // list the files line by line
1232    for (int i = 0; i < lines; i++) {
1233      showmatches_oneline(xp, matches, numMatches, lines, i, maxlen, showtail);
1234      if (got_int) {
1235        got_int = false;
1236        break;
1237      }
1238    }
1239
1240    // we redraw the command below the lines that we have just listed
1241    // This is a bit tricky, but it saves a lot of screen updating.
1242    cmdline_row = msg_row;      // will put it back later
1243  }
1244
1245  // "list" and "full" in the same 'wildmode' phase: the matches are listed
1246  // above and shown in the menu as well.
1247  if (display_wildmenu && display_list) {
1248    if (cmdline_compl_use_pum(true)) {
1249      show_pum_matches(ccline, xp, matches, numMatches, showtail, noselect, cmdline_unchanged);
1250    } else {
1251      redraw_wildmenu(xp, numMatches, matches, noselect ? -1 : 0, showtail);
1252    }
1253  }
1254
1255  if (xp->xp_numfiles == -1) {
1256    FreeWild(numMatches, matches);
1257    free_xp_files_extra(xp, numMatches);
1258  }
1259
1260  return EXPAND_OK;
1261}
1262
1263/// path_tail() version for showmatches() and redraw_wildmenu():
1264/// Return the tail of file name path "s", ignoring a trailing "/".
1265static char *showmatches_gettail(char *s, bool eager)
1266{
1267  char *t = s;
1268  bool had_sep = false;
1269
1270  for (char *p = s; *p != NUL;) {
1271    if (vim_ispathsep(*p)
1272#ifdef BACKSLASH_IN_FILENAME
1273        && !rem_backslash(p)
1274#endif
1275        ) {
1276      if (eager) {
1277        t = p + 1;
1278      } else {
1279        had_sep = true;
1280      }
1281    } else if (had_sep) {
1282      t = p;
1283      had_sep = false;
1284    }
1285    MB_PTR_ADV(p);
1286  }
1287  return t;
1288}
1289
1290/// Return true if we only need to show the tail of completion matches.
1291/// When not completing file names or there is a wildcard in the path false is
1292/// returned.
1293static bool expand_showtail(expand_T *xp)
1294{
1295  // When not completing file names a "/" may mean something different.
1296  if (xp->xp_context != EXPAND_FILES
1297      && xp->xp_context != EXPAND_SHELLCMD
1298      && xp->xp_context != EXPAND_DIRECTORIES) {
1299    return false;
1300  }
1301
1302  char *end = path_tail(xp->xp_pattern);
1303  if (end == xp->xp_pattern) {          // there is no path separator
1304    return false;
1305  }
1306
1307  for (char *s = xp->xp_pattern; s < end; s++) {
1308    // Skip escaped wildcards.  Only when the backslash is not a path
1309    // separator, on DOS the '*' "path\*\file" must not be skipped.
1310    if (rem_backslash(s)) {
1311      s++;
1312    } else if (vim_strchr("*?[", (uint8_t)(*s)) != NULL) {
1313      return false;
1314    }
1315  }
1316  return true;
1317}
1318
1319/// Prepare a string for expansion.
1320///
1321/// When expanding file names: The string will be used with expand_wildcards().
1322/// Copy "fname[len]" into allocated memory and add a '*' at the end.
1323/// When expanding other names: The string will be used with regcomp().  Copy
1324/// the name into allocated memory and prepend "^".
1325///
1326/// @param context EXPAND_FILES etc.
1327char *addstar(char *fname, size_t len, int context)
1328  FUNC_ATTR_NONNULL_RET
1329{
1330  char *retval;
1331
1332  if (context != EXPAND_FILES
1333      && context != EXPAND_FILES_IN_PATH
1334      && context != EXPAND_SHELLCMD
1335      && context != EXPAND_DIRECTORIES
1336      && context != EXPAND_DIRS_IN_CDPATH) {
1337    // Matching will be done internally (on something other than files).
1338    // So we convert the file-matching-type wildcards into our kind for
1339    // use with vim_regcomp().  First work out how long it will be:
1340
1341    // For help tags the translation is done in find_help_tags().
1342    // For a tag pattern starting with "/" no translation is needed.
1343    if (context == EXPAND_FINDFUNC
1344        || context == EXPAND_HELP
1345        || context == EXPAND_COLORS
1346        || context == EXPAND_COMPILER
1347        || context == EXPAND_OWNSYNTAX
1348        || context == EXPAND_FILETYPE
1349        || context == EXPAND_KEYMAP
1350        || context == EXPAND_PACKADD
1351        || context == EXPAND_RUNTIME
1352        || ((context == EXPAND_TAGS_LISTFILES || context == EXPAND_TAGS)
1353            && fname[0] == '/')
1354        || context == EXPAND_CHECKHEALTH
1355        || context == EXPAND_LSP
1356        || context == EXPAND_LOG
1357        || context == EXPAND_PACKDEL
1358        || context == EXPAND_PACKUPDATE
1359        || context == EXPAND_MARKS
1360        || context == EXPAND_LUA) {
1361      retval = xstrnsave(fname, len);
1362    } else {
1363      size_t new_len = len + 2;                // +2 for '^' at start, NUL at end
1364      for (size_t i = 0; i < len; i++) {
1365        if (fname[i] == '*' || fname[i] == '~') {
1366          new_len++;                    // '*' needs to be replaced by ".*"
1367                                        // '~' needs to be replaced by "\~"
1368        }
1369        // Buffer names are like file names.  "." should be literal
1370        if (context == EXPAND_BUFFERS && fname[i] == '.') {
1371          new_len++;                    // "." becomes "\."
1372        }
1373        // Custom expansion takes care of special things, match
1374        // backslashes literally (perhaps also for other types?)
1375        if ((context == EXPAND_USER_DEFINED
1376             || context == EXPAND_USER_LIST) && fname[i] == '\\') {
1377          new_len++;                    // '\' becomes "\\"
1378        }
1379      }
1380      retval = xmalloc(new_len);
1381      {
1382        retval[0] = '^';
1383        size_t j = 1;
1384        for (size_t i = 0; i < len; i++, j++) {
1385          // Skip backslash.  But why?  At least keep it for custom
1386          // expansion.
1387          if (context != EXPAND_USER_DEFINED
1388              && context != EXPAND_USER_LIST
1389              && fname[i] == '\\'
1390              && ++i == len) {
1391            break;
1392          }
1393
1394          switch (fname[i]) {
1395          case '*':
1396            retval[j++] = '.';
1397            break;
1398          case '~':
1399            retval[j++] = '\\';
1400            break;
1401          case '?':
1402            retval[j] = '.';
1403            continue;
1404          case '.':
1405            if (context == EXPAND_BUFFERS) {
1406              retval[j++] = '\\';
1407            }
1408            break;
1409          case '\\':
1410            if (context == EXPAND_USER_DEFINED
1411                || context == EXPAND_USER_LIST) {
1412              retval[j++] = '\\';
1413            }
1414            break;
1415          }
1416          retval[j] = fname[i];
1417        }
1418        retval[j] = NUL;
1419      }
1420    }
1421  } else {
1422    retval = xmalloc(len + 4);
1423    xmemcpyz(retval, fname, len);
1424
1425    // Don't add a star to *, ~, ~user, $var or `cmd`.
1426    // * would become **, which walks the whole tree.
1427    // ~ would be at the start of the file name, but not the tail.
1428    // $ could be anywhere in the tail.
1429    // ` could be anywhere in the file name.
1430    // When the name ends in '$' don't add a star, remove the '$'.
1431    char *tail = path_tail(retval);
1432    int ends_in_star = (len > 0 && retval[len - 1] == '*');
1433#ifndef BACKSLASH_IN_FILENAME
1434    for (ssize_t k = (ssize_t)len - 2; k >= 0; k--) {
1435      if (retval[k] != '\\') {
1436        break;
1437      }
1438      ends_in_star = !ends_in_star;
1439    }
1440#endif
1441    if ((*retval != '~' || tail != retval)
1442        && !ends_in_star
1443        && vim_strchr(tail, '$') == NULL
1444        && vim_strchr(retval, '`') == NULL) {
1445      retval[len++] = '*';
1446    } else if (len > 0 && retval[len - 1] == '$') {
1447      len--;
1448    }
1449    retval[len] = NUL;
1450  }
1451  return retval;
1452}
1453
1454/// Must parse the command line so far to work out what context we are in.
1455/// Completion can then be done based on that context.
1456/// This routine sets the variables:
1457///  xp->xp_pattern          The start of the pattern to be expanded within
1458///                              the command line (ends at the cursor).
1459///  xp->xp_context          The type of thing to expand.  Will be one of:
1460///
1461///  EXPAND_UNSUCCESSFUL     Used sometimes when there is something illegal on
1462///                          the command line, like an unknown command.  Caller
1463///                          should beep.
1464///  EXPAND_NOTHING          Unrecognised context for completion, use char like
1465///                          a normal char, rather than for completion.  eg
1466///                          :s/^I/
1467///  EXPAND_COMMANDS         Cursor is still touching the command, so complete
1468///                          it.
1469///  EXPAND_BUFFERS          Complete file names for :buf and :sbuf commands.
1470///  EXPAND_FILES            After command with EX_XFILE set, or after setting
1471///                          with kOptFlagExpand set.  eg :e ^I, :w>>^I
1472///  EXPAND_DIRECTORIES      In some cases this is used instead of the latter
1473///                          when we know only directories are of interest.
1474///                          E.g.  :set dir=^I  and  :cd ^I
1475///  EXPAND_SHELLCMD         After ":!cmd", ":r !cmd"  or ":w !cmd".
1476///  EXPAND_SETTINGS         Complete variable names.  eg :set d^I
1477///  EXPAND_BOOL_SETTINGS    Complete boolean variables only,  eg :set no^I
1478///  EXPAND_TAGS             Complete tags from the files in p_tags.  eg :ta a^I
1479///  EXPAND_TAGS_LISTFILES   As above, but list filenames on ^D, after :tselect
1480///  EXPAND_HELP             Complete tags from the file 'helpfile'/tags
1481///  EXPAND_EVENTS           Complete event names
1482///  EXPAND_SYNTAX           Complete :syntax command arguments
1483///  EXPAND_HIGHLIGHT        Complete highlight (syntax) group names
1484///  EXPAND_AUGROUP          Complete autocommand group names
1485///  EXPAND_USER_VARS        Complete user defined variable names, eg :unlet a^I
1486///  EXPAND_MAPPINGS         Complete mapping and abbreviation names,
1487///                            eg :unmap a^I , :cunab x^I
1488///  EXPAND_FUNCTIONS        Complete internal or user defined function names,
1489///                            eg :call sub^I
1490///  EXPAND_USER_FUNC        Complete user defined function names, eg :delf F^I
1491///  EXPAND_EXPRESSION       Complete internal or user defined function/variable
1492///                          names in expressions, eg :while s^I
1493///  EXPAND_ENV_VARS         Complete environment variable names
1494///  EXPAND_USER             Complete user names
1495///  EXPAND_PATTERN_IN_BUF   Complete pattern in '/', '?', ':s', ':g', etc.
1496void set_expand_context(expand_T *xp)
1497{
1498  CmdlineInfo *const ccline = get_cmdline_info();
1499
1500  // Handle search commands: '/' or '?'
1501  if ((ccline->cmdfirstc == '/' || ccline->cmdfirstc == '?')
1502      && may_expand_pattern) {
1503    xp->xp_context = EXPAND_PATTERN_IN_BUF;
1504    xp->xp_search_dir = (ccline->cmdfirstc == '/') ? FORWARD : BACKWARD;
1505    xp->xp_pattern = ccline->cmdbuff;
1506    xp->xp_pattern_len = (size_t)ccline->cmdpos;
1507    Search.first_line = 0;  // Search entire buffer
1508    return;
1509  }
1510
1511  // Only handle ':', '>', or '=' command-lines, or expression input
1512  if (ccline->cmdfirstc != ':'
1513      && ccline->cmdfirstc != '>' && ccline->cmdfirstc != '='
1514      && !ccline->input_fn) {
1515    xp->xp_context = EXPAND_NOTHING;
1516    return;
1517  }
1518
1519  // Fallback to command-line expansion
1520  set_cmd_context(xp, ccline->cmdbuff, ccline->cmdlen, ccline->cmdpos, true);
1521}
1522
1523/// Sets the index of a built-in or user defined command "cmd" in eap->cmdidx.
1524/// For user defined commands, the completion context is set in "xp" and the
1525/// completion flags in "complp".
1526///
1527/// @return  a pointer to the text after the command or NULL for failure.
1528static const char *set_cmd_index(const char *cmd, exarg_T *eap, expand_T *xp, int *complp)
1529{
1530  const char *p = NULL;
1531  const bool fuzzy = cmdline_fuzzy_complete(cmd);
1532
1533  // Isolate the command and search for it in the command table.
1534  // Exceptions:
1535  // - the 'k' command can directly be followed by any character, but do
1536  // accept "keepmarks", "keepalt" and "keepjumps". Bypass also when
1537  // 'ignorecase' is set so a lowercase ":kz" still completes a user
1538  // command like :Kz, and for fuzzy matching as that can find
1539  // matches anywhere in the command name.
1540  // - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
1541  if (!fuzzy && !p_ic && (*cmd == 'k' && cmd[1] != 'e')) {
1542    eap->cmdidx = CMD_k;
1543    p = cmd + 1;
1544  } else {
1545    p = cmd;
1546    while (ASCII_ISALPHA(*p) || *p == '*') {  // Allow * wild card
1547      p++;
1548    }
1549    // a user command may contain digits
1550    if (ASCII_ISUPPER(cmd[0])) {
1551      while (ASCII_ISALNUM(*p) || *p == '*') {
1552        p++;
1553      }
1554    }
1555    // for python 3.x: ":py3*" commands completion
1556    if (cmd[0] == 'p' && cmd[1] == 'y' && p == cmd + 2 && *p == '3') {
1557      p++;
1558      while (ASCII_ISALPHA(*p) || *p == '*') {
1559        p++;
1560      }
1561    }
1562    // check for non-alpha command
1563    if (p == cmd && vim_strchr("@*!=><&~#", (uint8_t)(*p)) != NULL) {
1564      p++;
1565    }
1566    size_t len = (size_t)(p - cmd);
1567
1568    if (len == 0) {
1569      xp->xp_context = EXPAND_UNSUCCESSFUL;
1570      return NULL;
1571    }
1572
1573    eap->cmdidx = excmd_get_cmdidx(cmd, len);
1574
1575    // User defined commands support alphanumeric characters.
1576    // Also when doing fuzzy expansion for non-shell commands, support
1577    // alphanumeric characters.
1578    if ((cmd[0] >= 'A' && cmd[0] <= 'Z')
1579        || (fuzzy && eap->cmdidx != CMD_bang && *p != NUL)) {
1580      while (ASCII_ISALNUM(*p) || *p == '*') {  // Allow * wild card
1581        p++;
1582      }
1583    }
1584  }
1585
1586  // If the cursor is touching the command, and it ends in an alphanumeric
1587  // character, complete the command name.
1588  if (*p == NUL && ASCII_ISALNUM(p[-1])) {
1589    return NULL;
1590  }
1591
1592  if (eap->cmdidx == CMD_SIZE) {
1593    if (*cmd == 's' && vim_strchr("cgriI", (uint8_t)cmd[1]) != NULL) {
1594      eap->cmdidx = CMD_substitute;
1595      p = cmd + 1;
1596    } else if (cmd[0] >= 'A' && cmd[0] <= 'Z') {
1597      eap->cmd = (char *)cmd;
1598      p = find_ucmd(eap, (char *)p, NULL, xp, complp);
1599      if (p == NULL) {
1600        eap->cmdidx = CMD_SIZE;  // Ambiguous user command.
1601      }
1602    }
1603  }
1604  if (eap->cmdidx == CMD_SIZE) {
1605    // Not still touching the command and it was an illegal one
1606    xp->xp_context = EXPAND_UNSUCCESSFUL;
1607    return NULL;
1608  }
1609
1610  return p;
1611}
1612
1613/// Set the completion context for a command argument with wild card characters.
1614static void set_context_for_wildcard_arg(exarg_T *eap, const char *arg, bool usefilter,
1615                                         expand_T *xp, int *complp)
1616{
1617  bool in_quote = false;
1618  const char *bow = NULL;  // Beginning of word.
1619  size_t len = 0;
1620
1621  // Allow spaces within back-quotes to count as part of the argument
1622  // being expanded.
1623  xp->xp_pattern = skipwhite(arg);
1624  const char *p = xp->xp_pattern;
1625  while (*p != NUL) {
1626    int c = utf_ptr2char(p);
1627    if (c == '\\' && p[1] != NUL) {
1628      p++;
1629    } else if (c == '`') {
1630      if (!in_quote) {
1631        xp->xp_pattern = (char *)p;
1632        bow = p + 1;
1633      }
1634      in_quote = !in_quote;
1635      // An argument can contain just about everything, except
1636      // characters that end the command and white space.
1637    } else if (c == '|' || c == '\n' || c == '"'
1638               || (ascii_iswhite(c) && (!(eap != NULL && (eap->argt & EX_NOSPC))
1639                                        || usefilter))) {
1640      len = 0;  // avoid getting stuck when space is in 'isfname'
1641      while (*p != NUL) {
1642        c = utf_ptr2char(p);
1643        if (c == '`' || vim_isfilec_or_wc(c)) {
1644          break;
1645        }
1646        len = (size_t)utfc_ptr2len(p);
1647        MB_PTR_ADV(p);
1648      }
1649      if (in_quote) {
1650        bow = p;
1651      } else {
1652        xp->xp_pattern = (char *)p;
1653      }
1654      p -= len;
1655    }
1656    MB_PTR_ADV(p);
1657  }
1658
1659  // If we are still inside the quotes, and we passed a space, just
1660  // expand from there.
1661  if (bow != NULL && in_quote) {
1662    xp->xp_pattern = (char *)bow;
1663  }
1664  xp->xp_context = EXPAND_FILES;
1665
1666  // For a shell command more chars need to be escaped.
1667  if (usefilter
1668      || (eap != NULL && (eap->cmdidx == CMD_bang || eap->cmdidx == CMD_terminal))
1669      || *complp == EXPAND_SHELLCMDLINE) {
1670#ifndef BACKSLASH_IN_FILENAME
1671    xp->xp_shell = true;
1672#endif
1673    // When still after the command name expand executables.
1674    if (xp->xp_pattern == skipwhite(arg)) {
1675      xp->xp_context = EXPAND_SHELLCMD;
1676    }
1677  }
1678
1679  // Check for environment variable.
1680  if (*xp->xp_pattern == '$') {
1681    for (p = xp->xp_pattern + 1; *p != NUL; p++) {
1682      if (!vim_isIDc((uint8_t)(*p))) {
1683        break;
1684      }
1685    }
1686    if (*p == NUL) {
1687      xp->xp_context = EXPAND_ENV_VARS;
1688      xp->xp_pattern++;
1689      // Avoid that the assignment uses EXPAND_FILES again.
1690      if (*complp != EXPAND_USER_DEFINED && *complp != EXPAND_USER_LIST) {
1691        *complp = EXPAND_ENV_VARS;
1692      }
1693    }
1694  }
1695  // Check for user names.
1696  if (*xp->xp_pattern == '~') {
1697    for (p = xp->xp_pattern + 1; *p != NUL && *p != '/'; p++) {}
1698    // Complete ~user only if it partially matches a user name.
1699    // A full match ~user<Tab> will be replaced by user's home
1700    // directory i.e. something like ~user<Tab> -> /home/user/
1701    if (*p == NUL && p > xp->xp_pattern + 1 && match_user(xp->xp_pattern + 1) >= 1) {
1702      xp->xp_context = EXPAND_USER;
1703      xp->xp_pattern++;
1704    }
1705  }
1706}
1707
1708/// Set the completion context for the "++opt=arg" argument.  Always returns NULL.
1709static const char *set_context_in_argopt(expand_T *xp, const char *arg)
1710{
1711  char *p = vim_strchr(arg, '=');
1712  if (p == NULL) {
1713    xp->xp_pattern = (char *)arg;
1714  } else {
1715    xp->xp_pattern = p + 1;
1716  }
1717
1718  xp->xp_context = EXPAND_ARGOPT;
1719  return NULL;
1720}
1721
1722/// Set the completion context for the :filter command. Returns a pointer to the
1723/// next command after the :filter command.
1724static const char *set_context_in_filter_cmd(expand_T *xp, const char *arg)
1725{
1726  if (*arg != NUL) {
1727    arg = skip_vimgrep_pat((char *)arg, NULL, NULL);
1728  }
1729  if (arg == NULL || *arg == NUL) {
1730    xp->xp_context = EXPAND_NOTHING;
1731    return NULL;
1732  }
1733  return skipwhite(arg);
1734}
1735
1736/// Set the completion context for the :match command. Returns a pointer to the
1737/// next command after the :match command.
1738static const char *set_context_in_match_cmd(expand_T *xp, const char *arg)
1739{
1740  if (*arg == NUL || !ends_excmd(*arg)) {
1741    // also complete "None"
1742    set_context_in_echohl_cmd(xp, arg);
1743    arg = skipwhite(skiptowhite(arg));
1744    if (*arg != NUL) {
1745      xp->xp_context = EXPAND_NOTHING;
1746      arg = skip_regexp((char *)arg + 1, (uint8_t)(*arg), p_magic);
1747    }
1748  }
1749  return find_nextcmd(arg);
1750}
1751
1752/// Returns a pointer to the next command after a :global or a :v command.
1753/// Returns NULL if there is no next command.
1754static const char *find_cmd_after_global_cmd(const char *arg)
1755{
1756  const int delim = (uint8_t)(*arg);  // Get the delimiter.
1757  if (delim) {
1758    arg++;  // Skip delimiter if there is one.
1759  }
1760
1761  while (arg[0] != NUL && (uint8_t)arg[0] != delim) {
1762    if (arg[0] == '\\' && arg[1] != NUL) {
1763      arg++;
1764    }
1765    arg++;
1766  }
1767  if (arg[0] != NUL) {
1768    return arg + 1;
1769  }
1770
1771  return NULL;
1772}
1773
1774/// Returns a pointer to the next command after a :substitute or a :& command.
1775/// Returns NULL if there is no next command.
1776static const char *find_cmd_after_substitute_cmd(const char *arg)
1777{
1778  const int delim = (uint8_t)(*arg);
1779  if (delim) {
1780    // Skip "from" part.
1781    arg++;
1782    arg = skip_regexp((char *)arg, delim, p_magic);
1783
1784    if (arg[0] != NUL && arg[0] == delim) {
1785      // Skip "to" part.
1786      arg++;
1787      while (arg[0] != NUL && (uint8_t)arg[0] != delim) {
1788        if (arg[0] == '\\' && arg[1] != NUL) {
1789          arg++;
1790        }
1791        arg++;
1792      }
1793      if (arg[0] != NUL) {  // Skip delimiter.
1794        arg++;
1795      }
1796    }
1797  }
1798  while (arg[0] && strchr("|\"#", arg[0]) == NULL) {
1799    arg++;
1800  }
1801  if (arg[0] != NUL) {
1802    return arg;
1803  }
1804
1805  return NULL;
1806}
1807
1808/// Returns a pointer to the next command after a :isearch/:dsearch/:ilist
1809/// :dlist/:ijump/:psearch/:djump/:isplit/:dsplit command.
1810/// Returns NULL if there is no next command.
1811static const char *find_cmd_after_isearch_cmd(expand_T *xp, const char *arg)
1812{
1813  // Skip count.
1814  arg = skipwhite(skipdigits(arg));
1815  if (*arg != '/') {
1816    return NULL;
1817  }
1818
1819  // Match regexp, not just whole words.
1820  for (++arg; *arg && *arg != '/'; arg++) {
1821    if (*arg == '\\' && arg[1] != NUL) {
1822      arg++;
1823    }
1824  }
1825  if (*arg) {
1826    arg = skipwhite(arg + 1);
1827
1828    // Check for trailing illegal characters.
1829    if (*arg == NUL || strchr("|\"\n", *arg) == NULL) {
1830      xp->xp_context = EXPAND_NOTHING;
1831    } else {
1832      return arg;
1833    }
1834  }
1835
1836  return NULL;
1837}
1838
1839/// Set the completion context for the :unlet command. Always returns NULL.
1840static const char *set_context_in_unlet_cmd(expand_T *xp, const char *arg)
1841{
1842  // NOLINTNEXTLINE(*-casting): remove once CI uses glibc 2.43
1843  while ((xp->xp_pattern = (char *)strchr(arg, ' ')) != NULL) {
1844    arg = xp->xp_pattern + 1;
1845  }
1846
1847  xp->xp_context = EXPAND_USER_VARS;
1848  xp->xp_pattern = (char *)arg;
1849
1850  if (*xp->xp_pattern == '$') {
1851    xp->xp_context = EXPAND_ENV_VARS;
1852    xp->xp_pattern++;
1853  }
1854
1855  return NULL;
1856}
1857
1858/// Set the completion context for the :language command. Always returns NULL.
1859static const char *set_context_in_lang_cmd(expand_T *xp, const char *arg)
1860{
1861  const char *p = skiptowhite(arg);
1862  if (*p == NUL) {
1863    xp->xp_context = EXPAND_LANGUAGE;
1864    xp->xp_pattern = (char *)arg;
1865  } else {
1866    if (strncmp(arg, "messages", (size_t)(p - arg)) == 0
1867        || strncmp(arg, "ctype", (size_t)(p - arg)) == 0
1868        || strncmp(arg, "time", (size_t)(p - arg)) == 0
1869        || strncmp(arg, "collate", (size_t)(p - arg)) == 0) {
1870      xp->xp_context = EXPAND_LOCALES;
1871      xp->xp_pattern = skipwhite(p);
1872    } else {
1873      xp->xp_context = EXPAND_NOTHING;
1874    }
1875  }
1876
1877  return NULL;
1878}
1879
1880static enum {
1881  EXP_FILETYPECMD_ALL,     ///< expand all :filetype values
1882  EXP_FILETYPECMD_PLUGIN,  ///< expand plugin on off
1883  EXP_FILETYPECMD_INDENT,  ///< expand indent on off
1884  EXP_FILETYPECMD_ONOFF,   ///< expand on off
1885} filetype_expand_what;
1886
1887enum {
1888  EXPAND_FILETYPECMD_PLUGIN = 0x01,
1889  EXPAND_FILETYPECMD_INDENT = 0x02,
1890  EXPAND_FILETYPECMD_ONOFF  = 0x04,
1891};
1892
1893static enum {
1894  EXP_BREAKPT_ADD,  ///< expand ":breakadd" sub-commands
1895  EXP_BREAKPT_DEL,  ///< expand ":breakdel" sub-commands
1896  EXP_PROFDEL,      ///< expand ":profdel" sub-commands
1897} breakpt_expand_what;
1898
1899/// Set the completion context for the :breakadd command. Always returns NULL.
1900static const char *set_context_in_breakadd_cmd(expand_T *xp, const char *arg, cmdidx_T cmdidx)
1901{
1902  xp->xp_context = EXPAND_BREAKPOINT;
1903  xp->xp_pattern = (char *)arg;
1904
1905  if (cmdidx == CMD_breakadd) {
1906    breakpt_expand_what = EXP_BREAKPT_ADD;
1907  } else if (cmdidx == CMD_breakdel) {
1908    breakpt_expand_what = EXP_BREAKPT_DEL;
1909  } else {
1910    breakpt_expand_what = EXP_PROFDEL;
1911  }
1912
1913  const char *p = skipwhite(arg);
1914  if (*p == NUL) {
1915    return NULL;
1916  }
1917  const char *subcmd_start = p;
1918
1919  if (strncmp("file ", p, 5) == 0 || strncmp("func ", p, 5) == 0) {
1920    // :breakadd file [lnum] <filename>
1921    // :breakadd func [lnum] <funcname>
1922    p += 4;
1923    p = skipwhite(p);
1924
1925    // skip line number (if specified)
1926    if (ascii_isdigit(*p)) {
1927      p = skipdigits(p);
1928      if (*p != ' ') {
1929        xp->xp_context = EXPAND_NOTHING;
1930        return NULL;
1931      }
1932      p = skipwhite(p);
1933    }
1934    if (strncmp("file", subcmd_start, 4) == 0) {
1935      xp->xp_context = EXPAND_FILES;
1936    } else {
1937      xp->xp_context = EXPAND_USER_FUNC;
1938    }
1939    xp->xp_pattern = (char *)p;
1940  } else if (strncmp("expr ", p, 5) == 0) {
1941    // :breakadd expr <expression>
1942    xp->xp_context = EXPAND_EXPRESSION;
1943    xp->xp_pattern = skipwhite(p + 5);
1944  }
1945
1946  return NULL;
1947}
1948
1949static const char *set_context_in_scriptnames_cmd(expand_T *xp, const char *arg)
1950{
1951  xp->xp_context = EXPAND_NOTHING;
1952  xp->xp_pattern = NULL;
1953
1954  char *p = skipwhite(arg);
1955  if (ascii_isdigit(*p)) {
1956    return NULL;
1957  }
1958
1959  xp->xp_context = EXPAND_SCRIPTNAMES;
1960  xp->xp_pattern = p;
1961
1962  return NULL;
1963}
1964
1965/// Set the completion context for the :filetype command. Always returns NULL.
1966static const char *set_context_in_filetype_cmd(expand_T *xp, const char *arg)
1967{
1968  xp->xp_context = EXPAND_FILETYPECMD;
1969  xp->xp_pattern = (char *)arg;
1970  filetype_expand_what = EXP_FILETYPECMD_ALL;
1971
1972  char *p = skipwhite(arg);
1973  if (*p == NUL) {
1974    return NULL;
1975  }
1976
1977  int val = 0;
1978
1979  while (true) {
1980    if (strncmp(p, "plugin", 6) == 0 && ascii_iswhite(p[6])) {
1981      val |= EXPAND_FILETYPECMD_PLUGIN;
1982      p = skipwhite(p + 6);
1983      continue;
1984    }
1985    if (strncmp(p, "indent", 6) == 0 && ascii_iswhite(p[6])) {
1986      val |= EXPAND_FILETYPECMD_INDENT;
1987      p = skipwhite(p + 6);
1988      continue;
1989    }
1990    break;
1991  }
1992
1993  if ((val & EXPAND_FILETYPECMD_PLUGIN) && (val & EXPAND_FILETYPECMD_INDENT)) {
1994    filetype_expand_what = EXP_FILETYPECMD_ONOFF;
1995  } else if ((val & EXPAND_FILETYPECMD_PLUGIN)) {
1996    filetype_expand_what = EXP_FILETYPECMD_INDENT;
1997  } else if ((val & EXPAND_FILETYPECMD_INDENT)) {
1998    filetype_expand_what = EXP_FILETYPECMD_PLUGIN;
1999  }
2000
2001  xp->xp_pattern = p;
2002
2003  return NULL;
2004}
2005
2006/// Sets the completion context for commands that involve a search pattern
2007/// and a line range (e.g., :s, :g, :v).
2008static void set_context_with_pattern(expand_T *xp)
2009{
2010  CmdlineInfo *ccline = get_cmdline_info();
2011
2012  emsg_off++;
2013  int skiplen = 0;
2014  int dummy, patlen;
2015  bool magic = p_magic;
2016  int retval = parse_pattern_and_range(&pre_incsearch_pos, &dummy, &skiplen, &patlen, &magic);
2017  emsg_off--;
2018
2019  // Check if cursor is within search pattern
2020  if (!retval || ccline->cmdpos <= skiplen || ccline->cmdpos > skiplen + patlen) {
2021    return;
2022  }
2023
2024  xp->xp_pattern = ccline->cmdbuff + skiplen;
2025  xp->xp_pattern_len = (size_t)(ccline->cmdpos - skiplen);
2026  xp->xp_context = EXPAND_PATTERN_IN_BUF;
2027  xp->xp_search_dir = FORWARD;
2028}
2029
2030/// Set the completion context in "xp" for command "cmd" with index "cmdidx".
2031/// The argument to the command is "arg" and the argument flags is "argt".
2032/// For user-defined commands and for environment variables, "context" has the
2033/// completion type.
2034///
2035/// @return  a pointer to the next command, or NULL if there is no next command.
2036static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, expand_T *xp,
2037                                          const char *arg, uint32_t argt, int context, bool forceit)
2038{
2039  const char *nextcmd;
2040
2041  switch (cmdidx) {
2042  case CMD_find:
2043  case CMD_sfind:
2044  case CMD_tabfind:
2045    if (xp->xp_context == EXPAND_FILES) {
2046      xp->xp_context = get_findfunc()->type !=
2047                       kCallbackNone ? EXPAND_FINDFUNC : EXPAND_FILES_IN_PATH;
2048    }
2049    break;
2050  case CMD_bcd:
2051  case CMD_bchdir:
2052  case CMD_cd:
2053  case CMD_chdir:
2054  case CMD_lcd:
2055  case CMD_lchdir:
2056  case CMD_tcd:
2057  case CMD_tchdir:
2058    if (xp->xp_context == EXPAND_FILES) {
2059      xp->xp_context = EXPAND_DIRS_IN_CDPATH;
2060    }
2061    break;
2062  case CMD_help:
2063    xp->xp_context = EXPAND_HELP;
2064    xp->xp_pattern = (char *)arg;
2065    break;
2066
2067  // Command modifiers: return the argument.
2068  // Also for commands with an argument that is a command.
2069  case CMD_aboveleft:
2070  case CMD_argdo:
2071  case CMD_belowright:
2072  case CMD_botright:
2073  case CMD_browse:
2074  case CMD_bufdo:
2075  case CMD_cdo:
2076  case CMD_cfdo:
2077  case CMD_confirm:
2078  case CMD_debug:
2079  case CMD_folddoclosed:
2080  case CMD_folddoopen:
2081  case CMD_hide:
2082  case CMD_horizontal:
2083  case CMD_keepalt:
2084  case CMD_keepjumps:
2085  case CMD_keepmarks:
2086  case CMD_keeppatterns:
2087  case CMD_ldo:
2088  case CMD_leftabove:
2089  case CMD_lfdo:
2090  case CMD_lockmarks:
2091  case CMD_noautocmd:
2092  case CMD_noswapfile:
2093  case CMD_restart:
2094  case CMD_rightbelow:
2095  case CMD_sandbox:
2096  case CMD_silent:
2097  case CMD_tab:
2098  case CMD_tabdo:
2099  case CMD_topleft:
2100  case CMD_unsilent:
2101  case CMD_verbose:
2102  case CMD_vertical:
2103  case CMD_windo:
2104    return arg;
2105
2106  case CMD_filter:
2107    return set_context_in_filter_cmd(xp, arg);
2108
2109  case CMD_match:
2110    return set_context_in_match_cmd(xp, arg);
2111
2112  // All completion for the +cmdline_compl feature goes here.
2113
2114  case CMD_command:
2115    return set_context_in_user_cmd(xp, arg);
2116
2117  case CMD_delcommand:
2118    xp->xp_context = EXPAND_USER_COMMANDS;
2119    xp->xp_pattern = (char *)arg;
2120    break;
2121
2122  case CMD_global:
2123  case CMD_vglobal:
2124    nextcmd = find_cmd_after_global_cmd(arg);
2125    if (!nextcmd && may_expand_pattern) {
2126      set_context_with_pattern(xp);
2127    }
2128    return nextcmd;
2129
2130  case CMD_and:
2131  case CMD_substitute:
2132    nextcmd = find_cmd_after_substitute_cmd(arg);
2133    if (!nextcmd && may_expand_pattern) {
2134      set_context_with_pattern(xp);
2135    }
2136    return nextcmd;
2137
2138  case CMD_isearch:
2139  case CMD_dsearch:
2140  case CMD_ilist:
2141  case CMD_dlist:
2142  case CMD_ijump:
2143  case CMD_psearch:
2144  case CMD_djump:
2145  case CMD_isplit:
2146  case CMD_dsplit:
2147    return find_cmd_after_isearch_cmd(xp, arg);
2148  case CMD_autocmd:
2149    return aucmd_set_expand_context(xp, (char *)arg, false);
2150
2151  case CMD_doautocmd:
2152  case CMD_doautoall:
2153    return aucmd_set_expand_context(xp, (char *)arg, true);
2154  case CMD_set:
2155    set_context_in_set_cmd(xp, (char *)arg, 0);
2156    break;
2157  case CMD_setglobal:
2158    set_context_in_set_cmd(xp, (char *)arg, OPT_GLOBAL);
2159    break;
2160  case CMD_setlocal:
2161    set_context_in_set_cmd(xp, (char *)arg, OPT_LOCAL);
2162    break;
2163  case CMD_tag:
2164  case CMD_stag:
2165  case CMD_ptag:
2166  case CMD_ltag:
2167  case CMD_tselect:
2168  case CMD_stselect:
2169  case CMD_ptselect:
2170  case CMD_tjump:
2171  case CMD_stjump:
2172  case CMD_ptjump:
2173    if (wop_flags & kOptWopFlagTagfile) {
2174      xp->xp_context = EXPAND_TAGS_LISTFILES;
2175    } else {
2176      xp->xp_context = EXPAND_TAGS;
2177    }
2178    xp->xp_pattern = (char *)arg;
2179    break;
2180  case CMD_augroup:
2181    xp->xp_context = EXPAND_AUGROUP;
2182    xp->xp_pattern = (char *)arg;
2183    break;
2184  case CMD_syntax:
2185    set_context_in_syntax_cmd(xp, arg);
2186    break;
2187  case CMD_const:
2188  case CMD_let:
2189  case CMD_if:
2190  case CMD_elseif:
2191  case CMD_while:
2192  case CMD_for:
2193  case CMD_echo:
2194  case CMD_echon:
2195  case CMD_execute:
2196  case CMD_echomsg:
2197  case CMD_echoerr:
2198  case CMD_call:
2199  case CMD_return:
2200  case CMD_cexpr:
2201  case CMD_caddexpr:
2202  case CMD_cgetexpr:
2203  case CMD_lexpr:
2204  case CMD_laddexpr:
2205  case CMD_lgetexpr:
2206    set_context_for_expression(xp, (char *)arg, cmdidx);
2207    break;
2208
2209  case CMD_unlet:
2210    return set_context_in_unlet_cmd(xp, arg);
2211  case CMD_function:
2212  case CMD_delfunction:
2213    xp->xp_context = EXPAND_USER_FUNC;
2214    xp->xp_pattern = (char *)arg;
2215    break;
2216
2217  case CMD_echohl:
2218    set_context_in_echohl_cmd(xp, arg);
2219    break;
2220  case CMD_highlight:
2221    set_context_in_highlight_cmd(xp, arg);
2222    break;
2223  case CMD_sign:
2224    set_context_in_sign_cmd(xp, (char *)arg);
2225    break;
2226  case CMD_bdelete:
2227  case CMD_bwipeout:
2228  case CMD_bunload:
2229    // NOLINTNEXTLINE(*-casting): remove once CI uses glibc 2.43
2230    while ((xp->xp_pattern = (char *)strchr(arg, ' ')) != NULL) {
2231      arg = xp->xp_pattern + 1;
2232    }
2233    FALLTHROUGH;
2234  case CMD_buffer:
2235  case CMD_sbuffer:
2236  case CMD_pbuffer:
2237  case CMD_checktime:
2238    xp->xp_context = EXPAND_BUFFERS;
2239    xp->xp_pattern = (char *)arg;
2240    break;
2241  case CMD_diffget:
2242  case CMD_diffput:
2243    // If current buffer is in diff mode, complete buffer names
2244    // which are in diff mode, and different than current buffer.
2245    xp->xp_context = EXPAND_DIFF_BUFFERS;
2246    xp->xp_pattern = (char *)arg;
2247    break;
2248
2249  case CMD_USER:
2250  case CMD_USER_BUF:
2251    return set_context_in_user_cmdarg(cmd, arg, argt, context, xp, forceit);
2252
2253  case CMD_map:
2254  case CMD_noremap:
2255  case CMD_nmap:
2256  case CMD_nnoremap:
2257  case CMD_vmap:
2258  case CMD_vnoremap:
2259  case CMD_omap:
2260  case CMD_onoremap:
2261  case CMD_imap:
2262  case CMD_inoremap:
2263  case CMD_cmap:
2264  case CMD_cnoremap:
2265  case CMD_lmap:
2266  case CMD_lnoremap:
2267  case CMD_smap:
2268  case CMD_snoremap:
2269  case CMD_xmap:
2270  case CMD_xnoremap:
2271    return set_context_in_map_cmd(xp, (char *)cmd, (char *)arg, forceit, false,
2272                                  false, cmdidx);
2273  case CMD_unmap:
2274  case CMD_nunmap:
2275  case CMD_vunmap:
2276  case CMD_ounmap:
2277  case CMD_iunmap:
2278  case CMD_cunmap:
2279  case CMD_lunmap:
2280  case CMD_sunmap:
2281  case CMD_xunmap:
2282    return set_context_in_map_cmd(xp, (char *)cmd, (char *)arg, forceit, false,
2283                                  true, cmdidx);
2284  case CMD_mapclear:
2285  case CMD_nmapclear:
2286  case CMD_vmapclear:
2287  case CMD_omapclear:
2288  case CMD_imapclear:
2289  case CMD_cmapclear:
2290  case CMD_lmapclear:
2291  case CMD_smapclear:
2292  case CMD_xmapclear:
2293    xp->xp_context = EXPAND_MAPCLEAR;
2294    xp->xp_pattern = (char *)arg;
2295    break;
2296
2297  case CMD_abbreviate:
2298  case CMD_noreabbrev:
2299  case CMD_cabbrev:
2300  case CMD_cnoreabbrev:
2301  case CMD_iabbrev:
2302  case CMD_inoreabbrev:
2303    return set_context_in_map_cmd(xp, (char *)cmd, (char *)arg, forceit, true,
2304                                  false, cmdidx);
2305  case CMD_unabbreviate:
2306  case CMD_cunabbrev:
2307  case CMD_iunabbrev:
2308    return set_context_in_map_cmd(xp, (char *)cmd, (char *)arg, forceit, true,
2309                                  true, cmdidx);
2310  case CMD_menu:
2311  case CMD_noremenu:
2312  case CMD_unmenu:
2313  case CMD_amenu:
2314  case CMD_anoremenu:
2315  case CMD_aunmenu:
2316  case CMD_nmenu:
2317  case CMD_nnoremenu:
2318  case CMD_nunmenu:
2319  case CMD_vmenu:
2320  case CMD_vnoremenu:
2321  case CMD_vunmenu:
2322  case CMD_omenu:
2323  case CMD_onoremenu:
2324  case CMD_ounmenu:
2325  case CMD_imenu:
2326  case CMD_inoremenu:
2327  case CMD_iunmenu:
2328  case CMD_cmenu:
2329  case CMD_cnoremenu:
2330  case CMD_cunmenu:
2331  case CMD_tlmenu:
2332  case CMD_tlnoremenu:
2333  case CMD_tlunmenu:
2334  case CMD_tmenu:
2335  case CMD_tunmenu:
2336  case CMD_popup:
2337  case CMD_emenu:
2338    return set_context_in_menu_cmd(xp, cmd, (char *)arg, forceit);
2339
2340  case CMD_colorscheme:
2341    xp->xp_context = EXPAND_COLORS;
2342    xp->xp_pattern = (char *)arg;
2343    break;
2344
2345  case CMD_compiler:
2346    xp->xp_context = EXPAND_COMPILER;
2347    xp->xp_pattern = (char *)arg;
2348    break;
2349
2350  case CMD_ownsyntax:
2351    xp->xp_context = EXPAND_OWNSYNTAX;
2352    xp->xp_pattern = (char *)arg;
2353    break;
2354
2355  case CMD_setfiletype:
2356    xp->xp_context = EXPAND_FILETYPE;
2357    xp->xp_pattern = (char *)arg;
2358    break;
2359
2360  case CMD_packadd:
2361    xp->xp_context = EXPAND_PACKADD;
2362    xp->xp_pattern = (char *)arg;
2363    break;
2364
2365  case CMD_runtime:
2366    set_context_in_runtime_cmd(xp, arg);
2367    break;
2368
2369  case CMD_language:
2370    return set_context_in_lang_cmd(xp, arg);
2371
2372  case CMD_profile:
2373    set_context_in_profile_cmd(xp, arg);
2374    break;
2375  case CMD_checkhealth:
2376    xp->xp_context = EXPAND_CHECKHEALTH;
2377    break;
2378
2379  case CMD_marks:
2380    xp->xp_context = EXPAND_MARKS;
2381    break;
2382
2383  case CMD_log:
2384    xp->xp_context = EXPAND_LOG;
2385    break;
2386
2387  case CMD_lsp:
2388    xp->xp_context = EXPAND_LSP;
2389    break;
2390
2391  case CMD_packdel:
2392    xp->xp_context = EXPAND_PACKDEL;
2393    break;
2394
2395  case CMD_packupdate:
2396    xp->xp_context = EXPAND_PACKUPDATE;
2397    break;
2398
2399  case CMD_retab:
2400    xp->xp_context = EXPAND_RETAB;
2401    xp->xp_pattern = (char *)arg;
2402    break;
2403
2404  case CMD_messages:
2405    xp->xp_context = EXPAND_MESSAGES;
2406    xp->xp_pattern = (char *)arg;
2407    break;
2408
2409  case CMD_history:
2410    xp->xp_context = EXPAND_HISTORY;
2411    xp->xp_pattern = (char *)arg;
2412    break;
2413  case CMD_syntime:
2414    xp->xp_context = EXPAND_SYNTIME;
2415    xp->xp_pattern = (char *)arg;
2416    break;
2417
2418  case CMD_argdelete:
2419    while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL) {
2420      arg = (xp->xp_pattern + 1);
2421    }
2422    xp->xp_context = EXPAND_ARGLIST;
2423    xp->xp_pattern = (char *)arg;
2424    break;
2425
2426  case CMD_breakadd:
2427  case CMD_profdel:
2428  case CMD_breakdel:
2429    return set_context_in_breakadd_cmd(xp, arg, cmdidx);
2430
2431  case CMD_scriptnames:
2432    return set_context_in_scriptnames_cmd(xp, arg);
2433
2434  case CMD_filetype:
2435    return set_context_in_filetype_cmd(xp, arg);
2436
2437  case CMD_lua:
2438  case CMD_equal:
2439    xp->xp_context = EXPAND_LUA;
2440    break;
2441
2442  default:
2443    break;
2444  }
2445  return NULL;
2446}
2447
2448/// This is all pretty much copied from do_one_cmd(), with all the extra stuff
2449/// we don't need/want deleted.  Maybe this could be done better if we didn't
2450/// repeat all this stuff.  The only problem is that they may not stay
2451/// perfectly compatible with each other, but then the command line syntax
2452/// probably won't change that much -- webb.
2453///
2454/// @param buff  buffer for command string
2455static const char *set_one_cmd_context(expand_T *xp, const char *buff)
2456{
2457  size_t len = 0;
2458  exarg_T ea;
2459  int context = EXPAND_NOTHING;
2460  bool forceit = false;
2461  bool usefilter = false;  // Filter instead of file name.
2462
2463  ExpandInit(xp);
2464  xp->xp_pattern = (char *)buff;
2465  xp->xp_line = (char *)buff;
2466  xp->xp_context = EXPAND_COMMANDS;  // Default until we get past command
2467  ea.argt = 0;
2468
2469  // 1. skip comment lines and leading space, colons or bars
2470  const char *cmd;
2471  for (cmd = buff; vim_strchr(" \t:|", (uint8_t)(*cmd)) != NULL; cmd++) {}
2472  xp->xp_pattern = (char *)cmd;
2473
2474  if (*cmd == NUL) {
2475    return NULL;
2476  }
2477  if (*cmd == '"') {  // ignore comment lines
2478    xp->xp_context = EXPAND_NOTHING;
2479    return NULL;
2480  }
2481
2482  // 3. skip over a range specifier of the form: addr [,addr] [;addr] ..
2483  cmd = skip_range(cmd, &xp->xp_context);
2484  xp->xp_pattern = (char *)cmd;
2485  if (*cmd == NUL) {
2486    return NULL;
2487  }
2488  if (*cmd == '"') {
2489    xp->xp_context = EXPAND_NOTHING;
2490    return NULL;
2491  }
2492
2493  if (*cmd == '|' || *cmd == '\n') {
2494    return cmd + 1;  // There's another command
2495  }
2496
2497  // Get the command index.
2498  const char *p = set_cmd_index(cmd, &ea, xp, &context);
2499  if (p == NULL) {
2500    return NULL;
2501  }
2502
2503  xp->xp_context = EXPAND_NOTHING;  // Default now that we're past command
2504
2505  if (*p == '!') {  // forced commands
2506    forceit = true;
2507    p++;
2508  }
2509
2510  // 6. parse arguments
2511  if (!IS_USER_CMDIDX(ea.cmdidx)) {
2512    ea.argt = excmd_get_argt(ea.cmdidx);
2513  }
2514
2515  const char *arg = skipwhite(p);
2516
2517  // Does command allow "++argopt" argument?
2518  if (ea.argt & EX_ARGOPT) {
2519    while (*arg != NUL && strncmp(arg, "++", 2) == 0) {
2520      p = arg + 2;
2521      while (*p && !ascii_isspace(*p)) {
2522        MB_PTR_ADV(p);
2523      }
2524
2525      // Still touching the command after "++"?
2526      if (*p == NUL) {
2527        if (ea.argt & EX_ARGOPT) {
2528          return set_context_in_argopt(xp, arg + 2);
2529        }
2530      }
2531
2532      arg = skipwhite(p);
2533    }
2534  }
2535
2536  if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update) {
2537    if (*arg == '>') {  // append
2538      if (*++arg == '>') {
2539        arg++;
2540      }
2541      arg = skipwhite(arg);
2542    } else if (*arg == '!' && ea.cmdidx == CMD_write) {  // :w !filter
2543      arg++;
2544      usefilter = true;
2545    }
2546  }
2547
2548  if (ea.cmdidx == CMD_read) {
2549    usefilter = forceit;  // :r! filter if forced
2550    if (*arg == '!') {    // :r !filter
2551      arg++;
2552      usefilter = true;
2553    }
2554  }
2555
2556  if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift) {
2557    while (*arg == *cmd) {  // allow any number of '>' or '<'
2558      arg++;
2559    }
2560    arg = skipwhite(arg);
2561  }
2562
2563  // Does command allow "+command"?
2564  if ((ea.argt & EX_CMDARG) && !usefilter && *arg == '+') {
2565    // Check if we're in the +command
2566    p = arg + 1;
2567    arg = skip_cmd_arg((char *)arg, false);
2568
2569    // Still touching the command after '+'?
2570    if (*arg == NUL) {
2571      return p;
2572    }
2573
2574    // Skip space(s) after +command to get to the real argument.
2575    arg = skipwhite(arg);
2576  }
2577
2578  // Check for '|' to separate commands and '"' to start comments.
2579  // Don't do this for ":read !cmd" and ":write !cmd".
2580  if ((ea.argt & EX_TRLBAR) && !usefilter) {
2581    p = arg;
2582    // ":redir @" is not the start of a comment
2583    if (ea.cmdidx == CMD_redir && p[0] == '@' && p[1] == '"') {
2584      p += 2;
2585    }
2586    while (*p) {
2587      if (*p == Ctrl_V) {
2588        if (p[1] != NUL) {
2589          p++;
2590        }
2591      } else if ((*p == '"' && !(ea.argt & EX_NOTRLCOM))
2592                 || *p == '|'
2593                 || *p == '\n') {
2594        if (*(p - 1) != '\\') {
2595          if (*p == '|' || *p == '\n') {
2596            return p + 1;
2597          }
2598          return NULL;  // It's a comment
2599        }
2600      }
2601      MB_PTR_ADV(p);
2602    }
2603  }
2604
2605  if (!(ea.argt & EX_EXTRA) && *arg != NUL && strchr("|\"", *arg) == NULL) {
2606    // no arguments allowed but there is something
2607    return NULL;
2608  }
2609
2610  // Find start of last argument (argument just before cursor):
2611  p = buff;
2612  xp->xp_pattern = (char *)p;
2613  len = strlen(buff);
2614  while (*p && p < buff + len) {
2615    if (*p == ' ' || *p == TAB) {
2616      // argument starts after a space
2617      xp->xp_pattern = (char *)++p;
2618    } else {
2619      if (*p == '\\' && *(p + 1) != NUL) {
2620        p++;  // skip over escaped character
2621      }
2622      MB_PTR_ADV(p);
2623    }
2624  }
2625
2626  if (ea.argt & EX_XFILE) {
2627    set_context_for_wildcard_arg(&ea, arg, usefilter, xp, &context);
2628  }
2629
2630  // Switch on command name.
2631  return set_context_by_cmdname(cmd, ea.cmdidx, xp, arg, ea.argt, context, forceit);
2632}
2633
2634/// Set the completion context in "xp" for command "str"
2635///
2636/// @param str  start of command line
2637/// @param len  length of command line (excl. NUL)
2638/// @param col  position of cursor
2639/// @param use_ccline  use ccline for info
2640void set_cmd_context(expand_T *xp, char *str, int len, int col, int use_ccline)
2641{
2642  CmdlineInfo *const ccline = get_cmdline_info();
2643  char old_char = NUL;
2644
2645  // Only save and overwrite the character when it is not the NUL terminator
2646  // already.  "str" may be a read-only empty string: tv_get_string() falls
2647  // back to a "" literal for a NULL string or on a type error, and writing
2648  // at "col" would then crash.
2649  // This also avoids a UMR warning from Purify.
2650  if (col < len) {
2651    old_char = str[col];
2652    str[col] = NUL;
2653  }
2654  const char *nextcomm = str;
2655
2656  if (use_ccline && ccline->cmdfirstc == '=') {
2657    // pass CMD_SIZE because there is no real command
2658    set_context_for_expression(xp, str, CMD_SIZE);
2659  } else if (use_ccline && ccline->input_fn) {
2660    xp->xp_context = ccline->xp_context;
2661    xp->xp_pattern = ccline->cmdbuff;
2662    xp->xp_arg = ccline->xp_arg;
2663    if (xp->xp_context == EXPAND_SHELLCMDLINE) {
2664      int context = xp->xp_context;
2665      set_context_for_wildcard_arg(NULL, xp->xp_pattern, false, xp, &context);
2666    }
2667  } else {
2668    while (nextcomm != NULL) {
2669      nextcomm = set_one_cmd_context(xp, nextcomm);
2670    }
2671  }
2672
2673  // Store the string here so that call_user_expand_func() can get to them
2674  // easily.
2675  xp->xp_line = str;
2676  xp->xp_col = col;
2677
2678  if (col < len) {
2679    str[col] = old_char;
2680  }
2681}
2682
2683/// Expand the command line "str" from context "xp".
2684/// "xp" must have been set by set_cmd_context().
2685/// xp->xp_pattern points into "str", to where the text that is to be expanded
2686/// starts.
2687/// Returns EXPAND_UNSUCCESSFUL when there is something illegal before the
2688/// cursor.
2689/// Returns EXPAND_NOTHING when there is nothing to expand, might insert the
2690/// key that triggered expansion literally.
2691/// Returns EXPAND_OK otherwise.
2692///
2693/// @param str  start of command line
2694/// @param col  position of cursor
2695/// @param matchcount  return: nr of matches
2696/// @param matches  return: array of pointers to matches
2697int expand_cmdline(expand_T *xp, const char *str, int col, int *matchcount, char ***matches)
2698{
2699  char *file_str = NULL;
2700  int options = WILD_ADD_SLASH|WILD_SILENT;
2701
2702  if (xp->xp_context == EXPAND_UNSUCCESSFUL) {
2703    beep_flush();
2704    return EXPAND_UNSUCCESSFUL;      // Something illegal on command line
2705  }
2706  if (xp->xp_context == EXPAND_NOTHING) {
2707    // Caller can use the character as a normal char instead
2708    return EXPAND_NOTHING;
2709  }
2710
2711  // add star to file name, or convert to regexp if not exp. files.
2712  assert((str + col) - xp->xp_pattern >= 0);
2713  xp->xp_pattern_len = (size_t)((str + col) - xp->xp_pattern);
2714  if (cmdline_fuzzy_completion_supported(xp)) {
2715    // If fuzzy matching, don't modify the search string
2716    file_str = xstrdup(xp->xp_pattern);
2717  } else {
2718    file_str = addstar(xp->xp_pattern, xp->xp_pattern_len, xp->xp_context);
2719  }
2720
2721  if (p_wic) {
2722    options += WILD_ICASE;
2723  }
2724
2725  // find all files that match the description
2726  if (ExpandFromContext(xp, file_str, matches, matchcount, options) == FAIL) {
2727    *matchcount = 0;
2728    *matches = NULL;
2729  }
2730  xfree(file_str);
2731
2732  return EXPAND_OK;
2733}
2734
2735/// Expand file or directory names.
2736static int expand_files_and_dirs(expand_T *xp, char *pat, char ***matches, int *numMatches,
2737                                 int flags, int options)
2738{
2739  bool free_pat = false;
2740
2741  // for ":set path=" and ":set tags=" halve backslashes for escaped space
2742  if (xp->xp_backslash != XP_BS_NONE) {
2743    free_pat = true;
2744    size_t pat_len = strlen(pat);
2745    pat = xstrnsave(pat, pat_len);
2746
2747    char *pat_end = pat + pat_len;
2748    for (char *p = pat; *p != NUL; p++) {
2749      if (*p != '\\') {
2750        continue;
2751      }
2752
2753      if (xp->xp_backslash & XP_BS_THREE
2754          && *(p + 1) == '\\'
2755          && *(p + 2) == '\\'
2756          && *(p + 3) == ' ') {
2757        char *from = p + 3;
2758        memmove(p, from, (size_t)(pat_end - from) + 1);  // +1 for NUL
2759        pat_end -= 3;
2760      } else if (xp->xp_backslash & XP_BS_ONE
2761                 && *(p + 1) == ' ') {
2762        char *from = p + 1;
2763        memmove(p, from, (size_t)(pat_end - from) + 1);  // +1 for NUL
2764        pat_end--;
2765      } else if (xp->xp_backslash & XP_BS_COMMA) {
2766        if (*(p + 1) == '\\' && *(p + 2) == ',') {
2767          char *from = p + 2;
2768          memmove(p, from, (size_t)(pat_end - from) + 1);  // +1 for NUL
2769          pat_end -= 2;
2770#ifdef BACKSLASH_IN_FILENAME
2771        } else if (*(p + 1) == ',') {
2772          char *from = p + 1;
2773          memmove(p, from, (size_t)(pat_end - from) + 1);  // +1 for NUL
2774          pat_end--;
2775#endif
2776        }
2777      }
2778    }
2779  }
2780
2781  int ret = FAIL;
2782  if (xp->xp_context == EXPAND_FINDFUNC) {
2783    ret = expand_findfunc(xp, pat, matches, numMatches);
2784  } else {
2785    if (xp->xp_context == EXPAND_FILES) {
2786      flags |= EW_FILE;
2787    } else if (xp->xp_context == EXPAND_FILES_IN_PATH) {
2788      flags |= (EW_FILE | EW_PATH);
2789    } else if (xp->xp_context == EXPAND_DIRS_IN_CDPATH) {
2790      flags = (flags | EW_DIR | EW_CDPATH) & ~EW_FILE;
2791    } else {
2792      flags = (flags | EW_DIR) & ~EW_FILE;
2793    }
2794    if (options & WILD_ICASE) {
2795      flags |= EW_ICASE;
2796    }
2797    // Expand wildcards, supporting %:h and the like.
2798    ret = expand_wildcards_eval(&pat, numMatches, matches, flags);
2799  }
2800  if (free_pat) {
2801    xfree(pat);
2802  }
2803#ifdef BACKSLASH_IN_FILENAME
2804  if (((options & WILD_USE_SHELLSLASH) && !p_ssl)
2805      || ((options & WILD_USE_COMPLETESLASH)
2806          && ((p_csl[0] == NUL && !p_ssl) || p_csl[0] == 'b'))) {
2807    for (int j = 0; j < *numMatches; j++) {
2808      char *ptr = (*matches)[j];
2809      for (; *ptr; ptr++) {
2810        if (*ptr == PATHSEP) {
2811          *ptr = '\\';
2812        }
2813      }
2814    }
2815  }
2816#endif
2817  return ret;
2818}
2819
2820/// Function given to ExpandGeneric() to obtain the possible arguments of the
2821/// ":filetype {plugin,indent}" command.
2822static char *get_filetypecmd_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx)
2823{
2824  if (idx < 0) {
2825    return NULL;
2826  }
2827
2828  if (filetype_expand_what == EXP_FILETYPECMD_ALL && idx < 5) {
2829    char *opts_all[] = { "detect", "indent", "plugin", "on", "off" };
2830    return opts_all[idx];
2831  }
2832  if (filetype_expand_what == EXP_FILETYPECMD_PLUGIN && idx < 3) {
2833    char *opts_plugin[] = { "plugin", "on", "off" };
2834    return opts_plugin[idx];
2835  }
2836  if (filetype_expand_what == EXP_FILETYPECMD_INDENT && idx < 3) {
2837    char *opts_indent[] = { "indent", "on", "off" };
2838    return opts_indent[idx];
2839  }
2840  if (filetype_expand_what == EXP_FILETYPECMD_ONOFF && idx < 2) {
2841    char *opts_onoff[] = { "on", "off" };
2842    return opts_onoff[idx];
2843  }
2844  return NULL;
2845}
2846
2847/// Function given to ExpandGeneric() to obtain the possible arguments of the
2848/// ":breakadd {expr, file, func, here}" command.
2849/// ":breakdel {func, file, here}" command.
2850static char *get_breakadd_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx)
2851{
2852  if (idx >= 0 && idx <= 3) {
2853    char *opts[] = { "expr", "file", "func", "here" };
2854
2855    // breakadd {expr, file, func, here}
2856    if (breakpt_expand_what == EXP_BREAKPT_ADD) {
2857      return opts[idx];
2858    } else if (breakpt_expand_what == EXP_BREAKPT_DEL) {
2859      // breakdel {func, file, here}
2860      if (idx <= 2) {
2861        return opts[idx + 1];
2862      }
2863    } else {
2864      // profdel {func, file}
2865      if (idx <= 1) {
2866        return opts[idx + 1];
2867      }
2868    }
2869  }
2870  return NULL;
2871}
2872
2873/// Function given to ExpandGeneric() to obtain the possible arguments for the
2874/// ":scriptnames" command.
2875static char *get_scriptnames_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx)
2876{
2877  if (!SCRIPT_ID_VALID(idx + 1)) {
2878    return NULL;
2879  }
2880
2881  scriptitem_T *si = SCRIPT_ITEM(idx + 1);
2882  home_replace(NULL, si->sn_name, NameBuff, MAXPATHL, true);
2883  return NameBuff;
2884}
2885
2886/// Function given to ExpandGeneric() to obtain the possible arguments of the
2887/// ":retab {-indentonly}" option.
2888static char *get_retab_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx)
2889{
2890  if (idx == 0) {
2891    return "-indentonly";
2892  }
2893  return NULL;
2894}
2895
2896/// Function given to ExpandGeneric() to obtain the possible arguments of the
2897/// ":messages {clear}" command.
2898static char *get_messages_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx)
2899{
2900  if (idx == 0) {
2901    return "clear";
2902  }
2903  return NULL;
2904}
2905
2906static char *get_mapclear_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx)
2907{
2908  if (idx == 0) {
2909    return "<buffer>";
2910  }
2911  return NULL;
2912}
2913
2914/// Completion for |:checkhealth| command.
2915///
2916/// Given to ExpandGeneric() to obtain all available heathcheck names.
2917/// @param[in] idx  Index of the healthcheck item.
2918/// @param[in] xp  Not used.
2919static char *get_healthcheck_names(expand_T *xp FUNC_ATTR_UNUSED, int idx)
2920{
2921  static Object names = OBJECT_INIT;
2922  static unsigned last_gen = 0;
2923
2924  if (last_gen != get_cmdline_last_prompt_id() || last_gen == 0) {
2925    Array a = ARRAY_DICT_INIT;
2926    Error err = ERROR_INIT;
2927    Object res = NLUA_EXEC_STATIC("return vim.health._complete()", a, kRetObject, NULL, &err);
2928    api_clear_error(&err);
2929    api_free_object(names);
2930    names = res;
2931    last_gen = get_cmdline_last_prompt_id();
2932  }
2933
2934  if (names.type == kObjectTypeArray && idx < (int)names.data.array.size
2935      && names.data.array.items[idx].type == kObjectTypeString) {
2936    return names.data.array.items[idx].data.string.data;
2937  }
2938  return NULL;
2939}
2940
2941/// Completes arg1 via Lua.
2942///
2943/// @param[in] lua Lua script.
2944/// @param[in] xp  Expandy thing 🤷
2945/// @param[in] idx Index of the item.
2946static char *get_arg1_from_lua(char *lua, expand_T *xp, int idx)
2947{
2948  static Object names = OBJECT_INIT;
2949  static char *last_xp_line = NULL;
2950  static unsigned last_gen = 0;
2951
2952  if (last_xp_line == NULL || strcmp(last_xp_line, xp->xp_line) != 0
2953      || last_gen != get_cmdline_last_prompt_id()) {
2954    xfree(last_xp_line);
2955    last_xp_line = xstrdup(xp->xp_line);
2956    MAXSIZE_TEMP_ARRAY(args, 2);
2957    Error err = ERROR_INIT;
2958
2959    ADD_C(args, CSTR_AS_OBJ(xp->xp_pattern));
2960    ADD_C(args, CSTR_AS_OBJ(xp->xp_line));
2961    // Build the current command line as a Lua string argument
2962    Object res = nlua_exec(cstr_as_string(lua), NULL, args, kRetObject, NULL, &err);
2963    api_clear_error(&err);
2964    api_free_object(names);
2965    names = res;
2966    last_gen = get_cmdline_last_prompt_id();
2967  }
2968
2969  if (names.type == kObjectTypeArray && idx < (int)names.data.array.size
2970      && names.data.array.items[idx].type == kObjectTypeString) {
2971    return names.data.array.items[idx].data.string.data;
2972  }
2973  return NULL;
2974}
2975
2976/// Completion for the |:marks| command. Given to ExpandGeneric().
2977/// @param[in] xp  Expandy thing 🤷
2978/// @param[in] idx  Index of the item.
2979static char *get_marks_arg(expand_T *xp, int idx)
2980{
2981  return get_arg1_from_lua("return require'vim._core.marks'.complete(...)", xp, idx);
2982}
2983
2984/// Completion for |:log| command. Given to ExpandGeneric().
2985/// @param[in] xp  Expandy thing 🤷
2986/// @param[in] idx  Index of the item.
2987static char *get_log_arg(expand_T *xp, int idx)
2988{
2989  return get_arg1_from_lua("return require'vim._core.ex_cmd'.log_complete(...)", xp, idx);
2990}
2991
2992/// Completion for |:lsp| command. Given to ExpandGeneric().
2993/// @param[in] xp  Expandy thing 🤷
2994/// @param[in] idx  Index of the item.
2995static char *get_lsp_arg(expand_T *xp, int idx)
2996{
2997  return get_arg1_from_lua("return require'vim._core.ex_cmd'.lsp_complete(...)", xp, idx);
2998}
2999
3000/// Completion for |:packdel| command. Given to ExpandGeneric().
3001/// @param[in] xp  Expandy thing.
3002/// @param[in] idx  Index of the item.
3003static char *get_packdel_arg(expand_T *xp, int idx)
3004{
3005  return get_arg1_from_lua("return require'vim._core.ex_cmd'.packdel_complete(...)", xp, idx);
3006}
3007
3008/// Completion for |:packupdate| command. Given to ExpandGeneric().
3009/// @param[in] xp  Expandy thing.
3010/// @param[in] idx  Index of the item.
3011static char *get_packupdate_arg(expand_T *xp, int idx)
3012{
3013  return get_arg1_from_lua("return require'vim._core.ex_cmd'.packupdate_complete(...)", xp, idx);
3014}
3015
3016/// Do the expansion based on xp->xp_context and "rmp".
3017static int ExpandOther(char *pat, expand_T *xp, regmatch_T *rmp, char ***matches, int *numMatches)
3018{
3019  typedef CompleteListItemGetter ExpandFunc;
3020  static struct expgen {
3021    int context;
3022    ExpandFunc func;
3023    int ic;
3024    int escaped;
3025  } tab[] = {
3026    { EXPAND_COMMANDS, get_command_name, false, true },
3027    { EXPAND_FILETYPECMD, get_filetypecmd_arg, true, true },
3028    { EXPAND_MAPCLEAR, get_mapclear_arg, true, true },
3029    { EXPAND_MESSAGES, get_messages_arg, true, true },
3030    { EXPAND_HISTORY, get_history_arg, true, true },
3031    { EXPAND_USER_COMMANDS, get_user_commands, false, true },
3032    { EXPAND_USER_ADDR_TYPE, get_user_cmd_addr_type, false, true },
3033    { EXPAND_USER_CMD_FLAGS, get_user_cmd_flags, false, true },
3034    { EXPAND_USER_NARGS, get_user_cmd_nargs, false, true },
3035    { EXPAND_USER_COMPLETE, get_user_cmd_complete, false, true },
3036    { EXPAND_USER_VARS, get_user_var_name, false, true },
3037    { EXPAND_FUNCTIONS, get_function_name, false, true },
3038    { EXPAND_USER_FUNC, get_user_func_name, false, true },
3039    { EXPAND_EXPRESSION, get_expr_name, false, true },
3040    { EXPAND_MENUS, get_menu_name, false, true },
3041    { EXPAND_MENUNAMES, get_menu_names, false, true },
3042    { EXPAND_SYNTAX, get_syntax_name, true, true },
3043    { EXPAND_SYNTIME, get_syntime_arg, true, true },
3044    { EXPAND_HIGHLIGHT, get_highlight_name, true, false },
3045    { EXPAND_EVENTS, expand_get_event_name, true, false },
3046    { EXPAND_AUGROUP, expand_get_augroup_name, true, false },
3047    { EXPAND_SIGN, get_sign_name, true, true },
3048    { EXPAND_PROFILE, get_profile_name, true, true },
3049    { EXPAND_LANGUAGE, get_lang_arg, true, false },
3050    { EXPAND_LOCALES, get_locales, true, false },
3051    { EXPAND_ENV_VARS, get_env_name, true, true },
3052    { EXPAND_USER, get_users, true, false },
3053    { EXPAND_ARGLIST, get_arglist_name, true, false },
3054    { EXPAND_BREAKPOINT, get_breakadd_arg, true, true },
3055    { EXPAND_SCRIPTNAMES, get_scriptnames_arg, true, false },
3056    { EXPAND_RETAB, get_retab_arg, true, true },
3057    { EXPAND_CHECKHEALTH, get_healthcheck_names, true, false },
3058    { EXPAND_MARKS, get_marks_arg, true, false },
3059    { EXPAND_LOG, get_log_arg, true, false },
3060    { EXPAND_LSP, get_lsp_arg, true, false },
3061    { EXPAND_PACKDEL, get_packdel_arg, true, false },
3062    { EXPAND_PACKUPDATE, get_packupdate_arg, true, false },
3063  };
3064  int ret = FAIL;
3065
3066  // Find a context in the table and call the ExpandGeneric() with the
3067  // right function to do the expansion.
3068  for (int i = 0; i < (int)ARRAY_SIZE(tab); i++) {
3069    if (xp->xp_context == tab[i].context) {
3070      if (tab[i].ic) {
3071        rmp->rm_ic = true;
3072      }
3073      ExpandGeneric(pat, xp, rmp, matches, numMatches, tab[i].func, tab[i].escaped);
3074      ret = OK;
3075      break;
3076    }
3077  }
3078
3079  return ret;
3080}
3081
3082/// Map wild expand options to flags for expand_wildcards()
3083static int map_wildopts_to_ewflags(int options)
3084{
3085  int flags = EW_DIR;       // include directories
3086  if (options & WILD_LIST_NOTFOUND) {
3087    flags |= EW_NOTFOUND;
3088  }
3089  if (options & WILD_ADD_SLASH) {
3090    flags |= EW_ADDSLASH;
3091  }
3092  if (options & WILD_KEEP_ALL) {
3093    flags |= EW_KEEPALL;
3094  }
3095  if (options & WILD_SILENT) {
3096    flags |= EW_SILENT;
3097  }
3098  if (options & WILD_NOERROR) {
3099    flags |= EW_NOERROR;
3100  }
3101  if (options & WILD_ALLLINKS) {
3102    flags |= EW_ALLLINKS;
3103  }
3104
3105  return flags;
3106}
3107
3108/// Do the expansion based on xp->xp_context and "pat".
3109///
3110/// @param options  WILD_ flags
3111static int ExpandFromContext(expand_T *xp, char *pat, char ***matches, int *numMatches, int options)
3112{
3113  regmatch_T regmatch = { .rm_ic = false };
3114  int ret;
3115  int flags = map_wildopts_to_ewflags(options);
3116  const bool fuzzy = cmdline_fuzzy_complete(pat)
3117                     && cmdline_fuzzy_completion_supported(xp);
3118
3119  if (xp->xp_context == EXPAND_FILES
3120      || xp->xp_context == EXPAND_DIRECTORIES
3121      || xp->xp_context == EXPAND_FILES_IN_PATH
3122      || xp->xp_context == EXPAND_FINDFUNC
3123      || xp->xp_context == EXPAND_DIRS_IN_CDPATH) {
3124    return expand_files_and_dirs(xp, pat, matches, numMatches, flags, options);
3125  }
3126
3127  *matches = NULL;
3128  *numMatches = 0;
3129  if (xp->xp_context == EXPAND_HELP) {
3130    // With an empty argument we would get all the help tags, which is
3131    // very slow.  Get matches for "help" instead.
3132    if (find_help_tags(*pat == NUL ? "help" : pat,
3133                       numMatches, matches, false) == OK) {
3134      cleanup_help_tags(*numMatches, *matches);
3135      return OK;
3136    }
3137    return FAIL;
3138  }
3139
3140  if (xp->xp_context == EXPAND_SHELLCMD) {
3141    expand_shellcmd(pat, matches, numMatches, flags);
3142    return OK;
3143  }
3144  if (xp->xp_context == EXPAND_OLD_SETTING) {
3145    return ExpandOldSetting(numMatches, matches);
3146  }
3147  if (xp->xp_context == EXPAND_BUFFERS) {
3148    return ExpandBufnames(pat, numMatches, matches, options);
3149  }
3150  if (xp->xp_context == EXPAND_DIFF_BUFFERS) {
3151    return ExpandBufnames(pat, numMatches, matches, options | BUF_DIFF_FILTER);
3152  }
3153  if (xp->xp_context == EXPAND_TAGS
3154      || xp->xp_context == EXPAND_TAGS_LISTFILES) {
3155    return expand_tags(xp->xp_context == EXPAND_TAGS, pat, numMatches, matches);
3156  }
3157  if (xp->xp_context == EXPAND_COLORS) {
3158    char *directories[] = { "colors", NULL };
3159    return ExpandRTDir(pat, DIP_START + DIP_OPT, numMatches, matches, directories);
3160  }
3161  if (xp->xp_context == EXPAND_COMPILER) {
3162    char *directories[] = { "compiler", NULL };
3163    return ExpandRTDir(pat, 0, numMatches, matches, directories);
3164  }
3165  if (xp->xp_context == EXPAND_OWNSYNTAX) {
3166    char *directories[] = { "syntax", NULL };
3167    return ExpandRTDir(pat, 0, numMatches, matches, directories);
3168  }
3169  if (xp->xp_context == EXPAND_FILETYPE) {
3170    char *directories[] = { "syntax", "indent", "ftplugin", NULL };
3171    return ExpandRTDir(pat, 0, numMatches, matches, directories);
3172  }
3173  if (xp->xp_context == EXPAND_KEYMAP) {
3174    char *directories[] = { "keymap", NULL };
3175    return ExpandRTDir(pat, 0, numMatches, matches, directories);
3176  }
3177  if (xp->xp_context == EXPAND_USER_LIST) {
3178    return ExpandUserList(xp, matches, numMatches);
3179  }
3180  if (xp->xp_context == EXPAND_USER_LUA) {
3181    return ExpandUserLua(xp, numMatches, matches);
3182  }
3183  if (xp->xp_context == EXPAND_PACKADD) {
3184    return ExpandPackAddDir(pat, numMatches, matches);
3185  }
3186  if (xp->xp_context == EXPAND_RUNTIME) {
3187    return expand_runtime_cmd(pat, numMatches, matches);
3188  }
3189  if (xp->xp_context == EXPAND_PATTERN_IN_BUF) {
3190    return expand_pattern_in_buf(pat, xp->xp_search_dir, matches, numMatches);
3191  }
3192
3193  // When expanding a function name starting with s:, match the <SNR>nr_
3194  // prefix.
3195  char *tofree = NULL;
3196  if (xp->xp_context == EXPAND_USER_FUNC && strncmp(pat, "^s:", 3) == 0) {
3197    const size_t len = strlen(pat) + 20;
3198
3199    tofree = xmalloc(len);
3200    snprintf(tofree, len, "^<SNR>\\d\\+_%s", pat + 3);
3201    pat = tofree;
3202  }
3203
3204  if (xp->xp_context == EXPAND_LUA) {
3205    return nlua_expand_get_matches(numMatches, matches);
3206  }
3207
3208  if (!fuzzy) {
3209    regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
3210    if (regmatch.regprog == NULL) {
3211      xfree(tofree);
3212      return FAIL;
3213    }
3214    // set ignore-case according to p_ic, p_scs and pat
3215    regmatch.rm_ic = ignorecase(pat);
3216  }
3217
3218  if (xp->xp_context == EXPAND_SETTINGS
3219      || xp->xp_context == EXPAND_BOOL_SETTINGS) {
3220    ret = ExpandSettings(xp, &regmatch, pat, numMatches, matches, fuzzy);
3221  } else if (xp->xp_context == EXPAND_STRING_SETTING) {
3222    ret = ExpandStringSetting(xp, &regmatch, numMatches, matches);
3223  } else if (xp->xp_context == EXPAND_SETTING_SUBTRACT) {
3224    ret = ExpandSettingSubtract(xp, &regmatch, numMatches, matches);
3225  } else if (xp->xp_context == EXPAND_MAPPINGS) {
3226    ret = ExpandMappings(pat, &regmatch, numMatches, matches);
3227  } else if (xp->xp_context == EXPAND_ARGOPT) {
3228    ret = expand_argopt(pat, xp, &regmatch, matches, numMatches);
3229  } else if (xp->xp_context == EXPAND_USER_DEFINED) {
3230    ret = ExpandUserDefined(pat, xp, &regmatch, matches, numMatches);
3231  } else {
3232    ret = ExpandOther(pat, xp, &regmatch, matches, numMatches);
3233  }
3234
3235  if (!fuzzy) {
3236    vim_regfree(regmatch.regprog);
3237  }
3238  xfree(tofree);
3239
3240  return ret;
3241}
3242
3243/// Expand a list of names.
3244///
3245/// Generic function for command line completion.  It calls a function to
3246/// obtain strings, one by one.  The strings are matched against a regexp
3247/// program.  Matching strings are copied into an array, which is returned.
3248///
3249/// @param func  returns a string from the list
3250void ExpandGeneric(const char *const pat, expand_T *xp, regmatch_T *regmatch, char ***matches,
3251                   int *numMatches, CompleteListItemGetter func, bool escaped)
3252{
3253  const bool fuzzy = cmdline_fuzzy_complete(pat);
3254  *matches = NULL;
3255  *numMatches = 0;
3256
3257  garray_T ga;
3258  if (!fuzzy) {
3259    ga_init(&ga, sizeof(char *), 30);
3260  } else {
3261    ga_init(&ga, sizeof(fuzmatch_str_T), 30);
3262  }
3263
3264  for (int i = 0;; i++) {
3265    char *str = (*func)(xp, i);
3266    if (str == NULL) {  // End of list.
3267      break;
3268    }
3269    if (*str == NUL) {  // Skip empty strings.
3270      continue;
3271    }
3272
3273    bool match;
3274    int score = 0;
3275    if (xp->xp_pattern[0] != NUL) {
3276      if (!fuzzy) {
3277        match = vim_regexec(regmatch, str, 0);
3278      } else {
3279        score = fuzzy_match_str(str, pat);
3280        match = (score != FUZZY_SCORE_NONE);
3281      }
3282    } else {
3283      match = true;
3284    }
3285
3286    if (!match) {
3287      continue;
3288    }
3289
3290    if (escaped) {
3291      str = vim_strsave_escaped(str, " \t\\.");
3292    } else {
3293      str = xstrdup(str);
3294    }
3295
3296    if (fuzzy) {
3297      GA_APPEND(fuzmatch_str_T, &ga, ((fuzmatch_str_T){
3298        .idx = ga.ga_len,
3299        .str = str,
3300        .score = score,
3301      }));
3302    } else {
3303      GA_APPEND(char *, &ga, str);
3304    }
3305
3306    if (func == get_menu_names) {
3307      // Test for separator added by get_menu_names().
3308      str += strlen(str) - 1;
3309      if (*str == '\001') {
3310        *str = '.';
3311      }
3312    }
3313  }
3314
3315  if (ga.ga_len == 0) {
3316    return;
3317  }
3318
3319  // Sort the matches when using regular expression matching and sorting
3320  // applies to the completion context. Menus and scriptnames should be kept
3321  // in the specified order.
3322  const bool sort_matches = !fuzzy
3323                            && xp->xp_context != EXPAND_MENUNAMES
3324                            && xp->xp_context != EXPAND_STRING_SETTING
3325                            && xp->xp_context != EXPAND_MENUS
3326                            && xp->xp_context != EXPAND_SCRIPTNAMES
3327                            && xp->xp_context != EXPAND_ARGOPT;
3328
3329  // <SNR> functions should be sorted to the end.
3330  const bool funcsort = xp->xp_context == EXPAND_EXPRESSION
3331                        || xp->xp_context == EXPAND_FUNCTIONS
3332                        || xp->xp_context == EXPAND_USER_FUNC;
3333
3334  // Sort the matches.
3335  if (sort_matches) {
3336    if (funcsort) {
3337      // <SNR> functions should be sorted to the end.
3338      qsort(ga.ga_data, (size_t)ga.ga_len, sizeof(char *), sort_func_compare);
3339    } else {
3340      sort_strings(ga.ga_data, ga.ga_len);
3341    }
3342  }
3343
3344  if (!fuzzy) {
3345    *matches = ga.ga_data;
3346    *numMatches = ga.ga_len;
3347  } else {
3348    fuzzymatches_to_strmatches(ga.ga_data, matches, ga.ga_len, funcsort);
3349    *numMatches = ga.ga_len;
3350  }
3351
3352  // Reset the variables used for special highlight names expansion, so that
3353  // they don't show up when getting normal highlight names by ID.
3354  reset_expand_highlight();
3355}
3356
3357/// Expand shell command matches in one directory of $PATH.
3358///
3359/// @param pathed_pattern  fully pathed pattern
3360/// @param pathlen         length of the path portion of pathed_pattern (0 if no path)
3361static void expand_shellcmd_onedir(char *pathed_pattern, size_t pathlen, char ***matches,
3362                                   int *numMatches, int flags, hashtab_T *ht, garray_T *gap)
3363{
3364  // Expand matches in one directory of $PATH.
3365  if (expand_wildcards(1, &pathed_pattern, numMatches, matches, flags) != OK) {
3366    return;
3367  }
3368
3369  ga_grow(gap, *numMatches);
3370
3371  for (int i = 0; i < *numMatches; i++) {
3372    char *name = (*matches)[i];
3373    size_t namelen = strlen(name);
3374
3375    if (namelen > pathlen) {
3376      // Check if this name was already found.
3377      hash_T hash = hash_hash(name + pathlen);
3378      hashitem_T *hi = hash_lookup(ht, name + pathlen, namelen - pathlen, hash);
3379      if (HASHITEM_EMPTY(hi)) {
3380        // Remove the path that was prepended.
3381        memmove(name, name + pathlen, namelen - pathlen + 1);  // +1 for NUL
3382        ((char **)gap->ga_data)[gap->ga_len++] = name;
3383        hash_add_item(ht, hi, name, hash);
3384        name = NULL;
3385      }
3386    }
3387    xfree(name);
3388  }
3389  xfree(*matches);
3390}
3391
3392/// Complete a shell command.
3393///
3394/// @param      filepat     is a pattern to match with command names.
3395/// @param[out] matches     is pointer to array of pointers to matches.
3396///                         *matches will either be set to NULL or point to
3397///                         allocated memory.
3398/// @param[out] numMatches  is pointer to number of matches.
3399/// @param      flagsarg    is a combination of EW_* flags.
3400static void expand_shellcmd(char *filepat, char ***matches, int *numMatches, int flagsarg)
3401  FUNC_ATTR_NONNULL_ALL
3402{
3403  char *path = NULL;
3404  garray_T ga;
3405  char *buf = xmalloc(MAXPATHL);
3406  int flags = flagsarg;
3407  bool did_curdir = false;
3408
3409  // for ":set path=" and ":set tags=" halve backslashes for escaped space
3410  size_t patlen = strlen(filepat);
3411  char *pat = xmemdupz(filepat, patlen);
3412  // Replace "\ " with " ".
3413  char *e = pat + patlen;
3414  for (char *s = pat; *s != NUL; s++) {
3415    if (*s != '\\') {
3416      continue;
3417    }
3418    char *p = s + 1;
3419    if (*p == ' ') {
3420      memmove(s, p, (size_t)(e - p) + 1);  // +1 for NUL
3421      e--;
3422    }
3423  }
3424  patlen = (size_t)(e - pat);
3425
3426  flags |= EW_FILE | EW_EXEC | EW_SHELLCMD;
3427
3428  bool mustfree = false;  // Track memory allocation for *path.
3429  if (pat[0] == '.' && (vim_ispathsep(pat[1])
3430                        || (pat[1] == '.' && vim_ispathsep(pat[2])))) {
3431    path = ".";
3432  } else {
3433    // For an absolute name we don't use $PATH.
3434    if (!path_is_absolute(pat)) {
3435      path = vim_getenv("PATH");
3436    }
3437    if (path == NULL) {
3438      path = "";
3439    } else {
3440      mustfree = true;
3441    }
3442  }
3443
3444  // Go over all directories in $PATH.  Expand matches in that directory and
3445  // collect them in "ga". When "." is not in $PATH also expand for the
3446  // current directory, to find "subdir/cmd".
3447  ga_init(&ga, (int)sizeof(char *), 10);
3448  hashtab_T found_ht;
3449  hash_init(&found_ht);
3450  for (char *s = path;; s = e) {
3451    size_t pathlen;  // length of the path portion of buf (including trailing slash).
3452    size_t seplen;
3453
3454    if (*s == NUL) {
3455      if (did_curdir) {
3456        break;
3457      }
3458
3459      // Find directories in the current directory, path is empty.
3460      did_curdir = true;
3461      flags |= EW_DIR;
3462
3463      e = s;
3464      pathlen = 0;
3465      seplen = 0;
3466    } else {
3467      e = vim_strchr(s, ENV_SEPCHAR);
3468      if (e == NULL) {
3469        e = s + strlen(s);
3470      }
3471
3472      pathlen = (size_t)(e - s);
3473      if (strncmp(s, ".", pathlen) == 0) {
3474        did_curdir = true;
3475        flags |= EW_DIR;
3476      } else {
3477        // Do not match directories inside a $PATH item.
3478        flags &= ~EW_DIR;
3479      }
3480
3481      seplen = !after_pathsep(s, e) ? STRLEN_LITERAL(PATHSEPSTR) : 0;
3482    }
3483
3484    // Make sure that the pathed pattern (ie the path and pattern concatenated
3485    // together) will fit inside the buffer. If not skip it and move on to the
3486    // next path.
3487    if (pathlen + seplen + patlen + 1 <= MAXPATHL) {
3488      if (pathlen > 0) {
3489        xmemcpyz(buf, s, pathlen);
3490        if (seplen > 0) {
3491          xmemcpyz(buf + pathlen, S_LEN(PATHSEPSTR));
3492          pathlen += seplen;
3493        }
3494      }
3495      xmemcpyz(buf + pathlen, pat, patlen);
3496
3497      expand_shellcmd_onedir(buf, pathlen, matches, numMatches, flags, &found_ht, &ga);
3498    }
3499
3500    if (*e != NUL) {
3501      e++;
3502    }
3503  }
3504  *matches = ga.ga_data;
3505  *numMatches = ga.ga_len;
3506
3507  xfree(buf);
3508  xfree(pat);
3509  if (mustfree) {
3510    xfree(path);
3511  }
3512  hash_clear(&found_ht);
3513}
3514
3515/// Call "user_expand_func()" to invoke a user defined Vim script function and
3516/// return the result (either a string, a List or NULL).
3517static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T *xp)
3518  FUNC_ATTR_NONNULL_ALL
3519{
3520  CmdlineInfo *const ccline = get_cmdline_info();
3521  char keep = 0;
3522  typval_T args[4];
3523  const sctx_T save_current_sctx = current_sctx;
3524
3525  if (xp->xp_arg == NULL || xp->xp_arg[0] == NUL || xp->xp_line == NULL) {
3526    return NULL;
3527  }
3528
3529  if (ccline->cmdbuff != NULL) {
3530    keep = ccline->cmdbuff[ccline->cmdlen];
3531    ccline->cmdbuff[ccline->cmdlen] = 0;
3532  }
3533
3534  char *pat = xstrnsave(xp->xp_pattern, xp->xp_pattern_len);
3535  args[0].v_type = VAR_STRING;
3536  args[1].v_type = VAR_STRING;
3537  args[2].v_type = VAR_NUMBER;
3538  args[3].v_type = VAR_UNKNOWN;
3539  args[0].vval.v_string = pat;
3540  args[1].vval.v_string = xp->xp_line;
3541  args[2].vval.v_number = xp->xp_col;
3542
3543  current_sctx = xp->xp_script_ctx;
3544
3545  void *const ret = user_expand_func(xp->xp_arg, 3, args);
3546
3547  current_sctx = save_current_sctx;
3548  if (ccline->cmdbuff != NULL) {
3549    ccline->cmdbuff[ccline->cmdlen] = keep;
3550  }
3551
3552  xfree(pat);
3553  return ret;
3554}
3555
3556/// Expand names with a function defined by the user (EXPAND_USER_DEFINED and
3557/// EXPAND_USER_LIST).
3558static int ExpandUserDefined(const char *const pat, expand_T *xp, regmatch_T *regmatch,
3559                             char ***matches, int *numMatches)
3560{
3561  const bool fuzzy = cmdline_fuzzy_complete(pat);
3562  *matches = NULL;
3563  *numMatches = 0;
3564
3565  char *const retstr = call_user_expand_func(call_func_retstr, xp);
3566  if (retstr == NULL) {
3567    return FAIL;
3568  }
3569
3570  garray_T ga;
3571  if (!fuzzy) {
3572    ga_init(&ga, (int)sizeof(char *), 3);
3573  } else {
3574    ga_init(&ga, (int)sizeof(fuzmatch_str_T), 3);
3575  }
3576
3577  for (char *s = retstr, *e; *s != NUL; s = e) {
3578    e = vim_strchr(s, '\n');
3579    if (e == NULL) {
3580      e = s + strlen(s);
3581    }
3582    const char keep = *e;
3583    *e = NUL;
3584
3585    bool match;
3586    int score = 0;
3587    if (xp->xp_pattern[0] != NUL) {
3588      if (!fuzzy) {
3589        match = vim_regexec(regmatch, s, 0);
3590      } else {
3591        score = fuzzy_match_str(s, pat);
3592        match = (score != FUZZY_SCORE_NONE);
3593      }
3594    } else {
3595      match = true;               // match everything
3596    }
3597
3598    *e = keep;
3599
3600    if (match) {
3601      char *p = xmemdupz(s, (size_t)(e - s));
3602
3603      if (!fuzzy) {
3604        GA_APPEND(char *, &ga, p);
3605      } else {
3606        GA_APPEND(fuzmatch_str_T, &ga, ((fuzmatch_str_T){
3607          .idx = ga.ga_len,
3608          .str = p,
3609          .score = score,
3610        }));
3611      }
3612    }
3613
3614    if (*e != NUL) {
3615      e++;
3616    }
3617  }
3618  xfree(retstr);
3619
3620  if (ga.ga_len == 0) {
3621    return OK;
3622  }
3623
3624  if (!fuzzy) {
3625    *matches = ga.ga_data;
3626    *numMatches = ga.ga_len;
3627  } else {
3628    fuzzymatches_to_strmatches(ga.ga_data, matches, ga.ga_len, false);
3629    *numMatches = ga.ga_len;
3630  }
3631  return OK;
3632}
3633
3634void expand_process_user_list(list_T *retlist, char ***matches, int *numMatches, expand_T *xp)
3635{
3636  garray_T ga;
3637  garray_T ga_abbr;
3638  garray_T ga_kind;
3639  garray_T ga_menu;
3640  garray_T ga_info;
3641  bool have_extra = false;
3642  ga_init(&ga, sizeof(char *), 3);
3643  ga_init(&ga_abbr, sizeof(char *), 3);
3644  ga_init(&ga_kind, sizeof(char *), 3);
3645  ga_init(&ga_menu, sizeof(char *), 3);
3646  ga_init(&ga_info, sizeof(char *), 3);
3647  // Loop over the items in the list.
3648  TV_LIST_ITER_CONST(retlist, li, {
3649    const typval_T *tv = TV_LIST_ITEM_TV(li);
3650    char *p = NULL;
3651    char *abbr = NULL;
3652    char *kind = NULL;
3653    char *menu = NULL;
3654    char *info = NULL;
3655
3656    if (tv->v_type == VAR_STRING) {
3657      if (tv->vval.v_string == NULL) {
3658        continue;  // Skip NULL strings
3659      }
3660      p = xstrdup(tv->vval.v_string);
3661    } else if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL) {
3662      dict_T *d = tv->vval.v_dict;
3663      char *word = tv_dict_get_string(d, "word", false);
3664
3665      if (word == NULL) {
3666        continue;  // "word" is required
3667      }
3668      p = xstrdup(word);
3669      abbr = tv_dict_get_string(d, "abbr", true);
3670      kind = tv_dict_get_string(d, "kind", true);
3671      menu = tv_dict_get_string(d, "menu", true);
3672      info = tv_dict_get_string(d, "info", true);
3673      if (abbr != NULL || kind != NULL || menu != NULL || info != NULL) {
3674        have_extra = true;
3675      }
3676    } else {
3677      continue;  // Skip other types
3678    }
3679
3680    GA_APPEND(char *, &ga, p);
3681    GA_APPEND(char *, &ga_abbr, abbr);
3682    GA_APPEND(char *, &ga_kind, kind);
3683    GA_APPEND(char *, &ga_menu, menu);
3684    GA_APPEND(char *, &ga_info, info);
3685  });
3686
3687  *matches = ga.ga_data;
3688  *numMatches = ga.ga_len;
3689  if (have_extra && ga.ga_len > 0) {
3690    xp->xp_files_abbr = (char **)ga_abbr.ga_data;
3691    xp->xp_files_kind = (char **)ga_kind.ga_data;
3692    xp->xp_files_menu = (char **)ga_menu.ga_data;
3693    xp->xp_files_info = (char **)ga_info.ga_data;
3694  } else {
3695    // No extra info collected; free the placeholder NULL entries.
3696    for (int i = 0; i < ga_abbr.ga_len; i++) {
3697      xfree(((char **)ga_abbr.ga_data)[i]);
3698    }
3699    xfree(ga_abbr.ga_data);
3700    for (int i = 0; i < ga_kind.ga_len; i++) {
3701      xfree(((char **)ga_kind.ga_data)[i]);
3702    }
3703    xfree(ga_kind.ga_data);
3704    for (int i = 0; i < ga_menu.ga_len; i++) {
3705      xfree(((char **)ga_menu.ga_data)[i]);
3706    }
3707    xfree(ga_menu.ga_data);
3708    for (int i = 0; i < ga_info.ga_len; i++) {
3709      xfree(((char **)ga_info.ga_data)[i]);
3710    }
3711    xfree(ga_info.ga_data);
3712  }
3713}
3714
3715/// Expand names with a list returned by a function defined by the user.
3716static int ExpandUserList(expand_T *xp, char ***matches, int *numMatches)
3717{
3718  *matches = NULL;
3719  *numMatches = 0;
3720  list_T *const retlist = call_user_expand_func(call_func_retlist, xp);
3721  if (retlist == NULL) {
3722    return FAIL;
3723  }
3724
3725  expand_process_user_list(retlist, matches, numMatches, xp);
3726  tv_list_unref(retlist);
3727  return OK;
3728}
3729
3730static int ExpandUserLua(expand_T *xp, int *numMatches, char ***matches)
3731{
3732  typval_T rettv = TV_INITIAL_VALUE;
3733  nlua_call_user_expand_func(xp, &rettv);
3734  if (rettv.v_type != VAR_LIST) {
3735    tv_clear(&rettv);
3736    return FAIL;
3737  }
3738
3739  list_T *const retlist = rettv.vval.v_list;
3740
3741  expand_process_user_list(retlist, matches, numMatches, xp);
3742  tv_list_unref(retlist);
3743  return OK;
3744}
3745
3746/// Expand `file` for all comma-separated directories in `path`.
3747/// Adds matches to `ga`.
3748/// If "dirs" is true only expand directory names.
3749void globpath(char *path, char *file, garray_T *ga, int expand_options, bool dirs)
3750  FUNC_ATTR_NONNULL_ALL
3751{
3752  char *buf = xmalloc(MAXPATHL);
3753
3754  expand_T xpc;
3755  ExpandInit(&xpc);
3756  xpc.xp_context = dirs ? EXPAND_DIRECTORIES : EXPAND_FILES;
3757
3758  size_t filelen = strlen(file);
3759
3760  // Loop over all entries in {path}.
3761  while (*path != NUL) {
3762    // Copy one item of the path to buf[] and concatenate the file name.
3763
3764    // length of the path portion of buf (including trailing slash).
3765    size_t pathlen = copy_option_part(&path, buf, MAXPATHL, ",");
3766    size_t seplen = (*buf != NUL && !after_pathsep(buf, buf + pathlen))
3767                    ? STRLEN_LITERAL(PATHSEPSTR) : 0;
3768
3769    if (pathlen + seplen + filelen + 1 <= MAXPATHL) {
3770      if (seplen > 0) {
3771        xmemcpyz(buf + pathlen, S_LEN(PATHSEPSTR));
3772        pathlen += seplen;
3773      }
3774      xmemcpyz(buf + pathlen, file, filelen);
3775
3776      char **p;
3777      int num_p = 0;
3778      ExpandFromContext(&xpc, buf, &p, &num_p, WILD_SILENT | expand_options);
3779      if (num_p > 0) {
3780        ExpandEscape(&xpc, buf, num_p, p, WILD_SILENT | expand_options);
3781
3782        // Concatenate new results to previous ones.
3783        ga_grow(ga, num_p);
3784        // take over the pointers and put them in "ga"
3785        for (int i = 0; i < num_p; i++) {
3786          ((char **)ga->ga_data)[ga->ga_len] = p[i];
3787          ga->ga_len++;
3788        }
3789        xfree(p);
3790      }
3791    }
3792  }
3793
3794  xfree(buf);
3795}
3796
3797/// Translate some keys pressed when 'wildmenu' is used.
3798int wildmenu_translate_key(CmdlineInfo *cclp, int key, expand_T *xp, bool did_wild_list)
3799{
3800  int c = key;
3801
3802  if (cmdline_pum_active() || did_wild_list || wild_menu_showing) {
3803    if (c == K_LEFT) {
3804      c = Ctrl_P;
3805    } else if (c == K_RIGHT) {
3806      c = Ctrl_N;
3807    }
3808  }
3809
3810  // Hitting CR after "emenu Name.": complete submenu
3811  if (xp->xp_context == EXPAND_MENUNAMES
3812      && cclp->cmdpos > 1
3813      && cclp->cmdbuff[cclp->cmdpos - 1] == '.'
3814      && cclp->cmdbuff[cclp->cmdpos - 2] != '\\'
3815      && (c == '\n' || c == '\r' || c == K_KENTER)) {
3816    c = K_DOWN;
3817  }
3818
3819  return c;
3820}
3821
3822/// Delete characters on the command line, from "from" to the current position.
3823static void cmdline_del(CmdlineInfo *cclp, int from)
3824{
3825  assert(cclp->cmdpos <= cclp->cmdlen);
3826  memmove(cclp->cmdbuff + from, cclp->cmdbuff + cclp->cmdpos,
3827          (size_t)cclp->cmdlen - (size_t)cclp->cmdpos + 1);
3828  cclp->cmdlen -= cclp->cmdpos - from;
3829  cclp->cmdpos = from;
3830}
3831
3832/// Handle a key pressed when the wild menu for the menu names
3833/// (EXPAND_MENUNAMES) is displayed.
3834static int wildmenu_process_key_menunames(CmdlineInfo *cclp, int key, expand_T *xp)
3835{
3836  // Hitting <Down> after "emenu Name.": complete submenu
3837  if (key == K_DOWN && cclp->cmdpos > 0
3838      && cclp->cmdbuff[cclp->cmdpos - 1] == '.') {
3839    key = (int)p_wc;
3840    KeyTyped = true;  // in case the key was mapped
3841  } else if (key == K_UP) {
3842    // Hitting <Up>: Remove one submenu name in front of the
3843    // cursor
3844    bool found = false;
3845
3846    int j = (int)(xp->xp_pattern - cclp->cmdbuff);
3847    int i = 0;
3848    while (--j > 0) {
3849      // check for start of menu name
3850      if (cclp->cmdbuff[j] == ' '
3851          && cclp->cmdbuff[j - 1] != '\\') {
3852        i = j + 1;
3853        break;
3854      }
3855      // check for start of submenu name
3856      if (cclp->cmdbuff[j] == '.'
3857          && cclp->cmdbuff[j - 1] != '\\') {
3858        if (found) {
3859          i = j + 1;
3860          break;
3861        } else {
3862          found = true;
3863        }
3864      }
3865    }
3866    if (i > 0) {
3867      cmdline_del(cclp, i);
3868    }
3869    key = (int)p_wc;
3870    KeyTyped = true;  // in case the key was mapped
3871    xp->xp_context = EXPAND_NOTHING;
3872  }
3873
3874  return key;
3875}
3876
3877/// Handle a key pressed when the wild menu for file names (EXPAND_FILES) or
3878/// directory names (EXPAND_DIRECTORIES) or shell command names
3879/// (EXPAND_SHELLCMD) is displayed.
3880static int wildmenu_process_key_filenames(CmdlineInfo *cclp, int key, expand_T *xp)
3881{
3882  char upseg[5];
3883  upseg[0] = PATHSEP;
3884  upseg[1] = '.';
3885  upseg[2] = '.';
3886  upseg[3] = PATHSEP;
3887  upseg[4] = NUL;
3888
3889  if (key == K_DOWN
3890      && cclp->cmdpos > 0
3891      && cclp->cmdbuff[cclp->cmdpos - 1] == PATHSEP
3892      && (cclp->cmdpos < 3
3893          || cclp->cmdbuff[cclp->cmdpos - 2] != '.'
3894          || cclp->cmdbuff[cclp->cmdpos - 3] != '.')) {
3895    // go down a directory
3896    key = (int)p_wc;
3897    KeyTyped = true;  // in case the key was mapped
3898  } else if (strncmp(xp->xp_pattern, upseg + 1, 3) == 0 && key == K_DOWN) {
3899    // If in a direct ancestor, strip off one ../ to go down
3900    bool found = false;
3901
3902    int j = cclp->cmdpos;
3903    int i = (int)(xp->xp_pattern - cclp->cmdbuff);
3904    while (--j > i) {
3905      j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j);
3906      if (vim_ispathsep(cclp->cmdbuff[j])) {
3907        found = true;
3908        break;
3909      }
3910    }
3911    if (found
3912        && cclp->cmdbuff[j - 1] == '.'
3913        && cclp->cmdbuff[j - 2] == '.'
3914        && (vim_ispathsep(cclp->cmdbuff[j - 3]) || j == i + 2)) {
3915      cmdline_del(cclp, j - 2);
3916      key = (int)p_wc;
3917      KeyTyped = true;  // in case the key was mapped
3918    }
3919  } else if (key == K_UP) {
3920    // go up a directory
3921    bool found = false;
3922
3923    int j = cclp->cmdpos - 1;
3924    int i = (int)(xp->xp_pattern - cclp->cmdbuff);
3925    while (--j > i) {
3926      j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j);
3927      if (vim_ispathsep(cclp->cmdbuff[j])
3928#ifdef BACKSLASH_IN_FILENAME
3929          && vim_strchr(" *?[{`$%#", (uint8_t)cclp->cmdbuff[j + 1]) == NULL
3930#endif
3931          ) {
3932        if (found) {
3933          i = j + 1;
3934          break;
3935        } else {
3936          found = true;
3937        }
3938      }
3939    }
3940
3941    if (!found) {
3942      j = i;
3943    } else if (strncmp(cclp->cmdbuff + j, upseg, 4) == 0) {
3944      j += 4;
3945    } else if (strncmp(cclp->cmdbuff + j, upseg + 1, 3) == 0
3946               && j == i) {
3947      j += 3;
3948    } else {
3949      j = 0;
3950    }
3951
3952    if (j > 0) {
3953      // TODO(tarruda): this is only for DOS/Unix systems - need to put in
3954      // machine-specific stuff here and in upseg init
3955      cmdline_del(cclp, j);
3956      put_on_cmdline(upseg + 1, 3, false);
3957    } else if (cclp->cmdpos > i) {
3958      cmdline_del(cclp, i);
3959    }
3960
3961    // Now complete in the new directory. Set KeyTyped in case the
3962    // Up key came from a mapping.
3963    key = (int)p_wc;
3964    KeyTyped = true;
3965  }
3966
3967  return key;
3968}
3969
3970/// Handle a key pressed when wild menu is displayed
3971int wildmenu_process_key(CmdlineInfo *cclp, int key, expand_T *xp)
3972{
3973  // Special translations for 'wildmenu'
3974  if (xp->xp_context == EXPAND_MENUNAMES) {
3975    return wildmenu_process_key_menunames(cclp, key, xp);
3976  }
3977  if (xp->xp_context == EXPAND_FILES
3978      || xp->xp_context == EXPAND_DIRECTORIES
3979      || xp->xp_context == EXPAND_SHELLCMD) {
3980    return wildmenu_process_key_filenames(cclp, key, xp);
3981  }
3982
3983  return key;
3984}
3985
3986/// Free expanded names when finished walking through the matches
3987void wildmenu_cleanup(CmdlineInfo *cclp)
3988{
3989  if (!p_wmnu || wild_menu_showing == 0) {
3990    return;
3991  }
3992
3993  const bool skt = KeyTyped;
3994  const int old_RedrawingDisabled = RedrawingDisabled;
3995
3996  if (cclp->input_fn) {
3997    RedrawingDisabled = 0;
3998  }
3999
4000  // Clear highlighting applied during wildmenu activity
4001  set_no_hlsearch(true);
4002
4003  if (wild_menu_showing == WM_SCROLLED) {
4004    // Entered command line, move it up
4005    cmdline_row--;
4006    redrawcmd();
4007    wild_menu_showing = 0;
4008  } else if (save_p_ls != -1) {
4009    // restore 'laststatus' and 'winminheight'
4010    p_ls = save_p_ls;
4011    p_wmh = save_p_wmh;
4012    last_status(false);
4013    update_screen();  // redraw the screen NOW
4014    redrawcmd();
4015    save_p_ls = -1;
4016    wild_menu_showing = 0;
4017  } else {
4018    win_redraw_last_status(topframe);
4019    wild_menu_showing = 0;  // must be before redraw_statuslines #8385
4020    redraw_statuslines();
4021  }
4022  KeyTyped = skt;
4023  if (cclp->input_fn) {
4024    RedrawingDisabled = old_RedrawingDisabled;
4025  }
4026}
4027
4028/// "getcompletion()" function
4029void f_getcompletion(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4030{
4031  expand_T xpc;
4032  bool filtered = false;
4033  int options = WILD_SILENT | WILD_USE_NL | WILD_ADD_SLASH
4034                | WILD_NO_BEEP | WILD_HOME_REPLACE;
4035
4036  if (tv_check_for_string_arg(argvars, 1) == FAIL) {
4037    return;
4038  }
4039  const char *const type = tv_get_string(&argvars[1]);
4040
4041  if (argvars[2].v_type != VAR_UNKNOWN) {
4042    filtered = (bool)tv_get_bool_chk(&argvars[2], NULL);
4043  }
4044
4045  if (p_wic) {
4046    options |= WILD_ICASE;
4047  }
4048
4049  // For filtered results, 'wildignore' is used
4050  if (!filtered) {
4051    options |= WILD_KEEP_ALL;
4052  }
4053
4054  if (argvars[0].v_type != VAR_STRING) {
4055    if (tv_get_string_chk(&argvars[0]) != NULL) {
4056      emsg(_(e_invarg));
4057    }
4058    return;
4059  }
4060  const char *const pattern = tv_get_string(&argvars[0]);
4061  const char *pattern_start = pattern;
4062
4063  if (strcmp(type, "cmdline") == 0) {
4064    const int cmdline_len = (int)strlen(pattern);
4065    set_cmd_context(&xpc, (char *)pattern, cmdline_len, cmdline_len, false);
4066    pattern_start = xpc.xp_pattern;
4067    xpc.xp_pattern_len = strlen(xpc.xp_pattern);
4068    xpc.xp_col = cmdline_len;
4069    goto theend;
4070  }
4071
4072  ExpandInit(&xpc);
4073  xpc.xp_pattern = (char *)pattern;
4074  xpc.xp_pattern_len = strlen(xpc.xp_pattern);
4075  xpc.xp_line = (char *)pattern;
4076
4077  xpc.xp_context = cmdcomplete_str_to_type(type);
4078  switch (xpc.xp_context) {
4079  case EXPAND_NOTHING:
4080    semsg(_(e_invarg2), type);
4081    return;
4082
4083  case EXPAND_USER_DEFINED:
4084    // Must be "custom,funcname" pattern
4085    if (strncmp(type, "custom,", 7) != 0) {
4086      semsg(_(e_invarg2), type);
4087      return;
4088    }
4089
4090    xpc.xp_arg = (char *)(type + 7);
4091    break;
4092
4093  case EXPAND_USER_LIST:
4094    // Must be "customlist,funcname" pattern
4095    if (strncmp(type, "customlist,", 11) != 0) {
4096      semsg(_(e_invarg2), type);
4097      return;
4098    }
4099
4100    xpc.xp_arg = (char *)(type + 11);
4101    break;
4102
4103  case EXPAND_MENUS:
4104    set_context_in_menu_cmd(&xpc, "menu", xpc.xp_pattern, false);
4105    xpc.xp_pattern_len -= (size_t)(xpc.xp_pattern - pattern_start);
4106    break;
4107
4108  case EXPAND_SIGN:
4109    set_context_in_sign_cmd(&xpc, xpc.xp_pattern);
4110    xpc.xp_pattern_len -= (size_t)(xpc.xp_pattern - pattern_start);
4111    break;
4112
4113  case EXPAND_RUNTIME:
4114    set_context_in_runtime_cmd(&xpc, xpc.xp_pattern);
4115    xpc.xp_pattern_len -= (size_t)(xpc.xp_pattern - pattern_start);
4116    break;
4117
4118  case EXPAND_SHELLCMDLINE: {
4119    int context = EXPAND_SHELLCMDLINE;
4120    set_context_for_wildcard_arg(NULL, xpc.xp_pattern, false, &xpc, &context);
4121    xpc.xp_pattern_len -= (size_t)(xpc.xp_pattern - pattern_start);
4122    break;
4123  }
4124
4125  case EXPAND_FILETYPECMD:
4126    filetype_expand_what = EXP_FILETYPECMD_ALL;
4127    break;
4128
4129  default:
4130    break;
4131  }
4132
4133theend:
4134  if (xpc.xp_context == EXPAND_LUA) {
4135    xpc.xp_col = (int)strlen(xpc.xp_line);
4136    nlua_expand_pat(&xpc);
4137    xpc.xp_pattern_len -= (size_t)(xpc.xp_pattern - pattern_start);
4138  }
4139  char *pat;
4140  if (cmdline_fuzzy_completion_supported(&xpc)) {
4141    // when fuzzy matching, don't modify the search string
4142    pat = xmemdupz(xpc.xp_pattern, xpc.xp_pattern_len);
4143  } else {
4144    pat = addstar(xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context);
4145  }
4146
4147  ExpandOne(&xpc, pat, NULL, options, WILD_ALL_KEEP);
4148  tv_list_alloc_ret(rettv, xpc.xp_numfiles);
4149
4150  for (int i = 0; i < xpc.xp_numfiles; i++) {
4151    tv_list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
4152  }
4153  xfree(pat);
4154  ExpandCleanup(&xpc);
4155}
4156
4157/// "getcompletiontype()" function
4158void f_getcompletiontype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4159{
4160  rettv->v_type = VAR_STRING;
4161  rettv->vval.v_string = NULL;
4162
4163  if (tv_check_for_string_arg(argvars, 0) == FAIL) {
4164    return;
4165  }
4166
4167  const char *pat = tv_get_string(&argvars[0]);
4168  expand_T xpc;
4169  ExpandInit(&xpc);
4170
4171  int cmdline_len = (int)strlen(pat);
4172  set_cmd_context(&xpc, (char *)pat, cmdline_len, cmdline_len, false);
4173  rettv->vval.v_string = cmdcomplete_type_to_str(xpc.xp_context, xpc.xp_arg);
4174
4175  ExpandCleanup(&xpc);
4176}
4177
4178/// "cmdcomplete_info()" function
4179void f_cmdcomplete_info(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4180{
4181  CmdlineInfo *ccline = get_cmdline_info();
4182
4183  tv_dict_alloc_ret(rettv);
4184  if (ccline == NULL || ccline->xpc == NULL || ccline->xpc->xp_files == NULL) {
4185    return;
4186  }
4187
4188  dict_T *retdict = rettv->vval.v_dict;
4189  int ret = tv_dict_add_str_len(retdict, S_LEN("cmdline_orig"),
4190                                cmdline_orig.data, (int)cmdline_orig.size);
4191  if (ret == OK) {
4192    ret = tv_dict_add_nr(retdict, S_LEN("pum_visible"), pum_visible());
4193  }
4194  if (ret == OK) {
4195    ret = tv_dict_add_nr(retdict, S_LEN("selected"), ccline->xpc->xp_selected);
4196  }
4197  if (ret == OK) {
4198    list_T *li = tv_list_alloc(ccline->xpc->xp_numfiles);
4199    ret = tv_dict_add_list(retdict, S_LEN("matches"), li);
4200    for (int idx = 0; ret == OK && idx < ccline->xpc->xp_numfiles; idx++) {
4201      tv_list_append_string(li, ccline->xpc->xp_files[idx], -1);
4202    }
4203  }
4204}
4205
4206/// Copy a substring from the current buffer (curbuf), spanning from the given
4207/// 'start' position to the word boundary after 'end' position.
4208/// The copied string is stored in '*match', and the actual end position of the
4209/// matched text is returned in '*match_end'.
4210static int copy_substring_from_pos(pos_T *start, pos_T *end, char **match, pos_T *match_end)
4211{
4212  bool exacttext = wop_flags & kOptWopFlagExacttext;
4213
4214  if (start->lnum > end->lnum
4215      || (start->lnum == end->lnum && start->col >= end->col)) {
4216    return FAIL;  // invalid range
4217  }
4218
4219  // Use a growable string (ga)
4220  garray_T ga;
4221  ga_init(&ga, 1, 128);
4222
4223  // Append start line from start->col to end
4224  char *start_line = ml_get(start->lnum);
4225  char *start_ptr = start_line + start->col;
4226  bool is_single_line = start->lnum == end->lnum;
4227
4228  int segment_len = is_single_line ? (int)(end->col - start->col)
4229                                   : (int)(ml_get_len(start->lnum) - start->col);
4230  ga_grow(&ga, segment_len + 2);
4231  ga_concat_len(&ga, start_ptr, (size_t)segment_len);
4232  if (!is_single_line) {
4233    if (exacttext) {
4234      GA_CONCAT_LITERAL(&ga, "\\n");
4235    } else {
4236      ga_append(&ga, '\n');
4237    }
4238  }
4239
4240  // Append full lines between start and end
4241  if (!is_single_line) {
4242    for (linenr_T lnum = start->lnum + 1; lnum < end->lnum; lnum++) {
4243      char *line = ml_get(lnum);
4244      int linelen = ml_get_len(lnum);
4245      ga_grow(&ga, linelen + 2);
4246      ga_concat_len(&ga, line, (size_t)linelen);
4247      if (exacttext) {
4248        GA_CONCAT_LITERAL(&ga, "\\n");
4249      } else {
4250        ga_append(&ga, '\n');
4251      }
4252    }
4253  }
4254
4255  // Append partial end line (up to word end)
4256  char *end_line = ml_get(end->lnum);
4257  char *word_end = find_word_end(end_line + end->col);
4258  segment_len = (int)(word_end - end_line);
4259  ga_grow(&ga, segment_len);
4260  ga_concat_len(&ga, end_line + (is_single_line ? end->col : 0),
4261                (size_t)(segment_len - (is_single_line ? end->col : 0)));
4262
4263  // Null-terminate
4264  ga_grow(&ga, 1);
4265  ga_append(&ga, NUL);
4266
4267  *match = (char *)ga.ga_data;
4268  match_end->lnum = end->lnum;
4269  match_end->col = segment_len;
4270
4271  return OK;
4272}
4273
4274/// Returns true if the given string `str` matches the regex pattern `pat`.
4275/// Honors the 'ignorecase' (p_ic) and 'smartcase' (p_scs) settings to determine
4276/// case sensitivity.
4277static bool is_regex_match(char *pat, char *str)
4278{
4279  if (strcmp(pat, str) == 0) {
4280    return true;
4281  }
4282
4283  regmatch_T regmatch;
4284
4285  emsg_off++;
4286  msg_silent++;
4287  regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
4288  emsg_off--;
4289  msg_silent--;
4290
4291  if (regmatch.regprog == NULL) {
4292    return false;
4293  }
4294  regmatch.rm_ic = p_ic;
4295  if (p_ic && p_scs) {
4296    regmatch.rm_ic = !pat_has_uppercase(pat);
4297  }
4298
4299  emsg_off++;
4300  msg_silent++;
4301  bool result = vim_regexec_nl(&regmatch, str, (colnr_T)0);
4302  emsg_off--;
4303  msg_silent--;
4304
4305  vim_regfree(regmatch.regprog);
4306  return result;
4307}
4308
4309/// Constructs a new match string by appending text from the buffer (starting at
4310/// end_match_pos) to the given pattern `pat`. The result is a concatenation of
4311/// `pat` and the word following end_match_pos.
4312/// If 'lowercase' is true, the appended text is converted to lowercase before
4313/// being combined. Returns the newly allocated match string, or NULL on failure.
4314static char *concat_pattern_with_buffer_match(char *pat, int pat_len, pos_T *end_match_pos,
4315                                              bool lowercase)
4316  FUNC_ATTR_NONNULL_RET
4317{
4318  char *line = ml_get(end_match_pos->lnum);
4319  char *word_end = find_word_end(line + end_match_pos->col);
4320  int match_len = (int)(word_end - (line + end_match_pos->col));
4321  char *match = xmalloc((size_t)match_len + (size_t)pat_len + 1);  // +1 for NUL
4322
4323  memmove(match, pat, (size_t)pat_len);
4324  if (match_len > 0) {
4325    if (lowercase) {
4326      char *mword = xstrnsave(line + end_match_pos->col, (size_t)match_len);
4327      char *lower = strcase_save(mword, false);
4328      xfree(mword);
4329      memmove(match + pat_len, lower, (size_t)match_len);
4330      xfree(lower);
4331    } else {
4332      memmove(match + pat_len, line + end_match_pos->col, (size_t)match_len);
4333    }
4334  }
4335  match[pat_len + match_len] = NUL;
4336  return match;
4337}
4338
4339/// Search for strings matching "pat" in the specified range and return them.
4340/// Returns OK on success, FAIL otherwise.
4341///
4342/// @param      pat        pattern to match
4343/// @param      dir        FORWARD or BACKWARD
4344/// @param[out] matches    array with matched string
4345/// @param[out] numMatches number of matches
4346static int expand_pattern_in_buf(char *pat, Direction dir, char ***matches, int *numMatches)
4347{
4348  bool exacttext = wop_flags & kOptWopFlagExacttext;
4349  bool has_range = Search.first_line != 0;
4350
4351  *matches = NULL;
4352  *numMatches = 0;
4353
4354  if (pat == NULL || *pat == NUL) {
4355    return FAIL;
4356  }
4357
4358  int pat_len = (int)strlen(pat);
4359  pos_T cur_match_pos = { 0 }, prev_match_pos = { 0 };
4360  if (has_range) {
4361    cur_match_pos.lnum = Search.first_line;
4362  } else {
4363    cur_match_pos = pre_incsearch_pos;
4364  }
4365
4366  int search_flags = SEARCH_OPT | SEARCH_NOOF | SEARCH_PEEK | SEARCH_NFMSG
4367                     | (has_range ? SEARCH_START : 0);
4368
4369  garray_T ga;
4370  ga_init(&ga, sizeof(char *), 10);  // Use growable array of char *
4371
4372  pos_T end_match_pos, word_end_pos;
4373  bool looped_around = false;
4374  bool compl_started = false;
4375  char *match, *full_match;
4376
4377  while (true) {
4378    emsg_off++;
4379    msg_silent++;
4380    int found_new_match = searchit(NULL, curbuf, &cur_match_pos,
4381                                   &end_match_pos, dir, pat, (size_t)pat_len, 1L,
4382                                   search_flags, RE_LAST, p_magic, NULL);
4383    msg_silent--;
4384    emsg_off--;
4385
4386    if (found_new_match == FAIL) {
4387      break;
4388    }
4389
4390    // If in range mode, check if match is within the range
4391    if (has_range && (cur_match_pos.lnum < Search.first_line
4392                      || cur_match_pos.lnum > Search.last_line)) {
4393      break;
4394    }
4395
4396    if (compl_started) {
4397      // If we've looped back to an earlier match, stop
4398      if ((dir == FORWARD && ltoreq(cur_match_pos, prev_match_pos))
4399          || (dir == BACKWARD && ltoreq(prev_match_pos, cur_match_pos))) {
4400        if (looped_around) {
4401          break;
4402        } else {
4403          looped_around = true;
4404        }
4405      }
4406    }
4407
4408    compl_started = true;
4409    prev_match_pos = cur_match_pos;
4410
4411    // Abort if user typed a character or interrupted
4412    if (char_avail() || got_int) {
4413      if (got_int) {
4414        (void)vpeekc();  // Remove <C-C> from input stream
4415        got_int = false;  // Don't abandon the command line
4416      }
4417      goto cleanup;
4418    }
4419
4420    // searchit() can return line number +1 past the last line when
4421    // searching for "foo\n" if "foo" is at end of buffer.
4422    if (end_match_pos.lnum > curbuf->b_ml.ml_line_count) {
4423      cur_match_pos.lnum = 1;
4424      cur_match_pos.col = 0;
4425      cur_match_pos.coladd = 0;
4426      continue;
4427    }
4428
4429    // Extract the matching text prepended to completed word
4430    if (copy_substring_from_pos(&cur_match_pos, &end_match_pos, &full_match,
4431                                &word_end_pos) == FAIL) {
4432      break;
4433    }
4434
4435    if (exacttext) {
4436      match = full_match;
4437    } else {
4438      // Construct a new match from completed word appended to pattern itself
4439      match = concat_pattern_with_buffer_match(pat, pat_len, &end_match_pos, false);
4440
4441      // The regex pattern may include '\C' or '\c'. First, try matching the
4442      // buffer word as-is. If it doesn't match, try again with the lowercase
4443      // version of the word to handle smartcase behavior.
4444      if (!is_regex_match(match, full_match)) {
4445        xfree(match);
4446        match = concat_pattern_with_buffer_match(pat, pat_len, &end_match_pos, true);
4447        if (!is_regex_match(match, full_match)) {
4448          xfree(match);
4449          xfree(full_match);
4450          continue;
4451        }
4452      }
4453      xfree(full_match);
4454    }
4455
4456    // Include this match if it is not a duplicate
4457    for (int i = 0; i < ga.ga_len; i++) {
4458      if (strcmp(match, ((char **)ga.ga_data)[i]) == 0) {
4459        XFREE_CLEAR(match);
4460        break;
4461      }
4462    }
4463    if (match != NULL) {
4464      ga_grow(&ga, 1);
4465      ((char **)ga.ga_data)[ga.ga_len++] = match;
4466      if (ga.ga_len > TAG_MANY) {
4467        break;
4468      }
4469    }
4470    if (has_range) {
4471      cur_match_pos = word_end_pos;
4472    }
4473  }
4474
4475  *matches = (char **)ga.ga_data;
4476  *numMatches = ga.ga_len;
4477  return OK;
4478
4479cleanup:
4480  ga_clear_strings(&ga);
4481  return FAIL;
4482}