robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
41.1 KiB1273 linesraw
1#include <inttypes.h>
2#include <lauxlib.h>
3#include <stdbool.h>
4#include <stdio.h>
5#include <string.h>
6
7#include "klib/kvec.h"
8#include "nvim/api/command.h"
9#include "nvim/api/keysets_defs.h"
10#include "nvim/api/private/defs.h"
11#include "nvim/api/private/dispatch.h"
12#include "nvim/api/private/helpers.h"
13#include "nvim/api/private/validate.h"
14#include "nvim/ascii_defs.h"
15#include "nvim/autocmd.h"
16#include "nvim/autocmd_defs.h"
17#include "nvim/buffer_defs.h"
18#include "nvim/charset.h"
19#include "nvim/cmdexpand_defs.h"
20#include "nvim/ex_cmds_defs.h"
21#include "nvim/ex_docmd.h"
22#include "nvim/ex_eval.h"
23#include "nvim/garray.h"
24#include "nvim/garray_defs.h"
25#include "nvim/globals.h"
26#include "nvim/lua/executor.h"
27#include "nvim/macros_defs.h"
28#include "nvim/mbyte.h"
29#include "nvim/memory.h"
30#include "nvim/memory_defs.h"
31#include "nvim/pos_defs.h"
32#include "nvim/regexp.h"
33#include "nvim/register.h"
34#include "nvim/strings.h"
35#include "nvim/types_defs.h"
36#include "nvim/usercmd.h"
37#include "nvim/vim_defs.h"
38#include "nvim/window.h"
39
40#include "api/command.c.generated.h"
41
42/// Parse arguments for :map/:abbrev commands, preserving whitespace in RHS.
43/// @param arg_str  The argument string to parse
44/// @param arena    Arena allocator
45/// @return Array with at most 2 elements: [lhs, rhs]
46static Array parse_map_cmd(const char *arg_str, Arena *arena)
47{
48  Array args = arena_array(arena, 2);
49
50  char *lhs_start = (char *)arg_str;
51  char *lhs_end = skiptowhite(lhs_start);
52  size_t lhs_len = (size_t)(lhs_end - lhs_start);
53
54  // Add the LHS (first argument)
55  ADD_C(args, STRING_OBJ(cstrn_as_string(lhs_start, lhs_len)));
56
57  // Add the RHS (second argument) if it exists, preserving all whitespace
58  char *rhs_start = skipwhite(lhs_end);
59  if (*rhs_start != NUL) {
60    size_t rhs_len = strlen(rhs_start);
61    ADD_C(args, STRING_OBJ(cstrn_as_string(rhs_start, rhs_len)));
62  }
63
64  return args;
65}
66
67/// Parse command line.
68///
69/// Doesn't check the validity of command arguments.
70///
71/// @param str       Command line string to parse. Cannot contain "\n".
72/// @param opts      Optional parameters. Reserved for future use.
73/// @param[out] err  Error details, if any.
74/// @return Dict containing command information, with these keys:
75///         - cmd: (string) Command name.
76///         - range: (array) (optional) Command range ([<line1>] [<line2>]).
77///                          Omitted if command doesn't accept a range.
78///                          Otherwise, has no elements if no range was specified, one element if
79///                          only a single range item was specified, or two elements if both range
80///                          items were specified.
81///         - count: (number) (optional) Command [<count>].
82///                           Omitted if command cannot take a count.
83///         - reg: (string) (optional) Command [<register>].
84///                         Omitted if command cannot take a register.
85///         - bang: (boolean) Whether command contains a [<bang>] (!) modifier.
86///         - args: (array) Command arguments.
87///         - addr: (string) Value of |:command-addr|. Uses short name or "line" for -addr=lines.
88///         - nargs: (string) Value of |:command-nargs|.
89///         - nextcmd: (string) Next command if there are multiple commands separated by a |:bar|.
90///                             Empty if there isn't a next command.
91///         - magic: (dict) Which characters have special meaning in the command arguments.
92///             - file: (boolean) The command expands filenames. Which means characters such as "%",
93///                               "#" and wildcards are expanded.
94///             - bar: (boolean) The "|" character is treated as a command separator and the double
95///                              quote character (") is treated as the start of a comment.
96///         - mods: (dict) |:command-modifiers|.
97///             - filter: (dict) |:filter|.
98///                 - pattern: (string) Filter pattern. Empty string if there is no filter.
99///                 - force: (boolean) Whether filter is inverted or not.
100///             - silent: (boolean) |:silent|.
101///             - emsg_silent: (boolean) |:silent!|.
102///             - unsilent: (boolean) |:unsilent|.
103///             - sandbox: (boolean) |:sandbox|.
104///             - noautocmd: (boolean) |:noautocmd|.
105///             - browse: (boolean) |:browse|.
106///             - confirm: (boolean) |:confirm|.
107///             - hide: (boolean) |:hide|.
108///             - horizontal: (boolean) |:horizontal|.
109///             - keepalt: (boolean) |:keepalt|.
110///             - keepjumps: (boolean) |:keepjumps|.
111///             - keepmarks: (boolean) |:keepmarks|.
112///             - keeppatterns: (boolean) |:keeppatterns|.
113///             - lockmarks: (boolean) |:lockmarks|.
114///             - noswapfile: (boolean) |:noswapfile|.
115///             - tab: (integer) |:tab|. -1 when omitted.
116///             - verbose: (integer) |:verbose|. -1 when omitted.
117///             - vertical: (boolean) |:vertical|.
118///             - split: (string) Split modifier string, is an empty string when there's no split
119///                               modifier. If there is a split modifier it can be one of:
120///               - "aboveleft": |:aboveleft|.
121///               - "belowright": |:belowright|.
122///               - "topleft": |:topleft|.
123///               - "botright": |:botright|.
124Dict(cmd) nvim_parse_cmd(String str, Dict(empty) *opts, Arena *arena, Error *err)
125  FUNC_API_SINCE(10) FUNC_API_FAST
126{
127  Dict(cmd) result = KEYDICT_INIT;
128
129  // Parse command line
130  exarg_T ea;
131  cmdmod_T cmod;
132  char *cmdline = arena_memdupz(arena, str.data, str.size);
133  const char *errormsg = NULL;
134
135  if (!parse_cmdline(&cmdline, &ea, &cmod, &errormsg, false)) {
136    if (errormsg != NULL) {
137      api_set_error(err, kErrorTypeException, "Parsing command-line: %s", errormsg);
138    } else {
139      api_set_error(err, kErrorTypeException, "Parsing command-line");
140    }
141    goto end;
142  }
143
144  // Parse arguments
145  Array args = ARRAY_DICT_INIT;
146  size_t length = strlen(ea.arg);
147
148  // Check if this is a mapping command that needs special handling
149  // like mapping commands need special argument parsing to preserve whitespace in RHS:
150  // "map a b  c" => { args=["a", "b  c"], ... }
151  if (ea.cmdidx != CMD_SIZE && is_map_cmd(ea.cmdidx) && *ea.arg != NUL) {
152    // For mapping commands, split differently to preserve whitespace
153    args = parse_map_cmd(ea.arg, arena);
154  } else if (ea.argt & EX_NOSPC) {
155    // For nargs = 1 or '_' or '?', pass the entire argument list as a single argument,
156    // otherwise split arguments by whitespace.
157    if (*ea.arg != NUL) {
158      args = arena_array(arena, 1);
159      ADD_C(args, STRING_OBJ(cstrn_as_string(ea.arg, length)));
160    }
161  } else {
162    size_t end = 0;
163    size_t len = 0;
164    char *buf = arena_alloc(arena, length + 1, false);
165    bool done = false;
166    args = arena_array(arena, uc_nargs_upper_bound(ea.arg, length));
167
168    while (!done) {
169      done = uc_split_args_iter(ea.arg, length, &end, buf, &len);
170      if (len > 0) {
171        ADD_C(args, STRING_OBJ(cstrn_as_string(buf, len)));
172        buf += len + 1;
173      }
174    }
175  }
176
177  ucmd_T *cmd = NULL;
178  if (ea.cmdidx == CMD_USER) {
179    cmd = USER_CMD(ea.useridx);
180  } else if (ea.cmdidx == CMD_USER_BUF) {
181    cmd = USER_CMD_GA(&curbuf->b_ucmds, ea.useridx);
182  }
183
184  // For range-only (:1) or modifier-only (:aboveleft) commands, cmd is empty string.
185  char *name = ea.cmdidx == CMD_SIZE
186               ? "" : (cmd != NULL ? cmd->uc_name : get_command_name(NULL, ea.cmdidx));
187
188  PUT_KEY(result, cmd, cmd, cstr_as_string(name));
189
190  if ((ea.argt & EX_RANGE) && ea.addr_count > 0) {
191    Array range = arena_array(arena, 2);
192    if (ea.addr_count > 1) {
193      ADD_C(range, INTEGER_OBJ(ea.line1));
194    }
195    ADD_C(range, INTEGER_OBJ(ea.line2));
196    PUT_KEY(result, cmd, range, range);
197  }
198
199  if (ea.argt & EX_COUNT) {
200    Integer count = ea.addr_count > 0 ? ea.line2 : (cmd != NULL ? cmd->uc_def : 0);
201    // For built-in commands, if count is not explicitly provided and the default value is 0,
202    // do not include the count field in the result, so the command uses its built-in default
203    // behavior.
204    if (ea.addr_count > 0 || (cmd != NULL && cmd->uc_def != 0) || count != 0) {
205      PUT_KEY(result, cmd, count, count);
206    }
207  }
208
209  if (ea.argt & EX_REGSTR) {
210    char reg[2] = { (char)ea.regname, NUL };
211    PUT_KEY(result, cmd, reg, CSTR_TO_ARENA_STR(arena, reg));
212  }
213
214  PUT_KEY(result, cmd, bang, ea.forceit);
215  PUT_KEY(result, cmd, args, args);
216
217  char nargs[2];
218  if (ea.argt & EX_EXTRA) {
219    if (ea.argt & EX_NOSPC) {
220      if (ea.argt & EX_ARGSPACE) {
221        nargs[0] = '_';
222      } else if (ea.argt & EX_NEEDARG) {
223        nargs[0] = '1';
224      } else {
225        nargs[0] = '?';
226      }
227    } else if (ea.argt & EX_NEEDARG) {
228      nargs[0] = '+';
229    } else {
230      nargs[0] = '*';
231    }
232  } else {
233    nargs[0] = '0';
234  }
235  nargs[1] = NUL;
236  PUT_KEY(result, cmd, nargs, CSTR_TO_ARENA_OBJ(arena, nargs));
237
238  char *addr;
239  switch (ea.addr_type) {
240  case ADDR_LINES:
241    addr = "line";
242    break;
243  case ADDR_ARGUMENTS:
244    addr = "arg";
245    break;
246  case ADDR_BUFFERS:
247    addr = "buf";
248    break;
249  case ADDR_LOADED_BUFFERS:
250    addr = "load";
251    break;
252  case ADDR_WINDOWS:
253    addr = "win";
254    break;
255  case ADDR_TABS:
256    addr = "tab";
257    break;
258  case ADDR_QUICKFIX:
259    addr = "qf";
260    break;
261  case ADDR_NONE:
262    addr = "none";
263    break;
264  default:
265    addr = "?";
266    break;
267  }
268  PUT_KEY(result, cmd, addr, cstr_as_string(addr));
269  PUT_KEY(result, cmd, nextcmd, cstr_as_string(ea.nextcmd));
270
271  // TODO(bfredl): nested keydict would be nice..
272  Dict mods = arena_dict(arena, 20);
273
274  Dict filter = arena_dict(arena, 2);
275  PUT_C(filter, "pattern", CSTR_TO_ARENA_OBJ(arena, cmod.cmod_filter_pat));
276  PUT_C(filter, "force", BOOLEAN_OBJ(cmod.cmod_filter_force));
277  PUT_C(mods, "filter", DICT_OBJ(filter));
278
279  PUT_C(mods, "silent", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_SILENT));
280  PUT_C(mods, "emsg_silent", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_ERRSILENT));
281  PUT_C(mods, "unsilent", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_UNSILENT));
282  PUT_C(mods, "sandbox", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_SANDBOX));
283  PUT_C(mods, "noautocmd", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_NOAUTOCMD));
284  PUT_C(mods, "tab", INTEGER_OBJ(cmod.cmod_tab - 1));
285  PUT_C(mods, "verbose", INTEGER_OBJ(cmod.cmod_verbose - 1));
286  PUT_C(mods, "browse", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_BROWSE));
287  PUT_C(mods, "confirm", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_CONFIRM));
288  PUT_C(mods, "hide", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_HIDE));
289  PUT_C(mods, "keepalt", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_KEEPALT));
290  PUT_C(mods, "keepjumps", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_KEEPJUMPS));
291  PUT_C(mods, "keepmarks", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_KEEPMARKS));
292  PUT_C(mods, "keeppatterns", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_KEEPPATTERNS));
293  PUT_C(mods, "lockmarks", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_LOCKMARKS));
294  PUT_C(mods, "noswapfile", BOOLEAN_OBJ(cmod.cmod_flags & CMOD_NOSWAPFILE));
295  PUT_C(mods, "vertical", BOOLEAN_OBJ(cmod.cmod_split & WSP_VERT));
296  PUT_C(mods, "horizontal", BOOLEAN_OBJ(cmod.cmod_split & WSP_HOR));
297
298  char *split;
299  if (cmod.cmod_split & WSP_BOT) {
300    split = "botright";
301  } else if (cmod.cmod_split & WSP_TOP) {
302    split = "topleft";
303  } else if (cmod.cmod_split & WSP_BELOW) {
304    split = "belowright";
305  } else if (cmod.cmod_split & WSP_ABOVE) {
306    split = "aboveleft";
307  } else {
308    split = "";
309  }
310  PUT_C(mods, "split", CSTR_AS_OBJ(split));
311
312  PUT_KEY(result, cmd, mods, mods);
313
314  Dict magic = arena_dict(arena, 2);
315  PUT_C(magic, "file", BOOLEAN_OBJ(ea.magic.file));
316  PUT_C(magic, "bar", BOOLEAN_OBJ(ea.magic.bar));
317  PUT_KEY(result, cmd, magic, magic);
318
319  undo_cmdmod(&cmod);
320end:
321  return result;
322}
323
324/// Executes an Ex command `cmd`, specified as a Dict with the same structure as returned by
325/// |nvim_parse_cmd()|.
326///
327/// Use `magic={…=false}` to disable special chars (see also |open-file|):
328/// ```lua
329/// vim.api.nvim_cmd({
330///     cmd = 'edit',
331///     args = { '%foo"|bar#baz"' },
332///     magic = { file = false, bar = false }
333///   },
334///   {}
335/// )
336/// ```
337///
338/// - See |nvim_parse_cmd()| to parse a cmdline string (which can then be passed to `nvim_cmd`).
339/// - See |nvim_command()| to execute a cmdline string.
340///
341/// On execution error: fails with Vimscript error, updates v:errmsg.
342///
343/// @see |nvim_command()|
344/// @see |nvim_exec2()|
345/// @see |nvim_parse_cmd()|
346///
347/// @param cmd       Command to execute, a Dict with the same structure as the return value of
348///                  |nvim_parse_cmd()| (except "addr", "nargs" and "nextcmd" are ignored).
349///                  All keys except "cmd" are optional.
350/// @param opts      Optional parameters.
351///                  - output: (boolean, default false) Whether to return command output.
352/// @param[out] err  Error details, if any.
353/// @return Command output (non-error, non-shell |:!|) if `output` is true, else empty string.
354String nvim_cmd(uint64_t channel_id, Dict(cmd) *cmd, Dict(cmd_opts) *opts, Arena *arena, Error *err)
355  FUNC_API_SINCE(10)
356{
357  exarg_T ea;
358  CLEAR_FIELD(ea);
359
360  cmdmod_T cmod;
361  CLEAR_FIELD(cmod);
362
363  char *cmdline = NULL;
364  char *cmdname = NULL;
365  const char *errormsg = NULL;
366  ArrayOf(String) args = ARRAY_DICT_INIT;
367
368  String retv = (String)STRING_INIT;
369
370#define OBJ_TO_BOOL(var, value, default, varname) \
371  do { \
372    (var) = api_object_to_bool(value, varname, default, err); \
373    if (ERROR_SET(err)) { \
374      goto end; \
375    } \
376  } while (0)
377
378#define VALIDATE_MOD(cond, mod_, name_) \
379  do { \
380    if (!(cond)) { \
381      api_set_error(err, kErrorTypeValidation, "Command cannot accept %s: %s", (mod_), (name_)); \
382      goto end; \
383    } \
384  } while (0)
385
386  VALIDATE_R(HAS_KEY(cmd, cmd, cmd), "cmd", {
387    goto end;
388  });
389
390  if (cmd->cmd.data[0] == NUL) {
391    VALIDATE_EXP((HAS_KEY(cmd, cmd, range) && cmd->range.size > 0) || HAS_KEY(cmd, cmd, mods),
392                 "cmd", "non-empty String", NULL, {
393      goto end;
394    });
395  }
396
397  cmdname = arena_string(arena, cmd->cmd).data;
398  ea.cmd = cmdname;
399
400  char *p = find_ex_command(&ea, NULL);
401
402  // If this looks like an undefined user command and there are CmdUndefined
403  // autocommands defined, trigger the matching autocommands.
404  if (p != NULL && ea.cmdidx == CMD_SIZE && ASCII_ISUPPER(*ea.cmd)
405      && has_event(EVENT_CMDUNDEFINED)) {
406    p = arena_string(arena, cmd->cmd).data;
407    int ret = apply_autocmds(EVENT_CMDUNDEFINED, p, p, true, NULL);
408    // If the autocommands did something and didn't cause an error, try
409    // finding the command again.
410    p = (ret && !aborting()) ? find_ex_command(&ea, NULL) : ea.cmd;
411  }
412
413  // Commands such as ":1" are "range only" commands.
414  bool range_only = ea.cmdidx == CMD_SIZE && cmd->cmd.data[0] == NUL
415                    && HAS_KEY(cmd, cmd, range) && cmd->range.size > 0;
416
417  // modifier only
418  if (ea.cmdidx == CMD_SIZE && cmd->cmd.data[0] == NUL
419      && (!HAS_KEY(cmd, cmd, range) || cmd->range.size == 0)
420      && HAS_KEY(cmd, cmd, mods)) {
421    goto end;
422  }
423  // Allow CMD_SIZE only for range-only commands (empty cmd with range)
424  VALIDATE((p != NULL && ea.cmdidx != CMD_SIZE) || range_only,
425           "Command not found: %s", cmdname, {
426    goto end;
427  });
428
429  VALIDATE(range_only || !is_cmd_ni(ea.cmdidx), "Command not implemented: %s", cmdname, {
430    goto end;
431  });
432
433  if (!range_only) {
434    const char *fullname = IS_USER_CMDIDX(ea.cmdidx)
435                           ? get_user_command_name(ea.useridx, ea.cmdidx)
436                           : get_command_name(NULL, ea.cmdidx);
437    VALIDATE(strncmp(fullname, cmdname, strlen(cmdname)) == 0,
438             "Invalid command: \"%s\"", cmdname, {
439      goto end;
440    });
441  }
442
443  if (range_only) {
444    ea.argt = EX_RANGE | EX_SBOXOK;
445  } else if (!IS_USER_CMDIDX(ea.cmdidx)) {
446    // Get the command flags so that we can know what type of arguments the command uses.
447    // Not required for a user command since `find_ex_command` already deals with it in that case.
448    ea.argt = excmd_get_argt(ea.cmdidx);
449  }
450
451  // Track whether the first argument was interpreted as count to avoid conflicts
452  bool count_from_first_arg = false;
453  // Parse command arguments since it's needed to get the command address type.
454  if (HAS_KEY(cmd, cmd, args)) {
455    // Special handling: for commands that support count but not regular arguments,
456    // if a single numeric argument is provided, interpret it as count
457    if (cmd->args.size == 1 && (ea.argt & EX_COUNT) && !(ea.argt & EX_EXTRA)) {
458      Object first_arg = cmd->args.items[0];
459      bool is_numeric = false;
460      int64_t count_value = 0;
461
462      if (first_arg.type == kObjectTypeInteger) {
463        is_numeric = true;
464        count_value = first_arg.data.integer;
465      } else if (first_arg.type == kObjectTypeString) {
466        // Try to parse string as a number Example: vim.api.nvim_cmd({cmd = 'copen', args = {'10'}})
467        char *endptr = first_arg.data.string.data;
468        long val = getdigits_long(&endptr, false, 0);
469        // Check if entire string was consumed (valid number) and string is not empty
470        if (*endptr == '\0' && first_arg.data.string.size > 0) {
471          is_numeric = true;
472          count_value = val;
473        }
474      }
475
476      if (is_numeric && count_value >= 0) {
477        // Interpret the argument as count
478        count_from_first_arg = true;
479        ea.addr_count = 1;
480        ea.line1 = ea.line2 = (linenr_T)count_value;
481        args = arena_array(arena, 0);
482      }
483    }
484
485    if (!count_from_first_arg) {
486      // Process all arguments. Convert non-String arguments to String and check if String arguments
487      // have non-whitespace characters.
488      args = arena_array(arena, cmd->args.size);
489      for (size_t i = 0; i < cmd->args.size; i++) {
490        Object elem = cmd->args.items[i];
491        char *data_str;
492
493        switch (elem.type) {
494        case kObjectTypeBoolean:
495          data_str = arena_alloc(arena, 2, false);
496          data_str[0] = elem.data.boolean ? '1' : '0';
497          data_str[1] = NUL;
498          ADD_C(args, CSTR_AS_OBJ(data_str));
499          break;
500        case kObjectTypeBuffer:
501        case kObjectTypeWindow:
502        case kObjectTypeTabpage:
503        case kObjectTypeInteger:
504          data_str = arena_alloc(arena, NUMBUFLEN, false);
505          snprintf(data_str, NUMBUFLEN, "%" PRId64, elem.data.integer);
506          ADD_C(args, CSTR_AS_OBJ(data_str));
507          break;
508        case kObjectTypeString:
509          VALIDATE_EXP(!string_iswhite(elem.data.string), "command arg", "non-whitespace", NULL, {
510            goto end;
511          });
512          ADD_C(args, elem);
513          break;
514        default:
515          VALIDATE_EXP(false, "command arg", "valid type", api_typename(elem.type), {
516            goto end;
517          });
518          break;
519        }
520      }
521
522      bool argc_valid;
523
524      // Check if correct number of arguments is used.
525      switch (ea.argt & (EX_EXTRA | EX_NOSPC | EX_NEEDARG)) {
526      case EX_EXTRA | EX_NOSPC | EX_NEEDARG:
527        argc_valid = args.size == 1;
528        break;
529      case EX_EXTRA | EX_NOSPC:
530        argc_valid = args.size <= 1;
531        break;
532      case EX_EXTRA | EX_NEEDARG:
533        argc_valid = args.size >= 1;
534        break;
535      case EX_EXTRA:
536        argc_valid = true;
537        break;
538      default:
539        argc_valid = args.size == 0;
540        break;
541      }
542
543      VALIDATE(argc_valid, "%s", "Wrong number of arguments", {
544        goto end;
545      });
546    }
547  }
548
549  if (HAS_KEY(cmd, cmd, range)) {
550    VALIDATE_MOD((ea.argt & EX_RANGE), "range", cmd->cmd.data);
551    VALIDATE_EXP((cmd->range.size <= 2), "range", "<=2 elements", NULL, {
552      goto end;
553    });
554
555    Array range = cmd->range;
556    ea.addr_count = (int)range.size;
557
558    for (size_t i = 0; i < range.size; i++) {
559      Object elem = range.items[i];
560      VALIDATE_EXP((elem.type == kObjectTypeInteger && elem.data.integer >= 0),
561                   "range element", "non-negative Integer", NULL, {
562        goto end;
563      });
564    }
565
566    if (range.size > 0) {
567      ea.line1 = (linenr_T)range.items[0].data.integer;
568      ea.line2 = (linenr_T)range.items[range.size - 1].data.integer;
569    }
570  }
571
572  // parse_cmdline() refills ea: the address type, range and default range come from the Ex parser.
573  build_cmdline_str(&cmdline, &ea, args);
574  if (!parse_cmdline(&cmdline, &ea, &cmod, &errormsg,
575                     // Don't parse modifiers/reg/etc. Those come from `cmd`.
576                     true)) {
577    api_set_error(err, kErrorTypeException, "%s", errormsg ? errormsg : "Parsing command-line");
578    goto end;
579  }
580
581  if (range_only) {
582    ea.argt = EX_RANGE | EX_SBOXOK;
583  }
584
585  if (HAS_KEY(cmd, cmd, range)) {
586    VALIDATE_S((invalid_range(&ea) == NULL), "range", "", {
587      goto end;
588    });
589  }
590
591  if (ea.addr_count == 0 && !(ea.argt & EX_DFLALL) && ea.addr_type == ADDR_OTHER) {
592    // Default is 1, not cursor.
593    ea.line2 = 1;
594  }
595
596  // parse_cmdline() only sees one string, set the argument boundaries.
597  ea.argc = args.size;
598  if (ea.argc > 0) {
599    ea.args = xcalloc(ea.argc, sizeof(char *));
600    ea.arglens = xcalloc(ea.argc, sizeof(size_t));
601    p = ea.arg;
602    for (size_t i = 0; i < ea.argc; i++) {
603      ea.args[i] = p;
604      ea.arglens[i] = args.items[i].data.string.size;
605      p += ea.arglens[i] + 1;  // Account for space
606    }
607  }
608
609  if (HAS_KEY(cmd, cmd, count)) {
610    VALIDATE(!count_from_first_arg, "%s", "Cannot specify both 'count' and numeric argument", {
611      goto end;
612    });
613    VALIDATE_MOD((ea.argt & EX_COUNT), "count", cmd->cmd.data);
614    VALIDATE_EXP((cmd->count >= 0), "count", "non-negative Integer", NULL, {
615      goto end;
616    });
617    set_cmd_count(&ea, (linenr_T)cmd->count, true);
618  }
619
620  if (HAS_KEY(cmd, cmd, reg)) {
621    VALIDATE_MOD((ea.argt & EX_REGSTR), "register", cmd->cmd.data);
622    VALIDATE_EXP((cmd->reg.size == 1),
623                 "reg", "single character", cmd->reg.data, {
624      goto end;
625    });
626    char regname = cmd->reg.data[0];
627    VALIDATE((regname != '='), "%s", "Cannot use register \"=", {
628      goto end;
629    });
630    VALIDATE(valid_yank_reg(regname,
631                            (!IS_USER_CMDIDX(ea.cmdidx)
632                             && ea.cmdidx != CMD_put && ea.cmdidx != CMD_iput)),
633             "Invalid register: \"%c", regname, {
634      goto end;
635    });
636    ea.regname = (uint8_t)regname;
637  }
638
639  ea.forceit = cmd->bang;
640  VALIDATE_MOD((!ea.forceit || (ea.argt & EX_BANG)), "bang", cmd->cmd.data);
641
642  if (HAS_KEY(cmd, cmd, magic)) {
643    Dict(cmd_magic) magic[1] = KEYDICT_INIT;
644    if (!api_dict_to_keydict(magic, DictHash(cmd_magic), cmd->magic, err)) {
645      goto end;
646    }
647
648    ea.magic.file = HAS_KEY(magic, cmd_magic, file) ? magic->file : (ea.argt & EX_XFILE);
649    ea.magic.bar = HAS_KEY(magic, cmd_magic, bar) ? magic->bar : (ea.argt & EX_TRLBAR);
650    if (ea.magic.file) {
651      ea.argt |= EX_XFILE;
652    } else {
653      ea.argt &= ~EX_XFILE;
654    }
655  } else {
656    ea.magic.file = ea.argt & EX_XFILE;
657    ea.magic.bar = ea.argt & EX_TRLBAR;
658  }
659
660  if (HAS_KEY(cmd, cmd, mods)) {
661    Dict(cmd_mods) mods[1] = KEYDICT_INIT;
662    if (!api_dict_to_keydict(mods, DictHash(cmd_mods), cmd->mods, err)) {
663      goto end;
664    }
665
666    if (HAS_KEY(mods, cmd_mods, filter)) {
667      Dict(cmd_mods_filter) filter[1] = KEYDICT_INIT;
668
669      if (!api_dict_to_keydict(&filter, DictHash(cmd_mods_filter),
670                               mods->filter, err)) {
671        goto end;
672      }
673
674      if (HAS_KEY(filter, cmd_mods_filter, pattern)) {
675        cmod.cmod_filter_force = filter->force;
676
677        // "filter! // is not no-op, so add a filter if either the pattern is non-empty or if filter
678        // is inverted.
679        if (*filter->pattern.data != NUL || cmod.cmod_filter_force) {
680          cmod.cmod_filter_pat = string_to_cstr(filter->pattern);
681          cmod.cmod_filter_regmatch.regprog = vim_regcomp(cmod.cmod_filter_pat, RE_MAGIC);
682        }
683      }
684    }
685
686    if (HAS_KEY(mods, cmd_mods, tab)) {
687      if ((int)mods->tab >= 0) {
688        // Silently ignore negative integers to allow mods.tab to be set to -1.
689        cmod.cmod_tab = (int)mods->tab + 1;
690      }
691    }
692
693    if (HAS_KEY(mods, cmd_mods, verbose)) {
694      if ((int)mods->verbose >= 0) {
695        // Silently ignore negative integers to allow mods.verbose to be set to -1.
696        cmod.cmod_verbose = (int)mods->verbose + 1;
697      }
698    }
699
700    cmod.cmod_split |= (mods->vertical ? WSP_VERT : 0);
701
702    cmod.cmod_split |= (mods->horizontal ? WSP_HOR : 0);
703
704    if (HAS_KEY(mods, cmd_mods, split)) {
705      if (*mods->split.data == NUL) {
706        // Empty string, do nothing.
707      } else if (strcmp(mods->split.data, "aboveleft") == 0
708                 || strcmp(mods->split.data, "leftabove") == 0) {
709        cmod.cmod_split |= WSP_ABOVE;
710      } else if (strcmp(mods->split.data, "belowright") == 0
711                 || strcmp(mods->split.data, "rightbelow") == 0) {
712        cmod.cmod_split |= WSP_BELOW;
713      } else if (strcmp(mods->split.data, "topleft") == 0) {
714        cmod.cmod_split |= WSP_TOP;
715      } else if (strcmp(mods->split.data, "botright") == 0) {
716        cmod.cmod_split |= WSP_BOT;
717      } else {
718        VALIDATE_S(false, "mods.split", "", {
719          goto end;
720        });
721      }
722    }
723
724#define OBJ_TO_CMOD_FLAG(flag, value) \
725  if (value) { \
726    cmod.cmod_flags |= (flag); \
727  }
728
729    OBJ_TO_CMOD_FLAG(CMOD_SILENT, mods->silent);
730    OBJ_TO_CMOD_FLAG(CMOD_ERRSILENT, mods->emsg_silent);
731    OBJ_TO_CMOD_FLAG(CMOD_UNSILENT, mods->unsilent);
732    OBJ_TO_CMOD_FLAG(CMOD_SANDBOX, mods->sandbox);
733    OBJ_TO_CMOD_FLAG(CMOD_NOAUTOCMD, mods->noautocmd);
734    OBJ_TO_CMOD_FLAG(CMOD_BROWSE, mods->browse);
735    OBJ_TO_CMOD_FLAG(CMOD_CONFIRM, mods->confirm);
736    OBJ_TO_CMOD_FLAG(CMOD_HIDE, mods->hide);
737    OBJ_TO_CMOD_FLAG(CMOD_KEEPALT, mods->keepalt);
738    OBJ_TO_CMOD_FLAG(CMOD_KEEPJUMPS, mods->keepjumps);
739    OBJ_TO_CMOD_FLAG(CMOD_KEEPMARKS, mods->keepmarks);
740    OBJ_TO_CMOD_FLAG(CMOD_KEEPPATTERNS, mods->keeppatterns);
741    OBJ_TO_CMOD_FLAG(CMOD_LOCKMARKS, mods->lockmarks);
742    OBJ_TO_CMOD_FLAG(CMOD_NOSWAPFILE, mods->noswapfile);
743
744    if (cmod.cmod_flags & CMOD_ERRSILENT) {
745      // CMOD_ERRSILENT must imply CMOD_SILENT, otherwise apply_cmdmod() and undo_cmdmod() won't
746      // work properly.
747      cmod.cmod_flags |= CMOD_SILENT;
748    }
749
750    VALIDATE(!((cmod.cmod_flags & CMOD_SANDBOX) && !(ea.argt & EX_SBOXOK)),
751             "%s", "Command cannot be run in sandbox", {
752      goto end;
753    });
754  }
755
756  // Replace :make and :grep with 'makeprg' and 'grepprg'.
757  p = replace_makeprg(&ea, ea.arg, &cmdline);
758  if (p != ea.arg) {
759    // If replace_makeprg() modified the cmdline string, correct the ea.arg pointer.
760    ea.arg = p;
761    // This cannot be a user command, so ea.args will not be used.
762    XFREE_CLEAR(ea.args);
763    XFREE_CLEAR(ea.arglens);
764    ea.argc = 0;
765  }
766
767  // Check for "++opt=val" argument.
768  if (ea.argt & EX_ARGOPT) {
769    while (ea.arg[0] == '+' && ea.arg[1] == '+') {
770      char *orig_arg = ea.arg;
771      int result = getargopt(&ea);
772      VALIDATE_S(result != FAIL || is_cmd_ni(ea.cmdidx), "argument ", orig_arg, {
773        goto end;
774      });
775    }
776  }
777
778  // Check for "+command" argument.
779  if ((ea.argt & EX_CMDARG) && !ea.usefilter) {
780    ea.do_ecmd_cmd = getargcmd(&ea.arg);
781  }
782
783  garray_T capture_local;
784  const int save_msg_silent = msg_silent;
785  const bool save_redir_off = redir_off;
786  garray_T * const save_capture_ga = capture_ga;
787  const int save_msg_col = msg_col;
788
789  if (opts->output) {
790    ga_init(&capture_local, 1, 80);
791    capture_ga = &capture_local;
792  }
793
794  TRY_WRAP(err, {
795    if (opts->output) {
796      msg_silent++;
797      redir_off = false;
798      msg_col = 0;  // prevent leading spaces
799    }
800
801    WITH_SCRIPT_CONTEXT(channel_id, {
802      execute_cmd(&ea, &cmod, false);
803    });
804
805    if (opts->output) {
806      capture_ga = save_capture_ga;
807      msg_silent = save_msg_silent;
808      redir_off = save_redir_off;
809      // Put msg_col back where it was, since nothing should have been written.
810      msg_col = save_msg_col;
811    }
812  });
813
814  if (ERROR_SET(err)) {
815    goto clear_ga;
816  }
817
818  if (opts->output && capture_local.ga_len > 1) {
819    // TODO(bfredl): if there are more cases like this we might want custom xfree-list in arena
820    retv = CBUF_TO_ARENA_STR(arena, capture_local.ga_data, (size_t)capture_local.ga_len);
821    // redir usually (except :echon) prepends a newline.
822    if (retv.data[0] == '\n') {
823      retv.data++;
824      retv.size--;
825    }
826  }
827clear_ga:
828  if (opts->output) {
829    ga_clear(&capture_local);
830  }
831end:
832  xfree(cmdline);
833  xfree(ea.args);
834  xfree(ea.arglens);
835
836  return retv;
837
838#undef OBJ_TO_BOOL
839#undef OBJ_TO_CMOD_FLAG
840#undef VALIDATE_MOD
841}
842
843/// Check if a string contains only whitespace characters.
844static bool string_iswhite(String str)
845{
846  for (size_t i = 0; i < str.size; i++) {
847    if (!ascii_iswhite(str.data[i])) {
848      // Found a non-whitespace character
849      return false;
850    } else if (str.data[i] == NUL) {
851      // Terminate at first occurrence of a NUL character
852      break;
853    }
854  }
855  return true;
856}
857
858/// Build cmdline string for command, used by `nvim_cmd()`.
859///
860/// Only the range, command name and arguments; nvim_cmd() applies the other fields.
861static void build_cmdline_str(char **cmdlinep, exarg_T *eap, ArrayOf(String) args)
862{
863  StringBuilder cmdline = KV_INITIAL_VALUE;
864  kv_resize(cmdline, 32);  // Make it big enough to handle most typical commands
865
866  // Command range / count.
867  if (eap->argt & EX_RANGE) {
868    if (eap->addr_count == 1) {
869      kv_printf(cmdline, "%" PRIdLINENR, eap->line2);
870    } else if (eap->addr_count > 1) {
871      kv_printf(cmdline, "%" PRIdLINENR ",%" PRIdLINENR, eap->line1, eap->line2);
872    }
873  }
874
875  kv_concat(cmdline, eap->cmd);
876
877  for (size_t i = 0; i < args.size; i++) {
878    String s = args.items[i].data.string;
879    kv_concat(cmdline, " ");
880    kv_concat_len(cmdline, s.data, s.size);
881  }
882
883  // Done appending to cmdline, ensure it is NUL terminated
884  kv_push(cmdline, NUL);
885
886  *cmdlinep = cmdline.items;
887}
888
889// uncrustify:off
890
891/// Creates a global |user-commands| command.
892///
893/// For Lua usage see |lua-guide-commands-create|.
894///
895/// Example:
896///
897/// ```vim
898/// :call nvim_create_user_command('SayHello', 'echo "Hello world!"', {'bang': v:true})
899/// :SayHello
900/// Hello world!
901/// ```
902///
903/// @param  name    Command name. First char must be uppercase.
904/// @param  cmd     Command or Lua function, executed when the command is invoked. Lua function
905///                 receives a table with keys:
906///                 - args: (string) Args passed to the command, if any. [<args>]
907///                 - bang: (boolean) true if the command was executed with "!". [<bang>]
908///                 - count: (number) Count, if any. [<count>]
909///                 - fargs: (table) Args split by unescaped whitespace (when more than one arg is
910///                   allowed), if any. [<f-args>]
911///                 - line1: (number) Start of the command range. [<line1>]
912///                 - line2: (number) End of the command range. [<line2>]
913///                 - mods: (string) Command modifiers (unstructured string), if any. [<mods>]
914///                 - name: (string) Command name.
915///                 - nargs: (string) Number of arguments allowed by the command. |:command-nargs|
916///                 - range: (number) Number of items in the command range: 0, 1, or 2. [<range>]
917///                 - reg: (string) Register name, if any. [<reg>]
918///                 - smods: (table) Command modifiers (structured), same as "mods" in |nvim_parse_cmd()|.
919/// @param  opts    Optional flags:
920///                 - `addr` |:command-addr|
921///                 - `complete` |:command-complete| command or function |:command-completion-customlist|.
922///                 - `count` |:command-count|
923///                 - `desc` (string) Command description.
924///                 - `force` (boolean, default true) Override the existing definition, if any.
925///                 - `nargs` Number of arguments allowed by the command. |:command-nargs|
926///                 - `preview` (function) Preview handler for 'inccommand'. |:command-preview|
927///                 - `range` |:command-range|
928///                 - boolean |command-attributes| such as |:command-bang| or |:command-bar| (but
929///                   not |:command-buffer|, use |nvim_buf_create_user_command()| instead).
930/// @param[out] err Error details, if any.
931void nvim_create_user_command(uint64_t channel_id,
932                              String name,
933                              Union(String, LuaRefOf((DictAs(create_user_command__command_args) args))) cmd,
934                              Dict(user_command) *opts,
935                              Error *err)
936  FUNC_API_SINCE(9)
937{
938  create_user_command(channel_id, name, cmd, opts, 0, err);
939}
940
941// uncrustify:on
942
943/// Delete a user-defined command.
944///
945/// @param  name    Name of the command to delete.
946/// @param[out] err Error details, if any.
947void nvim_del_user_command(String name, Error *err)
948  FUNC_API_SINCE(9)
949{
950  nvim_buf_del_user_command(-1, name, err);
951}
952
953/// Creates a buffer-local command |user-commands|.
954///
955/// @param  buf  Buffer id, or 0 for current buffer.
956/// @param[out] err Error details, if any.
957/// @see nvim_create_user_command
958void nvim_buf_create_user_command(uint64_t channel_id, Buffer buf, String name, Object cmd,
959                                  Dict(user_command) *opts, Error *err)
960  FUNC_API_SINCE(9)
961{
962  buf_T *target_buf = find_buffer_by_handle(buf, err);
963  if (ERROR_SET(err)) {
964    return;
965  }
966
967  buf_T *save_curbuf = curbuf;
968  curbuf = target_buf;
969  create_user_command(channel_id, name, cmd, opts, UC_BUFFER, err);
970  curbuf = save_curbuf;
971}
972
973/// Delete a buffer-local user-defined command.
974///
975/// Only commands created with |:command-buffer| or
976/// |nvim_buf_create_user_command()| can be deleted with this function.
977///
978/// @param  buf  Buffer id, or 0 for current buffer.
979/// @param  name    Name of the command to delete.
980/// @param[out] err Error details, if any.
981void nvim_buf_del_user_command(Buffer buf, String name, Error *err)
982  FUNC_API_SINCE(9)
983{
984  garray_T *gap;
985  if (buf == -1) {
986    gap = &ucmds;
987  } else {
988    buf_T *b = find_buffer_by_handle(buf, err);
989    if (ERROR_SET(err)) {
990      return;
991    }
992    gap = &b->b_ucmds;
993  }
994
995  for (int i = 0; i < gap->ga_len; i++) {
996    ucmd_T *cmd = USER_CMD_GA(gap, i);
997    if (!strcmp(name.data, cmd->uc_name)) {
998      free_ucmd(cmd);
999
1000      gap->ga_len -= 1;
1001
1002      if (i < gap->ga_len) {
1003        memmove(cmd, cmd + 1, (size_t)(gap->ga_len - i) * sizeof(ucmd_T));
1004      }
1005
1006      return;
1007    }
1008  }
1009
1010  api_set_error(err, kErrorTypeException, "Invalid command (not found): %s", name.data);
1011}
1012
1013void create_user_command(uint64_t channel_id, String name, Union(String, LuaRef) cmd,
1014                         Dict(user_command) *opts, int flags, Error *err)
1015{
1016  uint32_t argt = 0;
1017  int64_t def = -1;
1018  cmd_addr_T addr_type_arg = ADDR_NONE;
1019  int context = EXPAND_NOTHING;
1020  char *compl_arg = NULL;
1021  const char *rep = NULL;
1022  LuaRef luaref = LUA_NOREF;
1023  LuaRef compl_luaref = LUA_NOREF;
1024  LuaRef preview_luaref = LUA_NOREF;
1025
1026  VALIDATE_S(uc_validate_name(name.data), "command name", name.data, {
1027    goto err;
1028  });
1029  VALIDATE_S(!mb_islower(name.data[0]), "command name (must start with uppercase)",
1030             name.data, {
1031    goto err;
1032  });
1033  VALIDATE((!HAS_KEY(opts, user_command, range) || !HAS_KEY(opts, user_command, count)), "%s",
1034           "Cannot use both 'range' and 'count'", {
1035    goto err;
1036  });
1037
1038  if (opts->nargs.type == kObjectTypeInteger) {
1039    switch (opts->nargs.data.integer) {
1040    case 0:
1041      // Default value, nothing to do
1042      break;
1043    case 1:
1044      argt |= EX_EXTRA | EX_NOSPC | EX_NEEDARG;
1045      break;
1046    default:
1047      VALIDATE_INT(false, "nargs", (int64_t)opts->nargs.data.integer, {
1048        goto err;
1049      });
1050    }
1051  } else if (opts->nargs.type == kObjectTypeString) {
1052    VALIDATE_S((opts->nargs.data.string.size <= 1), "nargs", opts->nargs.data.string.data, {
1053      goto err;
1054    });
1055
1056    switch (opts->nargs.data.string.data[0]) {
1057    case '*':
1058      argt |= EX_EXTRA;
1059      break;
1060    case '?':
1061      argt |= EX_EXTRA | EX_NOSPC;
1062      break;
1063    case '+':
1064      argt |= EX_EXTRA | EX_NEEDARG;
1065      break;
1066    case '_':
1067      argt |= EX_EXTRA | EX_NOSPC | EX_NEEDARG | EX_ARGSPACE;
1068      break;
1069    default:
1070      VALIDATE_S(false, "nargs", opts->nargs.data.string.data, {
1071        goto err;
1072      });
1073    }
1074  } else if (HAS_KEY(opts, user_command, nargs)) {
1075    VALIDATE_S(false, "nargs", "", {
1076      goto err;
1077    });
1078  }
1079
1080  VALIDATE((!HAS_KEY(opts, user_command, complete) || argt),
1081           "%s", "'complete' used without 'nargs'", {
1082    goto err;
1083  });
1084
1085  if (opts->range.type == kObjectTypeBoolean) {
1086    if (opts->range.data.boolean) {
1087      argt |= EX_RANGE;
1088      addr_type_arg = ADDR_LINES;
1089    }
1090  } else if (opts->range.type == kObjectTypeString) {
1091    VALIDATE_S((opts->range.data.string.data[0] == '%' && opts->range.data.string.size == 1),
1092               "range", "", {
1093      goto err;
1094    });
1095    argt |= EX_RANGE | EX_DFLALL;
1096    addr_type_arg = ADDR_LINES;
1097  } else if (opts->range.type == kObjectTypeInteger) {
1098    argt |= EX_RANGE | EX_ZEROR;
1099    def = opts->range.data.integer;
1100    addr_type_arg = ADDR_LINES;
1101  } else if (HAS_KEY(opts, user_command, range)) {
1102    VALIDATE_S(false, "range", "", {
1103      goto err;
1104    });
1105  }
1106
1107  if (opts->count.type == kObjectTypeBoolean) {
1108    if (opts->count.data.boolean) {
1109      argt |= EX_COUNT | EX_ZEROR | EX_RANGE;
1110      addr_type_arg = ADDR_OTHER;
1111      def = 0;
1112    }
1113  } else if (opts->count.type == kObjectTypeInteger) {
1114    argt |= EX_COUNT | EX_ZEROR | EX_RANGE;
1115    addr_type_arg = ADDR_OTHER;
1116    def = opts->count.data.integer;
1117  } else if (HAS_KEY(opts, user_command, count)) {
1118    VALIDATE_S(false, "count", "", {
1119      goto err;
1120    });
1121  }
1122
1123  if (HAS_KEY(opts, user_command, addr)) {
1124    VALIDATE_T("addr", kObjectTypeString, opts->addr.type, {
1125      goto err;
1126    });
1127
1128    VALIDATE_S(OK == parse_addr_type_arg(opts->addr.data.string.data,
1129                                         (int)opts->addr.data.string.size, &addr_type_arg), "addr",
1130               opts->addr.data.string.data, {
1131      goto err;
1132    });
1133
1134    argt |= EX_RANGE;
1135    if (addr_type_arg != ADDR_LINES) {
1136      argt |= EX_ZEROR;
1137    }
1138  }
1139
1140  if (opts->bang) {
1141    argt |= EX_BANG;
1142  }
1143
1144  if (opts->bar) {
1145    argt |= EX_TRLBAR;
1146  }
1147
1148  if (opts->register_) {
1149    argt |= EX_REGSTR;
1150  }
1151
1152  if (opts->keepscript) {
1153    argt |= EX_KEEPSCRIPT;
1154  }
1155
1156  bool force = GET_BOOL_OR_TRUE(opts, user_command, force);
1157  if (ERROR_SET(err)) {
1158    goto err;
1159  }
1160
1161  if (opts->complete.type == kObjectTypeLuaRef) {
1162    context = EXPAND_USER_LUA;
1163    compl_luaref = opts->complete.data.luaref;
1164    opts->complete.data.luaref = LUA_NOREF;
1165  } else if (opts->complete.type == kObjectTypeString) {
1166    VALIDATE_S(OK == parse_compl_arg(opts->complete.data.string.data,
1167                                     (int)opts->complete.data.string.size, &context, &argt,
1168                                     &compl_arg),
1169               "complete", opts->complete.data.string.data, {
1170      goto err;
1171    });
1172  } else if (HAS_KEY(opts, user_command, complete)) {
1173    VALIDATE_EXP(false, "complete", "Function or String", NULL, {
1174      goto err;
1175    });
1176  }
1177
1178  if (HAS_KEY(opts, user_command, preview)) {
1179    VALIDATE_T("preview", kObjectTypeLuaRef, opts->preview.type, {
1180      goto err;
1181    });
1182
1183    argt |= EX_PREVIEW;
1184    preview_luaref = opts->preview.data.luaref;
1185    opts->preview.data.luaref = LUA_NOREF;
1186  }
1187
1188  const char *desc = NULL;
1189  if (HAS_KEY(opts, user_command, desc)) {
1190    VALIDATE_T("desc", kObjectTypeString, opts->desc.type, {
1191      goto err;
1192    });
1193    desc = opts->desc.data.string.data;
1194  }
1195
1196  switch (cmd.type) {
1197  case kObjectTypeLuaRef:
1198    luaref = api_new_luaref(cmd.data.luaref);
1199    rep = "";
1200    break;
1201  case kObjectTypeString:
1202    rep = cmd.data.string.data;
1203    break;
1204  default:
1205    VALIDATE_EXP(false, "command", "Function or String", NULL, {
1206      goto err;
1207    });
1208  }
1209
1210  WITH_SCRIPT_CONTEXT(channel_id, {
1211    if (uc_add_command(name.data, name.size, rep, argt, def, flags, context, compl_arg,
1212                       compl_luaref, preview_luaref, addr_type_arg, luaref, desc, force) != OK) {
1213      api_set_error(err, kErrorTypeException, "Failed to create user command");
1214      // Do not goto err, since uc_add_command now owns luaref, compl_luaref, preview_luaref,
1215      // and compl_arg
1216    }
1217  });
1218
1219  return;
1220
1221err:
1222  NLUA_CLEAR_REF(luaref);
1223  NLUA_CLEAR_REF(compl_luaref);
1224  NLUA_CLEAR_REF(preview_luaref);
1225  xfree(compl_arg);
1226}
1227/// Gets a map of global (non-buffer-local) Ex commands.
1228///
1229/// Currently only |user-commands| are supported, not builtin Ex commands.
1230///
1231/// @see |nvim_get_all_options_info()|
1232///
1233/// @param  opts  Optional parameters. Currently only supports
1234///               {"builtin":false}
1235/// @param[out]  err   Error details, if any.
1236///
1237/// @returns Map of maps describing commands.
1238DictOf(DictAs(command_info)) nvim_get_commands(Dict(get_commands) *opts, Arena *arena, Error *err)
1239  FUNC_API_SINCE(4)
1240{
1241  return nvim_buf_get_commands(-1, opts, arena, err);
1242}
1243
1244/// Gets a map of buffer-local |user-commands|.
1245///
1246/// @param  buf  Buffer id, or 0 for current buffer
1247/// @param  opts  Optional parameters. Currently not used.
1248/// @param[out]  err   Error details, if any.
1249///
1250/// @returns Map of maps describing commands.
1251DictAs(command_info) nvim_buf_get_commands(Buffer buf, Dict(get_commands) *opts, Arena *arena,
1252                                           Error *err)
1253  FUNC_API_SINCE(4)
1254{
1255  bool global = (buf == -1);
1256  if (ERROR_SET(err)) {
1257    return (Dict)ARRAY_DICT_INIT;
1258  }
1259
1260  if (global) {
1261    if (opts->builtin) {
1262      api_set_error(err, kErrorTypeValidation, "builtin=true not implemented");
1263      return (Dict)ARRAY_DICT_INIT;
1264    }
1265    return commands_array(NULL, arena);
1266  }
1267
1268  buf_T *b = find_buffer_by_handle(buf, err);
1269  if (opts->builtin || !b) {
1270    return (Dict)ARRAY_DICT_INIT;
1271  }
1272  return commands_array(b, arena);
1273}