robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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{ 48Array args = arena_array (arena ,2 ); 49 50char * lhs_start = (char * )arg_str ; 51char * lhs_end = skiptowhite (lhs_start ); 52size_t lhs_len = (size_t )(lhs_end - lhs_start ); 53 54// Add the LHS (first argument) 55ADD_C (args ,STRING_OBJ (cstrn_as_string (lhs_start ,lhs_len ))); 56 57// Add the RHS (second argument) if it exists, preserving all whitespace 58char * rhs_start = skipwhite (lhs_end ); 59if (* rhs_start != NUL ) { 60size_t rhs_len = strlen (rhs_start ); 61ADD_C (args ,STRING_OBJ (cstrn_as_string (rhs_start ,rhs_len ))); 62 } 63 64return 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 ) 125FUNC_API_SINCE (10 )FUNC_API_FAST 126{ 127Dict (cmd )result = KEYDICT_INIT ; 128 129// Parse command line 130exarg_T ea ; 131cmdmod_T cmod ; 132char * cmdline = arena_memdupz (arena ,str .data ,str .size ); 133const char * errormsg = NULL ; 134 135if (!parse_cmdline (& cmdline ,& ea ,& cmod ,& errormsg , false)) { 136if (errormsg != NULL ) { 137api_set_error (err ,kErrorTypeException ,"Parsing command-line: %s" ,errormsg ); 138 }else { 139api_set_error (err ,kErrorTypeException ,"Parsing command-line" ); 140 } 141 gotoend ; 142 } 143 144// Parse arguments 145Array args = ARRAY_DICT_INIT ; 146size_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"], ... } 151if (ea .cmdidx != CMD_SIZE && is_map_cmd (ea .cmdidx )&& * ea .arg != NUL ) { 152// For mapping commands, split differently to preserve whitespace 153args = 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. 157if (* ea .arg != NUL ) { 158args = arena_array (arena ,1 ); 159ADD_C (args ,STRING_OBJ (cstrn_as_string (ea .arg ,length ))); 160 } 161 }else { 162size_t end = 0 ; 163size_t len = 0 ; 164char * buf = arena_alloc (arena ,length + 1 , false); 165bool done = false; 166args = arena_array (arena ,uc_nargs_upper_bound (ea .arg ,length )); 167 168while (!done ) { 169done = uc_split_args_iter (ea .arg ,length ,& end ,buf ,& len ); 170if (len > 0 ) { 171ADD_C (args ,STRING_OBJ (cstrn_as_string (buf ,len ))); 172buf += len + 1 ; 173 } 174 } 175 } 176 177ucmd_T * cmd = NULL ; 178if (ea .cmdidx == CMD_USER ) { 179cmd = USER_CMD (ea .useridx ); 180 }else if (ea .cmdidx == CMD_USER_BUF ) { 181cmd = USER_CMD_GA (& curbuf -> b_ucmds ,ea .useridx ); 182 } 183 184// For range-only (:1) or modifier-only (:aboveleft) commands, cmd is empty string. 185char * name = ea .cmdidx == CMD_SIZE 186 ?"" : (cmd != NULL ?cmd -> uc_name :get_command_name (NULL ,ea .cmdidx )); 187 188PUT_KEY (result ,cmd ,cmd ,cstr_as_string (name )); 189 190if ((ea .argt & EX_RANGE )&& ea .addr_count > 0 ) { 191Array range = arena_array (arena ,2 ); 192if (ea .addr_count > 1 ) { 193ADD_C (range ,INTEGER_OBJ (ea .line1 )); 194 } 195ADD_C (range ,INTEGER_OBJ (ea .line2 )); 196PUT_KEY (result ,cmd ,range ,range ); 197 } 198 199if (ea .argt & EX_COUNT ) { 200Integer 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. 204if (ea .addr_count > 0 || (cmd != NULL && cmd -> uc_def != 0 )|| count != 0 ) { 205PUT_KEY (result ,cmd ,count ,count ); 206 } 207 } 208 209if (ea .argt & EX_REGSTR ) { 210char reg [2 ]= { (char )ea .regname ,NUL }; 211PUT_KEY (result ,cmd ,reg ,CSTR_TO_ARENA_STR (arena ,reg )); 212 } 213 214PUT_KEY (result ,cmd ,bang ,ea .forceit ); 215PUT_KEY (result ,cmd ,args ,args ); 216 217char nargs [2 ]; 218if (ea .argt & EX_EXTRA ) { 219if (ea .argt & EX_NOSPC ) { 220if (ea .argt & EX_ARGSPACE ) { 221nargs [0 ]= '_' ; 222 }else if (ea .argt & EX_NEEDARG ) { 223nargs [0 ]= '1' ; 224 }else { 225nargs [0 ]= '?' ; 226 } 227 }else if (ea .argt & EX_NEEDARG ) { 228nargs [0 ]= '+' ; 229 }else { 230nargs [0 ]= '*' ; 231 } 232 }else { 233nargs [0 ]= '0' ; 234 } 235nargs [1 ]= NUL ; 236PUT_KEY (result ,cmd ,nargs ,CSTR_TO_ARENA_OBJ (arena ,nargs )); 237 238char * addr ; 239switch (ea .addr_type ) { 240case ADDR_LINES : 241addr = "line" ; 242break ; 243case ADDR_ARGUMENTS : 244addr = "arg" ; 245break ; 246case ADDR_BUFFERS : 247addr = "buf" ; 248break ; 249case ADDR_LOADED_BUFFERS : 250addr = "load" ; 251break ; 252case ADDR_WINDOWS : 253addr = "win" ; 254break ; 255case ADDR_TABS : 256addr = "tab" ; 257break ; 258case ADDR_QUICKFIX : 259addr = "qf" ; 260break ; 261case ADDR_NONE : 262addr = "none" ; 263break ; 264default : 265addr = "?" ; 266break ; 267 } 268PUT_KEY (result ,cmd ,addr ,cstr_as_string (addr )); 269PUT_KEY (result ,cmd ,nextcmd ,cstr_as_string (ea .nextcmd )); 270 271// TODO(bfredl): nested keydict would be nice.. 272Dict mods = arena_dict (arena ,20 ); 273 274Dict filter = arena_dict (arena ,2 ); 275PUT_C (filter ,"pattern" ,CSTR_TO_ARENA_OBJ (arena ,cmod .cmod_filter_pat )); 276PUT_C (filter ,"force" ,BOOLEAN_OBJ (cmod .cmod_filter_force )); 277PUT_C (mods ,"filter" ,DICT_OBJ (filter )); 278 279PUT_C (mods ,"silent" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_SILENT )); 280PUT_C (mods ,"emsg_silent" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_ERRSILENT )); 281PUT_C (mods ,"unsilent" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_UNSILENT )); 282PUT_C (mods ,"sandbox" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_SANDBOX )); 283PUT_C (mods ,"noautocmd" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_NOAUTOCMD )); 284PUT_C (mods ,"tab" ,INTEGER_OBJ (cmod .cmod_tab - 1 )); 285PUT_C (mods ,"verbose" ,INTEGER_OBJ (cmod .cmod_verbose - 1 )); 286PUT_C (mods ,"browse" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_BROWSE )); 287PUT_C (mods ,"confirm" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_CONFIRM )); 288PUT_C (mods ,"hide" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_HIDE )); 289PUT_C (mods ,"keepalt" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_KEEPALT )); 290PUT_C (mods ,"keepjumps" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_KEEPJUMPS )); 291PUT_C (mods ,"keepmarks" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_KEEPMARKS )); 292PUT_C (mods ,"keeppatterns" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_KEEPPATTERNS )); 293PUT_C (mods ,"lockmarks" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_LOCKMARKS )); 294PUT_C (mods ,"noswapfile" ,BOOLEAN_OBJ (cmod .cmod_flags & CMOD_NOSWAPFILE )); 295PUT_C (mods ,"vertical" ,BOOLEAN_OBJ (cmod .cmod_split & WSP_VERT )); 296PUT_C (mods ,"horizontal" ,BOOLEAN_OBJ (cmod .cmod_split & WSP_HOR )); 297 298char * split ; 299if (cmod .cmod_split & WSP_BOT ) { 300split = "botright" ; 301 }else if (cmod .cmod_split & WSP_TOP ) { 302split = "topleft" ; 303 }else if (cmod .cmod_split & WSP_BELOW ) { 304split = "belowright" ; 305 }else if (cmod .cmod_split & WSP_ABOVE ) { 306split = "aboveleft" ; 307 }else { 308split = "" ; 309 } 310PUT_C (mods ,"split" ,CSTR_AS_OBJ (split )); 311 312PUT_KEY (result ,cmd ,mods ,mods ); 313 314Dict magic = arena_dict (arena ,2 ); 315PUT_C (magic ,"file" ,BOOLEAN_OBJ (ea .magic .file )); 316PUT_C (magic ,"bar" ,BOOLEAN_OBJ (ea .magic .bar )); 317PUT_KEY (result ,cmd ,magic ,magic ); 318 319undo_cmdmod (& cmod ); 320end : 321return 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 ) 355FUNC_API_SINCE (10 ) 356{ 357exarg_T ea ; 358CLEAR_FIELD (ea ); 359 360cmdmod_T cmod ; 361CLEAR_FIELD (cmod ); 362 363char * cmdline = NULL ; 364char * cmdname = NULL ; 365const char * errormsg = NULL ; 366ArrayOf (String )args = ARRAY_DICT_INIT ; 367 368String 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 386VALIDATE_R (HAS_KEY (cmd ,cmd ,cmd ),"cmd" , { 387 gotoend ; 388 }); 389 390if (cmd -> cmd .data [0 ]== NUL ) { 391VALIDATE_EXP ((HAS_KEY (cmd ,cmd ,range )&& cmd -> range .size > 0 )|| HAS_KEY (cmd ,cmd ,mods ), 392"cmd" ,"non-empty String" ,NULL , { 393 gotoend ; 394 }); 395 } 396 397cmdname = arena_string (arena ,cmd -> cmd ).data ; 398ea .cmd = cmdname ; 399 400char * 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. 404if (p != NULL && ea .cmdidx == CMD_SIZE && ASCII_ISUPPER (* ea .cmd ) 405&& has_event (EVENT_CMDUNDEFINED )) { 406p = arena_string (arena ,cmd -> cmd ).data ; 407int 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. 410p = (ret && !aborting ()) ?find_ex_command (& ea ,NULL ) :ea .cmd ; 411 } 412 413// Commands such as ":1" are "range only" commands. 414bool 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 418if (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 gotoend ; 422 } 423// Allow CMD_SIZE only for range-only commands (empty cmd with range) 424VALIDATE ((p != NULL && ea .cmdidx != CMD_SIZE )|| range_only , 425"Command not found: %s" ,cmdname , { 426 gotoend ; 427 }); 428 429VALIDATE (range_only || !is_cmd_ni (ea .cmdidx ),"Command not implemented: %s" ,cmdname , { 430 gotoend ; 431 }); 432 433if (!range_only ) { 434const char * fullname = IS_USER_CMDIDX (ea .cmdidx ) 435 ?get_user_command_name (ea .useridx ,ea .cmdidx ) 436 :get_command_name (NULL ,ea .cmdidx ); 437VALIDATE (strncmp (fullname ,cmdname ,strlen (cmdname ))== 0 , 438"Invalid command: \"%s\"" ,cmdname , { 439 gotoend ; 440 }); 441 } 442 443if (range_only ) { 444ea .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. 448ea .argt = excmd_get_argt (ea .cmdidx ); 449 } 450 451// Track whether the first argument was interpreted as count to avoid conflicts 452bool count_from_first_arg = false; 453// Parse command arguments since it's needed to get the command address type. 454if (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 457if (cmd -> args .size == 1 && (ea .argt & EX_COUNT )&& !(ea .argt & EX_EXTRA )) { 458Object first_arg = cmd -> args .items [0 ]; 459bool is_numeric = false; 460int64_t count_value = 0 ; 461 462if (first_arg .type == kObjectTypeInteger ) { 463is_numeric = true; 464count_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'}}) 467char * endptr = first_arg .data .string .data ; 468long val = getdigits_long (& endptr , false,0 ); 469// Check if entire string was consumed (valid number) and string is not empty 470if (* endptr == '\0' && first_arg .data .string .size > 0 ) { 471is_numeric = true; 472count_value = val ; 473 } 474 } 475 476if (is_numeric && count_value >=0 ) { 477// Interpret the argument as count 478count_from_first_arg = true; 479ea .addr_count = 1 ; 480ea .line1 = ea .line2 = (linenr_T )count_value ; 481args = arena_array (arena ,0 ); 482 } 483 } 484 485if (!count_from_first_arg ) { 486// Process all arguments. Convert non-String arguments to String and check if String arguments 487// have non-whitespace characters. 488args = arena_array (arena ,cmd -> args .size ); 489for (size_t i = 0 ;i < cmd -> args .size ;i ++ ) { 490Object elem = cmd -> args .items [i ]; 491char * data_str ; 492 493switch (elem .type ) { 494case kObjectTypeBoolean : 495data_str = arena_alloc (arena ,2 , false); 496data_str [0 ]= elem .data .boolean ?'1' :'0' ; 497data_str [1 ]= NUL ; 498ADD_C (args ,CSTR_AS_OBJ (data_str )); 499break ; 500case kObjectTypeBuffer : 501case kObjectTypeWindow : 502case kObjectTypeTabpage : 503case kObjectTypeInteger : 504data_str = arena_alloc (arena ,NUMBUFLEN , false); 505snprintf (data_str ,NUMBUFLEN ,"%" PRId64 ,elem .data .integer ); 506ADD_C (args ,CSTR_AS_OBJ (data_str )); 507break ; 508case kObjectTypeString : 509VALIDATE_EXP (!string_iswhite (elem .data .string ),"command arg" ,"non-whitespace" ,NULL , { 510 gotoend ; 511 }); 512ADD_C (args ,elem ); 513break ; 514default : 515VALIDATE_EXP (false,"command arg" ,"valid type" ,api_typename (elem .type ), { 516 gotoend ; 517 }); 518break ; 519 } 520 } 521 522bool argc_valid ; 523 524// Check if correct number of arguments is used. 525switch (ea .argt & (EX_EXTRA |EX_NOSPC |EX_NEEDARG )) { 526case EX_EXTRA |EX_NOSPC |EX_NEEDARG : 527argc_valid = args .size == 1 ; 528break ; 529case EX_EXTRA |EX_NOSPC : 530argc_valid = args .size <=1 ; 531break ; 532case EX_EXTRA |EX_NEEDARG : 533argc_valid = args .size >=1 ; 534break ; 535case EX_EXTRA : 536argc_valid = true; 537break ; 538default : 539argc_valid = args .size == 0 ; 540break ; 541 } 542 543VALIDATE (argc_valid ,"%s" ,"Wrong number of arguments" , { 544 gotoend ; 545 }); 546 } 547 } 548 549if (HAS_KEY (cmd ,cmd ,range )) { 550VALIDATE_MOD ((ea .argt & EX_RANGE ),"range" ,cmd -> cmd .data ); 551VALIDATE_EXP ((cmd -> range .size <=2 ),"range" ,"<=2 elements" ,NULL , { 552 gotoend ; 553 }); 554 555Array range = cmd -> range ; 556ea .addr_count = (int )range .size ; 557 558for (size_t i = 0 ;i < range .size ;i ++ ) { 559Object elem = range .items [i ]; 560VALIDATE_EXP ((elem .type == kObjectTypeInteger && elem .data .integer >=0 ), 561"range element" ,"non-negative Integer" ,NULL , { 562 gotoend ; 563 }); 564 } 565 566if (range .size > 0 ) { 567ea .line1 = (linenr_T )range .items [0 ].data .integer ; 568ea .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. 573build_cmdline_str (& cmdline ,& ea ,args ); 574if (!parse_cmdline (& cmdline ,& ea ,& cmod ,& errormsg , 575// Don't parse modifiers/reg/etc. Those come from `cmd`. 576 true)) { 577api_set_error (err ,kErrorTypeException ,"%s" ,errormsg ?errormsg :"Parsing command-line" ); 578 gotoend ; 579 } 580 581if (range_only ) { 582ea .argt = EX_RANGE |EX_SBOXOK ; 583 } 584 585if (HAS_KEY (cmd ,cmd ,range )) { 586VALIDATE_S ((invalid_range (& ea )== NULL ),"range" ,"" , { 587 gotoend ; 588 }); 589 } 590 591if (ea .addr_count == 0 && !(ea .argt & EX_DFLALL )&& ea .addr_type == ADDR_OTHER ) { 592// Default is 1, not cursor. 593ea .line2 = 1 ; 594 } 595 596// parse_cmdline() only sees one string, set the argument boundaries. 597ea .argc = args .size ; 598if (ea .argc > 0 ) { 599ea .args = xcalloc (ea .argc ,sizeof (char * )); 600ea .arglens = xcalloc (ea .argc ,sizeof (size_t )); 601p = ea .arg ; 602for (size_t i = 0 ;i < ea .argc ;i ++ ) { 603ea .args [i ]= p ; 604ea .arglens [i ]= args .items [i ].data .string .size ; 605p += ea .arglens [i ]+ 1 ;// Account for space 606 } 607 } 608 609if (HAS_KEY (cmd ,cmd ,count )) { 610VALIDATE (!count_from_first_arg ,"%s" ,"Cannot specify both 'count' and numeric argument" , { 611 gotoend ; 612 }); 613VALIDATE_MOD ((ea .argt & EX_COUNT ),"count" ,cmd -> cmd .data ); 614VALIDATE_EXP ((cmd -> count >=0 ),"count" ,"non-negative Integer" ,NULL , { 615 gotoend ; 616 }); 617set_cmd_count (& ea , (linenr_T )cmd -> count , true); 618 } 619 620if (HAS_KEY (cmd ,cmd ,reg )) { 621VALIDATE_MOD ((ea .argt & EX_REGSTR ),"register" ,cmd -> cmd .data ); 622VALIDATE_EXP ((cmd -> reg .size == 1 ), 623"reg" ,"single character" ,cmd -> reg .data , { 624 gotoend ; 625 }); 626char regname = cmd -> reg .data [0 ]; 627VALIDATE ((regname != '=' ),"%s" ,"Cannot use register \"=" , { 628 gotoend ; 629 }); 630VALIDATE (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 gotoend ; 635 }); 636ea .regname = (uint8_t )regname ; 637 } 638 639ea .forceit = cmd -> bang ; 640VALIDATE_MOD ((!ea .forceit || (ea .argt & EX_BANG )),"bang" ,cmd -> cmd .data ); 641 642if (HAS_KEY (cmd ,cmd ,magic )) { 643Dict (cmd_magic )magic [1 ]= KEYDICT_INIT ; 644if (!api_dict_to_keydict (magic ,DictHash (cmd_magic ),cmd -> magic ,err )) { 645 gotoend ; 646 } 647 648ea .magic .file = HAS_KEY (magic ,cmd_magic ,file ) ?magic -> file : (ea .argt & EX_XFILE ); 649ea .magic .bar = HAS_KEY (magic ,cmd_magic ,bar ) ?magic -> bar : (ea .argt & EX_TRLBAR ); 650if (ea .magic .file ) { 651ea .argt |=EX_XFILE ; 652 }else { 653ea .argt &= ~EX_XFILE ; 654 } 655 }else { 656ea .magic .file = ea .argt & EX_XFILE ; 657ea .magic .bar = ea .argt & EX_TRLBAR ; 658 } 659 660if (HAS_KEY (cmd ,cmd ,mods )) { 661Dict (cmd_mods )mods [1 ]= KEYDICT_INIT ; 662if (!api_dict_to_keydict (mods ,DictHash (cmd_mods ),cmd -> mods ,err )) { 663 gotoend ; 664 } 665 666if (HAS_KEY (mods ,cmd_mods ,filter )) { 667Dict (cmd_mods_filter )filter [1 ]= KEYDICT_INIT ; 668 669if (!api_dict_to_keydict (& filter ,DictHash (cmd_mods_filter ), 670mods -> filter ,err )) { 671 gotoend ; 672 } 673 674if (HAS_KEY (filter ,cmd_mods_filter ,pattern )) { 675cmod .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. 679if (* filter -> pattern .data != NUL || cmod .cmod_filter_force ) { 680cmod .cmod_filter_pat = string_to_cstr (filter -> pattern ); 681cmod .cmod_filter_regmatch .regprog = vim_regcomp (cmod .cmod_filter_pat ,RE_MAGIC ); 682 } 683 } 684 } 685 686if (HAS_KEY (mods ,cmd_mods ,tab )) { 687if ((int )mods -> tab >=0 ) { 688// Silently ignore negative integers to allow mods.tab to be set to -1. 689cmod .cmod_tab = (int )mods -> tab + 1 ; 690 } 691 } 692 693if (HAS_KEY (mods ,cmd_mods ,verbose )) { 694if ((int )mods -> verbose >=0 ) { 695// Silently ignore negative integers to allow mods.verbose to be set to -1. 696cmod .cmod_verbose = (int )mods -> verbose + 1 ; 697 } 698 } 699 700cmod .cmod_split |= (mods -> vertical ?WSP_VERT :0 ); 701 702cmod .cmod_split |= (mods -> horizontal ?WSP_HOR :0 ); 703 704if (HAS_KEY (mods ,cmd_mods ,split )) { 705if (* 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 ) { 709cmod .cmod_split |=WSP_ABOVE ; 710 }else if (strcmp (mods -> split .data ,"belowright" )== 0 711|| strcmp (mods -> split .data ,"rightbelow" )== 0 ) { 712cmod .cmod_split |=WSP_BELOW ; 713 }else if (strcmp (mods -> split .data ,"topleft" )== 0 ) { 714cmod .cmod_split |=WSP_TOP ; 715 }else if (strcmp (mods -> split .data ,"botright" )== 0 ) { 716cmod .cmod_split |=WSP_BOT ; 717 }else { 718VALIDATE_S (false,"mods.split" ,"" , { 719 gotoend ; 720 }); 721 } 722 } 723 724#define OBJ_TO_CMOD_FLAG (flag ,value ) \ 725 if (value) { \ 726 cmod.cmod_flags |= (flag); \ 727 } 728 729OBJ_TO_CMOD_FLAG (CMOD_SILENT ,mods -> silent ); 730OBJ_TO_CMOD_FLAG (CMOD_ERRSILENT ,mods -> emsg_silent ); 731OBJ_TO_CMOD_FLAG (CMOD_UNSILENT ,mods -> unsilent ); 732OBJ_TO_CMOD_FLAG (CMOD_SANDBOX ,mods -> sandbox ); 733OBJ_TO_CMOD_FLAG (CMOD_NOAUTOCMD ,mods -> noautocmd ); 734OBJ_TO_CMOD_FLAG (CMOD_BROWSE ,mods -> browse ); 735OBJ_TO_CMOD_FLAG (CMOD_CONFIRM ,mods -> confirm ); 736OBJ_TO_CMOD_FLAG (CMOD_HIDE ,mods -> hide ); 737OBJ_TO_CMOD_FLAG (CMOD_KEEPALT ,mods -> keepalt ); 738OBJ_TO_CMOD_FLAG (CMOD_KEEPJUMPS ,mods -> keepjumps ); 739OBJ_TO_CMOD_FLAG (CMOD_KEEPMARKS ,mods -> keepmarks ); 740OBJ_TO_CMOD_FLAG (CMOD_KEEPPATTERNS ,mods -> keeppatterns ); 741OBJ_TO_CMOD_FLAG (CMOD_LOCKMARKS ,mods -> lockmarks ); 742OBJ_TO_CMOD_FLAG (CMOD_NOSWAPFILE ,mods -> noswapfile ); 743 744if (cmod .cmod_flags & CMOD_ERRSILENT ) { 745// CMOD_ERRSILENT must imply CMOD_SILENT, otherwise apply_cmdmod() and undo_cmdmod() won't 746// work properly. 747cmod .cmod_flags |=CMOD_SILENT ; 748 } 749 750VALIDATE (!((cmod .cmod_flags & CMOD_SANDBOX )&& !(ea .argt & EX_SBOXOK )), 751"%s" ,"Command cannot be run in sandbox" , { 752 gotoend ; 753 }); 754 } 755 756// Replace :make and :grep with 'makeprg' and 'grepprg'. 757p = replace_makeprg (& ea ,ea .arg ,& cmdline ); 758if (p != ea .arg ) { 759// If replace_makeprg() modified the cmdline string, correct the ea.arg pointer. 760ea .arg = p ; 761// This cannot be a user command, so ea.args will not be used. 762XFREE_CLEAR (ea .args ); 763XFREE_CLEAR (ea .arglens ); 764ea .argc = 0 ; 765 } 766 767// Check for "++opt=val" argument. 768if (ea .argt & EX_ARGOPT ) { 769while (ea .arg [0 ]== '+' && ea .arg [1 ]== '+' ) { 770char * orig_arg = ea .arg ; 771int result = getargopt (& ea ); 772VALIDATE_S (result != FAIL || is_cmd_ni (ea .cmdidx ),"argument " ,orig_arg , { 773 gotoend ; 774 }); 775 } 776 } 777 778// Check for "+command" argument. 779if ((ea .argt & EX_CMDARG )&& !ea .usefilter ) { 780ea .do_ecmd_cmd = getargcmd (& ea .arg ); 781 } 782 783garray_T capture_local ; 784const int save_msg_silent = msg_silent ; 785const bool save_redir_off = redir_off ; 786garray_T * const save_capture_ga = capture_ga ; 787const int save_msg_col = msg_col ; 788 789if (opts -> output ) { 790ga_init (& capture_local ,1 ,80 ); 791capture_ga = & capture_local ; 792 } 793 794TRY_WRAP (err , { 795if (opts -> output ) { 796msg_silent ++ ; 797redir_off = false; 798msg_col = 0 ;// prevent leading spaces 799 } 800 801WITH_SCRIPT_CONTEXT (channel_id , { 802execute_cmd (& ea ,& cmod , false); 803 }); 804 805if (opts -> output ) { 806capture_ga = save_capture_ga ; 807msg_silent = save_msg_silent ; 808redir_off = save_redir_off ; 809// Put msg_col back where it was, since nothing should have been written. 810msg_col = save_msg_col ; 811 } 812 }); 813 814if (ERROR_SET (err )) { 815 gotoclear_ga ; 816 } 817 818if (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 820retv = CBUF_TO_ARENA_STR (arena ,capture_local .ga_data , (size_t )capture_local .ga_len ); 821// redir usually (except :echon) prepends a newline. 822if (retv .data [0 ]== '\n' ) { 823retv .data ++ ; 824retv .size -- ; 825 } 826 } 827clear_ga : 828if (opts -> output ) { 829ga_clear (& capture_local ); 830 } 831end : 832xfree (cmdline ); 833xfree (ea .args ); 834xfree (ea .arglens ); 835 836return 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{ 846for (size_t i = 0 ;i < str .size ;i ++ ) { 847if (!ascii_iswhite (str .data [i ])) { 848// Found a non-whitespace character 849return false; 850 }else if (str .data [i ]== NUL ) { 851// Terminate at first occurrence of a NUL character 852break ; 853 } 854 } 855return 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{ 863StringBuilder cmdline = KV_INITIAL_VALUE ; 864kv_resize (cmdline ,32 );// Make it big enough to handle most typical commands 865 866// Command range / count. 867if (eap -> argt & EX_RANGE ) { 868if (eap -> addr_count == 1 ) { 869kv_printf (cmdline ,"%" PRIdLINENR ,eap -> line2 ); 870 }else if (eap -> addr_count > 1 ) { 871kv_printf (cmdline ,"%" PRIdLINENR ",%" PRIdLINENR ,eap -> line1 ,eap -> line2 ); 872 } 873 } 874 875kv_concat (cmdline ,eap -> cmd ); 876 877for (size_t i = 0 ;i < args .size ;i ++ ) { 878String s = args .items [i ].data .string ; 879kv_concat (cmdline ," " ); 880kv_concat_len (cmdline ,s .data ,s .size ); 881 } 882 883// Done appending to cmdline, ensure it is NUL terminated 884kv_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 , 932String name , 933Union (String ,LuaRefOf ((DictAs (create_user_command__command_args )args )))cmd , 934Dict (user_command )* opts , 935Error * err ) 936FUNC_API_SINCE (9 ) 937{ 938create_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 ) 948FUNC_API_SINCE (9 ) 949{ 950nvim_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 , 959Dict (user_command )* opts ,Error * err ) 960FUNC_API_SINCE (9 ) 961{ 962buf_T * target_buf = find_buffer_by_handle (buf ,err ); 963if (ERROR_SET (err )) { 964return ; 965 } 966 967buf_T * save_curbuf = curbuf ; 968curbuf = target_buf ; 969create_user_command (channel_id ,name ,cmd ,opts ,UC_BUFFER ,err ); 970curbuf = 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 ) 982FUNC_API_SINCE (9 ) 983{ 984garray_T * gap ; 985if (buf == -1 ) { 986gap = & ucmds ; 987 }else { 988buf_T * b = find_buffer_by_handle (buf ,err ); 989if (ERROR_SET (err )) { 990return ; 991 } 992gap = & b -> b_ucmds ; 993 } 994 995for (int i = 0 ;i < gap -> ga_len ;i ++ ) { 996ucmd_T * cmd = USER_CMD_GA (gap ,i ); 997if (!strcmp (name .data ,cmd -> uc_name )) { 998free_ucmd (cmd ); 999 1000gap -> ga_len -= 1 ; 1001 1002if (i < gap -> ga_len ) { 1003memmove (cmd ,cmd + 1 , (size_t )(gap -> ga_len - i )* sizeof (ucmd_T )); 1004 } 1005 1006return ; 1007 } 1008 } 1009 1010api_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 , 1014Dict (user_command )* opts ,int flags ,Error * err ) 1015{ 1016uint32_t argt = 0 ; 1017int64_t def = -1 ; 1018cmd_addr_T addr_type_arg = ADDR_NONE ; 1019int context = EXPAND_NOTHING ; 1020char * compl_arg = NULL ; 1021const char * rep = NULL ; 1022LuaRef luaref = LUA_NOREF ; 1023LuaRef compl_luaref = LUA_NOREF ; 1024LuaRef preview_luaref = LUA_NOREF ; 1025 1026VALIDATE_S (uc_validate_name (name .data ),"command name" ,name .data , { 1027 gotoerr ; 1028 }); 1029VALIDATE_S (!mb_islower (name .data [0 ]),"command name (must start with uppercase)" , 1030name .data , { 1031 gotoerr ; 1032 }); 1033VALIDATE ((!HAS_KEY (opts ,user_command ,range )|| !HAS_KEY (opts ,user_command ,count )),"%s" , 1034"Cannot use both 'range' and 'count'" , { 1035 gotoerr ; 1036 }); 1037 1038if (opts -> nargs .type == kObjectTypeInteger ) { 1039switch (opts -> nargs .data .integer ) { 1040case 0 : 1041// Default value, nothing to do 1042break ; 1043case 1 : 1044argt |=EX_EXTRA |EX_NOSPC |EX_NEEDARG ; 1045break ; 1046default : 1047VALIDATE_INT (false,"nargs" , (int64_t )opts -> nargs .data .integer , { 1048 gotoerr ; 1049 }); 1050 } 1051 }else if (opts -> nargs .type == kObjectTypeString ) { 1052VALIDATE_S ((opts -> nargs .data .string .size <=1 ),"nargs" ,opts -> nargs .data .string .data , { 1053 gotoerr ; 1054 }); 1055 1056switch (opts -> nargs .data .string .data [0 ]) { 1057case '*' : 1058argt |=EX_EXTRA ; 1059break ; 1060case '?' : 1061argt |=EX_EXTRA |EX_NOSPC ; 1062break ; 1063case '+' : 1064argt |=EX_EXTRA |EX_NEEDARG ; 1065break ; 1066case '_' : 1067argt |=EX_EXTRA |EX_NOSPC |EX_NEEDARG |EX_ARGSPACE ; 1068break ; 1069default : 1070VALIDATE_S (false,"nargs" ,opts -> nargs .data .string .data , { 1071 gotoerr ; 1072 }); 1073 } 1074 }else if (HAS_KEY (opts ,user_command ,nargs )) { 1075VALIDATE_S (false,"nargs" ,"" , { 1076 gotoerr ; 1077 }); 1078 } 1079 1080VALIDATE ((!HAS_KEY (opts ,user_command ,complete )|| argt ), 1081"%s" ,"'complete' used without 'nargs'" , { 1082 gotoerr ; 1083 }); 1084 1085if (opts -> range .type == kObjectTypeBoolean ) { 1086if (opts -> range .data .boolean ) { 1087argt |=EX_RANGE ; 1088addr_type_arg = ADDR_LINES ; 1089 } 1090 }else if (opts -> range .type == kObjectTypeString ) { 1091VALIDATE_S ((opts -> range .data .string .data [0 ]== '%' && opts -> range .data .string .size == 1 ), 1092"range" ,"" , { 1093 gotoerr ; 1094 }); 1095argt |=EX_RANGE |EX_DFLALL ; 1096addr_type_arg = ADDR_LINES ; 1097 }else if (opts -> range .type == kObjectTypeInteger ) { 1098argt |=EX_RANGE |EX_ZEROR ; 1099def = opts -> range .data .integer ; 1100addr_type_arg = ADDR_LINES ; 1101 }else if (HAS_KEY (opts ,user_command ,range )) { 1102VALIDATE_S (false,"range" ,"" , { 1103 gotoerr ; 1104 }); 1105 } 1106 1107if (opts -> count .type == kObjectTypeBoolean ) { 1108if (opts -> count .data .boolean ) { 1109argt |=EX_COUNT |EX_ZEROR |EX_RANGE ; 1110addr_type_arg = ADDR_OTHER ; 1111def = 0 ; 1112 } 1113 }else if (opts -> count .type == kObjectTypeInteger ) { 1114argt |=EX_COUNT |EX_ZEROR |EX_RANGE ; 1115addr_type_arg = ADDR_OTHER ; 1116def = opts -> count .data .integer ; 1117 }else if (HAS_KEY (opts ,user_command ,count )) { 1118VALIDATE_S (false,"count" ,"" , { 1119 gotoerr ; 1120 }); 1121 } 1122 1123if (HAS_KEY (opts ,user_command ,addr )) { 1124VALIDATE_T ("addr" ,kObjectTypeString ,opts -> addr .type , { 1125 gotoerr ; 1126 }); 1127 1128VALIDATE_S (OK == parse_addr_type_arg (opts -> addr .data .string .data , 1129 (int )opts -> addr .data .string .size ,& addr_type_arg ),"addr" , 1130opts -> addr .data .string .data , { 1131 gotoerr ; 1132 }); 1133 1134argt |=EX_RANGE ; 1135if (addr_type_arg != ADDR_LINES ) { 1136argt |=EX_ZEROR ; 1137 } 1138 } 1139 1140if (opts -> bang ) { 1141argt |=EX_BANG ; 1142 } 1143 1144if (opts -> bar ) { 1145argt |=EX_TRLBAR ; 1146 } 1147 1148if (opts -> register_ ) { 1149argt |=EX_REGSTR ; 1150 } 1151 1152if (opts -> keepscript ) { 1153argt |=EX_KEEPSCRIPT ; 1154 } 1155 1156bool force = GET_BOOL_OR_TRUE (opts ,user_command ,force ); 1157if (ERROR_SET (err )) { 1158 gotoerr ; 1159 } 1160 1161if (opts -> complete .type == kObjectTypeLuaRef ) { 1162context = EXPAND_USER_LUA ; 1163compl_luaref = opts -> complete .data .luaref ; 1164opts -> complete .data .luaref = LUA_NOREF ; 1165 }else if (opts -> complete .type == kObjectTypeString ) { 1166VALIDATE_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 gotoerr ; 1171 }); 1172 }else if (HAS_KEY (opts ,user_command ,complete )) { 1173VALIDATE_EXP (false,"complete" ,"Function or String" ,NULL , { 1174 gotoerr ; 1175 }); 1176 } 1177 1178if (HAS_KEY (opts ,user_command ,preview )) { 1179VALIDATE_T ("preview" ,kObjectTypeLuaRef ,opts -> preview .type , { 1180 gotoerr ; 1181 }); 1182 1183argt |=EX_PREVIEW ; 1184preview_luaref = opts -> preview .data .luaref ; 1185opts -> preview .data .luaref = LUA_NOREF ; 1186 } 1187 1188const char * desc = NULL ; 1189if (HAS_KEY (opts ,user_command ,desc )) { 1190VALIDATE_T ("desc" ,kObjectTypeString ,opts -> desc .type , { 1191 gotoerr ; 1192 }); 1193desc = opts -> desc .data .string .data ; 1194 } 1195 1196switch (cmd .type ) { 1197case kObjectTypeLuaRef : 1198luaref = api_new_luaref (cmd .data .luaref ); 1199rep = "" ; 1200break ; 1201case kObjectTypeString : 1202rep = cmd .data .string .data ; 1203break ; 1204default : 1205VALIDATE_EXP (false,"command" ,"Function or String" ,NULL , { 1206 gotoerr ; 1207 }); 1208 } 1209 1210WITH_SCRIPT_CONTEXT (channel_id , { 1211if (uc_add_command (name .data ,name .size ,rep ,argt ,def ,flags ,context ,compl_arg , 1212compl_luaref ,preview_luaref ,addr_type_arg ,luaref ,desc ,force )!= OK ) { 1213api_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 1219return ; 1220 1221err : 1222NLUA_CLEAR_REF (luaref ); 1223NLUA_CLEAR_REF (compl_luaref ); 1224NLUA_CLEAR_REF (preview_luaref ); 1225xfree (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 ) 1239FUNC_API_SINCE (4 ) 1240{ 1241return 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 , 1252Error * err ) 1253FUNC_API_SINCE (4 ) 1254{ 1255bool global = (buf == -1 ); 1256if (ERROR_SET (err )) { 1257return (Dict )ARRAY_DICT_INIT ; 1258 } 1259 1260if (global ) { 1261if (opts -> builtin ) { 1262api_set_error (err ,kErrorTypeValidation ,"builtin=true not implemented" ); 1263return (Dict )ARRAY_DICT_INIT ; 1264 } 1265return commands_array (NULL ,arena ); 1266 } 1267 1268buf_T * b = find_buffer_by_handle (buf ,err ); 1269if (opts -> builtin || !b ) { 1270return (Dict )ARRAY_DICT_INIT ; 1271 } 1272return commands_array (b ,arena ); 1273}