// This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* * eval.c: Expression evaluation. */ #include #include #include #include #include #include #include #include #include #include #include "nvim/assert.h" #include "nvim/vim.h" #include "nvim/ascii.h" #ifdef HAVE_LOCALE_H # include #endif #include "nvim/eval.h" #include "nvim/buffer.h" #include "nvim/change.h" #include "nvim/channel.h" #include "nvim/charset.h" #include "nvim/context.h" #include "nvim/cursor.h" #include "nvim/diff.h" #include "nvim/edit.h" #include "nvim/ex_cmds.h" #include "nvim/ex_cmds2.h" #include "nvim/ex_docmd.h" #include "nvim/ex_eval.h" #include "nvim/ex_getln.h" #include "nvim/fileio.h" #include "nvim/os/fileio.h" #include "nvim/func_attr.h" #include "nvim/fold.h" #include "nvim/getchar.h" #include "nvim/hashtab.h" #include "nvim/iconv.h" #include "nvim/if_cscope.h" #include "nvim/indent_c.h" #include "nvim/indent.h" #include "nvim/mark.h" #include "nvim/math.h" #include "nvim/mbyte.h" #include "nvim/memline.h" #include "nvim/memory.h" #include "nvim/menu.h" #include "nvim/message.h" #include "nvim/misc1.h" #include "nvim/keymap.h" #include "nvim/map.h" #include "nvim/file_search.h" #include "nvim/garray.h" #include "nvim/move.h" #include "nvim/normal.h" #include "nvim/ops.h" #include "nvim/option.h" #include "nvim/os_unix.h" #include "nvim/path.h" #include "nvim/popupmnu.h" #include "nvim/profile.h" #include "nvim/quickfix.h" #include "nvim/regexp.h" #include "nvim/screen.h" #include "nvim/search.h" #include "nvim/sha256.h" #include "nvim/sign.h" #include "nvim/spell.h" #include "nvim/state.h" #include "nvim/strings.h" #include "nvim/syntax.h" #include "nvim/tag.h" #include "nvim/ui.h" #include "nvim/main.h" #include "nvim/mouse.h" #include "nvim/terminal.h" #include "nvim/undo.h" #include "nvim/version.h" #include "nvim/window.h" #include "nvim/eval/encode.h" #include "nvim/eval/decode.h" #include "nvim/os/os.h" #include "nvim/event/libuv_process.h" #include "nvim/os/pty_process.h" #include "nvim/event/rstream.h" #include "nvim/event/wstream.h" #include "nvim/event/time.h" #include "nvim/os/time.h" #include "nvim/msgpack_rpc/channel.h" #include "nvim/msgpack_rpc/server.h" #include "nvim/msgpack_rpc/helpers.h" #include "nvim/api/private/helpers.h" #include "nvim/api/vim.h" #include "nvim/os/dl.h" #include "nvim/os/input.h" #include "nvim/event/loop.h" #include "nvim/lib/kvec.h" #include "nvim/lib/khash.h" #include "nvim/lib/queue.h" #include "nvim/lua/executor.h" #include "nvim/eval/typval.h" #include "nvim/eval/executor.h" #include "nvim/eval/gc.h" #include "nvim/macros.h" // TODO(ZyX-I): Remove DICT_MAXNEST, make users be non-recursive instead #define DICT_MAXNEST 100 /* maximum nesting of lists and dicts */ // Character used as separator in autoload function/variable names. #define AUTOLOAD_CHAR '#' /* * Structure returned by get_lval() and used by set_var_lval(). * For a plain name: * "name" points to the variable name. * "exp_name" is NULL. * "tv" is NULL * For a magic braces name: * "name" points to the expanded variable name. * "exp_name" is non-NULL, to be freed later. * "tv" is NULL * For an index in a list: * "name" points to the (expanded) variable name. * "exp_name" NULL or non-NULL, to be freed later. * "tv" points to the (first) list item value * "li" points to the (first) list item * "range", "n1", "n2" and "empty2" indicate what items are used. * For an existing Dict item: * "name" points to the (expanded) variable name. * "exp_name" NULL or non-NULL, to be freed later. * "tv" points to the dict item value * "newkey" is NULL * For a non-existing Dict item: * "name" points to the (expanded) variable name. * "exp_name" NULL or non-NULL, to be freed later. * "tv" points to the Dictionary typval_T * "newkey" is the key for the new item. */ typedef struct lval_S { const char *ll_name; ///< Start of variable name (can be NULL). size_t ll_name_len; ///< Length of the .ll_name. char *ll_exp_name; ///< NULL or expanded name in allocated memory. typval_T *ll_tv; ///< Typeval of item being used. If "newkey" ///< isn't NULL it's the Dict to which to add the item. listitem_T *ll_li; ///< The list item or NULL. list_T *ll_list; ///< The list or NULL. int ll_range; ///< TRUE when a [i:j] range was used. long ll_n1; ///< First index for list. long ll_n2; ///< Second index for list range. int ll_empty2; ///< Second index is empty: [i:]. dict_T *ll_dict; ///< The Dictionary or NULL. dictitem_T *ll_di; ///< The dictitem or NULL. char_u *ll_newkey; ///< New key for Dict in allocated memory or NULL. } lval_T; static char *e_letunexp = N_("E18: Unexpected characters in :let"); static char *e_missbrac = N_("E111: Missing ']'"); static char *e_listarg = N_("E686: Argument of %s must be a List"); static char *e_listdictarg = N_( "E712: Argument of %s must be a List or Dictionary"); static char *e_listreq = N_("E714: List required"); static char *e_dictreq = N_("E715: Dictionary required"); static char *e_stringreq = N_("E928: String required"); static char *e_toomanyarg = N_("E118: Too many arguments for function: %s"); static char *e_dictkey = N_("E716: Key not present in Dictionary: %s"); static char *e_funcexts = N_( "E122: Function %s already exists, add ! to replace it"); static char *e_funcdict = N_("E717: Dictionary entry already exists"); static char *e_funcref = N_("E718: Funcref required"); static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary"); static char *e_nofunc = N_("E130: Unknown function: %s"); static char *e_illvar = N_("E461: Illegal variable name: %s"); static char *e_cannot_mod = N_("E995: Cannot modify existing variable"); static const char *e_readonlyvar = N_( "E46: Cannot change read-only variable \"%.*s\""); // TODO(ZyX-I): move to eval/executor static char *e_letwrong = N_("E734: Wrong variable type for %s="); static char_u * const namespace_char = (char_u *)"abglstvw"; /// Variable used for g: static ScopeDictDictItem globvars_var; /// g: value #define globvarht globvardict.dv_hashtab /* * Old Vim variables such as "v:version" are also available without the "v:". * Also in functions. We need a special hashtable for them. */ static hashtab_T compat_hashtab; hashtab_T func_hashtab; // Used for checking if local variables or arguments used in a lambda. static int *eval_lavars_used = NULL; /* * Array to hold the hashtab with variables local to each sourced script. * Each item holds a variable (nameless) that points to the dict_T. */ typedef struct { ScopeDictDictItem sv_var; dict_T sv_dict; } scriptvar_T; static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T *), 4, NULL}; #define SCRIPT_SV(id) (((scriptvar_T **)ga_scripts.ga_data)[(id) - 1]) #define SCRIPT_VARS(id) (SCRIPT_SV(id)->sv_dict.dv_hashtab) static int echo_attr = 0; /* attributes used for ":echo" */ /// Describe data to return from find_some_match() typedef enum { kSomeMatch, ///< Data for match(). kSomeMatchEnd, ///< Data for matchend(). kSomeMatchList, ///< Data for matchlist(). kSomeMatchStr, ///< Data for matchstr(). kSomeMatchStrPos, ///< Data for matchstrpos(). } SomeMatchType; /// trans_function_name() flags typedef enum { TFN_INT = 1, ///< May use internal function name TFN_QUIET = 2, ///< Do not emit error messages. TFN_NO_AUTOLOAD = 4, ///< Do not use script autoloading. TFN_NO_DEREF = 8, ///< Do not dereference a Funcref. TFN_READ_ONLY = 16, ///< Will not change the variable. } TransFunctionNameFlags; /// get_lval() flags typedef enum { GLV_QUIET = TFN_QUIET, ///< Do not emit error messages. GLV_NO_AUTOLOAD = TFN_NO_AUTOLOAD, ///< Do not use script autoloading. GLV_READ_ONLY = TFN_READ_ONLY, ///< Indicates that caller will not change ///< the value (prevents error message). } GetLvalFlags; // flags used in uf_flags #define FC_ABORT 0x01 // abort function on error #define FC_RANGE 0x02 // function accepts range #define FC_DICT 0x04 // Dict function, uses "self" #define FC_CLOSURE 0x08 // closure, uses outer scope variables #define FC_DELETED 0x10 // :delfunction used while uf_refcount > 0 #define FC_REMOVED 0x20 // function redefined while uf_refcount > 0 #define FC_SANDBOX 0x40 // function defined in the sandbox // The names of packages that once were loaded are remembered. static garray_T ga_loaded = { 0, 0, sizeof(char_u *), 4, NULL }; #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j] #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j] /// Short variable name length #define VAR_SHORT_LEN 20 /// Number of fixed variables used for arguments #define FIXVAR_CNT 12 struct funccall_S { ufunc_T *func; ///< Function being called. int linenr; ///< Next line to be executed. int returned; ///< ":return" used. /// Fixed variables for arguments. TV_DICTITEM_STRUCT(VAR_SHORT_LEN + 1) fixvar[FIXVAR_CNT]; dict_T l_vars; ///< l: local function variables. ScopeDictDictItem l_vars_var; ///< Variable for l: scope. dict_T l_avars; ///< a: argument variables. ScopeDictDictItem l_avars_var; ///< Variable for a: scope. list_T l_varlist; ///< List for a:000. listitem_T l_listitems[MAX_FUNC_ARGS]; ///< List items for a:000. typval_T *rettv; ///< Return value. linenr_T breakpoint; ///< Next line with breakpoint or zero. int dbg_tick; ///< Debug_tick when breakpoint was set. int level; ///< Top nesting level of executed function. proftime_T prof_child; ///< Time spent in a child. funccall_T *caller; ///< Calling function or NULL. int fc_refcount; ///< Number of user functions that reference this funccall. int fc_copyID; ///< CopyID used for garbage collection. garray_T fc_funcs; ///< List of ufunc_T* which keep a reference to "func". }; ///< Structure used by trans_function_name() typedef struct { dict_T *fd_dict; ///< Dictionary used. char_u *fd_newkey; ///< New key in "dict" in allocated memory. dictitem_T *fd_di; ///< Dictionary item used. } funcdict_T; /* * Info used by a ":for" loop. */ typedef struct { int fi_semicolon; /* TRUE if ending in '; var]' */ int fi_varcount; /* nr of variables in the list */ listwatch_T fi_lw; /* keep an eye on the item used. */ list_T *fi_list; /* list being used */ } forinfo_T; /* values for vv_flags: */ #define VV_COMPAT 1 /* compatible, also used without "v:" */ #define VV_RO 2 /* read-only */ #define VV_RO_SBX 4 /* read-only in the sandbox */ #define VV(idx, name, type, flags) \ [idx] = { \ .vv_name = name, \ .vv_di = { \ .di_tv = { .v_type = type }, \ .di_flags = 0, \ .di_key = { 0 }, \ }, \ .vv_flags = flags, \ } // Array to hold the value of v: variables. // The value is in a dictitem, so that it can also be used in the v: scope. // The reason to use this table anyway is for very quick access to the // variables with the VV_ defines. static struct vimvar { char *vv_name; ///< Name of the variable, without v:. TV_DICTITEM_STRUCT(17) vv_di; ///< Value and name for key (max 16 chars). char vv_flags; ///< Flags: #VV_COMPAT, #VV_RO, #VV_RO_SBX. } vimvars[] = { // VV_ tails differing from upcased string literals: // VV_CC_FROM "charconvert_from" // VV_CC_TO "charconvert_to" // VV_SEND_SERVER "servername" // VV_REG "register" // VV_OP "operator" VV(VV_COUNT, "count", VAR_NUMBER, VV_RO), VV(VV_COUNT1, "count1", VAR_NUMBER, VV_RO), VV(VV_PREVCOUNT, "prevcount", VAR_NUMBER, VV_RO), VV(VV_ERRMSG, "errmsg", VAR_STRING, 0), VV(VV_WARNINGMSG, "warningmsg", VAR_STRING, 0), VV(VV_STATUSMSG, "statusmsg", VAR_STRING, 0), VV(VV_SHELL_ERROR, "shell_error", VAR_NUMBER, VV_RO), VV(VV_THIS_SESSION, "this_session", VAR_STRING, 0), VV(VV_VERSION, "version", VAR_NUMBER, VV_COMPAT+VV_RO), VV(VV_LNUM, "lnum", VAR_NUMBER, VV_RO_SBX), VV(VV_TERMRESPONSE, "termresponse", VAR_STRING, VV_RO), VV(VV_FNAME, "fname", VAR_STRING, VV_RO), VV(VV_LANG, "lang", VAR_STRING, VV_RO), VV(VV_LC_TIME, "lc_time", VAR_STRING, VV_RO), VV(VV_CTYPE, "ctype", VAR_STRING, VV_RO), VV(VV_CC_FROM, "charconvert_from", VAR_STRING, VV_RO), VV(VV_CC_TO, "charconvert_to", VAR_STRING, VV_RO), VV(VV_FNAME_IN, "fname_in", VAR_STRING, VV_RO), VV(VV_FNAME_OUT, "fname_out", VAR_STRING, VV_RO), VV(VV_FNAME_NEW, "fname_new", VAR_STRING, VV_RO), VV(VV_FNAME_DIFF, "fname_diff", VAR_STRING, VV_RO), VV(VV_CMDARG, "cmdarg", VAR_STRING, VV_RO), VV(VV_FOLDSTART, "foldstart", VAR_NUMBER, VV_RO_SBX), VV(VV_FOLDEND, "foldend", VAR_NUMBER, VV_RO_SBX), VV(VV_FOLDDASHES, "folddashes", VAR_STRING, VV_RO_SBX), VV(VV_FOLDLEVEL, "foldlevel", VAR_NUMBER, VV_RO_SBX), VV(VV_PROGNAME, "progname", VAR_STRING, VV_RO), VV(VV_SEND_SERVER, "servername", VAR_STRING, VV_RO), VV(VV_DYING, "dying", VAR_NUMBER, VV_RO), VV(VV_EXCEPTION, "exception", VAR_STRING, VV_RO), VV(VV_THROWPOINT, "throwpoint", VAR_STRING, VV_RO), VV(VV_STDERR, "stderr", VAR_NUMBER, VV_RO), VV(VV_REG, "register", VAR_STRING, VV_RO), VV(VV_CMDBANG, "cmdbang", VAR_NUMBER, VV_RO), VV(VV_INSERTMODE, "insertmode", VAR_STRING, VV_RO), VV(VV_VAL, "val", VAR_UNKNOWN, VV_RO), VV(VV_KEY, "key", VAR_UNKNOWN, VV_RO), VV(VV_PROFILING, "profiling", VAR_NUMBER, VV_RO), VV(VV_FCS_REASON, "fcs_reason", VAR_STRING, VV_RO), VV(VV_FCS_CHOICE, "fcs_choice", VAR_STRING, 0), VV(VV_BEVAL_BUFNR, "beval_bufnr", VAR_NUMBER, VV_RO), VV(VV_BEVAL_WINNR, "beval_winnr", VAR_NUMBER, VV_RO), VV(VV_BEVAL_WINID, "beval_winid", VAR_NUMBER, VV_RO), VV(VV_BEVAL_LNUM, "beval_lnum", VAR_NUMBER, VV_RO), VV(VV_BEVAL_COL, "beval_col", VAR_NUMBER, VV_RO), VV(VV_BEVAL_TEXT, "beval_text", VAR_STRING, VV_RO), VV(VV_SCROLLSTART, "scrollstart", VAR_STRING, 0), VV(VV_SWAPNAME, "swapname", VAR_STRING, VV_RO), VV(VV_SWAPCHOICE, "swapchoice", VAR_STRING, 0), VV(VV_SWAPCOMMAND, "swapcommand", VAR_STRING, VV_RO), VV(VV_CHAR, "char", VAR_STRING, 0), VV(VV_MOUSE_WIN, "mouse_win", VAR_NUMBER, 0), VV(VV_MOUSE_WINID, "mouse_winid", VAR_NUMBER, 0), VV(VV_MOUSE_LNUM, "mouse_lnum", VAR_NUMBER, 0), VV(VV_MOUSE_COL, "mouse_col", VAR_NUMBER, 0), VV(VV_OP, "operator", VAR_STRING, VV_RO), VV(VV_SEARCHFORWARD, "searchforward", VAR_NUMBER, 0), VV(VV_HLSEARCH, "hlsearch", VAR_NUMBER, 0), VV(VV_OLDFILES, "oldfiles", VAR_LIST, 0), VV(VV_WINDOWID, "windowid", VAR_NUMBER, VV_RO_SBX), VV(VV_PROGPATH, "progpath", VAR_STRING, VV_RO), VV(VV_COMPLETED_ITEM, "completed_item", VAR_DICT, VV_RO), VV(VV_OPTION_NEW, "option_new", VAR_STRING, VV_RO), VV(VV_OPTION_OLD, "option_old", VAR_STRING, VV_RO), VV(VV_OPTION_TYPE, "option_type", VAR_STRING, VV_RO), VV(VV_ERRORS, "errors", VAR_LIST, 0), VV(VV_MSGPACK_TYPES, "msgpack_types", VAR_DICT, VV_RO), VV(VV_EVENT, "event", VAR_DICT, VV_RO), VV(VV_FALSE, "false", VAR_SPECIAL, VV_RO), VV(VV_TRUE, "true", VAR_SPECIAL, VV_RO), VV(VV_NULL, "null", VAR_SPECIAL, VV_RO), VV(VV__NULL_LIST, "_null_list", VAR_LIST, VV_RO), VV(VV__NULL_DICT, "_null_dict", VAR_DICT, VV_RO), VV(VV_VIM_DID_ENTER, "vim_did_enter", VAR_NUMBER, VV_RO), VV(VV_TESTING, "testing", VAR_NUMBER, 0), VV(VV_TYPE_NUMBER, "t_number", VAR_NUMBER, VV_RO), VV(VV_TYPE_STRING, "t_string", VAR_NUMBER, VV_RO), VV(VV_TYPE_FUNC, "t_func", VAR_NUMBER, VV_RO), VV(VV_TYPE_LIST, "t_list", VAR_NUMBER, VV_RO), VV(VV_TYPE_DICT, "t_dict", VAR_NUMBER, VV_RO), VV(VV_TYPE_FLOAT, "t_float", VAR_NUMBER, VV_RO), VV(VV_TYPE_BOOL, "t_bool", VAR_NUMBER, VV_RO), VV(VV_ECHOSPACE, "echospace", VAR_NUMBER, VV_RO), VV(VV_EXITING, "exiting", VAR_NUMBER, VV_RO), }; #undef VV /* shorthand */ #define vv_type vv_di.di_tv.v_type #define vv_nr vv_di.di_tv.vval.v_number #define vv_special vv_di.di_tv.vval.v_special #define vv_float vv_di.di_tv.vval.v_float #define vv_str vv_di.di_tv.vval.v_string #define vv_list vv_di.di_tv.vval.v_list #define vv_dict vv_di.di_tv.vval.v_dict #define vv_tv vv_di.di_tv /// Variable used for v: static ScopeDictDictItem vimvars_var; /// v: hashtab #define vimvarht vimvardict.dv_hashtab typedef struct { TimeWatcher tw; int timer_id; int repeat_count; int refcount; int emsg_count; ///< Errors in a repeating timer. long timeout; bool stopped; bool paused; Callback callback; } timer_T; typedef void (*FunPtr)(void); /// Prototype of C function that implements VimL function typedef void (*VimLFunc)(typval_T *args, typval_T *rvar, FunPtr data); /// Structure holding VimL function definition typedef struct fst { char *name; ///< Name of the function. uint8_t min_argc; ///< Minimal number of arguments. uint8_t max_argc; ///< Maximal number of arguments. VimLFunc func; ///< Function implementation. FunPtr data; ///< Userdata for function implementation. } VimLFuncDef; KHASH_MAP_INIT_STR(functions, VimLFuncDef) /// Type of assert_* check being performed typedef enum { ASSERT_EQUAL, ASSERT_NOTEQUAL, ASSERT_MATCH, ASSERT_NOTMATCH, ASSERT_INRANGE, ASSERT_OTHER, } assert_type_T; /// Type for dict_list function typedef enum { kDictListKeys, ///< List dictionary keys. kDictListValues, ///< List dictionary values. kDictListItems, ///< List dictionary contents: [keys, values]. } DictListType; #ifdef INCLUDE_GENERATED_DECLARATIONS # include "eval.c.generated.h" #endif #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */ #define FNE_CHECK_START 2 /* find_name_end(): check name starts with valid character */ static uint64_t last_timer_id = 1; static PMap(uint64_t) *timers = NULL; /// Dummy va_list for passing to vim_snprintf /// /// Used because: /// - passing a NULL pointer doesn't work when va_list isn't a pointer /// - locally in the function results in a "used before set" warning /// - using va_start() to initialize it gives "function with fixed args" error static va_list dummy_ap; static const char *const msgpack_type_names[] = { [kMPNil] = "nil", [kMPBoolean] = "boolean", [kMPInteger] = "integer", [kMPFloat] = "float", [kMPString] = "string", [kMPBinary] = "binary", [kMPArray] = "array", [kMPMap] = "map", [kMPExt] = "ext", }; const list_T *eval_msgpack_type_lists[] = { [kMPNil] = NULL, [kMPBoolean] = NULL, [kMPInteger] = NULL, [kMPFloat] = NULL, [kMPString] = NULL, [kMPBinary] = NULL, [kMPArray] = NULL, [kMPMap] = NULL, [kMPExt] = NULL, }; // Return "n1" divided by "n2", taking care of dividing by zero. varnumber_T num_divide(varnumber_T n1, varnumber_T n2) FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT { varnumber_T result; if (n2 == 0) { // give an error message? if (n1 == 0) { result = VARNUMBER_MIN; // similar to NaN } else if (n1 < 0) { result = -VARNUMBER_MAX; } else { result = VARNUMBER_MAX; } } else { result = n1 / n2; } return result; } // Return "n1" modulus "n2", taking care of dividing by zero. varnumber_T num_modulus(varnumber_T n1, varnumber_T n2) FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT { // Give an error when n2 is 0? return (n2 == 0) ? 0 : (n1 % n2); } /* * Initialize the global and v: variables. */ void eval_init(void) { vimvars[VV_VERSION].vv_nr = VIM_VERSION_100; timers = pmap_new(uint64_t)(); struct vimvar *p; init_var_dict(&globvardict, &globvars_var, VAR_DEF_SCOPE); init_var_dict(&vimvardict, &vimvars_var, VAR_SCOPE); vimvardict.dv_lock = VAR_FIXED; hash_init(&compat_hashtab); hash_init(&func_hashtab); for (size_t i = 0; i < ARRAY_SIZE(vimvars); i++) { p = &vimvars[i]; assert(STRLEN(p->vv_name) <= 16); STRCPY(p->vv_di.di_key, p->vv_name); if (p->vv_flags & VV_RO) p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; else if (p->vv_flags & VV_RO_SBX) p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX; else p->vv_di.di_flags = DI_FLAGS_FIX; /* add to v: scope dict, unless the value is not always available */ if (p->vv_type != VAR_UNKNOWN) hash_add(&vimvarht, p->vv_di.di_key); if (p->vv_flags & VV_COMPAT) /* add to compat scope dict */ hash_add(&compat_hashtab, p->vv_di.di_key); } vimvars[VV_VERSION].vv_nr = VIM_VERSION_100; dict_T *const msgpack_types_dict = tv_dict_alloc(); for (size_t i = 0; i < ARRAY_SIZE(msgpack_type_names); i++) { list_T *const type_list = tv_list_alloc(0); tv_list_set_lock(type_list, VAR_FIXED); tv_list_ref(type_list); dictitem_T *const di = tv_dict_item_alloc(msgpack_type_names[i]); di->di_flags |= DI_FLAGS_RO|DI_FLAGS_FIX; di->di_tv = (typval_T) { .v_type = VAR_LIST, .vval = { .v_list = type_list, }, }; eval_msgpack_type_lists[i] = type_list; if (tv_dict_add(msgpack_types_dict, di) == FAIL) { // There must not be duplicate items in this dictionary by definition. assert(false); } } msgpack_types_dict->dv_lock = VAR_FIXED; set_vim_var_dict(VV_MSGPACK_TYPES, msgpack_types_dict); set_vim_var_dict(VV_COMPLETED_ITEM, tv_dict_alloc()); dict_T *v_event = tv_dict_alloc(); v_event->dv_lock = VAR_FIXED; set_vim_var_dict(VV_EVENT, v_event); set_vim_var_list(VV_ERRORS, tv_list_alloc(kListLenUnknown)); set_vim_var_nr(VV_STDERR, CHAN_STDERR); set_vim_var_nr(VV_SEARCHFORWARD, 1L); set_vim_var_nr(VV_HLSEARCH, 1L); set_vim_var_nr(VV_COUNT1, 1); set_vim_var_nr(VV_TYPE_NUMBER, VAR_TYPE_NUMBER); set_vim_var_nr(VV_TYPE_STRING, VAR_TYPE_STRING); set_vim_var_nr(VV_TYPE_FUNC, VAR_TYPE_FUNC); set_vim_var_nr(VV_TYPE_LIST, VAR_TYPE_LIST); set_vim_var_nr(VV_TYPE_DICT, VAR_TYPE_DICT); set_vim_var_nr(VV_TYPE_FLOAT, VAR_TYPE_FLOAT); set_vim_var_nr(VV_TYPE_BOOL, VAR_TYPE_BOOL); set_vim_var_special(VV_FALSE, kSpecialVarFalse); set_vim_var_special(VV_TRUE, kSpecialVarTrue); set_vim_var_special(VV_NULL, kSpecialVarNull); set_vim_var_special(VV_EXITING, kSpecialVarNull); set_vim_var_nr(VV_ECHOSPACE, sc_col - 1); set_reg_var(0); // default for v:register is not 0 but '"' } #if defined(EXITFREE) void eval_clear(void) { struct vimvar *p; for (size_t i = 0; i < ARRAY_SIZE(vimvars); i++) { p = &vimvars[i]; if (p->vv_di.di_tv.v_type == VAR_STRING) { XFREE_CLEAR(p->vv_str); } else if (p->vv_di.di_tv.v_type == VAR_LIST) { tv_list_unref(p->vv_list); p->vv_list = NULL; } } hash_clear(&vimvarht); hash_init(&vimvarht); /* garbage_collect() will access it */ hash_clear(&compat_hashtab); free_scriptnames(); free_locales(); /* global variables */ vars_clear(&globvarht); /* autoloaded script names */ ga_clear_strings(&ga_loaded); /* Script-local variables. First clear all the variables and in a second * loop free the scriptvar_T, because a variable in one script might hold * a reference to the whole scope of another script. */ for (int i = 1; i <= ga_scripts.ga_len; ++i) vars_clear(&SCRIPT_VARS(i)); for (int i = 1; i <= ga_scripts.ga_len; ++i) xfree(SCRIPT_SV(i)); ga_clear(&ga_scripts); // unreferenced lists and dicts (void)garbage_collect(false); // functions free_all_functions(); } #endif /* * Return the name of the executed function. */ char_u *func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T *func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int *func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* pointer to funccal for currently active function */ funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. funccall_T *previous_funccal = NULL; /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } /* * Set an internal variable to a string value. Creates the variable if it does * not already exist. */ void set_internal_string_var(char_u *name, char_u *value) { const typval_T tv = { .v_type = VAR_STRING, .vval.v_string = value, }; set_var((const char *)name, STRLEN(name), (typval_T *)&tv, true); } static lval_T *redir_lval = NULL; static garray_T redir_ga; // Only valid when redir_lval is not NULL. static char_u *redir_endp = NULL; static char_u *redir_varname = NULL; /* * Start recording command output to a variable * Returns OK if successfully completed the setup. FAIL otherwise. */ int var_redir_start( char_u *name, int append /* append to an existing variable */ ) { int save_emsg; int err; typval_T tv; /* Catch a bad name early. */ if (!eval_isnamec1(*name)) { EMSG(_(e_invarg)); return FAIL; } /* Make a copy of the name, it is used in redir_lval until redir ends. */ redir_varname = vim_strsave(name); redir_lval = xcalloc(1, sizeof(lval_T)); /* The output is stored in growarray "redir_ga" until redirection ends. */ ga_init(&redir_ga, (int)sizeof(char), 500); // Parse the variable name (can be a dict or list entry). redir_endp = (char_u *)get_lval(redir_varname, NULL, redir_lval, false, false, 0, FNE_CHECK_START); if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL) { clear_lval(redir_lval); if (redir_endp != NULL && *redir_endp != NUL) /* Trailing characters are present after the variable name */ EMSG(_(e_trailing)); else EMSG(_(e_invarg)); redir_endp = NULL; /* don't store a value, only cleanup */ var_redir_stop(); return FAIL; } /* check if we can write to the variable: set it to or append an empty * string */ save_emsg = did_emsg; did_emsg = FALSE; tv.v_type = VAR_STRING; tv.vval.v_string = (char_u *)""; if (append) { set_var_lval(redir_lval, redir_endp, &tv, true, false, (char_u *)"."); } else { set_var_lval(redir_lval, redir_endp, &tv, true, false, (char_u *)"="); } clear_lval(redir_lval); err = did_emsg; did_emsg |= save_emsg; if (err) { redir_endp = NULL; /* don't store a value, only cleanup */ var_redir_stop(); return FAIL; } return OK; } /* * Append "value[value_len]" to the variable set by var_redir_start(). * The actual appending is postponed until redirection ends, because the value * appended may in fact be the string we write to, changing it may cause freed * memory to be used: * :redir => foo * :let foo * :redir END */ void var_redir_str(char_u *value, int value_len) { int len; if (redir_lval == NULL) return; if (value_len == -1) len = (int)STRLEN(value); /* Append the entire string */ else len = value_len; /* Append only "value_len" characters */ ga_grow(&redir_ga, len); memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len); redir_ga.ga_len += len; } /* * Stop redirecting command output to a variable. * Frees the allocated memory. */ void var_redir_stop(void) { typval_T tv; if (redir_lval != NULL) { /* If there was no error: assign the text to the variable. */ if (redir_endp != NULL) { ga_append(&redir_ga, NUL); /* Append the trailing NUL. */ tv.v_type = VAR_STRING; tv.vval.v_string = redir_ga.ga_data; // Call get_lval() again, if it's inside a Dict or List it may // have changed. redir_endp = (char_u *)get_lval(redir_varname, NULL, redir_lval, false, false, 0, FNE_CHECK_START); if (redir_endp != NULL && redir_lval->ll_name != NULL) { set_var_lval(redir_lval, redir_endp, &tv, false, false, (char_u *)"."); } clear_lval(redir_lval); } // free the collected output XFREE_CLEAR(redir_ga.ga_data); XFREE_CLEAR(redir_lval); } XFREE_CLEAR(redir_varname); } int eval_charconvert(const char *const enc_from, const char *const enc_to, const char *const fname_from, const char *const fname_to) { bool err = false; set_vim_var_string(VV_CC_FROM, enc_from, -1); set_vim_var_string(VV_CC_TO, enc_to, -1); set_vim_var_string(VV_FNAME_IN, fname_from, -1); set_vim_var_string(VV_FNAME_OUT, fname_to, -1); if (eval_to_bool(p_ccv, &err, NULL, false)) { err = true; } set_vim_var_string(VV_CC_FROM, NULL, -1); set_vim_var_string(VV_CC_TO, NULL, -1); set_vim_var_string(VV_FNAME_IN, NULL, -1); set_vim_var_string(VV_FNAME_OUT, NULL, -1); if (err) { return FAIL; } return OK; } int eval_printexpr(const char *const fname, const char *const args) { bool err = false; set_vim_var_string(VV_FNAME_IN, fname, -1); set_vim_var_string(VV_CMDARG, args, -1); if (eval_to_bool(p_pexpr, &err, NULL, false)) { err = true; } set_vim_var_string(VV_FNAME_IN, NULL, -1); set_vim_var_string(VV_CMDARG, NULL, -1); if (err) { os_remove(fname); return FAIL; } return OK; } void eval_diff(const char *const origfile, const char *const newfile, const char *const outfile) { bool err = false; set_vim_var_string(VV_FNAME_IN, origfile, -1); set_vim_var_string(VV_FNAME_NEW, newfile, -1); set_vim_var_string(VV_FNAME_OUT, outfile, -1); (void)eval_to_bool(p_dex, &err, NULL, FALSE); set_vim_var_string(VV_FNAME_IN, NULL, -1); set_vim_var_string(VV_FNAME_NEW, NULL, -1); set_vim_var_string(VV_FNAME_OUT, NULL, -1); } void eval_patch(const char *const origfile, const char *const difffile, const char *const outfile) { bool err = false; set_vim_var_string(VV_FNAME_IN, origfile, -1); set_vim_var_string(VV_FNAME_DIFF, difffile, -1); set_vim_var_string(VV_FNAME_OUT, outfile, -1); (void)eval_to_bool(p_pex, &err, NULL, FALSE); set_vim_var_string(VV_FNAME_IN, NULL, -1); set_vim_var_string(VV_FNAME_DIFF, NULL, -1); set_vim_var_string(VV_FNAME_OUT, NULL, -1); } /* * Top level evaluation function, returning a boolean. * Sets "error" to TRUE if there was an error. * Return TRUE or FALSE. */ int eval_to_bool( char_u *arg, bool *error, char_u **nextcmd, int skip /* only parse, don't execute */ ) { typval_T tv; bool retval = false; if (skip) { emsg_skip++; } if (eval0(arg, &tv, nextcmd, !skip) == FAIL) { *error = true; } else { *error = false; if (!skip) { retval = (tv_get_number_chk(&tv, error) != 0); tv_clear(&tv); } } if (skip) { emsg_skip--; } return retval; } // Call eval1() and give an error message if not done at a lower level. static int eval1_emsg(char_u **arg, typval_T *rettv, bool evaluate) FUNC_ATTR_NONNULL_ARG(1, 2) { const char_u *const start = *arg; const int did_emsg_before = did_emsg; const int called_emsg_before = called_emsg; const int ret = eval1(arg, rettv, evaluate); if (ret == FAIL) { // Report the invalid expression unless the expression evaluation has // been cancelled due to an aborting error, an interrupt, or an // exception, or we already gave a more specific error. // Also check called_emsg for when using assert_fails(). if (!aborting() && did_emsg == did_emsg_before && called_emsg == called_emsg_before) { emsgf(_(e_invexpr2), start); } } return ret; } static int eval_expr_typval(const typval_T *expr, typval_T *argv, int argc, typval_T *rettv) FUNC_ATTR_NONNULL_ARG(1, 2, 4) { int dummy; if (expr->v_type == VAR_FUNC) { const char_u *const s = expr->vval.v_string; if (s == NULL || *s == NUL) { return FAIL; } if (call_func(s, (int)STRLEN(s), rettv, argc, argv, NULL, 0L, 0L, &dummy, true, NULL, NULL) == FAIL) { return FAIL; } } else if (expr->v_type == VAR_PARTIAL) { partial_T *const partial = expr->vval.v_partial; const char_u *const s = partial_name(partial); if (s == NULL || *s == NUL) { return FAIL; } if (call_func(s, (int)STRLEN(s), rettv, argc, argv, NULL, 0L, 0L, &dummy, true, partial, NULL) == FAIL) { return FAIL; } } else { char buf[NUMBUFLEN]; char_u *s = (char_u *)tv_get_string_buf_chk(expr, buf); if (s == NULL) { return FAIL; } s = skipwhite(s); if (eval1_emsg(&s, rettv, true) == FAIL) { return FAIL; } if (*s != NUL) { // check for trailing chars after expr tv_clear(rettv); emsgf(_(e_invexpr2), s); return FAIL; } } return OK; } /// Like eval_to_bool() but using a typval_T instead of a string. /// Works for string, funcref and partial. static bool eval_expr_to_bool(const typval_T *expr, bool *error) FUNC_ATTR_NONNULL_ARG(1, 2) { typval_T argv, rettv; if (eval_expr_typval(expr, &argv, 0, &rettv) == FAIL) { *error = true; return false; } const bool res = (tv_get_number_chk(&rettv, error) != 0); tv_clear(&rettv); return res; } /// Top level evaluation function, returning a string /// /// @param[in] arg String to evaluate. /// @param nextcmd Pointer to the start of the next Ex command. /// @param[in] skip If true, only do parsing to nextcmd without reporting /// errors or actually evaluating anything. /// /// @return [allocated] string result of evaluation or NULL in case of error or /// when skipping. char *eval_to_string_skip(const char *arg, const char **nextcmd, const bool skip) FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_WARN_UNUSED_RESULT { typval_T tv; char *retval; if (skip) { emsg_skip++; } if (eval0((char_u *)arg, &tv, (char_u **)nextcmd, !skip) == FAIL || skip) { retval = NULL; } else { retval = xstrdup(tv_get_string(&tv)); tv_clear(&tv); } if (skip) { emsg_skip--; } return retval; } /* * Skip over an expression at "*pp". * Return FAIL for an error, OK otherwise. */ int skip_expr(char_u **pp) { typval_T rettv; *pp = skipwhite(*pp); return eval1(pp, &rettv, FALSE); } /* * Top level evaluation function, returning a string. * When "convert" is TRUE convert a List into a sequence of lines and convert * a Float to a String. * Return pointer to allocated memory, or NULL for failure. */ char_u *eval_to_string(char_u *arg, char_u **nextcmd, int convert) { typval_T tv; char *retval; garray_T ga; if (eval0(arg, &tv, nextcmd, true) == FAIL) { retval = NULL; } else { if (convert && tv.v_type == VAR_LIST) { ga_init(&ga, (int)sizeof(char), 80); if (tv.vval.v_list != NULL) { tv_list_join(&ga, tv.vval.v_list, "\n"); if (tv_list_len(tv.vval.v_list) > 0) { ga_append(&ga, NL); } } ga_append(&ga, NUL); retval = (char *)ga.ga_data; } else if (convert && tv.v_type == VAR_FLOAT) { char numbuf[NUMBUFLEN]; vim_snprintf(numbuf, NUMBUFLEN, "%g", tv.vval.v_float); retval = xstrdup(numbuf); } else { retval = xstrdup(tv_get_string(&tv)); } tv_clear(&tv); } return (char_u *)retval; } /* * Call eval_to_string() without using current local variables and using * textlock. When "use_sandbox" is TRUE use the sandbox. */ char_u *eval_to_string_safe(char_u *arg, char_u **nextcmd, int use_sandbox) { char_u *retval; void *save_funccalp; save_funccalp = save_funccal(); if (use_sandbox) ++sandbox; ++textlock; retval = eval_to_string(arg, nextcmd, FALSE); if (use_sandbox) --sandbox; --textlock; restore_funccal(save_funccalp); return retval; } /* * Top level evaluation function, returning a number. * Evaluates "expr" silently. * Returns -1 for an error. */ varnumber_T eval_to_number(char_u *expr) { typval_T rettv; varnumber_T retval; char_u *p = skipwhite(expr); ++emsg_off; if (eval1(&p, &rettv, true) == FAIL) { retval = -1; } else { retval = tv_get_number_chk(&rettv, NULL); tv_clear(&rettv); } --emsg_off; return retval; } /* * Prepare v: variable "idx" to be used. * Save the current typeval in "save_tv". * When not used yet add the variable to the v: hashtable. */ static void prepare_vimvar(int idx, typval_T *save_tv) { *save_tv = vimvars[idx].vv_tv; if (vimvars[idx].vv_type == VAR_UNKNOWN) hash_add(&vimvarht, vimvars[idx].vv_di.di_key); } /* * Restore v: variable "idx" to typeval "save_tv". * When no longer defined, remove the variable from the v: hashtable. */ static void restore_vimvar(int idx, typval_T *save_tv) { hashitem_T *hi; vimvars[idx].vv_tv = *save_tv; if (vimvars[idx].vv_type == VAR_UNKNOWN) { hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key); if (HASHITEM_EMPTY(hi)) { internal_error("restore_vimvar()"); } else { hash_remove(&vimvarht, hi); } } } /// If there is a window for "curbuf", make it the current window. static void find_win_for_curbuf(void) { for (wininfo_T *wip = curbuf->b_wininfo; wip != NULL; wip = wip->wi_next) { if (wip->wi_win != NULL) { curwin = wip->wi_win; break; } } } /* * Evaluate an expression to a list with suggestions. * For the "expr:" part of 'spellsuggest'. * Returns NULL when there is an error. */ list_T *eval_spell_expr(char_u *badword, char_u *expr) { typval_T save_val; typval_T rettv; list_T *list = NULL; char_u *p = skipwhite(expr); // Set "v:val" to the bad word. prepare_vimvar(VV_VAL, &save_val); vimvars[VV_VAL].vv_type = VAR_STRING; vimvars[VV_VAL].vv_str = badword; if (p_verbose == 0) ++emsg_off; if (eval1(&p, &rettv, true) == OK) { if (rettv.v_type != VAR_LIST) { tv_clear(&rettv); } else { list = rettv.vval.v_list; } } if (p_verbose == 0) --emsg_off; restore_vimvar(VV_VAL, &save_val); return list; } /// Get spell word from an entry from spellsuggest=expr: /// /// Entry in question is supposed to be a list (to be checked by the caller) /// with two items: a word and a score represented as an unsigned number /// (whether it actually is unsigned is not checked). /// /// Used to get the good word and score from the eval_spell_expr() result. /// /// @param[in] list List to get values from. /// @param[out] ret_word Suggested word. Not initialized if return value is /// -1. /// /// @return -1 in case of error, score otherwise. int get_spellword(list_T *const list, const char **ret_word) { if (tv_list_len(list) != 2) { EMSG(_("E5700: Expression from 'spellsuggest' must yield lists with " "exactly two values")); return -1; } *ret_word = tv_list_find_str(list, 0); if (*ret_word == NULL) { return -1; } return tv_list_find_nr(list, -1, NULL); } // Call some vim script function and return the result in "*rettv". // Uses argv[0] to argv[argc-1] for the function arguments. argv[argc] // should have type VAR_UNKNOWN. // // Return OK or FAIL. int call_vim_function( const char_u *func, int argc, typval_T *argv, typval_T *rettv ) FUNC_ATTR_NONNULL_ALL { int doesrange; int ret; rettv->v_type = VAR_UNKNOWN; // tv_clear() uses this. ret = call_func(func, (int)STRLEN(func), rettv, argc, argv, NULL, curwin->w_cursor.lnum, curwin->w_cursor.lnum, &doesrange, true, NULL, NULL); if (ret == FAIL) { tv_clear(rettv); } return ret; } /// Call Vim script function and return the result as a number /// /// @param[in] func Function name. /// @param[in] argc Number of arguments. /// @param[in] argv Array with typval_T arguments. /// /// @return -1 when calling function fails, result of function otherwise. varnumber_T call_func_retnr(const char_u *func, int argc, typval_T *argv) FUNC_ATTR_NONNULL_ALL { typval_T rettv; varnumber_T retval; if (call_vim_function(func, argc, argv, &rettv) == FAIL) { return -1; } retval = tv_get_number_chk(&rettv, NULL); tv_clear(&rettv); return retval; } /// Call Vim script function and return the result as a string /// /// @param[in] func Function name. /// @param[in] argc Number of arguments. /// @param[in] argv Array with typval_T arguments. /// /// @return [allocated] NULL when calling function fails, allocated string /// otherwise. char *call_func_retstr(const char *const func, int argc, typval_T *argv) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC { typval_T rettv; // All arguments are passed as strings, no conversion to number. if (call_vim_function((const char_u *)func, argc, argv, &rettv) == FAIL) { return NULL; } char *const retval = xstrdup(tv_get_string(&rettv)); tv_clear(&rettv); return retval; } /// Call Vim script function and return the result as a List /// /// @param[in] func Function name. /// @param[in] argc Number of arguments. /// @param[in] argv Array with typval_T arguments. /// /// @return [allocated] NULL when calling function fails or return tv is not a /// List, allocated List otherwise. void *call_func_retlist(const char_u *func, int argc, typval_T *argv) FUNC_ATTR_NONNULL_ALL { typval_T rettv; // All arguments are passed as strings, no conversion to number. if (call_vim_function(func, argc, argv, &rettv) == FAIL) { return NULL; } if (rettv.v_type != VAR_LIST) { tv_clear(&rettv); return NULL; } return rettv.vval.v_list; } /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void *save_funccal(void) { funccall_T *fc = current_funccal; current_funccal = NULL; return (void *)fc; } void restore_funccal(void *vfc) { funccall_T *fc = (funccall_T *)vfc; current_funccal = fc; } /* * Prepare profiling for entering a child or something else that is not * counted for the script/function itself. * Should always be called in pair with prof_child_exit(). */ void prof_child_enter(proftime_T *tm /* place to store waittime */ ) { funccall_T *fc = current_funccal; if (fc != NULL && fc->func->uf_profiling) { fc->prof_child = profile_start(); } script_prof_save(tm); } /* * Take care of time spent in a child. * Should always be called after prof_child_enter(). */ void prof_child_exit(proftime_T *tm /* where waittime was stored */ ) { funccall_T *fc = current_funccal; if (fc != NULL && fc->func->uf_profiling) { fc->prof_child = profile_end(fc->prof_child); // don't count waiting time fc->prof_child = profile_sub_wait(*tm, fc->prof_child); fc->func->uf_tm_children = profile_add(fc->func->uf_tm_children, fc->prof_child); fc->func->uf_tml_children = profile_add(fc->func->uf_tml_children, fc->prof_child); } script_prof_restore(tm); } /* * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding * it in "*cp". Doesn't give error messages. */ int eval_foldexpr(char_u *arg, int *cp) { typval_T tv; varnumber_T retval; char_u *s; int use_sandbox = was_set_insecurely((char_u *)"foldexpr", OPT_LOCAL); ++emsg_off; if (use_sandbox) ++sandbox; ++textlock; *cp = NUL; if (eval0(arg, &tv, NULL, TRUE) == FAIL) retval = 0; else { /* If the result is a number, just return the number. */ if (tv.v_type == VAR_NUMBER) retval = tv.vval.v_number; else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL) retval = 0; else { /* If the result is a string, check if there is a non-digit before * the number. */ s = tv.vval.v_string; if (!ascii_isdigit(*s) && *s != '-') *cp = *s++; retval = atol((char *)s); } tv_clear(&tv); } --emsg_off; if (use_sandbox) --sandbox; --textlock; return (int)retval; } // ":cons[t] var = expr1" define constant // ":cons[t] [name1, name2, ...] = expr1" define constants unpacking list // ":cons[t] [name, ..., ; lastname] = expr" define constants unpacking list void ex_const(exarg_T *eap) { ex_let_const(eap, true); } // ":let" list all variable values // ":let var1 var2" list variable values // ":let var = expr" assignment command. // ":let var += expr" assignment command. // ":let var -= expr" assignment command. // ":let var *= expr" assignment command. // ":let var /= expr" assignment command. // ":let var %= expr" assignment command. // ":let var .= expr" assignment command. // ":let var ..= expr" assignment command. // ":let [var1, var2] = expr" unpack list. // ":let [name, ..., ; lastname] = expr" unpack list. void ex_let(exarg_T *eap) { ex_let_const(eap, false); } static void ex_let_const(exarg_T *eap, const bool is_const) { char_u *arg = eap->arg; char_u *expr = NULL; typval_T rettv; int i; int var_count = 0; int semicolon = 0; char_u op[2]; char_u *argend; int first = TRUE; argend = (char_u *)skip_var_list(arg, &var_count, &semicolon); if (argend == NULL) { return; } if (argend > arg && argend[-1] == '.') { // For var.='str'. argend--; } expr = skipwhite(argend); if (*expr != '=' && !((vim_strchr((char_u *)"+-*/%.", *expr) != NULL && expr[1] == '=') || STRNCMP(expr, "..=", 3) == 0)) { // ":let" without "=": list variables if (*arg == '[') { EMSG(_(e_invarg)); } else if (!ends_excmd(*arg)) { // ":let var1 var2" arg = (char_u *)list_arg_vars(eap, (const char *)arg, &first); } else if (!eap->skip) { // ":let" list_glob_vars(&first); list_buf_vars(&first); list_win_vars(&first); list_tab_vars(&first); list_script_vars(&first); list_func_vars(&first); list_vim_vars(&first); } eap->nextcmd = check_nextcmd(arg); } else { op[0] = '='; op[1] = NUL; if (*expr != '=') { if (vim_strchr((char_u *)"+-*/%.", *expr) != NULL) { op[0] = *expr; // +=, -=, *=, /=, %= or .= if (expr[0] == '.' && expr[1] == '.') { // ..= expr++; } } expr = skipwhite(expr + 2); } else { expr = skipwhite(expr + 1); } if (eap->skip) ++emsg_skip; i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip); if (eap->skip) { if (i != FAIL) { tv_clear(&rettv); } emsg_skip--; } else if (i != FAIL) { (void)ex_let_vars(eap->arg, &rettv, false, semicolon, var_count, is_const, op); tv_clear(&rettv); } } } /* * Assign the typevalue "tv" to the variable or variables at "arg_start". * Handles both "var" with any type and "[var, var; var]" with a list type. * When "nextchars" is not NULL it points to a string with characters that * must appear after the variable(s). Use "+", "-" or "." for add, subtract * or concatenate. * Returns OK or FAIL; */ static int ex_let_vars( char_u *arg_start, typval_T *tv, int copy, // copy values from "tv", don't move int semicolon, // from skip_var_list() int var_count, // from skip_var_list() int is_const, // lock variables for :const char_u *nextchars ) { char_u *arg = arg_start; typval_T ltv; if (*arg != '[') { /* * ":let var = expr" or ":for var in list" */ if (ex_let_one(arg, tv, copy, is_const, nextchars, nextchars) == NULL) { return FAIL; } return OK; } // ":let [v1, v2] = list" or ":for [v1, v2] in listlist" if (tv->v_type != VAR_LIST) { EMSG(_(e_listreq)); return FAIL; } list_T *const l = tv->vval.v_list; const int len = tv_list_len(l); if (semicolon == 0 && var_count < len) { EMSG(_("E687: Less targets than List items")); return FAIL; } if (var_count - semicolon > len) { EMSG(_("E688: More targets than List items")); return FAIL; } // List l may actually be NULL, but it should fail with E688 or even earlier // if you try to do ":let [] = v:_null_list". assert(l != NULL); listitem_T *item = tv_list_first(l); size_t rest_len = tv_list_len(l); while (*arg != ']') { arg = skipwhite(arg + 1); arg = ex_let_one(arg, TV_LIST_ITEM_TV(item), true, is_const, (const char_u *)",;]", nextchars); if (arg == NULL) { return FAIL; } rest_len--; item = TV_LIST_ITEM_NEXT(l, item); arg = skipwhite(arg); if (*arg == ';') { /* Put the rest of the list (may be empty) in the var after ';'. * Create a new list for this. */ list_T *const rest_list = tv_list_alloc(rest_len); while (item != NULL) { tv_list_append_tv(rest_list, TV_LIST_ITEM_TV(item)); item = TV_LIST_ITEM_NEXT(l, item); } ltv.v_type = VAR_LIST; ltv.v_lock = VAR_UNLOCKED; ltv.vval.v_list = rest_list; tv_list_ref(rest_list); arg = ex_let_one(skipwhite(arg + 1), <v, false, is_const, (char_u *)"]", nextchars); tv_clear(<v); if (arg == NULL) { return FAIL; } break; } else if (*arg != ',' && *arg != ']') { internal_error("ex_let_vars()"); return FAIL; } } return OK; } /* * Skip over assignable variable "var" or list of variables "[var, var]". * Used for ":let varvar = expr" and ":for varvar in expr". * For "[var, var]" increment "*var_count" for each variable. * for "[var, var; var]" set "semicolon". * Return NULL for an error. */ static const char_u *skip_var_list(const char_u *arg, int *var_count, int *semicolon) { const char_u *p; const char_u *s; if (*arg == '[') { /* "[var, var]": find the matching ']'. */ p = arg; for (;; ) { p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */ s = skip_var_one(p); if (s == p) { EMSG2(_(e_invarg2), p); return NULL; } ++*var_count; p = skipwhite(s); if (*p == ']') break; else if (*p == ';') { if (*semicolon == 1) { EMSG(_("Double ; in list of variables")); return NULL; } *semicolon = 1; } else if (*p != ',') { EMSG2(_(e_invarg2), p); return NULL; } } return p + 1; } else return skip_var_one(arg); } /* * Skip one (assignable) variable name, including @r, $VAR, &option, d.key, * l[idx]. */ static const char_u *skip_var_one(const char_u *arg) { if (*arg == '@' && arg[1] != NUL) return arg + 2; return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START); } /* * List variables for hashtab "ht" with prefix "prefix". * If "empty" is TRUE also list NULL strings as empty strings. */ static void list_hashtable_vars(hashtab_T *ht, const char *prefix, int empty, int *first) { hashitem_T *hi; dictitem_T *di; int todo; todo = (int)ht->ht_used; for (hi = ht->ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { todo--; di = TV_DICT_HI2DI(hi); char buf[IOSIZE]; // apply :filter /pat/ to variable name xstrlcpy(buf, prefix, IOSIZE - 1); xstrlcat(buf, (char *)di->di_key, IOSIZE); if (message_filtered((char_u *)buf)) { continue; } if (empty || di->di_tv.v_type != VAR_STRING || di->di_tv.vval.v_string != NULL) { list_one_var(di, prefix, first); } } } } /* * List global variables. */ static void list_glob_vars(int *first) { list_hashtable_vars(&globvarht, "", true, first); } /* * List buffer variables. */ static void list_buf_vars(int *first) { list_hashtable_vars(&curbuf->b_vars->dv_hashtab, "b:", true, first); } /* * List window variables. */ static void list_win_vars(int *first) { list_hashtable_vars(&curwin->w_vars->dv_hashtab, "w:", true, first); } /* * List tab page variables. */ static void list_tab_vars(int *first) { list_hashtable_vars(&curtab->tp_vars->dv_hashtab, "t:", true, first); } /* * List Vim variables. */ static void list_vim_vars(int *first) { list_hashtable_vars(&vimvarht, "v:", false, first); } // List script-local variables, if there is a script. static void list_script_vars(int *first) { if (current_sctx.sc_sid > 0 && current_sctx.sc_sid <= ga_scripts.ga_len) { list_hashtable_vars(&SCRIPT_VARS(current_sctx.sc_sid), "s:", false, first); } } /* * List function variables, if there is a function. */ static void list_func_vars(int *first) { if (current_funccal != NULL) { list_hashtable_vars(¤t_funccal->l_vars.dv_hashtab, "l:", false, first); } } /* * List variables in "arg". */ static const char *list_arg_vars(exarg_T *eap, const char *arg, int *first) { int error = FALSE; int len; const char *name; const char *name_start; typval_T tv; while (!ends_excmd(*arg) && !got_int) { if (error || eap->skip) { arg = (const char *)find_name_end((char_u *)arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START); if (!ascii_iswhite(*arg) && !ends_excmd(*arg)) { emsg_severe = TRUE; EMSG(_(e_trailing)); break; } } else { // get_name_len() takes care of expanding curly braces name_start = name = arg; char *tofree; len = get_name_len(&arg, &tofree, true, true); if (len <= 0) { /* This is mainly to keep test 49 working: when expanding * curly braces fails overrule the exception error message. */ if (len < 0 && !aborting()) { emsg_severe = TRUE; EMSG2(_(e_invarg2), arg); break; } error = TRUE; } else { if (tofree != NULL) { name = tofree; } if (get_var_tv((const char *)name, len, &tv, NULL, true, false) == FAIL) { error = true; } else { // handle d.key, l[idx], f(expr) const char *const arg_subsc = arg; if (handle_subscript(&arg, &tv, true, true) == FAIL) { error = true; } else { if (arg == arg_subsc && len == 2 && name[1] == ':') { switch (*name) { case 'g': list_glob_vars(first); break; case 'b': list_buf_vars(first); break; case 'w': list_win_vars(first); break; case 't': list_tab_vars(first); break; case 'v': list_vim_vars(first); break; case 's': list_script_vars(first); break; case 'l': list_func_vars(first); break; default: EMSG2(_("E738: Can't list variables for %s"), name); } } else { char *const s = encode_tv2echo(&tv, NULL); const char *const used_name = (arg == arg_subsc ? name : name_start); const ptrdiff_t name_size = (used_name == tofree ? (ptrdiff_t)strlen(used_name) : (arg - used_name)); list_one_var_a("", used_name, name_size, tv.v_type, s == NULL ? "" : s, first); xfree(s); } tv_clear(&tv); } } } xfree(tofree); } arg = (const char *)skipwhite((const char_u *)arg); } return arg; } // TODO(ZyX-I): move to eval/ex_cmds /// Set one item of `:let var = expr` or `:let [v1, v2] = list` to its value /// /// @param[in] arg Start of the variable name. /// @param[in] tv Value to assign to the variable. /// @param[in] copy If true, copy value from `tv`. /// @param[in] endchars Valid characters after variable name or NULL. /// @param[in] op Operation performed: *op is `+`, `-`, `.` for `+=`, etc. /// NULL for `=`. /// /// @return a pointer to the char just after the var name or NULL in case of /// error. static char_u *ex_let_one(char_u *arg, typval_T *const tv, const bool copy, const bool is_const, const char_u *const endchars, const char_u *const op) FUNC_ATTR_NONNULL_ARG(1, 2) FUNC_ATTR_WARN_UNUSED_RESULT { char_u *arg_end = NULL; int len; int opt_flags; char_u *tofree = NULL; /* * ":let $VAR = expr": Set environment variable. */ if (*arg == '$') { if (is_const) { EMSG(_("E996: Cannot lock an environment variable")); return NULL; } // Find the end of the name. arg++; char *name = (char *)arg; len = get_env_len((const char_u **)&arg); if (len == 0) { EMSG2(_(e_invarg2), name - 1); } else { if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL) { EMSG2(_(e_letwrong), op); } else if (endchars != NULL && vim_strchr(endchars, *skipwhite(arg)) == NULL) { EMSG(_(e_letunexp)); } else if (!check_secure()) { const char c1 = name[len]; name[len] = NUL; const char *p = tv_get_string_chk(tv); if (p != NULL && op != NULL && *op == '.') { char *s = vim_getenv(name); if (s != NULL) { tofree = concat_str((const char_u *)s, (const char_u *)p); p = (const char *)tofree; xfree(s); } } if (p != NULL) { os_setenv(name, p, 1); if (STRICMP(name, "HOME") == 0) { init_homedir(); } else if (didset_vim && STRICMP(name, "VIM") == 0) { didset_vim = false; } else if (didset_vimruntime && STRICMP(name, "VIMRUNTIME") == 0) { didset_vimruntime = false; } arg_end = arg; } name[len] = c1; xfree(tofree); } } // ":let &option = expr": Set option value. // ":let &l:option = expr": Set local option value. // ":let &g:option = expr": Set global option value. } else if (*arg == '&') { if (is_const) { EMSG(_("E996: Cannot lock an option")); return NULL; } // Find the end of the name. char *const p = (char *)find_option_end((const char **)&arg, &opt_flags); if (p == NULL || (endchars != NULL && vim_strchr(endchars, *skipwhite((const char_u *)p)) == NULL)) { EMSG(_(e_letunexp)); } else { int opt_type; long numval; char *stringval = NULL; const char c1 = *p; *p = NUL; varnumber_T n = tv_get_number(tv); const char *s = tv_get_string_chk(tv); // != NULL if number or string. if (s != NULL && op != NULL && *op != '=') { opt_type = get_option_value(arg, &numval, (char_u **)&stringval, opt_flags); if ((opt_type == 1 && *op == '.') || (opt_type == 0 && *op != '.')) { EMSG2(_(e_letwrong), op); s = NULL; // don't set the value } else { if (opt_type == 1) { // number switch (*op) { case '+': n = numval + n; break; case '-': n = numval - n; break; case '*': n = numval * n; break; case '/': n = num_divide(numval, n); break; case '%': n = num_modulus(numval, n); break; } } else if (opt_type == 0 && stringval != NULL) { // string char *const oldstringval = stringval; stringval = (char *)concat_str((const char_u *)stringval, (const char_u *)s); xfree(oldstringval); s = stringval; } } } if (s != NULL) { set_option_value((const char *)arg, n, s, opt_flags); arg_end = (char_u *)p; } *p = c1; xfree(stringval); } // ":let @r = expr": Set register contents. } else if (*arg == '@') { if (is_const) { EMSG(_("E996: Cannot lock a register")); return NULL; } arg++; if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL) { emsgf(_(e_letwrong), op); } else if (endchars != NULL && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL) { EMSG(_(e_letunexp)); } else { char_u *s; char_u *ptofree = NULL; const char *p = tv_get_string_chk(tv); if (p != NULL && op != NULL && *op == '.') { s = get_reg_contents(*arg == '@' ? '"' : *arg, kGRegExprSrc); if (s != NULL) { ptofree = concat_str(s, (const char_u *)p); p = (const char *)ptofree; xfree(s); } } if (p != NULL) { write_reg_contents(*arg == '@' ? '"' : *arg, (const char_u *)p, STRLEN(p), false); arg_end = arg + 1; } xfree(ptofree); } } /* * ":let var = expr": Set internal variable. * ":let {expr} = expr": Idem, name made with curly braces */ else if (eval_isnamec1(*arg) || *arg == '{') { lval_T lv; char_u *const p = get_lval(arg, tv, &lv, false, false, 0, FNE_CHECK_START); if (p != NULL && lv.ll_name != NULL) { if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL) { EMSG(_(e_letunexp)); } else { set_var_lval(&lv, p, tv, copy, is_const, op); arg_end = p; } } clear_lval(&lv); } else EMSG2(_(e_invarg2), arg); return arg_end; } // TODO(ZyX-I): move to eval/executor /// Get an lvalue /// /// Lvalue may be /// - variable: "name", "na{me}" /// - dictionary item: "dict.key", "dict['key']" /// - list item: "list[expr]" /// - list slice: "list[expr:expr]" /// /// Indexing only works if trying to use it with an existing List or Dictionary. /// /// @param[in] name Name to parse. /// @param rettv Pointer to the value to be assigned or NULL. /// @param[out] lp Lvalue definition. When evaluation errors occur `->ll_name` /// is NULL. /// @param[in] unlet True if using `:unlet`. This results in slightly /// different behaviour when something is wrong; must end in /// space or cmd separator. /// @param[in] skip True when skipping. /// @param[in] flags @see GetLvalFlags. /// @param[in] fne_flags Flags for find_name_end(). /// /// @return A pointer to just after the name, including indexes. Returns NULL /// for a parsing error, but it is still needed to free items in lp. static char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, const bool unlet, const bool skip, const int flags, const int fne_flags) FUNC_ATTR_NONNULL_ARG(1, 3) { dictitem_T *v; typval_T var1; typval_T var2; int empty1 = FALSE; listitem_T *ni; hashtab_T *ht; int quiet = flags & GLV_QUIET; /* Clear everything in "lp". */ memset(lp, 0, sizeof(lval_T)); if (skip) { // When skipping just find the end of the name. lp->ll_name = (const char *)name; return (char_u *)find_name_end((const char_u *)name, NULL, NULL, FNE_INCL_BR | fne_flags); } // Find the end of the name. char_u *expr_start; char_u *expr_end; char_u *p = (char_u *)find_name_end(name, (const char_u **)&expr_start, (const char_u **)&expr_end, fne_flags); if (expr_start != NULL) { /* Don't expand the name when we already know there is an error. */ if (unlet && !ascii_iswhite(*p) && !ends_excmd(*p) && *p != '[' && *p != '.') { EMSG(_(e_trailing)); return NULL; } lp->ll_exp_name = (char *)make_expanded_name(name, expr_start, expr_end, (char_u *)p); lp->ll_name = lp->ll_exp_name; if (lp->ll_exp_name == NULL) { /* Report an invalid expression in braces, unless the * expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting() && !quiet) { emsg_severe = TRUE; EMSG2(_(e_invarg2), name); return NULL; } lp->ll_name_len = 0; } else { lp->ll_name_len = strlen(lp->ll_name); } } else { lp->ll_name = (const char *)name; lp->ll_name_len = (size_t)((const char *)p - lp->ll_name); } // Without [idx] or .key we are done. if ((*p != '[' && *p != '.') || lp->ll_name == NULL) { return p; } // Only pass &ht when we would write to the variable, it prevents autoload // as well. v = find_var(lp->ll_name, lp->ll_name_len, (flags & GLV_READ_ONLY) ? NULL : &ht, flags & GLV_NO_AUTOLOAD); if (v == NULL && !quiet) { emsgf(_("E121: Undefined variable: %.*s"), (int)lp->ll_name_len, lp->ll_name); } if (v == NULL) { return NULL; } /* * Loop until no more [idx] or .key is following. */ lp->ll_tv = &v->di_tv; var1.v_type = VAR_UNKNOWN; var2.v_type = VAR_UNKNOWN; while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT)) { if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL) && !(lp->ll_tv->v_type == VAR_DICT && lp->ll_tv->vval.v_dict != NULL)) { if (!quiet) EMSG(_("E689: Can only index a List or Dictionary")); return NULL; } if (lp->ll_range) { if (!quiet) EMSG(_("E708: [:] must come last")); return NULL; } int len = -1; char_u *key = NULL; if (*p == '.') { key = p + 1; for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; len++) { } if (len == 0) { if (!quiet) { EMSG(_("E713: Cannot use empty key after .")); } return NULL; } p = key + len; } else { /* Get the index [expr] or the first index [expr: ]. */ p = skipwhite(p + 1); if (*p == ':') { empty1 = true; } else { empty1 = false; if (eval1(&p, &var1, true) == FAIL) { // Recursive! return NULL; } if (!tv_check_str(&var1)) { // Not a number or string. tv_clear(&var1); return NULL; } } /* Optionally get the second index [ :expr]. */ if (*p == ':') { if (lp->ll_tv->v_type == VAR_DICT) { if (!quiet) { EMSG(_(e_dictrange)); } tv_clear(&var1); return NULL; } if (rettv != NULL && (rettv->v_type != VAR_LIST || rettv->vval.v_list == NULL)) { if (!quiet) { EMSG(_("E709: [:] requires a List value")); } tv_clear(&var1); return NULL; } p = skipwhite(p + 1); if (*p == ']') { lp->ll_empty2 = true; } else { lp->ll_empty2 = false; if (eval1(&p, &var2, true) == FAIL) { // Recursive! tv_clear(&var1); return NULL; } if (!tv_check_str(&var2)) { // Not a number or string. tv_clear(&var1); tv_clear(&var2); return NULL; } } lp->ll_range = TRUE; } else lp->ll_range = FALSE; if (*p != ']') { if (!quiet) { EMSG(_(e_missbrac)); } tv_clear(&var1); tv_clear(&var2); return NULL; } /* Skip to past ']'. */ ++p; } if (lp->ll_tv->v_type == VAR_DICT) { if (len == -1) { // "[key]": get key from "var1" key = (char_u *)tv_get_string(&var1); // is number or string } lp->ll_list = NULL; lp->ll_dict = lp->ll_tv->vval.v_dict; lp->ll_di = tv_dict_find(lp->ll_dict, (const char *)key, len); /* When assigning to a scope dictionary check that a function and * variable name is valid (only variable name unless it is l: or * g: dictionary). Disallow overwriting a builtin function. */ if (rettv != NULL && lp->ll_dict->dv_scope != 0) { int prevval; int wrong; if (len != -1) { prevval = key[len]; key[len] = NUL; } else { prevval = 0; // Avoid compiler warning. } wrong = ((lp->ll_dict->dv_scope == VAR_DEF_SCOPE && tv_is_func(*rettv) && !var_check_func_name((const char *)key, lp->ll_di == NULL)) || !valid_varname((const char *)key)); if (len != -1) { key[len] = prevval; } if (wrong) { return NULL; } } if (lp->ll_di == NULL) { // Can't add "v:" or "a:" variable. if (lp->ll_dict == &vimvardict || &lp->ll_dict->dv_hashtab == get_funccal_args_ht()) { EMSG2(_(e_illvar), name); tv_clear(&var1); return NULL; } // Key does not exist in dict: may need to add it. if (*p == '[' || *p == '.' || unlet) { if (!quiet) { emsgf(_(e_dictkey), key); } tv_clear(&var1); return NULL; } if (len == -1) { lp->ll_newkey = vim_strsave(key); } else { lp->ll_newkey = vim_strnsave(key, len); } tv_clear(&var1); break; // existing variable, need to check if it can be changed } else if (!(flags & GLV_READ_ONLY) && var_check_ro(lp->ll_di->di_flags, (const char *)name, (size_t)(p - name))) { tv_clear(&var1); return NULL; } tv_clear(&var1); lp->ll_tv = &lp->ll_di->di_tv; } else { // Get the number and item for the only or first index of the List. if (empty1) { lp->ll_n1 = 0; } else { // Is number or string. lp->ll_n1 = (long)tv_get_number(&var1); } tv_clear(&var1); lp->ll_dict = NULL; lp->ll_list = lp->ll_tv->vval.v_list; lp->ll_li = tv_list_find(lp->ll_list, lp->ll_n1); if (lp->ll_li == NULL) { if (lp->ll_n1 < 0) { lp->ll_n1 = 0; lp->ll_li = tv_list_find(lp->ll_list, lp->ll_n1); } } if (lp->ll_li == NULL) { tv_clear(&var2); if (!quiet) { EMSGN(_(e_listidx), lp->ll_n1); } return NULL; } /* * May need to find the item or absolute index for the second * index of a range. * When no index given: "lp->ll_empty2" is TRUE. * Otherwise "lp->ll_n2" is set to the second index. */ if (lp->ll_range && !lp->ll_empty2) { lp->ll_n2 = (long)tv_get_number(&var2); // Is number or string. tv_clear(&var2); if (lp->ll_n2 < 0) { ni = tv_list_find(lp->ll_list, lp->ll_n2); if (ni == NULL) { if (!quiet) EMSGN(_(e_listidx), lp->ll_n2); return NULL; } lp->ll_n2 = tv_list_idx_of_item(lp->ll_list, ni); } // Check that lp->ll_n2 isn't before lp->ll_n1. if (lp->ll_n1 < 0) { lp->ll_n1 = tv_list_idx_of_item(lp->ll_list, lp->ll_li); } if (lp->ll_n2 < lp->ll_n1) { if (!quiet) { EMSGN(_(e_listidx), lp->ll_n2); } return NULL; } } lp->ll_tv = TV_LIST_ITEM_TV(lp->ll_li); } } tv_clear(&var1); return p; } // TODO(ZyX-I): move to eval/executor /* * Clear lval "lp" that was filled by get_lval(). */ static void clear_lval(lval_T *lp) { xfree(lp->ll_exp_name); xfree(lp->ll_newkey); } // TODO(ZyX-I): move to eval/executor /* * Set a variable that was parsed by get_lval() to "rettv". * "endp" points to just after the parsed name. * "op" is NULL, "+" for "+=", "-" for "-=", "*" for "*=", "/" for "/=", * "%" for "%=", "." for ".=" or "=" for "=". */ static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv, int copy, const bool is_const, const char_u *op) { int cc; listitem_T *ri; dictitem_T *di; if (lp->ll_tv == NULL) { cc = *endp; *endp = NUL; if (op != NULL && *op != '=') { typval_T tv; if (is_const) { EMSG(_(e_cannot_mod)); *endp = cc; return; } // handle +=, -=, *=, /=, %= and .= di = NULL; if (get_var_tv((const char *)lp->ll_name, (int)STRLEN(lp->ll_name), &tv, &di, true, false) == OK) { if ((di == NULL || (!var_check_ro(di->di_flags, (const char *)lp->ll_name, TV_CSTRING) && !tv_check_lock(di->di_tv.v_lock, (const char *)lp->ll_name, TV_CSTRING))) && eexe_mod_op(&tv, rettv, (const char *)op) == OK) { set_var(lp->ll_name, lp->ll_name_len, &tv, false); } tv_clear(&tv); } } else { set_var_const(lp->ll_name, lp->ll_name_len, rettv, copy, is_const); } *endp = cc; } else if (tv_check_lock(lp->ll_newkey == NULL ? lp->ll_tv->v_lock : lp->ll_tv->vval.v_dict->dv_lock, (const char *)lp->ll_name, TV_CSTRING)) { } else if (lp->ll_range) { listitem_T *ll_li = lp->ll_li; int ll_n1 = lp->ll_n1; if (is_const) { EMSG(_("E996: Cannot lock a range")); return; } // Check whether any of the list items is locked for (ri = tv_list_first(rettv->vval.v_list); ri != NULL && ll_li != NULL; ) { if (tv_check_lock(TV_LIST_ITEM_TV(ll_li)->v_lock, (const char *)lp->ll_name, TV_CSTRING)) { return; } ri = TV_LIST_ITEM_NEXT(rettv->vval.v_list, ri); if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == ll_n1)) { break; } ll_li = TV_LIST_ITEM_NEXT(lp->ll_list, ll_li); ll_n1++; } /* * Assign the List values to the list items. */ for (ri = tv_list_first(rettv->vval.v_list); ri != NULL; ) { if (op != NULL && *op != '=') { eexe_mod_op(TV_LIST_ITEM_TV(lp->ll_li), TV_LIST_ITEM_TV(ri), (const char *)op); } else { tv_clear(TV_LIST_ITEM_TV(lp->ll_li)); tv_copy(TV_LIST_ITEM_TV(ri), TV_LIST_ITEM_TV(lp->ll_li)); } ri = TV_LIST_ITEM_NEXT(rettv->vval.v_list, ri); if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1)) { break; } assert(lp->ll_li != NULL); if (TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li) == NULL) { // Need to add an empty item. tv_list_append_number(lp->ll_list, 0); // ll_li may have become invalid after append, don’t use it. lp->ll_li = tv_list_last(lp->ll_list); // Valid again. } else { lp->ll_li = TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li); } lp->ll_n1++; } if (ri != NULL) { EMSG(_("E710: List value has more items than target")); } else if (lp->ll_empty2 ? (lp->ll_li != NULL && TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li) != NULL) : lp->ll_n1 != lp->ll_n2) { EMSG(_("E711: List value has not enough items")); } } else { typval_T oldtv = TV_INITIAL_VALUE; dict_T *dict = lp->ll_dict; bool watched = tv_dict_is_watched(dict); if (is_const) { EMSG(_("E996: Cannot lock a list or dict")); return; } // Assign to a List or Dictionary item. if (lp->ll_newkey != NULL) { if (op != NULL && *op != '=') { EMSG2(_(e_letwrong), op); return; } // Need to add an item to the Dictionary. di = tv_dict_item_alloc((const char *)lp->ll_newkey); if (tv_dict_add(lp->ll_tv->vval.v_dict, di) == FAIL) { xfree(di); return; } lp->ll_tv = &di->di_tv; } else { if (watched) { tv_copy(lp->ll_tv, &oldtv); } if (op != NULL && *op != '=') { eexe_mod_op(lp->ll_tv, rettv, (const char *)op); goto notify; } else { tv_clear(lp->ll_tv); } } // Assign the value to the variable or list item. if (copy) { tv_copy(rettv, lp->ll_tv); } else { *lp->ll_tv = *rettv; lp->ll_tv->v_lock = 0; tv_init(rettv); } notify: if (watched) { if (oldtv.v_type == VAR_UNKNOWN) { assert(lp->ll_newkey != NULL); tv_dict_watcher_notify(dict, (char *)lp->ll_newkey, lp->ll_tv, NULL); } else { dictitem_T *di_ = lp->ll_di; assert(di_->di_key != NULL); tv_dict_watcher_notify(dict, (char *)di_->di_key, lp->ll_tv, &oldtv); tv_clear(&oldtv); } } } } // TODO(ZyX-I): move to eval/ex_cmds /* * Evaluate the expression used in a ":for var in expr" command. * "arg" points to "var". * Set "*errp" to TRUE for an error, FALSE otherwise; * Return a pointer that holds the info. Null when there is an error. */ void *eval_for_line(const char_u *arg, bool *errp, char_u **nextcmdp, int skip) { forinfo_T *fi = xcalloc(1, sizeof(forinfo_T)); const char_u *expr; typval_T tv; list_T *l; *errp = true; // Default: there is an error. expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon); if (expr == NULL) return fi; expr = skipwhite(expr); if (expr[0] != 'i' || expr[1] != 'n' || !ascii_iswhite(expr[2])) { EMSG(_("E690: Missing \"in\" after :for")); return fi; } if (skip) ++emsg_skip; if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK) { *errp = false; if (!skip) { l = tv.vval.v_list; if (tv.v_type != VAR_LIST) { EMSG(_(e_listreq)); tv_clear(&tv); } else if (l == NULL) { // a null list is like an empty list: do nothing tv_clear(&tv); } else { /* No need to increment the refcount, it's already set for the * list being used in "tv". */ fi->fi_list = l; tv_list_watch_add(l, &fi->fi_lw); fi->fi_lw.lw_item = tv_list_first(l); } } } if (skip) --emsg_skip; return fi; } // TODO(ZyX-I): move to eval/ex_cmds /* * Use the first item in a ":for" list. Advance to the next. * Assign the values to the variable (list). "arg" points to the first one. * Return TRUE when a valid item was found, FALSE when at end of list or * something wrong. */ bool next_for_item(void *fi_void, char_u *arg) { forinfo_T *fi = (forinfo_T *)fi_void; listitem_T *item = fi->fi_lw.lw_item; if (item == NULL) { return false; } else { fi->fi_lw.lw_item = TV_LIST_ITEM_NEXT(fi->fi_list, item); return (ex_let_vars(arg, TV_LIST_ITEM_TV(item), true, fi->fi_semicolon, fi->fi_varcount, false, NULL) == OK); } } // TODO(ZyX-I): move to eval/ex_cmds /* * Free the structure used to store info used by ":for". */ void free_for_info(void *fi_void) { forinfo_T *fi = (forinfo_T *)fi_void; if (fi != NULL && fi->fi_list != NULL) { tv_list_watch_remove(fi->fi_list, &fi->fi_lw); tv_list_unref(fi->fi_list); } xfree(fi); } void set_context_for_expression(expand_T *xp, char_u *arg, cmdidx_T cmdidx) { int got_eq = FALSE; int c; char_u *p; if (cmdidx == CMD_let) { xp->xp_context = EXPAND_USER_VARS; if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL) { /* ":let var1 var2 ...": find last space. */ for (p = arg + STRLEN(arg); p >= arg; ) { xp->xp_pattern = p; MB_PTR_BACK(arg, p); if (ascii_iswhite(*p)) { break; } } return; } } else xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS : EXPAND_EXPRESSION; while ((xp->xp_pattern = vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL) { c = *xp->xp_pattern; if (c == '&') { c = xp->xp_pattern[1]; if (c == '&') { ++xp->xp_pattern; xp->xp_context = cmdidx != CMD_let || got_eq ? EXPAND_EXPRESSION : EXPAND_NOTHING; } else if (c != ' ') { xp->xp_context = EXPAND_SETTINGS; if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':') xp->xp_pattern += 2; } } else if (c == '$') { /* environment variable */ xp->xp_context = EXPAND_ENV_VARS; } else if (c == '=') { got_eq = TRUE; xp->xp_context = EXPAND_EXPRESSION; } else if (c == '#' && xp->xp_context == EXPAND_EXPRESSION) { // Autoload function/variable contains '#' break; } else if ((c == '<' || c == '#') && xp->xp_context == EXPAND_FUNCTIONS && vim_strchr(xp->xp_pattern, '(') == NULL) { /* Function name can start with "" and contain '#'. */ break; } else if (cmdidx != CMD_let || got_eq) { if (c == '"') { /* string */ while ((c = *++xp->xp_pattern) != NUL && c != '"') if (c == '\\' && xp->xp_pattern[1] != NUL) ++xp->xp_pattern; xp->xp_context = EXPAND_NOTHING; } else if (c == '\'') { /* literal string */ /* Trick: '' is like stopping and starting a literal string. */ while ((c = *++xp->xp_pattern) != NUL && c != '\'') /* skip */; xp->xp_context = EXPAND_NOTHING; } else if (c == '|') { if (xp->xp_pattern[1] == '|') { ++xp->xp_pattern; xp->xp_context = EXPAND_EXPRESSION; } else xp->xp_context = EXPAND_COMMANDS; } else xp->xp_context = EXPAND_EXPRESSION; } else /* Doesn't look like something valid, expand as an expression * anyway. */ xp->xp_context = EXPAND_EXPRESSION; arg = xp->xp_pattern; if (*arg != NUL) while ((c = *++arg) != NUL && (c == ' ' || c == '\t')) /* skip */; } xp->xp_pattern = arg; } // TODO(ZyX-I): move to eval/ex_cmds /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; bool failed = false; funcdict_T fudi; partial_T *partial = NULL; if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif. emsg_skip++; if (eval0(eap->arg, &rettv, &eap->nextcmd, false) != FAIL) { tv_clear(&rettv); } emsg_skip--; return; } tofree = trans_function_name(&arg, false, TFN_INT, &fudi, &partial); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. EMSG2(_(e_dictkey), fudi.fd_newkey); xfree(fudi.fd_newkey); } if (tofree == NULL) { return; } // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) { fudi.fd_dict->dv_refcount++; } // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name((const char *)tofree, &len, partial != NULL ? NULL : &partial, false); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); rettv.v_type = VAR_UNKNOWN; // tv_clear() uses this. if (*startarg != '(') { EMSG2(_("E107: Missing parentheses: %s"), eap->arg); goto end; } lnum = eap->line1; for (; lnum <= eap->line2; lnum++) { if (eap->addr_count > 0) { // -V560 if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. EMSG(_(e_invrange)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg, eap->line1, eap->line2, &doesrange, true, partial, fudi.fd_dict) == FAIL) { failed = true; break; } // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript((const char **)&arg, &rettv, true, true) == FAIL) { failed = true; break; } tv_clear(&rettv); if (doesrange) { break; } // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) { break; } } if (!failed) { // Check for trailing illegal characters and a following command. if (!ends_excmd(*arg)) { emsg_severe = TRUE; EMSG(_(e_trailing)); } else { eap->nextcmd = check_nextcmd(arg); } } end: tv_dict_unref(fudi.fd_dict); xfree(tofree); } // TODO(ZyX-I): move to eval/ex_cmds /* * ":unlet[!] var1 ... " command. */ void ex_unlet(exarg_T *eap) { ex_unletlock(eap, eap->arg, 0); } // TODO(ZyX-I): move to eval/ex_cmds /* * ":lockvar" and ":unlockvar" commands */ void ex_lockvar(exarg_T *eap) { char_u *arg = eap->arg; int deep = 2; if (eap->forceit) { deep = -1; } else if (ascii_isdigit(*arg)) { deep = getdigits_int(&arg, false, -1); arg = skipwhite(arg); } ex_unletlock(eap, arg, deep); } // TODO(ZyX-I): move to eval/ex_cmds /* * ":unlet", ":lockvar" and ":unlockvar" are quite similar. */ static void ex_unletlock(exarg_T *eap, char_u *argstart, int deep) { char_u *arg = argstart; bool error = false; lval_T lv; do { if (*arg == '$') { const char *name = (char *)++arg; if (get_env_len((const char_u **)&arg) == 0) { EMSG2(_(e_invarg2), name - 1); return; } os_unsetenv(name); arg = skipwhite(arg); continue; } // Parse the name and find the end. char_u *const name_end = (char_u *)get_lval(arg, NULL, &lv, true, eap->skip || error, 0, FNE_CHECK_START); if (lv.ll_name == NULL) { error = true; // error, but continue parsing. } if (name_end == NULL || (!ascii_iswhite(*name_end) && !ends_excmd(*name_end))) { if (name_end != NULL) { emsg_severe = TRUE; EMSG(_(e_trailing)); } if (!(eap->skip || error)) clear_lval(&lv); break; } if (!error && !eap->skip) { if (eap->cmdidx == CMD_unlet) { if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL) error = TRUE; } else { if (do_lock_var(&lv, name_end, deep, eap->cmdidx == CMD_lockvar) == FAIL) { error = true; } } } if (!eap->skip) clear_lval(&lv); arg = skipwhite(name_end); } while (!ends_excmd(*arg)); eap->nextcmd = check_nextcmd(arg); } // TODO(ZyX-I): move to eval/ex_cmds static int do_unlet_var(lval_T *const lp, char_u *const name_end, int forceit) { int ret = OK; int cc; if (lp->ll_tv == NULL) { cc = *name_end; *name_end = NUL; // Normal name or expanded name. if (do_unlet(lp->ll_name, lp->ll_name_len, forceit) == FAIL) { ret = FAIL; } *name_end = cc; } else if ((lp->ll_list != NULL // ll_list is not NULL when lvalue is not in a list, NULL lists // yield E689. && tv_check_lock(tv_list_locked(lp->ll_list), (const char *)lp->ll_name, lp->ll_name_len)) || (lp->ll_dict != NULL && tv_check_lock(lp->ll_dict->dv_lock, (const char *)lp->ll_name, lp->ll_name_len))) { return FAIL; } else if (lp->ll_range) { assert(lp->ll_list != NULL); // Delete a range of List items. listitem_T *const first_li = lp->ll_li; listitem_T *last_li = first_li; for (;;) { listitem_T *const li = TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li); if (tv_check_lock(TV_LIST_ITEM_TV(lp->ll_li)->v_lock, (const char *)lp->ll_name, lp->ll_name_len)) { return false; } lp->ll_li = li; lp->ll_n1++; if (lp->ll_li == NULL || (!lp->ll_empty2 && lp->ll_n2 < lp->ll_n1)) { break; } else { last_li = lp->ll_li; } } tv_list_remove_items(lp->ll_list, first_li, last_li); } else { if (lp->ll_list != NULL) { // unlet a List item. tv_list_item_remove(lp->ll_list, lp->ll_li); } else { // unlet a Dictionary item. dict_T *d = lp->ll_dict; assert(d != NULL); dictitem_T *di = lp->ll_di; bool watched = tv_dict_is_watched(d); char *key = NULL; typval_T oldtv; if (watched) { tv_copy(&di->di_tv, &oldtv); // need to save key because dictitem_remove will free it key = xstrdup((char *)di->di_key); } tv_dict_item_remove(d, di); if (watched) { tv_dict_watcher_notify(d, key, NULL, &oldtv); tv_clear(&oldtv); xfree(key); } } } return ret; } // TODO(ZyX-I): move to eval/ex_cmds /// unlet a variable /// /// @param[in] name Variable name to unlet. /// @param[in] name_len Variable name length. /// @param[in] fonceit If true, do not complain if variable doesn’t exist. /// /// @return OK if it existed, FAIL otherwise. int do_unlet(const char *const name, const size_t name_len, const int forceit) FUNC_ATTR_NONNULL_ALL { const char *varname; dict_T *dict; hashtab_T *ht = find_var_ht_dict(name, name_len, &varname, &dict); if (ht != NULL && *varname != NUL) { dict_T *d; if (ht == &globvarht) { d = &globvardict; } else if (current_funccal != NULL && ht == ¤t_funccal->l_vars.dv_hashtab) { d = ¤t_funccal->l_vars; } else if (ht == &compat_hashtab) { d = &vimvardict; } else { dictitem_T *const di = find_var_in_ht(ht, *name, "", 0, false); d = di->di_tv.vval.v_dict; } if (d == NULL) { internal_error("do_unlet()"); return FAIL; } hashitem_T *hi = hash_find(ht, (const char_u *)varname); if (HASHITEM_EMPTY(hi)) { hi = find_hi_in_scoped_ht((const char *)name, &ht); } if (hi != NULL && !HASHITEM_EMPTY(hi)) { dictitem_T *const di = TV_DICT_HI2DI(hi); if (var_check_fixed(di->di_flags, (const char *)name, TV_CSTRING) || var_check_ro(di->di_flags, (const char *)name, TV_CSTRING) || tv_check_lock(d->dv_lock, (const char *)name, TV_CSTRING)) { return FAIL; } if (tv_check_lock(d->dv_lock, (const char *)name, TV_CSTRING)) { return FAIL; } typval_T oldtv; bool watched = tv_dict_is_watched(dict); if (watched) { tv_copy(&di->di_tv, &oldtv); } delete_var(ht, hi); if (watched) { tv_dict_watcher_notify(dict, varname, NULL, &oldtv); tv_clear(&oldtv); } return OK; } } if (forceit) return OK; EMSG2(_("E108: No such variable: \"%s\""), name); return FAIL; } // TODO(ZyX-I): move to eval/ex_cmds /* * Lock or unlock variable indicated by "lp". * "deep" is the levels to go (-1 for unlimited); * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar". */ static int do_lock_var(lval_T *lp, char_u *const name_end, const int deep, const bool lock) { int ret = OK; if (deep == 0) { // Nothing to do. return OK; } if (lp->ll_tv == NULL) { // Normal name or expanded name. dictitem_T *const di = find_var( (const char *)lp->ll_name, lp->ll_name_len, NULL, true); if (di == NULL) { ret = FAIL; } else if ((di->di_flags & DI_FLAGS_FIX) && di->di_tv.v_type != VAR_DICT && di->di_tv.v_type != VAR_LIST) { // For historical reasons this error is not given for Lists and // Dictionaries. E.g. b: dictionary may be locked/unlocked. emsgf(_("E940: Cannot lock or unlock variable %s"), lp->ll_name); } else { if (lock) { di->di_flags |= DI_FLAGS_LOCK; } else { di->di_flags &= ~DI_FLAGS_LOCK; } tv_item_lock(&di->di_tv, deep, lock); } } else if (lp->ll_range) { listitem_T *li = lp->ll_li; /* (un)lock a range of List items. */ while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1)) { tv_item_lock(TV_LIST_ITEM_TV(li), deep, lock); li = TV_LIST_ITEM_NEXT(lp->ll_list, li); lp->ll_n1++; } } else if (lp->ll_list != NULL) { // (un)lock a List item. tv_item_lock(TV_LIST_ITEM_TV(lp->ll_li), deep, lock); } else { // (un)lock a Dictionary item. tv_item_lock(&lp->ll_di->di_tv, deep, lock); } return ret; } /* * Delete all "menutrans_" variables. */ void del_menutrans_vars(void) { hash_lock(&globvarht); HASHTAB_ITER(&globvarht, hi, { if (STRNCMP(hi->hi_key, "menutrans_", 10) == 0) { delete_var(&globvarht, hi); } }); hash_unlock(&globvarht); } /* * Local string buffer for the next two functions to store a variable name * with its prefix. Allocated in cat_prefix_varname(), freed later in * get_user_var_name(). */ static char_u *varnamebuf = NULL; static size_t varnamebuflen = 0; /* * Function to concatenate a prefix and a variable name. */ static char_u *cat_prefix_varname(int prefix, char_u *name) { size_t len = STRLEN(name) + 3; if (len > varnamebuflen) { xfree(varnamebuf); len += 10; /* some additional space */ varnamebuf = xmalloc(len); varnamebuflen = len; } *varnamebuf = prefix; varnamebuf[1] = ':'; STRCPY(varnamebuf + 2, name); return varnamebuf; } /* * Function given to ExpandGeneric() to obtain the list of user defined * (global/buffer/window/built-in) variable names. */ char_u *get_user_var_name(expand_T *xp, int idx) { static size_t gdone; static size_t bdone; static size_t wdone; static size_t tdone; static size_t vidx; static hashitem_T *hi; hashtab_T *ht; if (idx == 0) { gdone = bdone = wdone = vidx = 0; tdone = 0; } /* Global variables */ if (gdone < globvarht.ht_used) { if (gdone++ == 0) hi = globvarht.ht_array; else ++hi; while (HASHITEM_EMPTY(hi)) ++hi; if (STRNCMP("g:", xp->xp_pattern, 2) == 0) return cat_prefix_varname('g', hi->hi_key); return hi->hi_key; } /* b: variables */ ht = &curbuf->b_vars->dv_hashtab; if (bdone < ht->ht_used) { if (bdone++ == 0) hi = ht->ht_array; else ++hi; while (HASHITEM_EMPTY(hi)) ++hi; return cat_prefix_varname('b', hi->hi_key); } /* w: variables */ ht = &curwin->w_vars->dv_hashtab; if (wdone < ht->ht_used) { if (wdone++ == 0) hi = ht->ht_array; else ++hi; while (HASHITEM_EMPTY(hi)) ++hi; return cat_prefix_varname('w', hi->hi_key); } /* t: variables */ ht = &curtab->tp_vars->dv_hashtab; if (tdone < ht->ht_used) { if (tdone++ == 0) hi = ht->ht_array; else ++hi; while (HASHITEM_EMPTY(hi)) ++hi; return cat_prefix_varname('t', hi->hi_key); } // v: variables if (vidx < ARRAY_SIZE(vimvars)) { return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name); } XFREE_CLEAR(varnamebuf); varnamebuflen = 0; return NULL; } // TODO(ZyX-I): move to eval/expressions /// Return TRUE if "pat" matches "text". /// Does not use 'cpo' and always uses 'magic'. static int pattern_match(char_u *pat, char_u *text, int ic) { int matches = 0; regmatch_T regmatch; // avoid 'l' flag in 'cpoptions' char_u *save_cpo = p_cpo; p_cpo = (char_u *)""; regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING); if (regmatch.regprog != NULL) { regmatch.rm_ic = ic; matches = vim_regexec_nl(®match, text, (colnr_T)0); vim_regfree(regmatch.regprog); } p_cpo = save_cpo; return matches; } /* * types for expressions. */ typedef enum { TYPE_UNKNOWN = 0, TYPE_EQUAL, // == TYPE_NEQUAL, // != TYPE_GREATER, // > TYPE_GEQUAL, // >= TYPE_SMALLER, // < TYPE_SEQUAL, // <= TYPE_MATCH, // =~ TYPE_NOMATCH, // !~ } exptype_T; // TODO(ZyX-I): move to eval/expressions /* * The "evaluate" argument: When FALSE, the argument is only parsed but not * executed. The function may return OK, but the rettv will be of type * VAR_UNKNOWN. The function still returns FAIL for a syntax error. */ /* * Handle zero level expression. * This calls eval1() and handles error message and nextcmd. * Put the result in "rettv" when returning OK and "evaluate" is TRUE. * Note: "rettv.v_lock" is not set. * Return OK or FAIL. */ int eval0(char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate) { int ret; char_u *p; p = skipwhite(arg); ret = eval1(&p, rettv, evaluate); if (ret == FAIL || !ends_excmd(*p)) { if (ret != FAIL) { tv_clear(rettv); } // Report the invalid expression unless the expression evaluation has // been cancelled due to an aborting error, an interrupt, or an // exception. if (!aborting()) { emsgf(_(e_invexpr2), arg); } ret = FAIL; } if (nextcmd != NULL) *nextcmd = check_nextcmd(p); return ret; } // TODO(ZyX-I): move to eval/expressions /* * Handle top level expression: * expr2 ? expr1 : expr1 * * "arg" must point to the first non-white of the expression. * "arg" is advanced to the next non-white after the recognized expression. * * Note: "rettv.v_lock" is not set. * * Return OK or FAIL. */ static int eval1(char_u **arg, typval_T *rettv, int evaluate) { int result; typval_T var2; /* * Get the first variable. */ if (eval2(arg, rettv, evaluate) == FAIL) return FAIL; if ((*arg)[0] == '?') { result = FALSE; if (evaluate) { bool error = false; if (tv_get_number_chk(rettv, &error) != 0) { result = true; } tv_clear(rettv); if (error) { return FAIL; } } /* * Get the second variable. */ *arg = skipwhite(*arg + 1); if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */ return FAIL; /* * Check for the ":". */ if ((*arg)[0] != ':') { EMSG(_("E109: Missing ':' after '?'")); if (evaluate && result) { tv_clear(rettv); } return FAIL; } /* * Get the third variable. */ *arg = skipwhite(*arg + 1); if (eval1(arg, &var2, evaluate && !result) == FAIL) { // Recursive! if (evaluate && result) { tv_clear(rettv); } return FAIL; } if (evaluate && !result) *rettv = var2; } return OK; } // TODO(ZyX-I): move to eval/expressions /* * Handle first level expression: * expr2 || expr2 || expr2 logical OR * * "arg" must point to the first non-white of the expression. * "arg" is advanced to the next non-white after the recognized expression. * * Return OK or FAIL. */ static int eval2(char_u **arg, typval_T *rettv, int evaluate) { typval_T var2; long result; int first; bool error = false; /* * Get the first variable. */ if (eval3(arg, rettv, evaluate) == FAIL) return FAIL; /* * Repeat until there is no following "||". */ first = TRUE; result = FALSE; while ((*arg)[0] == '|' && (*arg)[1] == '|') { if (evaluate && first) { if (tv_get_number_chk(rettv, &error) != 0) { result = true; } tv_clear(rettv); if (error) { return FAIL; } first = false; } /* * Get the second variable. */ *arg = skipwhite(*arg + 2); if (eval3(arg, &var2, evaluate && !result) == FAIL) return FAIL; /* * Compute the result. */ if (evaluate && !result) { if (tv_get_number_chk(&var2, &error) != 0) { result = true; } tv_clear(&var2); if (error) { return FAIL; } } if (evaluate) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = result; } } return OK; } // TODO(ZyX-I): move to eval/expressions /* * Handle second level expression: * expr3 && expr3 && expr3 logical AND * * "arg" must point to the first non-white of the expression. * "arg" is advanced to the next non-white after the recognized expression. * * Return OK or FAIL. */ static int eval3(char_u **arg, typval_T *rettv, int evaluate) { typval_T var2; long result; int first; bool error = false; /* * Get the first variable. */ if (eval4(arg, rettv, evaluate) == FAIL) return FAIL; /* * Repeat until there is no following "&&". */ first = TRUE; result = TRUE; while ((*arg)[0] == '&' && (*arg)[1] == '&') { if (evaluate && first) { if (tv_get_number_chk(rettv, &error) == 0) { result = false; } tv_clear(rettv); if (error) { return FAIL; } first = false; } /* * Get the second variable. */ *arg = skipwhite(*arg + 2); if (eval4(arg, &var2, evaluate && result) == FAIL) return FAIL; /* * Compute the result. */ if (evaluate && result) { if (tv_get_number_chk(&var2, &error) == 0) { result = false; } tv_clear(&var2); if (error) { return FAIL; } } if (evaluate) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = result; } } return OK; } // TODO(ZyX-I): move to eval/expressions /* * Handle third level expression: * var1 == var2 * var1 =~ var2 * var1 != var2 * var1 !~ var2 * var1 > var2 * var1 >= var2 * var1 < var2 * var1 <= var2 * var1 is var2 * var1 isnot var2 * * "arg" must point to the first non-white of the expression. * "arg" is advanced to the next non-white after the recognized expression. * * Return OK or FAIL. */ static int eval4(char_u **arg, typval_T *rettv, int evaluate) { typval_T var2; char_u *p; int i; exptype_T type = TYPE_UNKNOWN; int type_is = FALSE; /* TRUE for "is" and "isnot" */ int len = 2; varnumber_T n1, n2; int ic; /* * Get the first variable. */ if (eval5(arg, rettv, evaluate) == FAIL) return FAIL; p = *arg; switch (p[0]) { case '=': if (p[1] == '=') type = TYPE_EQUAL; else if (p[1] == '~') type = TYPE_MATCH; break; case '!': if (p[1] == '=') type = TYPE_NEQUAL; else if (p[1] == '~') type = TYPE_NOMATCH; break; case '>': if (p[1] != '=') { type = TYPE_GREATER; len = 1; } else type = TYPE_GEQUAL; break; case '<': if (p[1] != '=') { type = TYPE_SMALLER; len = 1; } else type = TYPE_SEQUAL; break; case 'i': if (p[1] == 's') { if (p[2] == 'n' && p[3] == 'o' && p[4] == 't') { len = 5; } if (!isalnum(p[len]) && p[len] != '_') { type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL; type_is = TRUE; } } break; } /* * If there is a comparative operator, use it. */ if (type != TYPE_UNKNOWN) { /* extra question mark appended: ignore case */ if (p[len] == '?') { ic = TRUE; ++len; } /* extra '#' appended: match case */ else if (p[len] == '#') { ic = FALSE; ++len; } /* nothing appended: use 'ignorecase' */ else ic = p_ic; /* * Get the second variable. */ *arg = skipwhite(p + len); if (eval5(arg, &var2, evaluate) == FAIL) { tv_clear(rettv); return FAIL; } if (evaluate) { if (type_is && rettv->v_type != var2.v_type) { /* For "is" a different type always means FALSE, for "notis" * it means TRUE. */ n1 = (type == TYPE_NEQUAL); } else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST) { if (type_is) { n1 = (rettv->v_type == var2.v_type && rettv->vval.v_list == var2.vval.v_list); if (type == TYPE_NEQUAL) n1 = !n1; } else if (rettv->v_type != var2.v_type || (type != TYPE_EQUAL && type != TYPE_NEQUAL)) { if (rettv->v_type != var2.v_type) { EMSG(_("E691: Can only compare List with List")); } else { EMSG(_("E692: Invalid operation for List")); } tv_clear(rettv); tv_clear(&var2); return FAIL; } else { // Compare two Lists for being equal or unequal. n1 = tv_list_equal(rettv->vval.v_list, var2.vval.v_list, ic, false); if (type == TYPE_NEQUAL) { n1 = !n1; } } } else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT) { if (type_is) { n1 = (rettv->v_type == var2.v_type && rettv->vval.v_dict == var2.vval.v_dict); if (type == TYPE_NEQUAL) n1 = !n1; } else if (rettv->v_type != var2.v_type || (type != TYPE_EQUAL && type != TYPE_NEQUAL)) { if (rettv->v_type != var2.v_type) EMSG(_("E735: Can only compare Dictionary with Dictionary")); else EMSG(_("E736: Invalid operation for Dictionary")); tv_clear(rettv); tv_clear(&var2); return FAIL; } else { // Compare two Dictionaries for being equal or unequal. n1 = tv_dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic, false); if (type == TYPE_NEQUAL) { n1 = !n1; } } } else if (tv_is_func(*rettv) || tv_is_func(var2)) { if (type != TYPE_EQUAL && type != TYPE_NEQUAL) { EMSG(_("E694: Invalid operation for Funcrefs")); tv_clear(rettv); tv_clear(&var2); return FAIL; } if ((rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial == NULL) || (var2.v_type == VAR_PARTIAL && var2.vval.v_partial == NULL)) { // when a partial is NULL assume not equal n1 = false; } else if (type_is) { if (rettv->v_type == VAR_FUNC && var2.v_type == VAR_FUNC) { // strings are considered the same if their value is // the same n1 = tv_equal(rettv, &var2, ic, false); } else if (rettv->v_type == VAR_PARTIAL && var2.v_type == VAR_PARTIAL) { n1 = (rettv->vval.v_partial == var2.vval.v_partial); } else { n1 = false; } } else { n1 = tv_equal(rettv, &var2, ic, false); } if (type == TYPE_NEQUAL) { n1 = !n1; } } /* * If one of the two variables is a float, compare as a float. * When using "=~" or "!~", always compare as string. */ else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT) && type != TYPE_MATCH && type != TYPE_NOMATCH) { float_T f1, f2; if (rettv->v_type == VAR_FLOAT) { f1 = rettv->vval.v_float; } else { f1 = tv_get_number(rettv); } if (var2.v_type == VAR_FLOAT) { f2 = var2.vval.v_float; } else { f2 = tv_get_number(&var2); } n1 = false; switch (type) { case TYPE_EQUAL: n1 = (f1 == f2); break; case TYPE_NEQUAL: n1 = (f1 != f2); break; case TYPE_GREATER: n1 = (f1 > f2); break; case TYPE_GEQUAL: n1 = (f1 >= f2); break; case TYPE_SMALLER: n1 = (f1 < f2); break; case TYPE_SEQUAL: n1 = (f1 <= f2); break; case TYPE_UNKNOWN: case TYPE_MATCH: case TYPE_NOMATCH: break; } } /* * If one of the two variables is a number, compare as a number. * When using "=~" or "!~", always compare as string. */ else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER) && type != TYPE_MATCH && type != TYPE_NOMATCH) { n1 = tv_get_number(rettv); n2 = tv_get_number(&var2); switch (type) { case TYPE_EQUAL: n1 = (n1 == n2); break; case TYPE_NEQUAL: n1 = (n1 != n2); break; case TYPE_GREATER: n1 = (n1 > n2); break; case TYPE_GEQUAL: n1 = (n1 >= n2); break; case TYPE_SMALLER: n1 = (n1 < n2); break; case TYPE_SEQUAL: n1 = (n1 <= n2); break; case TYPE_UNKNOWN: case TYPE_MATCH: case TYPE_NOMATCH: break; } } else { char buf1[NUMBUFLEN]; char buf2[NUMBUFLEN]; const char *const s1 = tv_get_string_buf(rettv, buf1); const char *const s2 = tv_get_string_buf(&var2, buf2); if (type != TYPE_MATCH && type != TYPE_NOMATCH) { i = mb_strcmp_ic((bool)ic, s1, s2); } else { i = 0; } n1 = false; switch (type) { case TYPE_EQUAL: n1 = (i == 0); break; case TYPE_NEQUAL: n1 = (i != 0); break; case TYPE_GREATER: n1 = (i > 0); break; case TYPE_GEQUAL: n1 = (i >= 0); break; case TYPE_SMALLER: n1 = (i < 0); break; case TYPE_SEQUAL: n1 = (i <= 0); break; case TYPE_MATCH: case TYPE_NOMATCH: { n1 = pattern_match((char_u *)s2, (char_u *)s1, ic); if (type == TYPE_NOMATCH) { n1 = !n1; } break; } case TYPE_UNKNOWN: break; // Avoid gcc warning. } } tv_clear(rettv); tv_clear(&var2); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = n1; } } return OK; } // TODO(ZyX-I): move to eval/expressions /* * Handle fourth level expression: * + number addition * - number subtraction * . string concatenation * .. string concatenation * * "arg" must point to the first non-white of the expression. * "arg" is advanced to the next non-white after the recognized expression. * * Return OK or FAIL. */ static int eval5(char_u **arg, typval_T *rettv, int evaluate) { typval_T var2; typval_T var3; int op; varnumber_T n1, n2; float_T f1 = 0, f2 = 0; char_u *p; /* * Get the first variable. */ if (eval6(arg, rettv, evaluate, FALSE) == FAIL) return FAIL; /* * Repeat computing, until no '+', '-' or '.' is following. */ for (;; ) { op = **arg; if (op != '+' && op != '-' && op != '.') break; if ((op != '+' || rettv->v_type != VAR_LIST) && (op == '.' || rettv->v_type != VAR_FLOAT)) { // For "list + ...", an illegal use of the first operand as // a number cannot be determined before evaluating the 2nd // operand: if this is also a list, all is ok. // For "something . ...", "something - ..." or "non-list + ...", // we know that the first operand needs to be a string or number // without evaluating the 2nd operand. So check before to avoid // side effects after an error. if (evaluate && !tv_check_str(rettv)) { tv_clear(rettv); return FAIL; } } /* * Get the second variable. */ if (op == '.' && *(*arg + 1) == '.') { // ..string concatenation (*arg)++; } *arg = skipwhite(*arg + 1); if (eval6(arg, &var2, evaluate, op == '.') == FAIL) { tv_clear(rettv); return FAIL; } if (evaluate) { /* * Compute the result. */ if (op == '.') { char buf1[NUMBUFLEN]; char buf2[NUMBUFLEN]; // s1 already checked const char *const s1 = tv_get_string_buf(rettv, buf1); const char *const s2 = tv_get_string_buf_chk(&var2, buf2); if (s2 == NULL) { // Type error? tv_clear(rettv); tv_clear(&var2); return FAIL; } p = concat_str((const char_u *)s1, (const char_u *)s2); tv_clear(rettv); rettv->v_type = VAR_STRING; rettv->vval.v_string = p; } else if (op == '+' && rettv->v_type == VAR_LIST && var2.v_type == VAR_LIST) { // Concatenate Lists. if (tv_list_concat(rettv->vval.v_list, var2.vval.v_list, &var3) == FAIL) { tv_clear(rettv); tv_clear(&var2); return FAIL; } tv_clear(rettv); *rettv = var3; } else { bool error = false; if (rettv->v_type == VAR_FLOAT) { f1 = rettv->vval.v_float; n1 = 0; } else { n1 = tv_get_number_chk(rettv, &error); if (error) { /* This can only happen for "list + non-list". For * "non-list + ..." or "something - ...", we returned * before evaluating the 2nd operand. */ tv_clear(rettv); return FAIL; } if (var2.v_type == VAR_FLOAT) f1 = n1; } if (var2.v_type == VAR_FLOAT) { f2 = var2.vval.v_float; n2 = 0; } else { n2 = tv_get_number_chk(&var2, &error); if (error) { tv_clear(rettv); tv_clear(&var2); return FAIL; } if (rettv->v_type == VAR_FLOAT) f2 = n2; } tv_clear(rettv); /* If there is a float on either side the result is a float. */ if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT) { if (op == '+') f1 = f1 + f2; else f1 = f1 - f2; rettv->v_type = VAR_FLOAT; rettv->vval.v_float = f1; } else { if (op == '+') n1 = n1 + n2; else n1 = n1 - n2; rettv->v_type = VAR_NUMBER; rettv->vval.v_number = n1; } } tv_clear(&var2); } } return OK; } // TODO(ZyX-I): move to eval/expressions /// Handle fifth level expression: /// - * number multiplication /// - / number division /// - % number modulo /// /// @param[in,out] arg Points to the first non-whitespace character of the /// expression. Is advanced to the next non-whitespace /// character after the recognized expression. /// @param[out] rettv Location where result is saved. /// @param[in] evaluate If not true, rettv is not populated. /// @param[in] want_string True if "." is string_concatenation, otherwise /// float /// @return OK or FAIL. static int eval6(char_u **arg, typval_T *rettv, int evaluate, int want_string) FUNC_ATTR_NO_SANITIZE_UNDEFINED { typval_T var2; int op; varnumber_T n1, n2; bool use_float = false; float_T f1 = 0, f2 = 0; bool error = false; /* * Get the first variable. */ if (eval7(arg, rettv, evaluate, want_string) == FAIL) return FAIL; /* * Repeat computing, until no '*', '/' or '%' is following. */ for (;; ) { op = **arg; if (op != '*' && op != '/' && op != '%') break; if (evaluate) { if (rettv->v_type == VAR_FLOAT) { f1 = rettv->vval.v_float; use_float = true; n1 = 0; } else { n1 = tv_get_number_chk(rettv, &error); } tv_clear(rettv); if (error) { return FAIL; } } else { n1 = 0; } /* * Get the second variable. */ *arg = skipwhite(*arg + 1); if (eval7(arg, &var2, evaluate, FALSE) == FAIL) return FAIL; if (evaluate) { if (var2.v_type == VAR_FLOAT) { if (!use_float) { f1 = n1; use_float = true; } f2 = var2.vval.v_float; n2 = 0; } else { n2 = tv_get_number_chk(&var2, &error); tv_clear(&var2); if (error) { return FAIL; } if (use_float) { f2 = n2; } } /* * Compute the result. * When either side is a float the result is a float. */ if (use_float) { if (op == '*') { f1 = f1 * f2; } else if (op == '/') { // Division by zero triggers error from AddressSanitizer f1 = (f2 == 0 ? ( #ifdef NAN f1 == 0 ? NAN : #endif (f1 > 0 ? INFINITY : -INFINITY) ) : f1 / f2); } else { EMSG(_("E804: Cannot use '%' with Float")); return FAIL; } rettv->v_type = VAR_FLOAT; rettv->vval.v_float = f1; } else { if (op == '*') { n1 = n1 * n2; } else if (op == '/') { n1 = num_divide(n1, n2); } else { n1 = num_modulus(n1, n2); } rettv->v_type = VAR_NUMBER; rettv->vval.v_number = n1; } } } return OK; } // TODO(ZyX-I): move to eval/expressions // Handle sixth level expression: // number number constant // "string" string constant // 'string' literal string constant // &option-name option value // @r register contents // identifier variable value // function() function call // $VAR environment variable // (expression) nested expression // [expr, expr] List // {key: val, key: val} Dictionary // // Also handle: // ! in front logical NOT // - in front unary minus // + in front unary plus (ignored) // trailing [] subscript in String or List // trailing .name entry in Dictionary // // "arg" must point to the first non-white of the expression. // "arg" is advanced to the next non-white after the recognized expression. // // Return OK or FAIL. static int eval7( char_u **arg, typval_T *rettv, int evaluate, int want_string // after "." operator ) { varnumber_T n; int len; char_u *s; char_u *start_leader, *end_leader; int ret = OK; char_u *alias; // Initialise variable so that tv_clear() can't mistake this for a // string and free a string that isn't there. rettv->v_type = VAR_UNKNOWN; // Skip '!', '-' and '+' characters. They are handled later. start_leader = *arg; while (**arg == '!' || **arg == '-' || **arg == '+') { *arg = skipwhite(*arg + 1); } end_leader = *arg; switch (**arg) { // Number constant. case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { char_u *p = skipdigits(*arg + 1); int get_float = false; // We accept a float when the format matches // "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very // strict to avoid backwards compatibility problems. // Don't look for a float after the "." operator, so that // ":let vers = 1.2.3" doesn't fail. if (!want_string && p[0] == '.' && ascii_isdigit(p[1])) { get_float = true; p = skipdigits(p + 2); if (*p == 'e' || *p == 'E') { ++p; if (*p == '-' || *p == '+') { ++p; } if (!ascii_isdigit(*p)) { get_float = false; } else { p = skipdigits(p + 1); } } if (ASCII_ISALPHA(*p) || *p == '.') { get_float = false; } } if (get_float) { float_T f; *arg += string2float((char *) *arg, &f); if (evaluate) { rettv->v_type = VAR_FLOAT; rettv->vval.v_float = f; } } else { vim_str2nr(*arg, NULL, &len, STR2NR_ALL, &n, NULL, 0); *arg += len; if (evaluate) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = n; } } break; } // String constant: "string". case '"': ret = get_string_tv(arg, rettv, evaluate); break; // Literal string constant: 'str''ing'. case '\'': ret = get_lit_string_tv(arg, rettv, evaluate); break; // List: [expr, expr] case '[': ret = get_list_tv(arg, rettv, evaluate); break; // Lambda: {arg, arg -> expr} // Dictionary: {key: val, key: val} case '{': ret = get_lambda_tv(arg, rettv, evaluate); if (ret == NOTDONE) { ret = dict_get_tv(arg, rettv, evaluate); } break; // Option value: &name case '&': { ret = get_option_tv((const char **)arg, rettv, evaluate); break; } // Environment variable: $VAR. case '$': ret = get_env_tv(arg, rettv, evaluate); break; // Register contents: @r. case '@': ++*arg; if (evaluate) { rettv->v_type = VAR_STRING; rettv->vval.v_string = get_reg_contents(**arg, kGRegExprSrc); } if (**arg != NUL) { ++*arg; } break; // nested expression: (expression). case '(': *arg = skipwhite(*arg + 1); ret = eval1(arg, rettv, evaluate); // recursive! if (**arg == ')') { ++*arg; } else if (ret == OK) { EMSG(_("E110: Missing ')'")); tv_clear(rettv); ret = FAIL; } break; default: ret = NOTDONE; break; } if (ret == NOTDONE) { // Must be a variable or function name. // Can also be a curly-braces kind of name: {expr}. s = *arg; len = get_name_len((const char **)arg, (char **)&alias, evaluate, true); if (alias != NULL) { s = alias; } if (len <= 0) { ret = FAIL; } else { if (**arg == '(') { // recursive! partial_T *partial; if (!evaluate) { check_vars((const char *)s, len); } // If "s" is the name of a variable of type VAR_FUNC // use its contents. s = deref_func_name((const char *)s, &len, &partial, !evaluate); // Need to make a copy, in case evaluating the arguments makes // the name invalid. s = xmemdupz(s, len); // Invoke the function. ret = get_func_tv(s, len, rettv, arg, curwin->w_cursor.lnum, curwin->w_cursor.lnum, &len, evaluate, partial, NULL); xfree(s); // If evaluate is false rettv->v_type was not set in // get_func_tv, but it's needed in handle_subscript() to parse // what follows. So set it here. if (rettv->v_type == VAR_UNKNOWN && !evaluate && **arg == '(') { rettv->vval.v_string = (char_u *)tv_empty_string; rettv->v_type = VAR_FUNC; } // Stop the expression evaluation when immediately // aborting on error, or when an interrupt occurred or // an exception was thrown but not caught. if (evaluate && aborting()) { if (ret == OK) { tv_clear(rettv); } ret = FAIL; } } else if (evaluate) { ret = get_var_tv((const char *)s, len, rettv, NULL, true, false); } else { check_vars((const char *)s, len); ret = OK; } } xfree(alias); } *arg = skipwhite(*arg); // Handle following '[', '(' and '.' for expr[expr], expr.name, // expr(expr). if (ret == OK) { ret = handle_subscript((const char **)arg, rettv, evaluate, true); } // Apply logical NOT and unary '-', from right to left, ignore '+'. if (ret == OK && evaluate && end_leader > start_leader) { bool error = false; varnumber_T val = 0; float_T f = 0.0; if (rettv->v_type == VAR_FLOAT) { f = rettv->vval.v_float; } else { val = tv_get_number_chk(rettv, &error); } if (error) { tv_clear(rettv); ret = FAIL; } else { while (end_leader > start_leader) { --end_leader; if (*end_leader == '!') { if (rettv->v_type == VAR_FLOAT) { f = !f; } else { val = !val; } } else if (*end_leader == '-') { if (rettv->v_type == VAR_FLOAT) { f = -f; } else { val = -val; } } } if (rettv->v_type == VAR_FLOAT) { tv_clear(rettv); rettv->vval.v_float = f; } else { tv_clear(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = val; } } } return ret; } // TODO(ZyX-I): move to eval/expressions /* * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key". * "*arg" points to the '[' or '.'. * Returns FAIL or OK. "*arg" is advanced to after the ']'. */ static int eval_index( char_u **arg, typval_T *rettv, int evaluate, int verbose /* give error messages */ ) { bool empty1 = false; bool empty2 = false; long n1, n2 = 0; ptrdiff_t len = -1; int range = false; char_u *key = NULL; switch (rettv->v_type) { case VAR_FUNC: case VAR_PARTIAL: { if (verbose) { EMSG(_("E695: Cannot index a Funcref")); } return FAIL; } case VAR_FLOAT: { if (verbose) { EMSG(_(e_float_as_string)); } return FAIL; } case VAR_SPECIAL: { if (verbose) { EMSG(_("E909: Cannot index a special variable")); } return FAIL; } case VAR_UNKNOWN: { if (evaluate) { return FAIL; } FALLTHROUGH; } case VAR_STRING: case VAR_NUMBER: case VAR_LIST: case VAR_DICT: { break; } } typval_T var1 = TV_INITIAL_VALUE; typval_T var2 = TV_INITIAL_VALUE; if (**arg == '.') { /* * dict.name */ key = *arg + 1; for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len) ; if (len == 0) return FAIL; *arg = skipwhite(key + len); } else { /* * something[idx] * * Get the (first) variable from inside the []. */ *arg = skipwhite(*arg + 1); if (**arg == ':') { empty1 = true; } else if (eval1(arg, &var1, evaluate) == FAIL) { // Recursive! return FAIL; } else if (evaluate && !tv_check_str(&var1)) { // Not a number or string. tv_clear(&var1); return FAIL; } /* * Get the second variable from inside the [:]. */ if (**arg == ':') { range = TRUE; *arg = skipwhite(*arg + 1); if (**arg == ']') { empty2 = true; } else if (eval1(arg, &var2, evaluate) == FAIL) { // Recursive! if (!empty1) { tv_clear(&var1); } return FAIL; } else if (evaluate && !tv_check_str(&var2)) { // Not a number or string. if (!empty1) { tv_clear(&var1); } tv_clear(&var2); return FAIL; } } /* Check for the ']'. */ if (**arg != ']') { if (verbose) { EMSG(_(e_missbrac)); } tv_clear(&var1); if (range) { tv_clear(&var2); } return FAIL; } *arg = skipwhite(*arg + 1); /* skip the ']' */ } if (evaluate) { n1 = 0; if (!empty1 && rettv->v_type != VAR_DICT) { n1 = tv_get_number(&var1); tv_clear(&var1); } if (range) { if (empty2) { n2 = -1; } else { n2 = tv_get_number(&var2); tv_clear(&var2); } } switch (rettv->v_type) { case VAR_NUMBER: case VAR_STRING: { const char *const s = tv_get_string(rettv); char *v; len = (ptrdiff_t)strlen(s); if (range) { // The resulting variable is a substring. If the indexes // are out of range the result is empty. if (n1 < 0) { n1 = len + n1; if (n1 < 0) { n1 = 0; } } if (n2 < 0) { n2 = len + n2; } else if (n2 >= len) { n2 = len; } if (n1 >= len || n2 < 0 || n1 > n2) { v = NULL; } else { v = xmemdupz(s + n1, (size_t)(n2 - n1 + 1)); } } else { // The resulting variable is a string of a single // character. If the index is too big or negative the // result is empty. if (n1 >= len || n1 < 0) { v = NULL; } else { v = xmemdupz(s + n1, 1); } } tv_clear(rettv); rettv->v_type = VAR_STRING; rettv->vval.v_string = (char_u *)v; break; } case VAR_LIST: { len = tv_list_len(rettv->vval.v_list); if (n1 < 0) { n1 = len + n1; } if (!empty1 && (n1 < 0 || n1 >= len)) { // For a range we allow invalid values and return an empty // list. A list index out of range is an error. if (!range) { if (verbose) { EMSGN(_(e_listidx), n1); } return FAIL; } n1 = len; } if (range) { list_T *l; listitem_T *item; if (n2 < 0) { n2 = len + n2; } else if (n2 >= len) { n2 = len - 1; } if (!empty2 && (n2 < 0 || n2 + 1 < n1)) { n2 = -1; } l = tv_list_alloc(n2 - n1 + 1); item = tv_list_find(rettv->vval.v_list, n1); while (n1++ <= n2) { tv_list_append_tv(l, TV_LIST_ITEM_TV(item)); item = TV_LIST_ITEM_NEXT(rettv->vval.v_list, item); } tv_clear(rettv); tv_list_set_ret(rettv, l); } else { tv_copy(TV_LIST_ITEM_TV(tv_list_find(rettv->vval.v_list, n1)), &var1); tv_clear(rettv); *rettv = var1; } break; } case VAR_DICT: { if (range) { if (verbose) { EMSG(_(e_dictrange)); } if (len == -1) { tv_clear(&var1); } return FAIL; } if (len == -1) { key = (char_u *)tv_get_string_chk(&var1); if (key == NULL) { tv_clear(&var1); return FAIL; } } dictitem_T *const item = tv_dict_find(rettv->vval.v_dict, (const char *)key, len); if (item == NULL && verbose) { emsgf(_(e_dictkey), key); } if (len == -1) { tv_clear(&var1); } if (item == NULL) { return FAIL; } tv_copy(&item->di_tv, &var1); tv_clear(rettv); *rettv = var1; break; } case VAR_SPECIAL: case VAR_FUNC: case VAR_FLOAT: case VAR_PARTIAL: case VAR_UNKNOWN: { break; // Not evaluating, skipping over subscript } } } return OK; } // TODO(ZyX-I): move to eval/executor /// Get an option value /// /// @param[in,out] arg Points to the '&' or '+' before the option name. Is /// advanced to the character after the option name. /// @param[out] rettv Location where result is saved. /// @param[in] evaluate If not true, rettv is not populated. /// /// @return OK or FAIL. static int get_option_tv(const char **const arg, typval_T *const rettv, const bool evaluate) FUNC_ATTR_NONNULL_ARG(1) { long numval; char_u *stringval; int opt_type; int c; bool working = (**arg == '+'); // has("+option") int ret = OK; int opt_flags; // Isolate the option name and find its value. char *option_end = (char *)find_option_end(arg, &opt_flags); if (option_end == NULL) { if (rettv != NULL) { EMSG2(_("E112: Option name missing: %s"), *arg); } return FAIL; } if (!evaluate) { *arg = option_end; return OK; } c = *option_end; *option_end = NUL; opt_type = get_option_value((char_u *)(*arg), &numval, rettv == NULL ? NULL : &stringval, opt_flags); if (opt_type == -3) { /* invalid name */ if (rettv != NULL) EMSG2(_("E113: Unknown option: %s"), *arg); ret = FAIL; } else if (rettv != NULL) { if (opt_type == -2) { /* hidden string option */ rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; } else if (opt_type == -1) { /* hidden number option */ rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; } else if (opt_type == 1) { /* number option */ rettv->v_type = VAR_NUMBER; rettv->vval.v_number = numval; } else { /* string option */ rettv->v_type = VAR_STRING; rettv->vval.v_string = stringval; } } else if (working && (opt_type == -2 || opt_type == -1)) ret = FAIL; *option_end = c; /* put back for error messages */ *arg = option_end; return ret; } /* * Allocate a variable for a string constant. * Return OK or FAIL. */ static int get_string_tv(char_u **arg, typval_T *rettv, int evaluate) { char_u *p; char_u *name; unsigned int extra = 0; /* * Find the end of the string, skipping backslashed characters. */ for (p = *arg + 1; *p != NUL && *p != '"'; MB_PTR_ADV(p)) { if (*p == '\\' && p[1] != NUL) { ++p; /* A "\" form occupies at least 4 characters, and produces up * to 6 characters: reserve space for 2 extra */ if (*p == '<') extra += 2; } } if (*p != '"') { EMSG2(_("E114: Missing quote: %s"), *arg); return FAIL; } /* If only parsing, set *arg and return here */ if (!evaluate) { *arg = p + 1; return OK; } /* * Copy the string into allocated memory, handling backslashed * characters. */ name = xmalloc(p - *arg + extra); rettv->v_type = VAR_STRING; rettv->vval.v_string = name; for (p = *arg + 1; *p != NUL && *p != '"'; ) { if (*p == '\\') { switch (*++p) { case 'b': *name++ = BS; ++p; break; case 'e': *name++ = ESC; ++p; break; case 'f': *name++ = FF; ++p; break; case 'n': *name++ = NL; ++p; break; case 'r': *name++ = CAR; ++p; break; case 't': *name++ = TAB; ++p; break; case 'X': /* hex: "\x1", "\x12" */ case 'x': case 'u': /* Unicode: "\u0023" */ case 'U': if (ascii_isxdigit(p[1])) { int n, nr; int c = toupper(*p); if (c == 'X') { n = 2; } else if (*p == 'u') { n = 4; } else { n = 8; } nr = 0; while (--n >= 0 && ascii_isxdigit(p[1])) { ++p; nr = (nr << 4) + hex2nr(*p); } ++p; /* For "\u" store the number according to * 'encoding'. */ if (c != 'X') { name += utf_char2bytes(nr, name); } else { *name++ = nr; } } break; /* octal: "\1", "\12", "\123" */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': *name = *p++ - '0'; if (*p >= '0' && *p <= '7') { *name = (*name << 3) + *p++ - '0'; if (*p >= '0' && *p <= '7') *name = (*name << 3) + *p++ - '0'; } ++name; break; // Special key, e.g.: "\" case '<': extra = trans_special((const char_u **)&p, STRLEN(p), name, true, true); if (extra != 0) { name += extra; break; } FALLTHROUGH; default: MB_COPY_CHAR(p, name); break; } } else MB_COPY_CHAR(p, name); } *name = NUL; if (*p != NUL) { // just in case p++; } *arg = p; return OK; } /* * Allocate a variable for a 'str''ing' constant. * Return OK or FAIL. */ static int get_lit_string_tv(char_u **arg, typval_T *rettv, int evaluate) { char_u *p; char_u *str; int reduce = 0; /* * Find the end of the string, skipping ''. */ for (p = *arg + 1; *p != NUL; MB_PTR_ADV(p)) { if (*p == '\'') { if (p[1] != '\'') break; ++reduce; ++p; } } if (*p != '\'') { EMSG2(_("E115: Missing quote: %s"), *arg); return FAIL; } /* If only parsing return after setting "*arg" */ if (!evaluate) { *arg = p + 1; return OK; } /* * Copy the string into allocated memory, handling '' to ' reduction. */ str = xmalloc((p - *arg) - reduce); rettv->v_type = VAR_STRING; rettv->vval.v_string = str; for (p = *arg + 1; *p != NUL; ) { if (*p == '\'') { if (p[1] != '\'') break; ++p; } MB_COPY_CHAR(p, str); } *str = NUL; *arg = p + 1; return OK; } /// @return the function name of the partial. char_u *partial_name(partial_T *pt) { if (pt->pt_name != NULL) { return pt->pt_name; } return pt->pt_func->uf_name; } // TODO(ZyX-I): Move to eval/typval.h static void partial_free(partial_T *pt) { for (int i = 0; i < pt->pt_argc; i++) { tv_clear(&pt->pt_argv[i]); } xfree(pt->pt_argv); tv_dict_unref(pt->pt_dict); if (pt->pt_name != NULL) { func_unref(pt->pt_name); xfree(pt->pt_name); } else { func_ptr_unref(pt->pt_func); } xfree(pt); } // TODO(ZyX-I): Move to eval/typval.h /// Unreference a closure: decrement the reference count and free it when it /// becomes zero. void partial_unref(partial_T *pt) { if (pt != NULL && --pt->pt_refcount <= 0) { partial_free(pt); } } /// Allocate a variable for a List and fill it from "*arg". /// Return OK or FAIL. static int get_list_tv(char_u **arg, typval_T *rettv, int evaluate) { list_T *l = NULL; if (evaluate) { l = tv_list_alloc(kListLenShouldKnow); } *arg = skipwhite(*arg + 1); while (**arg != ']' && **arg != NUL) { typval_T tv; if (eval1(arg, &tv, evaluate) == FAIL) { // Recursive! goto failret; } if (evaluate) { tv.v_lock = VAR_UNLOCKED; tv_list_append_owned_tv(l, tv); } if (**arg == ']') { break; } if (**arg != ',') { emsgf(_("E696: Missing comma in List: %s"), *arg); goto failret; } *arg = skipwhite(*arg + 1); } if (**arg != ']') { emsgf(_("E697: Missing end of List ']': %s"), *arg); failret: if (evaluate) { tv_list_free(l); } return FAIL; } *arg = skipwhite(*arg + 1); if (evaluate) { tv_list_set_ret(rettv, l); } return OK; } bool func_equal( typval_T *tv1, typval_T *tv2, bool ic // ignore case ) { char_u *s1, *s2; dict_T *d1, *d2; int a1, a2; // empty and NULL function name considered the same s1 = tv1->v_type == VAR_FUNC ? tv1->vval.v_string : partial_name(tv1->vval.v_partial); if (s1 != NULL && *s1 == NUL) { s1 = NULL; } s2 = tv2->v_type == VAR_FUNC ? tv2->vval.v_string : partial_name(tv2->vval.v_partial); if (s2 != NULL && *s2 == NUL) { s2 = NULL; } if (s1 == NULL || s2 == NULL) { if (s1 != s2) { return false; } } else if (STRCMP(s1, s2) != 0) { return false; } // empty dict and NULL dict is different d1 = tv1->v_type == VAR_FUNC ? NULL : tv1->vval.v_partial->pt_dict; d2 = tv2->v_type == VAR_FUNC ? NULL : tv2->vval.v_partial->pt_dict; if (d1 == NULL || d2 == NULL) { if (d1 != d2) { return false; } } else if (!tv_dict_equal(d1, d2, ic, true)) { return false; } // empty list and no list considered the same a1 = tv1->v_type == VAR_FUNC ? 0 : tv1->vval.v_partial->pt_argc; a2 = tv2->v_type == VAR_FUNC ? 0 : tv2->vval.v_partial->pt_argc; if (a1 != a2) { return false; } for (int i = 0; i < a1; i++) { if (!tv_equal(tv1->vval.v_partial->pt_argv + i, tv2->vval.v_partial->pt_argv + i, ic, true)) { return false; } } return true; } /// Get next (unique) copy ID /// /// Used for traversing nested structures e.g. when serializing them or garbage /// collecting. int get_copyID(void) FUNC_ATTR_WARN_UNUSED_RESULT { // CopyID for recursively traversing lists and dicts // // This value is needed to avoid endless recursiveness. Last bit is used for // previous_funccal and normally ignored when comparing. static int current_copyID = 0; current_copyID += COPYID_INC; return current_copyID; } // Used by get_func_tv() static garray_T funcargs = GA_EMPTY_INIT_VALUE; /* * Garbage collection for lists and dictionaries. * * We use reference counts to be able to free most items right away when they * are no longer used. But for composite items it's possible that it becomes * unused while the reference count is > 0: When there is a recursive * reference. Example: * :let l = [1, 2, 3] * :let d = {9: l} * :let l[1] = d * * Since this is quite unusual we handle this with garbage collection: every * once in a while find out which lists and dicts are not referenced from any * variable. * * Here is a good reference text about garbage collection (refers to Python * but it applies to all reference-counting mechanisms): * http://python.ca/nas/python/gc/ */ /// Do garbage collection for lists and dicts. /// /// @param testing true if called from test_garbagecollect_now(). /// @returns true if some memory was freed. bool garbage_collect(bool testing) { bool abort = false; #define ABORTING(func) abort = abort || func if (!testing) { // Only do this once. want_garbage_collect = false; may_garbage_collect = false; garbage_collect_at_exit = false; } // We advance by two (COPYID_INC) because we add one for items referenced // through previous_funccal. const int copyID = get_copyID(); // 1. Go through all accessible variables and mark all lists and dicts // with copyID. // Don't free variables in the previous_funccal list unless they are only // referenced through previous_funccal. This must be first, because if // the item is referenced elsewhere the funccal must not be freed. for (funccall_T *fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; ABORTING(set_ref_in_ht)(&fc->l_vars.dv_hashtab, copyID + 1, NULL); ABORTING(set_ref_in_ht)(&fc->l_avars.dv_hashtab, copyID + 1, NULL); } // script-local variables for (int i = 1; i <= ga_scripts.ga_len; ++i) { ABORTING(set_ref_in_ht)(&SCRIPT_VARS(i), copyID, NULL); } FOR_ALL_BUFFERS(buf) { // buffer-local variables ABORTING(set_ref_in_item)(&buf->b_bufvar.di_tv, copyID, NULL, NULL); // buffer marks (ShaDa additional data) ABORTING(set_ref_in_fmark)(buf->b_last_cursor, copyID); ABORTING(set_ref_in_fmark)(buf->b_last_insert, copyID); ABORTING(set_ref_in_fmark)(buf->b_last_change, copyID); for (size_t i = 0; i < NMARKS; i++) { ABORTING(set_ref_in_fmark)(buf->b_namedm[i], copyID); } // buffer change list (ShaDa additional data) for (int i = 0; i < buf->b_changelistlen; i++) { ABORTING(set_ref_in_fmark)(buf->b_changelist[i], copyID); } // buffer ShaDa additional data ABORTING(set_ref_dict)(buf->additional_data, copyID); } FOR_ALL_TAB_WINDOWS(tp, wp) { // window-local variables ABORTING(set_ref_in_item)(&wp->w_winvar.di_tv, copyID, NULL, NULL); // window jump list (ShaDa additional data) for (int i = 0; i < wp->w_jumplistlen; i++) { ABORTING(set_ref_in_fmark)(wp->w_jumplist[i].fmark, copyID); } } if (aucmd_win != NULL) { ABORTING(set_ref_in_item)(&aucmd_win->w_winvar.di_tv, copyID, NULL, NULL); } // registers (ShaDa additional data) { const void *reg_iter = NULL; do { yankreg_T reg; char name = NUL; bool is_unnamed = false; reg_iter = op_global_reg_iter(reg_iter, &name, ®, &is_unnamed); if (name != NUL) { ABORTING(set_ref_dict)(reg.additional_data, copyID); } } while (reg_iter != NULL); } // global marks (ShaDa additional data) { const void *mark_iter = NULL; do { xfmark_T fm; char name = NUL; mark_iter = mark_global_iter(mark_iter, &name, &fm); if (name != NUL) { ABORTING(set_ref_dict)(fm.fmark.additional_data, copyID); } } while (mark_iter != NULL); } // tabpage-local variables FOR_ALL_TABS(tp) { ABORTING(set_ref_in_item)(&tp->tp_winvar.di_tv, copyID, NULL, NULL); } // global variables ABORTING(set_ref_in_ht)(&globvarht, copyID, NULL); // function-local variables for (funccall_T *fc = current_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID; ABORTING(set_ref_in_ht)(&fc->l_vars.dv_hashtab, copyID, NULL); ABORTING(set_ref_in_ht)(&fc->l_avars.dv_hashtab, copyID, NULL); } // named functions (matters for closures) ABORTING(set_ref_in_functions(copyID)); // Channels { Channel *data; map_foreach_value(channels, data, { set_ref_in_callback_reader(&data->on_data, copyID, NULL, NULL); set_ref_in_callback_reader(&data->on_stderr, copyID, NULL, NULL); set_ref_in_callback(&data->on_exit, copyID, NULL, NULL); }) } // Timers { timer_T *timer; map_foreach_value(timers, timer, { set_ref_in_callback(&timer->callback, copyID, NULL, NULL); }) } // function call arguments, if v:testing is set. for (int i = 0; i < funcargs.ga_len; i++) { ABORTING(set_ref_in_item)(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL); } // v: vars ABORTING(set_ref_in_ht)(&vimvarht, copyID, NULL); // history items (ShaDa additional elements) if (p_hi) { for (uint8_t i = 0; i < HIST_COUNT; i++) { const void *iter = NULL; do { histentry_T hist; iter = hist_iter(iter, i, false, &hist); if (hist.hisstr != NULL) { ABORTING(set_ref_list)(hist.additional_elements, copyID); } } while (iter != NULL); } } // previously used search/substitute patterns (ShaDa additional data) { SearchPattern pat; get_search_pattern(&pat); ABORTING(set_ref_dict)(pat.additional_data, copyID); get_substitute_pattern(&pat); ABORTING(set_ref_dict)(pat.additional_data, copyID); } // previously used replacement string { SubReplacementString sub; sub_get_replacement(&sub); ABORTING(set_ref_list)(sub.additional_elements, copyID); } ABORTING(set_ref_in_quickfix)(copyID); bool did_free = false; if (!abort) { // 2. Free lists and dictionaries that are not referenced. did_free = free_unref_items(copyID); // 3. Check if any funccal can be freed now. bool did_free_funccal = false; for (funccall_T **pfc = &previous_funccal; *pfc != NULL;) { if (can_free_funccal(*pfc, copyID)) { funccall_T *fc = *pfc; *pfc = fc->caller; free_funccal(fc, true); did_free = true; did_free_funccal = true; } else { pfc = &(*pfc)->caller; } } if (did_free_funccal) { // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); } } else if (p_verbose > 0) { verb_msg(_( "Not enough memory to set references, garbage collection aborted!")); } #undef ABORTING return did_free; } /// Free lists and dictionaries that are no longer referenced. /// /// @note This function may only be called from garbage_collect(). /// /// @param copyID Free lists/dictionaries that don't have this ID. /// @return true, if something was freed. static int free_unref_items(int copyID) { bool did_free = false; // Let all "free" functions know that we are here. This means no // dictionaries, lists, or jobs are to be freed, because we will // do that here. tv_in_free_unref_items = true; // PASS 1: free the contents of the items. We don't free the items // themselves yet, so that it is possible to decrement refcount counters. // Go through the list of dicts and free items without the copyID. // Don't free dicts that are referenced internally. for (dict_T *dd = gc_first_dict; dd != NULL; dd = dd->dv_used_next) { if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)) { // Free the Dictionary and ordinary items it contains, but don't // recurse into Lists and Dictionaries, they will be in the list // of dicts or list of lists. tv_dict_free_contents(dd); did_free = true; } } // Go through the list of lists and free items without the copyID. // But don't free a list that has a watcher (used in a for loop), these // are not referenced anywhere. for (list_T *ll = gc_first_list; ll != NULL; ll = ll->lv_used_next) { if ((tv_list_copyid(ll) & COPYID_MASK) != (copyID & COPYID_MASK) && !tv_list_has_watchers(ll)) { // Free the List and ordinary items it contains, but don't recurse // into Lists and Dictionaries, they will be in the list of dicts // or list of lists. tv_list_free_contents(ll); did_free = true; } } // PASS 2: free the items themselves. dict_T *dd_next; for (dict_T *dd = gc_first_dict; dd != NULL; dd = dd_next) { dd_next = dd->dv_used_next; if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)) { tv_dict_free_dict(dd); } } list_T *ll_next; for (list_T *ll = gc_first_list; ll != NULL; ll = ll_next) { ll_next = ll->lv_used_next; if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK) && !tv_list_has_watchers(ll)) { // Free the List and ordinary items it contains, but don't recurse // into Lists and Dictionaries, they will be in the list of dicts // or list of lists. tv_list_free_list(ll); } } tv_in_free_unref_items = false; return did_free; } /// Mark all lists and dicts referenced through hashtab "ht" with "copyID". /// /// @param ht Hashtab content will be marked. /// @param copyID New mark for lists and dicts. /// @param list_stack Used to add lists to be marked. Can be NULL. /// /// @returns true if setting references failed somehow. bool set_ref_in_ht(hashtab_T *ht, int copyID, list_stack_T **list_stack) FUNC_ATTR_WARN_UNUSED_RESULT { bool abort = false; ht_stack_T *ht_stack = NULL; hashtab_T *cur_ht = ht; for (;;) { if (!abort) { // Mark each item in the hashtab. If the item contains a hashtab // it is added to ht_stack, if it contains a list it is added to // list_stack. HASHTAB_ITER(cur_ht, hi, { abort = abort || set_ref_in_item( &TV_DICT_HI2DI(hi)->di_tv, copyID, &ht_stack, list_stack); }); } if (ht_stack == NULL) { break; } // take an item from the stack cur_ht = ht_stack->ht; ht_stack_T *tempitem = ht_stack; ht_stack = ht_stack->prev; xfree(tempitem); } return abort; } /// Mark all lists and dicts referenced through list "l" with "copyID". /// /// @param l List content will be marked. /// @param copyID New mark for lists and dicts. /// @param ht_stack Used to add hashtabs to be marked. Can be NULL. /// /// @returns true if setting references failed somehow. bool set_ref_in_list(list_T *l, int copyID, ht_stack_T **ht_stack) FUNC_ATTR_WARN_UNUSED_RESULT { bool abort = false; list_stack_T *list_stack = NULL; list_T *cur_l = l; for (;;) { // Mark each item in the list. If the item contains a hashtab // it is added to ht_stack, if it contains a list it is added to // list_stack. TV_LIST_ITER(cur_l, li, { if (abort) { break; } abort = set_ref_in_item(TV_LIST_ITEM_TV(li), copyID, ht_stack, &list_stack); }); if (list_stack == NULL) { break; } // take an item from the stack cur_l = list_stack->list; list_stack_T *tempitem = list_stack; list_stack = list_stack->prev; xfree(tempitem); } return abort; } /// Mark all lists and dicts referenced through typval "tv" with "copyID". /// /// @param tv Typval content will be marked. /// @param copyID New mark for lists and dicts. /// @param ht_stack Used to add hashtabs to be marked. Can be NULL. /// @param list_stack Used to add lists to be marked. Can be NULL. /// /// @returns true if setting references failed somehow. bool set_ref_in_item(typval_T *tv, int copyID, ht_stack_T **ht_stack, list_stack_T **list_stack) FUNC_ATTR_WARN_UNUSED_RESULT { bool abort = false; switch (tv->v_type) { case VAR_DICT: { dict_T *dd = tv->vval.v_dict; if (dd != NULL && dd->dv_copyID != copyID) { // Didn't see this dict yet. dd->dv_copyID = copyID; if (ht_stack == NULL) { abort = set_ref_in_ht(&dd->dv_hashtab, copyID, list_stack); } else { ht_stack_T *newitem = try_malloc(sizeof(ht_stack_T)); if (newitem == NULL) { abort = true; } else { newitem->ht = &dd->dv_hashtab; newitem->prev = *ht_stack; *ht_stack = newitem; } } QUEUE *w = NULL; DictWatcher *watcher = NULL; QUEUE_FOREACH(w, &dd->watchers) { watcher = tv_dict_watcher_node_data(w); set_ref_in_callback(&watcher->callback, copyID, ht_stack, list_stack); } } break; } case VAR_LIST: { list_T *ll = tv->vval.v_list; if (ll != NULL && ll->lv_copyID != copyID) { // Didn't see this list yet. ll->lv_copyID = copyID; if (list_stack == NULL) { abort = set_ref_in_list(ll, copyID, ht_stack); } else { list_stack_T *newitem = try_malloc(sizeof(list_stack_T)); if (newitem == NULL) { abort = true; } else { newitem->list = ll; newitem->prev = *list_stack; *list_stack = newitem; } } } break; } case VAR_PARTIAL: { partial_T *pt = tv->vval.v_partial; // A partial does not have a copyID, because it cannot contain itself. if (pt != NULL) { abort = set_ref_in_func(pt->pt_name, pt->pt_func, copyID); if (pt->pt_dict != NULL) { typval_T dtv; dtv.v_type = VAR_DICT; dtv.vval.v_dict = pt->pt_dict; abort = abort || set_ref_in_item(&dtv, copyID, ht_stack, list_stack); } for (int i = 0; i < pt->pt_argc; i++) { abort = abort || set_ref_in_item(&pt->pt_argv[i], copyID, ht_stack, list_stack); } } break; } case VAR_FUNC: abort = set_ref_in_func(tv->vval.v_string, NULL, copyID); break; case VAR_UNKNOWN: case VAR_SPECIAL: case VAR_FLOAT: case VAR_NUMBER: case VAR_STRING: { break; } } return abort; } /// Set "copyID" in all functions available by name. bool set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; bool abort = false; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; hi++) { if (!HASHITEM_EMPTY(hi)) { todo--; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name)) { abort = abort || set_ref_in_func(NULL, fp, copyID); } } } return abort; } /// Mark all lists and dicts referenced in given mark /// /// @returns true if setting references failed somehow. static inline bool set_ref_in_fmark(fmark_T fm, int copyID) FUNC_ATTR_WARN_UNUSED_RESULT { if (fm.additional_data != NULL && fm.additional_data->dv_copyID != copyID) { fm.additional_data->dv_copyID = copyID; return set_ref_in_ht(&fm.additional_data->dv_hashtab, copyID, NULL); } return false; } /// Mark all lists and dicts referenced in given list and the list itself /// /// @returns true if setting references failed somehow. static inline bool set_ref_list(list_T *list, int copyID) FUNC_ATTR_WARN_UNUSED_RESULT { if (list != NULL) { typval_T tv = (typval_T) { .v_type = VAR_LIST, .vval = { .v_list = list } }; return set_ref_in_item(&tv, copyID, NULL, NULL); } return false; } /// Mark all lists and dicts referenced in given dict and the dict itself /// /// @returns true if setting references failed somehow. static inline bool set_ref_dict(dict_T *dict, int copyID) FUNC_ATTR_WARN_UNUSED_RESULT { if (dict != NULL) { typval_T tv = (typval_T) { .v_type = VAR_DICT, .vval = { .v_dict = dict } }; return set_ref_in_item(&tv, copyID, NULL, NULL); } return false; } static bool set_ref_in_funccal(funccall_T *fc, int copyID) { bool abort = false; if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL); abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL); abort = abort || set_ref_in_func(NULL, fc->func, copyID); } return abort; } /* * Allocate a variable for a Dictionary and fill it from "*arg". * Return OK or FAIL. Returns NOTDONE for {expr}. */ static int dict_get_tv(char_u **arg, typval_T *rettv, int evaluate) { dict_T *d = NULL; typval_T tvkey; typval_T tv; char_u *key = NULL; dictitem_T *item; char_u *start = skipwhite(*arg + 1); char buf[NUMBUFLEN]; /* * First check if it's not a curly-braces thing: {expr}. * Must do this without evaluating, otherwise a function may be called * twice. Unfortunately this means we need to call eval1() twice for the * first item. * But {} is an empty Dictionary. */ if (*start != '}') { if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */ return FAIL; if (*start == '}') return NOTDONE; } if (evaluate) { d = tv_dict_alloc(); } tvkey.v_type = VAR_UNKNOWN; tv.v_type = VAR_UNKNOWN; *arg = skipwhite(*arg + 1); while (**arg != '}' && **arg != NUL) { if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */ goto failret; if (**arg != ':') { EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg); tv_clear(&tvkey); goto failret; } if (evaluate) { key = (char_u *)tv_get_string_buf_chk(&tvkey, buf); if (key == NULL) { // "key" is NULL when tv_get_string_buf_chk() gave an errmsg tv_clear(&tvkey); goto failret; } } *arg = skipwhite(*arg + 1); if (eval1(arg, &tv, evaluate) == FAIL) { // Recursive! if (evaluate) { tv_clear(&tvkey); } goto failret; } if (evaluate) { item = tv_dict_find(d, (const char *)key, -1); if (item != NULL) { EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key); tv_clear(&tvkey); tv_clear(&tv); goto failret; } item = tv_dict_item_alloc((const char *)key); tv_clear(&tvkey); item->di_tv = tv; item->di_tv.v_lock = 0; if (tv_dict_add(d, item) == FAIL) { tv_dict_item_free(item); } } if (**arg == '}') break; if (**arg != ',') { EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg); goto failret; } *arg = skipwhite(*arg + 1); } if (**arg != '}') { EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg); failret: if (evaluate) { tv_dict_free(d); } return FAIL; } *arg = skipwhite(*arg + 1); if (evaluate) { tv_dict_set_ret(rettv, d); } return OK; } /// Get function arguments. static int get_function_args(char_u **argp, char_u endchar, garray_T *newargs, int *varargs, bool skip) { bool mustend = false; char_u *arg = *argp; char_u *p = arg; int c; int i; if (newargs != NULL) { ga_init(newargs, (int)sizeof(char_u *), 3); } if (varargs != NULL) { *varargs = false; } // Isolate the arguments: "arg1, arg2, ...)" while (*p != endchar) { if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) { *varargs = true; } p += 3; mustend = true; } else { arg = p; while (ASCII_ISALNUM(*p) || *p == '_') { p++; } if (arg == p || isdigit(*arg) || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)) { if (!skip) { EMSG2(_("E125: Illegal argument: %s"), arg); } break; } if (newargs != NULL) { ga_grow(newargs, 1); c = *p; *p = NUL; arg = vim_strsave(arg); // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; i++) { if (STRCMP(((char_u **)(newargs->ga_data))[i], arg) == 0) { EMSG2(_("E853: Duplicate argument name: %s"), arg); xfree(arg); goto err_ret; } } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg; newargs->ga_len++; *p = c; } if (*p == ',') { p++; } else { mustend = true; } } p = skipwhite(p); if (mustend && *p != endchar) { if (!skip) { EMSG2(_(e_invarg2), *argp); } break; } } if (*p != endchar) { goto err_ret; } p++; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) { ga_clear_strings(newargs); } return FAIL; } /// Register function "fp" as using "current_funccal" as its scope. static void register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) { // no change return; } funccal_unref(fp->uf_scoped, fp, false); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; ga_grow(¤t_funccal->fc_funcs, 1); ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; } /// Parse a lambda expression and get a Funcref from "*arg". /// /// @return OK or FAIL. Returns NOTDONE for dict or {expr}. static int get_lambda_tv(char_u **arg, typval_T *rettv, bool evaluate) { garray_T newargs = GA_EMPTY_INIT_VALUE; garray_T *pnewargs; ufunc_T *fp = NULL; int varargs; int ret; char_u *start = skipwhite(*arg + 1); char_u *s, *e; static int lambda_no = 0; int *old_eval_lavars = eval_lavars_used; int eval_lavars = false; // First, check if this is a lambda expression. "->" must exists. ret = get_function_args(&start, '-', NULL, NULL, true); if (ret == FAIL || *start != '>') { return NOTDONE; } // Parse the arguments again. if (evaluate) { pnewargs = &newargs; } else { pnewargs = NULL; } *arg = skipwhite(*arg + 1); ret = get_function_args(arg, '-', pnewargs, &varargs, false); if (ret == FAIL || **arg != '>') { goto errret; } // Set up a flag for checking local variables and arguments. if (evaluate) { eval_lavars_used = &eval_lavars; } // Get the start and the end of the expression. *arg = skipwhite(*arg + 1); s = *arg; ret = skip_expr(arg); if (ret == FAIL) { goto errret; } e = *arg; *arg = skipwhite(*arg); if (**arg != '}') { goto errret; } (*arg)++; if (evaluate) { int len, flags = 0; char_u *p; char_u name[20]; partial_T *pt; garray_T newlines; lambda_no++; snprintf((char *)name, sizeof(name), "%d", lambda_no); fp = xcalloc(1, offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); pt = xcalloc(1, sizeof(partial_T)); ga_init(&newlines, (int)sizeof(char_u *), 1); ga_grow(&newlines, 1); // Add "return " before the expression. len = 7 + e - s + 1; p = (char_u *)xmalloc(len); ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); STRLCPY(p + 7, s, e - s + 1); fp->uf_refcount = 1; STRCPY(fp->uf_name, name); hash_add(&func_hashtab, UF2HIKEY(fp)); fp->uf_args = newargs; fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; register_closure(fp); } else { fp->uf_scoped = NULL; } if (prof_def_func()) { func_do_profile(fp); } if (sandbox) { flags |= FC_SANDBOX; } fp->uf_varargs = true; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += sourcing_lnum - newlines.ga_len; pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; } eval_lavars_used = old_eval_lavars; return OK; errret: ga_clear_strings(&newargs); xfree(fp); eval_lavars_used = old_eval_lavars; return FAIL; } /// Convert the string to a floating point number /// /// This uses strtod(). setlocale(LC_NUMERIC, "C") has been used earlier to /// make sure this always uses a decimal point. /// /// @param[in] text String to convert. /// @param[out] ret_value Location where conversion result is saved. /// /// @return Length of the text that was consumed. size_t string2float(const char *const text, float_T *const ret_value) FUNC_ATTR_NONNULL_ALL { char *s = NULL; // MS-Windows does not deal with "inf" and "nan" properly if (STRNICMP(text, "inf", 3) == 0) { *ret_value = INFINITY; return 3; } if (STRNICMP(text, "-inf", 3) == 0) { *ret_value = -INFINITY; return 4; } if (STRNICMP(text, "nan", 3) == 0) { *ret_value = NAN; return 3; } *ret_value = strtod(text, &s); return (size_t) (s - text); } /// Get the value of an environment variable. /// /// If the environment variable was not set, silently assume it is empty. /// /// @param arg Points to the '$'. It is advanced to after the name. /// @return FAIL if the name is invalid. /// static int get_env_tv(char_u **arg, typval_T *rettv, int evaluate) { char_u *name; char_u *string = NULL; int len; int cc; ++*arg; name = *arg; len = get_env_len((const char_u **)arg); if (evaluate) { if (len == 0) { return FAIL; // Invalid empty name. } cc = name[len]; name[len] = NUL; // First try vim_getenv(), fast for normal environment vars. string = (char_u *)vim_getenv((char *)name); if (string == NULL || *string == NUL) { xfree(string); // Next try expanding things like $VIM and ${HOME}. string = expand_env_save(name - 1); if (string != NULL && *string == '$') { XFREE_CLEAR(string); } } name[len] = cc; rettv->v_type = VAR_STRING; rettv->vval.v_string = string; } return OK; } #ifdef INCLUDE_GENERATED_DECLARATIONS #ifdef _MSC_VER // This prevents MSVC from replacing the functions with intrinsics, // and causing errors when trying to get their addresses in funcs.generated.h #pragma function (ceil) #pragma function (floor) #endif PRAGMA_DIAG_PUSH_IGNORE_MISSING_PROTOTYPES # include "funcs.generated.h" PRAGMA_DIAG_POP #endif /* * Function given to ExpandGeneric() to obtain the list of internal * or user defined function names. */ char_u *get_function_name(expand_T *xp, int idx) { static int intidx = -1; char_u *name; if (idx == 0) intidx = -1; if (intidx < 0) { name = get_user_func_name(xp, idx); if (name != NULL) return name; } while ( (size_t)++intidx < ARRAY_SIZE(functions) && functions[intidx].name[0] == '\0') { } if ((size_t)intidx >= ARRAY_SIZE(functions)) { return NULL; } const char *const key = functions[intidx].name; const size_t key_len = strlen(key); memcpy(IObuff, key, key_len); IObuff[key_len] = '('; if (functions[intidx].max_argc == 0) { IObuff[key_len + 1] = ')'; IObuff[key_len + 2] = NUL; } else { IObuff[key_len + 1] = NUL; } return IObuff; } /* * Function given to ExpandGeneric() to obtain the list of internal or * user defined variable or function names. */ char_u *get_expr_name(expand_T *xp, int idx) { static int intidx = -1; char_u *name; if (idx == 0) intidx = -1; if (intidx < 0) { name = get_function_name(xp, idx); if (name != NULL) return name; } return get_user_var_name(xp, ++intidx); } /// Find internal function in hash functions /// /// @param[in] name Name of the function. /// /// Returns pointer to the function definition or NULL if not found. static const VimLFuncDef *find_internal_func(const char *const name) FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL { size_t len = strlen(name); return find_internal_func_gperf(name, len); } /// Return name of the function corresponding to `name` /// /// If `name` points to variable that is either a function or partial then /// corresponding function name is returned. Otherwise it returns `name` itself. /// /// @param[in] name Function name to check. /// @param[in,out] lenp Location where length of the returned name is stored. /// Must be set to the length of the `name` argument. /// @param[out] partialp Location where partial will be stored if found /// function appears to be a partial. May be NULL if this /// is not needed. /// @param[in] no_autoload If true, do not source autoload scripts if function /// was not found. /// /// @return name of the function. static char_u *deref_func_name(const char *name, int *lenp, partial_T **const partialp, bool no_autoload) FUNC_ATTR_NONNULL_ARG(1, 2) { if (partialp != NULL) { *partialp = NULL; } dictitem_T *const v = find_var(name, (size_t)(*lenp), NULL, no_autoload); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { if (v->di_tv.vval.v_string == NULL) { // just in case *lenp = 0; return (char_u *)""; } *lenp = (int)STRLEN(v->di_tv.vval.v_string); return v->di_tv.vval.v_string; } if (v != NULL && v->di_tv.v_type == VAR_PARTIAL) { partial_T *const pt = v->di_tv.vval.v_partial; if (pt == NULL) { // just in case *lenp = 0; return (char_u *)""; } if (partialp != NULL) { *partialp = pt; } char_u *s = partial_name(pt); *lenp = (int)STRLEN(s); return s; } return (char_u *)name; } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ static int get_func_tv( char_u *name, // name of the function int len, // length of "name" typval_T *rettv, char_u **arg, // argument, pointing to the '(' linenr_T firstline, // first line of range linenr_T lastline, // last line of range int *doesrange, // return: function handled range int evaluate, partial_T *partial, // for extra arguments dict_T *selfdict // Dictionary for "self" ) { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */ int argcount = 0; /* number of arguments found */ /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { argp = skipwhite(argp + 1); // skip the '(' or ',' if (*argp == ')' || *argp == ',' || *argp == NUL) { break; } if (eval1(&argp, &argvars[argcount], evaluate) == FAIL) { ret = FAIL; break; } ++argcount; if (*argp != ',') break; } if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling garbagecollect_for_testing(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) { ga_init(&funcargs, (int)sizeof(typval_T *), 50); } for (i = 0; i < argcount; i++) { ga_grow(&funcargs, 1); ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } } ret = call_func(name, len, rettv, argcount, argvars, NULL, firstline, lastline, doesrange, evaluate, partial, selfdict); funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) { emsg_funcname(N_("E740: Too many arguments for function %s"), name); } else { emsg_funcname(N_("E116: Invalid arguments for function %s"), name); } } while (--argcount >= 0) { tv_clear(&argvars[argcount]); } *arg = skipwhite(argp); return ret; } typedef enum { ERROR_UNKNOWN = 0, ERROR_TOOMANY, ERROR_TOOFEW, ERROR_SCRIPT, ERROR_DICT, ERROR_NONE, ERROR_OTHER, ERROR_BOTH, ERROR_DELETED, } FnameTransError; #define FLEN_FIXED 40 /// In a script transform script-local names into actually used names /// /// Transforms "" and "s:" prefixes to `K_SNR {N}` (e.g. K_SNR "123") and /// "" prefix to `K_SNR`. Uses `fname_buf` buffer that is supposed to have /// #FLEN_FIXED + 1 length when it fits, otherwise it allocates memory. /// /// @param[in] name Name to transform. /// @param fname_buf Buffer to save resulting function name to, if it fits. /// Must have at least #FLEN_FIXED + 1 length. /// @param[out] tofree Location where pointer to an allocated memory is saved /// in case result does not fit into fname_buf. /// @param[out] error Location where error type is saved, @see /// FnameTransError. /// /// @return transformed name: either `fname_buf` or a pointer to an allocated /// memory. static char_u *fname_trans_sid(const char_u *const name, char_u *const fname_buf, char_u **const tofree, int *const error) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT { char_u *fname; const int llen = eval_fname_script((const char *)name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; int i = 3; if (eval_fname_sid((const char *)name)) { // "" or "s:" if (current_sctx.sc_sid <= 0) { *error = ERROR_SCRIPT; } else { snprintf((char *)fname_buf + 3, FLEN_FIXED + 1, "%" PRId64 "_", (int64_t)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = xmalloc(i + STRLEN(name + llen) + 1); *tofree = fname; memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } else { fname = (char_u *)name; } return fname; } /// Mark all lists and dicts referenced through function "name" with "copyID". /// "list_stack" is used to add lists to be marked. Can be NULL. /// "ht_stack" is used to add hashtabs to be marked. Can be NULL. /// /// @return true if setting references failed somehow. bool set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = ERROR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; bool abort = false; if (name == NULL && fp_in == NULL) { return false; } if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) { abort = abort || set_ref_in_funccal(fc, copyID); } } xfree(tofree); return abort; } /// Call a function with its resolved parameters /// /// "argv_func", when not NULL, can be used to fill in arguments only when the /// invoked function uses them. It is called like this: /// new_argcount = argv_func(current_argcount, argv, called_func_argcount) /// /// @return FAIL if function cannot be called, else OK (even if an error /// occurred while executing the function! Set `msg_list` to capture /// the error, see do_cmdline()). int call_func( const char_u *funcname, // name of the function int len, // length of "name" typval_T *rettv, // [out] value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! ArgvFunc argv_func, // function to fill in argvars linenr_T firstline, // first line of range linenr_T lastline, // last line of range int *doesrange, // [out] function handled range bool evaluate, partial_T *partial, // optional, can be NULL dict_T *selfdict_in // Dictionary for "self" ) FUNC_ATTR_NONNULL_ARG(1, 3, 5, 9) { int ret = FAIL; int error = ERROR_NONE; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; char_u *name; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = selfdict_in; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" is not NULL int argv_clear = 0; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; // Make a copy of the name, if it comes from a funcref variable it could // be changed or deleted in the called function. name = vim_strnsave(funcname, len); fname = fname_trans_sid(name, fname_buf, &tofree, &error); *doesrange = false; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict_in == NULL || !partial->pt_auto)) { selfdict = partial->pt_dict; } if (error == ERROR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; argv_clear++) { tv_copy(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (int i = 0; i < argcount_in; i++) { argv[i + argv_clear] = argvars_in[i]; } argvars = argv; argcount = partial->pt_argc + argcount_in; } } if (error == ERROR_NONE && evaluate) { char_u *rfname = fname; /* Ignore "g:" before a function name. */ if (fname[0] == 'g' && fname[1] == ':') { rfname = fname + 2; } rettv->v_type = VAR_NUMBER; /* default rettv is number zero */ rettv->vval.v_number = 0; error = ERROR_UNKNOWN; if (!builtin_function((const char *)rfname, -1)) { // User defined function. if (partial != NULL && partial->pt_func != NULL) { fp = partial->pt_func; } else { fp = find_func(rfname); } // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { /* executed an autocommand, search for the function again */ fp = find_func(rfname); } // Try loading a package. if (fp == NULL && script_autoload((const char *)rfname, STRLEN(rfname), true) && !aborting()) { // Loaded a package, search for the function again. fp = find_func(rfname); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) { error = ERROR_DELETED; } else if (fp != NULL) { if (argv_func != NULL) { argcount = argv_func(argcount, argvars, fp->uf_args.ga_len); } if (fp->uf_flags & FC_RANGE) { *doesrange = true; } if (argcount < fp->uf_args.ga_len) { error = ERROR_TOOFEW; } else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len) { error = ERROR_TOOMANY; } else if ((fp->uf_flags & FC_DICT) && selfdict == NULL) { error = ERROR_DICT; } else { // Call the user function. call_user_func(fp, argcount, argvars, rettv, firstline, lastline, (fp->uf_flags & FC_DICT) ? selfdict : NULL); error = ERROR_NONE; } } } else { // Find the function name in the table, call its implementation. const VimLFuncDef *const fdef = find_internal_func((const char *)fname); if (fdef != NULL) { if (argcount < fdef->min_argc) { error = ERROR_TOOFEW; } else if (argcount > fdef->max_argc) { error = ERROR_TOOMANY; } else { argvars[argcount].v_type = VAR_UNKNOWN; fdef->func(argvars, rettv, fdef->data); error = ERROR_NONE; } } } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == ERROR_NONE) ret = OK; /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { switch (error) { case ERROR_UNKNOWN: emsg_funcname(N_("E117: Unknown function: %s"), name); break; case ERROR_DELETED: emsg_funcname(N_("E933: Function was deleted: %s"), name); break; case ERROR_TOOMANY: emsg_funcname(e_toomanyarg, name); break; case ERROR_TOOFEW: emsg_funcname(N_("E119: Not enough arguments for function: %s"), name); break; case ERROR_SCRIPT: emsg_funcname(N_("E120: Using not in a script context: %s"), name); break; case ERROR_DICT: emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"), name); break; } } while (argv_clear > 0) { tv_clear(&argv[--argv_clear]); } xfree(tofree); xfree(name); return ret; } /// Give an error message with a function name. Handle things. /// /// @param ermsg must be passed without translation (use N_() instead of _()). /// @param name function name static void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) { p = concat_str((char_u *)"", name + 3); } else { p = name; } EMSG2(_(ermsg), p); if (p != name) { xfree(p); } } /* * Return TRUE for a non-zero Number and a non-empty String. */ static int non_zero_arg(typval_T *argvars) { return ((argvars[0].v_type == VAR_NUMBER && argvars[0].vval.v_number != 0) || (argvars[0].v_type == VAR_SPECIAL && argvars[0].vval.v_special == kSpecialVarTrue) || (argvars[0].v_type == VAR_STRING && argvars[0].vval.v_string != NULL && *argvars[0].vval.v_string != NUL)); } /********************************************* * Implementation of the built-in functions */ // Apply a floating point C function on a typval with one float_T. // // Some versions of glibc on i386 have an optimization that makes it harder to // call math functions indirectly from inside an inlined function, causing // compile-time errors. Avoid `inline` in that case. #3072 static void float_op_wrapper(typval_T *argvars, typval_T *rettv, FunPtr fptr) { float_T f; float_T (*function)(float_T) = (float_T (*)(float_T))fptr; rettv->v_type = VAR_FLOAT; if (tv_get_float_chk(argvars, &f)) { rettv->vval.v_float = function(f); } else { rettv->vval.v_float = 0.0; } } static void api_wrapper(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (check_restricted() || check_secure()) { return; } ApiDispatchWrapper fn = (ApiDispatchWrapper)fptr; Array args = ARRAY_DICT_INIT; for (typval_T *tv = argvars; tv->v_type != VAR_UNKNOWN; tv++) { ADD(args, vim_to_object(tv)); } Error err = ERROR_INIT; Object result = fn(VIML_INTERNAL_CALL, args, &err); if (ERROR_SET(&err)) { emsgf_multiline((const char *)e_api_error, err.msg); goto end; } if (!object_to_vim(result, rettv, &err)) { EMSG2(_("Error converting the call result: %s"), err.msg); } end: api_free_array(args); api_free_object(result); api_clear_error(&err); } /* * "abs(expr)" function */ static void f_abs(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type == VAR_FLOAT) { float_op_wrapper(argvars, rettv, (FunPtr)&fabs); } else { varnumber_T n; bool error = false; n = tv_get_number_chk(&argvars[0], &error); if (error) { rettv->vval.v_number = -1; } else if (n > 0) { rettv->vval.v_number = n; } else { rettv->vval.v_number = -n; } } } /* * "add(list, item)" function */ static void f_add(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = 1; // Default: failed. if (argvars[0].v_type == VAR_LIST) { list_T *const l = argvars[0].vval.v_list; if (!tv_check_lock(tv_list_locked(l), N_("add() argument"), TV_TRANSLATE)) { tv_list_append_tv(l, &argvars[1]); tv_copy(&argvars[0], rettv); } } else { EMSG(_(e_listreq)); } } /* * "and(expr, expr)" function */ static void f_and(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = tv_get_number_chk(&argvars[0], NULL) & tv_get_number_chk(&argvars[1], NULL); } /// "api_info()" function static void f_api_info(typval_T *argvars, typval_T *rettv, FunPtr fptr) { Dictionary metadata = api_metadata(); (void)object_to_vim(DICTIONARY_OBJ(metadata), rettv, NULL); api_free_dictionary(metadata); } // "append(lnum, string/list)" function static void f_append(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const linenr_T lnum = tv_get_lnum(&argvars[0]); set_buffer_lines(curbuf, lnum, true, &argvars[1], rettv); } // "appendbufline(buf, lnum, string/list)" function static void f_appendbufline(typval_T *argvars, typval_T *rettv, FunPtr fptr) { buf_T *const buf = tv_get_buf(&argvars[0], false); if (buf == NULL) { rettv->vval.v_number = 1; // FAIL } else { const linenr_T lnum = tv_get_lnum_buf(&argvars[1], buf); set_buffer_lines(buf, lnum, true, &argvars[2], rettv); } } static void f_argc(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type == VAR_UNKNOWN) { // use the current window rettv->vval.v_number = ARGCOUNT; } else if (argvars[0].v_type == VAR_NUMBER && tv_get_number(&argvars[0]) == -1) { // use the global argument list rettv->vval.v_number = GARGCOUNT; } else { // use the argument list of the specified window win_T *wp = find_win_by_nr_or_id(&argvars[0]); if (wp != NULL) { rettv->vval.v_number = WARGCOUNT(wp); } else { rettv->vval.v_number = -1; } } } /* * "argidx()" function */ static void f_argidx(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = curwin->w_arg_idx; } /// "arglistid" function static void f_arglistid(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = -1; win_T *wp = find_tabwin(&argvars[0], &argvars[1]); if (wp != NULL) { rettv->vval.v_number = wp->w_alist->id; } } /// Get the argument list for a given window static void get_arglist_as_rettv(aentry_T *arglist, int argcount, typval_T *rettv) { tv_list_alloc_ret(rettv, argcount); if (arglist != NULL) { for (int idx = 0; idx < argcount; idx++) { tv_list_append_string(rettv->vval.v_list, (const char *)alist_name(&arglist[idx]), -1); } } } /* * "argv(nr)" function */ static void f_argv(typval_T *argvars, typval_T *rettv, FunPtr fptr) { aentry_T *arglist = NULL; int argcount = -1; if (argvars[0].v_type != VAR_UNKNOWN) { if (argvars[1].v_type == VAR_UNKNOWN) { arglist = ARGLIST; argcount = ARGCOUNT; } else if (argvars[1].v_type == VAR_NUMBER && tv_get_number(&argvars[1]) == -1) { arglist = GARGLIST; argcount = GARGCOUNT; } else { win_T *wp = find_win_by_nr_or_id(&argvars[1]); if (wp != NULL) { // Use the argument list of the specified window arglist = WARGLIST(wp); argcount = WARGCOUNT(wp); } } rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; int idx = tv_get_number_chk(&argvars[0], NULL); if (arglist != NULL && idx >= 0 && idx < argcount) { rettv->vval.v_string = (char_u *)xstrdup( (const char *)alist_name(&arglist[idx])); } else if (idx == -1) { get_arglist_as_rettv(arglist, argcount, rettv); } } else { get_arglist_as_rettv(ARGLIST, ARGCOUNT, rettv); } } // Prepare "gap" for an assert error and add the sourcing position. static void prepare_assert_error(garray_T *gap) { char buf[NUMBUFLEN]; ga_init(gap, 1, 100); if (sourcing_name != NULL) { ga_concat(gap, sourcing_name); if (sourcing_lnum > 0) { ga_concat(gap, (char_u *)" "); } } if (sourcing_lnum > 0) { vim_snprintf(buf, ARRAY_SIZE(buf), "line %" PRId64, (int64_t)sourcing_lnum); ga_concat(gap, (char_u *)buf); } if (sourcing_name != NULL || sourcing_lnum > 0) { ga_concat(gap, (char_u *)": "); } } // Append "str" to "gap", escaping unprintable characters. // Changes NL to \n, CR to \r, etc. static void ga_concat_esc(garray_T *gap, char_u *str) { char_u *p; char_u buf[NUMBUFLEN]; if (str == NULL) { ga_concat(gap, (char_u *)"NULL"); return; } for (p = str; *p != NUL; p++) { switch (*p) { case BS: ga_concat(gap, (char_u *)"\\b"); break; case ESC: ga_concat(gap, (char_u *)"\\e"); break; case FF: ga_concat(gap, (char_u *)"\\f"); break; case NL: ga_concat(gap, (char_u *)"\\n"); break; case TAB: ga_concat(gap, (char_u *)"\\t"); break; case CAR: ga_concat(gap, (char_u *)"\\r"); break; case '\\': ga_concat(gap, (char_u *)"\\\\"); break; default: if (*p < ' ') { vim_snprintf((char *)buf, NUMBUFLEN, "\\x%02x", *p); ga_concat(gap, buf); } else { ga_append(gap, *p); } break; } } } // Fill "gap" with information about an assert error. static void fill_assert_error(garray_T *gap, typval_T *opt_msg_tv, char_u *exp_str, typval_T *exp_tv, typval_T *got_tv, assert_type_T atype) { char_u *tofree; if (opt_msg_tv->v_type != VAR_UNKNOWN) { tofree = (char_u *)encode_tv2echo(opt_msg_tv, NULL); ga_concat(gap, tofree); xfree(tofree); ga_concat(gap, (char_u *)": "); } if (atype == ASSERT_MATCH || atype == ASSERT_NOTMATCH) { ga_concat(gap, (char_u *)"Pattern "); } else if (atype == ASSERT_NOTEQUAL) { ga_concat(gap, (char_u *)"Expected not equal to "); } else { ga_concat(gap, (char_u *)"Expected "); } if (exp_str == NULL) { tofree = (char_u *)encode_tv2string(exp_tv, NULL); ga_concat_esc(gap, tofree); xfree(tofree); } else { ga_concat_esc(gap, exp_str); } if (atype != ASSERT_NOTEQUAL) { if (atype == ASSERT_MATCH) { ga_concat(gap, (char_u *)" does not match "); } else if (atype == ASSERT_NOTMATCH) { ga_concat(gap, (char_u *)" does match "); } else { ga_concat(gap, (char_u *)" but got "); } tofree = (char_u *)encode_tv2string(got_tv, NULL); ga_concat_esc(gap, tofree); xfree(tofree); } } // Add an assert error to v:errors. static void assert_error(garray_T *gap) { struct vimvar *vp = &vimvars[VV_ERRORS]; if (vp->vv_type != VAR_LIST || vimvars[VV_ERRORS].vv_list == NULL) { // Make sure v:errors is a list. set_vim_var_list(VV_ERRORS, tv_list_alloc(1)); } tv_list_append_string(vimvars[VV_ERRORS].vv_list, (const char *)gap->ga_data, (ptrdiff_t)gap->ga_len); } static void assert_equal_common(typval_T *argvars, assert_type_T atype) { garray_T ga; if (tv_equal(&argvars[0], &argvars[1], false, false) != (atype == ASSERT_EQUAL)) { prepare_assert_error(&ga); fill_assert_error(&ga, &argvars[2], NULL, &argvars[0], &argvars[1], atype); assert_error(&ga); ga_clear(&ga); } } static void f_assert_beeps(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *const cmd = tv_get_string_chk(&argvars[0]); garray_T ga; called_vim_beep = false; suppress_errthrow = true; emsg_silent = false; do_cmdline_cmd(cmd); if (!called_vim_beep) { prepare_assert_error(&ga); ga_concat(&ga, (const char_u *)"command did not beep: "); ga_concat(&ga, (const char_u *)cmd); assert_error(&ga); ga_clear(&ga); } suppress_errthrow = false; emsg_on_display = false; } // "assert_equal(expected, actual[, msg])" function static void f_assert_equal(typval_T *argvars, typval_T *rettv, FunPtr fptr) { assert_equal_common(argvars, ASSERT_EQUAL); } // "assert_notequal(expected, actual[, msg])" function static void f_assert_notequal(typval_T *argvars, typval_T *rettv, FunPtr fptr) { assert_equal_common(argvars, ASSERT_NOTEQUAL); } /// "assert_report(msg) static void f_assert_report(typval_T *argvars, typval_T *rettv, FunPtr fptr) { garray_T ga; prepare_assert_error(&ga); ga_concat(&ga, (const char_u *)tv_get_string(&argvars[0])); assert_error(&ga); ga_clear(&ga); } /// "assert_exception(string[, msg])" function static void f_assert_exception(typval_T *argvars, typval_T *rettv, FunPtr fptr) { garray_T ga; const char *const error = tv_get_string_chk(&argvars[0]); if (vimvars[VV_EXCEPTION].vv_str == NULL) { prepare_assert_error(&ga); ga_concat(&ga, (char_u *)"v:exception is not set"); assert_error(&ga); ga_clear(&ga); } else if (error != NULL && strstr((char *)vimvars[VV_EXCEPTION].vv_str, error) == NULL) { prepare_assert_error(&ga); fill_assert_error(&ga, &argvars[1], NULL, &argvars[0], &vimvars[VV_EXCEPTION].vv_tv, ASSERT_OTHER); assert_error(&ga); ga_clear(&ga); } } /// "assert_fails(cmd [, error])" function static void f_assert_fails(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *const cmd = tv_get_string_chk(&argvars[0]); garray_T ga; int save_trylevel = trylevel; // trylevel must be zero for a ":throw" command to be considered failed trylevel = 0; called_emsg = false; suppress_errthrow = true; emsg_silent = true; do_cmdline_cmd(cmd); if (!called_emsg) { prepare_assert_error(&ga); ga_concat(&ga, (const char_u *)"command did not fail: "); ga_concat(&ga, (const char_u *)cmd); assert_error(&ga); ga_clear(&ga); } else if (argvars[1].v_type != VAR_UNKNOWN) { char buf[NUMBUFLEN]; const char *const error = tv_get_string_buf_chk(&argvars[1], buf); if (error == NULL || strstr((char *)vimvars[VV_ERRMSG].vv_str, error) == NULL) { prepare_assert_error(&ga); fill_assert_error(&ga, &argvars[2], NULL, &argvars[1], &vimvars[VV_ERRMSG].vv_tv, ASSERT_OTHER); assert_error(&ga); ga_clear(&ga); } } trylevel = save_trylevel; called_emsg = false; suppress_errthrow = false; emsg_silent = false; emsg_on_display = false; set_vim_var_string(VV_ERRMSG, NULL, 0); } void assert_inrange(typval_T *argvars) { bool error = false; const varnumber_T lower = tv_get_number_chk(&argvars[0], &error); const varnumber_T upper = tv_get_number_chk(&argvars[1], &error); const varnumber_T actual = tv_get_number_chk(&argvars[2], &error); if (error) { return; } if (actual < lower || actual > upper) { garray_T ga; prepare_assert_error(&ga); char msg[55]; vim_snprintf(msg, sizeof(msg), "range %" PRIdVARNUMBER " - %" PRIdVARNUMBER ",", lower, upper); fill_assert_error(&ga, &argvars[3], (char_u *)msg, NULL, &argvars[2], ASSERT_INRANGE); assert_error(&ga); ga_clear(&ga); } } // Common for assert_true() and assert_false(). static void assert_bool(typval_T *argvars, bool is_true) { bool error = false; garray_T ga; if ((argvars[0].v_type != VAR_NUMBER || (tv_get_number_chk(&argvars[0], &error) == 0) == is_true || error) && (argvars[0].v_type != VAR_SPECIAL || (argvars[0].vval.v_special != (SpecialVarValue) (is_true ? kSpecialVarTrue : kSpecialVarFalse)))) { prepare_assert_error(&ga); fill_assert_error(&ga, &argvars[1], (char_u *)(is_true ? "True" : "False"), NULL, &argvars[0], ASSERT_OTHER); assert_error(&ga); ga_clear(&ga); } } // "assert_false(actual[, msg])" function static void f_assert_false(typval_T *argvars, typval_T *rettv, FunPtr fptr) { assert_bool(argvars, false); } static void assert_match_common(typval_T *argvars, assert_type_T atype) { char buf1[NUMBUFLEN]; char buf2[NUMBUFLEN]; const char *const pat = tv_get_string_buf_chk(&argvars[0], buf1); const char *const text = tv_get_string_buf_chk(&argvars[1], buf2); if (pat == NULL || text == NULL) { EMSG(_(e_invarg)); } else if (pattern_match((char_u *)pat, (char_u *)text, false) != (atype == ASSERT_MATCH)) { garray_T ga; prepare_assert_error(&ga); fill_assert_error(&ga, &argvars[2], NULL, &argvars[0], &argvars[1], atype); assert_error(&ga); ga_clear(&ga); } } /// "assert_inrange(lower, upper[, msg])" function static void f_assert_inrange(typval_T *argvars, typval_T *rettv, FunPtr fptr) { assert_inrange(argvars); } /// "assert_match(pattern, actual[, msg])" function static void f_assert_match(typval_T *argvars, typval_T *rettv, FunPtr fptr) { assert_match_common(argvars, ASSERT_MATCH); } /// "assert_notmatch(pattern, actual[, msg])" function static void f_assert_notmatch(typval_T *argvars, typval_T *rettv, FunPtr fptr) { assert_match_common(argvars, ASSERT_NOTMATCH); } // "assert_true(actual[, msg])" function static void f_assert_true(typval_T *argvars, typval_T *rettv, FunPtr fptr) { assert_bool(argvars, true); } /* * "atan2()" function */ static void f_atan2(typval_T *argvars, typval_T *rettv, FunPtr fptr) { float_T fx; float_T fy; rettv->v_type = VAR_FLOAT; if (tv_get_float_chk(argvars, &fx) && tv_get_float_chk(&argvars[1], &fy)) { rettv->vval.v_float = atan2(fx, fy); } else { rettv->vval.v_float = 0.0; } } /* * "browse(save, title, initdir, default)" function */ static void f_browse(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_string = NULL; rettv->v_type = VAR_STRING; } /* * "browsedir(title, initdir)" function */ static void f_browsedir(typval_T *argvars, typval_T *rettv, FunPtr fptr) { f_browse(argvars, rettv, NULL); } /* * Find a buffer by number or exact name. */ static buf_T *find_buffer(typval_T *avar) { buf_T *buf = NULL; if (avar->v_type == VAR_NUMBER) buf = buflist_findnr((int)avar->vval.v_number); else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL) { buf = buflist_findname_exp(avar->vval.v_string); if (buf == NULL) { /* No full path name match, try a match with a URL or a "nofile" * buffer, these don't use the full path. */ FOR_ALL_BUFFERS(bp) { if (bp->b_fname != NULL && (path_with_url((char *)bp->b_fname) || bt_nofile(bp) ) && STRCMP(bp->b_fname, avar->vval.v_string) == 0) { buf = bp; break; } } } } return buf; } // "bufadd(expr)" function static void f_bufadd(typval_T *argvars, typval_T *rettv, FunPtr fptr) { char_u *name = (char_u *)tv_get_string(&argvars[0]); rettv->vval.v_number = buflist_add(*name == NUL ? NULL : name, 0); } /* * "bufexists(expr)" function */ static void f_bufexists(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL); } /* * "buflisted(expr)" function */ static void f_buflisted(typval_T *argvars, typval_T *rettv, FunPtr fptr) { buf_T *buf; buf = find_buffer(&argvars[0]); rettv->vval.v_number = (buf != NULL && buf->b_p_bl); } // "bufload(expr)" function static void f_bufload(typval_T *argvars, typval_T *unused, FunPtr fptr) { buf_T *buf = get_buf_arg(&argvars[0]); if (buf != NULL && buf->b_ml.ml_mfp == NULL) { aco_save_T aco; aucmd_prepbuf(&aco, buf); swap_exists_action = SEA_NONE; open_buffer(false, NULL, 0); aucmd_restbuf(&aco); } } /* * "bufloaded(expr)" function */ static void f_bufloaded(typval_T *argvars, typval_T *rettv, FunPtr fptr) { buf_T *buf; buf = find_buffer(&argvars[0]); rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL); } /* * Get buffer by number or pattern. */ static buf_T *tv_get_buf(typval_T *tv, int curtab_only) { char_u *name = tv->vval.v_string; int save_magic; char_u *save_cpo; buf_T *buf; if (tv->v_type == VAR_NUMBER) return buflist_findnr((int)tv->vval.v_number); if (tv->v_type != VAR_STRING) return NULL; if (name == NULL || *name == NUL) return curbuf; if (name[0] == '$' && name[1] == NUL) return lastbuf; // Ignore 'magic' and 'cpoptions' here to make scripts portable save_magic = p_magic; p_magic = TRUE; save_cpo = p_cpo; p_cpo = (char_u *)""; buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name), TRUE, FALSE, curtab_only)); p_magic = save_magic; p_cpo = save_cpo; // If not found, try expanding the name, like done for bufexists(). if (buf == NULL) { buf = find_buffer(tv); } return buf; } /// Get the buffer from "arg" and give an error and return NULL if it is not /// valid. static buf_T * get_buf_arg(typval_T *arg) { buf_T *buf; emsg_off++; buf = tv_get_buf(arg, false); emsg_off--; if (buf == NULL) { EMSG2(_("E158: Invalid buffer name: %s"), tv_get_string(arg)); } return buf; } /* * "bufname(expr)" function */ static void f_bufname(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const buf_T *buf; rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; if (argvars[0].v_type == VAR_UNKNOWN) { buf = curbuf; } else { if (!tv_check_str_or_nr(&argvars[0])) { return; } emsg_off++; buf = tv_get_buf(&argvars[0], false); emsg_off--; } if (buf != NULL && buf->b_fname != NULL) { rettv->vval.v_string = (char_u *)xstrdup((char *)buf->b_fname); } } /* * "bufnr(expr)" function */ static void f_bufnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const buf_T *buf; bool error = false; rettv->vval.v_number = -1; if (argvars[0].v_type == VAR_UNKNOWN) { buf = curbuf; } else { if (!tv_check_str_or_nr(&argvars[0])) { return; } emsg_off++; buf = tv_get_buf(&argvars[0], false); emsg_off--; } // If the buffer isn't found and the second argument is not zero create a // new buffer. const char *name; if (buf == NULL && argvars[1].v_type != VAR_UNKNOWN && tv_get_number_chk(&argvars[1], &error) != 0 && !error && (name = tv_get_string_chk(&argvars[0])) != NULL) { buf = buflist_new((char_u *)name, NULL, 1, 0); } if (buf != NULL) { rettv->vval.v_number = buf->b_fnum; } } static void buf_win_common(typval_T *argvars, typval_T *rettv, bool get_nr) { if (!tv_check_str_or_nr(&argvars[0])) { rettv->vval.v_number = -1; return; } emsg_off++; buf_T *buf = tv_get_buf(&argvars[0], true); if (buf == NULL) { // no need to search if buffer was not found rettv->vval.v_number = -1; goto end; } int winnr = 0; int winid; bool found_buf = false; FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { winnr++; if (wp->w_buffer == buf) { found_buf = true; winid = wp->handle; break; } } rettv->vval.v_number = (found_buf ? (get_nr ? winnr : winid) : -1); end: emsg_off--; } /// "bufwinid(nr)" function static void f_bufwinid(typval_T *argvars, typval_T *rettv, FunPtr fptr) { buf_win_common(argvars, rettv, false); } /// "bufwinnr(nr)" function static void f_bufwinnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) { buf_win_common(argvars, rettv, true); } /* * "byte2line(byte)" function */ static void f_byte2line(typval_T *argvars, typval_T *rettv, FunPtr fptr) { long boff = tv_get_number(&argvars[0]) - 1; if (boff < 0) { rettv->vval.v_number = -1; } else { rettv->vval.v_number = (varnumber_T)ml_find_line_or_offset(curbuf, 0, &boff, false); } } static void byteidx(typval_T *argvars, typval_T *rettv, int comp) { const char *const str = tv_get_string_chk(&argvars[0]); varnumber_T idx = tv_get_number_chk(&argvars[1], NULL); rettv->vval.v_number = -1; if (str == NULL || idx < 0) { return; } const char *t = str; for (; idx > 0; idx--) { if (*t == NUL) { // EOL reached. return; } if (enc_utf8 && comp) { t += utf_ptr2len((const char_u *)t); } else { t += (*mb_ptr2len)((const char_u *)t); } } rettv->vval.v_number = (varnumber_T)(t - str); } /* * "byteidx()" function */ static void f_byteidx(typval_T *argvars, typval_T *rettv, FunPtr fptr) { byteidx(argvars, rettv, FALSE); } /* * "byteidxcomp()" function */ static void f_byteidxcomp(typval_T *argvars, typval_T *rettv, FunPtr fptr) { byteidx(argvars, rettv, TRUE); } int func_call(char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int dummy; int r = 0; TV_LIST_ITER(args->vval.v_list, item, { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { EMSG(_("E699: Too many arguments")); goto func_call_skip_call; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. tv_copy(TV_LIST_ITEM_TV(item), &argv[argc++]); }); r = call_func(name, (int)STRLEN(name), rettv, argc, argv, NULL, curwin->w_cursor.lnum, curwin->w_cursor.lnum, &dummy, true, partial, selfdict); func_call_skip_call: // Free the arguments. while (argc > 0) { tv_clear(&argv[--argc]); } return r; } /// "call(func, arglist [, dict])" function static void f_call(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[1].v_type != VAR_LIST) { EMSG(_(e_listreq)); return; } if (argvars[1].vval.v_list == NULL) { return; } char_u *func; partial_T *partial = NULL; dict_T *selfdict = NULL; if (argvars[0].v_type == VAR_FUNC) { func = argvars[0].vval.v_string; } else if (argvars[0].v_type == VAR_PARTIAL) { partial = argvars[0].vval.v_partial; func = partial_name(partial); } else { func = (char_u *)tv_get_string(&argvars[0]); } if (*func == NUL) { return; // type error or empty name } if (argvars[2].v_type != VAR_UNKNOWN) { if (argvars[2].v_type != VAR_DICT) { EMSG(_(e_dictreq)); return; } selfdict = argvars[2].vval.v_dict; } func_call(func, &argvars[1], partial, selfdict, rettv); } /* * "changenr()" function */ static void f_changenr(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = curbuf->b_u_seq_cur; } // "chanclose(id[, stream])" function static void f_chanclose(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; if (check_restricted() || check_secure()) { return; } if (argvars[0].v_type != VAR_NUMBER || (argvars[1].v_type != VAR_STRING && argvars[1].v_type != VAR_UNKNOWN)) { EMSG(_(e_invarg)); return; } ChannelPart part = kChannelPartAll; if (argvars[1].v_type == VAR_STRING) { char *stream = (char *)argvars[1].vval.v_string; if (!strcmp(stream, "stdin")) { part = kChannelPartStdin; } else if (!strcmp(stream, "stdout")) { part = kChannelPartStdout; } else if (!strcmp(stream, "stderr")) { part = kChannelPartStderr; } else if (!strcmp(stream, "rpc")) { part = kChannelPartRpc; } else { EMSG2(_("Invalid channel stream \"%s\""), stream); return; } } const char *error; rettv->vval.v_number = channel_close(argvars[0].vval.v_number, part, &error); if (!rettv->vval.v_number) { EMSG(error); } } // "chansend(id, data)" function static void f_chansend(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; if (check_restricted() || check_secure()) { return; } if (argvars[0].v_type != VAR_NUMBER || argvars[1].v_type == VAR_UNKNOWN) { // First argument is the channel id and second is the data to write EMSG(_(e_invarg)); return; } ptrdiff_t input_len = 0; char *input = save_tv_as_string(&argvars[1], &input_len, false); if (!input) { // Either the error has been handled by save_tv_as_string(), // or there is no input to send. return; } uint64_t id = argvars[0].vval.v_number; const char *error = NULL; rettv->vval.v_number = channel_send(id, input, input_len, &error); if (error) { EMSG(error); } } /* * "char2nr(string)" function */ static void f_char2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[1].v_type != VAR_UNKNOWN) { if (!tv_check_num(&argvars[1])) { return; } } rettv->vval.v_number = utf_ptr2char( (const char_u *)tv_get_string(&argvars[0])); } /* * "cindent(lnum)" function */ static void f_cindent(typval_T *argvars, typval_T *rettv, FunPtr fptr) { pos_T pos; linenr_T lnum; pos = curwin->w_cursor; lnum = tv_get_lnum(argvars); if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { curwin->w_cursor.lnum = lnum; rettv->vval.v_number = get_c_indent(); curwin->w_cursor = pos; } else rettv->vval.v_number = -1; } /* * "clearmatches()" function */ static void f_clearmatches(typval_T *argvars, typval_T *rettv, FunPtr fptr) { clear_matches(curwin); } /* * "col(string)" function */ static void f_col(typval_T *argvars, typval_T *rettv, FunPtr fptr) { colnr_T col = 0; pos_T *fp; int fnum = curbuf->b_fnum; fp = var2fpos(&argvars[0], FALSE, &fnum); if (fp != NULL && fnum == curbuf->b_fnum) { if (fp->col == MAXCOL) { /* '> can be MAXCOL, get the length of the line then */ if (fp->lnum <= curbuf->b_ml.ml_line_count) col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1; else col = MAXCOL; } else { col = fp->col + 1; /* col(".") when the cursor is on the NUL at the end of the line * because of "coladd" can be seen as an extra column. */ if (virtual_active() && fp == &curwin->w_cursor) { char_u *p = get_cursor_pos_ptr(); if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p, curwin->w_virtcol - curwin->w_cursor.coladd)) { int l; if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL) col += l; } } } } rettv->vval.v_number = col; } /* * "complete()" function */ static void f_complete(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if ((State & INSERT) == 0) { EMSG(_("E785: complete() can only be used in Insert mode")); return; } /* Check for undo allowed here, because if something was already inserted * the line was already saved for undo and this check isn't done. */ if (!undo_allowed()) return; if (argvars[1].v_type != VAR_LIST) { EMSG(_(e_invarg)); return; } const colnr_T startcol = tv_get_number_chk(&argvars[0], NULL); if (startcol <= 0) { return; } set_completion(startcol - 1, argvars[1].vval.v_list); } /* * "complete_add()" function */ static void f_complete_add(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0); } /* * "complete_check()" function */ static void f_complete_check(typval_T *argvars, typval_T *rettv, FunPtr fptr) { int saved = RedrawingDisabled; RedrawingDisabled = 0; ins_compl_check_keys(0, true); rettv->vval.v_number = compl_interrupted; RedrawingDisabled = saved; } // "complete_info()" function static void f_complete_info(typval_T *argvars, typval_T *rettv, FunPtr fptr) { tv_dict_alloc_ret(rettv); list_T *what_list = NULL; if (argvars[0].v_type != VAR_UNKNOWN) { if (argvars[0].v_type != VAR_LIST) { EMSG(_(e_listreq)); return; } what_list = argvars[0].vval.v_list; } get_complete_info(what_list, rettv->vval.v_dict); } /* * "confirm(message, buttons[, default [, type]])" function */ static void f_confirm(typval_T *argvars, typval_T *rettv, FunPtr fptr) { char buf[NUMBUFLEN]; char buf2[NUMBUFLEN]; const char *message; const char *buttons = NULL; int def = 1; int type = VIM_GENERIC; const char *typestr; bool error = false; message = tv_get_string_chk(&argvars[0]); if (message == NULL) { error = true; } if (argvars[1].v_type != VAR_UNKNOWN) { buttons = tv_get_string_buf_chk(&argvars[1], buf); if (buttons == NULL) { error = true; } if (argvars[2].v_type != VAR_UNKNOWN) { def = tv_get_number_chk(&argvars[2], &error); if (argvars[3].v_type != VAR_UNKNOWN) { typestr = tv_get_string_buf_chk(&argvars[3], buf2); if (typestr == NULL) { error = true; } else { switch (TOUPPER_ASC(*typestr)) { case 'E': type = VIM_ERROR; break; case 'Q': type = VIM_QUESTION; break; case 'I': type = VIM_INFO; break; case 'W': type = VIM_WARNING; break; case 'G': type = VIM_GENERIC; break; } } } } } if (buttons == NULL || *buttons == NUL) { buttons = _("&Ok"); } if (!error) { rettv->vval.v_number = do_dialog( type, NULL, (char_u *)message, (char_u *)buttons, def, NULL, false); } } /* * "copy()" function */ static void f_copy(typval_T *argvars, typval_T *rettv, FunPtr fptr) { var_item_copy(NULL, &argvars[0], rettv, false, 0); } /* * "count()" function */ static void f_count(typval_T *argvars, typval_T *rettv, FunPtr fptr) { long n = 0; int ic = 0; bool error = false; if (argvars[2].v_type != VAR_UNKNOWN) { ic = tv_get_number_chk(&argvars[2], &error); } if (argvars[0].v_type == VAR_STRING) { const char_u *expr = (char_u *)tv_get_string_chk(&argvars[1]); const char_u *p = argvars[0].vval.v_string; if (!error && expr != NULL && *expr != NUL && p != NULL) { if (ic) { const size_t len = STRLEN(expr); while (*p != NUL) { if (mb_strnicmp(p, expr, len) == 0) { n++; p += len; } else { MB_PTR_ADV(p); } } } else { char_u *next; while ((next = (char_u *)strstr((char *)p, (char *)expr)) != NULL) { n++; p = next + STRLEN(expr); } } } } else if (argvars[0].v_type == VAR_LIST) { listitem_T *li; list_T *l; long idx; if ((l = argvars[0].vval.v_list) != NULL) { li = tv_list_first(l); if (argvars[2].v_type != VAR_UNKNOWN) { if (argvars[3].v_type != VAR_UNKNOWN) { idx = tv_get_number_chk(&argvars[3], &error); if (!error) { li = tv_list_find(l, idx); if (li == NULL) { EMSGN(_(e_listidx), idx); } } } if (error) li = NULL; } for (; li != NULL; li = TV_LIST_ITEM_NEXT(l, li)) { if (tv_equal(TV_LIST_ITEM_TV(li), &argvars[1], ic, false)) { n++; } } } } else if (argvars[0].v_type == VAR_DICT) { int todo; dict_T *d; hashitem_T *hi; if ((d = argvars[0].vval.v_dict) != NULL) { if (argvars[2].v_type != VAR_UNKNOWN) { if (argvars[3].v_type != VAR_UNKNOWN) { EMSG(_(e_invarg)); } } todo = error ? 0 : (int)d->dv_hashtab.ht_used; for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { todo--; if (tv_equal(&TV_DICT_HI2DI(hi)->di_tv, &argvars[1], ic, false)) { n++; } } } } } else { EMSG2(_(e_listdictarg), "count()"); } rettv->vval.v_number = n; } /* * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function * * Checks the existence of a cscope connection. */ static void f_cscope_connection(typval_T *argvars, typval_T *rettv, FunPtr fptr) { int num = 0; const char *dbpath = NULL; const char *prepend = NULL; char buf[NUMBUFLEN]; if (argvars[0].v_type != VAR_UNKNOWN && argvars[1].v_type != VAR_UNKNOWN) { num = (int)tv_get_number(&argvars[0]); dbpath = tv_get_string(&argvars[1]); if (argvars[2].v_type != VAR_UNKNOWN) { prepend = tv_get_string_buf(&argvars[2], buf); } } rettv->vval.v_number = cs_connection(num, (char_u *)dbpath, (char_u *)prepend); } /// "ctxget([{index}])" function static void f_ctxget(typval_T *argvars, typval_T *rettv, FunPtr fptr) { size_t index = 0; if (argvars[0].v_type == VAR_NUMBER) { index = argvars[0].vval.v_number; } else if (argvars[0].v_type != VAR_UNKNOWN) { EMSG2(_(e_invarg2), "expected nothing or a Number as an argument"); return; } Context *ctx = ctx_get(index); if (ctx == NULL) { EMSG3(_(e_invargNval), "index", "out of bounds"); return; } Dictionary ctx_dict = ctx_to_dict(ctx); Error err = ERROR_INIT; object_to_vim(DICTIONARY_OBJ(ctx_dict), rettv, &err); api_free_dictionary(ctx_dict); api_clear_error(&err); } /// "ctxpop()" function static void f_ctxpop(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (!ctx_restore(NULL, kCtxAll)) { EMSG(_("Context stack is empty")); } } /// "ctxpush([{types}])" function static void f_ctxpush(typval_T *argvars, typval_T *rettv, FunPtr fptr) { int types = kCtxAll; if (argvars[0].v_type == VAR_LIST) { types = 0; TV_LIST_ITER(argvars[0].vval.v_list, li, { typval_T *tv_li = TV_LIST_ITEM_TV(li); if (tv_li->v_type == VAR_STRING) { if (strequal((char *)tv_li->vval.v_string, "regs")) { types |= kCtxRegs; } else if (strequal((char *)tv_li->vval.v_string, "jumps")) { types |= kCtxJumps; } else if (strequal((char *)tv_li->vval.v_string, "bufs")) { types |= kCtxBufs; } else if (strequal((char *)tv_li->vval.v_string, "gvars")) { types |= kCtxGVars; } else if (strequal((char *)tv_li->vval.v_string, "sfuncs")) { types |= kCtxSFuncs; } else if (strequal((char *)tv_li->vval.v_string, "funcs")) { types |= kCtxFuncs; } } }); } else if (argvars[0].v_type != VAR_UNKNOWN) { EMSG2(_(e_invarg2), "expected nothing or a List as an argument"); return; } ctx_save(NULL, types); } /// "ctxset({context}[, {index}])" function static void f_ctxset(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type != VAR_DICT) { EMSG2(_(e_invarg2), "expected dictionary as first argument"); return; } size_t index = 0; if (argvars[1].v_type == VAR_NUMBER) { index = argvars[1].vval.v_number; } else if (argvars[1].v_type != VAR_UNKNOWN) { EMSG2(_(e_invarg2), "expected nothing or a Number as second argument"); return; } Context *ctx = ctx_get(index); if (ctx == NULL) { EMSG3(_(e_invargNval), "index", "out of bounds"); return; } int save_did_emsg = did_emsg; did_emsg = false; Dictionary dict = vim_to_object(&argvars[0]).data.dictionary; Context tmp = CONTEXT_INIT; ctx_from_dict(dict, &tmp); if (did_emsg) { ctx_free(&tmp); } else { ctx_free(ctx); *ctx = tmp; } api_free_dictionary(dict); did_emsg = save_did_emsg; } /// "ctxsize()" function static void f_ctxsize(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = ctx_size(); } /// "cursor(lnum, col)" function, or /// "cursor(list)" /// /// Moves the cursor to the specified line and column. /// /// @returns 0 when the position could be set, -1 otherwise. static void f_cursor(typval_T *argvars, typval_T *rettv, FunPtr fptr) { long line, col; long coladd = 0; bool set_curswant = true; rettv->vval.v_number = -1; if (argvars[1].v_type == VAR_UNKNOWN) { pos_T pos; colnr_T curswant = -1; if (list2fpos(argvars, &pos, NULL, &curswant) == FAIL) { EMSG(_(e_invarg)); return; } line = pos.lnum; col = pos.col; coladd = pos.coladd; if (curswant >= 0) { curwin->w_curswant = curswant - 1; set_curswant = false; } } else { line = tv_get_lnum(argvars); col = (long)tv_get_number_chk(&argvars[1], NULL); if (argvars[2].v_type != VAR_UNKNOWN) { coladd = (long)tv_get_number_chk(&argvars[2], NULL); } } if (line < 0 || col < 0 || coladd < 0) { return; // type error; errmsg already given } if (line > 0) { curwin->w_cursor.lnum = line; } if (col > 0) { curwin->w_cursor.col = col - 1; } curwin->w_cursor.coladd = coladd; // Make sure the cursor is in a valid position. check_cursor(); // Correct cursor for multi-byte character. if (has_mbyte) { mb_adjust_cursor(); } curwin->w_set_curswant = set_curswant; rettv->vval.v_number = 0; } /* * "deepcopy()" function */ static void f_deepcopy(typval_T *argvars, typval_T *rettv, FunPtr fptr) { int noref = 0; if (argvars[1].v_type != VAR_UNKNOWN) { noref = tv_get_number_chk(&argvars[1], NULL); } if (noref < 0 || noref > 1) { EMSG(_(e_invarg)); } else { var_item_copy(NULL, &argvars[0], rettv, true, (noref == 0 ? get_copyID() : 0)); } } // "delete()" function static void f_delete(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = -1; if (check_restricted() || check_secure()) { return; } const char *const name = tv_get_string(&argvars[0]); if (*name == NUL) { EMSG(_(e_invarg)); return; } char nbuf[NUMBUFLEN]; const char *flags; if (argvars[1].v_type != VAR_UNKNOWN) { flags = tv_get_string_buf(&argvars[1], nbuf); } else { flags = ""; } if (*flags == NUL) { // delete a file rettv->vval.v_number = os_remove(name) == 0 ? 0 : -1; } else if (strcmp(flags, "d") == 0) { // delete an empty directory rettv->vval.v_number = os_rmdir(name) == 0 ? 0 : -1; } else if (strcmp(flags, "rf") == 0) { // delete a directory recursively rettv->vval.v_number = delete_recursive(name); } else { emsgf(_(e_invexpr2), flags); } } // dictwatcheradd(dict, key, funcref) function static void f_dictwatcheradd(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (check_restricted() || check_secure()) { return; } if (argvars[0].v_type != VAR_DICT) { emsgf(_(e_invarg2), "dict"); return; } else if (argvars[0].vval.v_dict == NULL) { const char *const arg_errmsg = _("dictwatcheradd() argument"); const size_t arg_errmsg_len = strlen(arg_errmsg); emsgf(_(e_readonlyvar), (int)arg_errmsg_len, arg_errmsg); return; } if (argvars[1].v_type != VAR_STRING && argvars[1].v_type != VAR_NUMBER) { emsgf(_(e_invarg2), "key"); return; } const char *const key_pattern = tv_get_string_chk(argvars + 1); if (key_pattern == NULL) { return; } const size_t key_pattern_len = strlen(key_pattern); Callback callback; if (!callback_from_typval(&callback, &argvars[2])) { emsgf(_(e_invarg2), "funcref"); return; } tv_dict_watcher_add(argvars[0].vval.v_dict, key_pattern, key_pattern_len, callback); } // dictwatcherdel(dict, key, funcref) function static void f_dictwatcherdel(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (check_restricted() || check_secure()) { return; } if (argvars[0].v_type != VAR_DICT) { emsgf(_(e_invarg2), "dict"); return; } if (argvars[2].v_type != VAR_FUNC && argvars[2].v_type != VAR_STRING) { emsgf(_(e_invarg2), "funcref"); return; } const char *const key_pattern = tv_get_string_chk(argvars + 1); if (key_pattern == NULL) { return; } Callback callback; if (!callback_from_typval(&callback, &argvars[2])) { return; } if (!tv_dict_watcher_remove(argvars[0].vval.v_dict, key_pattern, strlen(key_pattern), callback)) { EMSG("Couldn't find a watcher matching key and callback"); } callback_free(&callback); } /// "deletebufline()" function static void f_deletebufline(typval_T *argvars, typval_T *rettv, FunPtr fptr) { linenr_T last; buf_T *curbuf_save = NULL; win_T *curwin_save = NULL; buf_T *const buf = tv_get_buf(&argvars[0], false); if (buf == NULL) { rettv->vval.v_number = 1; // FAIL return; } const bool is_curbuf = buf == curbuf; const linenr_T first = tv_get_lnum_buf(&argvars[1], buf); if (argvars[2].v_type != VAR_UNKNOWN) { last = tv_get_lnum_buf(&argvars[2], buf); } else { last = first; } if (buf->b_ml.ml_mfp == NULL || first < 1 || first > buf->b_ml.ml_line_count || last < first) { rettv->vval.v_number = 1; // FAIL return; } if (!is_curbuf) { curbuf_save = curbuf; curwin_save = curwin; curbuf = buf; find_win_for_curbuf(); } if (last > curbuf->b_ml.ml_line_count) { last = curbuf->b_ml.ml_line_count; } const long count = last - first + 1; // When coming here from Insert mode, sync undo, so that this can be // undone separately from what was previously inserted. if (u_sync_once == 2) { u_sync_once = 1; // notify that u_sync() was called u_sync(true); } if (u_save(first - 1, last + 1) == FAIL) { rettv->vval.v_number = 1; // FAIL return; } for (linenr_T lnum = first; lnum <= last; lnum++) { ml_delete(first, true); } FOR_ALL_TAB_WINDOWS(tp, wp) { if (wp->w_buffer == buf) { if (wp->w_cursor.lnum > last) { wp->w_cursor.lnum -= count; } else if (wp->w_cursor.lnum> first) { wp->w_cursor.lnum = first; } if (wp->w_cursor.lnum > wp->w_buffer->b_ml.ml_line_count) { wp->w_cursor.lnum = wp->w_buffer->b_ml.ml_line_count; } } } check_cursor_col(); deleted_lines_mark(first, count); if (!is_curbuf) { curbuf = curbuf_save; curwin = curwin_save; } } /* * "did_filetype()" function */ static void f_did_filetype(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = did_filetype; } /* * "diff_filler()" function */ static void f_diff_filler(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = diff_check_fill(curwin, tv_get_lnum(argvars)); } /* * "diff_hlID()" function */ static void f_diff_hlID(typval_T *argvars, typval_T *rettv, FunPtr fptr) { linenr_T lnum = tv_get_lnum(argvars); static linenr_T prev_lnum = 0; static int changedtick = 0; static int fnum = 0; static int change_start = 0; static int change_end = 0; static hlf_T hlID = (hlf_T)0; int filler_lines; int col; if (lnum < 0) /* ignore type error in {lnum} arg */ lnum = 0; if (lnum != prev_lnum || changedtick != buf_get_changedtick(curbuf) || fnum != curbuf->b_fnum) { /* New line, buffer, change: need to get the values. */ filler_lines = diff_check(curwin, lnum); if (filler_lines < 0) { if (filler_lines == -1) { change_start = MAXCOL; change_end = -1; if (diff_find_change(curwin, lnum, &change_start, &change_end)) hlID = HLF_ADD; /* added line */ else hlID = HLF_CHD; /* changed line */ } else hlID = HLF_ADD; /* added line */ } else hlID = (hlf_T)0; prev_lnum = lnum; changedtick = buf_get_changedtick(curbuf); fnum = curbuf->b_fnum; } if (hlID == HLF_CHD || hlID == HLF_TXD) { col = tv_get_number(&argvars[1]) - 1; // Ignore type error in {col}. if (col >= change_start && col <= change_end) { hlID = HLF_TXD; // Changed text. } else { hlID = HLF_CHD; // Changed line. } } rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)(hlID + 1); } /* * "empty({expr})" function */ static void f_empty(typval_T *argvars, typval_T *rettv, FunPtr fptr) { bool n = true; switch (argvars[0].v_type) { case VAR_STRING: case VAR_FUNC: { n = argvars[0].vval.v_string == NULL || *argvars[0].vval.v_string == NUL; break; } case VAR_PARTIAL: { n = false; break; } case VAR_NUMBER: { n = argvars[0].vval.v_number == 0; break; } case VAR_FLOAT: { n = argvars[0].vval.v_float == 0.0; break; } case VAR_LIST: { n = (tv_list_len(argvars[0].vval.v_list) == 0); break; } case VAR_DICT: { n = (tv_dict_len(argvars[0].vval.v_dict) == 0); break; } case VAR_SPECIAL: { // Using switch to get warning if SpecialVarValue receives more values. switch (argvars[0].vval.v_special) { case kSpecialVarTrue: { n = false; break; } case kSpecialVarFalse: case kSpecialVarNull: { n = true; break; } } break; } case VAR_UNKNOWN: { internal_error("f_empty(UNKNOWN)"); break; } } rettv->vval.v_number = n; } /// "environ()" function static void f_environ(typval_T *argvars, typval_T *rettv, FunPtr fptr) { tv_dict_alloc_ret(rettv); for (int i = 0; ; i++) { // TODO(justinmk): use os_copyfullenv from #7202 ? char *envname = os_getenvname_at_index((size_t)i); if (envname == NULL) { break; } const char *value = os_getenv(envname); tv_dict_add_str(rettv->vval.v_dict, (char *)envname, STRLEN((char *)envname), value == NULL ? "" : value); xfree(envname); } } /* * "escape({string}, {chars})" function */ static void f_escape(typval_T *argvars, typval_T *rettv, FunPtr fptr) { char buf[NUMBUFLEN]; rettv->vval.v_string = vim_strsave_escaped( (const char_u *)tv_get_string(&argvars[0]), (const char_u *)tv_get_string_buf(&argvars[1], buf)); rettv->v_type = VAR_STRING; } /// "getenv()" function static void f_getenv(typval_T *argvars, typval_T *rettv, FunPtr fptr) { char_u *p = (char_u *)vim_getenv(tv_get_string(&argvars[0])); if (p == NULL) { rettv->v_type = VAR_SPECIAL; rettv->vval.v_number = kSpecialVarNull; return; } rettv->vval.v_string = p; rettv->v_type = VAR_STRING; } /* * "eval()" function */ static void f_eval(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *s = tv_get_string_chk(&argvars[0]); if (s != NULL) { s = (const char *)skipwhite((const char_u *)s); } const char *const expr_start = s; if (s == NULL || eval1((char_u **)&s, rettv, true) == FAIL) { if (expr_start != NULL && !aborting()) { EMSG2(_(e_invexpr2), expr_start); } need_clr_eos = FALSE; rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; } else if (*s != NUL) { EMSG(_(e_trailing)); } } /* * "eventhandler()" function */ static void f_eventhandler(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = vgetc_busy; } /* * "executable()" function */ static void f_executable(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *name = tv_get_string(&argvars[0]); // Check in $PATH and also check directly if there is a directory name rettv->vval.v_number = os_can_exe(name, NULL, true); } typedef struct { const list_T *const l; const listitem_T *li; } GetListLineCookie; static char_u *get_list_line(int c, void *cookie, int indent) { GetListLineCookie *const p = (GetListLineCookie *)cookie; const listitem_T *const item = p->li; if (item == NULL) { return NULL; } char buf[NUMBUFLEN]; const char *const s = tv_get_string_buf_chk(TV_LIST_ITEM_TV(item), buf); p->li = TV_LIST_ITEM_NEXT(p->l, item); return (char_u *)(s == NULL ? NULL : xstrdup(s)); } // "execute(command)" function static void f_execute(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const int save_msg_silent = msg_silent; const int save_emsg_silent = emsg_silent; const bool save_emsg_noredir = emsg_noredir; const bool save_redir_off = redir_off; garray_T *const save_capture_ga = capture_ga; const int save_msg_col = msg_col; bool echo_output = false; if (check_secure()) { return; } if (argvars[1].v_type != VAR_UNKNOWN) { char buf[NUMBUFLEN]; const char *const s = tv_get_string_buf_chk(&argvars[1], buf); if (s == NULL) { return; } if (*s == NUL) { echo_output = true; } if (strncmp(s, "silent", 6) == 0) { msg_silent++; } if (strcmp(s, "silent!") == 0) { emsg_silent = true; emsg_noredir = true; } } else { msg_silent++; } garray_T capture_local; ga_init(&capture_local, (int)sizeof(char), 80); capture_ga = &capture_local; redir_off = false; if (!echo_output) { msg_col = 0; // prevent leading spaces } if (argvars[0].v_type != VAR_LIST) { do_cmdline_cmd(tv_get_string(&argvars[0])); } else if (argvars[0].vval.v_list != NULL) { list_T *const list = argvars[0].vval.v_list; tv_list_ref(list); GetListLineCookie cookie = { .l = list, .li = tv_list_first(list), }; do_cmdline(NULL, get_list_line, (void *)&cookie, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT|DOCMD_KEYTYPED); tv_list_unref(list); } msg_silent = save_msg_silent; emsg_silent = save_emsg_silent; emsg_noredir = save_emsg_noredir; redir_off = save_redir_off; // "silent reg" or "silent echo x" leaves msg_col somewhere in the line. if (echo_output) { // When not working silently: put it in column zero. A following // "echon" will overwrite the message, unavoidably. msg_col = 0; } else { // When working silently: Put it back where it was, since nothing // should have been written. msg_col = save_msg_col; } ga_append(capture_ga, NUL); rettv->v_type = VAR_STRING; rettv->vval.v_string = capture_ga->ga_data; capture_ga = save_capture_ga; } /// "exepath()" function static void f_exepath(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *arg = tv_get_string(&argvars[0]); char *path = NULL; (void)os_can_exe(arg, &path, true); rettv->v_type = VAR_STRING; rettv->vval.v_string = (char_u *)path; } /// Find a window: When using a Window ID in any tab page, when using a number /// in the current tab page. win_T * find_win_by_nr_or_id(typval_T *vp) { int nr = (int)tv_get_number_chk(vp, NULL); if (nr >= LOWEST_WIN_ID) { return win_id2wp(vp); } return find_win_by_nr(vp, NULL); } /* * "exists()" function */ static void f_exists(typval_T *argvars, typval_T *rettv, FunPtr fptr) { int n = false; int len = 0; const char *p = tv_get_string(&argvars[0]); if (*p == '$') { // Environment variable. // First try "normal" environment variables (fast). if (os_env_exists(p + 1)) { n = true; } else { // Try expanding things like $VIM and ${HOME}. char_u *const exp = expand_env_save((char_u *)p); if (exp != NULL && *exp != '$') { n = true; } xfree(exp); } } else if (*p == '&' || *p == '+') { // Option. n = (get_option_tv(&p, NULL, true) == OK); if (*skipwhite((const char_u *)p) != NUL) { n = false; // Trailing garbage. } } else if (*p == '*') { // Internal or user defined function. n = function_exists(p + 1, false); } else if (*p == ':') { n = cmd_exists(p + 1); } else if (*p == '#') { if (p[1] == '#') { n = autocmd_supported(p + 2); } else { n = au_exists(p + 1); } } else { // Internal variable. typval_T tv; // get_name_len() takes care of expanding curly braces const char *name = p; char *tofree; len = get_name_len((const char **)&p, &tofree, true, false); if (len > 0) { if (tofree != NULL) { name = tofree; } n = (get_var_tv(name, len, &tv, NULL, false, true) == OK); if (n) { // Handle d.key, l[idx], f(expr). n = (handle_subscript(&p, &tv, true, false) == OK); if (n) { tv_clear(&tv); } } } if (*p != NUL) n = FALSE; xfree(tofree); } rettv->vval.v_number = n; } /* * "expand()" function */ static void f_expand(typval_T *argvars, typval_T *rettv, FunPtr fptr) { size_t len; char_u *errormsg; int options = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND; expand_T xpc; bool error = false; char_u *result; rettv->v_type = VAR_STRING; if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN && tv_get_number_chk(&argvars[2], &error) && !error) { tv_list_set_ret(rettv, NULL); } const char *s = tv_get_string(&argvars[0]); if (*s == '%' || *s == '#' || *s == '<') { emsg_off++; result = eval_vars((char_u *)s, (char_u *)s, &len, NULL, &errormsg, NULL); emsg_off--; if (rettv->v_type == VAR_LIST) { tv_list_alloc_ret(rettv, (result != NULL)); if (result != NULL) { tv_list_append_string(rettv->vval.v_list, (const char *)result, -1); } } else rettv->vval.v_string = result; } else { /* When the optional second argument is non-zero, don't remove matches * for 'wildignore' and don't put matches for 'suffixes' at the end. */ if (argvars[1].v_type != VAR_UNKNOWN && tv_get_number_chk(&argvars[1], &error)) { options |= WILD_KEEP_ALL; } if (!error) { ExpandInit(&xpc); xpc.xp_context = EXPAND_FILES; if (p_wic) { options += WILD_ICASE; } if (rettv->v_type == VAR_STRING) { rettv->vval.v_string = ExpandOne(&xpc, (char_u *)s, NULL, options, WILD_ALL); } else { ExpandOne(&xpc, (char_u *)s, NULL, options, WILD_ALL_KEEP); tv_list_alloc_ret(rettv, xpc.xp_numfiles); for (int i = 0; i < xpc.xp_numfiles; i++) { tv_list_append_string(rettv->vval.v_list, (const char *)xpc.xp_files[i], -1); } ExpandCleanup(&xpc); } } else { rettv->vval.v_string = NULL; } } } /// "menu_get(path [, modes])" function static void f_menu_get(typval_T *argvars, typval_T *rettv, FunPtr fptr) { tv_list_alloc_ret(rettv, kListLenMayKnow); int modes = MENU_ALL_MODES; if (argvars[1].v_type == VAR_STRING) { const char_u *const strmodes = (char_u *)tv_get_string(&argvars[1]); modes = get_menu_cmd_modes(strmodes, false, NULL, NULL); } menu_get((char_u *)tv_get_string(&argvars[0]), modes, rettv->vval.v_list); } /* * "extend(list, list [, idx])" function * "extend(dict, dict [, action])" function */ static void f_extend(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *const arg_errmsg = N_("extend() argument"); if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST) { long before; bool error = false; list_T *const l1 = argvars[0].vval.v_list; list_T *const l2 = argvars[1].vval.v_list; if (!tv_check_lock(tv_list_locked(l1), arg_errmsg, TV_TRANSLATE)) { listitem_T *item; if (argvars[2].v_type != VAR_UNKNOWN) { before = (long)tv_get_number_chk(&argvars[2], &error); if (error) { return; // Type error; errmsg already given. } if (before == tv_list_len(l1)) { item = NULL; } else { item = tv_list_find(l1, before); if (item == NULL) { EMSGN(_(e_listidx), before); return; } } } else { item = NULL; } tv_list_extend(l1, l2, item); tv_copy(&argvars[0], rettv); } } else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT) { dict_T *const d1 = argvars[0].vval.v_dict; dict_T *const d2 = argvars[1].vval.v_dict; if (d1 == NULL) { const bool locked = tv_check_lock(VAR_FIXED, arg_errmsg, TV_TRANSLATE); (void)locked; assert(locked == true); } else if (d2 == NULL) { // Do nothing tv_copy(&argvars[0], rettv); } else if (!tv_check_lock(d1->dv_lock, arg_errmsg, TV_TRANSLATE)) { const char *action = "force"; // Check the third argument. if (argvars[2].v_type != VAR_UNKNOWN) { const char *const av[] = { "keep", "force", "error" }; action = tv_get_string_chk(&argvars[2]); if (action == NULL) { return; // Type error; error message already given. } size_t i; for (i = 0; i < ARRAY_SIZE(av); i++) { if (strcmp(action, av[i]) == 0) { break; } } if (i == 3) { EMSG2(_(e_invarg2), action); return; } } tv_dict_extend(d1, d2, action); tv_copy(&argvars[0], rettv); } } else { EMSG2(_(e_listdictarg), "extend()"); } } /* * "feedkeys()" function */ static void f_feedkeys(typval_T *argvars, typval_T *rettv, FunPtr fptr) { // This is not allowed in the sandbox. If the commands would still be // executed in the sandbox it would be OK, but it probably happens later, // when "sandbox" is no longer set. if (check_secure()) { return; } const char *const keys = tv_get_string(&argvars[0]); char nbuf[NUMBUFLEN]; const char *flags = NULL; if (argvars[1].v_type != VAR_UNKNOWN) { flags = tv_get_string_buf(&argvars[1], nbuf); } nvim_feedkeys(cstr_as_string((char *)keys), cstr_as_string((char *)flags), true); } /// "filereadable()" function static void f_filereadable(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *const p = tv_get_string(&argvars[0]); rettv->vval.v_number = (*p && !os_isdir((const char_u *)p) && os_file_is_readable(p)); } /* * Return 0 for not writable, 1 for writable file, 2 for a dir which we have * rights to write into. */ static void f_filewritable(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *filename = tv_get_string(&argvars[0]); rettv->vval.v_number = os_file_is_writable(filename); } static void findfilendir(typval_T *argvars, typval_T *rettv, int find_what) { char_u *fresult = NULL; char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path; int count = 1; bool first = true; bool error = false; rettv->vval.v_string = NULL; rettv->v_type = VAR_STRING; const char *fname = tv_get_string(&argvars[0]); char pathbuf[NUMBUFLEN]; if (argvars[1].v_type != VAR_UNKNOWN) { const char *p = tv_get_string_buf_chk(&argvars[1], pathbuf); if (p == NULL) { error = true; } else { if (*p != NUL) { path = (char_u *)p; } if (argvars[2].v_type != VAR_UNKNOWN) { count = tv_get_number_chk(&argvars[2], &error); } } } if (count < 0) { tv_list_alloc_ret(rettv, kListLenUnknown); } if (*fname != NUL && !error) { do { if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST) xfree(fresult); fresult = find_file_in_path_option(first ? (char_u *)fname : NULL, first ? strlen(fname) : 0, 0, first, path, find_what, curbuf->b_ffname, (find_what == FINDFILE_DIR ? (char_u *)"" : curbuf->b_p_sua)); first = false; if (fresult != NULL && rettv->v_type == VAR_LIST) { tv_list_append_string(rettv->vval.v_list, (const char *)fresult, -1); } } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL); } if (rettv->v_type == VAR_STRING) rettv->vval.v_string = fresult; } /* * Implementation of map() and filter(). */ static void filter_map(typval_T *argvars, typval_T *rettv, int map) { typval_T *expr; list_T *l = NULL; dictitem_T *di; hashtab_T *ht; hashitem_T *hi; dict_T *d = NULL; typval_T save_val; typval_T save_key; int rem = false; int todo; char_u *ermsg = (char_u *)(map ? "map()" : "filter()"); const char *const arg_errmsg = (map ? N_("map() argument") : N_("filter() argument")); int save_did_emsg; int idx = 0; if (argvars[0].v_type == VAR_LIST) { tv_copy(&argvars[0], rettv); if ((l = argvars[0].vval.v_list) == NULL || (!map && tv_check_lock(tv_list_locked(l), arg_errmsg, TV_TRANSLATE))) { return; } } else if (argvars[0].v_type == VAR_DICT) { tv_copy(&argvars[0], rettv); if ((d = argvars[0].vval.v_dict) == NULL || (!map && tv_check_lock(d->dv_lock, arg_errmsg, TV_TRANSLATE))) { return; } } else { EMSG2(_(e_listdictarg), ermsg); return; } expr = &argvars[1]; // On type errors, the preceding call has already displayed an error // message. Avoid a misleading error message for an empty string that // was not passed as argument. if (expr->v_type != VAR_UNKNOWN) { prepare_vimvar(VV_VAL, &save_val); // We reset "did_emsg" to be able to detect whether an error // occurred during evaluation of the expression. save_did_emsg = did_emsg; did_emsg = FALSE; prepare_vimvar(VV_KEY, &save_key); if (argvars[0].v_type == VAR_DICT) { vimvars[VV_KEY].vv_type = VAR_STRING; ht = &d->dv_hashtab; hash_lock(ht); todo = (int)ht->ht_used; for (hi = ht->ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = TV_DICT_HI2DI(hi); if (map && (tv_check_lock(di->di_tv.v_lock, arg_errmsg, TV_TRANSLATE) || var_check_ro(di->di_flags, arg_errmsg, TV_TRANSLATE))) { break; } vimvars[VV_KEY].vv_str = vim_strsave(di->di_key); int r = filter_map_one(&di->di_tv, expr, map, &rem); tv_clear(&vimvars[VV_KEY].vv_tv); if (r == FAIL || did_emsg) { break; } if (!map && rem) { if (var_check_fixed(di->di_flags, arg_errmsg, TV_TRANSLATE) || var_check_ro(di->di_flags, arg_errmsg, TV_TRANSLATE)) { break; } tv_dict_item_remove(d, di); } } } hash_unlock(ht); } else { assert(argvars[0].v_type == VAR_LIST); vimvars[VV_KEY].vv_type = VAR_NUMBER; for (listitem_T *li = tv_list_first(l); li != NULL;) { if (map && tv_check_lock(TV_LIST_ITEM_TV(li)->v_lock, arg_errmsg, TV_TRANSLATE)) { break; } vimvars[VV_KEY].vv_nr = idx; if (filter_map_one(TV_LIST_ITEM_TV(li), expr, map, &rem) == FAIL || did_emsg) { break; } if (!map && rem) { li = tv_list_item_remove(l, li); } else { li = TV_LIST_ITEM_NEXT(l, li); } idx++; } } restore_vimvar(VV_KEY, &save_key); restore_vimvar(VV_VAL, &save_val); did_emsg |= save_did_emsg; } } static int filter_map_one(typval_T *tv, typval_T *expr, int map, int *remp) FUNC_ATTR_NONNULL_ARG(1, 2) { typval_T rettv; typval_T argv[3]; int retval = FAIL; tv_copy(tv, &vimvars[VV_VAL].vv_tv); argv[0] = vimvars[VV_KEY].vv_tv; argv[1] = vimvars[VV_VAL].vv_tv; if (eval_expr_typval(expr, argv, 2, &rettv) == FAIL) { goto theend; } if (map) { // map(): replace the list item value. tv_clear(tv); rettv.v_lock = 0; *tv = rettv; } else { bool error = false; // filter(): when expr is zero remove the item *remp = (tv_get_number_chk(&rettv, &error) == 0); tv_clear(&rettv); // On type error, nothing has been removed; return FAIL to stop the // loop. The error message was given by tv_get_number_chk(). if (error) { goto theend; } } retval = OK; theend: tv_clear(&vimvars[VV_VAL].vv_tv); return retval; } /* * "filter()" function */ static void f_filter(typval_T *argvars, typval_T *rettv, FunPtr fptr) { filter_map(argvars, rettv, FALSE); } /* * "finddir({fname}[, {path}[, {count}]])" function */ static void f_finddir(typval_T *argvars, typval_T *rettv, FunPtr fptr) { findfilendir(argvars, rettv, FINDFILE_DIR); } /* * "findfile({fname}[, {path}[, {count}]])" function */ static void f_findfile(typval_T *argvars, typval_T *rettv, FunPtr fptr) { findfilendir(argvars, rettv, FINDFILE_FILE); } /* * "float2nr({float})" function */ static void f_float2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr) { float_T f; if (tv_get_float_chk(argvars, &f)) { if (f <= -VARNUMBER_MAX + DBL_EPSILON) { rettv->vval.v_number = -VARNUMBER_MAX; } else if (f >= VARNUMBER_MAX - DBL_EPSILON) { rettv->vval.v_number = VARNUMBER_MAX; } else { rettv->vval.v_number = (varnumber_T)f; } } } /* * "fmod()" function */ static void f_fmod(typval_T *argvars, typval_T *rettv, FunPtr fptr) { float_T fx; float_T fy; rettv->v_type = VAR_FLOAT; if (tv_get_float_chk(argvars, &fx) && tv_get_float_chk(&argvars[1], &fy)) { rettv->vval.v_float = fmod(fx, fy); } else { rettv->vval.v_float = 0.0; } } /* * "fnameescape({string})" function */ static void f_fnameescape(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_string = (char_u *)vim_strsave_fnameescape( tv_get_string(&argvars[0]), false); rettv->v_type = VAR_STRING; } /* * "fnamemodify({fname}, {mods})" function */ static void f_fnamemodify(typval_T *argvars, typval_T *rettv, FunPtr fptr) { char_u *fbuf = NULL; size_t len; char buf[NUMBUFLEN]; const char *fname = tv_get_string_chk(&argvars[0]); const char *const mods = tv_get_string_buf_chk(&argvars[1], buf); if (fname == NULL || mods == NULL) { fname = NULL; } else { len = strlen(fname); size_t usedlen = 0; (void)modify_fname((char_u *)mods, false, &usedlen, (char_u **)&fname, &fbuf, &len); } rettv->v_type = VAR_STRING; if (fname == NULL) { rettv->vval.v_string = NULL; } else { rettv->vval.v_string = (char_u *)xmemdupz(fname, len); } xfree(fbuf); } /* * "foldclosed()" function */ static void foldclosed_both(typval_T *argvars, typval_T *rettv, int end) { const linenr_T lnum = tv_get_lnum(argvars); if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { linenr_T first; linenr_T last; if (hasFoldingWin(curwin, lnum, &first, &last, false, NULL)) { if (end) { rettv->vval.v_number = (varnumber_T)last; } else { rettv->vval.v_number = (varnumber_T)first; } return; } } rettv->vval.v_number = -1; } /* * "foldclosed()" function */ static void f_foldclosed(typval_T *argvars, typval_T *rettv, FunPtr fptr) { foldclosed_both(argvars, rettv, FALSE); } /* * "foldclosedend()" function */ static void f_foldclosedend(typval_T *argvars, typval_T *rettv, FunPtr fptr) { foldclosed_both(argvars, rettv, TRUE); } /* * "foldlevel()" function */ static void f_foldlevel(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const linenr_T lnum = tv_get_lnum(argvars); if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { rettv->vval.v_number = foldLevel(lnum); } } /* * "foldtext()" function */ static void f_foldtext(typval_T *argvars, typval_T *rettv, FunPtr fptr) { linenr_T foldstart; linenr_T foldend; char_u *dashes; linenr_T lnum; char_u *s; char_u *r; int len; char *txt; rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; foldstart = (linenr_T)get_vim_var_nr(VV_FOLDSTART); foldend = (linenr_T)get_vim_var_nr(VV_FOLDEND); dashes = get_vim_var_str(VV_FOLDDASHES); if (foldstart > 0 && foldend <= curbuf->b_ml.ml_line_count) { // Find first non-empty line in the fold. for (lnum = foldstart; lnum < foldend; lnum++) { if (!linewhite(lnum)) { break; } } /* Find interesting text in this line. */ s = skipwhite(ml_get(lnum)); /* skip C comment-start */ if (s[0] == '/' && (s[1] == '*' || s[1] == '/')) { s = skipwhite(s + 2); if (*skipwhite(s) == NUL && lnum + 1 < foldend) { s = skipwhite(ml_get(lnum + 1)); if (*s == '*') s = skipwhite(s + 1); } } unsigned long count = (unsigned long)(foldend - foldstart + 1); txt = NGETTEXT("+-%s%3ld line: ", "+-%s%3ld lines: ", count); r = xmalloc(STRLEN(txt) + STRLEN(dashes) // for %s + 20 // for %3ld + STRLEN(s)); // concatenated sprintf((char *)r, txt, dashes, count); len = (int)STRLEN(r); STRCAT(r, s); /* remove 'foldmarker' and 'commentstring' */ foldtext_cleanup(r + len); rettv->vval.v_string = r; } } /* * "foldtextresult(lnum)" function */ static void f_foldtextresult(typval_T *argvars, typval_T *rettv, FunPtr fptr) { char_u *text; char_u buf[FOLD_TEXT_LEN]; foldinfo_T foldinfo; int fold_count; static bool entered = false; rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; if (entered) { return; // reject recursive use } entered = true; linenr_T lnum = tv_get_lnum(argvars); // Treat illegal types and illegal string values for {lnum} the same. if (lnum < 0) { lnum = 0; } fold_count = foldedCount(curwin, lnum, &foldinfo); if (fold_count > 0) { text = get_foldtext(curwin, lnum, lnum + fold_count - 1, &foldinfo, buf); if (text == buf) { text = vim_strsave(text); } rettv->vval.v_string = text; } entered = false; } /* * "foreground()" function */ static void f_foreground(typval_T *argvars, typval_T *rettv, FunPtr fptr) { } static void common_function(typval_T *argvars, typval_T *rettv, bool is_funcref, FunPtr fptr) { char_u *s; char_u *name; bool use_string = false; partial_T *arg_pt = NULL; char_u *trans_name = NULL; if (argvars[0].v_type == VAR_FUNC) { // function(MyFunc, [arg], dict) s = argvars[0].vval.v_string; } else if (argvars[0].v_type == VAR_PARTIAL && argvars[0].vval.v_partial != NULL) { // function(dict.MyFunc, [arg]) arg_pt = argvars[0].vval.v_partial; s = partial_name(arg_pt); } else { // function('MyFunc', [arg], dict) s = (char_u *)tv_get_string(&argvars[0]); use_string = true; } if ((use_string && vim_strchr(s, AUTOLOAD_CHAR) == NULL) || is_funcref) { name = s; trans_name = trans_function_name(&name, false, TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD | TFN_NO_DEREF, NULL, NULL); if (*name != NUL) { s = NULL; } } if (s == NULL || *s == NUL || (use_string && ascii_isdigit(*s)) || (is_funcref && trans_name == NULL)) { emsgf(_(e_invarg2), (use_string ? tv_get_string(&argvars[0]) : (const char *)s)); // Don't check an autoload name for existence here. } else if (trans_name != NULL && (is_funcref ? find_func(trans_name) == NULL : !translated_function_exists((const char *)trans_name))) { emsgf(_("E700: Unknown function: %s"), s); } else { int dict_idx = 0; int arg_idx = 0; list_T *list = NULL; if (STRNCMP(s, "s:", 2) == 0 || STRNCMP(s, "", 5) == 0) { char sid_buf[25]; int off = *s == 's' ? 2 : 5; // Expand s: and into nr_, so that the function can // also be called from another script. Using trans_function_name() // would also work, but some plugins depend on the name being // printable text. snprintf(sid_buf, sizeof(sid_buf), "%" PRId64 "_", (int64_t)current_sctx.sc_sid); name = xmalloc(STRLEN(sid_buf) + STRLEN(s + off) + 1); STRCPY(name, sid_buf); STRCAT(name, s + off); } else { name = vim_strsave(s); } if (argvars[1].v_type != VAR_UNKNOWN) { if (argvars[2].v_type != VAR_UNKNOWN) { // function(name, [args], dict) arg_idx = 1; dict_idx = 2; } else if (argvars[1].v_type == VAR_DICT) { // function(name, dict) dict_idx = 1; } else { // function(name, [args]) arg_idx = 1; } if (dict_idx > 0) { if (argvars[dict_idx].v_type != VAR_DICT) { EMSG(_("E922: expected a dict")); xfree(name); goto theend; } if (argvars[dict_idx].vval.v_dict == NULL) { dict_idx = 0; } } if (arg_idx > 0) { if (argvars[arg_idx].v_type != VAR_LIST) { EMSG(_("E923: Second argument of function() must be " "a list or a dict")); xfree(name); goto theend; } list = argvars[arg_idx].vval.v_list; if (tv_list_len(list) == 0) { arg_idx = 0; } } } if (dict_idx > 0 || arg_idx > 0 || arg_pt != NULL || is_funcref) { partial_T *const pt = xcalloc(1, sizeof(*pt)); // result is a VAR_PARTIAL if (arg_idx > 0 || (arg_pt != NULL && arg_pt->pt_argc > 0)) { const int arg_len = (arg_pt == NULL ? 0 : arg_pt->pt_argc); const int lv_len = tv_list_len(list); pt->pt_argc = arg_len + lv_len; pt->pt_argv = xmalloc(sizeof(pt->pt_argv[0]) * pt->pt_argc); int i = 0; for (; i < arg_len; i++) { tv_copy(&arg_pt->pt_argv[i], &pt->pt_argv[i]); } if (lv_len > 0) { TV_LIST_ITER(list, li, { tv_copy(TV_LIST_ITEM_TV(li), &pt->pt_argv[i++]); }); } } // For "function(dict.func, [], dict)" and "func" is a partial // use "dict". That is backwards compatible. if (dict_idx > 0) { // The dict is bound explicitly, pt_auto is false pt->pt_dict = argvars[dict_idx].vval.v_dict; (pt->pt_dict->dv_refcount)++; } else if (arg_pt != NULL) { // If the dict was bound automatically the result is also // bound automatically. pt->pt_dict = arg_pt->pt_dict; pt->pt_auto = arg_pt->pt_auto; if (pt->pt_dict != NULL) { (pt->pt_dict->dv_refcount)++; } } pt->pt_refcount = 1; if (arg_pt != NULL && arg_pt->pt_func != NULL) { pt->pt_func = arg_pt->pt_func; func_ptr_ref(pt->pt_func); xfree(name); } else if (is_funcref) { pt->pt_func = find_func(trans_name); func_ptr_ref(pt->pt_func); xfree(name); } else { pt->pt_name = name; func_ref(name); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } else { // result is a VAR_FUNC rettv->v_type = VAR_FUNC; rettv->vval.v_string = name; func_ref(name); } } theend: xfree(trans_name); } static void f_funcref(typval_T *argvars, typval_T *rettv, FunPtr fptr) { common_function(argvars, rettv, true, fptr); } static void f_function(typval_T *argvars, typval_T *rettv, FunPtr fptr) { common_function(argvars, rettv, false, fptr); } /// "garbagecollect()" function static void f_garbagecollect(typval_T *argvars, typval_T *rettv, FunPtr fptr) { // This is postponed until we are back at the toplevel, because we may be // using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". want_garbage_collect = true; if (argvars[0].v_type != VAR_UNKNOWN && tv_get_number(&argvars[0]) == 1) { garbage_collect_at_exit = true; } } /* * "get()" function */ static void f_get(typval_T *argvars, typval_T *rettv, FunPtr fptr) { listitem_T *li; list_T *l; dictitem_T *di; dict_T *d; typval_T *tv = NULL; bool what_is_dict = false; if (argvars[0].v_type == VAR_LIST) { if ((l = argvars[0].vval.v_list) != NULL) { bool error = false; li = tv_list_find(l, tv_get_number_chk(&argvars[1], &error)); if (!error && li != NULL) { tv = TV_LIST_ITEM_TV(li); } } } else if (argvars[0].v_type == VAR_DICT) { if ((d = argvars[0].vval.v_dict) != NULL) { di = tv_dict_find(d, tv_get_string(&argvars[1]), -1); if (di != NULL) { tv = &di->di_tv; } } } else if (tv_is_func(argvars[0])) { partial_T *pt; partial_T fref_pt; if (argvars[0].v_type == VAR_PARTIAL) { pt = argvars[0].vval.v_partial; } else { memset(&fref_pt, 0, sizeof(fref_pt)); fref_pt.pt_name = argvars[0].vval.v_string; pt = &fref_pt; } if (pt != NULL) { const char *const what = tv_get_string(&argvars[1]); if (strcmp(what, "func") == 0 || strcmp(what, "name") == 0) { rettv->v_type = (*what == 'f' ? VAR_FUNC : VAR_STRING); const char *const n = (const char *)partial_name(pt); assert(n != NULL); rettv->vval.v_string = (char_u *)xstrdup(n); if (rettv->v_type == VAR_FUNC) { func_ref(rettv->vval.v_string); } } else if (strcmp(what, "dict") == 0) { what_is_dict = true; if (pt->pt_dict != NULL) { tv_dict_set_ret(rettv, pt->pt_dict); } } else if (strcmp(what, "args") == 0) { rettv->v_type = VAR_LIST; if (tv_list_alloc_ret(rettv, pt->pt_argc) != NULL) { for (int i = 0; i < pt->pt_argc; i++) { tv_list_append_tv(rettv->vval.v_list, &pt->pt_argv[i]); } } } else { EMSG2(_(e_invarg2), what); } // When {what} == "dict" and pt->pt_dict == NULL, evaluate the // third argument if (!what_is_dict) { return; } } } else { EMSG2(_(e_listdictarg), "get()"); } if (tv == NULL) { if (argvars[2].v_type != VAR_UNKNOWN) { tv_copy(&argvars[2], rettv); } } else { tv_copy(tv, rettv); } } /// Returns buffer options, variables and other attributes in a dictionary. static dict_T *get_buffer_info(buf_T *buf) { dict_T *const dict = tv_dict_alloc(); tv_dict_add_nr(dict, S_LEN("bufnr"), buf->b_fnum); tv_dict_add_str(dict, S_LEN("name"), buf->b_ffname != NULL ? (const char *)buf->b_ffname : ""); tv_dict_add_nr(dict, S_LEN("lnum"), buf == curbuf ? curwin->w_cursor.lnum : buflist_findlnum(buf)); tv_dict_add_nr(dict, S_LEN("loaded"), buf->b_ml.ml_mfp != NULL); tv_dict_add_nr(dict, S_LEN("listed"), buf->b_p_bl); tv_dict_add_nr(dict, S_LEN("changed"), bufIsChanged(buf)); tv_dict_add_nr(dict, S_LEN("changedtick"), buf_get_changedtick(buf)); tv_dict_add_nr(dict, S_LEN("hidden"), buf->b_ml.ml_mfp != NULL && buf->b_nwindows == 0); // Get a reference to buffer variables tv_dict_add_dict(dict, S_LEN("variables"), buf->b_vars); // List of windows displaying this buffer list_T *const windows = tv_list_alloc(kListLenMayKnow); FOR_ALL_TAB_WINDOWS(tp, wp) { if (wp->w_buffer == buf) { tv_list_append_number(windows, (varnumber_T)wp->handle); } } tv_dict_add_list(dict, S_LEN("windows"), windows); if (buf->b_signlist != NULL) { // List of signs placed in this buffer tv_dict_add_list(dict, S_LEN("signs"), get_buffer_signs(buf)); } return dict; } /// "getbufinfo()" function static void f_getbufinfo(typval_T *argvars, typval_T *rettv, FunPtr fptr) { buf_T *argbuf = NULL; bool filtered = false; bool sel_buflisted = false; bool sel_bufloaded = false; bool sel_bufmodified = false; tv_list_alloc_ret(rettv, kListLenMayKnow); // List of all the buffers or selected buffers if (argvars[0].v_type == VAR_DICT) { dict_T *sel_d = argvars[0].vval.v_dict; if (sel_d != NULL) { dictitem_T *di; filtered = true; di = tv_dict_find(sel_d, S_LEN("buflisted")); if (di != NULL && tv_get_number(&di->di_tv)) { sel_buflisted = true; } di = tv_dict_find(sel_d, S_LEN("bufloaded")); if (di != NULL && tv_get_number(&di->di_tv)) { sel_bufloaded = true; } di = tv_dict_find(sel_d, S_LEN("bufmodified")); if (di != NULL && tv_get_number(&di->di_tv)) { sel_bufmodified = true; } } } else if (argvars[0].v_type != VAR_UNKNOWN) { // Information about one buffer. Argument specifies the buffer if (tv_check_num(&argvars[0])) { // issue errmsg if type error emsg_off++; argbuf = tv_get_buf(&argvars[0], false); emsg_off--; if (argbuf == NULL) { return; } } } // Return information about all the buffers or a specified buffer FOR_ALL_BUFFERS(buf) { if (argbuf != NULL && argbuf != buf) { continue; } if (filtered && ((sel_bufloaded && buf->b_ml.ml_mfp == NULL) || (sel_buflisted && !buf->b_p_bl) || (sel_bufmodified && !buf->b_changed))) { continue; } dict_T *const d = get_buffer_info(buf); tv_list_append_dict(rettv->vval.v_list, d); if (argbuf != NULL) { return; } } } /* * Get line or list of lines from buffer "buf" into "rettv". * Return a range (from start to end) of lines in rettv from the specified * buffer. * If 'retlist' is TRUE, then the lines are returned as a Vim List. */ static void get_buffer_lines(buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv) { rettv->v_type = (retlist ? VAR_LIST : VAR_STRING); rettv->vval.v_string = NULL; if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0 || end < start) { if (retlist) { tv_list_alloc_ret(rettv, 0); } return; } if (retlist) { if (start < 1) { start = 1; } if (end > buf->b_ml.ml_line_count) { end = buf->b_ml.ml_line_count; } tv_list_alloc_ret(rettv, end - start + 1); while (start <= end) { tv_list_append_string(rettv->vval.v_list, (const char *)ml_get_buf(buf, start++, false), -1); } } else { rettv->v_type = VAR_STRING; rettv->vval.v_string = ((start >= 1 && start <= buf->b_ml.ml_line_count) ? vim_strsave(ml_get_buf(buf, start, false)) : NULL); } } /// Get the line number from VimL object /// /// @note Unlike tv_get_lnum(), this one supports only "$" special string. /// /// @param[in] tv Object to get value from. Is expected to be a number or /// a special string "$". /// @param[in] buf Buffer to take last line number from in case tv is "$". May /// be NULL, in this case "$" results in zero return. /// /// @return Line number or 0 in case of error. static linenr_T tv_get_lnum_buf(const typval_T *const tv, const buf_T *const buf) FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_WARN_UNUSED_RESULT { if (tv->v_type == VAR_STRING && tv->vval.v_string != NULL && tv->vval.v_string[0] == '$' && buf != NULL) { return buf->b_ml.ml_line_count; } return tv_get_number_chk(tv, NULL); } /* * "getbufline()" function */ static void f_getbufline(typval_T *argvars, typval_T *rettv, FunPtr fptr) { buf_T *buf = NULL; if (tv_check_str_or_nr(&argvars[0])) { emsg_off++; buf = tv_get_buf(&argvars[0], false); emsg_off--; } const linenr_T lnum = tv_get_lnum_buf(&argvars[1], buf); const linenr_T end = (argvars[2].v_type == VAR_UNKNOWN ? lnum : tv_get_lnum_buf(&argvars[2], buf)); get_buffer_lines(buf, lnum, end, true, rettv); } /* * "getbufvar()" function */ static void f_getbufvar(typval_T *argvars, typval_T *rettv, FunPtr fptr) { bool done = false; rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; if (!tv_check_str_or_nr(&argvars[0])) { goto f_getbufvar_end; } const char *varname = tv_get_string_chk(&argvars[1]); emsg_off++; buf_T *const buf = tv_get_buf(&argvars[0], false); if (buf != NULL && varname != NULL) { // set curbuf to be our buf, temporarily buf_T *const save_curbuf = curbuf; curbuf = buf; if (*varname == '&') { // buffer-local-option if (varname[1] == NUL) { // get all buffer-local options in a dict dict_T *opts = get_winbuf_options(true); if (opts != NULL) { tv_dict_set_ret(rettv, opts); done = true; } } else if (get_option_tv(&varname, rettv, true) == OK) { // buffer-local-option done = true; } } else { // Look up the variable. // Let getbufvar({nr}, "") return the "b:" dictionary. dictitem_T *const v = find_var_in_ht(&curbuf->b_vars->dv_hashtab, 'b', varname, strlen(varname), false); if (v != NULL) { tv_copy(&v->di_tv, rettv); done = true; } } // restore previous notion of curbuf curbuf = save_curbuf; } emsg_off--; f_getbufvar_end: if (!done && argvars[2].v_type != VAR_UNKNOWN) { // use the default value tv_copy(&argvars[2], rettv); } } // "getchangelist()" function static void f_getchangelist(typval_T *argvars, typval_T *rettv, FunPtr fptr) { tv_list_alloc_ret(rettv, 2); vim_ignored = tv_get_number(&argvars[0]); // issue errmsg if type error emsg_off++; const buf_T *const buf = tv_get_buf(&argvars[0], false); emsg_off--; if (buf == NULL) { return; } list_T *const l = tv_list_alloc(buf->b_changelistlen); tv_list_append_list(rettv->vval.v_list, l); // The current window change list index tracks only the position in the // current buffer change list. For other buffers, use the change list // length as the current index. tv_list_append_number(rettv->vval.v_list, (buf == curwin->w_buffer) ? curwin->w_changelistidx : buf->b_changelistlen); for (int i = 0; i < buf->b_changelistlen; i++) { if (buf->b_changelist[i].mark.lnum == 0) { continue; } dict_T *const d = tv_dict_alloc(); tv_list_append_dict(l, d); tv_dict_add_nr(d, S_LEN("lnum"), buf->b_changelist[i].mark.lnum); tv_dict_add_nr(d, S_LEN("col"), buf->b_changelist[i].mark.col); tv_dict_add_nr(d, S_LEN("coladd"), buf->b_changelist[i].mark.coladd); } } /* * "getchar()" function */ static void f_getchar(typval_T *argvars, typval_T *rettv, FunPtr fptr) { varnumber_T n; bool error = false; no_mapping++; for (;; ) { // Position the cursor. Needed after a message that ends in a space, // or if event processing caused a redraw. ui_cursor_goto(msg_row, msg_col); if (argvars[0].v_type == VAR_UNKNOWN) { // getchar(): blocking wait. if (!(char_avail() || using_script() || input_available())) { (void)os_inchar(NULL, 0, -1, 0, main_loop.events); if (!multiqueue_empty(main_loop.events)) { multiqueue_process_events(main_loop.events); continue; } } n = safe_vgetc(); } else if (tv_get_number_chk(&argvars[0], &error) == 1) { // getchar(1): only check if char avail n = vpeekc_any(); } else if (error || vpeekc_any() == NUL) { // illegal argument or getchar(0) and no char avail: return zero n = 0; } else { // getchar(0) and char avail: return char n = safe_vgetc(); } if (n == K_IGNORE) { continue; } break; } no_mapping--; vimvars[VV_MOUSE_WIN].vv_nr = 0; vimvars[VV_MOUSE_WINID].vv_nr = 0; vimvars[VV_MOUSE_LNUM].vv_nr = 0; vimvars[VV_MOUSE_COL].vv_nr = 0; rettv->vval.v_number = n; if (IS_SPECIAL(n) || mod_mask != 0) { char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */ int i = 0; /* Turn a special key into three bytes, plus modifier. */ if (mod_mask != 0) { temp[i++] = K_SPECIAL; temp[i++] = KS_MODIFIER; temp[i++] = mod_mask; } if (IS_SPECIAL(n)) { temp[i++] = K_SPECIAL; temp[i++] = K_SECOND(n); temp[i++] = K_THIRD(n); } else { i += utf_char2bytes(n, temp + i); } temp[i++] = NUL; rettv->v_type = VAR_STRING; rettv->vval.v_string = vim_strsave(temp); if (is_mouse_key(n)) { int row = mouse_row; int col = mouse_col; int grid = mouse_grid; win_T *win; linenr_T lnum; win_T *wp; int winnr = 1; if (row >= 0 && col >= 0) { /* Find the window at the mouse coordinates and compute the * text position. */ win = mouse_find_win(&grid, &row, &col); if (win == NULL) { return; } (void)mouse_comp_pos(win, &row, &col, &lnum); for (wp = firstwin; wp != win; wp = wp->w_next) ++winnr; vimvars[VV_MOUSE_WIN].vv_nr = winnr; vimvars[VV_MOUSE_WINID].vv_nr = wp->handle; vimvars[VV_MOUSE_LNUM].vv_nr = lnum; vimvars[VV_MOUSE_COL].vv_nr = col + 1; } } } } /* * "getcharmod()" function */ static void f_getcharmod(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = mod_mask; } /* * "getcharsearch()" function */ static void f_getcharsearch(typval_T *argvars, typval_T *rettv, FunPtr fptr) { tv_dict_alloc_ret(rettv); dict_T *dict = rettv->vval.v_dict; tv_dict_add_str(dict, S_LEN("char"), last_csearch()); tv_dict_add_nr(dict, S_LEN("forward"), last_csearch_forward()); tv_dict_add_nr(dict, S_LEN("until"), last_csearch_until()); } /* * "getcmdline()" function */ static void f_getcmdline(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_STRING; rettv->vval.v_string = get_cmdline_str(); } /* * "getcmdpos()" function */ static void f_getcmdpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = get_cmdline_pos() + 1; } /* * "getcmdtype()" function */ static void f_getcmdtype(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_STRING; rettv->vval.v_string = xmallocz(1); rettv->vval.v_string[0] = get_cmdline_type(); } /* * "getcmdwintype()" function */ static void f_getcmdwintype(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; rettv->vval.v_string = xmallocz(1); rettv->vval.v_string[0] = cmdwin_type; } // "getcompletion()" function static void f_getcompletion(typval_T *argvars, typval_T *rettv, FunPtr fptr) { char_u *pat; expand_T xpc; bool filtered = false; int options = WILD_SILENT | WILD_USE_NL | WILD_ADD_SLASH | WILD_NO_BEEP; if (argvars[2].v_type != VAR_UNKNOWN) { filtered = (bool)tv_get_number_chk(&argvars[2], NULL); } if (p_wic) { options |= WILD_ICASE; } // For filtered results, 'wildignore' is used if (!filtered) { options |= WILD_KEEP_ALL; } if (argvars[0].v_type != VAR_STRING || argvars[1].v_type != VAR_STRING) { EMSG(_(e_invarg)); return; } if (strcmp(tv_get_string(&argvars[1]), "cmdline") == 0) { set_one_cmd_context(&xpc, tv_get_string(&argvars[0])); xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); goto theend; } ExpandInit(&xpc); xpc.xp_pattern = (char_u *)tv_get_string(&argvars[0]); xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); xpc.xp_context = cmdcomplete_str_to_type( (char_u *)tv_get_string(&argvars[1])); if (xpc.xp_context == EXPAND_NOTHING) { EMSG2(_(e_invarg2), argvars[1].vval.v_string); return; } if (xpc.xp_context == EXPAND_MENUS) { set_context_in_menu_cmd(&xpc, (char_u *)"menu", xpc.xp_pattern, false); xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); } if (xpc.xp_context == EXPAND_CSCOPE) { set_context_in_cscope_cmd(&xpc, (const char *)xpc.xp_pattern, CMD_cscope); xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); } if (xpc.xp_context == EXPAND_SIGN) { set_context_in_sign_cmd(&xpc, xpc.xp_pattern); xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); } theend: pat = addstar(xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context); ExpandOne(&xpc, pat, NULL, options, WILD_ALL_KEEP); tv_list_alloc_ret(rettv, xpc.xp_numfiles); for (int i = 0; i < xpc.xp_numfiles; i++) { tv_list_append_string(rettv->vval.v_list, (const char *)xpc.xp_files[i], -1); } xfree(pat); ExpandCleanup(&xpc); } /// `getcwd([{win}[, {tab}]])` function /// /// Every scope not specified implies the currently selected scope object. /// /// @pre The arguments must be of type number. /// @pre There may not be more than two arguments. /// @pre An argument may not be -1 if preceding arguments are not all -1. /// /// @post The return value will be a string. static void f_getcwd(typval_T *argvars, typval_T *rettv, FunPtr fptr) { // Possible scope of working directory to return. CdScope scope = kCdScopeInvalid; // Numbers of the scope objects (window, tab) we want the working directory // of. A `-1` means to skip this scope, a `0` means the current object. int scope_number[] = { [kCdScopeWindow] = 0, // Number of window to look at. [kCdScopeTab ] = 0, // Number of tab to look at. }; char_u *cwd = NULL; // Current working directory to print char_u *from = NULL; // The original string to copy tabpage_T *tp = curtab; // The tabpage to look at. win_T *win = curwin; // The window to look at. rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; // Pre-conditions and scope extraction together for (int i = MIN_CD_SCOPE; i < MAX_CD_SCOPE; i++) { // If there is no argument there are no more scopes after it, break out. if (argvars[i].v_type == VAR_UNKNOWN) { break; } if (argvars[i].v_type != VAR_NUMBER) { EMSG(_(e_invarg)); return; } scope_number[i] = argvars[i].vval.v_number; // It is an error for the scope number to be less than `-1`. if (scope_number[i] < -1) { EMSG(_(e_invarg)); return; } // Use the narrowest scope the user requested if (scope_number[i] >= 0 && scope == kCdScopeInvalid) { // The scope is the current iteration step. scope = i; } else if (scope_number[i] < 0) { scope = i + 1; } } // If the user didn't specify anything, default to window scope if (scope == kCdScopeInvalid) { scope = MIN_CD_SCOPE; } // Find the tabpage by number if (scope_number[kCdScopeTab] > 0) { tp = find_tabpage(scope_number[kCdScopeTab]); if (!tp) { EMSG(_("E5000: Cannot find tab number.")); return; } } // Find the window in `tp` by number, `NULL` if none. if (scope_number[kCdScopeWindow] >= 0) { if (scope_number[kCdScopeTab] < 0) { EMSG(_("E5001: Higher scope cannot be -1 if lower scope is >= 0.")); return; } if (scope_number[kCdScopeWindow] > 0) { win = find_win_by_nr(&argvars[0], tp); if (!win) { EMSG(_("E5002: Cannot find window number.")); return; } } } cwd = xmalloc(MAXPATHL); switch (scope) { case kCdScopeWindow: assert(win); from = win->w_localdir; if (from) { break; } FALLTHROUGH; case kCdScopeTab: assert(tp); from = tp->tp_localdir; if (from) { break; } FALLTHROUGH; case kCdScopeGlobal: if (globaldir) { // `globaldir` is not always set. from = globaldir; } else if (os_dirname(cwd, MAXPATHL) == FAIL) { // Get the OS CWD. from = (char_u *)""; // Return empty string on failure. } break; case kCdScopeInvalid: // We should never get here assert(false); } if (from) { xstrlcpy((char *)cwd, (char *)from, MAXPATHL); } rettv->vval.v_string = vim_strsave(cwd); #ifdef BACKSLASH_IN_FILENAME slash_adjust(rettv->vval.v_string); #endif xfree(cwd); } /* * "getfontname()" function */ static void f_getfontname(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; } /* * "getfperm({fname})" function */ static void f_getfperm(typval_T *argvars, typval_T *rettv, FunPtr fptr) { char *perm = NULL; char_u flags[] = "rwx"; const char *filename = tv_get_string(&argvars[0]); int32_t file_perm = os_getperm(filename); if (file_perm >= 0) { perm = xstrdup("---------"); for (int i = 0; i < 9; i++) { if (file_perm & (1 << (8 - i))) { perm[i] = flags[i % 3]; } } } rettv->v_type = VAR_STRING; rettv->vval.v_string = (char_u *)perm; } /* * "getfsize({fname})" function */ static void f_getfsize(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *fname = tv_get_string(&argvars[0]); rettv->v_type = VAR_NUMBER; FileInfo file_info; if (os_fileinfo(fname, &file_info)) { uint64_t filesize = os_fileinfo_size(&file_info); if (os_isdir((const char_u *)fname)) { rettv->vval.v_number = 0; } else { rettv->vval.v_number = (varnumber_T)filesize; /* non-perfect check for overflow */ if ((uint64_t)rettv->vval.v_number != filesize) { rettv->vval.v_number = -2; } } } else { rettv->vval.v_number = -1; } } /* * "getftime({fname})" function */ static void f_getftime(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *fname = tv_get_string(&argvars[0]); FileInfo file_info; if (os_fileinfo(fname, &file_info)) { rettv->vval.v_number = (varnumber_T)file_info.stat.st_mtim.tv_sec; } else { rettv->vval.v_number = -1; } } /* * "getftype({fname})" function */ static void f_getftype(typval_T *argvars, typval_T *rettv, FunPtr fptr) { char_u *type = NULL; char *t; const char *fname = tv_get_string(&argvars[0]); rettv->v_type = VAR_STRING; FileInfo file_info; if (os_fileinfo_link(fname, &file_info)) { uint64_t mode = file_info.stat.st_mode; #ifdef S_ISREG if (S_ISREG(mode)) t = "file"; else if (S_ISDIR(mode)) t = "dir"; # ifdef S_ISLNK else if (S_ISLNK(mode)) t = "link"; # endif # ifdef S_ISBLK else if (S_ISBLK(mode)) t = "bdev"; # endif # ifdef S_ISCHR else if (S_ISCHR(mode)) t = "cdev"; # endif # ifdef S_ISFIFO else if (S_ISFIFO(mode)) t = "fifo"; # endif # ifdef S_ISSOCK else if (S_ISSOCK(mode)) t = "socket"; # endif else t = "other"; #else # ifdef S_IFMT switch (mode & S_IFMT) { case S_IFREG: t = "file"; break; case S_IFDIR: t = "dir"; break; # ifdef S_IFLNK case S_IFLNK: t = "link"; break; # endif # ifdef S_IFBLK case S_IFBLK: t = "bdev"; break; # endif # ifdef S_IFCHR case S_IFCHR: t = "cdev"; break; # endif # ifdef S_IFIFO case S_IFIFO: t = "fifo"; break; # endif # ifdef S_IFSOCK case S_IFSOCK: t = "socket"; break; # endif default: t = "other"; } # else if (os_isdir((const char_u *)fname)) { t = "dir"; } else { t = "file"; } # endif #endif type = vim_strsave((char_u *)t); } rettv->vval.v_string = type; } // "getjumplist()" function static void f_getjumplist(typval_T *argvars, typval_T *rettv, FunPtr fptr) { tv_list_alloc_ret(rettv, kListLenMayKnow); win_T *const wp = find_tabwin(&argvars[0], &argvars[1]); if (wp == NULL) { return; } cleanup_jumplist(wp, true); list_T *const l = tv_list_alloc(wp->w_jumplistlen); tv_list_append_list(rettv->vval.v_list, l); tv_list_append_number(rettv->vval.v_list, wp->w_jumplistidx); for (int i = 0; i < wp->w_jumplistlen; i++) { if (wp->w_jumplist[i].fmark.mark.lnum == 0) { continue; } dict_T *const d = tv_dict_alloc(); tv_list_append_dict(l, d); tv_dict_add_nr(d, S_LEN("lnum"), wp->w_jumplist[i].fmark.mark.lnum); tv_dict_add_nr(d, S_LEN("col"), wp->w_jumplist[i].fmark.mark.col); tv_dict_add_nr(d, S_LEN("coladd"), wp->w_jumplist[i].fmark.mark.coladd); tv_dict_add_nr(d, S_LEN("bufnr"), wp->w_jumplist[i].fmark.fnum); if (wp->w_jumplist[i].fname != NULL) { tv_dict_add_str(d, S_LEN("filename"), (char *)wp->w_jumplist[i].fname); } } } /* * "getline(lnum, [end])" function */ static void f_getline(typval_T *argvars, typval_T *rettv, FunPtr fptr) { linenr_T end; bool retlist; const linenr_T lnum = tv_get_lnum(argvars); if (argvars[1].v_type == VAR_UNKNOWN) { end = lnum; retlist = false; } else { end = tv_get_lnum(&argvars[1]); retlist = true; } get_buffer_lines(curbuf, lnum, end, retlist, rettv); } static void get_qf_loc_list(int is_qf, win_T *wp, typval_T *what_arg, typval_T *rettv) { if (what_arg->v_type == VAR_UNKNOWN) { tv_list_alloc_ret(rettv, kListLenMayKnow); if (is_qf || wp != NULL) { (void)get_errorlist(NULL, wp, -1, rettv->vval.v_list); } } else { tv_dict_alloc_ret(rettv); if (is_qf || wp != NULL) { if (what_arg->v_type == VAR_DICT) { dict_T *d = what_arg->vval.v_dict; if (d != NULL) { qf_get_properties(wp, d, rettv->vval.v_dict); } } else { EMSG(_(e_dictreq)); } } } } /// "getloclist()" function static void f_getloclist(typval_T *argvars, typval_T *rettv, FunPtr fptr) { win_T *wp = find_win_by_nr_or_id(&argvars[0]); get_qf_loc_list(false, wp, &argvars[1], rettv); } /* * "getmatches()" function */ static void f_getmatches(typval_T *argvars, typval_T *rettv, FunPtr fptr) { matchitem_T *cur = curwin->w_match_head; int i; tv_list_alloc_ret(rettv, kListLenMayKnow); while (cur != NULL) { dict_T *dict = tv_dict_alloc(); if (cur->match.regprog == NULL) { // match added with matchaddpos() for (i = 0; i < MAXPOSMATCH; i++) { llpos_T *llpos; char buf[30]; // use 30 to avoid compiler warning llpos = &cur->pos.pos[i]; if (llpos->lnum == 0) { break; } list_T *const l = tv_list_alloc(1 + (llpos->col > 0 ? 2 : 0)); tv_list_append_number(l, (varnumber_T)llpos->lnum); if (llpos->col > 0) { tv_list_append_number(l, (varnumber_T)llpos->col); tv_list_append_number(l, (varnumber_T)llpos->len); } int len = snprintf(buf, sizeof(buf), "pos%d", i + 1); assert((size_t)len < sizeof(buf)); tv_dict_add_list(dict, buf, (size_t)len, l); } } else { tv_dict_add_str(dict, S_LEN("pattern"), (const char *)cur->pattern); } tv_dict_add_str(dict, S_LEN("group"), (const char *)syn_id2name(cur->hlg_id)); tv_dict_add_nr(dict, S_LEN("priority"), (varnumber_T)cur->priority); tv_dict_add_nr(dict, S_LEN("id"), (varnumber_T)cur->id); if (cur->conceal_char) { char buf[MB_MAXBYTES + 1]; buf[utf_char2bytes((int)cur->conceal_char, (char_u *)buf)] = NUL; tv_dict_add_str(dict, S_LEN("conceal"), buf); } tv_list_append_dict(rettv->vval.v_list, dict); cur = cur->next; } } /* * "getpid()" function */ static void f_getpid(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = os_get_pid(); } static void getpos_both(typval_T *argvars, typval_T *rettv, bool getcurpos) { pos_T *fp; int fnum = -1; if (getcurpos) { fp = &curwin->w_cursor; } else { fp = var2fpos(&argvars[0], true, &fnum); } list_T *const l = tv_list_alloc_ret(rettv, 4 + (!!getcurpos)); tv_list_append_number(l, (fnum != -1) ? (varnumber_T)fnum : (varnumber_T)0); tv_list_append_number(l, ((fp != NULL) ? (varnumber_T)fp->lnum : (varnumber_T)0)); tv_list_append_number( l, ((fp != NULL) ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1) : (varnumber_T)0)); tv_list_append_number( l, (fp != NULL) ? (varnumber_T)fp->coladd : (varnumber_T)0); if (getcurpos) { const int save_set_curswant = curwin->w_set_curswant; const colnr_T save_curswant = curwin->w_curswant; const colnr_T save_virtcol = curwin->w_virtcol; update_curswant(); tv_list_append_number(l, (curwin->w_curswant == MAXCOL ? (varnumber_T)MAXCOL : (varnumber_T)curwin->w_curswant + 1)); // Do not change "curswant", as it is unexpected that a get // function has a side effect. if (save_set_curswant) { curwin->w_set_curswant = save_set_curswant; curwin->w_curswant = save_curswant; curwin->w_virtcol = save_virtcol; curwin->w_valid &= ~VALID_VIRTCOL; } } } /* * "getcurpos(string)" function */ static void f_getcurpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) { getpos_both(argvars, rettv, true); } /* * "getpos(string)" function */ static void f_getpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) { getpos_both(argvars, rettv, false); } /// "getqflist()" functions static void f_getqflist(typval_T *argvars, typval_T *rettv, FunPtr fptr) { get_qf_loc_list(true, NULL, &argvars[0], rettv); } /// "getreg()" function static void f_getreg(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *strregname; int arg2 = false; bool return_list = false; bool error = false; if (argvars[0].v_type != VAR_UNKNOWN) { strregname = tv_get_string_chk(&argvars[0]); error = strregname == NULL; if (argvars[1].v_type != VAR_UNKNOWN) { arg2 = tv_get_number_chk(&argvars[1], &error); if (!error && argvars[2].v_type != VAR_UNKNOWN) { return_list = tv_get_number_chk(&argvars[2], &error); } } } else { strregname = (const char *)vimvars[VV_REG].vv_str; } if (error) { return; } int regname = (uint8_t)(strregname == NULL ? '"' : *strregname); if (regname == 0) { regname = '"'; } if (return_list) { rettv->v_type = VAR_LIST; rettv->vval.v_list = get_reg_contents(regname, (arg2 ? kGRegExprSrc : 0) | kGRegList); if (rettv->vval.v_list == NULL) { rettv->vval.v_list = tv_list_alloc(0); } tv_list_ref(rettv->vval.v_list); } else { rettv->v_type = VAR_STRING; rettv->vval.v_string = get_reg_contents(regname, arg2 ? kGRegExprSrc : 0); } } /* * "getregtype()" function */ static void f_getregtype(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *strregname; if (argvars[0].v_type != VAR_UNKNOWN) { strregname = tv_get_string_chk(&argvars[0]); if (strregname == NULL) { // Type error; errmsg already given. rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; return; } } else { // Default to v:register. strregname = (const char *)vimvars[VV_REG].vv_str; } int regname = (uint8_t)(strregname == NULL ? '"' : *strregname); if (regname == 0) { regname = '"'; } colnr_T reglen = 0; char buf[NUMBUFLEN + 2]; MotionType reg_type = get_reg_type(regname, ®len); format_reg_type(reg_type, reglen, buf, ARRAY_SIZE(buf)); rettv->v_type = VAR_STRING; rettv->vval.v_string = (char_u *)xstrdup(buf); } /// Returns information (variables, options, etc.) about a tab page /// as a dictionary. static dict_T *get_tabpage_info(tabpage_T *tp, int tp_idx) { dict_T *const dict = tv_dict_alloc(); tv_dict_add_nr(dict, S_LEN("tabnr"), tp_idx); list_T *const l = tv_list_alloc(kListLenMayKnow); FOR_ALL_WINDOWS_IN_TAB(wp, tp) { tv_list_append_number(l, (varnumber_T)wp->handle); } tv_dict_add_list(dict, S_LEN("windows"), l); // Make a reference to tabpage variables tv_dict_add_dict(dict, S_LEN("variables"), tp->tp_vars); return dict; } /// "gettabinfo()" function static void f_gettabinfo(typval_T *argvars, typval_T *rettv, FunPtr fptr) { tabpage_T *tparg = NULL; tv_list_alloc_ret(rettv, (argvars[0].v_type == VAR_UNKNOWN ? 1 : kListLenMayKnow)); if (argvars[0].v_type != VAR_UNKNOWN) { // Information about one tab page tparg = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL)); if (tparg == NULL) { return; } } // Get information about a specific tab page or all tab pages int tpnr = 0; FOR_ALL_TABS(tp) { tpnr++; if (tparg != NULL && tp != tparg) { continue; } dict_T *const d = get_tabpage_info(tp, tpnr); tv_list_append_dict(rettv->vval.v_list, d); if (tparg != NULL) { return; } } } /* * "gettabvar()" function */ static void f_gettabvar(typval_T *argvars, typval_T *rettv, FunPtr fptr) { win_T *oldcurwin; tabpage_T *oldtabpage; bool done = false; rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; const char *const varname = tv_get_string_chk(&argvars[1]); tabpage_T *const tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL)); if (tp != NULL && varname != NULL) { // Set tp to be our tabpage, temporarily. Also set the window to the // first window in the tabpage, otherwise the window is not valid. win_T *const window = tp == curtab || tp->tp_firstwin == NULL ? firstwin : tp->tp_firstwin; if (switch_win(&oldcurwin, &oldtabpage, window, tp, true) == OK) { // look up the variable // Let gettabvar({nr}, "") return the "t:" dictionary. const dictitem_T *const v = find_var_in_ht(&tp->tp_vars->dv_hashtab, 't', varname, strlen(varname), false); if (v != NULL) { tv_copy(&v->di_tv, rettv); done = true; } } // restore previous notion of curwin restore_win(oldcurwin, oldtabpage, true); } if (!done && argvars[2].v_type != VAR_UNKNOWN) { tv_copy(&argvars[2], rettv); } } /* * "gettabwinvar()" function */ static void f_gettabwinvar(typval_T *argvars, typval_T *rettv, FunPtr fptr) { getwinvar(argvars, rettv, 1); } // "gettagstack()" function static void f_gettagstack(typval_T *argvars, typval_T *rettv, FunPtr fptr) { win_T *wp = curwin; // default is current window tv_dict_alloc_ret(rettv); if (argvars[0].v_type != VAR_UNKNOWN) { wp = find_win_by_nr_or_id(&argvars[0]); if (wp == NULL) { return; } } get_tagstack(wp, rettv->vval.v_dict); } /// Returns information about a window as a dictionary. static dict_T *get_win_info(win_T *wp, int16_t tpnr, int16_t winnr) { dict_T *const dict = tv_dict_alloc(); tv_dict_add_nr(dict, S_LEN("tabnr"), tpnr); tv_dict_add_nr(dict, S_LEN("winnr"), winnr); tv_dict_add_nr(dict, S_LEN("winid"), wp->handle); tv_dict_add_nr(dict, S_LEN("height"), wp->w_height); tv_dict_add_nr(dict, S_LEN("winrow"), wp->w_winrow + 1); tv_dict_add_nr(dict, S_LEN("topline"), wp->w_topline); tv_dict_add_nr(dict, S_LEN("botline"), wp->w_botline - 1); tv_dict_add_nr(dict, S_LEN("width"), wp->w_width); tv_dict_add_nr(dict, S_LEN("bufnr"), wp->w_buffer->b_fnum); tv_dict_add_nr(dict, S_LEN("wincol"), wp->w_wincol + 1); tv_dict_add_nr(dict, S_LEN("terminal"), bt_terminal(wp->w_buffer)); tv_dict_add_nr(dict, S_LEN("quickfix"), bt_quickfix(wp->w_buffer)); tv_dict_add_nr(dict, S_LEN("loclist"), (bt_quickfix(wp->w_buffer) && wp->w_llist_ref != NULL)); // Add a reference to window variables tv_dict_add_dict(dict, S_LEN("variables"), wp->w_vars); return dict; } /// "getwininfo()" function static void f_getwininfo(typval_T *argvars, typval_T *rettv, FunPtr fptr) { win_T *wparg = NULL; tv_list_alloc_ret(rettv, kListLenMayKnow); if (argvars[0].v_type != VAR_UNKNOWN) { wparg = win_id2wp(argvars); if (wparg == NULL) { return; } } // Collect information about either all the windows across all the tab // pages or one particular window. int16_t tabnr = 0; FOR_ALL_TABS(tp) { tabnr++; int16_t winnr = 0; FOR_ALL_WINDOWS_IN_TAB(wp, tp) { winnr++; if (wparg != NULL && wp != wparg) { continue; } dict_T *const d = get_win_info(wp, tabnr, winnr); tv_list_append_dict(rettv->vval.v_list, d); if (wparg != NULL) { // found information about a specific window return; } } } } // Dummy timer callback. Used by f_wait(). static void dummy_timer_due_cb(TimeWatcher *tw, void *data) { } // Dummy timer close callback. Used by f_wait(). static void dummy_timer_close_cb(TimeWatcher *tw, void *data) { xfree(tw); } /// "wait(timeout, condition[, interval])" function static void f_wait(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; if (argvars[0].v_type != VAR_NUMBER) { EMSG2(_(e_invargval), "1"); return; } if ((argvars[2].v_type != VAR_NUMBER && argvars[2].v_type != VAR_UNKNOWN) || (argvars[2].v_type == VAR_NUMBER && argvars[2].vval.v_number <= 0)) { EMSG2(_(e_invargval), "3"); return; } int timeout = argvars[0].vval.v_number; typval_T expr = argvars[1]; int interval = argvars[2].v_type == VAR_NUMBER ? argvars[2].vval.v_number : 200; // Default. TimeWatcher *tw = xmalloc(sizeof(TimeWatcher)); // Start dummy timer. time_watcher_init(&main_loop, tw, NULL); tw->events = main_loop.events; tw->blockable = true; time_watcher_start(tw, dummy_timer_due_cb, interval, interval); typval_T argv = TV_INITIAL_VALUE; typval_T exprval = TV_INITIAL_VALUE; bool error = false; int save_called_emsg = called_emsg; called_emsg = false; LOOP_PROCESS_EVENTS_UNTIL(&main_loop, main_loop.events, timeout, eval_expr_typval(&expr, &argv, 0, &exprval) != OK || tv_get_number_chk(&exprval, &error) || called_emsg || error || got_int); if (called_emsg || error) { rettv->vval.v_number = -3; } else if (got_int) { got_int = false; vgetc(); rettv->vval.v_number = -2; } else if (tv_get_number_chk(&exprval, &error)) { rettv->vval.v_number = 0; } called_emsg = save_called_emsg; // Stop dummy timer time_watcher_stop(tw); time_watcher_close(tw, dummy_timer_close_cb); } // "win_screenpos()" function static void f_win_screenpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) { tv_list_alloc_ret(rettv, 2); const win_T *const wp = find_win_by_nr_or_id(&argvars[0]); tv_list_append_number(rettv->vval.v_list, wp == NULL ? 0 : wp->w_winrow + 1); tv_list_append_number(rettv->vval.v_list, wp == NULL ? 0 : wp->w_wincol + 1); } // "getwinpos({timeout})" function static void f_getwinpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) { tv_list_alloc_ret(rettv, 2); tv_list_append_number(rettv->vval.v_list, -1); tv_list_append_number(rettv->vval.v_list, -1); } /* * "getwinposx()" function */ static void f_getwinposx(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = -1; } /* * "getwinposy()" function */ static void f_getwinposy(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = -1; } /* * Find window specified by "vp" in tabpage "tp". */ static win_T * find_win_by_nr ( typval_T *vp, tabpage_T *tp /* NULL for current tab page */ ) { int nr = (int)tv_get_number_chk(vp, NULL); if (nr < 0) { return NULL; } if (nr == 0) { return curwin; } // This method accepts NULL as an alias for curtab. if (tp == NULL) { tp = curtab; } FOR_ALL_WINDOWS_IN_TAB(wp, tp) { if (nr >= LOWEST_WIN_ID) { if (wp->handle == nr) { return wp; } } else if (--nr <= 0) { return wp; } } return NULL; } /// Find window specified by "wvp" in tabpage "tvp". static win_T *find_tabwin(typval_T *wvp, typval_T *tvp) { win_T *wp = NULL; tabpage_T *tp = NULL; if (wvp->v_type != VAR_UNKNOWN) { if (tvp->v_type != VAR_UNKNOWN) { long n = tv_get_number(tvp); if (n >= 0) { tp = find_tabpage(n); } } else { tp = curtab; } if (tp != NULL) { wp = find_win_by_nr(wvp, tp); } } else { wp = curwin; } return wp; } /// "getwinvar()" function static void f_getwinvar(typval_T *argvars, typval_T *rettv, FunPtr fptr) { getwinvar(argvars, rettv, 0); } /* * getwinvar() and gettabwinvar() */ static void getwinvar( typval_T *argvars, typval_T *rettv, int off /* 1 for gettabwinvar() */ ) { win_T *win, *oldcurwin; dictitem_T *v; tabpage_T *tp = NULL; tabpage_T *oldtabpage = NULL; bool done = false; if (off == 1) { tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL)); } else { tp = curtab; } win = find_win_by_nr(&argvars[off], tp); const char *varname = tv_get_string_chk(&argvars[off + 1]); rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; emsg_off++; if (win != NULL && varname != NULL) { // Set curwin to be our win, temporarily. Also set the tabpage, // otherwise the window is not valid. Only do this when needed, // autocommands get blocked. bool need_switch_win = tp != curtab || win != curwin; if (!need_switch_win || switch_win(&oldcurwin, &oldtabpage, win, tp, true) == OK) { if (*varname == '&') { if (varname[1] == NUL) { // get all window-local options in a dict dict_T *opts = get_winbuf_options(false); if (opts != NULL) { tv_dict_set_ret(rettv, opts); done = true; } } else if (get_option_tv(&varname, rettv, 1) == OK) { // window-local-option done = true; } } else { // Look up the variable. // Let getwinvar({nr}, "") return the "w:" dictionary. v = find_var_in_ht(&win->w_vars->dv_hashtab, 'w', varname, strlen(varname), false); if (v != NULL) { tv_copy(&v->di_tv, rettv); done = true; } } } if (need_switch_win) { // restore previous notion of curwin restore_win(oldcurwin, oldtabpage, true); } } emsg_off--; if (!done && argvars[off + 2].v_type != VAR_UNKNOWN) { // use the default return value tv_copy(&argvars[off + 2], rettv); } } /* * "glob()" function */ static void f_glob(typval_T *argvars, typval_T *rettv, FunPtr fptr) { int options = WILD_SILENT|WILD_USE_NL; expand_T xpc; bool error = false; /* When the optional second argument is non-zero, don't remove matches * for 'wildignore' and don't put matches for 'suffixes' at the end. */ rettv->v_type = VAR_STRING; if (argvars[1].v_type != VAR_UNKNOWN) { if (tv_get_number_chk(&argvars[1], &error)) { options |= WILD_KEEP_ALL; } if (argvars[2].v_type != VAR_UNKNOWN) { if (tv_get_number_chk(&argvars[2], &error)) { tv_list_set_ret(rettv, NULL); } if (argvars[3].v_type != VAR_UNKNOWN && tv_get_number_chk(&argvars[3], &error)) { options |= WILD_ALLLINKS; } } } if (!error) { ExpandInit(&xpc); xpc.xp_context = EXPAND_FILES; if (p_wic) options += WILD_ICASE; if (rettv->v_type == VAR_STRING) { rettv->vval.v_string = ExpandOne( &xpc, (char_u *)tv_get_string(&argvars[0]), NULL, options, WILD_ALL); } else { ExpandOne(&xpc, (char_u *)tv_get_string(&argvars[0]), NULL, options, WILD_ALL_KEEP); tv_list_alloc_ret(rettv, xpc.xp_numfiles); for (int i = 0; i < xpc.xp_numfiles; i++) { tv_list_append_string(rettv->vval.v_list, (const char *)xpc.xp_files[i], -1); } ExpandCleanup(&xpc); } } else rettv->vval.v_string = NULL; } /// "globpath()" function static void f_globpath(typval_T *argvars, typval_T *rettv, FunPtr fptr) { int flags = 0; // Flags for globpath. bool error = false; // Return a string, or a list if the optional third argument is non-zero. rettv->v_type = VAR_STRING; if (argvars[2].v_type != VAR_UNKNOWN) { // When the optional second argument is non-zero, don't remove matches // for 'wildignore' and don't put matches for 'suffixes' at the end. if (tv_get_number_chk(&argvars[2], &error)) { flags |= WILD_KEEP_ALL; } if (argvars[3].v_type != VAR_UNKNOWN) { if (tv_get_number_chk(&argvars[3], &error)) { tv_list_set_ret(rettv, NULL); } if (argvars[4].v_type != VAR_UNKNOWN && tv_get_number_chk(&argvars[4], &error)) { flags |= WILD_ALLLINKS; } } } char buf1[NUMBUFLEN]; const char *const file = tv_get_string_buf_chk(&argvars[1], buf1); if (file != NULL && !error) { garray_T ga; ga_init(&ga, (int)sizeof(char_u *), 10); globpath((char_u *)tv_get_string(&argvars[0]), (char_u *)file, &ga, flags); if (rettv->v_type == VAR_STRING) { rettv->vval.v_string = ga_concat_strings_sep(&ga, "\n"); } else { tv_list_alloc_ret(rettv, ga.ga_len); for (int i = 0; i < ga.ga_len; i++) { tv_list_append_string(rettv->vval.v_list, ((const char **)(ga.ga_data))[i], -1); } } ga_clear_strings(&ga); } else { rettv->vval.v_string = NULL; } } // "glob2regpat()" function static void f_glob2regpat(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *const pat = tv_get_string_chk(&argvars[0]); // NULL on type error rettv->v_type = VAR_STRING; rettv->vval.v_string = ((pat == NULL) ? NULL : file_pat_to_reg_pat((char_u *)pat, NULL, NULL, false)); } /// "has()" function static void f_has(typval_T *argvars, typval_T *rettv, FunPtr fptr) { static const char *const has_list[] = { #ifdef UNIX "unix", #endif #if defined(WIN32) "win32", #endif #if defined(WIN64) || defined(_WIN64) "win64", #endif "fname_case", #ifdef HAVE_ACL "acl", #endif "autochdir", "arabic", "autocmd", "browsefilter", "byte_offset", "cindent", "cmdline_compl", "cmdline_hist", "comments", "conceal", "cscope", "cursorbind", "cursorshape", #ifdef DEBUG "debug", #endif "dialog_con", "diff", "digraphs", "eval", /* always present, of course! */ "ex_extra", "extra_search", "file_in_path", "filterpipe", "find_in_path", "float", "folding", #if defined(UNIX) "fork", #endif "gettext", #if defined(HAVE_ICONV) "iconv", #endif "insert_expand", "jumplist", "keymap", "lambda", "langmap", "libcall", "linebreak", "lispindent", "listcmds", "localmap", #ifdef __APPLE__ "mac", "macunix", "osx", "osxdarwin", #endif "menu", "mksession", "modify_fname", "mouse", "multi_byte", "multi_lang", "num64", "packages", "path_extra", "persistent_undo", "postscript", "printer", "profile", "pythonx", "reltime", "quickfix", "rightleft", "scrollbind", "showcmd", "cmdline_info", "shada", "signs", "smartindent", "startuptime", "statusline", "spell", "syntax", #if !defined(UNIX) "system", // TODO(SplinterOfChaos): This IS defined for UNIX! #endif "tablineat", "tag_binary", "termguicolors", "termresponse", "textobjects", "timers", "title", "user-commands", /* was accidentally included in 5.4 */ "user_commands", "vertsplit", "virtualedit", "visual", "visualextra", "vreplace", "wildignore", "wildmenu", "windows", "winaltkeys", "writebackup", #if defined(HAVE_WSL) "wsl", #endif "nvim", }; bool n = false; const char *const name = tv_get_string(&argvars[0]); for (size_t i = 0; i < ARRAY_SIZE(has_list); i++) { if (STRICMP(name, has_list[i]) == 0) { n = true; break; } } if (!n) { if (STRNICMP(name, "patch", 5) == 0) { if (name[5] == '-' && strlen(name) >= 11 && ascii_isdigit(name[6]) && ascii_isdigit(name[8]) && ascii_isdigit(name[10])) { int major = atoi(name + 6); int minor = atoi(name + 8); // Expect "patch-9.9.01234". n = (major < VIM_VERSION_MAJOR || (major == VIM_VERSION_MAJOR && (minor < VIM_VERSION_MINOR || (minor == VIM_VERSION_MINOR && has_vim_patch(atoi(name + 10)))))); } else { n = has_vim_patch(atoi(name + 5)); } } else if (STRNICMP(name, "nvim-", 5) == 0) { // Expect "nvim-x.y.z" n = has_nvim_version(name + 5); } else if (STRICMP(name, "vim_starting") == 0) { n = (starting != 0); } else if (STRICMP(name, "ttyin") == 0) { n = stdin_isatty; } else if (STRICMP(name, "ttyout") == 0) { n = stdout_isatty; } else if (STRICMP(name, "multi_byte_encoding") == 0) { n = has_mbyte != 0; } else if (STRICMP(name, "syntax_items") == 0) { n = syntax_present(curwin); #ifdef UNIX } else if (STRICMP(name, "unnamedplus") == 0) { n = eval_has_provider("clipboard"); #endif } } if (!n && eval_has_provider(name)) { n = true; } rettv->vval.v_number = n; } /* * "has_key()" function */ static void f_has_key(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type != VAR_DICT) { EMSG(_(e_dictreq)); return; } if (argvars[0].vval.v_dict == NULL) return; rettv->vval.v_number = tv_dict_find(argvars[0].vval.v_dict, tv_get_string(&argvars[1]), -1) != NULL; } /// `haslocaldir([{win}[, {tab}]])` function /// /// Returns `1` if the scope object has a local directory, `0` otherwise. If a /// scope object is not specified the current one is implied. This function /// share a lot of code with `f_getcwd`. /// /// @pre The arguments must be of type number. /// @pre There may not be more than two arguments. /// @pre An argument may not be -1 if preceding arguments are not all -1. /// /// @post The return value will be either the number `1` or `0`. static void f_haslocaldir(typval_T *argvars, typval_T *rettv, FunPtr fptr) { // Possible scope of working directory to return. CdScope scope = kCdScopeInvalid; // Numbers of the scope objects (window, tab) we want the working directory // of. A `-1` means to skip this scope, a `0` means the current object. int scope_number[] = { [kCdScopeWindow] = 0, // Number of window to look at. [kCdScopeTab ] = 0, // Number of tab to look at. }; tabpage_T *tp = curtab; // The tabpage to look at. win_T *win = curwin; // The window to look at. rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; // Pre-conditions and scope extraction together for (int i = MIN_CD_SCOPE; i < MAX_CD_SCOPE; i++) { if (argvars[i].v_type == VAR_UNKNOWN) { break; } if (argvars[i].v_type != VAR_NUMBER) { EMSG(_(e_invarg)); return; } scope_number[i] = argvars[i].vval.v_number; if (scope_number[i] < -1) { EMSG(_(e_invarg)); return; } // Use the narrowest scope the user requested if (scope_number[i] >= 0 && scope == kCdScopeInvalid) { // The scope is the current iteration step. scope = i; } else if (scope_number[i] < 0) { scope = i + 1; } } // If the user didn't specify anything, default to window scope if (scope == kCdScopeInvalid) { scope = MIN_CD_SCOPE; } // Find the tabpage by number if (scope_number[kCdScopeTab] > 0) { tp = find_tabpage(scope_number[kCdScopeTab]); if (!tp) { EMSG(_("E5000: Cannot find tab number.")); return; } } // Find the window in `tp` by number, `NULL` if none. if (scope_number[kCdScopeWindow] >= 0) { if (scope_number[kCdScopeTab] < 0) { EMSG(_("E5001: Higher scope cannot be -1 if lower scope is >= 0.")); return; } if (scope_number[kCdScopeWindow] > 0) { win = find_win_by_nr(&argvars[0], tp); if (!win) { EMSG(_("E5002: Cannot find window number.")); return; } } } switch (scope) { case kCdScopeWindow: assert(win); rettv->vval.v_number = win->w_localdir ? 1 : 0; break; case kCdScopeTab: assert(tp); rettv->vval.v_number = tp->tp_localdir ? 1 : 0; break; case kCdScopeGlobal: // The global scope never has a local directory rettv->vval.v_number = 0; break; case kCdScopeInvalid: // We should never get here assert(false); } } /* * "hasmapto()" function */ static void f_hasmapto(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const char *mode; const char *const name = tv_get_string(&argvars[0]); bool abbr = false; char buf[NUMBUFLEN]; if (argvars[1].v_type == VAR_UNKNOWN) { mode = "nvo"; } else { mode = tv_get_string_buf(&argvars[1], buf); if (argvars[2].v_type != VAR_UNKNOWN) { abbr = tv_get_number(&argvars[2]); } } if (map_to_exists(name, mode, abbr)) { rettv->vval.v_number = true; } else { rettv->vval.v_number = false; } } /* * "histadd()" function */ static void f_histadd(typval_T *argvars, typval_T *rettv, FunPtr fptr) { HistoryType histype; rettv->vval.v_number = false; if (check_restricted() || check_secure()) { return; } const char *str = tv_get_string_chk(&argvars[0]); // NULL on type error histype = str != NULL ? get_histtype(str, strlen(str), false) : HIST_INVALID; if (histype != HIST_INVALID) { char buf[NUMBUFLEN]; str = tv_get_string_buf(&argvars[1], buf); if (*str != NUL) { init_history(); add_to_history(histype, (char_u *)str, false, NUL); rettv->vval.v_number = true; return; } } } /* * "histdel()" function */ static void f_histdel(typval_T *argvars, typval_T *rettv, FunPtr fptr) { int n; const char *const str = tv_get_string_chk(&argvars[0]); // NULL on type error if (str == NULL) { n = 0; } else if (argvars[1].v_type == VAR_UNKNOWN) { // only one argument: clear entire history n = clr_history(get_histtype(str, strlen(str), false)); } else if (argvars[1].v_type == VAR_NUMBER) { // index given: remove that entry n = del_history_idx(get_histtype(str, strlen(str), false), (int)tv_get_number(&argvars[1])); } else { // string given: remove all matching entries char buf[NUMBUFLEN]; n = del_history_entry(get_histtype(str, strlen(str), false), (char_u *)tv_get_string_buf(&argvars[1], buf)); } rettv->vval.v_number = n; } /* * "histget()" function */ static void f_histget(typval_T *argvars, typval_T *rettv, FunPtr fptr) { HistoryType type; int idx; const char *const str = tv_get_string_chk(&argvars[0]); // NULL on type error if (str == NULL) { rettv->vval.v_string = NULL; } else { type = get_histtype(str, strlen(str), false); if (argvars[1].v_type == VAR_UNKNOWN) { idx = get_history_idx(type); } else { idx = (int)tv_get_number_chk(&argvars[1], NULL); } // -1 on type error rettv->vval.v_string = vim_strsave(get_history_entry(type, idx)); } rettv->v_type = VAR_STRING; } /* * "histnr()" function */ static void f_histnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) { int i; const char *const history = tv_get_string_chk(&argvars[0]); i = history == NULL ? HIST_CMD - 1 : get_histtype(history, strlen(history), false); if (i != HIST_INVALID) { i = get_history_idx(i); } else { i = -1; } rettv->vval.v_number = i; } /* * "highlightID(name)" function */ static void f_hlID(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = syn_name2id( (const char_u *)tv_get_string(&argvars[0])); } /* * "highlight_exists()" function */ static void f_hlexists(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = highlight_exists( (const char_u *)tv_get_string(&argvars[0])); } /* * "hostname()" function */ static void f_hostname(typval_T *argvars, typval_T *rettv, FunPtr fptr) { char hostname[256]; os_get_hostname(hostname, 256); rettv->v_type = VAR_STRING; rettv->vval.v_string = vim_strsave((char_u *)hostname); } /* * iconv() function */ static void f_iconv(typval_T *argvars, typval_T *rettv, FunPtr fptr) { vimconv_T vimconv; rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; const char *const str = tv_get_string(&argvars[0]); char buf1[NUMBUFLEN]; char_u *const from = enc_canonize(enc_skip( (char_u *)tv_get_string_buf(&argvars[1], buf1))); char buf2[NUMBUFLEN]; char_u *const to = enc_canonize(enc_skip( (char_u *)tv_get_string_buf(&argvars[2], buf2))); vimconv.vc_type = CONV_NONE; convert_setup(&vimconv, from, to); // If the encodings are equal, no conversion needed. if (vimconv.vc_type == CONV_NONE) { rettv->vval.v_string = (char_u *)xstrdup(str); } else { rettv->vval.v_string = string_convert(&vimconv, (char_u *)str, NULL); } convert_setup(&vimconv, NULL, NULL); xfree(from); xfree(to); } /* * "indent()" function */ static void f_indent(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const linenr_T lnum = tv_get_lnum(argvars); if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { rettv->vval.v_number = get_indent_lnum(lnum); } else { rettv->vval.v_number = -1; } } /* * "index()" function */ static void f_index(typval_T *argvars, typval_T *rettv, FunPtr fptr) { long idx = 0; bool ic = false; rettv->vval.v_number = -1; if (argvars[0].v_type != VAR_LIST) { EMSG(_(e_listreq)); return; } list_T *const l = argvars[0].vval.v_list; if (l != NULL) { listitem_T *item = tv_list_first(l); if (argvars[2].v_type != VAR_UNKNOWN) { bool error = false; // Start at specified item. idx = tv_list_uidx(l, tv_get_number_chk(&argvars[2], &error)); if (error || idx == -1) { item = NULL; } else { item = tv_list_find(l, idx); assert(item != NULL); } if (argvars[3].v_type != VAR_UNKNOWN) { ic = !!tv_get_number_chk(&argvars[3], &error); if (error) { item = NULL; } } } for (; item != NULL; item = TV_LIST_ITEM_NEXT(l, item), idx++) { if (tv_equal(TV_LIST_ITEM_TV(item), &argvars[1], ic, false)) { rettv->vval.v_number = idx; break; } } } } static int inputsecret_flag = 0; /* * This function is used by f_input() and f_inputdialog() functions. The third * argument to f_input() specifies the type of completion to use at the * prompt. The third argument to f_inputdialog() specifies the value to return * when the user cancels the prompt. */ void get_user_input(const typval_T *const argvars, typval_T *const rettv, const bool inputdialog) FUNC_ATTR_NONNULL_ALL { rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; const char *prompt = ""; const char *defstr = ""; const char *cancelreturn = NULL; const char *xp_name = NULL; Callback input_callback = { .type = kCallbackNone }; char prompt_buf[NUMBUFLEN]; char defstr_buf[NUMBUFLEN]; char cancelreturn_buf[NUMBUFLEN]; char xp_name_buf[NUMBUFLEN]; char def[1] = { 0 }; if (argvars[0].v_type == VAR_DICT) { if (argvars[1].v_type != VAR_UNKNOWN) { EMSG(_("E5050: {opts} must be the only argument")); return; } dict_T *const dict = argvars[0].vval.v_dict; prompt = tv_dict_get_string_buf_chk(dict, S_LEN("prompt"), prompt_buf, ""); if (prompt == NULL) { return; } defstr = tv_dict_get_string_buf_chk(dict, S_LEN("default"), defstr_buf, ""); if (defstr == NULL) { return; } cancelreturn = tv_dict_get_string_buf_chk(dict, S_LEN("cancelreturn"), cancelreturn_buf, def); if (cancelreturn == NULL) { // error return; } if (*cancelreturn == NUL) { cancelreturn = NULL; } xp_name = tv_dict_get_string_buf_chk(dict, S_LEN("completion"), xp_name_buf, def); if (xp_name == NULL) { // error return; } if (xp_name == def) { // default to NULL xp_name = NULL; } if (!tv_dict_get_callback(dict, S_LEN("highlight"), &input_callback)) { return; } } else { prompt = tv_get_string_buf_chk(&argvars[0], prompt_buf); if (prompt == NULL) { return; } if (argvars[1].v_type != VAR_UNKNOWN) { defstr = tv_get_string_buf_chk(&argvars[1], defstr_buf); if (defstr == NULL) { return; } if (argvars[2].v_type != VAR_UNKNOWN) { const char *const arg2 = tv_get_string_buf_chk(&argvars[2], cancelreturn_buf); if (arg2 == NULL) { return; } if (inputdialog) { cancelreturn = arg2; } else { xp_name = arg2; } } } } int xp_type = EXPAND_NOTHING; char *xp_arg = NULL; if (xp_name != NULL) { // input() with a third argument: completion const int xp_namelen = (int)strlen(xp_name); uint32_t argt; if (parse_compl_arg((char_u *)xp_name, xp_namelen, &xp_type, &argt, (char_u **)&xp_arg) == FAIL) { return; } } const bool cmd_silent_save = cmd_silent; cmd_silent = false; // Want to see the prompt. // Only the part of the message after the last NL is considered as // prompt for the command line, unlsess cmdline is externalized const char *p = prompt; if (!ui_has(kUICmdline)) { const char *lastnl = strrchr(prompt, '\n'); if (lastnl != NULL) { p = lastnl+1; msg_start(); msg_clr_eos(); msg_puts_attr_len(prompt, p - prompt, echo_attr); msg_didout = false; msg_starthere(); } } cmdline_row = msg_row; stuffReadbuffSpec(defstr); const int save_ex_normal_busy = ex_normal_busy; ex_normal_busy = 0; rettv->vval.v_string = (char_u *)getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr, xp_type, xp_arg, input_callback); ex_normal_busy = save_ex_normal_busy; callback_free(&input_callback); if (rettv->vval.v_string == NULL && cancelreturn != NULL) { rettv->vval.v_string = (char_u *)xstrdup(cancelreturn); } xfree(xp_arg); // Since the user typed this, no need to wait for return. need_wait_return = false; msg_didout = false; cmd_silent = cmd_silent_save; } /* * "input()" function * Also handles inputsecret() when inputsecret is set. */ static void f_input(typval_T *argvars, typval_T *rettv, FunPtr fptr) { get_user_input(argvars, rettv, FALSE); } /* * "inputdialog()" function */ static void f_inputdialog(typval_T *argvars, typval_T *rettv, FunPtr fptr) { get_user_input(argvars, rettv, TRUE); } /* * "inputlist()" function */ static void f_inputlist(typval_T *argvars, typval_T *rettv, FunPtr fptr) { int selected; int mouse_used; if (argvars[0].v_type != VAR_LIST) { EMSG2(_(e_listarg), "inputlist()"); return; } msg_start(); msg_row = Rows - 1; /* for when 'cmdheight' > 1 */ lines_left = Rows; /* avoid more prompt */ msg_scroll = TRUE; msg_clr_eos(); TV_LIST_ITER_CONST(argvars[0].vval.v_list, li, { msg_puts(tv_get_string(TV_LIST_ITEM_TV(li))); msg_putchar('\n'); }); // Ask for choice. selected = prompt_for_number(&mouse_used); if (mouse_used) { selected -= lines_left; } rettv->vval.v_number = selected; } static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL}; /// "inputrestore()" function static void f_inputrestore(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (!GA_EMPTY(&ga_userinput)) { ga_userinput.ga_len--; restore_typeahead((tasave_T *)(ga_userinput.ga_data) + ga_userinput.ga_len); // default return is zero == OK } else if (p_verbose > 1) { verb_msg(_("called inputrestore() more often than inputsave()")); rettv->vval.v_number = 1; // Failed } } /// "inputsave()" function static void f_inputsave(typval_T *argvars, typval_T *rettv, FunPtr fptr) { // Add an entry to the stack of typeahead storage. tasave_T *p = GA_APPEND_VIA_PTR(tasave_T, &ga_userinput); save_typeahead(p); } /// "inputsecret()" function static void f_inputsecret(typval_T *argvars, typval_T *rettv, FunPtr fptr) { cmdline_star++; inputsecret_flag++; f_input(argvars, rettv, NULL); cmdline_star--; inputsecret_flag--; } /* * "insert()" function */ static void f_insert(typval_T *argvars, typval_T *rettv, FunPtr fptr) { list_T *l; bool error = false; if (argvars[0].v_type != VAR_LIST) { EMSG2(_(e_listarg), "insert()"); } else if (!tv_check_lock(tv_list_locked((l = argvars[0].vval.v_list)), N_("insert() argument"), TV_TRANSLATE)) { long before = 0; if (argvars[2].v_type != VAR_UNKNOWN) { before = tv_get_number_chk(&argvars[2], &error); } if (error) { // type error; errmsg already given return; } listitem_T *item = NULL; if (before != tv_list_len(l)) { item = tv_list_find(l, before); if (item == NULL) { EMSGN(_(e_listidx), before); l = NULL; } } if (l != NULL) { tv_list_insert_tv(l, &argvars[1], item); tv_copy(&argvars[0], rettv); } } } /* * "invert(expr)" function */ static void f_invert(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = ~tv_get_number_chk(&argvars[0], NULL); } /* * "isdirectory()" function */ static void f_isdirectory(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = os_isdir((const char_u *)tv_get_string(&argvars[0])); } /* * "islocked()" function */ static void f_islocked(typval_T *argvars, typval_T *rettv, FunPtr fptr) { lval_T lv; dictitem_T *di; rettv->vval.v_number = -1; const char_u *const end = get_lval((char_u *)tv_get_string(&argvars[0]), NULL, &lv, false, false, GLV_NO_AUTOLOAD|GLV_READ_ONLY, FNE_CHECK_START); if (end != NULL && lv.ll_name != NULL) { if (*end != NUL) { EMSG(_(e_trailing)); } else { if (lv.ll_tv == NULL) { di = find_var((const char *)lv.ll_name, lv.ll_name_len, NULL, true); if (di != NULL) { // Consider a variable locked when: // 1. the variable itself is locked // 2. the value of the variable is locked. // 3. the List or Dict value is locked. rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK) || tv_islocked(&di->di_tv)); } } else if (lv.ll_range) { EMSG(_("E786: Range not allowed")); } else if (lv.ll_newkey != NULL) { EMSG2(_(e_dictkey), lv.ll_newkey); } else if (lv.ll_list != NULL) { // List item. rettv->vval.v_number = tv_islocked(TV_LIST_ITEM_TV(lv.ll_li)); } else { // Dictionary item. rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv); } } } clear_lval(&lv); } // "isinf()" function static void f_isinf(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type == VAR_FLOAT && xisinf(argvars[0].vval.v_float)) { rettv->vval.v_number = argvars[0].vval.v_float > 0.0 ? 1 : -1; } } // "isnan()" function static void f_isnan(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = argvars[0].v_type == VAR_FLOAT && xisnan(argvars[0].vval.v_float); } /// Turn a dictionary into a list /// /// @param[in] tv Dictionary to convert. Is checked for actually being /// a dictionary, will give an error if not. /// @param[out] rettv Location where result will be saved. /// @param[in] what What to save in rettv. static void dict_list(typval_T *const tv, typval_T *const rettv, const DictListType what) { if (tv->v_type != VAR_DICT) { EMSG(_(e_dictreq)); return; } if (tv->vval.v_dict == NULL) { return; } tv_list_alloc_ret(rettv, tv_dict_len(tv->vval.v_dict)); TV_DICT_ITER(tv->vval.v_dict, di, { typval_T tv_item = { .v_lock = VAR_UNLOCKED }; switch (what) { case kDictListKeys: { tv_item.v_type = VAR_STRING; tv_item.vval.v_string = vim_strsave(di->di_key); break; } case kDictListValues: { tv_copy(&di->di_tv, &tv_item); break; } case kDictListItems: { // items() list_T *const sub_l = tv_list_alloc(2); tv_item.v_type = VAR_LIST; tv_item.vval.v_list = sub_l; tv_list_ref(sub_l); tv_list_append_owned_tv(sub_l, (typval_T) { .v_type = VAR_STRING, .v_lock = VAR_UNLOCKED, .vval.v_string = (char_u *)xstrdup((const char *)di->di_key), }); tv_list_append_tv(sub_l, &di->di_tv); break; } } tv_list_append_owned_tv(rettv->vval.v_list, tv_item); }); } /// "id()" function static void f_id(typval_T *argvars, typval_T *rettv, FunPtr fptr) FUNC_ATTR_NONNULL_ALL { const int len = vim_vsnprintf_typval(NULL, 0, "%p", dummy_ap, argvars); rettv->v_type = VAR_STRING; rettv->vval.v_string = xmalloc(len + 1); vim_vsnprintf_typval((char *)rettv->vval.v_string, len + 1, "%p", dummy_ap, argvars); } /* * "items(dict)" function */ static void f_items(typval_T *argvars, typval_T *rettv, FunPtr fptr) { dict_list(argvars, rettv, 2); } // "jobpid(id)" function static void f_jobpid(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; if (check_restricted() || check_secure()) { return; } if (argvars[0].v_type != VAR_NUMBER) { EMSG(_(e_invarg)); return; } Channel *data = find_job(argvars[0].vval.v_number, true); if (!data) { return; } Process *proc = (Process *)&data->stream.proc; rettv->vval.v_number = proc->pid; } // "jobresize(job, width, height)" function static void f_jobresize(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; if (check_restricted() || check_secure()) { return; } if (argvars[0].v_type != VAR_NUMBER || argvars[1].v_type != VAR_NUMBER || argvars[2].v_type != VAR_NUMBER) { // job id, width, height EMSG(_(e_invarg)); return; } Channel *data = find_job(argvars[0].vval.v_number, true); if (!data) { return; } if (data->stream.proc.type != kProcessTypePty) { EMSG(_(e_channotpty)); return; } pty_process_resize(&data->stream.pty, argvars[1].vval.v_number, argvars[2].vval.v_number); rettv->vval.v_number = 1; } /// Builds a process argument vector from a VimL object (typval_T). /// /// @param[in] cmd_tv VimL object /// @param[out] cmd Returns the command or executable name. /// @param[out] executable Returns `false` if argv[0] is not executable. /// /// @returns Result of `shell_build_argv()` if `cmd_tv` is a String. /// Else, string values of `cmd_tv` copied to a (char **) list with /// argv[0] resolved to full path ($PATHEXT-resolved on Windows). static char **tv_to_argv(typval_T *cmd_tv, const char **cmd, bool *executable) { if (cmd_tv->v_type == VAR_STRING) { // String => "shell semantics". const char *cmd_str = tv_get_string(cmd_tv); if (cmd) { *cmd = cmd_str; } return shell_build_argv(cmd_str, NULL); } if (cmd_tv->v_type != VAR_LIST) { EMSG2(_(e_invarg2), "expected String or List"); return NULL; } list_T *argl = cmd_tv->vval.v_list; int argc = tv_list_len(argl); if (!argc) { EMSG(_(e_invarg)); // List must have at least one item. return NULL; } const char *arg0 = tv_get_string_chk(TV_LIST_ITEM_TV(tv_list_first(argl))); char *exe_resolved = NULL; if (!arg0 || !os_can_exe(arg0, &exe_resolved, true)) { if (arg0 && executable) { *executable = false; } return NULL; } if (cmd) { *cmd = exe_resolved; } // Build the argument vector int i = 0; char **argv = xcalloc(argc + 1, sizeof(char *)); TV_LIST_ITER_CONST(argl, arg, { const char *a = tv_get_string_chk(TV_LIST_ITEM_TV(arg)); if (!a) { // Did emsg in tv_get_string_chk; just deallocate argv. shell_free_argv(argv); xfree(exe_resolved); return NULL; } argv[i++] = xstrdup(a); }); // Replace argv[0] with absolute path. The only reason for this is to make // $PATHEXT work on Windows with jobstart([…]). #9569 xfree(argv[0]); argv[0] = exe_resolved; return argv; } // "jobstart()" function static void f_jobstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; if (check_restricted() || check_secure()) { return; } bool executable = true; char **argv = tv_to_argv(&argvars[0], NULL, &executable); if (!argv) { rettv->vval.v_number = executable ? 0 : -1; return; // Did error message in tv_to_argv. } if (argvars[1].v_type != VAR_DICT && argvars[1].v_type != VAR_UNKNOWN) { // Wrong argument types EMSG2(_(e_invarg2), "expected dictionary"); shell_free_argv(argv); return; } dict_T *job_opts = NULL; bool detach = false; bool rpc = false; bool pty = false; CallbackReader on_stdout = CALLBACK_READER_INIT, on_stderr = CALLBACK_READER_INIT; Callback on_exit = CALLBACK_NONE; char *cwd = NULL; if (argvars[1].v_type == VAR_DICT) { job_opts = argvars[1].vval.v_dict; detach = tv_dict_get_number(job_opts, "detach") != 0; rpc = tv_dict_get_number(job_opts, "rpc") != 0; pty = tv_dict_get_number(job_opts, "pty") != 0; if (pty && rpc) { EMSG2(_(e_invarg2), "job cannot have both 'pty' and 'rpc' options set"); shell_free_argv(argv); return; } char *new_cwd = tv_dict_get_string(job_opts, "cwd", false); if (new_cwd && strlen(new_cwd) > 0) { cwd = new_cwd; // The new cwd must be a directory. if (!os_isdir_executable((const char *)cwd)) { EMSG2(_(e_invarg2), "expected valid directory"); shell_free_argv(argv); return; } } if (!common_job_callbacks(job_opts, &on_stdout, &on_stderr, &on_exit)) { shell_free_argv(argv); return; } } uint16_t width = 0, height = 0; char *term_name = NULL; if (pty) { width = (uint16_t)tv_dict_get_number(job_opts, "width"); height = (uint16_t)tv_dict_get_number(job_opts, "height"); term_name = tv_dict_get_string(job_opts, "TERM", true); } Channel *chan = channel_job_start(argv, on_stdout, on_stderr, on_exit, pty, rpc, detach, cwd, width, height, term_name, &rettv->vval.v_number); if (chan) { channel_create_event(chan, NULL); } } // "jobstop()" function static void f_jobstop(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; if (check_restricted() || check_secure()) { return; } if (argvars[0].v_type != VAR_NUMBER) { // Only argument is the job id EMSG(_(e_invarg)); return; } Channel *data = find_job(argvars[0].vval.v_number, true); if (!data) { return; } const char *error = NULL; if (data->is_rpc) { // Ignore return code, but show error later. (void)channel_close(data->id, kChannelPartRpc, &error); } process_stop((Process *)&data->stream.proc); rettv->vval.v_number = 1; if (error) { EMSG(error); } } // "jobwait(ids[, timeout])" function static void f_jobwait(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; if (check_restricted() || check_secure()) { return; } if (argvars[0].v_type != VAR_LIST || (argvars[1].v_type != VAR_NUMBER && argvars[1].v_type != VAR_UNKNOWN)) { EMSG(_(e_invarg)); return; } ui_busy_start(); list_T *args = argvars[0].vval.v_list; Channel **jobs = xcalloc(tv_list_len(args), sizeof(*jobs)); MultiQueue *waiting_jobs = multiqueue_new_parent(loop_on_put, &main_loop); // Validate, prepare jobs for waiting. int i = 0; TV_LIST_ITER_CONST(args, arg, { Channel *chan = NULL; if (TV_LIST_ITEM_TV(arg)->v_type != VAR_NUMBER || !(chan = find_job(TV_LIST_ITEM_TV(arg)->vval.v_number, false))) { jobs[i] = NULL; // Invalid job. } else { jobs[i] = chan; channel_incref(chan); if (chan->stream.proc.status < 0) { // Process any pending events on the job's queue before temporarily // replacing it. multiqueue_process_events(chan->events); multiqueue_replace_parent(chan->events, waiting_jobs); } } i++; }); int remaining = -1; uint64_t before = 0; if (argvars[1].v_type == VAR_NUMBER && argvars[1].vval.v_number >= 0) { remaining = argvars[1].vval.v_number; before = os_hrtime(); } for (i = 0; i < tv_list_len(args); i++) { if (remaining == 0) { break; // Timeout. } if (jobs[i] == NULL) { continue; // Invalid job, will assign status=-3 below. } int status = process_wait(&jobs[i]->stream.proc, remaining, waiting_jobs); if (status < 0) { break; // Interrupted (CTRL-C) or timeout, skip remaining jobs. } if (remaining > 0) { uint64_t now = os_hrtime(); remaining = MIN(0, remaining - (int)((now - before) / 1000000)); before = now; } } list_T *const rv = tv_list_alloc(tv_list_len(args)); // For each job: // * Restore its parent queue if the job is still alive. // * Append its status to the output list, or: // -3 for "invalid job id" // -2 for "interrupted" (user hit CTRL-C) // -1 for jobs that were skipped or timed out for (i = 0; i < tv_list_len(args); i++) { if (jobs[i] == NULL) { tv_list_append_number(rv, -3); continue; } multiqueue_process_events(jobs[i]->events); multiqueue_replace_parent(jobs[i]->events, main_loop.events); tv_list_append_number(rv, jobs[i]->stream.proc.status); channel_decref(jobs[i]); } multiqueue_free(waiting_jobs); xfree(jobs); ui_busy_stop(); tv_list_ref(rv); rettv->v_type = VAR_LIST; rettv->vval.v_list = rv; } /* * "join()" function */ static void f_join(typval_T *argvars, typval_T *rettv, FunPtr fptr) { if (argvars[0].v_type != VAR_LIST) { EMSG(_(e_listreq)); return; } const char *const sep = (argvars[1].v_type == VAR_UNKNOWN ? " " : tv_get_string_chk(&argvars[1])); rettv->v_type = VAR_STRING; if (sep != NULL) { garray_T ga; ga_init(&ga, (int)sizeof(char), 80); tv_list_join(&ga, argvars[0].vval.v_list, sep); ga_append(&ga, NUL); rettv->vval.v_string = (char_u *)ga.ga_data; } else { rettv->vval.v_string = NULL; } } /// json_decode() function static void f_json_decode(typval_T *argvars, typval_T *rettv, FunPtr fptr) { char numbuf[NUMBUFLEN]; const char *s = NULL; char *tofree = NULL; size_t len; if (argvars[0].v_type == VAR_LIST) { if (!encode_vim_list_to_buf(argvars[0].vval.v_list, &len, &tofree)) { EMSG(_("E474: Failed to convert list to string")); return; } s = tofree; if (s == NULL) { assert(len == 0); s = ""; } } else { s = tv_get_string_buf_chk(&argvars[0], numbuf); if (s) { len = strlen(s); } else { return; } } if (json_decode_string(s, len, rettv) == FAIL) { emsgf(_("E474: Failed to parse %.*s"), (int)len, s); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = 0; } assert(rettv->v_type != VAR_UNKNOWN); xfree(tofree); } /// json_encode() function static void f_json_encode(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->v_type = VAR_STRING; rettv->vval.v_string = (char_u *) encode_tv2json(&argvars[0], NULL); } /* * "keys()" function */ static void f_keys(typval_T *argvars, typval_T *rettv, FunPtr fptr) { dict_list(argvars, rettv, 0); } /* * "last_buffer_nr()" function. */ static void f_last_buffer_nr(typval_T *argvars, typval_T *rettv, FunPtr fptr) { int n = 0; FOR_ALL_BUFFERS(buf) { if (n < buf->b_fnum) { n = buf->b_fnum; } } rettv->vval.v_number = n; } /* * "len()" function */ static void f_len(typval_T *argvars, typval_T *rettv, FunPtr fptr) { switch (argvars[0].v_type) { case VAR_STRING: case VAR_NUMBER: { rettv->vval.v_number = (varnumber_T)strlen( tv_get_string(&argvars[0])); break; } case VAR_LIST: { rettv->vval.v_number = tv_list_len(argvars[0].vval.v_list); break; } case VAR_DICT: { rettv->vval.v_number = tv_dict_len(argvars[0].vval.v_dict); break; } case VAR_UNKNOWN: case VAR_SPECIAL: case VAR_FLOAT: case VAR_PARTIAL: case VAR_FUNC: { EMSG(_("E701: Invalid type for len()")); break; } } } static void libcall_common(typval_T *argvars, typval_T *rettv, int out_type) { rettv->v_type = out_type; if (out_type != VAR_NUMBER) { rettv->vval.v_string = NULL; } if (check_restricted() || check_secure()) { return; } // The first two args (libname and funcname) must be strings if (argvars[0].v_type != VAR_STRING || argvars[1].v_type != VAR_STRING) { return; } const char *libname = (char *) argvars[0].vval.v_string; const char *funcname = (char *) argvars[1].vval.v_string; int in_type = argvars[2].v_type; // input variables char *str_in = (in_type == VAR_STRING) ? (char *) argvars[2].vval.v_string : NULL; int64_t int_in = argvars[2].vval.v_number; // output variables char **str_out = (out_type == VAR_STRING) ? (char **) &rettv->vval.v_string : NULL; int64_t int_out = 0; bool success = os_libcall(libname, funcname, str_in, int_in, str_out, &int_out); if (!success) { EMSG2(_(e_libcall), funcname); return; } if (out_type == VAR_NUMBER) { rettv->vval.v_number = (int) int_out; } } /* * "libcall()" function */ static void f_libcall(typval_T *argvars, typval_T *rettv, FunPtr fptr) { libcall_common(argvars, rettv, VAR_STRING); } /* * "libcallnr()" function */ static void f_libcallnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) { libcall_common(argvars, rettv, VAR_NUMBER); } /* * "line(string)" function */ static void f_line(typval_T *argvars, typval_T *rettv, FunPtr fptr) { linenr_T lnum = 0; pos_T *fp; int fnum; fp = var2fpos(&argvars[0], TRUE, &fnum); if (fp != NULL) lnum = fp->lnum; rettv->vval.v_number = lnum; } /* * "line2byte(lnum)" function */ static void f_line2byte(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const linenr_T lnum = tv_get_lnum(argvars); if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1) { rettv->vval.v_number = -1; } else { rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL, false); } if (rettv->vval.v_number >= 0) { rettv->vval.v_number++; } } /* * "lispindent(lnum)" function */ static void f_lispindent(typval_T *argvars, typval_T *rettv, FunPtr fptr) { const pos_T pos = curwin->w_cursor; const linenr_T lnum = tv_get_lnum(argvars); if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { curwin->w_cursor.lnum = lnum; rettv->vval.v_number = get_lisp_indent(); curwin->w_cursor = pos; } else { rettv->vval.v_number = -1; } } /* * "localtime()" function */ static void f_localtime(typval_T *argvars, typval_T *rettv, FunPtr fptr) { rettv->vval.v_number = (varnumber_T)time(NULL); } static void get_maparg(typval_T *argvars, typval_T *rettv, int exact) { char_u *keys_buf = NULL; char_u *rhs; int mode; int abbr = FALSE; int get_dict = FALSE; mapblock_T *mp; int buffer_local; // Return empty string for failure. rettv->v_type = VAR_STRING; rettv->vval.v_string = NULL; char_u *keys = (char_u *)tv_get_string(&argvars[0]); if (*keys == NUL) { return; } char buf[NUMBUFLEN]; const char *which; if (argvars[1].v_type != VAR_UNKNOWN) { which = tv_get_string_buf_chk(&argvars[1], buf); if (argvars[2].v_type != VAR_UNKNOWN) { abbr = tv_get_number(&argvars[2]); if (argvars[3].v_type != VAR_UNKNOWN) { get_dict = tv_get_number(&argvars[3]); } } } else { which = ""; } if (which == NULL) { return; } mode = get_map_mode((char_u **)&which, 0); keys = replace_termcodes(keys, STRLEN(keys), &keys_buf, true, true, true, CPO_TO_CPO_FLAGS); rhs = check_map(keys, mode, exact, false, abbr, &mp, &buffer_local); xfree(keys_buf); if (!get_dict) { // Return a string. if (rhs != NULL) { if (*rhs == NUL) { rettv->vval.v_string = vim_strsave((char_u *)""); } else { rettv->vval.v_string = (char_u *)str2special_save( (char *)rhs, false, false); } } } else { tv_dict_alloc_ret(rettv); if (rhs != NULL) { // Return a dictionary. mapblock_fill_dict(rettv->vval.v_dict, mp, buffer_local, true); } } } /// luaeval() function implementation static void f_luaeval(typval_T *argvars, typval_T *rettv, FunPtr fptr) FUNC_ATTR_NONNULL_ALL { const char *const str = (const char *)tv_get_string_chk(&argvars[0]); if (str == NULL) { return; } executor_eval_lua(cstr_as_string((char *)str), &argvars[1], rettv); } /// Fill a dictionary with all applicable maparg() like dictionaries /// /// @param dict The dictionary to be filled /// @param mp The maphash that contains the mapping information /// @param buffer_value The "buffer" value /// @param compatible True for compatible with old maparg() dict void mapblock_fill_dict(dict_T *const dict, const mapblock_T *const mp, long buffer_value, bool compatible) FUNC_ATTR_NONNULL_ALL { char *const lhs = str2special_save((const char *)mp->m_keys, compatible, !compatible); char *const mapmode = map_mode_to_chars(mp->m_mode); varnumber_T noremap_value; if (compatible) { // Keep old compatible behavior // This is unable to determine whether a mapping is a