robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
108.8 KiB3672 linesraw
1// eval/vars.c: functions for dealing with variables
2
3#include <assert.h>
4#include <ctype.h>
5#include <stdbool.h>
6#include <stddef.h>
7#include <stdint.h>
8#include <stdlib.h>
9#include <string.h>
10#include <uv.h>
11
12#include "nvim/ascii_defs.h"
13#include "nvim/autocmd.h"
14#include "nvim/autocmd_defs.h"
15#include "nvim/buffer_defs.h"
16#include "nvim/charset.h"
17#include "nvim/context.h"
18#include "nvim/drawscreen.h"
19#include "nvim/errors.h"
20#include "nvim/eval.h"
21#include "nvim/eval/encode.h"
22#include "nvim/eval/funcs.h"
23#include "nvim/eval/typval.h"
24#include "nvim/eval/typval_defs.h"
25#include "nvim/eval/userfunc.h"
26#include "nvim/eval/vars.h"
27#include "nvim/eval/window.h"
28#include "nvim/eval_defs.h"
29#include "nvim/ex_cmds.h"
30#include "nvim/ex_cmds_defs.h"
31#include "nvim/ex_docmd.h"
32#include "nvim/ex_eval.h"
33#include "nvim/garray.h"
34#include "nvim/gettext_defs.h"
35#include "nvim/globals.h"
36#include "nvim/hashtab.h"
37#include "nvim/lua/executor.h"
38#include "nvim/macros_defs.h"
39#include "nvim/mbyte.h"
40#include "nvim/memory.h"
41#include "nvim/message.h"
42#include "nvim/option.h"
43#include "nvim/option_defs.h"
44#include "nvim/optionstr.h"
45#include "nvim/os/os.h"
46#include "nvim/register.h"
47#include "nvim/runtime.h"
48#include "nvim/search.h"
49#include "nvim/strings.h"
50#include "nvim/types_defs.h"
51#include "nvim/version.h"
52#include "nvim/vim_defs.h"
53#include "nvim/window.h"
54
55typedef int (*ex_unletlock_callback)(lval_T *, char *, exarg_T *, int);
56
57#include "eval/vars.c.generated.h"
58
59// TODO(ZyX-I): Remove DICT_MAXNEST, make users be non-recursive instead
60
61#define DICT_MAXNEST 100        // maximum nesting of lists and dicts
62
63static const char *e_letunexp = N_("E18: Unexpected characters in :let");
64static const char e_double_semicolon_in_list_of_variables[]
65  = N_("E452: Double ; in list of variables");
66static const char *e_lock_unlock = N_("E940: Cannot lock or unlock variable %s");
67static const char e_setting_v_str_to_value_with_wrong_type[]
68  = N_("E963: Setting v:%s to value with wrong type");
69static const char e_missing_end_marker_str[] = N_("E990: Missing end marker '%s'");
70static const char e_cannot_use_heredoc_here[] = N_("E991: Cannot use =<< here");
71
72/// Variable used for g:
73static ScopeDictDictItem globvars_var;
74static dict_T globvardict;                  // Dict with g: variables
75/// g: value
76#define globvarht globvardict.dv_hashtab
77
78/// Old Vim variables such as "v:version" are also available without the "v:".
79/// Also in functions.  We need a special hashtable for them.
80static hashtab_T compat_hashtab;
81
82// values for vv_flags:
83#define VV_COMPAT       1       // compatible, also used without "v:"
84#define VV_RO           2       // read-only
85#define VV_RO_SBX       4       // read-only in the sandbox
86
87#define VV(idx, name, type, flags) \
88  [idx] = { \
89    .vv_name = (name), \
90    .vv_di = { \
91      .di_tv = { .v_type = (type) }, \
92      .di_flags = 0, \
93      .di_key = name, \
94    }, \
95    .vv_flags = (flags), \
96  }
97
98#define VIMVAR_KEY_LEN 16  // Maximum length of the key of v:variables
99
100// Array to hold the value of v: variables.
101// The value is in a dictitem, so that it can also be used in the v: scope.
102// The reason to use this table anyway is for very quick access to the
103// variables with the VV_ defines.
104static struct vimvar {
105  char *vv_name;  ///< Name of the variable, without v:.
106  TV_DICTITEM_STRUCT(VIMVAR_KEY_LEN + 1) vv_di;  ///< Value and name for key (max 16 chars).
107  char vv_flags;  ///< Flags: #VV_COMPAT, #VV_RO, #VV_RO_SBX.
108} vimvars[] = {
109  // VV_ tails differing from upcased string literals:
110  // VV_CC_FROM "charconvert_from"
111  // VV_CC_TO "charconvert_to"
112  // VV_SEND_SERVER "servername"
113  // VV_REG "register"
114  // VV_OP "operator"
115  VV(VV_COUNT,            "count",            VAR_NUMBER, VV_RO),
116  VV(VV_COUNT1,           "count1",           VAR_NUMBER, VV_RO),
117  VV(VV_PREVCOUNT,        "prevcount",        VAR_NUMBER, VV_RO),
118  VV(VV_ERRMSG,           "errmsg",           VAR_STRING, 0),
119  VV(VV_WARNINGMSG,       "warningmsg",       VAR_STRING, 0),
120  VV(VV_STATUSMSG,        "statusmsg",        VAR_STRING, 0),
121  VV(VV_SHELL_ERROR,      "shell_error",      VAR_NUMBER, VV_RO),
122  VV(VV_THIS_SESSION,     "this_session",     VAR_STRING, 0),
123  VV(VV_VERSION,          "version",          VAR_NUMBER, VV_COMPAT + VV_RO),
124  VV(VV_LNUM,             "lnum",             VAR_NUMBER, VV_RO_SBX),
125  VV(VV_TERMRESPONSE,     "termresponse",     VAR_STRING, VV_RO),
126  VV(VV_TERMREQUEST,      "termrequest",      VAR_STRING, VV_RO),
127  VV(VV_FNAME,            "fname",            VAR_STRING, VV_RO),
128  VV(VV_LANG,             "lang",             VAR_STRING, VV_RO),
129  VV(VV_LC_TIME,          "lc_time",          VAR_STRING, VV_RO),
130  VV(VV_CTYPE,            "ctype",            VAR_STRING, VV_RO),
131  VV(VV_CC_FROM,          "charconvert_from", VAR_STRING, VV_RO),
132  VV(VV_CC_TO,            "charconvert_to",   VAR_STRING, VV_RO),
133  VV(VV_FNAME_IN,         "fname_in",         VAR_STRING, VV_RO),
134  VV(VV_FNAME_OUT,        "fname_out",        VAR_STRING, VV_RO),
135  VV(VV_FNAME_NEW,        "fname_new",        VAR_STRING, VV_RO),
136  VV(VV_FNAME_DIFF,       "fname_diff",       VAR_STRING, VV_RO),
137  VV(VV_CMDARG,           "cmdarg",           VAR_STRING, VV_RO),
138  VV(VV_FOLDSTART,        "foldstart",        VAR_NUMBER, VV_RO_SBX),
139  VV(VV_FOLDEND,          "foldend",          VAR_NUMBER, VV_RO_SBX),
140  VV(VV_FOLDDASHES,       "folddashes",       VAR_STRING, VV_RO_SBX),
141  VV(VV_FOLDLEVEL,        "foldlevel",        VAR_NUMBER, VV_RO_SBX),
142  VV(VV_PROGNAME,         "progname",         VAR_STRING, VV_RO),
143  VV(VV_SEND_SERVER,      "servername",       VAR_STRING, VV_RO),
144  VV(VV_DYING,            "dying",            VAR_NUMBER, VV_RO),
145  VV(VV_EXCEPTION,        "exception",        VAR_STRING, VV_RO),
146  VV(VV_THROWPOINT,       "throwpoint",       VAR_STRING, VV_RO),
147  VV(VV_REG,              "register",         VAR_STRING, VV_RO),
148  VV(VV_CMDBANG,          "cmdbang",          VAR_NUMBER, VV_RO),
149  VV(VV_INSERTMODE,       "insertmode",       VAR_STRING, VV_RO),
150  VV(VV_VAL,              "val",              VAR_UNKNOWN, VV_RO),
151  VV(VV_KEY,              "key",              VAR_UNKNOWN, VV_RO),
152  VV(VV_PROFILING,        "profiling",        VAR_NUMBER, VV_RO),
153  VV(VV_FCS_REASON,       "fcs_reason",       VAR_STRING, VV_RO),
154  VV(VV_FCS_CHOICE,       "fcs_choice",       VAR_STRING, 0),
155  VV(VV_BEVAL_BUFNR,      "beval_bufnr",      VAR_NUMBER, VV_RO),
156  VV(VV_BEVAL_WINNR,      "beval_winnr",      VAR_NUMBER, VV_RO),
157  VV(VV_BEVAL_WINID,      "beval_winid",      VAR_NUMBER, VV_RO),
158  VV(VV_BEVAL_LNUM,       "beval_lnum",       VAR_NUMBER, VV_RO),
159  VV(VV_BEVAL_COL,        "beval_col",        VAR_NUMBER, VV_RO),
160  VV(VV_BEVAL_TEXT,       "beval_text",       VAR_STRING, VV_RO),
161  VV(VV_SCROLLSTART,      "scrollstart",      VAR_STRING, 0),
162  VV(VV_SWAPNAME,         "swapname",         VAR_STRING, VV_RO),
163  VV(VV_SWAPCHOICE,       "swapchoice",       VAR_STRING, 0),
164  VV(VV_SWAPCOMMAND,      "swapcommand",      VAR_STRING, VV_RO),
165  VV(VV_CHAR,             "char",             VAR_STRING, 0),
166  VV(VV_MOUSE_WIN,        "mouse_win",        VAR_NUMBER, 0),
167  VV(VV_MOUSE_WINID,      "mouse_winid",      VAR_NUMBER, 0),
168  VV(VV_MOUSE_LNUM,       "mouse_lnum",       VAR_NUMBER, 0),
169  VV(VV_MOUSE_COL,        "mouse_col",        VAR_NUMBER, 0),
170  VV(VV_OP,               "operator",         VAR_STRING, VV_RO),
171  VV(VV_SEARCHFORWARD,    "searchforward",    VAR_NUMBER, 0),
172  VV(VV_HLSEARCH,         "hlsearch",         VAR_NUMBER, 0),
173  VV(VV_OLDFILES,         "oldfiles",         VAR_LIST, 0),
174  VV(VV_WINDOWID,         "windowid",         VAR_NUMBER, VV_RO_SBX),
175  VV(VV_PROGPATH,         "progpath",         VAR_STRING, VV_RO),
176  VV(VV_COMPLETED_ITEM,   "completed_item",   VAR_DICT, 0),
177  VV(VV_OPTION_NEW,       "option_new",       VAR_STRING, VV_RO),
178  VV(VV_OPTION_OLD,       "option_old",       VAR_STRING, VV_RO),
179  VV(VV_OPTION_OLDLOCAL,  "option_oldlocal",  VAR_STRING, VV_RO),
180  VV(VV_OPTION_OLDGLOBAL, "option_oldglobal", VAR_STRING, VV_RO),
181  VV(VV_OPTION_COMMAND,   "option_command",   VAR_STRING, VV_RO),
182  VV(VV_OPTION_TYPE,      "option_type",      VAR_STRING, VV_RO),
183  VV(VV_ERRORS,           "errors",           VAR_LIST, 0),
184  VV(VV_FALSE,            "false",            VAR_BOOL, VV_RO),
185  VV(VV_TRUE,             "true",             VAR_BOOL, VV_RO),
186  VV(VV_NULL,             "null",             VAR_SPECIAL, VV_RO),
187  VV(VV_NUMBERMAX,        "numbermax",        VAR_NUMBER, VV_RO),
188  VV(VV_NUMBERMIN,        "numbermin",        VAR_NUMBER, VV_RO),
189  VV(VV_NUMBERSIZE,       "numbersize",       VAR_NUMBER, VV_RO),
190  VV(VV_VIM_DID_ENTER,    "vim_did_enter",    VAR_NUMBER, VV_RO),
191  VV(VV_TESTING,          "testing",          VAR_NUMBER, 0),
192  VV(VV_TYPE_NUMBER,      "t_number",         VAR_NUMBER, VV_RO),
193  VV(VV_TYPE_STRING,      "t_string",         VAR_NUMBER, VV_RO),
194  VV(VV_TYPE_FUNC,        "t_func",           VAR_NUMBER, VV_RO),
195  VV(VV_TYPE_LIST,        "t_list",           VAR_NUMBER, VV_RO),
196  VV(VV_TYPE_DICT,        "t_dict",           VAR_NUMBER, VV_RO),
197  VV(VV_TYPE_FLOAT,       "t_float",          VAR_NUMBER, VV_RO),
198  VV(VV_TYPE_BOOL,        "t_bool",           VAR_NUMBER, VV_RO),
199  VV(VV_TYPE_BLOB,        "t_blob",           VAR_NUMBER, VV_RO),
200  VV(VV_EVENT,            "event",            VAR_DICT, VV_RO),
201  VV(VV_VERSIONLONG,      "versionlong",      VAR_NUMBER, VV_RO),
202  VV(VV_ECHOSPACE,        "echospace",        VAR_NUMBER, VV_RO),
203  VV(VV_ARGF,             "argf",             VAR_LIST, VV_RO),
204  VV(VV_ARGV,             "argv",             VAR_LIST, VV_RO),
205  VV(VV_COLLATE,          "collate",          VAR_STRING, VV_RO),
206  VV(VV_EXITING,          "exiting",          VAR_NUMBER, VV_RO),
207  VV(VV_MAXCOL,           "maxcol",           VAR_NUMBER, VV_RO),
208  VV(VV_STACKTRACE,       "stacktrace",       VAR_LIST, VV_RO),
209  VV(VV_VIM_DID_INIT,     "vim_did_init",     VAR_NUMBER, VV_RO),
210  // Neovim
211  VV(VV_STDERR,           "stderr",           VAR_NUMBER, VV_RO),
212  VV(VV_MSGPACK_TYPES,    "msgpack_types",    VAR_DICT, VV_RO),
213  VV(VV__NULL_STRING,     "_null_string",     VAR_STRING, VV_RO),
214  VV(VV__NULL_LIST,       "_null_list",       VAR_LIST, VV_RO),
215  VV(VV__NULL_DICT,       "_null_dict",       VAR_DICT, VV_RO),
216  VV(VV__NULL_BLOB,       "_null_blob",       VAR_BLOB, VV_RO),
217  VV(VV_LUA,              "lua",              VAR_PARTIAL, VV_RO),
218  VV(VV_RELNUM,           "relnum",           VAR_NUMBER, VV_RO),
219  VV(VV_VIRTNUM,          "virtnum",          VAR_NUMBER, VV_RO),
220  VV(VV_STARTTIME,        "starttime",        VAR_NUMBER, VV_RO),
221  VV(VV_EXITREASON,       "exitreason",       VAR_STRING, VV_RO),
222  VV(VV_USERACTIVE,       "useractive",       VAR_NUMBER, VV_RO),
223  VV(VV_STARTREASON,      "startreason",      VAR_STRING, VV_RO),
224};
225#undef VV
226
227// shorthand
228#define vv_type         vv_di.di_tv.v_type
229#define vv_str          vv_di.di_tv.vval.v_string
230#define vv_list         vv_di.di_tv.vval.v_list
231#define vv_tv           vv_di.di_tv
232
233/// Variable used for v:
234static ScopeDictDictItem vimvars_var;
235static dict_T vimvardict;                   // Dict with v: variables
236/// v: hashtab
237#define vimvarht  vimvardict.dv_hashtab
238
239static const char *const msgpack_type_names[] = {
240  [kMPNil] = "nil",
241  [kMPBoolean] = "boolean",
242  [kMPInteger] = "integer",
243  [kMPFloat] = "float",
244  [kMPString] = "string",
245  [kMPArray] = "array",
246  [kMPMap] = "map",
247  [kMPExt] = "ext",
248};
249const list_T *eval_msgpack_type_lists[] = {
250  [kMPNil] = NULL,
251  [kMPBoolean] = NULL,
252  [kMPInteger] = NULL,
253  [kMPFloat] = NULL,
254  [kMPString] = NULL,
255  [kMPArray] = NULL,
256  [kMPMap] = NULL,
257  [kMPExt] = NULL,
258};
259
260#define SCRIPT_SV(id) (SCRIPT_ITEM(id)->sn_vars)
261#define SCRIPT_VARS(id) (SCRIPT_SV(id)->sv_dict.dv_hashtab)
262
263void evalvars_init(void)
264{
265  init_var_dict(get_globvar_dict(), &globvars_var, VAR_DEF_SCOPE);
266  init_var_dict(&vimvardict, &vimvars_var, VAR_SCOPE);
267  vimvardict.dv_lock = VAR_FIXED;
268  hash_init(&compat_hashtab);
269
270  for (size_t i = 0; i < ARRAY_SIZE(vimvars); i++) {
271    struct vimvar *p = &vimvars[i];
272    if (p->vv_flags & VV_RO) {
273      p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
274    } else if (p->vv_flags & VV_RO_SBX) {
275      p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
276    } else {
277      p->vv_di.di_flags = DI_FLAGS_FIX;
278    }
279
280    // add to v: scope dict, unless the value is not always available
281    if (p->vv_type != VAR_UNKNOWN) {
282      hash_add(&vimvarht, p->vv_di.di_key);
283    }
284    if (p->vv_flags & VV_COMPAT) {
285      // add to compat scope dict
286      hash_add(&compat_hashtab, p->vv_di.di_key);
287    }
288  }
289  const int vim_version = min_vim_version();
290  set_vim_var_nr(VV_VERSION, vim_version);
291  set_vim_var_nr(VV_VERSIONLONG, vim_version * 10000 + highest_patch());
292
293  dict_T *const msgpack_types_dict = tv_dict_alloc();
294  for (size_t i = 0; i < ARRAY_SIZE(msgpack_type_names); i++) {
295    list_T *const type_list = tv_list_alloc(0);
296    tv_list_set_lock(type_list, VAR_FIXED);
297    tv_list_ref(type_list);
298    dictitem_T *const di = tv_dict_item_alloc(msgpack_type_names[i]);
299    di->di_flags |= DI_FLAGS_RO|DI_FLAGS_FIX;
300    di->di_tv = (typval_T) {
301      .v_type = VAR_LIST,
302      .vval = { .v_list = type_list, },
303    };
304    eval_msgpack_type_lists[i] = type_list;
305    if (tv_dict_add(msgpack_types_dict, di) == FAIL) {
306      // There must not be duplicate items in this dictionary by definition.
307      abort();
308    }
309  }
310  msgpack_types_dict->dv_lock = VAR_FIXED;
311
312  set_vim_var_dict(VV_MSGPACK_TYPES, msgpack_types_dict);
313  set_vim_var_dict(VV_COMPLETED_ITEM, tv_dict_alloc_lock(VAR_FIXED));
314
315  set_vim_var_dict(VV_EVENT, tv_dict_alloc_lock(VAR_FIXED));
316  set_vim_var_list(VV_ERRORS, tv_list_alloc(kListLenUnknown));
317  set_vim_var_nr(VV_STDERR,   CHAN_STDERR);
318  set_vim_var_nr(VV_SEARCHFORWARD, 1);
319  set_vim_var_nr(VV_HLSEARCH, 1);
320  set_vim_var_nr(VV_COUNT1, 1);
321  set_vim_var_string(VV_STARTREASON, S_LEN("normal"));
322  set_vim_var_special(VV_EXITING, kSpecialVarNull);
323
324  set_vim_var_nr(VV_TYPE_NUMBER, VAR_TYPE_NUMBER);
325  set_vim_var_nr(VV_TYPE_STRING, VAR_TYPE_STRING);
326  set_vim_var_nr(VV_TYPE_FUNC,   VAR_TYPE_FUNC);
327  set_vim_var_nr(VV_TYPE_LIST,   VAR_TYPE_LIST);
328  set_vim_var_nr(VV_TYPE_DICT,   VAR_TYPE_DICT);
329  set_vim_var_nr(VV_TYPE_FLOAT,  VAR_TYPE_FLOAT);
330  set_vim_var_nr(VV_TYPE_BOOL,   VAR_TYPE_BOOL);
331  set_vim_var_nr(VV_TYPE_BLOB,   VAR_TYPE_BLOB);
332
333  set_vim_var_bool(VV_FALSE, kBoolVarFalse);
334  set_vim_var_bool(VV_TRUE, kBoolVarTrue);
335  set_vim_var_special(VV_NULL, kSpecialVarNull);
336  set_vim_var_nr(VV_NUMBERMAX, VARNUMBER_MAX);
337  set_vim_var_nr(VV_NUMBERMIN, VARNUMBER_MIN);
338  set_vim_var_nr(VV_NUMBERSIZE, sizeof(varnumber_T) * 8);
339  set_vim_var_nr(VV_MAXCOL, MAXCOL);
340
341  set_vim_var_nr(VV_ECHOSPACE,    sc_col - 1);
342
343  // vimvars[VV_LUA].vv_type = VAR_PARTIAL;
344  partial_T *vvlua_partial = xcalloc(1, sizeof(partial_T));
345  // this value shouldn't be printed, but if it is, do not crash
346  vvlua_partial->pt_name = xmallocz(0);
347  vvlua_partial->pt_refcount++;
348  set_vim_var_partial(VV_LUA, vvlua_partial);
349
350  set_reg_var(0);  // default for v:register is not 0 but '"'
351
352  // Set v:startreason via environment variable
353  const char *startreason = os_getenv_noalloc(ENV_STARTREASON);
354  if (strequal(startreason, "restart!") || strequal(startreason, "restart")) {
355    set_vim_var_string(VV_STARTREASON, startreason, -1);
356  }
357  if (os_env_exists(ENV_STARTREASON, false)) {
358    os_unsetenv(ENV_STARTREASON);
359  }
360}
361
362#ifdef EXITFREE
363void evalvars_clear(void)
364{
365  for (size_t i = 0; i < ARRAY_SIZE(vimvars); i++) {
366    struct vimvar *p = &vimvars[i];
367    if (p->vv_di.di_tv.v_type == VAR_STRING) {
368      XFREE_CLEAR(p->vv_str);
369    } else if (p->vv_di.di_tv.v_type == VAR_LIST) {
370      tv_list_unref(p->vv_list);
371      p->vv_list = NULL;
372    }
373  }
374
375  partial_unref(get_vim_var_partial(VV_LUA));
376  set_vim_var_partial(VV_LUA, NULL);
377  hash_clear(&vimvarht);
378  hash_init(&vimvarht);    // garbage_collect() will access it
379  hash_clear(&compat_hashtab);
380
381  // global variables
382  vars_clear(get_globvar_ht());
383
384  // Script-local variables. Clear all the variables here.
385  // The scriptvar_T is cleared later in free_scriptnames(), because a
386  // variable in one script might hold a reference to the whole scope of
387  // another script.
388  for (int i = 1; i <= script_items.ga_len; i++) {
389    vars_clear(&SCRIPT_VARS(i));
390  }
391}
392#endif
393
394int garbage_collect_globvars(int copyID)
395{
396  return set_ref_in_ht(&globvarht, copyID, NULL);
397}
398
399bool garbage_collect_vimvars(int copyID)
400{
401  return set_ref_in_ht(&vimvarht, copyID, NULL);
402}
403
404bool garbage_collect_scriptvars(int copyID)
405{
406  bool abort = false;
407
408  for (int i = 1; i <= script_items.ga_len; i++) {
409    abort = abort || set_ref_in_ht(&SCRIPT_VARS(i), copyID, NULL);
410  }
411
412  return abort;
413}
414
415/// Set an internal variable to a string value. Creates the variable if it does
416/// not already exist.
417void set_internal_string_var(const char *name, char *value)  // NOLINT(readability-non-const-parameter)
418  FUNC_ATTR_NONNULL_ARG(1)
419{
420  typval_T tv = {
421    .v_type = VAR_STRING,
422    .vval.v_string = value,
423  };
424
425  set_var(name, strlen(name), &tv, true);
426}
427
428int eval_charconvert(const char *const enc_from, const char *const enc_to,
429                     const char *const fname_from, const char *const fname_to)
430{
431  const sctx_T saved_sctx = current_sctx;
432
433  set_vim_var_string(VV_CC_FROM, enc_from, -1);
434  set_vim_var_string(VV_CC_TO, enc_to, -1);
435  set_vim_var_string(VV_FNAME_IN, fname_from, -1);
436  set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
437  sctx_T *ctx = get_option_sctx(kOptCharconvert);
438  if (ctx != NULL) {
439    current_sctx = *ctx;
440  }
441
442  bool err = false;
443  typval_T tv;
444  typval_T argv[1];
445  if (!callback_call(&p_ccv, 0, argv, &tv)) {
446    err = true;
447  } else {
448    if (tv_get_number_chk(&tv, NULL) != 0) {
449      err = true;
450    }
451    tv_clear(&tv);
452  }
453
454  set_vim_var_string(VV_CC_FROM, NULL, -1);
455  set_vim_var_string(VV_CC_TO, NULL, -1);
456  set_vim_var_string(VV_FNAME_IN, NULL, -1);
457  set_vim_var_string(VV_FNAME_OUT, NULL, -1);
458  current_sctx = saved_sctx;
459
460  if (err) {
461    return FAIL;
462  }
463  return OK;
464}
465
466void eval_diff(const char *const origfile, const char *const newfile, const char *const outfile)
467{
468  const sctx_T saved_sctx = current_sctx;
469  set_vim_var_string(VV_FNAME_IN, origfile, -1);
470  set_vim_var_string(VV_FNAME_NEW, newfile, -1);
471  set_vim_var_string(VV_FNAME_OUT, outfile, -1);
472
473  sctx_T *ctx = get_option_sctx(kOptDiffexpr);
474  if (ctx != NULL) {
475    current_sctx = *ctx;
476  }
477
478  // errors are ignored
479  typval_T tv;
480  typval_T argv[1];
481  if (callback_call(&p_dex, 0, argv, &tv)) {
482    tv_clear(&tv);
483  }
484
485  set_vim_var_string(VV_FNAME_IN, NULL, -1);
486  set_vim_var_string(VV_FNAME_NEW, NULL, -1);
487  set_vim_var_string(VV_FNAME_OUT, NULL, -1);
488  current_sctx = saved_sctx;
489}
490
491void eval_patch(const char *const origfile, const char *const difffile, const char *const outfile)
492{
493  const sctx_T saved_sctx = current_sctx;
494  set_vim_var_string(VV_FNAME_IN, origfile, -1);
495  set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
496  set_vim_var_string(VV_FNAME_OUT, outfile, -1);
497
498  sctx_T *ctx = get_option_sctx(kOptPatchexpr);
499  if (ctx != NULL) {
500    current_sctx = *ctx;
501  }
502
503  // errors are ignored
504  typval_T tv;
505  typval_T argv[1];
506  if (callback_call(&p_pex, 0, argv, &tv)) {
507    tv_clear(&tv);
508  }
509
510  set_vim_var_string(VV_FNAME_IN, NULL, -1);
511  set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
512  set_vim_var_string(VV_FNAME_OUT, NULL, -1);
513  current_sctx = saved_sctx;
514}
515
516/// Evaluate an expression to a list with suggestions.
517/// For the "expr:" part of 'spellsuggest'.
518///
519/// @return  NULL when there is an error.
520list_T *eval_spell_expr(char *badword, char *expr)
521{
522  typval_T save_val;
523  typval_T rettv;
524  list_T *list = NULL;
525  char *p = skipwhite(expr);
526  const sctx_T saved_sctx = current_sctx;
527
528  // Set "v:val" to the bad word.
529  prepare_vimvar(VV_VAL, &save_val);
530  set_vim_var_string(VV_VAL, badword, -1);
531  if (p_verbose == 0) {
532    emsg_off++;
533  }
534  sctx_T *ctx = get_option_sctx(kOptSpellsuggest);
535  if (ctx != NULL) {
536    current_sctx = *ctx;
537  }
538
539  int r = may_call_simple_func(p, &rettv);
540  if (r == NOTDONE) {
541    r = eval1(&p, &rettv, &EVALARG_EVALUATE);
542  }
543  if (r == OK) {
544    if (rettv.v_type != VAR_LIST) {
545      tv_clear(&rettv);
546    } else {
547      list = rettv.vval.v_list;
548    }
549  }
550
551  if (p_verbose == 0) {
552    emsg_off--;
553  }
554  tv_clear(get_vim_var_tv(VV_VAL));
555  restore_vimvar(VV_VAL, &save_val);
556  current_sctx = saved_sctx;
557
558  return list;
559}
560
561/// Get spell word from an entry from spellsuggest=expr:
562///
563/// Entry in question is supposed to be a list (to be checked by the caller)
564/// with two items: a word and a score represented as an unsigned number
565/// (whether it actually is unsigned is not checked).
566///
567/// Used to get the good word and score from the eval_spell_expr() result.
568///
569/// @param[in]  list  List to get values from.
570/// @param[out]  ret_word  Suggested word. Not initialized if return value is
571///                        -1.
572///
573/// @return -1 in case of error, score otherwise.
574int get_spellword(list_T *const list, const char **ret_word)
575{
576  if (tv_list_len(list) != 2) {
577    emsg(_("E5700: Expression from 'spellsuggest' must yield lists with "
578           "exactly two values"));
579    return -1;
580  }
581  *ret_word = tv_list_find_str(list, 0);
582  if (*ret_word == NULL) {
583    return -1;
584  }
585  return (int)tv_list_find_nr(list, -1, NULL);
586}
587
588/// Prepare v: variable "idx" to be used.
589/// Save the current typeval in "save_tv" and clear it.
590/// When not used yet add the variable to the v: hashtable.
591void prepare_vimvar(int idx, typval_T *save_tv)
592{
593  *save_tv = vimvars[idx].vv_tv;
594  vimvars[idx].vv_str = NULL;  // don't free it now
595  if (vimvars[idx].vv_type == VAR_UNKNOWN) {
596    hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
597  }
598}
599
600/// Restore v: variable "idx" to typeval "save_tv".
601/// Note that the v: variable must have been cleared already.
602/// When no longer defined, remove the variable from the v: hashtable.
603void restore_vimvar(int idx, typval_T *save_tv)
604{
605  vimvars[idx].vv_tv = *save_tv;
606  if (vimvars[idx].vv_type != VAR_UNKNOWN) {
607    return;
608  }
609
610  hashitem_T *hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
611  if (HASHITEM_EMPTY(hi)) {
612    internal_error("restore_vimvar()");
613  } else {
614    hash_remove(&vimvarht, hi);
615  }
616}
617
618/// List Vim variables.
619static void list_vim_vars(int *first)
620{
621  list_hashtable_vars(&vimvarht, "v:", false, first);
622}
623
624/// List script-local variables, if there is a script.
625static void list_script_vars(int *first)
626{
627  if (current_sctx.sc_sid > 0 && current_sctx.sc_sid <= script_items.ga_len) {
628    list_hashtable_vars(&SCRIPT_VARS(current_sctx.sc_sid), "s:", false, first);
629  }
630}
631
632/// Evaluate one Vim expression {expr} in string "p" and append the
633/// resulting string to "gap".  "p" points to the opening "{".
634/// When "evaluate" is false only skip over the expression.
635/// Return a pointer to the character after "}", NULL for an error.
636char *eval_one_expr_in_str(char *p, garray_T *gap, bool evaluate)
637{
638  char *block_start = skipwhite(p + 1);  // skip the opening {
639  char *block_end = block_start;
640
641  if (*block_start == NUL) {
642    semsg(_(e_missing_close_curly_str), p);
643    return NULL;
644  }
645  if (skip_expr(&block_end, NULL) == FAIL) {
646    return NULL;
647  }
648  block_end = skipwhite(block_end);
649  if (*block_end != '}') {
650    semsg(_(e_missing_close_curly_str), p);
651    return NULL;
652  }
653  if (evaluate) {
654    *block_end = NUL;
655    char *expr_val = eval_to_string(block_start, false, false);
656    *block_end = '}';
657    if (expr_val == NULL) {
658      return NULL;
659    }
660    ga_concat(gap, expr_val);
661    xfree(expr_val);
662  }
663
664  return block_end + 1;
665}
666
667/// Evaluate all the Vim expressions {expr} in "str" and return the resulting
668/// string in allocated memory.  "{{" is reduced to "{" and "}}" to "}".
669/// Used for a heredoc assignment.
670/// Returns NULL for an error.
671static char *eval_all_expr_in_str(char *str)
672{
673  garray_T ga;
674  ga_init(&ga, 1, 80);
675  char *p = str;
676
677  while (*p != NUL) {
678    bool escaped_brace = false;
679
680    // Look for a block start.
681    char *lit_start = p;
682    while (*p != '{' && *p != '}' && *p != NUL) {
683      p++;
684    }
685
686    if (*p != NUL && *p == p[1]) {
687      // Escaped brace, unescape and continue.
688      // Include the brace in the literal string.
689      p++;
690      escaped_brace = true;
691    } else if (*p == '}') {
692      semsg(_(e_stray_closing_curly_str), str);
693      ga_clear(&ga);
694      return NULL;
695    }
696
697    // Append the literal part.
698    ga_concat_len(&ga, lit_start, (size_t)(p - lit_start));
699
700    if (*p == NUL) {
701      break;
702    }
703
704    if (escaped_brace) {
705      // Skip the second brace.
706      p++;
707      continue;
708    }
709
710    // Evaluate the expression and append the result.
711    p = eval_one_expr_in_str(p, &ga, true);
712    if (p == NULL) {
713      ga_clear(&ga);
714      return NULL;
715    }
716  }
717  ga_append(&ga, NUL);
718
719  return ga.ga_data;
720}
721
722/// Get a list of lines from a HERE document. The here document is a list of
723/// lines surrounded by a marker.
724///     cmd << {marker}
725///       {line1}
726///       {line2}
727///       ....
728///     {marker}
729///
730/// The {marker} is a string. If the optional 'trim' word is supplied before the
731/// marker, then the leading indentation before the lines (matching the
732/// indentation in the 'cmd' line) is stripped.
733///
734/// When getting lines for an embedded script (e.g. python, lua, perl, ruby,
735/// tcl, mzscheme), "script_get" is set to true. In this case, if the marker is
736/// missing, then '.' is accepted as a marker.
737///
738/// @return  a List with {lines} or NULL on failure.
739list_T *heredoc_get(exarg_T *eap, char *cmd, bool script_get)
740{
741  char *marker;
742  int marker_indent_len = 0;
743  int text_indent_len = 0;
744  char *text_indent = NULL;
745  char dot[] = ".";
746  bool heredoc_in_string = false;
747  char *line_arg = NULL;
748  char *nl_ptr = vim_strchr(cmd, '\n');
749
750  if (nl_ptr != NULL) {
751    heredoc_in_string = true;
752    line_arg = nl_ptr + 1;
753    *nl_ptr = NUL;
754  } else if (eap->ea_getline == NULL) {
755    emsg(_(e_cannot_use_heredoc_here));
756    return NULL;
757  }
758
759  // Check for the optional 'trim' word before the marker
760  cmd = skipwhite(cmd);
761  bool evalstr = false;
762  bool eval_failed = false;
763  while (true) {
764    if (strncmp(cmd, "trim", 4) == 0
765        && (cmd[4] == NUL || ascii_iswhite(cmd[4]))) {
766      cmd = skipwhite(cmd + 4);
767
768      // Trim the indentation from all the lines in the here document.
769      // The amount of indentation trimmed is the same as the indentation
770      // of the first line after the :let command line.  To find the end
771      // marker the indent of the :let command line is trimmed.
772      char *p = *eap->cmdlinep;
773      while (ascii_iswhite(*p)) {
774        p++;
775        marker_indent_len++;
776      }
777      text_indent_len = -1;
778
779      continue;
780    }
781    if (strncmp(cmd, "eval", 4) == 0
782        && (cmd[4] == NUL || ascii_iswhite(cmd[4]))) {
783      cmd = skipwhite(cmd + 4);
784      evalstr = true;
785      continue;
786    }
787    break;
788  }
789
790  const char comment_char = '"';
791  // The marker is the next word.
792  if (*cmd != NUL && *cmd != comment_char) {
793    marker = skipwhite(cmd);
794    char *p = skiptowhite(marker);
795    if (*skipwhite(p) != NUL && *skipwhite(p) != comment_char) {
796      semsg(_(e_trailing_arg), p);
797      return NULL;
798    }
799    *p = NUL;
800    if (!script_get && islower((uint8_t)(*marker))) {
801      emsg(_("E221: Marker cannot start with lower case letter"));
802      return NULL;
803    }
804  } else {
805    // When getting lines for an embedded script, if the marker is missing,
806    // accept '.' as the marker.
807    if (script_get) {
808      marker = dot;
809    } else {
810      emsg(_("E172: Missing marker"));
811      return NULL;
812    }
813  }
814
815  char *theline = NULL;
816  list_T *l = tv_list_alloc(0);
817  while (true) {
818    int mi = 0;
819    int ti = 0;
820
821    if (heredoc_in_string) {
822      // heredoc in a string separated by newlines.  Get the next line
823      // from the string.
824
825      if (*line_arg == NUL) {
826        if (!script_get) {
827          semsg(_(e_missing_end_marker_str), marker);
828        }
829        break;
830      }
831
832      theline = line_arg;
833      char *next_line = vim_strchr(theline, '\n');
834      if (next_line == NULL) {
835        line_arg += strlen(line_arg);
836      } else {
837        *next_line = NUL;
838        line_arg = next_line + 1;
839      }
840    } else {
841      xfree(theline);
842      theline = eap->ea_getline(NUL, eap->cookie, 0, false);
843      if (theline == NULL) {
844        if (!script_get) {
845          semsg(_(e_missing_end_marker_str), marker);
846        }
847        break;
848      }
849    }
850
851    // with "trim": skip the indent matching the :let line to find the
852    // marker
853    if (marker_indent_len > 0
854        && strncmp(theline, *eap->cmdlinep, (size_t)marker_indent_len) == 0) {
855      mi = marker_indent_len;
856    }
857    if (strcmp(marker, theline + mi) == 0) {
858      break;
859    }
860
861    // If expression evaluation failed in the heredoc, then skip till the
862    // end marker.
863    if (eval_failed) {
864      continue;
865    }
866
867    if (text_indent_len == -1 && *theline != NUL) {
868      // set the text indent from the first line.
869      char *p = theline;
870      text_indent_len = 0;
871      while (ascii_iswhite(*p)) {
872        p++;
873        text_indent_len++;
874      }
875      text_indent = xmemdupz(theline, (size_t)text_indent_len);
876    }
877    // with "trim": skip the indent matching the first line
878    if (text_indent != NULL) {
879      for (ti = 0; ti < text_indent_len; ti++) {
880        if (theline[ti] != text_indent[ti]) {
881          break;
882        }
883      }
884    }
885
886    char *str = theline + ti;
887    if (evalstr && !eap->skip) {
888      str = eval_all_expr_in_str(str);
889      if (str == NULL) {
890        // expression evaluation failed
891        eval_failed = true;
892        continue;
893      }
894      tv_list_append_allocated_string(l, str);
895    } else {
896      tv_list_append_string(l, str, -1);
897    }
898  }
899  if (heredoc_in_string) {
900    // Next command follows the heredoc in the string.
901    eap->nextcmd = line_arg;
902  } else {
903    xfree(theline);
904  }
905  xfree(text_indent);
906
907  if (eval_failed) {
908    // expression evaluation in the heredoc failed
909    tv_list_free(l);
910    return NULL;
911  }
912  return l;
913}
914
915/// ":let" list all variable values
916/// ":let var1 var2" list variable values
917/// ":let var = expr" assignment command.
918/// ":let var += expr" assignment command.
919/// ":let var -= expr" assignment command.
920/// ":let var *= expr" assignment command.
921/// ":let var /= expr" assignment command.
922/// ":let var %= expr" assignment command.
923/// ":let var .= expr" assignment command.
924/// ":let var ..= expr" assignment command.
925/// ":let [var1, var2] = expr" unpack list.
926/// ":let [name, ..., ; lastname] = expr" unpack list.
927///
928/// ":cons[t] var = expr1" define constant
929/// ":cons[t] [name1, name2, ...] = expr1" define constants unpacking list
930/// ":cons[t] [name, ..., ; lastname] = expr" define constants unpacking list
931void ex_let(exarg_T *eap)
932{
933  const bool is_const = eap->cmdidx == CMD_const;
934  char *arg = eap->arg;
935  char *expr = NULL;
936  typval_T rettv;
937  int var_count = 0;
938  int semicolon = 0;
939  char op[2];
940  const char *argend;
941  int first = true;
942
943  argend = skip_var_list(arg, &var_count, &semicolon, false);
944  if (argend == NULL) {
945    return;
946  }
947  expr = skipwhite(argend);
948  bool concat = strncmp(expr, "..=", 3) == 0;
949  bool has_assign = *expr == '=' || (vim_strchr("+-*/%.", (uint8_t)(*expr)) != NULL
950                                     && expr[1] == '=');
951  if (!has_assign && !concat) {
952    // ":let" without "=": list variables
953    if (*arg == '[') {
954      emsg(_(e_invarg));
955    } else if (!ends_excmd(*arg)) {
956      // ":let var1 var2"
957      arg = (char *)list_arg_vars(eap, arg, &first);
958    } else if (!eap->skip) {
959      // ":let"
960      list_glob_vars(&first);
961      list_buf_vars(&first);
962      list_win_vars(&first);
963      list_tab_vars(&first);
964      list_script_vars(&first);
965      list_func_vars(&first);
966      list_vim_vars(&first);
967    }
968    eap->nextcmd = check_nextcmd(arg);
969    return;
970  }
971
972  if (expr[0] == '=' && expr[1] == '<' && expr[2] == '<') {
973    // HERE document
974    list_T *l = heredoc_get(eap, expr + 3, false);
975    if (l != NULL) {
976      tv_list_set_ret(&rettv, l);
977      if (!eap->skip) {
978        op[0] = '=';
979        op[1] = NUL;
980        ex_let_vars(eap->arg, &rettv, false, semicolon, var_count, is_const, op);
981      }
982      tv_clear(&rettv);
983    }
984    return;
985  }
986
987  rettv.v_type = VAR_UNKNOWN;
988
989  op[0] = '=';
990  op[1] = NUL;
991  if (*expr != '=') {
992    if (vim_strchr("+-*/%.", (uint8_t)(*expr)) != NULL) {
993      op[0] = *expr;  // +=, -=, *=, /=, %= or .=
994      if (expr[0] == '.' && expr[1] == '.') {  // ..=
995        expr++;
996      }
997    }
998    expr += 2;
999  } else {
1000    expr += 1;
1001  }
1002
1003  expr = skipwhite(expr);
1004
1005  if (eap->skip) {
1006    emsg_skip++;
1007  }
1008  evalarg_T evalarg;
1009  fill_evalarg_from_eap(&evalarg, eap, eap->skip);
1010  int eval_res = eval0(expr, &rettv, eap, &evalarg);
1011  if (eap->skip) {
1012    emsg_skip--;
1013  }
1014  clear_evalarg(&evalarg, eap);
1015
1016  if (!eap->skip && eval_res != FAIL) {
1017    ex_let_vars(eap->arg, &rettv, false, semicolon, var_count, is_const, op);
1018  }
1019  if (eval_res != FAIL) {
1020    tv_clear(&rettv);
1021  }
1022}
1023
1024/// Assign the typevalue "tv" to the variable or variables at "arg_start".
1025/// Handles both "var" with any type and "[var, var; var]" with a list type.
1026/// When "op" is not NULL it points to a string with characters that
1027/// must appear after the variable(s).  Use "+", "-" or "." for add, subtract
1028/// or concatenate.
1029///
1030/// @param copy  copy values from "tv", don't move
1031/// @param semicolon  from skip_var_list()
1032/// @param var_count  from skip_var_list()
1033/// @param is_const  lock variables for :const
1034///
1035/// @return  OK or FAIL;
1036int ex_let_vars(char *arg_start, typval_T *tv, int copy, int semicolon, int var_count, int is_const,
1037                char *op)
1038{
1039  char *arg = arg_start;
1040  typval_T ltv;
1041
1042  if (*arg != '[') {
1043    // ":let var = expr" or ":for var in list"
1044    if (ex_let_one(arg, tv, copy, is_const, op, op) == NULL) {
1045      return FAIL;
1046    }
1047    return OK;
1048  }
1049
1050  // ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1051  if (tv->v_type != VAR_LIST) {
1052    emsg(_(e_listreq));
1053    return FAIL;
1054  }
1055  list_T *const l = tv->vval.v_list;
1056
1057  const int len = tv_list_len(l);
1058  if (semicolon == 0 && var_count < len) {
1059    emsg(_("E687: Less targets than List items"));
1060    return FAIL;
1061  }
1062  if (var_count - semicolon > len) {
1063    emsg(_("E688: More targets than List items"));
1064    return FAIL;
1065  }
1066  // List l may actually be NULL, but it should fail with E688 or even earlier
1067  // if you try to do ":let [] = v:_null_list".
1068  assert(l != NULL);
1069
1070  listitem_T *item = tv_list_first(l);
1071  size_t rest_len = (size_t)tv_list_len(l);
1072  while (*arg != ']') {
1073    arg = skipwhite(arg + 1);
1074    arg = ex_let_one(arg, TV_LIST_ITEM_TV(item), true, is_const, ",;]", op);
1075    if (arg == NULL) {
1076      return FAIL;
1077    }
1078    rest_len--;
1079
1080    item = TV_LIST_ITEM_NEXT(l, item);
1081    arg = skipwhite(arg);
1082    if (*arg == ';') {
1083      // Put the rest of the list (may be empty) in the var after ';'.
1084      // Create a new list for this.
1085      list_T *const rest_list = tv_list_alloc((ptrdiff_t)rest_len);
1086      while (item != NULL) {
1087        tv_list_append_tv(rest_list, TV_LIST_ITEM_TV(item));
1088        item = TV_LIST_ITEM_NEXT(l, item);
1089      }
1090
1091      ltv.v_type = VAR_LIST;
1092      ltv.v_lock = VAR_UNLOCKED;
1093      ltv.vval.v_list = rest_list;
1094      tv_list_ref(rest_list);
1095
1096      arg = ex_let_one(skipwhite(arg + 1), &ltv, false, is_const, "]", op);
1097      tv_clear(&ltv);
1098      if (arg == NULL) {
1099        return FAIL;
1100      }
1101      break;
1102    } else if (*arg != ',' && *arg != ']') {
1103      internal_error("ex_let_vars()");
1104      return FAIL;
1105    }
1106  }
1107
1108  return OK;
1109}
1110
1111/// Skip over assignable variable "var" or list of variables "[var, var]".
1112/// Used for ":let varvar = expr" and ":for varvar in expr".
1113/// For "[var, var]" increment "*var_count" for each variable.
1114/// for "[var, var; var]" set "semicolon" to 1.
1115/// If "silent" is true do not give an "invalid argument" error message.
1116///
1117/// @return  NULL for an error.
1118const char *skip_var_list(const char *arg, int *var_count, int *semicolon, bool silent)
1119{
1120  if (*arg == '[') {
1121    const char *s;
1122    // "[var, var]": find the matching ']'.
1123    const char *p = arg;
1124    while (true) {
1125      p = skipwhite(p + 1);             // skip whites after '[', ';' or ','
1126      s = skip_var_one(p);
1127      if (s == p) {
1128        if (!silent) {
1129          semsg(_(e_invarg2), p);
1130        }
1131        return NULL;
1132      }
1133      (*var_count)++;
1134
1135      p = skipwhite(s);
1136      if (*p == ']') {
1137        break;
1138      } else if (*p == ';') {
1139        if (*semicolon == 1) {
1140          if (!silent) {
1141            emsg(_(e_double_semicolon_in_list_of_variables));
1142          }
1143          return NULL;
1144        }
1145        *semicolon = 1;
1146      } else if (*p != ',') {
1147        if (!silent) {
1148          semsg(_(e_invarg2), p);
1149        }
1150        return NULL;
1151      }
1152    }
1153    return p + 1;
1154  }
1155  return skip_var_one(arg);
1156}
1157
1158/// Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1159/// l[idx].
1160static const char *skip_var_one(const char *arg)
1161{
1162  if (*arg == '@' && arg[1] != NUL) {
1163    return arg + 2;
1164  }
1165  return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1166                       NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1167}
1168
1169/// List variables for hashtab "ht" with prefix "prefix".
1170///
1171/// @param empty  if true also list NULL strings as empty strings.
1172void list_hashtable_vars(hashtab_T *ht, const char *prefix, int empty, int *first)
1173{
1174  hashitem_T *hi;
1175  dictitem_T *di;
1176  int todo;
1177
1178  todo = (int)ht->ht_used;
1179  for (hi = ht->ht_array; todo > 0 && !got_int; hi++) {
1180    if (!HASHITEM_EMPTY(hi)) {
1181      todo--;
1182      di = TV_DICT_HI2DI(hi);
1183      char buf[IOSIZE];
1184
1185      // apply :filter /pat/ to variable name
1186      xstrlcpy(buf, prefix, IOSIZE);
1187      xstrlcat(buf, di->di_key, IOSIZE);
1188      if (message_filtered(buf)) {
1189        continue;
1190      }
1191
1192      if (empty || di->di_tv.v_type != VAR_STRING
1193          || di->di_tv.vval.v_string != NULL) {
1194        list_one_var(di, prefix, first);
1195      }
1196    }
1197  }
1198}
1199
1200/// List global variables.
1201static void list_glob_vars(int *first)
1202{
1203  list_hashtable_vars(&globvarht, "", true, first);
1204}
1205
1206/// List buffer variables.
1207static void list_buf_vars(int *first)
1208{
1209  list_hashtable_vars(&curbuf->b_vars->dv_hashtab, "b:", true, first);
1210}
1211
1212/// List window variables.
1213static void list_win_vars(int *first)
1214{
1215  list_hashtable_vars(&curwin->w_vars->dv_hashtab, "w:", true, first);
1216}
1217
1218/// List tab page variables.
1219static void list_tab_vars(int *first)
1220{
1221  list_hashtable_vars(&curtab->tp_vars->dv_hashtab, "t:", true, first);
1222}
1223
1224/// List variables in "arg".
1225static const char *list_arg_vars(exarg_T *eap, const char *arg, int *first)
1226{
1227  bool error = false;
1228  int len;
1229  const char *name;
1230  const char *name_start;
1231  typval_T tv;
1232
1233  while (!ends_excmd(*arg) && !got_int) {
1234    if (error || eap->skip) {
1235      arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1236      if (!ascii_iswhite(*arg) && !ends_excmd(*arg)) {
1237        emsg_severe = true;
1238        semsg(_(e_trailing_arg), arg);
1239        break;
1240      }
1241    } else {
1242      // get_name_len() takes care of expanding curly braces
1243      name_start = name = arg;
1244      char *tofree;
1245      len = get_name_len(&arg, &tofree, true, true);
1246      if (len <= 0) {
1247        // This is mainly to keep test 49 working: when expanding
1248        // curly braces fails overrule the exception error message.
1249        if (len < 0 && !aborting()) {
1250          emsg_severe = true;
1251          semsg(_(e_invarg2), arg);
1252          break;
1253        }
1254        error = true;
1255      } else {
1256        if (tofree != NULL) {
1257          name = tofree;
1258        }
1259        if (eval_variable(name, len, &tv, NULL, true, false) == FAIL) {
1260          error = true;
1261        } else {
1262          // handle d.key, l[idx], f(expr)
1263          const char *const arg_subsc = arg;
1264          if (handle_subscript(&arg, &tv, &EVALARG_EVALUATE, true) == FAIL) {
1265            error = true;
1266          } else {
1267            if (arg == arg_subsc && len == 2 && name[1] == ':') {
1268              switch (*name) {
1269              case 'g':
1270                list_glob_vars(first); break;
1271              case 'b':
1272                list_buf_vars(first); break;
1273              case 'w':
1274                list_win_vars(first); break;
1275              case 't':
1276                list_tab_vars(first); break;
1277              case 'v':
1278                list_vim_vars(first); break;
1279              case 's':
1280                list_script_vars(first); break;
1281              case 'l':
1282                list_func_vars(first); break;
1283              default:
1284                semsg(_("E738: Can't list variables for %s"), name);
1285              }
1286            } else {
1287              char *const s = encode_tv2echo(&tv, NULL);
1288              const char *const used_name = (arg == arg_subsc
1289                                             ? name
1290                                             : name_start);
1291              assert(used_name != NULL);
1292              const ptrdiff_t name_size = (used_name == tofree
1293                                           ? (ptrdiff_t)strlen(used_name)
1294                                           : (arg - used_name));
1295              list_one_var_a("", used_name, name_size,
1296                             tv.v_type, s == NULL ? "" : s, first);
1297              xfree(s);
1298            }
1299            tv_clear(&tv);
1300          }
1301        }
1302      }
1303
1304      xfree(tofree);
1305    }
1306
1307    arg = skipwhite(arg);
1308  }
1309
1310  return arg;
1311}
1312
1313/// Set an environment variable, part of ex_let_one().
1314static char *ex_let_env(char *arg, typval_T *const tv, const bool is_const,
1315                        const char *const endchars, const char *const op)
1316  FUNC_ATTR_NONNULL_ARG(1, 2) FUNC_ATTR_WARN_UNUSED_RESULT
1317{
1318  if (is_const) {
1319    emsg(_("E996: Cannot lock an environment variable"));
1320    return NULL;
1321  }
1322
1323  // Find the end of the name.
1324  char *arg_end = NULL;
1325  arg++;
1326  char *name = arg;
1327  int len = get_env_len((const char **)&arg);
1328  if (len == 0) {
1329    semsg(_(e_invarg2), name - 1);
1330  } else {
1331    if (op != NULL && vim_strchr("+-*/%", (uint8_t)(*op)) != NULL) {
1332      semsg(_(e_letwrong), op);
1333    } else if (endchars != NULL
1334               && vim_strchr(endchars, (uint8_t)(*skipwhite(arg))) == NULL) {
1335      emsg(_(e_letunexp));
1336    } else if (!check_secure()) {
1337      char *tofree = NULL;
1338      const char c1 = name[len];
1339      name[len] = NUL;
1340      const char *p = tv_get_string_chk(tv);
1341      if (p != NULL && op != NULL && *op == '.') {
1342        char *s = vim_getenv(name);
1343        if (s != NULL) {
1344          tofree = concat_str(s, p);
1345          p = tofree;
1346          xfree(s);
1347        }
1348      }
1349      if (p != NULL) {
1350        vim_setenv_ext(name, p);
1351        arg_end = arg;
1352      }
1353      name[len] = c1;
1354      xfree(tofree);
1355    }
1356  }
1357  return arg_end;
1358}
1359
1360/// Set an option, part of ex_let_one().
1361static char *ex_let_option(char *arg, typval_T *const tv, const bool is_const,
1362                           const char *const endchars, const char *const op)
1363  FUNC_ATTR_NONNULL_ARG(1, 2) FUNC_ATTR_WARN_UNUSED_RESULT
1364{
1365  if (is_const) {
1366    emsg(_("E996: Cannot lock an option"));
1367    return NULL;
1368  }
1369
1370  // Find the end of the name.
1371  char *arg_end = NULL;
1372  OptIndex opt_idx;
1373  int opt_flags;
1374
1375  char *const p = (char *)find_option_var_end((const char **)&arg, &opt_idx, &opt_flags);
1376
1377  if (p == NULL || (endchars != NULL && vim_strchr(endchars, (uint8_t)(*skipwhite(p))) == NULL)) {
1378    emsg(_(e_letunexp));
1379    return NULL;
1380  }
1381
1382  const char c1 = *p;
1383  *p = NUL;
1384
1385  bool is_tty_opt = is_tty_option(arg);
1386  bool hidden = is_option_hidden(opt_idx);
1387  Object curval = is_tty_opt ? get_tty_option(arg) : get_option_value(opt_idx, opt_flags);
1388  Object newval = NIL;
1389
1390  if (curval.type == kObjectTypeNil) {
1391    semsg(_(e_unknown_option2), arg);
1392    goto theend;
1393  }
1394  if (op != NULL && *op != '='
1395      && ((curval.type != kObjectTypeString && *op == '.')
1396          || (curval.type == kObjectTypeString && *op != '.'))) {
1397    semsg(_(e_letwrong), op);
1398    goto theend;
1399  }
1400
1401  bool error;
1402  newval = opt_from_tv(tv, opt_idx, arg, &error);
1403  if (error) {
1404    goto theend;
1405  }
1406
1407  // Global-local w/ unset local: assigning -1 unsets it again, so `curval` and `newval` may differ.
1408  // in type. Apply a compound operator only to concrete same-kind values.
1409  const bool is_num = (curval.type == kObjectTypeInteger || curval.type == kObjectTypeBoolean)
1410                      && (newval.type == kObjectTypeInteger || newval.type == kObjectTypeBoolean);
1411  const bool is_string = curval.type == kObjectTypeString && newval.type == kObjectTypeString;
1412
1413  if (op != NULL && *op != '=') {
1414    if (!hidden && is_num) {  // number or bool
1415      OptInt cur_n = curval.type == kObjectTypeInteger ? curval.data.integer : curval.data.boolean;
1416      OptInt new_n = newval.type == kObjectTypeInteger ? newval.data.integer : newval.data.boolean;
1417
1418      switch (*op) {
1419      case '+':
1420        new_n = cur_n + new_n; break;
1421      case '-':
1422        new_n = cur_n - new_n; break;
1423      case '*':
1424        new_n = cur_n * new_n; break;
1425      case '/':
1426        new_n = num_divide(cur_n, new_n); break;
1427      case '%':
1428        new_n = num_modulus(cur_n, new_n); break;
1429      }
1430
1431      if (curval.type == kObjectTypeInteger) {
1432        newval = INTEGER_OBJ(new_n);
1433      } else {
1434        newval = opt_from_tristate(TRISTATE_FROM_INT(new_n));
1435      }
1436    } else if (!hidden && is_string) {  // string
1437      const char *curval_data = curval.data.string.data;
1438      const char *newval_data = newval.data.string.data;
1439
1440      if (curval_data != NULL && newval_data != NULL) {
1441        Object newval_old = newval;
1442        newval = CSTR_AS_OBJ(concat_str(curval_data, newval_data));
1443        optval_free(newval_old);
1444      }
1445    }
1446  }
1447
1448  arg_end = p;
1449  // Ignore TTY assignments after validation for compatibility with old vimrcs.
1450  if (!is_tty_opt) {
1451    set_option_value_give_err(opt_idx, newval, opt_flags);
1452  }
1453
1454theend:
1455  *p = c1;
1456  optval_free(curval);
1457  optval_free(newval);
1458  return arg_end;
1459}
1460
1461/// Set a register, part of ex_let_one().
1462static char *ex_let_register(char *arg, typval_T *const tv, const bool is_const,
1463                             const char *const endchars, const char *const op)
1464  FUNC_ATTR_NONNULL_ARG(1, 2) FUNC_ATTR_WARN_UNUSED_RESULT
1465{
1466  if (is_const) {
1467    emsg(_("E996: Cannot lock a register"));
1468    return NULL;
1469  }
1470
1471  char *arg_end = NULL;
1472  arg++;
1473  if (op != NULL && vim_strchr("+-*/%", (uint8_t)(*op)) != NULL) {
1474    semsg(_(e_letwrong), op);
1475  } else if (endchars != NULL
1476             && vim_strchr(endchars, (uint8_t)(*skipwhite(arg + 1))) == NULL) {
1477    emsg(_(e_letunexp));
1478  } else {
1479    char *ptofree = NULL;
1480    const char *p = tv_get_string_chk(tv);
1481    if (p != NULL && op != NULL && *op == '.') {
1482      char *s = get_reg_contents(*arg == '@' ? '"' : *arg, kGRegExprSrc);
1483      if (s != NULL) {
1484        ptofree = concat_str(s, p);
1485        p = ptofree;
1486        xfree(s);
1487      }
1488    }
1489    if (p != NULL) {
1490      write_reg_contents(*arg == '@' ? '"' : *arg, p, (ssize_t)strlen(p), false);
1491      arg_end = arg + 1;
1492    }
1493    xfree(ptofree);
1494  }
1495  return arg_end;
1496}
1497
1498/// Set one item of `:let var = expr` or `:let [v1, v2] = list` to its value
1499///
1500/// @param[in]  arg  Start of the variable name.
1501/// @param[in]  tv  Value to assign to the variable.
1502/// @param[in]  copy  If true, copy value from `tv`.
1503/// @param[in]  endchars  Valid characters after variable name or NULL.
1504/// @param[in]  op  Operation performed: *op is `+`, `-`, `.` for `+=`, etc.
1505///                 NULL for `=`.
1506///
1507/// @return a pointer to the char just after the var name or NULL in case of
1508///         error.
1509static char *ex_let_one(char *arg, typval_T *const tv, const bool copy, const bool is_const,
1510                        const char *const endchars, const char *const op)
1511  FUNC_ATTR_NONNULL_ARG(1, 2) FUNC_ATTR_WARN_UNUSED_RESULT
1512{
1513  char *arg_end = NULL;
1514
1515  if (*arg == '$') {
1516    // ":let $VAR = expr": Set environment variable.
1517    return ex_let_env(arg, tv, is_const, endchars, op);
1518  } else if (*arg == '&') {
1519    // ":let &option = expr": Set option value.
1520    // ":let &l:option = expr": Set local option value.
1521    // ":let &g:option = expr": Set global option value.
1522    return ex_let_option(arg, tv, is_const, endchars, op);
1523  } else if (*arg == '@') {
1524    // ":let @r = expr": Set register contents.
1525    return ex_let_register(arg, tv, is_const, endchars, op);
1526  } else if (eval_isnamec1(*arg) || *arg == '{') {
1527    // ":let var = expr": Set internal variable.
1528    // ":let {expr} = expr": Idem, name made with curly braces
1529    lval_T lv;
1530    char *const p = get_lval(arg, tv, &lv, false, false, 0, FNE_CHECK_START);
1531    if (p != NULL && lv.ll_name != NULL) {
1532      if (endchars != NULL && vim_strchr(endchars, (uint8_t)(*skipwhite(p))) == NULL) {
1533        emsg(_(e_letunexp));
1534      } else {
1535        set_var_lval(&lv, p, tv, copy, is_const, op);
1536        arg_end = p;
1537      }
1538    }
1539    clear_lval(&lv);
1540  } else {
1541    semsg(_(e_invarg2), arg);
1542  }
1543
1544  return arg_end;
1545}
1546
1547/// ":unlet[!] var1 ... " command.
1548void ex_unlet(exarg_T *eap)
1549{
1550  ex_unletlock(eap, eap->arg, 0, eap->forceit ? GLV_QUIET : 0, do_unlet_var);
1551}
1552
1553/// ":lockvar" and ":unlockvar" commands
1554void ex_lockvar(exarg_T *eap)
1555{
1556  char *arg = eap->arg;
1557  int deep = 2;
1558
1559  if (eap->forceit) {
1560    deep = -1;
1561  } else if (ascii_isdigit(*arg)) {
1562    deep = getdigits_int(&arg, false, -1);
1563    arg = skipwhite(arg);
1564  }
1565
1566  ex_unletlock(eap, arg, deep, 0, do_lock_var);
1567}
1568
1569/// Common parsing logic for :unlet, :lockvar and :unlockvar.
1570///
1571/// Invokes `callback` afterwards if successful and `eap->skip == false`.
1572///
1573/// @param[in]  eap  Ex command arguments for the command.
1574/// @param[in]  argstart  Start of the string argument for the command.
1575/// @param[in]  deep  Levels to (un)lock for :(un)lockvar, -1 to (un)lock
1576///                   everything.
1577/// @param[in]  callback  Appropriate handler for the command.
1578static void ex_unletlock(exarg_T *eap, char *argstart, int deep, int glv_flags,
1579                         ex_unletlock_callback callback)
1580  FUNC_ATTR_NONNULL_ALL
1581{
1582  char *arg = argstart;
1583  char *name_end;
1584  bool error = false;
1585  lval_T lv;
1586
1587  do {
1588    if (*arg == '$') {
1589      lv.ll_name = arg;
1590      lv.ll_tv = NULL;
1591      arg++;
1592      if (get_env_len((const char **)&arg) == 0) {
1593        semsg(_(e_invarg2), arg - 1);
1594        return;
1595      }
1596      assert(*lv.ll_name == '$');  // suppress clang "Uninitialized argument value"
1597      if (!error && !eap->skip && callback(&lv, arg, eap, deep) == FAIL) {
1598        error = true;
1599      }
1600      name_end = arg;
1601    } else {
1602      // Parse the name and find the end.
1603      name_end = get_lval(arg, NULL, &lv, true, eap->skip || error,
1604                          glv_flags, FNE_CHECK_START);
1605      if (lv.ll_name == NULL) {
1606        error = true;  // error, but continue parsing.
1607      }
1608      if (name_end == NULL
1609          || (!ascii_iswhite(*name_end) && !ends_excmd(*name_end))) {
1610        if (name_end != NULL) {
1611          emsg_severe = true;
1612          semsg(_(e_trailing_arg), name_end);
1613        }
1614        if (!(eap->skip || error)) {
1615          clear_lval(&lv);
1616        }
1617        break;
1618      }
1619
1620      if (!error && !eap->skip && callback(&lv, name_end, eap, deep) == FAIL) {
1621        error = true;
1622      }
1623
1624      if (!eap->skip) {
1625        clear_lval(&lv);
1626      }
1627    }
1628    arg = skipwhite(name_end);
1629  } while (!ends_excmd(*arg));
1630
1631  eap->nextcmd = check_nextcmd(arg);
1632}
1633
1634/// Unlet a variable indicated by `lp`.
1635///
1636/// @param[in]  lp  The lvalue.
1637/// @param[in]  name_end  End of the string argument for the command.
1638/// @param[in]  eap  Ex command arguments for :unlet.
1639/// @param[in]  deep  Unused.
1640///
1641/// @return OK on success, or FAIL on failure.
1642static int do_unlet_var(lval_T *lp, char *name_end, exarg_T *eap, int deep FUNC_ATTR_UNUSED)
1643  FUNC_ATTR_NONNULL_ALL
1644{
1645  int forceit = eap->forceit;
1646  int ret = OK;
1647
1648  if (lp->ll_tv == NULL) {
1649    int cc = (uint8_t)(*name_end);
1650    *name_end = NUL;
1651
1652    // Environment variable, normal name or expanded name.
1653    if (*lp->ll_name == '$') {
1654      vim_unsetenv_ext(lp->ll_name + 1);
1655    } else if (do_unlet(lp->ll_name, lp->ll_name_len, forceit) == FAIL) {
1656      ret = FAIL;
1657    }
1658    *name_end = (char)cc;
1659  } else if ((lp->ll_list != NULL
1660              // ll_list is not NULL when lvalue is not in a list, NULL lists
1661              // yield E689.
1662              && value_check_lock(tv_list_locked(lp->ll_list),
1663                                  lp->ll_name,
1664                                  lp->ll_name_len))
1665             || (lp->ll_dict != NULL
1666                 && value_check_lock(lp->ll_dict->dv_lock,
1667                                     lp->ll_name,
1668                                     lp->ll_name_len))) {
1669    return FAIL;
1670  } else if (lp->ll_range) {
1671    tv_list_unlet_range(lp->ll_list, lp->ll_li, lp->ll_n1, !lp->ll_empty2, lp->ll_n2);
1672  } else if (lp->ll_list != NULL) {
1673    // unlet a List item.
1674    tv_list_item_remove(lp->ll_list, lp->ll_li);
1675  } else {
1676    // unlet a Dict item.
1677    dict_T *d = lp->ll_dict;
1678    assert(d != NULL);
1679    dictitem_T *di = lp->ll_di;
1680    bool watched = tv_dict_is_watched(d);
1681    char *key = NULL;
1682    typval_T oldtv;
1683
1684    if (watched) {
1685      tv_copy(&di->di_tv, &oldtv);
1686      // need to save key because dictitem_remove will free it
1687      key = xstrdup(di->di_key);
1688    }
1689
1690    tv_dict_item_remove(d, di);
1691
1692    if (watched) {
1693      tv_dict_watcher_notify(d, key, NULL, &oldtv);
1694      tv_clear(&oldtv);
1695      xfree(key);
1696    }
1697  }
1698
1699  return ret;
1700}
1701
1702/// Unlet one item or a range of items from a list.
1703/// Return OK or FAIL.
1704static void tv_list_unlet_range(list_T *const l, listitem_T *const li_first, const int n1_arg,
1705                                const bool has_n2, const int n2)
1706{
1707  assert(l != NULL);
1708  // Delete a range of List items.
1709  listitem_T *li_last = li_first;
1710  int n1 = n1_arg;
1711  while (true) {
1712    listitem_T *const li = TV_LIST_ITEM_NEXT(l, li_last);
1713    n1++;
1714    if (li == NULL || (has_n2 && n2 < n1)) {
1715      break;
1716    }
1717    li_last = li;
1718  }
1719  tv_list_remove_items(l, li_first, li_last);
1720}
1721
1722/// unlet a variable
1723///
1724/// @param[in]  name  Variable name to unlet.
1725/// @param[in]  name_len  Variable name length.
1726/// @param[in]  forceit  If true, do not complain if variable doesn’t exist.
1727///
1728/// @return OK if it existed, FAIL otherwise.
1729int do_unlet(const char *const name, const size_t name_len, const bool forceit)
1730  FUNC_ATTR_NONNULL_ALL
1731{
1732  const char *varname = NULL;  // init to shut up gcc
1733  dict_T *dict;
1734  hashtab_T *ht = find_var_ht_dict(name, name_len, &varname, &dict);
1735
1736  if (ht != NULL && *varname != NUL) {
1737    dict_T *d = get_current_funccal_dict(ht);
1738    if (d == NULL) {
1739      if (ht == &globvarht) {
1740        d = &globvardict;
1741      } else if (ht == &compat_hashtab) {
1742        d = &vimvardict;
1743      } else {
1744        dictitem_T *const di = find_var_in_ht(ht, *name, "", 0, false);
1745        d = di->di_tv.vval.v_dict;
1746      }
1747      if (d == NULL) {
1748        internal_error("do_unlet()");
1749        return FAIL;
1750      }
1751    }
1752
1753    hashitem_T *hi = hash_find(ht, varname);
1754    if (HASHITEM_EMPTY(hi)) {
1755      hi = find_hi_in_scoped_ht(name, &ht);
1756    }
1757    if (hi != NULL && !HASHITEM_EMPTY(hi)) {
1758      dictitem_T *const di = TV_DICT_HI2DI(hi);
1759      if (var_check_fixed(di->di_flags, name, TV_CSTRING)
1760          || var_check_ro(di->di_flags, name, TV_CSTRING)
1761          || value_check_lock(d->dv_lock, name, TV_CSTRING)) {
1762        return FAIL;
1763      }
1764
1765      if (value_check_lock(d->dv_lock, name, TV_CSTRING)) {
1766        return FAIL;
1767      }
1768
1769      typval_T oldtv;
1770      bool watched = tv_dict_is_watched(dict);
1771
1772      if (watched) {
1773        tv_copy(&di->di_tv, &oldtv);
1774      }
1775
1776      delete_var(ht, hi);
1777
1778      if (watched) {
1779        tv_dict_watcher_notify(dict, varname, NULL, &oldtv);
1780        tv_clear(&oldtv);
1781      }
1782      return OK;
1783    }
1784  }
1785  if (forceit) {
1786    return OK;
1787  }
1788  semsg(_("E108: No such variable: \"%s\""), name);
1789  return FAIL;
1790}
1791
1792/// Lock or unlock variable indicated by `lp`.
1793///
1794/// Locks if `eap->cmdidx == CMD_lockvar`, unlocks otherwise.
1795///
1796/// @param[in]  lp  The lvalue.
1797/// @param[in]  name_end  Unused.
1798/// @param[in]  eap  Ex command arguments for :(un)lockvar.
1799/// @param[in]  deep  Levels to (un)lock, -1 to (un)lock everything.
1800///
1801/// @return OK on success, or FAIL on failure.
1802static int do_lock_var(lval_T *lp, char *name_end FUNC_ATTR_UNUSED, exarg_T *eap, int deep)
1803  FUNC_ATTR_NONNULL_ARG(1, 3)
1804{
1805  bool lock = eap->cmdidx == CMD_lockvar;
1806  int ret = OK;
1807
1808  if (lp->ll_tv == NULL) {
1809    if (*lp->ll_name == '$') {
1810      semsg(_(e_lock_unlock), lp->ll_name);
1811      ret = FAIL;
1812    } else {
1813      // Normal name or expanded name.
1814      dictitem_T *const di = find_var(lp->ll_name, lp->ll_name_len, NULL,
1815                                      true);
1816      if (di == NULL) {
1817        ret = FAIL;
1818      } else if ((di->di_flags & DI_FLAGS_FIX)
1819                 && di->di_tv.v_type != VAR_DICT
1820                 && di->di_tv.v_type != VAR_LIST) {
1821        // For historical reasons this error is not given for Lists and
1822        // Dictionaries. E.g. b: dictionary may be locked/unlocked.
1823        semsg(_(e_lock_unlock), lp->ll_name);
1824        ret = FAIL;
1825      } else {
1826        if (lock) {
1827          di->di_flags |= DI_FLAGS_LOCK;
1828        } else {
1829          di->di_flags &= (uint8_t)(~DI_FLAGS_LOCK);
1830        }
1831        if (deep != 0) {
1832          tv_item_lock(&di->di_tv, deep, lock, false);
1833        }
1834      }
1835    }
1836  } else if (deep == 0) {
1837    // nothing to do
1838  } else if (lp->ll_range) {
1839    listitem_T *li = lp->ll_li;
1840
1841    // (un)lock a range of List items.
1842    while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1)) {
1843      tv_item_lock(TV_LIST_ITEM_TV(li), deep, lock, false);
1844      li = TV_LIST_ITEM_NEXT(lp->ll_list, li);
1845      lp->ll_n1++;
1846    }
1847  } else if (lp->ll_list != NULL) {
1848    // (un)lock a List item.
1849    tv_item_lock(TV_LIST_ITEM_TV(lp->ll_li), deep, lock, false);
1850  } else {
1851    // (un)lock a Dict item.
1852    tv_item_lock(&lp->ll_di->di_tv, deep, lock, false);
1853  }
1854
1855  return ret;
1856}
1857
1858/// Delete all "menutrans_" variables.
1859void del_menutrans_vars(void)
1860{
1861  hash_lock(&globvarht);
1862  HASHTAB_ITER(&globvarht, hi, {
1863    if (strncmp(hi->hi_key, "menutrans_", 10) == 0) {
1864      delete_var(&globvarht, hi);
1865    }
1866  });
1867  hash_unlock(&globvarht);
1868}
1869
1870/// @return  global variable dictionary
1871dict_T *get_globvar_dict(void)
1872  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_RET
1873{
1874  return &globvardict;
1875}
1876
1877/// @return  global variable hash table
1878hashtab_T *get_globvar_ht(void)
1879{
1880  return &globvarht;
1881}
1882
1883/// @return  v: variable dictionary
1884dict_T *get_vimvar_dict(void)
1885  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_RET
1886{
1887  return &vimvardict;
1888}
1889
1890/// Set v:variable to tv.
1891///
1892/// @param[in]  idx  Index of variable to set.
1893/// @param[in]  val  Value to set to. Will be copied.
1894void set_vim_var_tv(const VimVarIndex idx, typval_T *const tv)
1895{
1896  typval_T *tv_out = get_vim_var_tv(idx);
1897  tv_clear(tv_out);
1898  tv_copy(tv, tv_out);
1899}
1900
1901char *get_vim_var_name(const VimVarIndex idx)
1902  FUNC_ATTR_NONNULL_RET
1903{
1904  return vimvars[idx].vv_name;
1905}
1906
1907/// Get typval_T v: variable value.
1908typval_T *get_vim_var_tv(const VimVarIndex idx)
1909{
1910  return &vimvars[idx].vv_tv;
1911}
1912
1913/// Get number v: variable value.
1914varnumber_T get_vim_var_nr(const VimVarIndex idx) FUNC_ATTR_PURE
1915{
1916  typval_T *tv = get_vim_var_tv(idx);
1917  return tv->vval.v_number;
1918}
1919
1920/// Get List v: variable value.  Caller must take care of reference count when
1921/// needed.
1922list_T *get_vim_var_list(const VimVarIndex idx) FUNC_ATTR_PURE
1923{
1924  typval_T *tv = get_vim_var_tv(idx);
1925  return tv->vval.v_list;
1926}
1927
1928/// Get Dictionary v: variable value.  Caller must take care of reference count
1929/// when needed.
1930dict_T *get_vim_var_dict(const VimVarIndex idx) FUNC_ATTR_PURE
1931{
1932  typval_T *tv = get_vim_var_tv(idx);
1933  return tv->vval.v_dict;
1934}
1935
1936/// Get string v: variable value.  Uses a static buffer, can only be used once.
1937/// If the String variable has never been set, return an empty string.
1938/// Never returns NULL.
1939char *get_vim_var_str(const VimVarIndex idx)
1940  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_RET
1941{
1942  return (char *)tv_get_string(get_vim_var_tv(idx));
1943}
1944
1945/// Get Partial v: variable value.  Caller must take care of reference count
1946/// when needed.
1947partial_T *get_vim_var_partial(const VimVarIndex idx) FUNC_ATTR_PURE
1948{
1949  typval_T *tv = get_vim_var_tv(idx);
1950  return tv->vval.v_partial;
1951}
1952
1953/// Local string buffer for the next two functions to store a variable name
1954/// with its prefix. Allocated in cat_prefix_varname(), freed later in
1955/// get_user_var_name().
1956
1957static char *varnamebuf = NULL;
1958static size_t varnamebuflen = 0;
1959
1960/// Function to concatenate a prefix and a variable name.
1961char *cat_prefix_varname(int prefix, const char *name)
1962  FUNC_ATTR_NONNULL_ALL
1963{
1964  size_t len = strlen(name) + 3;
1965
1966  if (len > varnamebuflen) {
1967    xfree(varnamebuf);
1968    len += 10;                          // some additional space
1969    varnamebuf = xmalloc(len);
1970    varnamebuflen = len;
1971  }
1972  *varnamebuf = (char)prefix;
1973  varnamebuf[1] = ':';
1974  STRCPY(varnamebuf + 2, name);
1975  return varnamebuf;
1976}
1977
1978/// Function given to ExpandGeneric() to obtain the list of user defined
1979/// (global/buffer/window/built-in) variable names.
1980char *get_user_var_name(expand_T *xp, int idx)
1981{
1982  static size_t gdone;
1983  static size_t bdone;
1984  static size_t wdone;
1985  static size_t tdone;
1986  static size_t vidx;
1987  static hashitem_T *hi;
1988
1989  if (idx == 0) {
1990    gdone = bdone = wdone = vidx = 0;
1991    tdone = 0;
1992  }
1993
1994  // Global variables
1995  if (gdone < globvarht.ht_used) {
1996    if (gdone++ == 0) {
1997      hi = globvarht.ht_array;
1998    } else {
1999      hi++;
2000    }
2001    while (HASHITEM_EMPTY(hi)) {
2002      hi++;
2003    }
2004    if (strncmp("g:", xp->xp_pattern, 2) == 0) {
2005      return cat_prefix_varname('g', hi->hi_key);
2006    }
2007    return hi->hi_key;
2008  }
2009
2010  // b: variables
2011  const hashtab_T *ht = &prevwin_curwin()->w_buffer->b_vars->dv_hashtab;
2012  if (bdone < ht->ht_used) {
2013    if (bdone++ == 0) {
2014      hi = ht->ht_array;
2015    } else {
2016      hi++;
2017    }
2018    while (HASHITEM_EMPTY(hi)) {
2019      hi++;
2020    }
2021    return cat_prefix_varname('b', hi->hi_key);
2022  }
2023
2024  // w: variables
2025  ht = &prevwin_curwin()->w_vars->dv_hashtab;
2026  if (wdone < ht->ht_used) {
2027    if (wdone++ == 0) {
2028      hi = ht->ht_array;
2029    } else {
2030      hi++;
2031    }
2032    while (HASHITEM_EMPTY(hi)) {
2033      hi++;
2034    }
2035    return cat_prefix_varname('w', hi->hi_key);
2036  }
2037
2038  // t: variables
2039  ht = &curtab->tp_vars->dv_hashtab;
2040  if (tdone < ht->ht_used) {
2041    if (tdone++ == 0) {
2042      hi = ht->ht_array;
2043    } else {
2044      hi++;
2045    }
2046    while (HASHITEM_EMPTY(hi)) {
2047      hi++;
2048    }
2049    return cat_prefix_varname('t', hi->hi_key);
2050  }
2051
2052  // v: variables
2053  if (vidx < ARRAY_SIZE(vimvars)) {
2054    return cat_prefix_varname('v', get_vim_var_name((VimVarIndex)vidx++));
2055  }
2056
2057  XFREE_CLEAR(varnamebuf);
2058  varnamebuflen = 0;
2059  return NULL;
2060}
2061
2062/// Set type of v: variable to the given type.
2063///
2064/// @param[in]  idx  Index of variable to set.
2065/// @param[in]  type  Type to set to.
2066void set_vim_var_type(const VimVarIndex idx, const VarType type)
2067{
2068  typval_T *tv = get_vim_var_tv(idx);
2069  tv->v_type = type;
2070}
2071
2072/// Set number v: variable to the given value
2073/// Note that this does not set the type, use set_vim_var_type() for that.
2074///
2075/// @param[in]  idx  Index of variable to set.
2076/// @param[in]  val  Value to set to.
2077void set_vim_var_nr(const VimVarIndex idx, const varnumber_T val)
2078{
2079  typval_T *tv = get_vim_var_tv(idx);
2080  tv_clear(tv);
2081  tv->vval.v_number = val;
2082}
2083
2084/// Set boolean v: {true, false} to the given value
2085///
2086/// @param[in]  idx  Index of variable to set.
2087/// @param[in]  val  Value to set to.
2088void set_vim_var_bool(const VimVarIndex idx, const BoolVarValue val)
2089{
2090  typval_T *tv = get_vim_var_tv(idx);
2091  tv_clear(tv);
2092  tv->v_type = VAR_BOOL;
2093  tv->vval.v_bool = val;
2094}
2095
2096/// Set special v: variable to the given value
2097///
2098/// @param[in]  idx  Index of variable to set.
2099/// @param[in]  val  Value to set to.
2100void set_vim_var_special(const VimVarIndex idx, const SpecialVarValue val)
2101{
2102  typval_T *tv = get_vim_var_tv(idx);
2103  tv_clear(tv);
2104  tv->v_type = VAR_SPECIAL;
2105  tv->vval.v_special = val;
2106}
2107
2108/// Set v:char to character "c".
2109void set_vim_var_char(int c)
2110{
2111  char buf[MB_MAXCHAR + 1];
2112  int buflen = utf_char2bytes(c, buf);
2113  buf[buflen] = NUL;
2114  set_vim_var_string(VV_CHAR, buf, buflen);
2115}
2116
2117/// Set string v: variable to the given string
2118///
2119/// @param[in]  idx  Index of variable to set.
2120/// @param[in]  val  Value to set to. Will be copied.
2121/// @param[in]  len  Length of that value or -1 in which case strlen() will be
2122///                  used.
2123void set_vim_var_string(const VimVarIndex idx, const char *const val, const ptrdiff_t len)
2124{
2125  typval_T *tv = get_vim_var_tv(idx);
2126  tv_clear(tv);
2127  tv->v_type = VAR_STRING;
2128  if (val == NULL) {
2129    tv->vval.v_string = NULL;
2130  } else if (len == -1) {
2131    tv->vval.v_string = xstrdup(val);
2132  } else {
2133    tv->vval.v_string = xstrndup(val, (size_t)len);
2134  }
2135}
2136
2137/// Set list v: variable to the given list
2138///
2139/// @param[in]  idx  Index of variable to set.
2140/// @param[in,out]  val  Value to set to. Reference count will be incremented.
2141void set_vim_var_list(const VimVarIndex idx, list_T *const val)
2142{
2143  typval_T *tv = get_vim_var_tv(idx);
2144  tv_clear(tv);
2145  tv->v_type = VAR_LIST;
2146  tv->vval.v_list = val;
2147  if (val != NULL) {
2148    tv_list_ref(val);
2149  }
2150}
2151
2152/// Set Dictionary v: variable to the given dictionary
2153///
2154/// @param[in]  idx  Index of variable to set.
2155/// @param[in,out]  val  Value to set to. Reference count will be incremented.
2156///                      Also keys of the dictionary will be made read-only.
2157void set_vim_var_dict(const VimVarIndex idx, dict_T *const val)
2158{
2159  typval_T *tv = get_vim_var_tv(idx);
2160  tv_clear(tv);
2161  tv->v_type = VAR_DICT;
2162  tv->vval.v_dict = val;
2163  if (val == NULL) {
2164    return;
2165  }
2166
2167  val->dv_refcount++;
2168  // Set readonly
2169  tv_dict_set_keys_readonly(val);
2170}
2171
2172/// Set partial v: variable to the given value
2173/// Note that this does not set the type, use set_vim_var_type() for that.
2174///
2175/// @param[in]  idx  Index of variable to set.
2176/// @param[in]  val  Value to set to.
2177void set_vim_var_partial(const VimVarIndex idx, partial_T *val)
2178{
2179  typval_T *tv = get_vim_var_tv(idx);
2180  tv->vval.v_partial = val;
2181}
2182
2183/// Set v:register if needed.
2184void set_reg_var(int c)
2185{
2186  char regname[2];
2187
2188  if (c == 0 || c == ' ') {
2189    regname[0] = '"';
2190  } else {
2191    regname[0] = (char)c;
2192  }
2193  regname[1] = NUL;
2194  // Avoid free/alloc when the value is already right.
2195  typval_T *tv = get_vim_var_tv(VV_REG);
2196  if (tv->vval.v_string == NULL || tv->vval.v_string[0] != c) {
2197    set_vim_var_string(VV_REG, regname, 1);
2198  }
2199}
2200
2201/// Get or set v:exception.  If "oldval" == NULL, return the current value.
2202/// Otherwise, restore the value to "oldval" and return NULL.
2203/// Must always be called in pairs to save and restore v:exception!  Does not
2204/// take care of memory allocations.
2205char *v_exception(char *oldval)
2206{
2207  typval_T *tv = get_vim_var_tv(VV_EXCEPTION);
2208  if (oldval == NULL) {
2209    return tv->vval.v_string;
2210  }
2211
2212  tv->vval.v_string = oldval;
2213  return NULL;
2214}
2215
2216/// Set v:cmdarg.
2217/// If "eap" != NULL, use "eap" to generate the value and return the old value.
2218/// If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
2219/// Must always be called in pairs!
2220char *set_cmdarg(exarg_T *eap, char *oldarg)
2221{
2222  typval_T *tv = get_vim_var_tv(VV_CMDARG);
2223  char *oldval = tv->vval.v_string;
2224  if (eap == NULL) {
2225    goto error;
2226  }
2227
2228  size_t len = 0;
2229  if (eap->force_bin == FORCE_BIN) {
2230    len += 6;  // " ++bin"
2231  } else if (eap->force_bin == FORCE_NOBIN) {
2232    len += 8;  // " ++nobin"
2233  }
2234
2235  if (eap->read_edit) {
2236    len += 7;  // " ++edit"
2237  }
2238
2239  if (eap->force_ff != 0) {
2240    len += 10;  // " ++ff=unix"
2241  }
2242  if (eap->force_enc != 0) {
2243    len += strlen(eap->cmd + eap->force_enc) + 7;
2244  }
2245  if (eap->bad_char != 0) {
2246    len += 7 + 4;  // " ++bad=" + "keep" or "drop"
2247  }
2248  if (eap->mkdir_p != 0) {
2249    len += 4;  // " ++p"
2250  }
2251
2252  const size_t newval_len = len + 1;
2253  char *newval = xmalloc(newval_len);
2254  size_t xlen = 0;
2255  int rc = 0;
2256
2257  if (eap->force_bin == FORCE_BIN) {
2258    rc = snprintf(newval, newval_len, " ++bin");
2259  } else if (eap->force_bin == FORCE_NOBIN) {
2260    rc = snprintf(newval, newval_len, " ++nobin");
2261  } else {
2262    *newval = NUL;
2263  }
2264  if (rc < 0) {
2265    goto error;
2266  }
2267  xlen += (size_t)rc;
2268
2269  if (eap->read_edit) {
2270    rc = snprintf(newval + xlen, newval_len - xlen, " ++edit");
2271    if (rc < 0) {
2272      goto error;
2273    }
2274    xlen += (size_t)rc;
2275  }
2276
2277  if (eap->force_ff != 0) {
2278    rc = snprintf(newval + xlen,
2279                  newval_len - xlen,
2280                  " ++ff=%s",
2281                  eap->force_ff == 'u' ? "unix"
2282                                       : eap->force_ff == 'd' ? "dos" : "mac");
2283    if (rc < 0) {
2284      goto error;
2285    }
2286    xlen += (size_t)rc;
2287  }
2288  if (eap->force_enc != 0) {
2289    rc = snprintf(newval + xlen, newval_len - xlen, " ++enc=%s", eap->cmd + eap->force_enc);
2290    if (rc < 0) {
2291      goto error;
2292    }
2293    xlen += (size_t)rc;
2294  }
2295
2296  if (eap->bad_char == BAD_KEEP) {
2297    rc = snprintf(newval + xlen, newval_len - xlen, " ++bad=keep");
2298    if (rc < 0) {
2299      goto error;
2300    }
2301    xlen += (size_t)rc;
2302  } else if (eap->bad_char == BAD_DROP) {
2303    rc = snprintf(newval + xlen, newval_len - xlen, " ++bad=drop");
2304    if (rc < 0) {
2305      goto error;
2306    }
2307    xlen += (size_t)rc;
2308  } else if (eap->bad_char != 0) {
2309    rc = snprintf(newval + xlen, newval_len - xlen, " ++bad=%c", eap->bad_char);
2310    if (rc < 0) {
2311      goto error;
2312    }
2313    xlen += (size_t)rc;
2314  }
2315
2316  if (eap->mkdir_p != 0) {
2317    rc = snprintf(newval + xlen, newval_len - xlen, " ++p");
2318    if (rc < 0) {
2319      goto error;
2320    }
2321    xlen += (size_t)rc;
2322  }
2323  assert(xlen <= newval_len);
2324
2325  tv->vval.v_string = newval;
2326  return oldval;
2327
2328error:
2329  xfree(oldval);
2330  tv->vval.v_string = oldarg;
2331  return NULL;
2332}
2333
2334/// Get or set v:throwpoint.  If "oldval" == NULL, return the current value.
2335/// Otherwise, restore the value to "oldval" and return NULL.
2336/// Must always be called in pairs to save and restore v:throwpoint!  Does not
2337/// take care of memory allocations.
2338char *v_throwpoint(char *oldval)
2339{
2340  typval_T *tv = get_vim_var_tv(VV_THROWPOINT);
2341  if (oldval == NULL) {
2342    return tv->vval.v_string;
2343  }
2344
2345  tv->vval.v_string = oldval;
2346  return NULL;
2347}
2348
2349/// Set v:count to "count" and v:count1 to "count1".
2350///
2351/// @param set_prevcount  if true, first set v:prevcount from v:count.
2352void set_vcount(int64_t count, int64_t count1, bool set_prevcount)
2353{
2354  if (set_prevcount) {
2355    get_vim_var_tv(VV_PREVCOUNT)->vval.v_number = get_vim_var_nr(VV_COUNT);
2356  }
2357  get_vim_var_tv(VV_COUNT)->vval.v_number = count;
2358  get_vim_var_tv(VV_COUNT1)->vval.v_number = count1;
2359}
2360
2361/// Get the value of internal variable "name".
2362/// Return OK or FAIL.  If OK is returned "rettv" must be cleared.
2363///
2364/// @param len  length of "name"
2365/// @param rettv  NULL when only checking existence
2366/// @param dip  non-NULL when typval's dict item is needed
2367/// @param verbose  may give error message
2368/// @param no_autoload  do not use script autoloading
2369int eval_variable(const char *name, int len, typval_T *rettv, dictitem_T **dip, bool verbose,
2370                  bool no_autoload)
2371{
2372  int ret = OK;
2373  typval_T *tv = NULL;
2374  dictitem_T *v;
2375
2376  v = find_var(name, (size_t)len, NULL, no_autoload);
2377  if (v != NULL) {
2378    tv = &v->di_tv;
2379    if (dip != NULL) {
2380      *dip = v;
2381    }
2382  }
2383
2384  if (tv == NULL) {
2385    if (rettv != NULL && verbose) {
2386      semsg(_("E121: Undefined variable: %.*s"), len, name);
2387    }
2388    ret = FAIL;
2389  } else if (rettv != NULL) {
2390    tv_copy(tv, rettv);
2391  }
2392
2393  return ret;
2394}
2395
2396/// Check if variable "name[len]" is a local variable or an argument.
2397/// If so, "*eval_lavars_used" is set to true.
2398void check_vars(const char *name, size_t len)
2399{
2400  if (eval_lavars_used == NULL) {
2401    return;
2402  }
2403
2404  const char *varname;
2405  hashtab_T *ht = find_var_ht(name, len, &varname);
2406
2407  if (ht == get_funccal_local_ht() || ht == get_funccal_args_ht()) {
2408    if (find_var(name, len, NULL, true) != NULL) {
2409      *eval_lavars_used = true;
2410    }
2411  }
2412}
2413
2414/// Find variable "name" in the list of variables.
2415/// Careful: "a:0" variables don't have a name.
2416/// When "htp" is not NULL we are writing to the variable, set "htp" to the
2417/// hashtab_T used.
2418///
2419/// @return  a pointer to it if found, NULL if not found.
2420dictitem_T *find_var(const char *const name, const size_t name_len, hashtab_T **htp,
2421                     int no_autoload)
2422{
2423  const char *varname;
2424  hashtab_T *const ht = find_var_ht(name, name_len, &varname);
2425  if (htp != NULL) {
2426    *htp = ht;
2427  }
2428  if (ht == NULL) {
2429    return NULL;
2430  }
2431  dictitem_T *const ret = find_var_in_ht(ht, *name,
2432                                         varname,
2433                                         name_len - (size_t)(varname - name),
2434                                         no_autoload || htp != NULL);
2435  if (ret != NULL) {
2436    return ret;
2437  }
2438
2439  // Search in parent scope for lambda
2440  return find_var_in_scoped_ht(name, name_len, no_autoload || htp != NULL);
2441}
2442
2443/// Find variable in hashtab.
2444/// When "varname" is empty returns curwin/curtab/etc vars dictionary.
2445///
2446/// @param[in]  ht  Hashtab to find variable in.
2447/// @param[in]  htname  Hashtab name (first character).
2448/// @param[in]  varname  Variable name.
2449/// @param[in]  varname_len  Variable name length.
2450/// @param[in]  no_autoload  If true then autoload scripts will not be sourced
2451///                          if autoload variable was not found.
2452///
2453/// @return pointer to the dictionary item with the found variable or NULL if it
2454///         was not found.
2455dictitem_T *find_var_in_ht(hashtab_T *const ht, int htname, const char *const varname,
2456                           const size_t varname_len, int no_autoload)
2457  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
2458{
2459  if (varname_len == 0) {
2460    // Must be something like "s:", otherwise "ht" would be NULL.
2461    switch (htname) {
2462    case 's':
2463      return (dictitem_T *)&SCRIPT_SV(current_sctx.sc_sid)->sv_var;
2464    case 'g':
2465      return (dictitem_T *)&globvars_var;
2466    case 'v':
2467      return (dictitem_T *)&vimvars_var;
2468    case 'b':
2469      return (dictitem_T *)&curbuf->b_bufvar;
2470    case 'w':
2471      return (dictitem_T *)&curwin->w_winvar;
2472    case 't':
2473      return (dictitem_T *)&curtab->tp_winvar;
2474    case 'l':
2475      return get_funccal_local_var();
2476    case 'a':
2477      return get_funccal_args_var();
2478    }
2479    return NULL;
2480  }
2481
2482  hashitem_T *hi = hash_find_len(ht, varname, varname_len);
2483  if (HASHITEM_EMPTY(hi)) {
2484    // For global variables we may try auto-loading the script.  If it
2485    // worked find the variable again.  Don't auto-load a script if it was
2486    // loaded already, otherwise it would be loaded every time when
2487    // checking if a function name is a Funcref variable.
2488    if (ht == get_globvar_ht() && !no_autoload) {
2489      // Note: script_autoload() may make "hi" invalid. It must either
2490      // be obtained again or not used.
2491      if (!script_autoload(varname, varname_len, false) || aborting()) {
2492        return NULL;
2493      }
2494      hi = hash_find_len(ht, varname, varname_len);
2495    }
2496    if (HASHITEM_EMPTY(hi)) {
2497      return NULL;
2498    }
2499  }
2500  return TV_DICT_HI2DI(hi);
2501}
2502
2503/// Finds the dict (g:, l:, s:, …) and hashtable used for a variable.
2504///
2505/// Assigns SID if s: scope is accessed from Lua or anonymous Vimscript. #15994
2506///
2507/// @param[in]  name  Variable name, possibly with scope prefix.
2508/// @param[in]  name_len  Variable name length.
2509/// @param[out]  varname  Will be set to the start of the name without scope
2510///                       prefix.
2511/// @param[out]  d  Scope dictionary.
2512///
2513/// @return Scope hashtab, NULL if name is not valid.
2514static hashtab_T *find_var_ht_dict(const char *name, const size_t name_len, const char **varname,
2515                                   dict_T **d)
2516{
2517  *d = NULL;
2518
2519  if (name_len == 0) {
2520    return NULL;
2521  }
2522  if (name_len == 1 || name[1] != ':') {
2523    // name has implicit scope
2524    if (name[0] == ':' || name[0] == AUTOLOAD_CHAR) {
2525      // The name must not start with a colon or #.
2526      return NULL;
2527    }
2528    *varname = name;
2529
2530    // "version" is "v:version" in all scopes
2531    hashitem_T *hi = hash_find_len(&compat_hashtab, name, name_len);
2532    if (!HASHITEM_EMPTY(hi)) {
2533      return &compat_hashtab;
2534    }
2535
2536    *d = get_funccal_local_dict();
2537    if (*d != NULL) {  // local variable
2538      goto end;
2539    }
2540
2541    *d = get_globvar_dict();  // global variable
2542    goto end;
2543  }
2544
2545  *varname = name + 2;
2546  if (*name == 'g') {  // global variable
2547    *d = get_globvar_dict();
2548  } else if (name_len > 2
2549             && (memchr(name + 2, ':', name_len - 2) != NULL
2550                 || memchr(name + 2, AUTOLOAD_CHAR, name_len - 2) != NULL)) {
2551    // There must be no ':' or '#' in the rest of the name if g: was not used
2552    return NULL;
2553  }
2554
2555  if (*name == 'b') {  // buffer variable
2556    *d = curbuf->b_vars;
2557  } else if (*name == 'w') {  // window variable
2558    *d = curwin->w_vars;
2559  } else if (*name == 't') {  // tab page variable
2560    *d = curtab->tp_vars;
2561  } else if (*name == 'v') {  // v: variable
2562    *d = get_vimvar_dict();
2563  } else if (*name == 'a') {  // a: function argument
2564    *d = get_funccal_args_dict();
2565  } else if (*name == 'l') {  // l: local variable
2566    *d = get_funccal_local_dict();
2567  } else if (*name == 's'  // script variable
2568             && (current_sctx.sc_sid > 0 || current_sctx.sc_sid == SID_STR
2569                 || current_sctx.sc_sid == SID_LUA)
2570             && current_sctx.sc_sid <= script_items.ga_len) {
2571    // For anonymous scripts without a script item, create one now so script vars can be used
2572    // Try to resolve lua filename & linenr so it can be shown in last-set messages.
2573    nlua_set_sctx(&current_sctx);
2574    if (current_sctx.sc_sid == SID_STR || current_sctx.sc_sid == SID_LUA) {
2575      // Create SID if s: scope is accessed from Lua or anon Vimscript. #15994
2576      new_script_item(NULL, &current_sctx.sc_sid);
2577    }
2578    *d = &SCRIPT_SV(current_sctx.sc_sid)->sv_dict;
2579  }
2580
2581end:
2582  return *d ? &(*d)->dv_hashtab : NULL;
2583}
2584
2585/// Find the hashtable used for a variable
2586///
2587/// @param[in]  name  Variable name, possibly with scope prefix.
2588/// @param[in]  name_len  Variable name length.
2589/// @param[out]  varname  Will be set to the start of the name without scope
2590///                       prefix.
2591///
2592/// @return Scope hashtab, NULL if name is not valid.
2593hashtab_T *find_var_ht(const char *name, const size_t name_len, const char **varname)
2594{
2595  dict_T *d;
2596  return find_var_ht_dict(name, name_len, varname, &d);
2597}
2598
2599/// @return  the string value of a (global/local) variable or
2600///          NULL when it doesn't exist.
2601///
2602/// @see  tv_get_string() for how long the pointer remains valid.
2603char *get_var_value(const char *const name)
2604{
2605  dictitem_T *v;
2606
2607  v = find_var(name, strlen(name), NULL, false);
2608  if (v == NULL) {
2609    return NULL;
2610  }
2611  return (char *)tv_get_string(&v->di_tv);
2612}
2613
2614/// Allocate a new hashtab for a sourced script.  It will be used while
2615/// sourcing this script and when executing functions defined in the script.
2616void new_script_vars(scid_T id)
2617{
2618  scriptvar_T *sv = xcalloc(1, sizeof(scriptvar_T));
2619  init_var_dict(&sv->sv_dict, &sv->sv_var, VAR_SCOPE);
2620  SCRIPT_ITEM(id)->sn_vars = sv;
2621}
2622
2623/// Initialize dictionary "dict" as a scope and set variable "dict_var" to
2624/// point to it.
2625void init_var_dict(dict_T *dict, ScopeDictDictItem *dict_var, ScopeType scope)
2626{
2627  hash_init(&dict->dv_hashtab);
2628  dict->dv_lock = VAR_UNLOCKED;
2629  dict->dv_scope = scope;
2630  dict->dv_refcount = DO_NOT_FREE_CNT;
2631  dict->dv_copyID = 0;
2632  dict_var->di_tv.vval.v_dict = dict;
2633  dict_var->di_tv.v_type = VAR_DICT;
2634  dict_var->di_tv.v_lock = VAR_FIXED;
2635  dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
2636  dict_var->di_key[0] = NUL;
2637  QUEUE_INIT(&dict->watchers);
2638}
2639
2640/// Unreference a dictionary initialized by init_var_dict().
2641void unref_var_dict(dict_T *dict)
2642{
2643  // Now the dict needs to be freed if no one else is using it, go back to
2644  // normal reference counting.
2645  dict->dv_refcount -= DO_NOT_FREE_CNT - 1;
2646  tv_dict_unref(dict);
2647}
2648
2649/// Clean up a list of internal variables.
2650/// Frees all allocated variables and the value they contain.
2651/// Clears hashtab "ht", does not free it.
2652void vars_clear(hashtab_T *ht)
2653{
2654  vars_clear_ext(ht, true);
2655}
2656
2657/// Like vars_clear(), but only free the value if "free_val" is true.
2658void vars_clear_ext(hashtab_T *ht, bool free_val)
2659{
2660  int todo;
2661  hashitem_T *hi;
2662  dictitem_T *v;
2663
2664  hash_lock(ht);
2665  todo = (int)ht->ht_used;
2666  for (hi = ht->ht_array; todo > 0; hi++) {
2667    if (!HASHITEM_EMPTY(hi)) {
2668      todo--;
2669
2670      // Free the variable.  Don't remove it from the hashtab,
2671      // ht_array might change then.  hash_clear() takes care of it
2672      // later.
2673      v = TV_DICT_HI2DI(hi);
2674      if (free_val) {
2675        tv_clear(&v->di_tv);
2676      }
2677      if (v->di_flags & DI_FLAGS_ALLOC) {
2678        xfree(v);
2679      }
2680    }
2681  }
2682  hash_clear(ht);
2683  hash_init(ht);
2684}
2685
2686/// Delete a variable from hashtab "ht" at item "hi".
2687/// Clear the variable value and free the dictitem.
2688static void delete_var(hashtab_T *ht, hashitem_T *hi)
2689{
2690  dictitem_T *di = TV_DICT_HI2DI(hi);
2691
2692  hash_remove(ht, hi);
2693  tv_clear(&di->di_tv);
2694  xfree(di);
2695}
2696
2697/// List the value of one internal variable.
2698static void list_one_var(dictitem_T *v, const char *prefix, int *first)
2699{
2700  char *const s = encode_tv2echo(&v->di_tv, NULL);
2701  list_one_var_a(prefix, v->di_key, (ptrdiff_t)strlen(v->di_key),
2702                 v->di_tv.v_type, (s == NULL ? "" : s), first);
2703  xfree(s);
2704}
2705
2706/// @param[in]  name_len  Length of the name. May be -1, in this case strlen()
2707///                       will be used.
2708/// @param[in,out]  first  When true clear rest of screen and set to false.
2709static void list_one_var_a(const char *prefix, const char *name, const ptrdiff_t name_len,
2710                           const VarType type, const char *string, int *first)
2711{
2712  if (*first) {
2713    msg_ext_set_kind("list_cmd");
2714    msg_start();
2715  } else {
2716    msg_putchar('\n');
2717  }
2718  // don't use msg() to avoid overwriting "v:statusmsg"
2719  if (*prefix != NUL) {
2720    msg_puts(prefix);
2721  }
2722  if (name != NULL) {  // "a:" vars don't have a name stored
2723    msg_puts_len(name, name_len, 0, false);
2724  }
2725  msg_putchar(' ');
2726  msg_advance(22);
2727  if (type == VAR_NUMBER) {
2728    msg_putchar('#');
2729  } else if (type == VAR_FUNC || type == VAR_PARTIAL) {
2730    msg_putchar('*');
2731  } else if (type == VAR_LIST) {
2732    msg_putchar('[');
2733    if (*string == '[') {
2734      string++;
2735    }
2736  } else if (type == VAR_DICT) {
2737    msg_putchar('{');
2738    if (*string == '{') {
2739      string++;
2740    }
2741  } else {
2742    msg_putchar(' ');
2743  }
2744
2745  msg_outtrans(string, 0, false);
2746
2747  if (type == VAR_FUNC || type == VAR_PARTIAL) {
2748    msg_puts("()");
2749  }
2750  if (*first) {
2751    msg_clr_eos();
2752    *first = false;
2753  }
2754}
2755
2756/// Additional handling for setting a v: variable.
2757///
2758/// @return  true if the variable should be set normally,
2759///          false if nothing else needs to be done.
2760bool before_set_vvar(const char *const varname, dictitem_T *const di, typval_T *const tv,
2761                     const bool copy, const bool watched, bool *const type_error)
2762{
2763  if (di->di_tv.v_type == VAR_STRING) {
2764    typval_T oldtv = TV_INITIAL_VALUE;
2765    if (watched) {
2766      tv_copy(&di->di_tv, &oldtv);
2767    }
2768    XFREE_CLEAR(di->di_tv.vval.v_string);
2769    if (copy || tv->v_type != VAR_STRING) {
2770      const char *const val = tv_get_string(tv);
2771      // Careful: when assigning to v:errmsg and tv_get_string()
2772      // causes an error message the variable will already be set.
2773      if (di->di_tv.vval.v_string == NULL) {
2774        di->di_tv.vval.v_string = xstrdup(val);
2775      }
2776    } else {
2777      // Take over the string to avoid an extra alloc/free.
2778      di->di_tv.vval.v_string = tv->vval.v_string;
2779      tv->vval.v_string = NULL;
2780    }
2781    // Notify watchers
2782    if (watched) {
2783      tv_dict_watcher_notify(&vimvardict, varname, &di->di_tv, &oldtv);
2784      tv_clear(&oldtv);
2785    }
2786    return false;
2787  } else if (di->di_tv.v_type == VAR_NUMBER) {
2788    typval_T oldtv = TV_INITIAL_VALUE;
2789    if (watched) {
2790      tv_copy(&di->di_tv, &oldtv);
2791    }
2792    di->di_tv.vval.v_number = tv_get_number(tv);
2793    if (strcmp(varname, "searchforward") == 0) {
2794      set_search_direction(di->di_tv.vval.v_number ? '/' : '?');
2795    } else if (strcmp(varname, "hlsearch") == 0) {
2796      Search.no_hlsearch = !di->di_tv.vval.v_number;
2797      redraw_all_later(UPD_SOME_VALID);
2798    }
2799    // Notify watchers
2800    if (watched) {
2801      tv_dict_watcher_notify(&vimvardict, varname, &di->di_tv, &oldtv);
2802      tv_clear(&oldtv);
2803    }
2804    return false;
2805  } else if (di->di_tv.v_type != tv->v_type) {
2806    *type_error = true;
2807    return false;
2808  }
2809  return true;
2810}
2811
2812/// Set variable to the given value
2813///
2814/// If the variable already exists, the value is updated. Otherwise the variable
2815/// is created.
2816///
2817/// @param[in]  name  Variable name to set.
2818/// @param[in]  name_len  Length of the variable name.
2819/// @param  tv  Variable value.
2820/// @param[in]  copy  True if value in tv is to be copied.
2821void set_var(const char *name, const size_t name_len, typval_T *const tv, const bool copy)
2822  FUNC_ATTR_NONNULL_ALL
2823{
2824  set_var_const(name, name_len, tv, copy, false);
2825}
2826
2827/// Set variable to the given value
2828///
2829/// If the variable already exists, the value is updated. Otherwise the variable
2830/// is created.
2831///
2832/// @param[in]  name  Variable name to set.
2833/// @param[in]  name_len  Length of the variable name.
2834/// @param  tv  Variable value.
2835/// @param[in]  copy  True if value in tv is to be copied.
2836/// @param[in]  is_const  True if value in tv is to be locked.
2837void set_var_const(const char *name, const size_t name_len, typval_T *const tv, const bool copy,
2838                   const bool is_const)
2839  FUNC_ATTR_NONNULL_ALL
2840{
2841  const char *varname;
2842  dict_T *dict;
2843  hashtab_T *ht = find_var_ht_dict(name, name_len, &varname, &dict);
2844  const bool watched = tv_dict_is_watched(dict);
2845
2846  if (ht == NULL || *varname == NUL) {
2847    semsg(_(e_illvar), name);
2848    return;
2849  }
2850  const size_t varname_len = name_len - (size_t)(varname - name);
2851  dictitem_T *di = find_var_in_ht(ht, 0, varname, varname_len, true);
2852
2853  // Search in parent scope which is possible to reference from lambda
2854  if (di == NULL) {
2855    di = find_var_in_scoped_ht(name, name_len, true);
2856  }
2857
2858  if (tv_is_func(*tv) && var_wrong_func_name(name, di == NULL)) {
2859    return;
2860  }
2861
2862  typval_T oldtv = TV_INITIAL_VALUE;
2863  if (di != NULL) {
2864    if (is_const) {
2865      emsg(_(e_cannot_mod));
2866      return;
2867    }
2868
2869    // Check in this order for backwards compatibility:
2870    // - Whether the variable is read-only
2871    // - Whether the variable value is locked
2872    // - Whether the variable is locked
2873    if (var_check_ro(di->di_flags, name, name_len)
2874        || value_check_lock(di->di_tv.v_lock, name, name_len)
2875        || var_check_lock(di->di_flags, name, name_len)) {
2876      return;
2877    }
2878
2879    // existing variable, need to clear the value
2880
2881    // Handle setting internal v: variables separately where needed to
2882    // prevent changing the type.
2883    bool type_error = false;
2884    if (ht == &vimvarht
2885        && !before_set_vvar(varname, di, tv, copy, watched, &type_error)) {
2886      if (type_error) {
2887        semsg(_(e_setting_v_str_to_value_with_wrong_type), varname);
2888      }
2889      return;
2890    }
2891
2892    if (watched) {
2893      tv_copy(&di->di_tv, &oldtv);
2894    }
2895    tv_clear(&di->di_tv);
2896  } else {  // Add a new variable.
2897    // Can't add "v:" or "a:" variable.
2898    if (ht == &vimvarht || ht == get_funccal_args_ht()) {
2899      semsg(_(e_illvar), name);
2900      return;
2901    }
2902
2903    // Make sure the variable name is valid.
2904    if (!valid_varname(varname)) {
2905      return;
2906    }
2907
2908    // Make sure dict is valid
2909    assert(dict != NULL);
2910
2911    di = xmalloc(offsetof(dictitem_T, di_key) + varname_len + 1);
2912    memcpy(di->di_key, varname, varname_len + 1);
2913    if (hash_add(ht, di->di_key) == FAIL) {
2914      xfree(di);
2915      return;
2916    }
2917    di->di_flags = DI_FLAGS_ALLOC;
2918    if (is_const) {
2919      di->di_flags |= DI_FLAGS_LOCK;
2920    }
2921  }
2922
2923  if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT) {
2924    tv_copy(tv, &di->di_tv);
2925  } else {
2926    di->di_tv = *tv;
2927    di->di_tv.v_lock = VAR_UNLOCKED;
2928    tv_init(tv);
2929  }
2930
2931  if (watched) {
2932    tv_dict_watcher_notify(dict, di->di_key, &di->di_tv, &oldtv);
2933    tv_clear(&oldtv);
2934  }
2935
2936  if (is_const) {
2937    // Like :lockvar! name: lock the value and what it contains, but only
2938    // if the reference count is up to one.  That locks only literal
2939    // values.
2940    tv_item_lock(&di->di_tv, DICT_MAXNEST, true, true);
2941  }
2942}
2943
2944/// Check whether variable is read-only (DI_FLAGS_RO, DI_FLAGS_RO_SBX)
2945///
2946/// Also gives an error message.
2947///
2948/// @param[in]  flags  di_flags attribute value.
2949/// @param[in]  name  Variable name, for use in error message.
2950/// @param[in]  name_len  Variable name length. Use #TV_TRANSLATE to translate
2951///                       variable name and compute the length. Use #TV_CSTRING
2952///                       to compute the length with strlen() without
2953///                       translating.
2954///
2955///                       Both #TV_… values are used for optimization purposes:
2956///                       variable name with its length is needed only in case
2957///                       of error, when no error occurs computing them is
2958///                       a waste of CPU resources. This especially applies to
2959///                       gettext.
2960///
2961/// @return True if variable is read-only: either always or in sandbox when
2962///         sandbox is enabled, false otherwise.
2963bool var_check_ro(const int flags, const char *name, size_t name_len)
2964  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
2965{
2966  const char *error_message = NULL;
2967  if (flags & DI_FLAGS_RO) {
2968    error_message = N_(e_cannot_change_readonly_variable_str);
2969  } else if ((flags & DI_FLAGS_RO_SBX) && sandbox) {
2970    error_message = N_(e_cannot_set_variable_in_sandbox_str);
2971  }
2972
2973  if (error_message == NULL) {
2974    return false;
2975  }
2976  if (name_len == TV_TRANSLATE) {
2977    name = _(name);
2978    name_len = strlen(name);
2979  } else if (name_len == TV_CSTRING) {
2980    name_len = strlen(name);
2981  }
2982
2983  semsg(_(error_message), (int)name_len, name);
2984
2985  return true;
2986}
2987
2988/// Return true if di_flags "flags" indicates variable "name" is locked.
2989/// Also give an error message.
2990bool var_check_lock(const int flags, const char *name, size_t name_len)
2991{
2992  if (!(flags & DI_FLAGS_LOCK)) {
2993    return false;
2994  }
2995
2996  if (name_len == TV_TRANSLATE) {
2997    name = _(name);
2998    name_len = strlen(name);
2999  } else if (name_len == TV_CSTRING) {
3000    name_len = strlen(name);
3001  }
3002
3003  semsg(_("E1122: Variable is locked: %.*s"), (int)name_len, name);
3004
3005  return true;
3006}
3007
3008/// Check whether variable is fixed (DI_FLAGS_FIX)
3009///
3010/// Also gives an error message.
3011///
3012/// @param[in]  flags  di_flags attribute value.
3013/// @param[in]  name  Variable name, for use in error message.
3014/// @param[in]  name_len  Variable name length. Use #TV_TRANSLATE to translate
3015///                       variable name and compute the length. Use #TV_CSTRING
3016///                       to compute the length with strlen() without
3017///                       translating.
3018///
3019///                       Both #TV_… values are used for optimization purposes:
3020///                       variable name with its length is needed only in case
3021///                       of error, when no error occurs computing them is
3022///                       a waste of CPU resources. This especially applies to
3023///                       gettext.
3024///
3025/// @return True if variable is fixed, false otherwise.
3026bool var_check_fixed(const int flags, const char *name, size_t name_len)
3027  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
3028{
3029  if (flags & DI_FLAGS_FIX) {
3030    if (name_len == TV_TRANSLATE) {
3031      name = _(name);
3032      name_len = strlen(name);
3033    } else if (name_len == TV_CSTRING) {
3034      name_len = strlen(name);
3035    }
3036    semsg(_(e_cannot_delete_variable_str), (int)name_len, name);
3037    return true;
3038  }
3039  return false;
3040}
3041
3042/// Check if name is a valid name to assign funcref to
3043///
3044/// @param[in]  name  Possible function/funcref name.
3045/// @param[in]  new_var  True if it is a name for a variable.
3046///
3047/// @return false in case of success, true in case of failure. Also gives an
3048///         error message if appropriate.
3049bool var_wrong_func_name(const char *const name, const bool new_var)
3050  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
3051{
3052  // Allow for w: b: s: and t:.
3053  // Allow autoload variable.
3054  if (!(vim_strchr("wbst", (uint8_t)name[0]) != NULL && name[1] == ':')
3055      && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':') ? name[2] : name[0])
3056      && vim_strchr(name, '#') == NULL) {
3057    semsg(_("E704: Funcref variable name must start with a capital: %s"), name);
3058    return true;
3059  }
3060  // Don't allow hiding a function.  When "v" is not NULL we might be
3061  // assigning another function to the same var, the type is checked
3062  // below.
3063  if (new_var && function_exists(name, false)) {
3064    semsg(_("E705: Variable name conflicts with existing function: %s"), name);
3065    return true;
3066  }
3067  return false;
3068}
3069
3070/// Check if a variable name is valid
3071///
3072/// @param[in]  varname  Variable name to check.
3073///
3074/// @return false when variable name is not valid, true when it is. Also gives
3075///         an error message if appropriate.
3076bool valid_varname(const char *varname)
3077  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
3078{
3079  for (const char *p = varname; *p != NUL; p++) {
3080    if (!eval_isnamec1((int)(uint8_t)(*p))
3081        && (p == varname || !ascii_isdigit(*p))
3082        && *p != AUTOLOAD_CHAR) {
3083      semsg(_(e_illvar), varname);
3084      return false;
3085    }
3086  }
3087  return true;
3088}
3089
3090/// Implements the logic to retrieve local variable and option values.
3091/// Used by "getwinvar()" "gettabvar()" "gettabwinvar()" "getbufvar()".
3092///
3093/// @param deftv   default value if not found
3094/// @param htname  't'ab, 'w'indow or 'b'uffer local
3095/// @param tp      can be NULL
3096/// @param buf     ignored if htname is not 'b'
3097static void get_var_from(const char *varname, typval_T *rettv, typval_T *deftv, int htname,
3098                         tabpage_T *tp, win_T *win, buf_T *buf)
3099{
3100  bool done = false;
3101  const bool do_change_curbuf = buf != NULL && htname == 'b';
3102
3103  emsg_off++;
3104
3105  rettv->v_type = VAR_STRING;
3106  rettv->vval.v_string = NULL;
3107
3108  if (varname != NULL && tp != NULL && win != NULL && (htname != 'b' || buf != NULL)) {
3109    // Set curwin to be our win, temporarily.  Also set the tabpage,
3110    // otherwise the window is not valid. Only do this when needed,
3111    // autocommands get blocked.
3112    // If we have a buffer reference avoid the switching, we're saving and
3113    // restoring curbuf directly.
3114    const bool need_switch_win = !(tp == curtab && win == curwin) && !do_change_curbuf;
3115    CtxSwitch switchwin;
3116    if (!need_switch_win || ctx_switch(&switchwin, win, tp, NULL, kCtxNoEvents | kCtxNoDisplay)) {
3117      if (*varname == '&' && htname != 't') {
3118        buf_T *const save_curbuf = curbuf;
3119
3120        // Change curbuf so the option is read from the correct buffer.
3121        if (do_change_curbuf) {
3122          curbuf = buf;
3123        }
3124
3125        if (varname[1] == NUL) {
3126          // get all window-local or buffer-local options in a dict
3127          dict_T *opts = get_winbuf_options(htname == 'b');
3128
3129          if (opts != NULL) {
3130            tv_dict_set_ret(rettv, opts);
3131            done = true;
3132          }
3133        } else if (eval_option(&varname, rettv, true) == OK) {
3134          // Local option
3135          done = true;
3136        }
3137
3138        curbuf = save_curbuf;
3139      } else if (*varname == NUL) {
3140        const ScopeDictDictItem *v;
3141        // Empty string: return a dict with all the local variables.
3142        if (htname == 'b') {
3143          v = &buf->b_bufvar;
3144        } else if (htname == 'w') {
3145          v = &win->w_winvar;
3146        } else {
3147          v = &tp->tp_winvar;
3148        }
3149        tv_copy(&v->di_tv, rettv);
3150        done = true;
3151      } else {
3152        hashtab_T *ht;
3153
3154        if (htname == 'b') {
3155          ht = &buf->b_vars->dv_hashtab;
3156        } else if (htname == 'w') {
3157          ht = &win->w_vars->dv_hashtab;
3158        } else {
3159          ht = &tp->tp_vars->dv_hashtab;
3160        }
3161
3162        // Look up the variable.
3163        const dictitem_T *const v = find_var_in_ht(ht, htname, varname, strlen(varname), false);
3164        if (v != NULL) {
3165          tv_copy(&v->di_tv, rettv);
3166          done = true;
3167        }
3168      }
3169    }
3170
3171    if (need_switch_win) {
3172      // restore previous notion of curwin
3173      ctx_restore(&switchwin);
3174    }
3175  }
3176
3177  if (!done && deftv->v_type != VAR_UNKNOWN) {
3178    // use the default value
3179    tv_copy(deftv, rettv);
3180  }
3181
3182  emsg_off--;
3183}
3184
3185/// getwinvar() and gettabwinvar()
3186///
3187/// @param off  1 for gettabwinvar()
3188static void getwinvar(typval_T *argvars, typval_T *rettv, int off)
3189{
3190  tabpage_T *tp;
3191
3192  if (off == 1) {
3193    tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3194  } else {
3195    tp = curtab;
3196  }
3197  win_T *const win = find_win_by_nr(&argvars[off], tp);
3198  const char *const varname = tv_get_string_chk(&argvars[off + 1]);
3199
3200  get_var_from(varname, rettv, &argvars[off + 2], 'w', tp, win, NULL);
3201}
3202
3203/// Converts a typval to a structured option value.
3204///
3205/// @param[in]   tv      typval to convert.
3206/// @param[in]   option  Option name.
3207/// @param[in]   flags   Option flags.
3208/// @param[out]  error   Whether an error occurred.
3209///
3210/// @return  Structured option, or NIL if invalid option name. Must be freed by caller.
3211static Object opt_from_tv(typval_T *tv, OptIndex opt_idx, const char *option, bool *error)
3212{
3213  Object value = NIL;
3214  char nbuf[NUMBUFLEN];
3215  bool err = false;
3216  const bool is_tty_opt = is_tty_option(option);
3217  const bool option_has_bool = !is_tty_opt && option_has_type(opt_idx, kObjectTypeBoolean);
3218  const bool option_has_num = !is_tty_opt && option_has_type(opt_idx, kObjectTypeInteger);
3219  const bool option_has_str = is_tty_opt || option_has_type(opt_idx, kObjectTypeString);
3220
3221  if (!is_tty_opt && (get_option(opt_idx)->flags & kOptFlagFunc) && tv_is_func(*tv)) {
3222    // If the option can be set to a function reference or a lambda
3223    // and the passed value is a function reference, then convert it to
3224    // the name (string) of the function reference.
3225    char *strval = encode_tv2string(tv, NULL);
3226    err = strval == NULL;
3227    value = CSTR_AS_OBJ(strval);
3228  } else if (option_has_bool || option_has_num) {
3229    varnumber_T n = option_has_num ? tv_get_number_chk(tv, &err) : tv_get_bool_chk(tv, &err);
3230    // This could be either "0" or a string that's not a number.
3231    // So we need to check if it's actually a number.
3232    if (!err && tv->v_type == VAR_STRING && n == 0) {
3233      unsigned idx;
3234      for (idx = 0; tv->vval.v_string != NULL && tv->vval.v_string[idx] == '0'; idx++) {}
3235      if (idx == 0 || tv->vval.v_string[idx] != NUL) {
3236        // There's another character after zeros or the string is empty.
3237        // In both cases, we are trying to set a num option using a string.
3238        err = true;
3239        semsg(_("E521: Number required: &%s = '%s'"), option,
3240              tv->vval.v_string == NULL ? "" : tv->vval.v_string);
3241      }
3242    }
3243    value = option_has_num ? INTEGER_OBJ((OptInt)n) : opt_from_tristate(TRISTATE_FROM_INT(n));
3244  } else if (option_has_str) {
3245    // Avoid setting string option to a boolean or a special value.
3246    if (tv->v_type != VAR_BOOL && tv->v_type != VAR_SPECIAL) {
3247      const char *strval = tv_get_string_buf_chk(tv, nbuf);
3248      err = strval == NULL;
3249      value = CSTR_TO_OBJ(strval);
3250    } else {
3251      err = true;
3252      emsg(_(e_string_required));
3253    }
3254  } else {
3255    abort();  // This should never happen.
3256  }
3257
3258  if (error != NULL) {
3259    *error = err;
3260  }
3261  return value;
3262}
3263
3264/// Converts an option value to typval. The result is independent of `value` (which is neither
3265/// consumed nor aliased): tv_clear() the result, and release `value` per its own ownership.
3266///
3267/// @param[in]  value    Option value to convert.
3268/// @param      numbool  Whether to convert boolean values to number.
3269///                      Used for backwards compatibility.
3270///
3271/// @return  Object converted to typval.
3272typval_T opt_to_tv(Object value, bool numbool)
3273{
3274  typval_T rettv = { .v_type = VAR_SPECIAL, .vval = { .v_special = kSpecialVarNull } };
3275
3276  switch (value.type) {
3277  case kObjectTypeUnset:
3278    // Legacy numbool callers (e.g. `&l:autoread` unset global-local boolean)
3279    // expect the kNone; otherwise an unset value is v:null.
3280    if (numbool) {
3281      rettv.v_type = VAR_NUMBER;
3282      rettv.vval.v_number = kNone;
3283    }
3284    break;
3285  case kObjectTypeNil:
3286    break;  // Return v:null.
3287  case kObjectTypeBoolean:
3288    if (numbool) {
3289      rettv.v_type = VAR_NUMBER;
3290      rettv.vval.v_number = value.data.boolean;
3291    } else {
3292      rettv.v_type = VAR_BOOL;
3293      rettv.vval.v_bool = value.data.boolean ? kBoolVarTrue : kBoolVarFalse;
3294    }
3295    break;
3296  case kObjectTypeInteger:
3297    rettv.v_type = VAR_NUMBER;
3298    rettv.vval.v_number = value.data.integer;
3299    break;
3300  case kObjectTypeString:
3301    rettv.v_type = VAR_STRING;
3302    rettv.vval.v_string = value.data.string.data != NULL ? xstrdup(value.data.string.data) : NULL;
3303    break;
3304  case kObjectTypeLuaRef:
3305    // Lua callback option (e.g. 'operatorfunc'): show a human-readable hint (same as `:map` does).
3306    rettv.v_type = VAR_STRING;
3307    rettv.vval.v_string = nlua_funcref_str(value.data.luaref, NULL, true);
3308    break;
3309  default:
3310    abort();  // Should never happen.
3311  }
3312
3313  return rettv;
3314}
3315
3316/// Set option "varname" to the value of "varp" for the current buffer/window.
3317static void set_option_from_tv(const char *varname, typval_T *varp)
3318{
3319  OptIndex opt_idx = find_option(varname);
3320  if (opt_idx == kOptInvalid) {
3321    semsg(_(e_unknown_option2), varname);
3322    return;
3323  }
3324
3325  bool error = false;
3326  Object value = opt_from_tv(varp, opt_idx, varname, &error);
3327
3328  if (!error) {
3329    const CharBuf errbuf = { (char[IOSIZE]){ 0 }, IOSIZE };
3330    const char *errmsg = set_option_value(opt_idx, value, OPT_LOCAL, true, &errbuf);
3331
3332    if (errmsg) {
3333      emsg(errmsg);
3334    }
3335  }
3336  optval_free(value);
3337}
3338
3339/// "setwinvar()" and "settabwinvar()" functions
3340static void setwinvar(typval_T *argvars, int off)
3341{
3342  if (check_secure()) {
3343    return;
3344  }
3345
3346  tabpage_T *tp = NULL;
3347  if (off == 1) {
3348    tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3349  } else {
3350    tp = curtab;
3351  }
3352  win_T *const win = find_win_by_nr(&argvars[off], tp);
3353  const char *varname = tv_get_string_chk(&argvars[off + 1]);
3354  typval_T *varp = &argvars[off + 2];
3355
3356  if (win == NULL || varname == NULL) {
3357    return;
3358  }
3359
3360  bool need_switch_win = !(tp == curtab && win == curwin);
3361  CtxSwitch switchwin;
3362  if (!need_switch_win || ctx_switch(&switchwin, win, tp, NULL, kCtxNoEvents | kCtxNoDisplay)) {
3363    if (*varname == '&') {
3364      set_option_from_tv(varname + 1, varp);
3365    } else {
3366      const size_t varname_len = strlen(varname);
3367      char *const winvarname = xmalloc(varname_len + 3);
3368      memcpy(winvarname, "w:", 2);
3369      memcpy(winvarname + 2, varname, varname_len + 1);
3370      set_var(winvarname, varname_len + 2, varp, true);
3371      xfree(winvarname);
3372    }
3373  }
3374  if (need_switch_win) {
3375    ctx_restore(&switchwin);
3376  }
3377}
3378
3379// reset v:option_new, v:option_old, v:option_oldlocal, v:option_oldglobal,
3380// v:option_type, and v:option_command.
3381void reset_v_option_vars(void)
3382{
3383  set_vim_var_string(VV_OPTION_NEW, NULL, -1);
3384  set_vim_var_string(VV_OPTION_OLD, NULL, -1);
3385  set_vim_var_string(VV_OPTION_OLDLOCAL, NULL, -1);
3386  set_vim_var_string(VV_OPTION_OLDGLOBAL, NULL, -1);
3387  set_vim_var_string(VV_OPTION_COMMAND, NULL, -1);
3388  set_vim_var_string(VV_OPTION_TYPE, NULL, -1);
3389}
3390
3391/// Add an assert error to v:errors.
3392void assert_error(garray_T *gap)
3393{
3394  typval_T *tv = get_vim_var_tv(VV_ERRORS);
3395
3396  if (tv->v_type != VAR_LIST || tv->vval.v_list == NULL) {
3397    // Make sure v:errors is a list.
3398    set_vim_var_list(VV_ERRORS, tv_list_alloc(1));
3399  }
3400  tv_list_append_string(get_vim_var_list(VV_ERRORS), gap->ga_data, (ptrdiff_t)gap->ga_len);
3401}
3402
3403bool var_exists(const char *var)
3404  FUNC_ATTR_NONNULL_ALL
3405{
3406  char *tofree;
3407  bool n = false;
3408
3409  // get_name_len() takes care of expanding curly braces
3410  const char *name = var;
3411  const int len = get_name_len(&var, &tofree, true, false);
3412  if (len > 0) {
3413    typval_T tv;
3414
3415    if (tofree != NULL) {
3416      name = tofree;
3417    }
3418    n = eval_variable(name, len, &tv, NULL, false, true) == OK;
3419    if (n) {
3420      // Handle d.key, l[idx], f(expr).
3421      n = handle_subscript(&var, &tv, &EVALARG_EVALUATE, false) == OK;
3422      if (n) {
3423        tv_clear(&tv);
3424      }
3425    }
3426  }
3427  if (*var != NUL) {
3428    n = false;
3429  }
3430
3431  xfree(tofree);
3432  return n;
3433}
3434
3435static lval_T *redir_lval = NULL;
3436static garray_T redir_ga;  // Only valid when redir_lval is not NULL.
3437static char *redir_endp = NULL;
3438static char *redir_varname = NULL;
3439
3440/// Start recording command output to a variable
3441///
3442/// @param append  append to an existing variable
3443///
3444/// @return  OK if successfully completed the setup.  FAIL otherwise.
3445int var_redir_start(char *name, bool append)
3446{
3447  // Catch a bad name early.
3448  if (!eval_isnamec1(*name)) {
3449    emsg(_(e_invarg));
3450    return FAIL;
3451  }
3452
3453  // Make a copy of the name, it is used in redir_lval until redir ends.
3454  redir_varname = xstrdup(name);
3455
3456  redir_lval = xcalloc(1, sizeof(lval_T));
3457
3458  // The output is stored in growarray "redir_ga" until redirection ends.
3459  ga_init(&redir_ga, (int)sizeof(char), 500);
3460
3461  // Parse the variable name (can be a dict or list entry).
3462  redir_endp = get_lval(redir_varname, NULL, redir_lval, false, false,
3463                        0, FNE_CHECK_START);
3464  if (redir_endp == NULL || redir_lval->ll_name == NULL
3465      || *redir_endp != NUL) {
3466    clear_lval(redir_lval);
3467    if (redir_endp != NULL && *redir_endp != NUL) {
3468      // Trailing characters are present after the variable name
3469      semsg(_(e_trailing_arg), redir_endp);
3470    } else {
3471      semsg(_(e_invarg2), name);
3472    }
3473    redir_endp = NULL;      // don't store a value, only cleanup
3474    var_redir_stop();
3475    return FAIL;
3476  }
3477
3478  // check if we can write to the variable: set it to or append an empty
3479  // string
3480  const int called_emsg_before = called_emsg;
3481  did_emsg = false;
3482  typval_T tv;
3483  tv.v_type = VAR_STRING;
3484  tv.vval.v_string = "";
3485  if (append) {
3486    set_var_lval(redir_lval, redir_endp, &tv, true, false, ".");
3487  } else {
3488    set_var_lval(redir_lval, redir_endp, &tv, true, false, "=");
3489  }
3490  clear_lval(redir_lval);
3491  if (called_emsg > called_emsg_before) {
3492    redir_endp = NULL;      // don't store a value, only cleanup
3493    var_redir_stop();
3494    return FAIL;
3495  }
3496
3497  return OK;
3498}
3499
3500/// Append "value[value_len]" to the variable set by var_redir_start().
3501/// The actual appending is postponed until redirection ends, because the value
3502/// appended may in fact be the string we write to, changing it may cause freed
3503/// memory to be used:
3504///   :redir => foo
3505///   :let foo
3506///   :redir END
3507void var_redir_str(const char *value, int value_len)
3508{
3509  if (redir_lval == NULL) {
3510    return;
3511  }
3512
3513  int len;
3514  if (value_len == -1) {
3515    len = (int)strlen(value);           // Append the entire string
3516  } else {
3517    len = value_len;                    // Append only "value_len" characters
3518  }
3519
3520  ga_grow(&redir_ga, len);
3521  memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, (size_t)len);
3522  redir_ga.ga_len += len;
3523}
3524
3525/// Stop redirecting command output to a variable.
3526/// Frees the allocated memory.
3527void var_redir_stop(void)
3528{
3529  if (redir_lval != NULL) {
3530    // If there was no error: assign the text to the variable.
3531    if (redir_endp != NULL) {
3532      ga_append(&redir_ga, NUL);        // Append the trailing NUL.
3533      typval_T tv;
3534      tv.v_type = VAR_STRING;
3535      tv.vval.v_string = redir_ga.ga_data;
3536      // Call get_lval() again, if it's inside a Dict or List it may
3537      // have changed.
3538      redir_endp = get_lval(redir_varname, NULL, redir_lval,
3539                            false, false, 0, FNE_CHECK_START);
3540      if (redir_endp != NULL && redir_lval->ll_name != NULL) {
3541        set_var_lval(redir_lval, redir_endp, &tv, false, false, ".");
3542      }
3543      clear_lval(redir_lval);
3544    }
3545
3546    // free the collected output
3547    XFREE_CLEAR(redir_ga.ga_data);
3548
3549    XFREE_CLEAR(redir_lval);
3550  }
3551  XFREE_CLEAR(redir_varname);
3552}
3553
3554/// "gettabvar()" function
3555void f_gettabvar(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3556{
3557  const char *const varname = tv_get_string_chk(&argvars[1]);
3558  tabpage_T *const tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3559  win_T *win = NULL;
3560
3561  if (tp != NULL) {
3562    win = tp == curtab || tp->tp_firstwin == NULL ? firstwin : tp->tp_firstwin;
3563  }
3564
3565  get_var_from(varname, rettv, &argvars[2], 't', tp, win, NULL);
3566}
3567
3568/// "gettabwinvar()" function
3569void f_gettabwinvar(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3570{
3571  getwinvar(argvars, rettv, 1);
3572}
3573
3574/// "getwinvar()" function
3575void f_getwinvar(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3576{
3577  getwinvar(argvars, rettv, 0);
3578}
3579
3580/// "getbufvar()" function
3581void f_getbufvar(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3582{
3583  const char *const varname = tv_get_string_chk(&argvars[1]);
3584  buf_T *const buf = tv_get_buf_from_arg(&argvars[0]);
3585
3586  get_var_from(varname, rettv, &argvars[2], 'b', curtab, curwin, buf);
3587}
3588
3589/// "settabvar()" function
3590void f_settabvar(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3591{
3592  if (check_secure()) {
3593    return;
3594  }
3595
3596  tabpage_T *const tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3597  const char *const varname = tv_get_string_chk(&argvars[1]);
3598  typval_T *const varp = &argvars[2];
3599
3600  if (varname == NULL || tp == NULL) {
3601    return;
3602  }
3603
3604  tabpage_T *const save_curtab = curtab;
3605  tabpage_T *const save_lu_tp = lastused_tabpage;
3606  goto_tabpage_tp(tp, false, false);
3607
3608  const size_t varname_len = strlen(varname);
3609  char *const tabvarname = xmalloc(varname_len + 3);
3610  memcpy(tabvarname, "t:", 2);
3611  memcpy(tabvarname + 2, varname, varname_len + 1);
3612  set_var(tabvarname, varname_len + 2, varp, true);
3613  xfree(tabvarname);
3614
3615  // Restore current tabpage and last accessed tabpage.
3616  if (valid_tabpage(save_curtab)) {
3617    goto_tabpage_tp(save_curtab, false, false);
3618    if (valid_tabpage(save_lu_tp)) {
3619      lastused_tabpage = save_lu_tp;
3620    }
3621  }
3622}
3623
3624/// "settabwinvar()" function
3625void f_settabwinvar(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3626{
3627  setwinvar(argvars, 1);
3628}
3629
3630/// "setwinvar()" function
3631void f_setwinvar(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3632{
3633  setwinvar(argvars, 0);
3634}
3635
3636/// "setbufvar()" function
3637void f_setbufvar(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3638{
3639  if (check_secure()
3640      || !tv_check_str_or_nr(&argvars[0])) {
3641    return;
3642  }
3643  const char *varname = tv_get_string_chk(&argvars[1]);
3644  buf_T *const buf = tv_get_buf(&argvars[0], false);
3645  typval_T *varp = &argvars[2];
3646
3647  if (buf == NULL || varname == NULL) {
3648    return;
3649  }
3650
3651  if (*varname == '&') {
3652    CtxSwitch aco = { 0 };
3653
3654    // Set curbuf to be our buf, temporarily.
3655    ctx_switch(&aco, NULL, NULL, buf, 0);
3656
3657    set_option_from_tv(varname + 1, varp);
3658
3659    // reset notion of buffer
3660    ctx_restore(&aco);
3661  } else {
3662    const size_t varname_len = strlen(varname);
3663    char *const bufvarname = xmalloc(varname_len + 3);
3664    buf_T *const save_curbuf = curbuf;
3665    curbuf = buf;
3666    memcpy(bufvarname, "b:", 2);
3667    memcpy(bufvarname + 2, varname, varname_len + 1);
3668    set_var(bufvarname, varname_len + 2, varp, true);
3669    xfree(bufvarname);
3670    curbuf = save_curbuf;
3671  }
3672}