robin/laufey

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

Justin M. Keyesfix(options): ":set foo?" for Lua callbacks #41100e02755cd9f

master
48.9 KiB1870 linesraw
1// usercmd.c: User defined command support
2
3#include <assert.h>
4#include <inttypes.h>
5#include <lauxlib.h>
6#include <stdbool.h>
7#include <stdio.h>
8#include <string.h>
9
10#include "auto/config.h"
11#include "nvim/api/private/helpers.h"
12#include "nvim/ascii_defs.h"
13#include "nvim/buffer_defs.h"
14#include "nvim/charset.h"
15#include "nvim/cmdexpand_defs.h"
16#include "nvim/eval.h"
17#include "nvim/ex_cmds_defs.h"
18#include "nvim/ex_docmd.h"
19#include "nvim/garray.h"
20#include "nvim/gettext_defs.h"
21#include "nvim/globals.h"
22#include "nvim/highlight_defs.h"
23#include "nvim/keycodes.h"
24#include "nvim/lua/executor.h"
25#include "nvim/macros_defs.h"
26#include "nvim/mapping.h"
27#include "nvim/mbyte.h"
28#include "nvim/memory.h"
29#include "nvim/memory_defs.h"
30#include "nvim/menu.h"
31#include "nvim/message.h"
32#include "nvim/option_vars.h"
33#include "nvim/os/input.h"
34#include "nvim/runtime.h"
35#include "nvim/strings.h"
36#include "nvim/usercmd.h"
37#include "nvim/vim_defs.h"
38#include "nvim/window.h"
39
40#include "usercmd.c.generated.h"
41
42garray_T ucmds = { 0, 0, sizeof(ucmd_T), 4, NULL };
43
44static const char e_argument_required_for_str[]
45  = N_("E179: Argument required for %s");
46static const char e_no_such_user_defined_command_str[]
47  = N_("E184: No such user-defined command: %s");
48static const char e_complete_used_without_allowing_arguments[]
49  = N_("E1208: -complete used without allowing arguments");
50static const char e_no_such_user_defined_command_in_current_buffer_str[]
51  = N_("E1237: No such user-defined command in current buffer: %s");
52
53/// List of names for completion for ":command" with the EXPAND_ flag.
54/// Must be alphabetical for completion.
55static const char *command_complete[] = {
56  [EXPAND_ARGLIST] = "arglist",
57  [EXPAND_AUGROUP] = "augroup",
58  [EXPAND_BUFFERS] = "buffer",
59  [EXPAND_CHECKHEALTH] = "checkhealth",
60  [EXPAND_COLORS] = "color",
61  [EXPAND_COMMANDS] = "command",
62  [EXPAND_COMPILER] = "compiler",
63  [EXPAND_USER_DEFINED] = "custom",
64  [EXPAND_USER_LIST] = "customlist",
65  [EXPAND_USER_LUA] = "<Lua function>",
66  [EXPAND_DIFF_BUFFERS] = "diff_buffer",
67  [EXPAND_DIRECTORIES] = "dir",
68  [EXPAND_ENV_VARS] = "environment",
69  [EXPAND_EVENTS] = "event",
70  [EXPAND_EXPRESSION] = "expression",
71  [EXPAND_FILES] = "file",
72  [EXPAND_FILES_IN_PATH] = "file_in_path",
73  [EXPAND_FILETYPE] = "filetype",
74  [EXPAND_FILETYPECMD] = "filetypecmd",
75  [EXPAND_FUNCTIONS] = "function",
76  [EXPAND_HELP] = "help",
77  [EXPAND_HIGHLIGHT] = "highlight",
78  [EXPAND_HISTORY] = "history",
79  [EXPAND_KEYMAP] = "keymap",
80  [EXPAND_LOCALES] = "locale",
81  [EXPAND_LUA] = "lua",
82  [EXPAND_MAPCLEAR] = "mapclear",
83  [EXPAND_MAPPINGS] = "mapping",
84  [EXPAND_MENUS] = "menu",
85  [EXPAND_MESSAGES] = "messages",
86  [EXPAND_OWNSYNTAX] = "syntax",
87  [EXPAND_SYNTIME] = "syntime",
88  [EXPAND_SETTINGS] = "option",
89  [EXPAND_PACKADD] = "packadd",
90  [EXPAND_RETAB] = "retab",
91  [EXPAND_RUNTIME] = "runtime",
92  [EXPAND_SHELLCMD] = "shellcmd",
93  [EXPAND_SHELLCMDLINE] = "shellcmdline",
94  [EXPAND_SIGN] = "sign",
95  [EXPAND_TAGS] = "tag",
96  [EXPAND_TAGS_LISTFILES] = "tag_listfiles",
97  [EXPAND_USER] = "user",
98  [EXPAND_USER_VARS] = "var",
99  [EXPAND_BREAKPOINT] = "breakpoint",
100  [EXPAND_SCRIPTNAMES] = "scriptnames",
101  [EXPAND_DIRS_IN_CDPATH] = "dir_in_path",
102};
103
104/// List of names of address types.  Must be alphabetical for completion.
105static struct {
106  cmd_addr_T expand;
107  char *name;
108  char *shortname;
109} addr_type_complete[] = {
110  { ADDR_ARGUMENTS, "arguments", "arg" },
111  { ADDR_LINES, "lines", "line" },
112  { ADDR_LOADED_BUFFERS, "loaded_buffers", "load" },
113  { ADDR_TABS, "tabs", "tab" },
114  { ADDR_BUFFERS, "buffers", "buf" },
115  { ADDR_WINDOWS, "windows", "win" },
116  { ADDR_QUICKFIX, "quickfix", "qf" },
117  { ADDR_OTHER, "other", "?" },
118  { ADDR_NONE, NULL, NULL }
119};
120
121/// Search for a user command that matches "eap->cmd".
122/// Return cmdidx in "eap->cmdidx", flags in "eap->argt", idx in "eap->useridx".
123/// Return a pointer to just after the command.
124/// Return NULL if there is no matching command.
125///
126/// @param *p      end of the command (possibly including count)
127/// @param full    set to true for a full match
128/// @param xp      used for completion, NULL otherwise
129/// @param complp  completion flags or NULL
130char *find_ucmd(exarg_T *eap, char *p, int *full, expand_T *xp, int *complp)
131{
132  int len = (int)(p - eap->cmd);
133  int matchlen = 0;
134  bool found = false;
135  bool possible = false;
136  bool amb_local = false;            // Found ambiguous buffer-local command,
137                                     // only full match global is accepted.
138
139  // Look for buffer-local user commands first, then global ones.
140  garray_T *gap = &prevwin_curwin()->w_buffer->b_ucmds;
141  while (true) {
142    int j;
143    for (j = 0; j < gap->ga_len; j++) {
144      ucmd_T *uc = USER_CMD_GA(gap, j);
145      char *cp = eap->cmd;
146      char *np = uc->uc_name;
147      int k = 0;
148      while (k < len && *np != NUL && *cp++ == *np++) {
149        k++;
150      }
151      if (k == len || (*np == NUL && ascii_isdigit(eap->cmd[k]))) {
152        // If finding a second match, the command is ambiguous.  But
153        // not if a buffer-local command wasn't a full match and a
154        // global command is a full match.
155        if (k == len && found && *np != NUL) {
156          if (gap == &ucmds) {
157            return NULL;
158          }
159          amb_local = true;
160        }
161
162        if (!found || (k == len && *np == NUL)) {
163          // If we matched up to a digit, then there could
164          // be another command including the digit that we
165          // should use instead.
166          if (k == len) {
167            found = true;
168          } else {
169            possible = true;
170          }
171
172          if (gap == &ucmds) {
173            eap->cmdidx = CMD_USER;
174          } else {
175            eap->cmdidx = CMD_USER_BUF;
176          }
177          eap->argt = uc->uc_argt;
178          eap->useridx = j;
179          eap->addr_type = uc->uc_addr_type;
180
181          if (complp != NULL) {
182            *complp = uc->uc_compl;
183          }
184          if (xp != NULL) {
185            xp->xp_luaref = uc->uc_compl_luaref;
186            xp->xp_arg = uc->uc_compl_arg;
187            xp->xp_script_ctx = uc->uc_script_ctx;
188            xp->xp_script_ctx.sc_lnum += SOURCING_LNUM;
189          }
190          // Do not search for further abbreviations
191          // if this is an exact match.
192          matchlen = k;
193          if (k == len && *np == NUL) {
194            if (full != NULL) {
195              *full = true;
196            }
197            amb_local = false;
198            break;
199          }
200        }
201      }
202    }
203
204    // Stop if we found a full match or searched all.
205    if (j < gap->ga_len || gap == &ucmds) {
206      break;
207    }
208    gap = &ucmds;
209  }
210
211  // Only found ambiguous matches.
212  if (amb_local) {
213    if (xp != NULL) {
214      xp->xp_context = EXPAND_UNSUCCESSFUL;
215    }
216    return NULL;
217  }
218
219  // The match we found may be followed immediately by a number.  Move "p"
220  // back to point to it.
221  if (found || possible) {
222    return p + (matchlen - len);
223  }
224  return p;
225}
226
227/// Set completion context for :command
228const char *set_context_in_user_cmd(expand_T *xp, const char *arg_in)
229{
230  const char *arg = arg_in;
231  const char *p;
232
233  // Check for attributes
234  while (*arg == '-') {
235    arg++;  // Skip "-".
236    p = skiptowhite(arg);
237    if (*p == NUL) {
238      // Cursor is still in the attribute.
239      p = strchr(arg, '=');
240      if (p == NULL) {
241        // No "=", so complete attribute names.
242        xp->xp_context = EXPAND_USER_CMD_FLAGS;
243        xp->xp_pattern = (char *)arg;
244        return NULL;
245      }
246
247      // For the -complete, -nargs and -addr attributes, we complete
248      // their arguments as well.
249      if (STRNICMP(arg, "complete", (size_t)(p - arg)) == 0) {
250        xp->xp_context = EXPAND_USER_COMPLETE;
251        xp->xp_pattern = (char *)p + 1;
252        return NULL;
253      } else if (STRNICMP(arg, "nargs", (size_t)(p - arg)) == 0) {
254        xp->xp_context = EXPAND_USER_NARGS;
255        xp->xp_pattern = (char *)p + 1;
256        return NULL;
257      } else if (STRNICMP(arg, "addr", (size_t)(p - arg)) == 0) {
258        xp->xp_context = EXPAND_USER_ADDR_TYPE;
259        xp->xp_pattern = (char *)p + 1;
260        return NULL;
261      }
262      return NULL;
263    }
264    arg = skipwhite(p);
265  }
266
267  // After the attributes comes the new command name.
268  p = skiptowhite(arg);
269  if (*p == NUL) {
270    xp->xp_context = EXPAND_USER_COMMANDS;
271    xp->xp_pattern = (char *)arg;
272    return NULL;
273  }
274
275  // And finally comes a normal command.
276  return skipwhite(p);
277}
278
279/// Set the completion context for the argument of a user defined command.
280const char *set_context_in_user_cmdarg(const char *cmd FUNC_ATTR_UNUSED, const char *arg,
281                                       uint32_t argt, int context, expand_T *xp, bool forceit)
282{
283  if (context == EXPAND_NOTHING) {
284    return NULL;
285  }
286
287  if (argt & EX_XFILE) {
288    // EX_XFILE: file names are handled before this call.
289    return NULL;
290  }
291
292  if (context == EXPAND_MENUS) {
293    return set_context_in_menu_cmd(xp, cmd, (char *)arg, forceit);
294  }
295  if (context == EXPAND_COMMANDS) {
296    return arg;
297  }
298  if (context == EXPAND_MAPPINGS) {
299    return set_context_in_map_cmd(xp, "map", (char *)arg, forceit, false, false,
300                                  CMD_map);
301  }
302  // Find start of last argument.
303  if (!(argt & EX_ARGSPACE)) {
304    const char *p = arg;
305    while (*p) {
306      if (*p == ' ') {
307        // argument starts after a space
308        arg = p + 1;
309      } else if (*p == '\\' && *(p + 1) != NUL) {
310        p++;  // skip over escaped character
311      }
312      MB_PTR_ADV(p);
313    }
314  }
315  xp->xp_pattern = (char *)arg;
316  xp->xp_context = context;
317
318  return NULL;
319}
320
321char *expand_user_command_name(int idx)
322{
323  return get_user_commands(NULL, idx - CMD_SIZE);
324}
325
326/// Function given to ExpandGeneric() to obtain the list of user command names.
327char *get_user_commands(expand_T *xp FUNC_ATTR_UNUSED, int idx)
328  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
329{
330  // In cmdwin, the alternative buffer should be used.
331  const buf_T *const buf = prevwin_curwin()->w_buffer;
332
333  if (idx < buf->b_ucmds.ga_len) {
334    return USER_CMD_GA(&buf->b_ucmds, idx)->uc_name;
335  }
336
337  idx -= buf->b_ucmds.ga_len;
338  if (idx < ucmds.ga_len) {
339    char *name = USER_CMD(idx)->uc_name;
340
341    for (int i = 0; i < buf->b_ucmds.ga_len; i++) {
342      if (strcmp(name, USER_CMD_GA(&buf->b_ucmds, i)->uc_name) == 0) {
343        // global command is overruled by buffer-local one
344        return "";
345      }
346    }
347    return name;
348  }
349  return NULL;
350}
351
352/// Get the name of user command "idx".  "cmdidx" can be CMD_USER or
353/// CMD_USER_BUF.
354///
355/// @return  NULL if the command is not found.
356char *get_user_command_name(int idx, int cmdidx)
357{
358  if (cmdidx == CMD_USER && idx < ucmds.ga_len) {
359    return USER_CMD(idx)->uc_name;
360  }
361  if (cmdidx == CMD_USER_BUF) {
362    // In cmdwin, the alternative buffer should be used.
363    const buf_T *const buf = prevwin_curwin()->w_buffer;
364
365    if (idx < buf->b_ucmds.ga_len) {
366      return USER_CMD_GA(&buf->b_ucmds, idx)->uc_name;
367    }
368  }
369  return NULL;
370}
371
372/// Function given to ExpandGeneric() to obtain the list of user address type names.
373char *get_user_cmd_addr_type(expand_T *xp, int idx)
374{
375  return addr_type_complete[idx].name;
376}
377
378/// Function given to ExpandGeneric() to obtain the list of user command
379/// attributes.
380char *get_user_cmd_flags(expand_T *xp, int idx)
381{
382  static char *user_cmd_flags[] = { "addr",   "bang",     "bar",
383                                    "buffer", "complete", "count",
384                                    "nargs",  "range",    "register",
385                                    "keepscript" };
386
387  if (idx >= (int)ARRAY_SIZE(user_cmd_flags)) {
388    return NULL;
389  }
390  return user_cmd_flags[idx];
391}
392
393/// Function given to ExpandGeneric() to obtain the list of values for -nargs.
394char *get_user_cmd_nargs(expand_T *xp, int idx)
395{
396  static char *user_cmd_nargs[] = { "0", "1", "_", "*", "?", "+" };
397
398  if (idx >= (int)ARRAY_SIZE(user_cmd_nargs)) {
399    return NULL;
400  }
401  return user_cmd_nargs[idx];
402}
403
404static char *get_command_complete(int arg)
405{
406  if (arg < 0 || arg >= (int)(ARRAY_SIZE(command_complete))) {
407    return NULL;
408  }
409  return (char *)command_complete[arg];
410}
411
412/// Function given to ExpandGeneric() to obtain the list of values for -complete.
413char *get_user_cmd_complete(expand_T *xp, int idx)
414{
415  if (idx >= (int)ARRAY_SIZE(command_complete)) {
416    return NULL;
417  }
418  char *cmd_compl = get_command_complete(idx);
419  if (cmd_compl == NULL || idx == EXPAND_USER_LUA) {
420    return "";
421  }
422  return cmd_compl;
423}
424
425/// Get the name of completion type "expand" as an allocated string.
426/// "compl_arg" is the function name for "custom" and "customlist" types.
427/// Returns NULL if no completion is available.
428char *cmdcomplete_type_to_str(int expand, const char *compl_arg)
429{
430  char *cmd_compl = get_command_complete(expand);
431  if (cmd_compl == NULL || expand == EXPAND_USER_LUA) {
432    return NULL;
433  }
434
435  if (expand == EXPAND_USER_LIST || expand == EXPAND_USER_DEFINED) {
436    size_t buflen = strlen(cmd_compl) + strlen(compl_arg) + 2;
437    char *buffer = xmalloc(buflen);
438    snprintf(buffer, buflen, "%s,%s", cmd_compl, compl_arg);
439    return buffer;
440  }
441
442  return xstrdup(cmd_compl);
443}
444
445int cmdcomplete_str_to_type(const char *complete_str)
446{
447  if (strncmp(complete_str, "custom,", 7) == 0) {
448    return EXPAND_USER_DEFINED;
449  }
450  if (strncmp(complete_str, "customlist,", 11) == 0) {
451    return EXPAND_USER_LIST;
452  }
453
454  for (int i = 0; i < (int)(ARRAY_SIZE(command_complete)); i++) {
455    char *cmd_compl = get_command_complete(i);
456    if (cmd_compl == NULL) {
457      continue;
458    }
459    if (strcmp(complete_str, command_complete[i]) == 0) {
460      return i;
461    }
462  }
463
464  return EXPAND_NOTHING;
465}
466
467static void uc_list(char *name, size_t name_len)
468{
469  bool found = false;
470
471  msg_ext_set_kind("list_cmd");
472  // In cmdwin, the alternative buffer should be used.
473  const garray_T *gap = &prevwin_curwin()->w_buffer->b_ucmds;
474  while (true) {
475    int i;
476    for (i = 0; i < gap->ga_len; i++) {
477      ucmd_T *cmd = USER_CMD_GA(gap, i);
478      uint32_t a = cmd->uc_argt;
479
480      // Skip commands which don't match the requested prefix and
481      // commands filtered out.
482      if (strncmp(name, cmd->uc_name, name_len) != 0
483          || message_filtered(cmd->uc_name)) {
484        continue;
485      }
486
487      // Put out the title first time
488      if (!found) {
489        msg_puts_title(_("\n    Name              Args Address Complete    Definition"));
490      }
491      found = true;
492      msg_putchar('\n');
493      if (got_int) {
494        break;
495      }
496
497      // Special cases
498      size_t len = 4;
499      if (a & EX_BANG) {
500        msg_putchar('!');
501        len--;
502      }
503      if (a & EX_REGSTR) {
504        msg_putchar('"');
505        len--;
506      }
507      if (gap != &ucmds) {
508        msg_putchar('b');
509        len--;
510      }
511      if (a & EX_TRLBAR) {
512        msg_putchar('|');
513        len--;
514      }
515      if (len != 0) {
516        msg_puts(&"    "[4 - len]);
517      }
518
519      msg_outtrans(cmd->uc_name, HLF_D, false);
520      len = strlen(cmd->uc_name) + 4;
521
522      if (len < 21) {
523        // Field padding spaces   12345678901234567
524        static char spaces[18] = "                 ";
525        msg_puts(&spaces[len - 4]);
526        len = 21;
527      }
528      msg_putchar(' ');
529      len++;
530
531      // "over" is how much longer the name is than the column width for
532      // the name, we'll try to align what comes after.
533      const int64_t over = (int64_t)len - 22;
534      len = 0;
535
536      // Arguments
537      switch (a & (EX_EXTRA | EX_NOSPC | EX_NEEDARG | EX_ARGSPACE)) {
538      case 0:
539        IObuff[len++] = '0';
540        break;
541      case (EX_EXTRA):
542        IObuff[len++] = '*';
543        break;
544      case (EX_EXTRA | EX_NOSPC):
545        IObuff[len++] = '?';
546        break;
547      case (EX_EXTRA | EX_NEEDARG):
548        IObuff[len++] = '+';
549        break;
550      case (EX_EXTRA | EX_NOSPC | EX_NEEDARG):
551        IObuff[len++] = '1';
552        break;
553      case (EX_EXTRA | EX_NOSPC | EX_NEEDARG | EX_ARGSPACE):
554        IObuff[len++] = '_';
555        break;
556      }
557
558      do {
559        IObuff[len++] = ' ';
560      } while ((int64_t)len < 5 - over);
561
562      // Address / Range
563      if (a & (EX_RANGE | EX_COUNT)) {
564        if (a & EX_COUNT) {
565          // -count=N
566          int rc = snprintf(IObuff + len, IOSIZE - len, "%" PRId64 "c", cmd->uc_def);
567          assert(rc > 0);
568          len += (size_t)rc;
569        } else if (a & EX_DFLALL) {
570          IObuff[len++] = '%';
571        } else if (cmd->uc_def >= 0) {
572          // -range=N
573          int rc = snprintf(IObuff + len, IOSIZE - len, "%" PRId64 "", cmd->uc_def);
574          assert(rc > 0);
575          len += (size_t)rc;
576        } else {
577          IObuff[len++] = '.';
578        }
579      }
580
581      do {
582        IObuff[len++] = ' ';
583      } while ((int64_t)len < 8 - over);
584
585      // Address Type
586      for (int j = 0; addr_type_complete[j].expand != ADDR_NONE; j++) {
587        if (addr_type_complete[j].expand != ADDR_LINES
588            && addr_type_complete[j].expand == cmd->uc_addr_type) {
589          int rc = snprintf(IObuff + len, IOSIZE - len, "%s", addr_type_complete[j].shortname);
590          assert(rc > 0);
591          len += (size_t)rc;
592          break;
593        }
594      }
595
596      do {
597        IObuff[len++] = ' ';
598      } while ((int64_t)len < 13 - over);
599
600      // Completion
601      char *cmd_compl = get_command_complete(cmd->uc_compl);
602      if (cmd_compl != NULL) {
603        int rc = snprintf(IObuff + len, IOSIZE - len, "%s", get_command_complete(cmd->uc_compl));
604        assert(rc > 0);
605        len += (size_t)rc;
606      }
607
608      do {
609        IObuff[len++] = ' ';
610      } while ((int64_t)len < 25 - over);
611
612      IObuff[len] = NUL;
613      msg_outtrans(IObuff, 0, false);
614
615      if (cmd->uc_luaref != LUA_NOREF) {
616        char *fn = nlua_funcref_str(cmd->uc_luaref, NULL, true);
617        msg_puts_hl(fn, HLF_8, false);
618        xfree(fn);
619        // put the description on a new line
620        if (*cmd->uc_rep != NUL) {
621          msg_puts("\n                                               ");
622        }
623      }
624
625      msg_outtrans_special(cmd->uc_rep, false,
626                           name_len == 0 ? Columns - 47 : 0);
627      if (p_verbose > 0) {
628        last_set_msg(cmd->uc_script_ctx);
629      }
630      line_breakcheck();
631      if (got_int) {
632        break;
633      }
634    }
635    if (gap == &ucmds || i < gap->ga_len) {
636      break;
637    }
638    gap = &ucmds;
639  }
640
641  if (!found) {
642    msg(_("No user-defined commands found"), 0);
643  }
644}
645
646/// Parse address type argument
647int parse_addr_type_arg(char *value, int vallen, cmd_addr_T *addr_type_arg)
648  FUNC_ATTR_NONNULL_ALL
649{
650  int i;
651
652  for (i = 0; addr_type_complete[i].expand != ADDR_NONE; i++) {
653    int a = (int)strlen(addr_type_complete[i].name) == vallen;
654    int b = strncmp(value, addr_type_complete[i].name, (size_t)vallen) == 0;
655    if (a && b) {
656      *addr_type_arg = addr_type_complete[i].expand;
657      break;
658    }
659  }
660
661  if (addr_type_complete[i].expand == ADDR_NONE) {
662    char *err = value;
663
664    for (i = 0; err[i] != NUL && !ascii_iswhite(err[i]); i++) {}
665    err[i] = NUL;
666    semsg(_("E180: Invalid address type value: %s"), err);
667    return FAIL;
668  }
669
670  return OK;
671}
672
673/// Parse a completion argument "value[vallen]".
674/// The detected completion goes in "*complp", argument type in "*argt".
675/// When there is an argument, for function and user defined completion, it's
676/// copied to allocated memory and stored in "*compl_arg".
677///
678/// @return  FAIL if something is wrong.
679int parse_compl_arg(const char *value, int vallen, int *complp, uint32_t *argt, char **compl_arg)
680  FUNC_ATTR_NONNULL_ALL
681{
682  const char *arg = NULL;
683  size_t arglen = 0;
684  int valend = vallen;
685
686  // Look for any argument part - which is the part after any ','
687  for (int i = 0; i < vallen; i++) {
688    if (value[i] == ',') {
689      arg = (char *)&value[i + 1];
690      arglen = (size_t)(vallen - i - 1);
691      valend = i;
692      break;
693    }
694  }
695
696  int i;
697  for (i = 0; i < (int)ARRAY_SIZE(command_complete); i++) {
698    if (get_command_complete(i) == NULL) {
699      continue;
700    }
701    if ((int)strlen(command_complete[i]) == valend
702        && strncmp(value, command_complete[i], (size_t)valend) == 0) {
703      *complp = i;
704      if (i == EXPAND_BUFFERS) {
705        *argt |= EX_BUFNAME;
706      } else if (i == EXPAND_DIRECTORIES || i == EXPAND_FILES
707                 || i == EXPAND_SHELLCMDLINE) {
708        *argt |= EX_XFILE;
709      }
710      break;
711    }
712  }
713
714  if (i == (int)ARRAY_SIZE(command_complete)) {
715    semsg(_("E180: Invalid complete value: %s"), value);
716    return FAIL;
717  }
718
719  if (*complp != EXPAND_USER_DEFINED && *complp != EXPAND_USER_LIST
720      && arg != NULL) {
721    emsg(_("E468: Completion argument only allowed for custom completion"));
722    return FAIL;
723  }
724
725  if ((*complp == EXPAND_USER_DEFINED || *complp == EXPAND_USER_LIST)
726      && arg == NULL) {
727    emsg(_("E467: Custom completion requires a function argument"));
728    return FAIL;
729  }
730
731  if (arg != NULL) {
732    *compl_arg = xstrnsave(arg, arglen);
733  }
734  return OK;
735}
736
737static int uc_scan_attr(char *attr, size_t len, uint32_t *argt, int *def, int *flags, int *complp,
738                        char **compl_arg, cmd_addr_T *addr_type_arg)
739  FUNC_ATTR_NONNULL_ALL
740{
741  if (len == 0) {
742    emsg(_("E175: No attribute specified"));
743    return FAIL;
744  }
745
746  // First, try the simple attributes (no arguments)
747  if (STRNICMP(attr, "bang", len) == 0) {
748    *argt |= EX_BANG;
749  } else if (STRNICMP(attr, "buffer", len) == 0) {
750    *flags |= UC_BUFFER;
751  } else if (STRNICMP(attr, "register", len) == 0) {
752    *argt |= EX_REGSTR;
753  } else if (STRNICMP(attr, "keepscript", len) == 0) {
754    *argt |= EX_KEEPSCRIPT;
755  } else if (STRNICMP(attr, "bar", len) == 0) {
756    *argt |= EX_TRLBAR;
757  } else {
758    char *val = NULL;
759    size_t vallen = 0;
760    size_t attrlen = len;
761
762    // Look for the attribute name - which is the part before any '='
763    for (int i = 0; i < (int)len; i++) {
764      if (attr[i] == '=') {
765        val = &attr[i + 1];
766        vallen = len - (size_t)i - 1;
767        attrlen = (size_t)i;
768        break;
769      }
770    }
771
772    if (STRNICMP(attr, "nargs", attrlen) == 0) {
773      if (vallen == 1) {
774        if (*val == '0') {
775          // Do nothing - this is the default;
776        } else if (*val == '1') {
777          *argt |= (EX_EXTRA | EX_NOSPC | EX_NEEDARG);
778        } else if (*val == '*') {
779          *argt |= EX_EXTRA;
780        } else if (*val == '?') {
781          *argt |= (EX_EXTRA | EX_NOSPC);
782        } else if (*val == '+') {
783          *argt |= (EX_EXTRA | EX_NEEDARG);
784        } else if (*val == '_') {
785          *argt |= (EX_EXTRA | EX_NOSPC | EX_NEEDARG | EX_ARGSPACE);
786        } else {
787          goto wrong_nargs;
788        }
789      } else {
790wrong_nargs:
791        emsg(_("E176: Invalid number of arguments"));
792        return FAIL;
793      }
794    } else if (STRNICMP(attr, "range", attrlen) == 0) {
795      *argt |= EX_RANGE;
796      if (vallen == 1 && *val == '%') {
797        *argt |= EX_DFLALL;
798      } else if (val != NULL) {
799        char *p = val;
800        if (*def >= 0) {
801two_count:
802          emsg(_("E177: Count cannot be specified twice"));
803          return FAIL;
804        }
805
806        *def = getdigits_int(&p, true, 0);
807        *argt |= EX_ZEROR;
808
809        if (p != val + vallen || vallen == 0) {
810invalid_count:
811          emsg(_("E178: Invalid default value for count"));
812          return FAIL;
813        }
814      }
815      // default for -range is using buffer lines
816      if (*addr_type_arg == ADDR_NONE) {
817        *addr_type_arg = ADDR_LINES;
818      }
819    } else if (STRNICMP(attr, "count", attrlen) == 0) {
820      *argt |= (EX_COUNT | EX_ZEROR | EX_RANGE);
821      // default for -count is using any number
822      if (*addr_type_arg == ADDR_NONE) {
823        *addr_type_arg = ADDR_OTHER;
824      }
825
826      if (val != NULL) {
827        char *p = val;
828        if (*def >= 0) {
829          goto two_count;
830        }
831
832        *def = getdigits_int(&p, true, 0);
833
834        if (p != val + vallen) {
835          goto invalid_count;
836        }
837      }
838
839      *def = MAX(*def, 0);
840    } else if (STRNICMP(attr, "complete", attrlen) == 0) {
841      if (val == NULL) {
842        semsg(_(e_argument_required_for_str), "-complete");
843        return FAIL;
844      }
845
846      if (parse_compl_arg(val, (int)vallen, complp, argt, compl_arg)
847          == FAIL) {
848        return FAIL;
849      }
850    } else if (STRNICMP(attr, "addr", attrlen) == 0) {
851      *argt |= EX_RANGE;
852      if (val == NULL) {
853        semsg(_(e_argument_required_for_str), "-addr");
854        return FAIL;
855      }
856      if (parse_addr_type_arg(val, (int)vallen, addr_type_arg) == FAIL) {
857        return FAIL;
858      }
859      if (*addr_type_arg != ADDR_LINES) {
860        *argt |= EX_ZEROR;
861      }
862    } else {
863      char ch = attr[len];
864      attr[len] = NUL;
865      semsg(_("E181: Invalid attribute: %s"), attr);
866      attr[len] = ch;
867      return FAIL;
868    }
869  }
870
871  return OK;
872}
873
874/// Check for a valid user command name
875///
876/// If the given {name} is valid, then a pointer to the end of the valid name is returned.
877/// Otherwise, returns NULL.
878char *uc_validate_name(char *name)
879{
880  if (ASCII_ISALPHA(*name)) {
881    while (ASCII_ISALNUM(*name)) {
882      name++;
883    }
884  }
885  if (!ends_excmd(*name) && !ascii_iswhite(*name)) {
886    return NULL;
887  }
888
889  return name;
890}
891
892/// Create a new user command {name}, if one doesn't already exist.
893///
894/// This function takes ownership of compl_arg, compl_luaref, and luaref.
895///
896/// @return  OK if the command is created, FAIL otherwise.
897int uc_add_command(char *name, size_t name_len, const char *rep, uint32_t argt, int64_t def,
898                   int flags, int context, char *compl_arg, LuaRef compl_luaref,
899                   LuaRef preview_luaref, cmd_addr_T addr_type, LuaRef luaref, const char *desc,
900                   bool force)
901  FUNC_ATTR_NONNULL_ARG(1, 3)
902{
903  ucmd_T *cmd = NULL;
904  int cmp = 1;
905  char *rep_buf = NULL;
906  garray_T *gap;
907
908  replace_termcodes(rep, strlen(rep), &rep_buf, 0, 0, NULL, p_cpo);
909  if (rep_buf == NULL) {
910    // Can't replace termcodes - try using the string as is
911    rep_buf = xstrdup(rep);
912  }
913
914  // get address of growarray: global or in curbuf
915  if (flags & UC_BUFFER) {
916    gap = &curbuf->b_ucmds;
917    if (gap->ga_itemsize == 0) {
918      ga_init(gap, (int)sizeof(ucmd_T), 4);
919    }
920  } else {
921    gap = &ucmds;
922  }
923
924  int i;
925
926  // Search for the command in the already defined commands.
927  for (i = 0; i < gap->ga_len; i++) {
928    cmd = USER_CMD_GA(gap, i);
929    size_t len = strlen(cmd->uc_name);
930    cmp = strncmp(name, cmd->uc_name, name_len);
931    if (cmp == 0) {
932      if (name_len < len) {
933        cmp = -1;
934      } else if (name_len > len) {
935        cmp = 1;
936      }
937    }
938
939    if (cmp == 0) {
940      // Command can be replaced with "command!" and when sourcing the
941      // same script again, but only once.
942      if (!force
943          && (cmd->uc_script_ctx.sc_sid != current_sctx.sc_sid
944              || cmd->uc_script_ctx.sc_seq == current_sctx.sc_seq)) {
945        semsg(_("E174: Command already exists: add ! to replace it: %s"),
946              name);
947        goto fail;
948      }
949
950      XFREE_CLEAR(cmd->uc_rep);
951      XFREE_CLEAR(cmd->uc_compl_arg);
952      XFREE_CLEAR(cmd->uc_desc);
953      NLUA_CLEAR_REF(cmd->uc_luaref);
954      NLUA_CLEAR_REF(cmd->uc_compl_luaref);
955      NLUA_CLEAR_REF(cmd->uc_preview_luaref);
956      break;
957    }
958
959    // Stop as soon as we pass the name to add
960    if (cmp < 0) {
961      break;
962    }
963  }
964
965  // Extend the array unless we're replacing an existing command
966  if (cmp != 0) {
967    ga_grow(gap, 1);
968
969    char *const p = xstrnsave(name, name_len);
970
971    cmd = USER_CMD_GA(gap, i);
972    memmove(cmd + 1, cmd, (size_t)(gap->ga_len - i) * sizeof(ucmd_T));
973
974    gap->ga_len++;
975
976    cmd->uc_name = p;
977  }
978
979  cmd->uc_rep = rep_buf;
980  cmd->uc_desc = (desc != NULL && *desc != NUL) ? xstrdup(desc) : NULL;
981  cmd->uc_argt = argt;
982  cmd->uc_def = def;
983  cmd->uc_compl = context;
984  cmd->uc_script_ctx = current_sctx;
985  cmd->uc_script_ctx.sc_lnum += SOURCING_LNUM;
986  nlua_set_sctx(&cmd->uc_script_ctx);
987  cmd->uc_compl_arg = compl_arg;
988  cmd->uc_compl_luaref = compl_luaref;
989  cmd->uc_preview_luaref = preview_luaref;
990  cmd->uc_addr_type = addr_type;
991  cmd->uc_luaref = luaref;
992
993  return OK;
994
995fail:
996  xfree(rep_buf);
997  xfree(compl_arg);
998  NLUA_CLEAR_REF(luaref);
999  NLUA_CLEAR_REF(compl_luaref);
1000  NLUA_CLEAR_REF(preview_luaref);
1001  return FAIL;
1002}
1003
1004/// ":command ..."
1005void ex_command(exarg_T *eap)
1006{
1007  char *end;
1008  uint32_t argt = 0;
1009  int def = -1;
1010  int flags = 0;
1011  int context = EXPAND_NOTHING;
1012  char *compl_arg = NULL;
1013  cmd_addr_T addr_type_arg = ADDR_NONE;
1014  int has_attr = (eap->arg[0] == '-');
1015
1016  char *p = eap->arg;
1017
1018  // Check for attributes
1019  while (*p == '-') {
1020    p++;
1021    end = skiptowhite(p);
1022    if (uc_scan_attr(p, (size_t)(end - p), &argt, &def, &flags, &context, &compl_arg,
1023                     &addr_type_arg) == FAIL) {
1024      goto theend;
1025    }
1026    p = skipwhite(end);
1027  }
1028
1029  // Get the name (if any) and skip to the following argument.
1030  char *name = p;
1031  end = uc_validate_name(name);
1032  if (!end) {
1033    emsg(_("E182: Invalid command name"));
1034    goto theend;
1035  }
1036  size_t name_len = (size_t)(end - name);
1037
1038  // If there is nothing after the name, and no attributes were specified,
1039  // we are listing commands
1040  p = skipwhite(end);
1041  if (!has_attr && ends_excmd(*p)) {
1042    uc_list(name, name_len);
1043  } else if (!ASCII_ISUPPER(*name)) {
1044    emsg(_("E183: User defined commands must start with an uppercase letter"));
1045  } else if (name_len <= 4 && strncmp(name, "Next", name_len) == 0) {
1046    emsg(_("E841: Reserved name, cannot be used for user defined command"));
1047  } else if (context > 0 && (argt & EX_EXTRA) == 0) {
1048    emsg(_(e_complete_used_without_allowing_arguments));
1049  } else {
1050    uc_add_command(name, name_len, p, argt, def, flags, context, compl_arg, LUA_NOREF, LUA_NOREF,
1051                   addr_type_arg, LUA_NOREF, NULL, eap->forceit);
1052
1053    return;  // success
1054  }
1055
1056theend:
1057  xfree(compl_arg);
1058}
1059
1060/// ":comclear"
1061/// Clear all user commands, global and for current buffer.
1062void ex_comclear(exarg_T *eap)
1063{
1064  uc_clear(&ucmds);
1065  if (curbuf != NULL) {
1066    uc_clear(&curbuf->b_ucmds);
1067  }
1068}
1069
1070void free_ucmd(ucmd_T *cmd)
1071{
1072  xfree(cmd->uc_name);
1073  xfree(cmd->uc_rep);
1074  xfree(cmd->uc_compl_arg);
1075  xfree(cmd->uc_desc);
1076  NLUA_CLEAR_REF(cmd->uc_compl_luaref);
1077  NLUA_CLEAR_REF(cmd->uc_luaref);
1078  NLUA_CLEAR_REF(cmd->uc_preview_luaref);
1079}
1080
1081/// Clear all user commands for "gap".
1082void uc_clear(garray_T *gap)
1083{
1084  GA_DEEP_CLEAR(gap, ucmd_T, free_ucmd);
1085}
1086
1087void ex_delcommand(exarg_T *eap)
1088{
1089  int i = 0;
1090  ucmd_T *cmd = NULL;
1091  int res = -1;
1092  const char *arg = eap->arg;
1093  bool buffer_only = false;
1094
1095  if (strncmp(arg, "-buffer", 7) == 0 && ascii_iswhite(arg[7])) {
1096    buffer_only = true;
1097    arg = skipwhite(arg + 7);
1098  }
1099
1100  garray_T *gap = &curbuf->b_ucmds;
1101  while (true) {
1102    for (i = 0; i < gap->ga_len; i++) {
1103      cmd = USER_CMD_GA(gap, i);
1104      res = strcmp(arg, cmd->uc_name);
1105      if (res <= 0) {
1106        break;
1107      }
1108    }
1109    if (gap == &ucmds || res == 0 || buffer_only) {
1110      break;
1111    }
1112    gap = &ucmds;
1113  }
1114
1115  if (res != 0) {
1116    semsg(_(buffer_only
1117            ? e_no_such_user_defined_command_in_current_buffer_str
1118            : e_no_such_user_defined_command_str),
1119          arg);
1120    return;
1121  }
1122
1123  free_ucmd(cmd);
1124
1125  gap->ga_len--;
1126
1127  if (i < gap->ga_len) {
1128    memmove(cmd, cmd + 1, (size_t)(gap->ga_len - i) * sizeof(ucmd_T));
1129  }
1130}
1131
1132/// Split a string by unescaped whitespace (space & tab), used for f-args on Lua commands callback.
1133/// Similar to uc_split_args(), but does not allocate, add quotes, add commas and is an iterator.
1134///
1135/// @param[in]  arg String to split
1136/// @param[in]  arglen Length of {arg}
1137/// @param[inout] end Index of last character of previous iteration
1138/// @param[out] buf Buffer to copy string into
1139/// @param[out] len Length of string in {buf}
1140///
1141/// @return true if iteration is complete, else false
1142bool uc_split_args_iter(const char *arg, size_t arglen, size_t *end, char *buf, size_t *len)
1143{
1144  if (!arglen) {
1145    return true;
1146  }
1147
1148  size_t pos = *end;
1149  while (pos < arglen && ascii_iswhite(arg[pos])) {
1150    pos++;
1151  }
1152
1153  size_t l = 0;
1154  for (; pos < arglen - 1; pos++) {
1155    if (arg[pos] == '\\' && (arg[pos + 1] == '\\' || ascii_iswhite(arg[pos + 1]))) {
1156      buf[l++] = arg[++pos];
1157    } else {
1158      buf[l++] = arg[pos];
1159    }
1160    if (ascii_iswhite(arg[pos + 1])) {
1161      *end = pos + 1;
1162      *len = l;
1163      return false;
1164    }
1165  }
1166
1167  if (pos < arglen && !ascii_iswhite(arg[pos])) {
1168    buf[l++] = arg[pos];
1169  }
1170
1171  *len = l;
1172  return true;
1173}
1174
1175size_t uc_nargs_upper_bound(const char *arg, size_t arglen)
1176{
1177  bool was_white = true;  // space before first arg
1178  size_t nargs = 0;
1179  for (size_t i = 0; i < arglen; i++) {
1180    bool is_white = ascii_iswhite(arg[i]);
1181    if (was_white && !is_white) {
1182      nargs++;
1183    }
1184    was_white = is_white;
1185  }
1186  return nargs;
1187}
1188
1189/// split and quote args for <f-args>
1190static char *uc_split_args(const char *arg, char **args, const size_t *arglens, size_t argc,
1191                           size_t *lenp)
1192{
1193  // Precalculate length
1194  int len = 2;   // Initial and final quotes
1195  if (args == NULL) {
1196    const char *p = arg;
1197
1198    while (*p) {
1199      if (p[0] == '\\' && p[1] == '\\') {
1200        len += 2;
1201        p += 2;
1202      } else if (p[0] == '\\' && ascii_iswhite(p[1])) {
1203        len += 1;
1204        p += 2;
1205      } else if (*p == '\\' || *p == '"') {
1206        len += 2;
1207        p += 1;
1208      } else if (ascii_iswhite(*p)) {
1209        p = skipwhite(p);
1210        if (*p == NUL) {
1211          break;
1212        }
1213        len += 4;  // ", "
1214      } else {
1215        const int charlen = utfc_ptr2len(p);
1216
1217        len += charlen;
1218        p += charlen;
1219      }
1220    }
1221  } else {
1222    for (size_t i = 0; i < argc; i++) {
1223      const char *p = args[i];
1224      const char *arg_end = args[i] + arglens[i];
1225
1226      while (p < arg_end) {
1227        if (*p == '\\' || *p == '"') {
1228          len += 2;
1229          p += 1;
1230        } else {
1231          const int charlen = utfc_ptr2len(p);
1232
1233          len += charlen;
1234          p += charlen;
1235        }
1236      }
1237
1238      if (i != argc - 1) {
1239        len += 4;  // ", "
1240      }
1241    }
1242  }
1243
1244  char *buf = xmalloc((size_t)len + 1);
1245
1246  char *q = buf;
1247  *q++ = '"';
1248
1249  if (args == NULL) {
1250    const char *p = arg;
1251    while (*p) {
1252      if (p[0] == '\\' && p[1] == '\\') {
1253        *q++ = '\\';
1254        *q++ = '\\';
1255        p += 2;
1256      } else if (p[0] == '\\' && ascii_iswhite(p[1])) {
1257        *q++ = p[1];
1258        p += 2;
1259      } else if (*p == '\\' || *p == '"') {
1260        *q++ = '\\';
1261        *q++ = *p++;
1262      } else if (ascii_iswhite(*p)) {
1263        p = skipwhite(p);
1264        if (*p == NUL) {
1265          break;
1266        }
1267        *q++ = '"';
1268        *q++ = ',';
1269        *q++ = ' ';
1270        *q++ = '"';
1271      } else {
1272        mb_copy_char(&p, &q);
1273      }
1274    }
1275  } else {
1276    for (size_t i = 0; i < argc; i++) {
1277      const char *p = args[i];
1278      const char *arg_end = args[i] + arglens[i];
1279
1280      while (p < arg_end) {
1281        if (*p == '\\' || *p == '"') {
1282          *q++ = '\\';
1283          *q++ = *p++;
1284        } else {
1285          mb_copy_char(&p, &q);
1286        }
1287      }
1288      if (i != argc - 1) {
1289        *q++ = '"';
1290        *q++ = ',';
1291        *q++ = ' ';
1292        *q++ = '"';
1293      }
1294    }
1295  }
1296
1297  *q++ = '"';
1298  *q = 0;
1299
1300  *lenp = (size_t)len;
1301  return buf;
1302}
1303
1304static size_t add_cmd_modifier(char *buf, char *mod_str, bool *multi_mods)
1305{
1306  size_t result = strlen(mod_str);
1307  if (*multi_mods) {
1308    result++;
1309  }
1310
1311  if (buf != NULL) {
1312    if (*multi_mods) {
1313      strcat(buf, " ");
1314    }
1315    strcat(buf, mod_str);
1316  }
1317
1318  *multi_mods = true;
1319  return result;
1320}
1321
1322/// Add modifiers from "cmod->cmod_split" to "buf".  Set "multi_mods" when one
1323/// was added.
1324///
1325/// @return the number of bytes added
1326size_t add_win_cmd_modifiers(char *buf, const cmdmod_T *cmod, bool *multi_mods)
1327{
1328  size_t result = 0;
1329
1330  // :aboveleft and :leftabove
1331  if (cmod->cmod_split & WSP_ABOVE) {
1332    result += add_cmd_modifier(buf, "aboveleft", multi_mods);
1333  }
1334  // :belowright and :rightbelow
1335  if (cmod->cmod_split & WSP_BELOW) {
1336    result += add_cmd_modifier(buf, "belowright", multi_mods);
1337  }
1338  // :botright
1339  if (cmod->cmod_split & WSP_BOT) {
1340    result += add_cmd_modifier(buf, "botright", multi_mods);
1341  }
1342
1343  // :tab
1344  if (cmod->cmod_tab > 0) {
1345    int tabnr = cmod->cmod_tab - 1;
1346    if (tabnr == tabpage_index(curtab)) {
1347      // For compatibility, don't add a tabpage number if it is the same
1348      // as the default number for :tab.
1349      result += add_cmd_modifier(buf, "tab", multi_mods);
1350    } else {
1351      char tab_buf[NUMBUFLEN + 3];
1352      snprintf(tab_buf, sizeof(tab_buf), "%dtab", tabnr);
1353      result += add_cmd_modifier(buf, tab_buf, multi_mods);
1354    }
1355  }
1356
1357  // :topleft
1358  if (cmod->cmod_split & WSP_TOP) {
1359    result += add_cmd_modifier(buf, "topleft", multi_mods);
1360  }
1361  // :vertical
1362  if (cmod->cmod_split & WSP_VERT) {
1363    result += add_cmd_modifier(buf, "vertical", multi_mods);
1364  }
1365  // :horizontal
1366  if (cmod->cmod_split & WSP_HOR) {
1367    result += add_cmd_modifier(buf, "horizontal", multi_mods);
1368  }
1369  return result;
1370}
1371
1372/// Generate text for the "cmod" command modifiers.
1373/// If "buf" is NULL just return the length.
1374size_t uc_mods(char *buf, const cmdmod_T *cmod, bool quote)
1375{
1376  size_t result = 0;
1377  bool multi_mods = false;
1378
1379  typedef struct {
1380    int flag;
1381    char *name;
1382  } mod_entry_T;
1383  static mod_entry_T mod_entries[] = {
1384    { CMOD_BROWSE, "browse" },
1385    { CMOD_CONFIRM, "confirm" },
1386    { CMOD_HIDE, "hide" },
1387    { CMOD_KEEPALT, "keepalt" },
1388    { CMOD_KEEPJUMPS, "keepjumps" },
1389    { CMOD_KEEPMARKS, "keepmarks" },
1390    { CMOD_KEEPPATTERNS, "keeppatterns" },
1391    { CMOD_LOCKMARKS, "lockmarks" },
1392    { CMOD_NOSWAPFILE, "noswapfile" },
1393    { CMOD_UNSILENT, "unsilent" },
1394    { CMOD_NOAUTOCMD, "noautocmd" },
1395    { CMOD_SANDBOX, "sandbox" },
1396  };
1397
1398  result = quote ? 2 : 0;
1399  if (buf != NULL) {
1400    if (quote) {
1401      *buf++ = '"';
1402    }
1403    *buf = NUL;
1404  }
1405
1406  // the modifiers that are simple flags
1407  for (size_t i = 0; i < ARRAY_SIZE(mod_entries); i++) {
1408    if (cmod->cmod_flags & mod_entries[i].flag) {
1409      result += add_cmd_modifier(buf, mod_entries[i].name, &multi_mods);
1410    }
1411  }
1412
1413  // :silent
1414  if (cmod->cmod_flags & CMOD_SILENT) {
1415    result += add_cmd_modifier(buf,
1416                               (cmod->cmod_flags & CMOD_ERRSILENT) ? "silent!" : "silent",
1417                               &multi_mods);
1418  }
1419  // :verbose
1420  if (cmod->cmod_verbose > 0) {
1421    int verbose_value = cmod->cmod_verbose - 1;
1422    if (verbose_value == 1) {
1423      result += add_cmd_modifier(buf, "verbose", &multi_mods);
1424    } else {
1425      char verbose_buf[NUMBUFLEN];
1426      snprintf(verbose_buf, sizeof(verbose_buf), "%dverbose", verbose_value);
1427      result += add_cmd_modifier(buf, verbose_buf, &multi_mods);
1428    }
1429  }
1430  // flags from cmod->cmod_split
1431  result += add_win_cmd_modifiers(buf, cmod, &multi_mods);
1432
1433  if (quote && buf != NULL) {
1434    buf += result - 2;
1435    *buf = '"';
1436  }
1437  return result;
1438}
1439
1440/// Check for a <> code in a user command.
1441///
1442/// @param code       points to the '<'.  "len" the length of the <> (inclusive).
1443/// @param buf        is where the result is to be added.
1444/// @param cmd        the user command we're expanding
1445/// @param eap        ex arguments
1446/// @param split_buf  points to a buffer used for splitting, caller should free it.
1447/// @param split_len  is the length of what "split_buf" contains.
1448///
1449/// @return           the length of the replacement, which has been added to "buf".
1450///                   Return -1 if there was no match, and only the "<" has been copied.
1451static size_t uc_check_code(char *code, size_t len, char *buf, ucmd_T *cmd, exarg_T *eap,
1452                            char **split_buf, size_t *split_len)
1453{
1454  size_t result = 0;
1455  char *p = code + 1;
1456  size_t l = len - 2;
1457  int quote = 0;
1458  enum {
1459    ct_ARGS,
1460    ct_BANG,
1461    ct_COUNT,
1462    ct_LINE1,
1463    ct_LINE2,
1464    ct_RANGE,
1465    ct_MODS,
1466    ct_REGISTER,
1467    ct_LT,
1468    ct_NONE,
1469  } type = ct_NONE;
1470
1471  if ((vim_strchr("qQfF", (uint8_t)(*p)) != NULL) && p[1] == '-') {
1472    quote = (*p == 'q' || *p == 'Q') ? 1 : 2;
1473    p += 2;
1474    l -= 2;
1475  }
1476
1477  l++;
1478  if (l <= 1) {
1479    // type = ct_NONE;
1480  } else if (STRNICMP(p, "args>", l) == 0) {
1481    type = ct_ARGS;
1482  } else if (STRNICMP(p, "bang>", l) == 0) {
1483    type = ct_BANG;
1484  } else if (STRNICMP(p, "count>", l) == 0) {
1485    type = ct_COUNT;
1486  } else if (STRNICMP(p, "line1>", l) == 0) {
1487    type = ct_LINE1;
1488  } else if (STRNICMP(p, "line2>", l) == 0) {
1489    type = ct_LINE2;
1490  } else if (STRNICMP(p, "range>", l) == 0) {
1491    type = ct_RANGE;
1492  } else if (STRNICMP(p, "lt>", l) == 0) {
1493    type = ct_LT;
1494  } else if (STRNICMP(p, "reg>", l) == 0 || STRNICMP(p, "register>", l) == 0) {
1495    type = ct_REGISTER;
1496  } else if (STRNICMP(p, "mods>", l) == 0) {
1497    type = ct_MODS;
1498  }
1499
1500  switch (type) {
1501  case ct_ARGS:
1502    // Simple case first
1503    if (*eap->arg == NUL) {
1504      if (quote == 1) {
1505        result = 2;
1506        if (buf != NULL) {
1507          STRCPY(buf, "''");
1508        }
1509      } else {
1510        result = 0;
1511      }
1512      break;
1513    }
1514
1515    // When specified there is a single argument don't split it.
1516    // Works for ":Cmd %" when % is "a b c".
1517    if ((eap->argt & EX_NOSPC) && quote == 2) {
1518      quote = 1;
1519    }
1520
1521    switch (quote) {
1522    case 0:     // No quoting, no splitting
1523      result = strlen(eap->arg);
1524      if (buf != NULL) {
1525        STRCPY(buf, eap->arg);
1526      }
1527      break;
1528    case 1:     // Quote, but don't split
1529      result = strlen(eap->arg) + 2;
1530      for (p = eap->arg; *p; p++) {
1531        if (*p == '\\' || *p == '"') {
1532          result++;
1533        }
1534      }
1535
1536      if (buf != NULL) {
1537        *buf++ = '"';
1538        for (p = eap->arg; *p; p++) {
1539          if (*p == '\\' || *p == '"') {
1540            *buf++ = '\\';
1541          }
1542          *buf++ = *p;
1543        }
1544        *buf = '"';
1545      }
1546
1547      break;
1548    case 2:     // Quote and split (<f-args>)
1549      // This is hard, so only do it once, and cache the result
1550      if (*split_buf == NULL) {
1551        *split_buf = uc_split_args(eap->arg, eap->args, eap->arglens, eap->argc, split_len);
1552      }
1553
1554      result = *split_len;
1555      if (buf != NULL && result != 0) {
1556        STRCPY(buf, *split_buf);
1557      }
1558
1559      break;
1560    }
1561    break;
1562
1563  case ct_BANG:
1564    result = eap->forceit ? 1 : 0;
1565    if (quote) {
1566      result += 2;
1567    }
1568    if (buf != NULL) {
1569      if (quote) {
1570        *buf++ = '"';
1571      }
1572      if (eap->forceit) {
1573        *buf++ = '!';
1574      }
1575      if (quote) {
1576        *buf = '"';
1577      }
1578    }
1579    break;
1580
1581  case ct_LINE1:
1582  case ct_LINE2:
1583  case ct_RANGE:
1584  case ct_COUNT: {
1585    char num_buf[20];
1586    int64_t num = type == ct_LINE1
1587                  ? eap->line1
1588                  : (type == ct_LINE2
1589                     ? eap->line2
1590                     : (type == ct_RANGE
1591                        ? eap->addr_count
1592                        : (eap->addr_count > 0 ? eap->line2 : cmd->uc_def)));
1593    size_t num_len;
1594
1595    snprintf(num_buf, sizeof(num_buf), "%" PRId64, num);
1596    num_len = strlen(num_buf);
1597    result = num_len;
1598
1599    if (quote) {
1600      result += 2;
1601    }
1602
1603    if (buf != NULL) {
1604      if (quote) {
1605        *buf++ = '"';
1606      }
1607      STRCPY(buf, num_buf);
1608      buf += num_len;
1609      if (quote) {
1610        *buf = '"';
1611      }
1612    }
1613
1614    break;
1615  }
1616
1617  case ct_MODS:
1618    result = uc_mods(buf, &cmdmod, quote);
1619    break;
1620
1621  case ct_REGISTER:
1622    result = eap->regname ? 1 : 0;
1623    if (quote) {
1624      result += 2;
1625    }
1626    if (buf != NULL) {
1627      if (quote) {
1628        *buf++ = '\'';
1629      }
1630      if (eap->regname) {
1631        *buf++ = (char)eap->regname;
1632      }
1633      if (quote) {
1634        *buf = '\'';
1635      }
1636    }
1637    break;
1638
1639  case ct_LT:
1640    result = 1;
1641    if (buf != NULL) {
1642      *buf = '<';
1643    }
1644    break;
1645
1646  default:
1647    // Not recognized: just copy the '<' and return -1.
1648    result = (size_t)-1;
1649    if (buf != NULL) {
1650      *buf = '<';
1651    }
1652    break;
1653  }
1654
1655  return result;
1656}
1657
1658int do_ucmd(exarg_T *eap, bool preview)
1659{
1660  char *end = NULL;
1661
1662  size_t split_len = 0;
1663  char *split_buf = NULL;
1664  ucmd_T *cmd;
1665
1666  if (eap->cmdidx == CMD_USER) {
1667    cmd = USER_CMD(eap->useridx);
1668  } else {
1669    cmd = USER_CMD_GA(&prevwin_curwin()->w_buffer->b_ucmds, eap->useridx);
1670  }
1671
1672  if (preview) {
1673    assert(cmd->uc_preview_luaref > 0);
1674    return nlua_do_ucmd(cmd, eap, true);
1675  }
1676
1677  if (cmd->uc_luaref > 0) {
1678    nlua_do_ucmd(cmd, eap, false);
1679    return 0;
1680  }
1681
1682  // Replace <> in the command by the arguments.
1683  // First round: "buf" is NULL, compute length, allocate "buf".
1684  // Second round: copy result into "buf".
1685  char *buf = NULL;
1686  while (true) {
1687    char *p = cmd->uc_rep;        // source
1688    char *q = buf;                // destination
1689    size_t totlen = 0;
1690
1691    while (true) {
1692      char *start = vim_strchr(p, '<');
1693      if (start != NULL) {
1694        end = vim_strchr(start + 1, '>');
1695      }
1696      if (buf != NULL) {
1697        char *ksp;
1698        for (ksp = p; *ksp != NUL && (uint8_t)(*ksp) != K_SPECIAL; ksp++) {}
1699        if ((uint8_t)(*ksp) == K_SPECIAL
1700            && (start == NULL || ksp < start || end == NULL)
1701            && ((uint8_t)ksp[1] == KS_SPECIAL && ksp[2] == KE_FILLER)) {
1702          // K_SPECIAL has been put in the buffer as K_SPECIAL
1703          // KS_SPECIAL KE_FILLER, like for mappings, but
1704          // do_cmdline() doesn't handle that, so convert it back.
1705          size_t len = (size_t)(ksp - p);
1706          if (len > 0) {
1707            memmove(q, p, len);
1708            q += len;
1709          }
1710          *q++ = (char)K_SPECIAL;
1711          p = ksp + 3;
1712          continue;
1713        }
1714      }
1715
1716      // break if no <item> is found
1717      if (start == NULL || end == NULL) {
1718        break;
1719      }
1720
1721      // Include the '>'
1722      end++;
1723
1724      // Take everything up to the '<'
1725      size_t len = (size_t)(start - p);
1726      if (buf == NULL) {
1727        totlen += len;
1728      } else {
1729        memmove(q, p, len);
1730        q += len;
1731      }
1732
1733      len = uc_check_code(start, (size_t)(end - start), q, cmd, eap, &split_buf, &split_len);
1734      if (len == (size_t)-1) {
1735        // no match, continue after '<'
1736        p = start + 1;
1737        len = 1;
1738      } else {
1739        p = end;
1740      }
1741      if (buf == NULL) {
1742        totlen += len;
1743      } else {
1744        q += len;
1745      }
1746    }
1747    if (buf != NULL) {              // second time here, finished
1748      STRCPY(q, p);
1749      break;
1750    }
1751
1752    totlen += strlen(p);            // Add on the trailing characters
1753    buf = xmalloc(totlen + 1);
1754  }
1755
1756  sctx_T save_current_sctx;
1757  bool restore_current_sctx = false;
1758  if ((cmd->uc_argt & EX_KEEPSCRIPT) == 0) {
1759    restore_current_sctx = true;
1760    save_current_sctx = current_sctx;
1761    current_sctx.sc_sid = cmd->uc_script_ctx.sc_sid;
1762  }
1763  do_cmdline(buf, eap->ea_getline, eap->cookie,
1764             DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
1765
1766  // Careful: Do not use "cmd" here, it may have become invalid if a user
1767  // command was added.
1768  if (restore_current_sctx) {
1769    current_sctx = save_current_sctx;
1770  }
1771  xfree(buf);
1772  xfree(split_buf);
1773
1774  return 0;
1775}
1776
1777/// Gets a map of maps describing user-commands defined for buffer `buf` or
1778/// defined globally if `buf` is NULL.
1779///
1780/// @param buf  Buffer to inspect, or NULL to get global commands.
1781///
1782/// @return Map of maps describing commands
1783Dict commands_array(buf_T *buf, Arena *arena)
1784{
1785  garray_T *gap = (buf == NULL) ? &ucmds : &buf->b_ucmds;
1786
1787  Dict rv = arena_dict(arena, (size_t)gap->ga_len);
1788  for (int i = 0; i < gap->ga_len; i++) {
1789    char arg[2] = { 0, 0 };
1790    Dict d = arena_dict(arena, 16);
1791    ucmd_T *cmd = USER_CMD_GA(gap, i);
1792
1793    PUT_C(d, "name", CSTR_AS_OBJ(cmd->uc_name));
1794    PUT_C(d, "definition", CSTR_AS_OBJ(cmd->uc_rep));
1795    PUT_C(d, "desc", CSTR_AS_OBJ(cmd->uc_desc));
1796    PUT_C(d, "script_id", INTEGER_OBJ(cmd->uc_script_ctx.sc_sid));
1797    PUT_C(d, "bang", BOOLEAN_OBJ(!!(cmd->uc_argt & EX_BANG)));
1798    PUT_C(d, "bar", BOOLEAN_OBJ(!!(cmd->uc_argt & EX_TRLBAR)));
1799    PUT_C(d, "register", BOOLEAN_OBJ(!!(cmd->uc_argt & EX_REGSTR)));
1800    PUT_C(d, "keepscript", BOOLEAN_OBJ(!!(cmd->uc_argt & EX_KEEPSCRIPT)));
1801
1802    if (cmd->uc_preview_luaref != LUA_NOREF) {
1803      PUT_C(d, "preview", LUAREF_OBJ(api_new_luaref(cmd->uc_preview_luaref)));
1804    }
1805
1806    if (cmd->uc_luaref != LUA_NOREF) {
1807      PUT_C(d, "callback", LUAREF_OBJ(api_new_luaref(cmd->uc_luaref)));
1808    }
1809
1810    switch (cmd->uc_argt & (EX_EXTRA | EX_NOSPC | EX_NEEDARG | EX_ARGSPACE)) {
1811    case 0:
1812      arg[0] = '0'; break;
1813    case (EX_EXTRA):
1814      arg[0] = '*'; break;
1815    case (EX_EXTRA | EX_NOSPC):
1816      arg[0] = '?'; break;
1817    case (EX_EXTRA | EX_NEEDARG):
1818      arg[0] = '+'; break;
1819    case (EX_EXTRA | EX_NOSPC | EX_NEEDARG):
1820      arg[0] = '1'; break;
1821    case (EX_EXTRA | EX_NOSPC | EX_NEEDARG | EX_ARGSPACE):
1822      arg[0] = '_'; break;
1823    }
1824    PUT_C(d, "nargs", CSTR_TO_ARENA_OBJ(arena, arg));
1825
1826    if (cmd->uc_compl_luaref != LUA_NOREF) {
1827      PUT_C(d, "complete", LUAREF_OBJ(api_new_luaref(cmd->uc_compl_luaref)));
1828    } else {
1829      char *cmd_compl = get_command_complete(cmd->uc_compl);
1830      PUT_C(d, "complete", (cmd_compl == NULL ? NIL : CSTR_AS_OBJ(cmd_compl)));
1831    }
1832    PUT_C(d, "complete_arg", cmd->uc_compl_arg == NULL
1833          ? NIL : CSTR_AS_OBJ(cmd->uc_compl_arg));
1834
1835    Object obj = NIL;
1836    if (cmd->uc_argt & EX_COUNT) {
1837      if (cmd->uc_def >= 0) {
1838        obj = STRING_OBJ(arena_printf(arena, "%" PRId64, cmd->uc_def));    // -count=N
1839      } else {
1840        obj = CSTR_AS_OBJ("0");    // -count
1841      }
1842    }
1843    PUT_C(d, "count", obj);
1844
1845    obj = NIL;
1846    if (cmd->uc_argt & EX_RANGE) {
1847      if (cmd->uc_argt & EX_DFLALL) {
1848        obj = STATIC_CSTR_AS_OBJ("%");    // -range=%
1849      } else if (cmd->uc_def >= 0) {
1850        obj = STRING_OBJ(arena_printf(arena, "%" PRId64, cmd->uc_def));    // -range=N
1851      } else {
1852        obj = STATIC_CSTR_AS_OBJ(".");    // -range
1853      }
1854    }
1855    PUT_C(d, "range", obj);
1856
1857    obj = NIL;
1858    for (int j = 0; addr_type_complete[j].expand != ADDR_NONE; j++) {
1859      if (addr_type_complete[j].expand != ADDR_LINES
1860          && addr_type_complete[j].expand == cmd->uc_addr_type) {
1861        obj = CSTR_AS_OBJ(addr_type_complete[j].name);
1862        break;
1863      }
1864    }
1865    PUT_C(d, "addr", obj);
1866
1867    PUT_C(rv, cmd->uc_name, DICT_OBJ(d));
1868  }
1869  return rv;
1870}