blob: 8af80ec0afe92e1f1283ddd687744214415b2a59 [file] [log] [blame]
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * evalvars.c: functions for dealing with variables
12 */
13
14#include "vim.h"
15
16#if defined(FEAT_EVAL) || defined(PROTO)
17
Bram Moolenaare5cdf152019-08-29 22:09:46 +020018static dictitem_T globvars_var; // variable used for g:
Bram Moolenaarda6c0332019-09-01 16:01:30 +020019static dict_T globvardict; // Dictionary with g: variables
20#define globvarht globvardict.dv_hashtab
Bram Moolenaare5cdf152019-08-29 22:09:46 +020021
22/*
23 * Old Vim variables such as "v:version" are also available without the "v:".
24 * Also in functions. We need a special hashtable for them.
25 */
26static hashtab_T compat_hashtab;
27
28/*
29 * Array to hold the value of v: variables.
30 * The value is in a dictitem, so that it can also be used in the v: scope.
31 * The reason to use this table anyway is for very quick access to the
32 * variables with the VV_ defines.
33 */
34
35// values for vv_flags:
36#define VV_COMPAT 1 // compatible, also used without "v:"
37#define VV_RO 2 // read-only
38#define VV_RO_SBX 4 // read-only in the sandbox
39
40#define VV_NAME(s, t) s, {{t, 0, {0}}, 0, {0}}
41
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010042typedef struct vimvar vimvar_T;
43
Bram Moolenaare5cdf152019-08-29 22:09:46 +020044static struct vimvar
45{
46 char *vv_name; // name of variable, without v:
47 dictitem16_T vv_di; // value and name for key (max 16 chars!)
48 char vv_flags; // VV_COMPAT, VV_RO, VV_RO_SBX
49} vimvars[VV_LEN] =
50{
Bram Moolenaar8d71b542019-08-30 15:46:30 +020051 // The order here must match the VV_ defines in vim.h!
52 // Initializing a union does not work, leave tv.vval empty to get zero's.
Bram Moolenaare5cdf152019-08-29 22:09:46 +020053 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
54 {VV_NAME("count1", VAR_NUMBER), VV_RO},
55 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
56 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
57 {VV_NAME("warningmsg", VAR_STRING), 0},
58 {VV_NAME("statusmsg", VAR_STRING), 0},
59 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
60 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
61 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
62 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
63 {VV_NAME("termresponse", VAR_STRING), VV_RO},
64 {VV_NAME("fname", VAR_STRING), VV_RO},
65 {VV_NAME("lang", VAR_STRING), VV_RO},
66 {VV_NAME("lc_time", VAR_STRING), VV_RO},
67 {VV_NAME("ctype", VAR_STRING), VV_RO},
68 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
69 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
70 {VV_NAME("fname_in", VAR_STRING), VV_RO},
71 {VV_NAME("fname_out", VAR_STRING), VV_RO},
72 {VV_NAME("fname_new", VAR_STRING), VV_RO},
73 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
74 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
75 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
76 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
77 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
78 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
79 {VV_NAME("progname", VAR_STRING), VV_RO},
80 {VV_NAME("servername", VAR_STRING), VV_RO},
81 {VV_NAME("dying", VAR_NUMBER), VV_RO},
82 {VV_NAME("exception", VAR_STRING), VV_RO},
83 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
84 {VV_NAME("register", VAR_STRING), VV_RO},
85 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
86 {VV_NAME("insertmode", VAR_STRING), VV_RO},
87 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
88 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
89 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
90 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
91 {VV_NAME("fcs_choice", VAR_STRING), 0},
92 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
93 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
94 {VV_NAME("beval_winid", VAR_NUMBER), VV_RO},
95 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
96 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
97 {VV_NAME("beval_text", VAR_STRING), VV_RO},
98 {VV_NAME("scrollstart", VAR_STRING), 0},
99 {VV_NAME("swapname", VAR_STRING), VV_RO},
100 {VV_NAME("swapchoice", VAR_STRING), 0},
101 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
102 {VV_NAME("char", VAR_STRING), 0},
103 {VV_NAME("mouse_win", VAR_NUMBER), 0},
104 {VV_NAME("mouse_winid", VAR_NUMBER), 0},
105 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
106 {VV_NAME("mouse_col", VAR_NUMBER), 0},
107 {VV_NAME("operator", VAR_STRING), VV_RO},
108 {VV_NAME("searchforward", VAR_NUMBER), 0},
109 {VV_NAME("hlsearch", VAR_NUMBER), 0},
110 {VV_NAME("oldfiles", VAR_LIST), 0},
111 {VV_NAME("windowid", VAR_NUMBER), VV_RO},
112 {VV_NAME("progpath", VAR_STRING), VV_RO},
113 {VV_NAME("completed_item", VAR_DICT), VV_RO},
114 {VV_NAME("option_new", VAR_STRING), VV_RO},
115 {VV_NAME("option_old", VAR_STRING), VV_RO},
116 {VV_NAME("option_oldlocal", VAR_STRING), VV_RO},
117 {VV_NAME("option_oldglobal", VAR_STRING), VV_RO},
118 {VV_NAME("option_command", VAR_STRING), VV_RO},
119 {VV_NAME("option_type", VAR_STRING), VV_RO},
120 {VV_NAME("errors", VAR_LIST), 0},
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +0100121 {VV_NAME("false", VAR_BOOL), VV_RO},
122 {VV_NAME("true", VAR_BOOL), VV_RO},
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200123 {VV_NAME("none", VAR_SPECIAL), VV_RO},
Bram Moolenaarf9706e92020-02-22 14:27:04 +0100124 {VV_NAME("null", VAR_SPECIAL), VV_RO},
125 {VV_NAME("numbersize", VAR_NUMBER), VV_RO},
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200126 {VV_NAME("vim_did_enter", VAR_NUMBER), VV_RO},
127 {VV_NAME("testing", VAR_NUMBER), 0},
128 {VV_NAME("t_number", VAR_NUMBER), VV_RO},
129 {VV_NAME("t_string", VAR_NUMBER), VV_RO},
130 {VV_NAME("t_func", VAR_NUMBER), VV_RO},
131 {VV_NAME("t_list", VAR_NUMBER), VV_RO},
132 {VV_NAME("t_dict", VAR_NUMBER), VV_RO},
133 {VV_NAME("t_float", VAR_NUMBER), VV_RO},
134 {VV_NAME("t_bool", VAR_NUMBER), VV_RO},
135 {VV_NAME("t_none", VAR_NUMBER), VV_RO},
136 {VV_NAME("t_job", VAR_NUMBER), VV_RO},
137 {VV_NAME("t_channel", VAR_NUMBER), VV_RO},
138 {VV_NAME("t_blob", VAR_NUMBER), VV_RO},
139 {VV_NAME("termrfgresp", VAR_STRING), VV_RO},
140 {VV_NAME("termrbgresp", VAR_STRING), VV_RO},
141 {VV_NAME("termu7resp", VAR_STRING), VV_RO},
142 {VV_NAME("termstyleresp", VAR_STRING), VV_RO},
143 {VV_NAME("termblinkresp", VAR_STRING), VV_RO},
144 {VV_NAME("event", VAR_DICT), VV_RO},
145 {VV_NAME("versionlong", VAR_NUMBER), VV_RO},
146 {VV_NAME("echospace", VAR_NUMBER), VV_RO},
Bram Moolenaar69bf6342019-10-29 04:16:57 +0100147 {VV_NAME("argv", VAR_LIST), VV_RO},
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200148};
149
150// shorthand
151#define vv_type vv_di.di_tv.v_type
152#define vv_nr vv_di.di_tv.vval.v_number
153#define vv_float vv_di.di_tv.vval.v_float
154#define vv_str vv_di.di_tv.vval.v_string
155#define vv_list vv_di.di_tv.vval.v_list
156#define vv_dict vv_di.di_tv.vval.v_dict
157#define vv_blob vv_di.di_tv.vval.v_blob
158#define vv_tv vv_di.di_tv
159
160static dictitem_T vimvars_var; // variable used for v:
Bram Moolenaarda6c0332019-09-01 16:01:30 +0200161static dict_T vimvardict; // Dictionary with v: variables
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200162#define vimvarht vimvardict.dv_hashtab
163
164// for VIM_VERSION_ defines
165#include "version.h"
166
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200167static void ex_let_const(exarg_T *eap, int is_const);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100168static char_u *skip_var_one(char_u *arg, int include_type);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200169static void list_glob_vars(int *first);
170static void list_buf_vars(int *first);
171static void list_win_vars(int *first);
172static void list_tab_vars(int *first);
173static char_u *list_arg_vars(exarg_T *eap, char_u *arg, int *first);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100174static char_u *ex_let_one(char_u *arg, typval_T *tv, int copy, int flags, char_u *endchars, char_u *op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200175static void ex_unletlock(exarg_T *eap, char_u *argstart, int deep);
176static int do_unlet_var(lval_T *lp, char_u *name_end, int forceit);
177static int do_lock_var(lval_T *lp, char_u *name_end, int deep, int lock);
178static void item_lock(typval_T *tv, int deep, int lock);
Bram Moolenaarda6c0332019-09-01 16:01:30 +0200179static void delete_var(hashtab_T *ht, hashitem_T *hi);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200180static void list_one_var(dictitem_T *v, char *prefix, int *first);
181static void list_one_var_a(char *prefix, char_u *name, int type, char_u *string, int *first);
182
183/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200184 * Initialize global and vim special variables
185 */
186 void
187evalvars_init(void)
188{
189 int i;
190 struct vimvar *p;
191
192 init_var_dict(&globvardict, &globvars_var, VAR_DEF_SCOPE);
193 init_var_dict(&vimvardict, &vimvars_var, VAR_SCOPE);
194 vimvardict.dv_lock = VAR_FIXED;
195 hash_init(&compat_hashtab);
196
197 for (i = 0; i < VV_LEN; ++i)
198 {
199 p = &vimvars[i];
200 if (STRLEN(p->vv_name) > DICTITEM16_KEY_LEN)
201 {
202 iemsg("INTERNAL: name too long, increase size of dictitem16_T");
203 getout(1);
204 }
205 STRCPY(p->vv_di.di_key, p->vv_name);
206 if (p->vv_flags & VV_RO)
207 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
208 else if (p->vv_flags & VV_RO_SBX)
209 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
210 else
211 p->vv_di.di_flags = DI_FLAGS_FIX;
212
213 // add to v: scope dict, unless the value is not always available
214 if (p->vv_type != VAR_UNKNOWN)
215 hash_add(&vimvarht, p->vv_di.di_key);
216 if (p->vv_flags & VV_COMPAT)
217 // add to compat scope dict
218 hash_add(&compat_hashtab, p->vv_di.di_key);
219 }
220 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
221 vimvars[VV_VERSIONLONG].vv_nr = VIM_VERSION_100 * 10000 + highest_patch();
222
223 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
224 set_vim_var_nr(VV_HLSEARCH, 1L);
225 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
226 set_vim_var_list(VV_ERRORS, list_alloc());
227 set_vim_var_dict(VV_EVENT, dict_alloc_lock(VAR_FIXED));
228
229 set_vim_var_nr(VV_FALSE, VVAL_FALSE);
230 set_vim_var_nr(VV_TRUE, VVAL_TRUE);
231 set_vim_var_nr(VV_NONE, VVAL_NONE);
232 set_vim_var_nr(VV_NULL, VVAL_NULL);
Bram Moolenaarf9706e92020-02-22 14:27:04 +0100233 set_vim_var_nr(VV_NUMBERSIZE, sizeof(varnumber_T) * 8);
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200234
235 set_vim_var_nr(VV_TYPE_NUMBER, VAR_TYPE_NUMBER);
236 set_vim_var_nr(VV_TYPE_STRING, VAR_TYPE_STRING);
237 set_vim_var_nr(VV_TYPE_FUNC, VAR_TYPE_FUNC);
238 set_vim_var_nr(VV_TYPE_LIST, VAR_TYPE_LIST);
239 set_vim_var_nr(VV_TYPE_DICT, VAR_TYPE_DICT);
240 set_vim_var_nr(VV_TYPE_FLOAT, VAR_TYPE_FLOAT);
241 set_vim_var_nr(VV_TYPE_BOOL, VAR_TYPE_BOOL);
242 set_vim_var_nr(VV_TYPE_NONE, VAR_TYPE_NONE);
243 set_vim_var_nr(VV_TYPE_JOB, VAR_TYPE_JOB);
244 set_vim_var_nr(VV_TYPE_CHANNEL, VAR_TYPE_CHANNEL);
245 set_vim_var_nr(VV_TYPE_BLOB, VAR_TYPE_BLOB);
246
247 set_vim_var_nr(VV_ECHOSPACE, sc_col - 1);
248
249 set_reg_var(0); // default for v:register is not 0 but '"'
250}
251
252#if defined(EXITFREE) || defined(PROTO)
253/*
254 * Free all vim variables information on exit
255 */
256 void
257evalvars_clear(void)
258{
259 int i;
260 struct vimvar *p;
261
262 for (i = 0; i < VV_LEN; ++i)
263 {
264 p = &vimvars[i];
265 if (p->vv_di.di_tv.v_type == VAR_STRING)
266 VIM_CLEAR(p->vv_str);
267 else if (p->vv_di.di_tv.v_type == VAR_LIST)
268 {
269 list_unref(p->vv_list);
270 p->vv_list = NULL;
271 }
272 }
273 hash_clear(&vimvarht);
274 hash_init(&vimvarht); // garbage_collect() will access it
275 hash_clear(&compat_hashtab);
276
277 // global variables
278 vars_clear(&globvarht);
279
Bram Moolenaar7ebcba62020-01-12 17:42:55 +0100280 // Script-local variables. Clear all the variables here.
281 // The scriptvar_T is cleared later in free_scriptnames(), because a
282 // variable in one script might hold a reference to the whole scope of
283 // another script.
284 for (i = 1; i <= script_items.ga_len; ++i)
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200285 vars_clear(&SCRIPT_VARS(i));
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200286}
287#endif
288
289 int
Bram Moolenaarda6c0332019-09-01 16:01:30 +0200290garbage_collect_globvars(int copyID)
291{
292 return set_ref_in_ht(&globvarht, copyID, NULL);
293}
294
295 int
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200296garbage_collect_vimvars(int copyID)
297{
298 return set_ref_in_ht(&vimvarht, copyID, NULL);
299}
300
301 int
302garbage_collect_scriptvars(int copyID)
303{
304 int i;
305 int abort = FALSE;
306
Bram Moolenaar7ebcba62020-01-12 17:42:55 +0100307 for (i = 1; i <= script_items.ga_len; ++i)
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200308 abort = abort || set_ref_in_ht(&SCRIPT_VARS(i), copyID, NULL);
309
310 return abort;
311}
312
313/*
314 * Set an internal variable to a string value. Creates the variable if it does
315 * not already exist.
316 */
317 void
318set_internal_string_var(char_u *name, char_u *value)
319{
320 char_u *val;
321 typval_T *tvp;
322
323 val = vim_strsave(value);
324 if (val != NULL)
325 {
326 tvp = alloc_string_tv(val);
327 if (tvp != NULL)
328 {
329 set_var(name, tvp, FALSE);
330 free_tv(tvp);
331 }
332 }
333}
334
Bram Moolenaarda6c0332019-09-01 16:01:30 +0200335 int
336eval_charconvert(
337 char_u *enc_from,
338 char_u *enc_to,
339 char_u *fname_from,
340 char_u *fname_to)
341{
342 int err = FALSE;
343
344 set_vim_var_string(VV_CC_FROM, enc_from, -1);
345 set_vim_var_string(VV_CC_TO, enc_to, -1);
346 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
347 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
348 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
349 err = TRUE;
350 set_vim_var_string(VV_CC_FROM, NULL, -1);
351 set_vim_var_string(VV_CC_TO, NULL, -1);
352 set_vim_var_string(VV_FNAME_IN, NULL, -1);
353 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
354
355 if (err)
356 return FAIL;
357 return OK;
358}
359
360# if defined(FEAT_POSTSCRIPT) || defined(PROTO)
361 int
362eval_printexpr(char_u *fname, char_u *args)
363{
364 int err = FALSE;
365
366 set_vim_var_string(VV_FNAME_IN, fname, -1);
367 set_vim_var_string(VV_CMDARG, args, -1);
368 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
369 err = TRUE;
370 set_vim_var_string(VV_FNAME_IN, NULL, -1);
371 set_vim_var_string(VV_CMDARG, NULL, -1);
372
373 if (err)
374 {
375 mch_remove(fname);
376 return FAIL;
377 }
378 return OK;
379}
380# endif
381
382# if defined(FEAT_DIFF) || defined(PROTO)
383 void
384eval_diff(
385 char_u *origfile,
386 char_u *newfile,
387 char_u *outfile)
388{
389 int err = FALSE;
390
391 set_vim_var_string(VV_FNAME_IN, origfile, -1);
392 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
393 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
394 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
395 set_vim_var_string(VV_FNAME_IN, NULL, -1);
396 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
397 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
398}
399
400 void
401eval_patch(
402 char_u *origfile,
403 char_u *difffile,
404 char_u *outfile)
405{
406 int err;
407
408 set_vim_var_string(VV_FNAME_IN, origfile, -1);
409 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
410 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
411 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
412 set_vim_var_string(VV_FNAME_IN, NULL, -1);
413 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
414 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
415}
416# endif
417
418#if defined(FEAT_SPELL) || defined(PROTO)
419/*
420 * Evaluate an expression to a list with suggestions.
421 * For the "expr:" part of 'spellsuggest'.
422 * Returns NULL when there is an error.
423 */
424 list_T *
425eval_spell_expr(char_u *badword, char_u *expr)
426{
427 typval_T save_val;
428 typval_T rettv;
429 list_T *list = NULL;
430 char_u *p = skipwhite(expr);
431
432 // Set "v:val" to the bad word.
433 prepare_vimvar(VV_VAL, &save_val);
434 set_vim_var_string(VV_VAL, badword, -1);
435 if (p_verbose == 0)
436 ++emsg_off;
437
438 if (eval1(&p, &rettv, TRUE) == OK)
439 {
440 if (rettv.v_type != VAR_LIST)
441 clear_tv(&rettv);
442 else
443 list = rettv.vval.v_list;
444 }
445
446 if (p_verbose == 0)
447 --emsg_off;
448 clear_tv(get_vim_var_tv(VV_VAL));
449 restore_vimvar(VV_VAL, &save_val);
450
451 return list;
452}
453
454/*
455 * "list" is supposed to contain two items: a word and a number. Return the
456 * word in "pp" and the number as the return value.
457 * Return -1 if anything isn't right.
458 * Used to get the good word and score from the eval_spell_expr() result.
459 */
460 int
461get_spellword(list_T *list, char_u **pp)
462{
463 listitem_T *li;
464
465 li = list->lv_first;
466 if (li == NULL)
467 return -1;
468 *pp = tv_get_string(&li->li_tv);
469
470 li = li->li_next;
471 if (li == NULL)
472 return -1;
473 return (int)tv_get_number(&li->li_tv);
474}
475#endif
476
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200477/*
478 * Prepare v: variable "idx" to be used.
Bram Moolenaar27da7de2019-09-03 17:13:37 +0200479 * Save the current typeval in "save_tv" and clear it.
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200480 * When not used yet add the variable to the v: hashtable.
481 */
482 void
483prepare_vimvar(int idx, typval_T *save_tv)
484{
485 *save_tv = vimvars[idx].vv_tv;
Bram Moolenaar27da7de2019-09-03 17:13:37 +0200486 vimvars[idx].vv_str = NULL; // don't free it now
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200487 if (vimvars[idx].vv_type == VAR_UNKNOWN)
488 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
489}
490
491/*
492 * Restore v: variable "idx" to typeval "save_tv".
Bram Moolenaar27da7de2019-09-03 17:13:37 +0200493 * Note that the v: variable must have been cleared already.
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200494 * When no longer defined, remove the variable from the v: hashtable.
495 */
496 void
497restore_vimvar(int idx, typval_T *save_tv)
498{
499 hashitem_T *hi;
500
501 vimvars[idx].vv_tv = *save_tv;
502 if (vimvars[idx].vv_type == VAR_UNKNOWN)
503 {
504 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
505 if (HASHITEM_EMPTY(hi))
506 internal_error("restore_vimvar()");
507 else
508 hash_remove(&vimvarht, hi);
509 }
510}
511
512/*
513 * List Vim variables.
514 */
515 static void
516list_vim_vars(int *first)
517{
518 list_hashtable_vars(&vimvarht, "v:", FALSE, first);
519}
520
521/*
522 * List script-local variables, if there is a script.
523 */
524 static void
525list_script_vars(int *first)
526{
Bram Moolenaar7ebcba62020-01-12 17:42:55 +0100527 if (current_sctx.sc_sid > 0 && current_sctx.sc_sid <= script_items.ga_len)
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200528 list_hashtable_vars(&SCRIPT_VARS(current_sctx.sc_sid),
529 "s:", FALSE, first);
530}
531
532/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200533 * Get a list of lines from a HERE document. The here document is a list of
534 * lines surrounded by a marker.
535 * cmd << {marker}
536 * {line1}
537 * {line2}
538 * ....
539 * {marker}
540 *
541 * The {marker} is a string. If the optional 'trim' word is supplied before the
542 * marker, then the leading indentation before the lines (matching the
543 * indentation in the 'cmd' line) is stripped.
544 * Returns a List with {lines} or NULL.
545 */
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100546 list_T *
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200547heredoc_get(exarg_T *eap, char_u *cmd)
548{
549 char_u *theline;
550 char_u *marker;
551 list_T *l;
552 char_u *p;
553 int marker_indent_len = 0;
554 int text_indent_len = 0;
555 char_u *text_indent = NULL;
556
557 if (eap->getline == NULL)
558 {
559 emsg(_("E991: cannot use =<< here"));
560 return NULL;
561 }
562
563 // Check for the optional 'trim' word before the marker
564 cmd = skipwhite(cmd);
565 if (STRNCMP(cmd, "trim", 4) == 0 && (cmd[4] == NUL || VIM_ISWHITE(cmd[4])))
566 {
567 cmd = skipwhite(cmd + 4);
568
569 // Trim the indentation from all the lines in the here document.
570 // The amount of indentation trimmed is the same as the indentation of
571 // the first line after the :let command line. To find the end marker
572 // the indent of the :let command line is trimmed.
573 p = *eap->cmdlinep;
574 while (VIM_ISWHITE(*p))
575 {
576 p++;
577 marker_indent_len++;
578 }
579 text_indent_len = -1;
580 }
581
582 // The marker is the next word.
583 if (*cmd != NUL && *cmd != '"')
584 {
585 marker = skipwhite(cmd);
586 p = skiptowhite(marker);
587 if (*skipwhite(p) != NUL && *skipwhite(p) != '"')
588 {
589 emsg(_(e_trailing));
590 return NULL;
591 }
592 *p = NUL;
593 if (vim_islower(*marker))
594 {
595 emsg(_("E221: Marker cannot start with lower case letter"));
596 return NULL;
597 }
598 }
599 else
600 {
601 emsg(_("E172: Missing marker"));
602 return NULL;
603 }
604
605 l = list_alloc();
606 if (l == NULL)
607 return NULL;
608
609 for (;;)
610 {
611 int mi = 0;
612 int ti = 0;
613
614 theline = eap->getline(NUL, eap->cookie, 0, FALSE);
615 if (theline == NULL)
616 {
617 semsg(_("E990: Missing end marker '%s'"), marker);
618 break;
619 }
620
621 // with "trim": skip the indent matching the :let line to find the
622 // marker
623 if (marker_indent_len > 0
624 && STRNCMP(theline, *eap->cmdlinep, marker_indent_len) == 0)
625 mi = marker_indent_len;
626 if (STRCMP(marker, theline + mi) == 0)
627 {
628 vim_free(theline);
629 break;
630 }
631
632 if (text_indent_len == -1 && *theline != NUL)
633 {
634 // set the text indent from the first line.
635 p = theline;
636 text_indent_len = 0;
637 while (VIM_ISWHITE(*p))
638 {
639 p++;
640 text_indent_len++;
641 }
642 text_indent = vim_strnsave(theline, text_indent_len);
643 }
644 // with "trim": skip the indent matching the first line
645 if (text_indent != NULL)
646 for (ti = 0; ti < text_indent_len; ++ti)
647 if (theline[ti] != text_indent[ti])
648 break;
649
650 if (list_append_string(l, theline + ti, -1) == FAIL)
651 break;
652 vim_free(theline);
653 }
654 vim_free(text_indent);
655
656 return l;
657}
658
659/*
660 * ":let" list all variable values
661 * ":let var1 var2" list variable values
662 * ":let var = expr" assignment command.
663 * ":let var += expr" assignment command.
664 * ":let var -= expr" assignment command.
665 * ":let var *= expr" assignment command.
666 * ":let var /= expr" assignment command.
667 * ":let var %= expr" assignment command.
668 * ":let var .= expr" assignment command.
669 * ":let var ..= expr" assignment command.
670 * ":let [var1, var2] = expr" unpack list.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100671 * ":let var =<< ..." heredoc
Bram Moolenaard672dde2020-02-26 13:43:51 +0100672 * ":let var: string" Vim9 declaration
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200673 */
674 void
675ex_let(exarg_T *eap)
676{
677 ex_let_const(eap, FALSE);
678}
679
680/*
681 * ":const" list all variable values
682 * ":const var1 var2" list variable values
683 * ":const var = expr" assignment command.
684 * ":const [var1, var2] = expr" unpack list.
685 */
686 void
687ex_const(exarg_T *eap)
688{
689 ex_let_const(eap, TRUE);
690}
691
692 static void
693ex_let_const(exarg_T *eap, int is_const)
694{
695 char_u *arg = eap->arg;
696 char_u *expr = NULL;
697 typval_T rettv;
698 int i;
699 int var_count = 0;
700 int semicolon = 0;
701 char_u op[2];
702 char_u *argend;
703 int first = TRUE;
704 int concat;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100705 int flags = is_const ? LET_IS_CONST : 0;
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200706
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100707 // detect Vim9 assignment without ":let" or ":const"
708 if (eap->arg == eap->cmd)
709 flags |= LET_NO_COMMAND;
710
711 argend = skip_var_list(arg, TRUE, &var_count, &semicolon);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200712 if (argend == NULL)
713 return;
714 if (argend > arg && argend[-1] == '.') // for var.='str'
715 --argend;
716 expr = skipwhite(argend);
717 concat = expr[0] == '.'
718 && ((expr[1] == '=' && current_sctx.sc_version < 2)
719 || (expr[1] == '.' && expr[2] == '='));
720 if (*expr != '=' && !((vim_strchr((char_u *)"+-*/%", *expr) != NULL
721 && expr[1] == '=') || concat))
722 {
723 // ":let" without "=": list variables
724 if (*arg == '[')
725 emsg(_(e_invarg));
726 else if (expr[0] == '.')
727 emsg(_("E985: .= is not supported with script version 2"));
728 else if (!ends_excmd(*arg))
729 // ":let var1 var2"
730 arg = list_arg_vars(eap, arg, &first);
731 else if (!eap->skip)
732 {
733 // ":let"
734 list_glob_vars(&first);
735 list_buf_vars(&first);
736 list_win_vars(&first);
737 list_tab_vars(&first);
738 list_script_vars(&first);
739 list_func_vars(&first);
740 list_vim_vars(&first);
741 }
742 eap->nextcmd = check_nextcmd(arg);
743 }
744 else if (expr[0] == '=' && expr[1] == '<' && expr[2] == '<')
745 {
746 list_T *l;
747
748 // HERE document
749 l = heredoc_get(eap, expr + 3);
750 if (l != NULL)
751 {
752 rettv_list_set(&rettv, l);
Bram Moolenaarb1ba9ab2019-10-16 23:34:42 +0200753 if (!eap->skip)
754 {
755 op[0] = '=';
756 op[1] = NUL;
757 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100758 flags, op);
Bram Moolenaarb1ba9ab2019-10-16 23:34:42 +0200759 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200760 clear_tv(&rettv);
761 }
762 }
763 else
764 {
765 op[0] = '=';
766 op[1] = NUL;
767 if (*expr != '=')
768 {
769 if (vim_strchr((char_u *)"+-*/%.", *expr) != NULL)
770 {
771 op[0] = *expr; // +=, -=, *=, /=, %= or .=
772 if (expr[0] == '.' && expr[1] == '.') // ..=
773 ++expr;
774 }
775 expr = skipwhite(expr + 2);
776 }
777 else
778 expr = skipwhite(expr + 1);
779
780 if (eap->skip)
781 ++emsg_skip;
782 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
783 if (eap->skip)
784 {
785 if (i != FAIL)
786 clear_tv(&rettv);
787 --emsg_skip;
788 }
789 else if (i != FAIL)
790 {
791 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100792 flags, op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200793 clear_tv(&rettv);
794 }
795 }
796}
797
798/*
799 * Assign the typevalue "tv" to the variable or variables at "arg_start".
800 * Handles both "var" with any type and "[var, var; var]" with a list type.
801 * When "op" is not NULL it points to a string with characters that
802 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
803 * or concatenate.
804 * Returns OK or FAIL;
805 */
806 int
807ex_let_vars(
808 char_u *arg_start,
809 typval_T *tv,
810 int copy, // copy values from "tv", don't move
811 int semicolon, // from skip_var_list()
812 int var_count, // from skip_var_list()
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100813 int flags, // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200814 char_u *op)
815{
816 char_u *arg = arg_start;
817 list_T *l;
818 int i;
819 listitem_T *item;
820 typval_T ltv;
821
822 if (*arg != '[')
823 {
824 // ":let var = expr" or ":for var in list"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100825 if (ex_let_one(arg, tv, copy, flags, op, op) == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200826 return FAIL;
827 return OK;
828 }
829
830 // ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
831 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
832 {
833 emsg(_(e_listreq));
834 return FAIL;
835 }
836
837 i = list_len(l);
838 if (semicolon == 0 && var_count < i)
839 {
840 emsg(_("E687: Less targets than List items"));
841 return FAIL;
842 }
843 if (var_count - semicolon > i)
844 {
845 emsg(_("E688: More targets than List items"));
846 return FAIL;
847 }
848
Bram Moolenaar50985eb2020-01-27 22:09:39 +0100849 range_list_materialize(l);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200850 item = l->lv_first;
851 while (*arg != ']')
852 {
853 arg = skipwhite(arg + 1);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100854 arg = ex_let_one(arg, &item->li_tv, TRUE, flags, (char_u *)",;]", op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200855 item = item->li_next;
856 if (arg == NULL)
857 return FAIL;
858
859 arg = skipwhite(arg);
860 if (*arg == ';')
861 {
862 // Put the rest of the list (may be empty) in the var after ';'.
863 // Create a new list for this.
864 l = list_alloc();
865 if (l == NULL)
866 return FAIL;
867 while (item != NULL)
868 {
869 list_append_tv(l, &item->li_tv);
870 item = item->li_next;
871 }
872
873 ltv.v_type = VAR_LIST;
874 ltv.v_lock = 0;
875 ltv.vval.v_list = l;
876 l->lv_refcount = 1;
877
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100878 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE, flags,
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200879 (char_u *)"]", op);
880 clear_tv(&ltv);
881 if (arg == NULL)
882 return FAIL;
883 break;
884 }
885 else if (*arg != ',' && *arg != ']')
886 {
887 internal_error("ex_let_vars()");
888 return FAIL;
889 }
890 }
891
892 return OK;
893}
894
895/*
896 * Skip over assignable variable "var" or list of variables "[var, var]".
897 * Used for ":let varvar = expr" and ":for varvar in expr".
898 * For "[var, var]" increment "*var_count" for each variable.
899 * for "[var, var; var]" set "semicolon".
900 * Return NULL for an error.
901 */
902 char_u *
903skip_var_list(
904 char_u *arg,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100905 int include_type,
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200906 int *var_count,
907 int *semicolon)
908{
909 char_u *p, *s;
910
911 if (*arg == '[')
912 {
913 // "[var, var]": find the matching ']'.
914 p = arg;
915 for (;;)
916 {
917 p = skipwhite(p + 1); // skip whites after '[', ';' or ','
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100918 s = skip_var_one(p, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200919 if (s == p)
920 {
921 semsg(_(e_invarg2), p);
922 return NULL;
923 }
924 ++*var_count;
925
926 p = skipwhite(s);
927 if (*p == ']')
928 break;
929 else if (*p == ';')
930 {
931 if (*semicolon == 1)
932 {
Bram Moolenaar9be61bb2020-03-30 22:51:24 +0200933 emsg(_("E452: Double ; in list of variables"));
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200934 return NULL;
935 }
936 *semicolon = 1;
937 }
938 else if (*p != ',')
939 {
940 semsg(_(e_invarg2), p);
941 return NULL;
942 }
943 }
944 return p + 1;
945 }
946 else
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100947 return skip_var_one(arg, include_type);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200948}
949
950/*
951 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
952 * l[idx].
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100953 * In Vim9 script also skip over ": type" if "include_type" is TRUE.
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200954 */
955 static char_u *
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100956skip_var_one(char_u *arg, int include_type)
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200957{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100958 char_u *end;
959
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200960 if (*arg == '@' && arg[1] != NUL)
961 return arg + 2;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100962 end = find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200963 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100964 if (include_type && current_sctx.sc_version == SCRIPT_VERSION_VIM9
965 && *end == ':')
966 {
967 end = skip_type(skipwhite(end + 1));
968 }
969 return end;
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200970}
971
972/*
973 * List variables for hashtab "ht" with prefix "prefix".
974 * If "empty" is TRUE also list NULL strings as empty strings.
975 */
976 void
977list_hashtable_vars(
978 hashtab_T *ht,
979 char *prefix,
980 int empty,
981 int *first)
982{
983 hashitem_T *hi;
984 dictitem_T *di;
985 int todo;
986 char_u buf[IOSIZE];
987
988 todo = (int)ht->ht_used;
989 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
990 {
991 if (!HASHITEM_EMPTY(hi))
992 {
993 --todo;
994 di = HI2DI(hi);
995
996 // apply :filter /pat/ to variable name
997 vim_strncpy((char_u *)buf, (char_u *)prefix, IOSIZE - 1);
998 vim_strcat((char_u *)buf, di->di_key, IOSIZE);
999 if (message_filtered(buf))
1000 continue;
1001
1002 if (empty || di->di_tv.v_type != VAR_STRING
1003 || di->di_tv.vval.v_string != NULL)
1004 list_one_var(di, prefix, first);
1005 }
1006 }
1007}
1008
1009/*
1010 * List global variables.
1011 */
1012 static void
1013list_glob_vars(int *first)
1014{
1015 list_hashtable_vars(&globvarht, "", TRUE, first);
1016}
1017
1018/*
1019 * List buffer variables.
1020 */
1021 static void
1022list_buf_vars(int *first)
1023{
1024 list_hashtable_vars(&curbuf->b_vars->dv_hashtab, "b:", TRUE, first);
1025}
1026
1027/*
1028 * List window variables.
1029 */
1030 static void
1031list_win_vars(int *first)
1032{
1033 list_hashtable_vars(&curwin->w_vars->dv_hashtab, "w:", TRUE, first);
1034}
1035
1036/*
1037 * List tab page variables.
1038 */
1039 static void
1040list_tab_vars(int *first)
1041{
1042 list_hashtable_vars(&curtab->tp_vars->dv_hashtab, "t:", TRUE, first);
1043}
1044
1045/*
1046 * List variables in "arg".
1047 */
1048 static char_u *
1049list_arg_vars(exarg_T *eap, char_u *arg, int *first)
1050{
1051 int error = FALSE;
1052 int len;
1053 char_u *name;
1054 char_u *name_start;
1055 char_u *arg_subsc;
1056 char_u *tofree;
1057 typval_T tv;
1058
1059 while (!ends_excmd(*arg) && !got_int)
1060 {
1061 if (error || eap->skip)
1062 {
1063 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1064 if (!VIM_ISWHITE(*arg) && !ends_excmd(*arg))
1065 {
1066 emsg_severe = TRUE;
1067 emsg(_(e_trailing));
1068 break;
1069 }
1070 }
1071 else
1072 {
1073 // get_name_len() takes care of expanding curly braces
1074 name_start = name = arg;
1075 len = get_name_len(&arg, &tofree, TRUE, TRUE);
1076 if (len <= 0)
1077 {
1078 // This is mainly to keep test 49 working: when expanding
1079 // curly braces fails overrule the exception error message.
1080 if (len < 0 && !aborting())
1081 {
1082 emsg_severe = TRUE;
1083 semsg(_(e_invarg2), arg);
1084 break;
1085 }
1086 error = TRUE;
1087 }
1088 else
1089 {
1090 if (tofree != NULL)
1091 name = tofree;
1092 if (get_var_tv(name, len, &tv, NULL, TRUE, FALSE) == FAIL)
1093 error = TRUE;
1094 else
1095 {
1096 // handle d.key, l[idx], f(expr)
1097 arg_subsc = arg;
1098 if (handle_subscript(&arg, &tv, TRUE, TRUE,
1099 name, &name) == FAIL)
1100 error = TRUE;
1101 else
1102 {
1103 if (arg == arg_subsc && len == 2 && name[1] == ':')
1104 {
1105 switch (*name)
1106 {
1107 case 'g': list_glob_vars(first); break;
1108 case 'b': list_buf_vars(first); break;
1109 case 'w': list_win_vars(first); break;
1110 case 't': list_tab_vars(first); break;
1111 case 'v': list_vim_vars(first); break;
1112 case 's': list_script_vars(first); break;
1113 case 'l': list_func_vars(first); break;
1114 default:
1115 semsg(_("E738: Can't list variables for %s"), name);
1116 }
1117 }
1118 else
1119 {
1120 char_u numbuf[NUMBUFLEN];
1121 char_u *tf;
1122 int c;
1123 char_u *s;
1124
1125 s = echo_string(&tv, &tf, numbuf, 0);
1126 c = *arg;
1127 *arg = NUL;
1128 list_one_var_a("",
1129 arg == arg_subsc ? name : name_start,
1130 tv.v_type,
1131 s == NULL ? (char_u *)"" : s,
1132 first);
1133 *arg = c;
1134 vim_free(tf);
1135 }
1136 clear_tv(&tv);
1137 }
1138 }
1139 }
1140
1141 vim_free(tofree);
1142 }
1143
1144 arg = skipwhite(arg);
1145 }
1146
1147 return arg;
1148}
1149
1150/*
1151 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
1152 * Returns a pointer to the char just after the var name.
1153 * Returns NULL if there is an error.
1154 */
1155 static char_u *
1156ex_let_one(
1157 char_u *arg, // points to variable name
1158 typval_T *tv, // value to assign to variable
1159 int copy, // copy value from "tv"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001160 int flags, // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001161 char_u *endchars, // valid chars after variable name or NULL
1162 char_u *op) // "+", "-", "." or NULL
1163{
1164 int c1;
1165 char_u *name;
1166 char_u *p;
1167 char_u *arg_end = NULL;
1168 int len;
1169 int opt_flags;
1170 char_u *tofree = NULL;
1171
1172 // ":let $VAR = expr": Set environment variable.
1173 if (*arg == '$')
1174 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001175 if (flags & LET_IS_CONST)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001176 {
1177 emsg(_("E996: Cannot lock an environment variable"));
1178 return NULL;
1179 }
1180 // Find the end of the name.
1181 ++arg;
1182 name = arg;
1183 len = get_env_len(&arg);
1184 if (len == 0)
1185 semsg(_(e_invarg2), name - 1);
1186 else
1187 {
1188 if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL)
1189 semsg(_(e_letwrong), op);
1190 else if (endchars != NULL
1191 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
1192 emsg(_(e_letunexp));
1193 else if (!check_secure())
1194 {
1195 c1 = name[len];
1196 name[len] = NUL;
1197 p = tv_get_string_chk(tv);
1198 if (p != NULL && op != NULL && *op == '.')
1199 {
1200 int mustfree = FALSE;
1201 char_u *s = vim_getenv(name, &mustfree);
1202
1203 if (s != NULL)
1204 {
1205 p = tofree = concat_str(s, p);
1206 if (mustfree)
1207 vim_free(s);
1208 }
1209 }
1210 if (p != NULL)
1211 {
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01001212 vim_setenv_ext(name, p);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001213 arg_end = arg;
1214 }
1215 name[len] = c1;
1216 vim_free(tofree);
1217 }
1218 }
1219 }
1220
1221 // ":let &option = expr": Set option value.
1222 // ":let &l:option = expr": Set local option value.
1223 // ":let &g:option = expr": Set global option value.
1224 else if (*arg == '&')
1225 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001226 if (flags & LET_IS_CONST)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001227 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001228 emsg(_(e_const_option));
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001229 return NULL;
1230 }
1231 // Find the end of the name.
1232 p = find_option_end(&arg, &opt_flags);
1233 if (p == NULL || (endchars != NULL
1234 && vim_strchr(endchars, *skipwhite(p)) == NULL))
1235 emsg(_(e_letunexp));
1236 else
1237 {
1238 long n;
1239 int opt_type;
1240 long numval;
1241 char_u *stringval = NULL;
1242 char_u *s;
1243
1244 c1 = *p;
1245 *p = NUL;
1246
1247 n = (long)tv_get_number(tv);
1248 s = tv_get_string_chk(tv); // != NULL if number or string
1249 if (s != NULL && op != NULL && *op != '=')
1250 {
1251 opt_type = get_option_value(arg, &numval,
1252 &stringval, opt_flags);
1253 if ((opt_type == 1 && *op == '.')
1254 || (opt_type == 0 && *op != '.'))
1255 {
1256 semsg(_(e_letwrong), op);
1257 s = NULL; // don't set the value
1258 }
1259 else
1260 {
1261 if (opt_type == 1) // number
1262 {
1263 switch (*op)
1264 {
1265 case '+': n = numval + n; break;
1266 case '-': n = numval - n; break;
1267 case '*': n = numval * n; break;
1268 case '/': n = (long)num_divide(numval, n); break;
1269 case '%': n = (long)num_modulus(numval, n); break;
1270 }
1271 }
1272 else if (opt_type == 0 && stringval != NULL) // string
1273 {
1274 s = concat_str(stringval, s);
1275 vim_free(stringval);
1276 stringval = s;
1277 }
1278 }
1279 }
1280 if (s != NULL)
1281 {
1282 set_option_value(arg, n, s, opt_flags);
1283 arg_end = p;
1284 }
1285 *p = c1;
1286 vim_free(stringval);
1287 }
1288 }
1289
1290 // ":let @r = expr": Set register contents.
1291 else if (*arg == '@')
1292 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001293 if (flags & LET_IS_CONST)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001294 {
1295 emsg(_("E996: Cannot lock a register"));
1296 return NULL;
1297 }
1298 ++arg;
1299 if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL)
1300 semsg(_(e_letwrong), op);
1301 else if (endchars != NULL
1302 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
1303 emsg(_(e_letunexp));
1304 else
1305 {
1306 char_u *ptofree = NULL;
1307 char_u *s;
1308
1309 p = tv_get_string_chk(tv);
1310 if (p != NULL && op != NULL && *op == '.')
1311 {
1312 s = get_reg_contents(*arg == '@' ? '"' : *arg, GREG_EXPR_SRC);
1313 if (s != NULL)
1314 {
1315 p = ptofree = concat_str(s, p);
1316 vim_free(s);
1317 }
1318 }
1319 if (p != NULL)
1320 {
1321 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
1322 arg_end = arg + 1;
1323 }
1324 vim_free(ptofree);
1325 }
1326 }
1327
1328 // ":let var = expr": Set internal variable.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001329 // ":let var: type = expr": Set internal variable with type.
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001330 // ":let {expr} = expr": Idem, name made with curly braces
1331 else if (eval_isnamec1(*arg) || *arg == '{')
1332 {
1333 lval_T lv;
1334
1335 p = get_lval(arg, tv, &lv, FALSE, FALSE, 0, FNE_CHECK_START);
1336 if (p != NULL && lv.ll_name != NULL)
1337 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001338 if (endchars != NULL && vim_strchr(endchars,
1339 *skipwhite(lv.ll_name_end)) == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001340 emsg(_(e_letunexp));
1341 else
1342 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001343 set_var_lval(&lv, p, tv, copy, flags, op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001344 arg_end = p;
1345 }
1346 }
1347 clear_lval(&lv);
1348 }
1349
1350 else
1351 semsg(_(e_invarg2), arg);
1352
1353 return arg_end;
1354}
1355
1356/*
1357 * ":unlet[!] var1 ... " command.
1358 */
1359 void
1360ex_unlet(exarg_T *eap)
1361{
1362 ex_unletlock(eap, eap->arg, 0);
1363}
1364
1365/*
1366 * ":lockvar" and ":unlockvar" commands
1367 */
1368 void
1369ex_lockvar(exarg_T *eap)
1370{
1371 char_u *arg = eap->arg;
1372 int deep = 2;
1373
1374 if (eap->forceit)
1375 deep = -1;
1376 else if (vim_isdigit(*arg))
1377 {
1378 deep = getdigits(&arg);
1379 arg = skipwhite(arg);
1380 }
1381
1382 ex_unletlock(eap, arg, deep);
1383}
1384
1385/*
1386 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
1387 */
1388 static void
1389ex_unletlock(
1390 exarg_T *eap,
1391 char_u *argstart,
1392 int deep)
1393{
1394 char_u *arg = argstart;
1395 char_u *name_end;
1396 int error = FALSE;
1397 lval_T lv;
1398
1399 do
1400 {
1401 if (*arg == '$')
1402 {
1403 char_u *name = ++arg;
1404
1405 if (get_env_len(&arg) == 0)
1406 {
1407 semsg(_(e_invarg2), name - 1);
1408 return;
1409 }
1410 vim_unsetenv(name);
1411 arg = skipwhite(arg);
1412 continue;
1413 }
1414
1415 // Parse the name and find the end.
1416 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, 0,
1417 FNE_CHECK_START);
1418 if (lv.ll_name == NULL)
1419 error = TRUE; // error but continue parsing
1420 if (name_end == NULL || (!VIM_ISWHITE(*name_end)
1421 && !ends_excmd(*name_end)))
1422 {
1423 if (name_end != NULL)
1424 {
1425 emsg_severe = TRUE;
1426 emsg(_(e_trailing));
1427 }
1428 if (!(eap->skip || error))
1429 clear_lval(&lv);
1430 break;
1431 }
1432
1433 if (!error && !eap->skip)
1434 {
1435 if (eap->cmdidx == CMD_unlet)
1436 {
1437 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
1438 error = TRUE;
1439 }
1440 else
1441 {
1442 if (do_lock_var(&lv, name_end, deep,
1443 eap->cmdidx == CMD_lockvar) == FAIL)
1444 error = TRUE;
1445 }
1446 }
1447
1448 if (!eap->skip)
1449 clear_lval(&lv);
1450
1451 arg = skipwhite(name_end);
1452 } while (!ends_excmd(*arg));
1453
1454 eap->nextcmd = check_nextcmd(arg);
1455}
1456
1457 static int
1458do_unlet_var(
1459 lval_T *lp,
1460 char_u *name_end,
1461 int forceit)
1462{
1463 int ret = OK;
1464 int cc;
1465
1466 if (lp->ll_tv == NULL)
1467 {
1468 cc = *name_end;
1469 *name_end = NUL;
1470
1471 // Normal name or expanded name.
1472 if (do_unlet(lp->ll_name, forceit) == FAIL)
1473 ret = FAIL;
1474 *name_end = cc;
1475 }
1476 else if ((lp->ll_list != NULL
1477 && var_check_lock(lp->ll_list->lv_lock, lp->ll_name, FALSE))
1478 || (lp->ll_dict != NULL
1479 && var_check_lock(lp->ll_dict->dv_lock, lp->ll_name, FALSE)))
1480 return FAIL;
1481 else if (lp->ll_range)
1482 {
1483 listitem_T *li;
1484 listitem_T *ll_li = lp->ll_li;
1485 int ll_n1 = lp->ll_n1;
1486
1487 while (ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= ll_n1))
1488 {
1489 li = ll_li->li_next;
1490 if (var_check_lock(ll_li->li_tv.v_lock, lp->ll_name, FALSE))
1491 return FAIL;
1492 ll_li = li;
1493 ++ll_n1;
1494 }
1495
1496 // Delete a range of List items.
1497 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
1498 {
1499 li = lp->ll_li->li_next;
1500 listitem_remove(lp->ll_list, lp->ll_li);
1501 lp->ll_li = li;
1502 ++lp->ll_n1;
1503 }
1504 }
1505 else
1506 {
1507 if (lp->ll_list != NULL)
1508 // unlet a List item.
1509 listitem_remove(lp->ll_list, lp->ll_li);
1510 else
1511 // unlet a Dictionary item.
1512 dictitem_remove(lp->ll_dict, lp->ll_di);
1513 }
1514
1515 return ret;
1516}
1517
1518/*
1519 * "unlet" a variable. Return OK if it existed, FAIL if not.
1520 * When "forceit" is TRUE don't complain if the variable doesn't exist.
1521 */
1522 int
1523do_unlet(char_u *name, int forceit)
1524{
1525 hashtab_T *ht;
1526 hashitem_T *hi;
1527 char_u *varname;
1528 dict_T *d;
1529 dictitem_T *di;
1530
1531 ht = find_var_ht(name, &varname);
1532 if (ht != NULL && *varname != NUL)
1533 {
1534 d = get_current_funccal_dict(ht);
1535 if (d == NULL)
1536 {
1537 if (ht == &globvarht)
1538 d = &globvardict;
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001539 else if (ht == &compat_hashtab)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001540 d = &vimvardict;
1541 else
1542 {
1543 di = find_var_in_ht(ht, *name, (char_u *)"", FALSE);
1544 d = di == NULL ? NULL : di->di_tv.vval.v_dict;
1545 }
1546 if (d == NULL)
1547 {
1548 internal_error("do_unlet()");
1549 return FAIL;
1550 }
1551 }
1552 hi = hash_find(ht, varname);
1553 if (HASHITEM_EMPTY(hi))
1554 hi = find_hi_in_scoped_ht(name, &ht);
1555 if (hi != NULL && !HASHITEM_EMPTY(hi))
1556 {
1557 di = HI2DI(hi);
1558 if (var_check_fixed(di->di_flags, name, FALSE)
1559 || var_check_ro(di->di_flags, name, FALSE)
1560 || var_check_lock(d->dv_lock, name, FALSE))
1561 return FAIL;
1562
1563 delete_var(ht, hi);
1564 return OK;
1565 }
1566 }
1567 if (forceit)
1568 return OK;
1569 semsg(_("E108: No such variable: \"%s\""), name);
1570 return FAIL;
1571}
1572
1573/*
1574 * Lock or unlock variable indicated by "lp".
1575 * "deep" is the levels to go (-1 for unlimited);
1576 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
1577 */
1578 static int
1579do_lock_var(
1580 lval_T *lp,
1581 char_u *name_end,
1582 int deep,
1583 int lock)
1584{
1585 int ret = OK;
1586 int cc;
1587 dictitem_T *di;
1588
1589 if (deep == 0) // nothing to do
1590 return OK;
1591
1592 if (lp->ll_tv == NULL)
1593 {
1594 cc = *name_end;
1595 *name_end = NUL;
1596
1597 // Normal name or expanded name.
1598 di = find_var(lp->ll_name, NULL, TRUE);
1599 if (di == NULL)
1600 ret = FAIL;
1601 else if ((di->di_flags & DI_FLAGS_FIX)
1602 && di->di_tv.v_type != VAR_DICT
1603 && di->di_tv.v_type != VAR_LIST)
1604 // For historic reasons this error is not given for a list or dict.
1605 // E.g., the b: dict could be locked/unlocked.
1606 semsg(_("E940: Cannot lock or unlock variable %s"), lp->ll_name);
1607 else
1608 {
1609 if (lock)
1610 di->di_flags |= DI_FLAGS_LOCK;
1611 else
1612 di->di_flags &= ~DI_FLAGS_LOCK;
1613 item_lock(&di->di_tv, deep, lock);
1614 }
1615 *name_end = cc;
1616 }
1617 else if (lp->ll_range)
1618 {
1619 listitem_T *li = lp->ll_li;
1620
1621 // (un)lock a range of List items.
1622 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
1623 {
1624 item_lock(&li->li_tv, deep, lock);
1625 li = li->li_next;
1626 ++lp->ll_n1;
1627 }
1628 }
1629 else if (lp->ll_list != NULL)
1630 // (un)lock a List item.
1631 item_lock(&lp->ll_li->li_tv, deep, lock);
1632 else
1633 // (un)lock a Dictionary item.
1634 item_lock(&lp->ll_di->di_tv, deep, lock);
1635
1636 return ret;
1637}
1638
1639/*
1640 * Lock or unlock an item. "deep" is nr of levels to go.
1641 */
1642 static void
1643item_lock(typval_T *tv, int deep, int lock)
1644{
1645 static int recurse = 0;
1646 list_T *l;
1647 listitem_T *li;
1648 dict_T *d;
1649 blob_T *b;
1650 hashitem_T *hi;
1651 int todo;
1652
1653 if (recurse >= DICT_MAXNEST)
1654 {
1655 emsg(_("E743: variable nested too deep for (un)lock"));
1656 return;
1657 }
1658 if (deep == 0)
1659 return;
1660 ++recurse;
1661
1662 // lock/unlock the item itself
1663 if (lock)
1664 tv->v_lock |= VAR_LOCKED;
1665 else
1666 tv->v_lock &= ~VAR_LOCKED;
1667
1668 switch (tv->v_type)
1669 {
1670 case VAR_UNKNOWN:
Bram Moolenaar4c683752020-04-05 21:38:23 +02001671 case VAR_ANY:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001672 case VAR_VOID:
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001673 case VAR_NUMBER:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001674 case VAR_BOOL:
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001675 case VAR_STRING:
1676 case VAR_FUNC:
1677 case VAR_PARTIAL:
1678 case VAR_FLOAT:
1679 case VAR_SPECIAL:
1680 case VAR_JOB:
1681 case VAR_CHANNEL:
1682 break;
1683
1684 case VAR_BLOB:
1685 if ((b = tv->vval.v_blob) != NULL)
1686 {
1687 if (lock)
1688 b->bv_lock |= VAR_LOCKED;
1689 else
1690 b->bv_lock &= ~VAR_LOCKED;
1691 }
1692 break;
1693 case VAR_LIST:
1694 if ((l = tv->vval.v_list) != NULL)
1695 {
1696 if (lock)
1697 l->lv_lock |= VAR_LOCKED;
1698 else
1699 l->lv_lock &= ~VAR_LOCKED;
Bram Moolenaar50985eb2020-01-27 22:09:39 +01001700 if ((deep < 0 || deep > 1) && l->lv_first != &range_list_item)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001701 // recursive: lock/unlock the items the List contains
Bram Moolenaaraeea7212020-04-02 18:50:46 +02001702 FOR_ALL_LIST_ITEMS(l, li)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001703 item_lock(&li->li_tv, deep - 1, lock);
1704 }
1705 break;
1706 case VAR_DICT:
1707 if ((d = tv->vval.v_dict) != NULL)
1708 {
1709 if (lock)
1710 d->dv_lock |= VAR_LOCKED;
1711 else
1712 d->dv_lock &= ~VAR_LOCKED;
1713 if (deep < 0 || deep > 1)
1714 {
1715 // recursive: lock/unlock the items the List contains
1716 todo = (int)d->dv_hashtab.ht_used;
1717 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
1718 {
1719 if (!HASHITEM_EMPTY(hi))
1720 {
1721 --todo;
1722 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
1723 }
1724 }
1725 }
1726 }
1727 }
1728 --recurse;
1729}
1730
Bram Moolenaarda6c0332019-09-01 16:01:30 +02001731#if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
1732/*
1733 * Delete all "menutrans_" variables.
1734 */
1735 void
1736del_menutrans_vars(void)
1737{
1738 hashitem_T *hi;
1739 int todo;
1740
1741 hash_lock(&globvarht);
1742 todo = (int)globvarht.ht_used;
1743 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
1744 {
1745 if (!HASHITEM_EMPTY(hi))
1746 {
1747 --todo;
1748 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
1749 delete_var(&globvarht, hi);
1750 }
1751 }
1752 hash_unlock(&globvarht);
1753}
1754#endif
1755
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001756/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001757 * Local string buffer for the next two functions to store a variable name
1758 * with its prefix. Allocated in cat_prefix_varname(), freed later in
1759 * get_user_var_name().
1760 */
1761
1762static char_u *varnamebuf = NULL;
1763static int varnamebuflen = 0;
1764
1765/*
1766 * Function to concatenate a prefix and a variable name.
1767 */
1768 static char_u *
1769cat_prefix_varname(int prefix, char_u *name)
1770{
1771 int len;
1772
1773 len = (int)STRLEN(name) + 3;
1774 if (len > varnamebuflen)
1775 {
1776 vim_free(varnamebuf);
Bram Moolenaar8d71b542019-08-30 15:46:30 +02001777 len += 10; // some additional space
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001778 varnamebuf = alloc(len);
1779 if (varnamebuf == NULL)
1780 {
1781 varnamebuflen = 0;
1782 return NULL;
1783 }
1784 varnamebuflen = len;
1785 }
1786 *varnamebuf = prefix;
1787 varnamebuf[1] = ':';
1788 STRCPY(varnamebuf + 2, name);
1789 return varnamebuf;
1790}
1791
1792/*
1793 * Function given to ExpandGeneric() to obtain the list of user defined
1794 * (global/buffer/window/built-in) variable names.
1795 */
1796 char_u *
1797get_user_var_name(expand_T *xp, int idx)
1798{
1799 static long_u gdone;
1800 static long_u bdone;
1801 static long_u wdone;
1802 static long_u tdone;
1803 static int vidx;
1804 static hashitem_T *hi;
1805 hashtab_T *ht;
1806
1807 if (idx == 0)
1808 {
1809 gdone = bdone = wdone = vidx = 0;
1810 tdone = 0;
1811 }
1812
1813 // Global variables
1814 if (gdone < globvarht.ht_used)
1815 {
1816 if (gdone++ == 0)
1817 hi = globvarht.ht_array;
1818 else
1819 ++hi;
1820 while (HASHITEM_EMPTY(hi))
1821 ++hi;
1822 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
1823 return cat_prefix_varname('g', hi->hi_key);
1824 return hi->hi_key;
1825 }
1826
1827 // b: variables
1828 ht = &curbuf->b_vars->dv_hashtab;
1829 if (bdone < ht->ht_used)
1830 {
1831 if (bdone++ == 0)
1832 hi = ht->ht_array;
1833 else
1834 ++hi;
1835 while (HASHITEM_EMPTY(hi))
1836 ++hi;
1837 return cat_prefix_varname('b', hi->hi_key);
1838 }
1839
1840 // w: variables
1841 ht = &curwin->w_vars->dv_hashtab;
1842 if (wdone < ht->ht_used)
1843 {
1844 if (wdone++ == 0)
1845 hi = ht->ht_array;
1846 else
1847 ++hi;
1848 while (HASHITEM_EMPTY(hi))
1849 ++hi;
1850 return cat_prefix_varname('w', hi->hi_key);
1851 }
1852
1853 // t: variables
1854 ht = &curtab->tp_vars->dv_hashtab;
1855 if (tdone < ht->ht_used)
1856 {
1857 if (tdone++ == 0)
1858 hi = ht->ht_array;
1859 else
1860 ++hi;
1861 while (HASHITEM_EMPTY(hi))
1862 ++hi;
1863 return cat_prefix_varname('t', hi->hi_key);
1864 }
1865
1866 // v: variables
1867 if (vidx < VV_LEN)
1868 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
1869
1870 VIM_CLEAR(varnamebuf);
1871 varnamebuflen = 0;
1872 return NULL;
1873}
1874
Bram Moolenaarda6c0332019-09-01 16:01:30 +02001875 char *
1876get_var_special_name(int nr)
1877{
1878 switch (nr)
1879 {
1880 case VVAL_FALSE: return "v:false";
1881 case VVAL_TRUE: return "v:true";
1882 case VVAL_NONE: return "v:none";
1883 case VVAL_NULL: return "v:null";
1884 }
1885 internal_error("get_var_special_name()");
1886 return "42";
1887}
1888
1889/*
1890 * Returns the global variable dictionary
1891 */
1892 dict_T *
1893get_globvar_dict(void)
1894{
1895 return &globvardict;
1896}
1897
1898/*
1899 * Returns the global variable hash table
1900 */
1901 hashtab_T *
1902get_globvar_ht(void)
1903{
1904 return &globvarht;
1905}
1906
1907/*
1908 * Returns the v: variable dictionary
1909 */
1910 dict_T *
1911get_vimvar_dict(void)
1912{
1913 return &vimvardict;
1914}
1915
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001916/*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001917 * Returns the index of a v:variable. Negative if not found.
Bram Moolenaar5da356e2020-04-09 19:34:43 +02001918 * Returns DI_ flags in "di_flags".
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001919 */
1920 int
Bram Moolenaar5da356e2020-04-09 19:34:43 +02001921find_vim_var(char_u *name, int *di_flags)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001922{
Bram Moolenaar5da356e2020-04-09 19:34:43 +02001923 dictitem_T *di = find_var_in_ht(&vimvarht, 0, name, TRUE);
1924 struct vimvar *vv;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001925
1926 if (di == NULL)
1927 return -1;
Bram Moolenaar5da356e2020-04-09 19:34:43 +02001928 *di_flags = di->di_flags;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001929 vv = (struct vimvar *)((char *)di - offsetof(vimvar_T, vv_di));
1930 return (int)(vv - vimvars);
1931}
1932
1933
1934/*
Bram Moolenaar34ed68d2019-08-29 22:48:24 +02001935 * Set type of v: variable to "type".
1936 */
1937 void
1938set_vim_var_type(int idx, vartype_T type)
1939{
1940 vimvars[idx].vv_type = type;
1941}
1942
1943/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001944 * Set number v: variable to "val".
Bram Moolenaar8d71b542019-08-30 15:46:30 +02001945 * Note that this does not set the type, use set_vim_var_type() for that.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001946 */
1947 void
1948set_vim_var_nr(int idx, varnumber_T val)
1949{
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001950 vimvars[idx].vv_nr = val;
1951}
1952
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001953 char *
1954get_vim_var_name(int idx)
1955{
1956 return vimvars[idx].vv_name;
1957}
1958
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001959/*
1960 * Get typval_T v: variable value.
1961 */
1962 typval_T *
1963get_vim_var_tv(int idx)
1964{
1965 return &vimvars[idx].vv_tv;
1966}
1967
1968/*
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01001969 * Set v: variable to "tv". Only accepts the same type.
1970 * Takes over the value of "tv".
1971 */
1972 int
1973set_vim_var_tv(int idx, typval_T *tv)
1974{
1975 if (vimvars[idx].vv_type != tv->v_type)
1976 {
1977 emsg(_("E1063: type mismatch for v: variable"));
1978 clear_tv(tv);
1979 return FAIL;
1980 }
1981 clear_tv(&vimvars[idx].vv_di.di_tv);
1982 vimvars[idx].vv_di.di_tv = *tv;
1983 return OK;
1984}
1985
1986/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001987 * Get number v: variable value.
1988 */
1989 varnumber_T
1990get_vim_var_nr(int idx)
1991{
1992 return vimvars[idx].vv_nr;
1993}
1994
1995/*
1996 * Get string v: variable value. Uses a static buffer, can only be used once.
1997 * If the String variable has never been set, return an empty string.
1998 * Never returns NULL;
1999 */
2000 char_u *
2001get_vim_var_str(int idx)
2002{
2003 return tv_get_string(&vimvars[idx].vv_tv);
2004}
2005
2006/*
2007 * Get List v: variable value. Caller must take care of reference count when
2008 * needed.
2009 */
2010 list_T *
2011get_vim_var_list(int idx)
2012{
2013 return vimvars[idx].vv_list;
2014}
2015
2016/*
2017 * Get Dict v: variable value. Caller must take care of reference count when
2018 * needed.
2019 */
2020 dict_T *
2021get_vim_var_dict(int idx)
2022{
2023 return vimvars[idx].vv_dict;
2024}
2025
2026/*
2027 * Set v:char to character "c".
2028 */
2029 void
2030set_vim_var_char(int c)
2031{
2032 char_u buf[MB_MAXBYTES + 1];
2033
2034 if (has_mbyte)
2035 buf[(*mb_char2bytes)(c, buf)] = NUL;
2036 else
2037 {
2038 buf[0] = c;
2039 buf[1] = NUL;
2040 }
2041 set_vim_var_string(VV_CHAR, buf, -1);
2042}
2043
2044/*
2045 * Set v:count to "count" and v:count1 to "count1".
2046 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
2047 */
2048 void
2049set_vcount(
2050 long count,
2051 long count1,
2052 int set_prevcount)
2053{
2054 if (set_prevcount)
2055 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
2056 vimvars[VV_COUNT].vv_nr = count;
2057 vimvars[VV_COUNT1].vv_nr = count1;
2058}
2059
2060/*
2061 * Save variables that might be changed as a side effect. Used when executing
2062 * a timer callback.
2063 */
2064 void
2065save_vimvars(vimvars_save_T *vvsave)
2066{
2067 vvsave->vv_prevcount = vimvars[VV_PREVCOUNT].vv_nr;
2068 vvsave->vv_count = vimvars[VV_COUNT].vv_nr;
2069 vvsave->vv_count1 = vimvars[VV_COUNT1].vv_nr;
2070}
2071
2072/*
2073 * Restore variables saved by save_vimvars().
2074 */
2075 void
2076restore_vimvars(vimvars_save_T *vvsave)
2077{
2078 vimvars[VV_PREVCOUNT].vv_nr = vvsave->vv_prevcount;
2079 vimvars[VV_COUNT].vv_nr = vvsave->vv_count;
2080 vimvars[VV_COUNT1].vv_nr = vvsave->vv_count1;
2081}
2082
2083/*
2084 * Set string v: variable to a copy of "val". If 'copy' is FALSE, then set the
2085 * value.
2086 */
2087 void
2088set_vim_var_string(
2089 int idx,
2090 char_u *val,
2091 int len) // length of "val" to use or -1 (whole string)
2092{
2093 clear_tv(&vimvars[idx].vv_di.di_tv);
2094 vimvars[idx].vv_type = VAR_STRING;
2095 if (val == NULL)
2096 vimvars[idx].vv_str = NULL;
2097 else if (len == -1)
2098 vimvars[idx].vv_str = vim_strsave(val);
2099 else
2100 vimvars[idx].vv_str = vim_strnsave(val, len);
2101}
2102
2103/*
2104 * Set List v: variable to "val".
2105 */
2106 void
2107set_vim_var_list(int idx, list_T *val)
2108{
2109 clear_tv(&vimvars[idx].vv_di.di_tv);
2110 vimvars[idx].vv_type = VAR_LIST;
2111 vimvars[idx].vv_list = val;
2112 if (val != NULL)
2113 ++val->lv_refcount;
2114}
2115
2116/*
2117 * Set Dictionary v: variable to "val".
2118 */
2119 void
2120set_vim_var_dict(int idx, dict_T *val)
2121{
2122 clear_tv(&vimvars[idx].vv_di.di_tv);
2123 vimvars[idx].vv_type = VAR_DICT;
2124 vimvars[idx].vv_dict = val;
2125 if (val != NULL)
2126 {
2127 ++val->dv_refcount;
2128 dict_set_items_ro(val);
2129 }
2130}
2131
2132/*
Bram Moolenaar69bf6342019-10-29 04:16:57 +01002133 * Set the v:argv list.
2134 */
2135 void
2136set_argv_var(char **argv, int argc)
2137{
2138 list_T *l = list_alloc();
2139 int i;
2140
2141 if (l == NULL)
2142 getout(1);
2143 l->lv_lock = VAR_FIXED;
2144 for (i = 0; i < argc; ++i)
2145 {
2146 if (list_append_string(l, (char_u *)argv[i], -1) == FAIL)
2147 getout(1);
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01002148 l->lv_u.mat.lv_last->li_tv.v_lock = VAR_FIXED;
Bram Moolenaar69bf6342019-10-29 04:16:57 +01002149 }
2150 set_vim_var_list(VV_ARGV, l);
2151}
2152
2153/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002154 * Set v:register if needed.
2155 */
2156 void
2157set_reg_var(int c)
2158{
2159 char_u regname;
2160
2161 if (c == 0 || c == ' ')
2162 regname = '"';
2163 else
2164 regname = c;
2165 // Avoid free/alloc when the value is already right.
2166 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
2167 set_vim_var_string(VV_REG, &regname, 1);
2168}
2169
2170/*
2171 * Get or set v:exception. If "oldval" == NULL, return the current value.
2172 * Otherwise, restore the value to "oldval" and return NULL.
2173 * Must always be called in pairs to save and restore v:exception! Does not
2174 * take care of memory allocations.
2175 */
2176 char_u *
2177v_exception(char_u *oldval)
2178{
2179 if (oldval == NULL)
2180 return vimvars[VV_EXCEPTION].vv_str;
2181
2182 vimvars[VV_EXCEPTION].vv_str = oldval;
2183 return NULL;
2184}
2185
2186/*
2187 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
2188 * Otherwise, restore the value to "oldval" and return NULL.
2189 * Must always be called in pairs to save and restore v:throwpoint! Does not
2190 * take care of memory allocations.
2191 */
2192 char_u *
2193v_throwpoint(char_u *oldval)
2194{
2195 if (oldval == NULL)
2196 return vimvars[VV_THROWPOINT].vv_str;
2197
2198 vimvars[VV_THROWPOINT].vv_str = oldval;
2199 return NULL;
2200}
2201
2202/*
2203 * Set v:cmdarg.
2204 * If "eap" != NULL, use "eap" to generate the value and return the old value.
2205 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
2206 * Must always be called in pairs!
2207 */
2208 char_u *
2209set_cmdarg(exarg_T *eap, char_u *oldarg)
2210{
2211 char_u *oldval;
2212 char_u *newval;
2213 unsigned len;
2214
2215 oldval = vimvars[VV_CMDARG].vv_str;
2216 if (eap == NULL)
2217 {
2218 vim_free(oldval);
2219 vimvars[VV_CMDARG].vv_str = oldarg;
2220 return NULL;
2221 }
2222
2223 if (eap->force_bin == FORCE_BIN)
2224 len = 6;
2225 else if (eap->force_bin == FORCE_NOBIN)
2226 len = 8;
2227 else
2228 len = 0;
2229
2230 if (eap->read_edit)
2231 len += 7;
2232
2233 if (eap->force_ff != 0)
2234 len += 10; // " ++ff=unix"
2235 if (eap->force_enc != 0)
2236 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
2237 if (eap->bad_char != 0)
2238 len += 7 + 4; // " ++bad=" + "keep" or "drop"
2239
2240 newval = alloc(len + 1);
2241 if (newval == NULL)
2242 return NULL;
2243
2244 if (eap->force_bin == FORCE_BIN)
2245 sprintf((char *)newval, " ++bin");
2246 else if (eap->force_bin == FORCE_NOBIN)
2247 sprintf((char *)newval, " ++nobin");
2248 else
2249 *newval = NUL;
2250
2251 if (eap->read_edit)
2252 STRCAT(newval, " ++edit");
2253
2254 if (eap->force_ff != 0)
2255 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
2256 eap->force_ff == 'u' ? "unix"
2257 : eap->force_ff == 'd' ? "dos"
2258 : "mac");
2259 if (eap->force_enc != 0)
2260 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
2261 eap->cmd + eap->force_enc);
2262 if (eap->bad_char == BAD_KEEP)
2263 STRCPY(newval + STRLEN(newval), " ++bad=keep");
2264 else if (eap->bad_char == BAD_DROP)
2265 STRCPY(newval + STRLEN(newval), " ++bad=drop");
2266 else if (eap->bad_char != 0)
2267 sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
2268 vimvars[VV_CMDARG].vv_str = newval;
2269 return oldval;
2270}
2271
2272/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002273 * Get the value of internal variable "name".
2274 * Return OK or FAIL. If OK is returned "rettv" must be cleared.
2275 */
2276 int
2277get_var_tv(
2278 char_u *name,
2279 int len, // length of "name"
2280 typval_T *rettv, // NULL when only checking existence
2281 dictitem_T **dip, // non-NULL when typval's dict item is needed
2282 int verbose, // may give error message
2283 int no_autoload) // do not use script autoloading
2284{
2285 int ret = OK;
2286 typval_T *tv = NULL;
2287 dictitem_T *v;
2288 int cc;
2289
2290 // truncate the name, so that we can use strcmp()
2291 cc = name[len];
2292 name[len] = NUL;
2293
2294 // Check for user-defined variables.
2295 v = find_var(name, NULL, no_autoload);
2296 if (v != NULL)
2297 {
2298 tv = &v->di_tv;
2299 if (dip != NULL)
2300 *dip = v;
2301 }
2302
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002303 if (tv == NULL && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2304 {
Bram Moolenaar4e12a5d2020-02-03 20:50:59 +01002305 imported_T *import = find_imported(name, 0, NULL);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002306
2307 // imported variable from another script
2308 if (import != NULL)
2309 {
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002310 scriptitem_T *si = SCRIPT_ITEM(import->imp_sid);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002311 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data)
2312 + import->imp_var_vals_idx;
2313 tv = sv->sv_tv;
2314 }
2315 }
2316
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002317 if (tv == NULL)
2318 {
2319 if (rettv != NULL && verbose)
2320 semsg(_(e_undefvar), name);
2321 ret = FAIL;
2322 }
2323 else if (rettv != NULL)
2324 copy_tv(tv, rettv);
2325
2326 name[len] = cc;
2327
2328 return ret;
2329}
2330
2331/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002332 * Check if variable "name[len]" is a local variable or an argument.
2333 * If so, "*eval_lavars_used" is set to TRUE.
2334 */
2335 void
2336check_vars(char_u *name, int len)
2337{
2338 int cc;
2339 char_u *varname;
2340 hashtab_T *ht;
2341
2342 if (eval_lavars_used == NULL)
2343 return;
2344
2345 // truncate the name, so that we can use strcmp()
2346 cc = name[len];
2347 name[len] = NUL;
2348
2349 ht = find_var_ht(name, &varname);
2350 if (ht == get_funccal_local_ht() || ht == get_funccal_args_ht())
2351 {
2352 if (find_var(name, NULL, TRUE) != NULL)
2353 *eval_lavars_used = TRUE;
2354 }
2355
2356 name[len] = cc;
2357}
2358
2359/*
2360 * Find variable "name" in the list of variables.
2361 * Return a pointer to it if found, NULL if not found.
2362 * Careful: "a:0" variables don't have a name.
2363 * When "htp" is not NULL we are writing to the variable, set "htp" to the
2364 * hashtab_T used.
2365 */
2366 dictitem_T *
2367find_var(char_u *name, hashtab_T **htp, int no_autoload)
2368{
2369 char_u *varname;
2370 hashtab_T *ht;
2371 dictitem_T *ret = NULL;
2372
2373 ht = find_var_ht(name, &varname);
2374 if (htp != NULL)
2375 *htp = ht;
2376 if (ht == NULL)
2377 return NULL;
2378 ret = find_var_in_ht(ht, *name, varname, no_autoload || htp != NULL);
2379 if (ret != NULL)
2380 return ret;
2381
Bram Moolenaar8d71b542019-08-30 15:46:30 +02002382 // Search in parent scope for lambda
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002383 return find_var_in_scoped_ht(name, no_autoload || htp != NULL);
2384}
2385
2386/*
2387 * Find variable "varname" in hashtab "ht" with name "htname".
Bram Moolenaar52592752020-04-03 18:43:35 +02002388 * When "varname" is empty returns curwin/curtab/etc vars dictionary.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002389 * Returns NULL if not found.
2390 */
2391 dictitem_T *
2392find_var_in_ht(
2393 hashtab_T *ht,
2394 int htname,
2395 char_u *varname,
2396 int no_autoload)
2397{
2398 hashitem_T *hi;
2399
2400 if (*varname == NUL)
2401 {
2402 // Must be something like "s:", otherwise "ht" would be NULL.
2403 switch (htname)
2404 {
2405 case 's': return &SCRIPT_SV(current_sctx.sc_sid)->sv_var;
2406 case 'g': return &globvars_var;
2407 case 'v': return &vimvars_var;
2408 case 'b': return &curbuf->b_bufvar;
2409 case 'w': return &curwin->w_winvar;
2410 case 't': return &curtab->tp_winvar;
2411 case 'l': return get_funccal_local_var();
2412 case 'a': return get_funccal_args_var();
2413 }
2414 return NULL;
2415 }
2416
2417 hi = hash_find(ht, varname);
2418 if (HASHITEM_EMPTY(hi))
2419 {
2420 // For global variables we may try auto-loading the script. If it
2421 // worked find the variable again. Don't auto-load a script if it was
2422 // loaded already, otherwise it would be loaded every time when
2423 // checking if a function name is a Funcref variable.
2424 if (ht == &globvarht && !no_autoload)
2425 {
2426 // Note: script_autoload() may make "hi" invalid. It must either
2427 // be obtained again or not used.
2428 if (!script_autoload(varname, FALSE) || aborting())
2429 return NULL;
2430 hi = hash_find(ht, varname);
2431 }
2432 if (HASHITEM_EMPTY(hi))
2433 return NULL;
2434 }
2435 return HI2DI(hi);
2436}
2437
2438/*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002439 * Get the script-local hashtab. NULL if not in a script context.
2440 */
Bram Moolenaarbdff0122020-04-05 18:56:05 +02002441 static hashtab_T *
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002442get_script_local_ht(void)
2443{
2444 scid_T sid = current_sctx.sc_sid;
2445
2446 if (sid > 0 && sid <= script_items.ga_len)
2447 return &SCRIPT_VARS(sid);
2448 return NULL;
2449}
2450
2451/*
2452 * Look for "name[len]" in script-local variables.
2453 * Return -1 when not found.
2454 */
2455 int
2456lookup_scriptvar(char_u *name, size_t len, cctx_T *dummy UNUSED)
2457{
2458 hashtab_T *ht = get_script_local_ht();
2459 char_u buffer[30];
2460 char_u *p;
2461 int res;
2462 hashitem_T *hi;
2463
2464 if (ht == NULL)
2465 return -1;
2466 if (len < sizeof(buffer) - 1)
2467 {
2468 vim_strncpy(buffer, name, len);
2469 p = buffer;
2470 }
2471 else
2472 {
2473 p = vim_strnsave(name, (int)len);
2474 if (p == NULL)
2475 return -1;
2476 }
2477
2478 hi = hash_find(ht, p);
2479 res = HASHITEM_EMPTY(hi) ? -1 : 1;
2480
2481 // if not script-local, then perhaps imported
Bram Moolenaar4e12a5d2020-02-03 20:50:59 +01002482 if (res == -1 && find_imported(p, 0, NULL) != NULL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002483 res = 1;
2484
2485 if (p != buffer)
2486 vim_free(p);
2487 return res;
2488}
2489
2490/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002491 * Find the hashtab used for a variable name.
2492 * Return NULL if the name is not valid.
2493 * Set "varname" to the start of name without ':'.
2494 */
2495 hashtab_T *
2496find_var_ht(char_u *name, char_u **varname)
2497{
2498 hashitem_T *hi;
2499 hashtab_T *ht;
2500
2501 if (name[0] == NUL)
2502 return NULL;
2503 if (name[1] != ':')
2504 {
2505 // The name must not start with a colon or #.
2506 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
2507 return NULL;
2508 *varname = name;
2509
2510 // "version" is "v:version" in all scopes if scriptversion < 3.
2511 // Same for a few other variables marked with VV_COMPAT.
2512 if (current_sctx.sc_version < 3)
2513 {
2514 hi = hash_find(&compat_hashtab, name);
2515 if (!HASHITEM_EMPTY(hi))
2516 return &compat_hashtab;
2517 }
2518
2519 ht = get_funccal_local_ht();
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002520 if (ht != NULL)
2521 return ht; // local variable
2522
2523 // in Vim9 script items at the script level are script-local
2524 if (current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2525 {
2526 ht = get_script_local_ht();
2527 if (ht != NULL)
2528 return ht;
2529 }
2530
2531 return &globvarht; // global variable
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002532 }
2533 *varname = name + 2;
2534 if (*name == 'g') // global variable
2535 return &globvarht;
2536 // There must be no ':' or '#' in the rest of the name, unless g: is used
2537 if (vim_strchr(name + 2, ':') != NULL
2538 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
2539 return NULL;
2540 if (*name == 'b') // buffer variable
2541 return &curbuf->b_vars->dv_hashtab;
2542 if (*name == 'w') // window variable
2543 return &curwin->w_vars->dv_hashtab;
2544 if (*name == 't') // tab page variable
2545 return &curtab->tp_vars->dv_hashtab;
2546 if (*name == 'v') // v: variable
2547 return &vimvarht;
Bram Moolenaarb35efa52020-02-26 20:15:18 +01002548 if (get_current_funccal() != NULL
2549 && get_current_funccal()->func->uf_dfunc_idx < 0)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002550 {
Bram Moolenaarb35efa52020-02-26 20:15:18 +01002551 // a: and l: are only used in functions defined with ":function"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002552 if (*name == 'a') // a: function argument
2553 return get_funccal_args_ht();
2554 if (*name == 'l') // l: local function variable
2555 return get_funccal_local_ht();
2556 }
2557 if (*name == 's') // script variable
2558 {
2559 ht = get_script_local_ht();
2560 if (ht != NULL)
2561 return ht;
2562 }
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002563 return NULL;
2564}
2565
2566/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002567 * Get the string value of a (global/local) variable.
2568 * Note: see tv_get_string() for how long the pointer remains valid.
2569 * Returns NULL when it doesn't exist.
2570 */
2571 char_u *
2572get_var_value(char_u *name)
2573{
2574 dictitem_T *v;
2575
2576 v = find_var(name, NULL, FALSE);
2577 if (v == NULL)
2578 return NULL;
2579 return tv_get_string(&v->di_tv);
2580}
2581
2582/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002583 * Allocate a new hashtab for a sourced script. It will be used while
2584 * sourcing this script and when executing functions defined in the script.
2585 */
2586 void
2587new_script_vars(scid_T id)
2588{
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002589 scriptvar_T *sv;
2590
Bram Moolenaar7ebcba62020-01-12 17:42:55 +01002591 sv = ALLOC_CLEAR_ONE(scriptvar_T);
2592 if (sv == NULL)
2593 return;
2594 init_var_dict(&sv->sv_dict, &sv->sv_var, VAR_SCOPE);
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002595 SCRIPT_ITEM(id)->sn_vars = sv;
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002596}
2597
2598/*
2599 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
2600 * point to it.
2601 */
2602 void
2603init_var_dict(dict_T *dict, dictitem_T *dict_var, int scope)
2604{
2605 hash_init(&dict->dv_hashtab);
2606 dict->dv_lock = 0;
2607 dict->dv_scope = scope;
2608 dict->dv_refcount = DO_NOT_FREE_CNT;
2609 dict->dv_copyID = 0;
2610 dict_var->di_tv.vval.v_dict = dict;
2611 dict_var->di_tv.v_type = VAR_DICT;
2612 dict_var->di_tv.v_lock = VAR_FIXED;
2613 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
2614 dict_var->di_key[0] = NUL;
2615}
2616
2617/*
2618 * Unreference a dictionary initialized by init_var_dict().
2619 */
2620 void
2621unref_var_dict(dict_T *dict)
2622{
Bram Moolenaar8d71b542019-08-30 15:46:30 +02002623 // Now the dict needs to be freed if no one else is using it, go back to
2624 // normal reference counting.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002625 dict->dv_refcount -= DO_NOT_FREE_CNT - 1;
2626 dict_unref(dict);
2627}
2628
2629/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002630 * Clean up a list of internal variables.
2631 * Frees all allocated variables and the value they contain.
2632 * Clears hashtab "ht", does not free it.
2633 */
2634 void
2635vars_clear(hashtab_T *ht)
2636{
2637 vars_clear_ext(ht, TRUE);
2638}
2639
2640/*
2641 * Like vars_clear(), but only free the value if "free_val" is TRUE.
2642 */
2643 void
2644vars_clear_ext(hashtab_T *ht, int free_val)
2645{
2646 int todo;
2647 hashitem_T *hi;
2648 dictitem_T *v;
2649
2650 hash_lock(ht);
2651 todo = (int)ht->ht_used;
2652 for (hi = ht->ht_array; todo > 0; ++hi)
2653 {
2654 if (!HASHITEM_EMPTY(hi))
2655 {
2656 --todo;
2657
2658 // Free the variable. Don't remove it from the hashtab,
2659 // ht_array might change then. hash_clear() takes care of it
2660 // later.
2661 v = HI2DI(hi);
2662 if (free_val)
2663 clear_tv(&v->di_tv);
2664 if (v->di_flags & DI_FLAGS_ALLOC)
2665 vim_free(v);
2666 }
2667 }
2668 hash_clear(ht);
2669 ht->ht_used = 0;
2670}
2671
2672/*
2673 * Delete a variable from hashtab "ht" at item "hi".
2674 * Clear the variable value and free the dictitem.
2675 */
Bram Moolenaarda6c0332019-09-01 16:01:30 +02002676 static void
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002677delete_var(hashtab_T *ht, hashitem_T *hi)
2678{
2679 dictitem_T *di = HI2DI(hi);
2680
2681 hash_remove(ht, hi);
2682 clear_tv(&di->di_tv);
2683 vim_free(di);
2684}
2685
2686/*
2687 * List the value of one internal variable.
2688 */
2689 static void
2690list_one_var(dictitem_T *v, char *prefix, int *first)
2691{
2692 char_u *tofree;
2693 char_u *s;
2694 char_u numbuf[NUMBUFLEN];
2695
2696 s = echo_string(&v->di_tv, &tofree, numbuf, get_copyID());
2697 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
2698 s == NULL ? (char_u *)"" : s, first);
2699 vim_free(tofree);
2700}
2701
2702 static void
2703list_one_var_a(
2704 char *prefix,
2705 char_u *name,
2706 int type,
2707 char_u *string,
2708 int *first) // when TRUE clear rest of screen and set to FALSE
2709{
2710 // don't use msg() or msg_attr() to avoid overwriting "v:statusmsg"
2711 msg_start();
2712 msg_puts(prefix);
2713 if (name != NULL) // "a:" vars don't have a name stored
2714 msg_puts((char *)name);
2715 msg_putchar(' ');
2716 msg_advance(22);
2717 if (type == VAR_NUMBER)
2718 msg_putchar('#');
2719 else if (type == VAR_FUNC || type == VAR_PARTIAL)
2720 msg_putchar('*');
2721 else if (type == VAR_LIST)
2722 {
2723 msg_putchar('[');
2724 if (*string == '[')
2725 ++string;
2726 }
2727 else if (type == VAR_DICT)
2728 {
2729 msg_putchar('{');
2730 if (*string == '{')
2731 ++string;
2732 }
2733 else
2734 msg_putchar(' ');
2735
2736 msg_outtrans(string);
2737
2738 if (type == VAR_FUNC || type == VAR_PARTIAL)
2739 msg_puts("()");
2740 if (*first)
2741 {
2742 msg_clr_eos();
2743 *first = FALSE;
2744 }
2745}
2746
2747/*
2748 * Set variable "name" to value in "tv".
2749 * If the variable already exists, the value is updated.
2750 * Otherwise the variable is created.
2751 */
2752 void
2753set_var(
2754 char_u *name,
2755 typval_T *tv,
2756 int copy) // make copy of value in "tv"
2757{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002758 set_var_const(name, NULL, tv, copy, 0);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002759}
2760
2761/*
2762 * Set variable "name" to value in "tv".
2763 * If the variable already exists and "is_const" is FALSE the value is updated.
2764 * Otherwise the variable is created.
2765 */
2766 void
2767set_var_const(
2768 char_u *name,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002769 type_T *type,
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002770 typval_T *tv,
2771 int copy, // make copy of value in "tv"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002772 int flags) // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002773{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002774 dictitem_T *di;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002775 char_u *varname;
2776 hashtab_T *ht;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002777 int is_script_local;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002778
2779 ht = find_var_ht(name, &varname);
2780 if (ht == NULL || *varname == NUL)
2781 {
2782 semsg(_(e_illvar), name);
2783 return;
2784 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002785 is_script_local = ht == get_script_local_ht();
2786
2787 di = find_var_in_ht(ht, 0, varname, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002788
2789 // Search in parent scope which is possible to reference from lambda
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002790 if (di == NULL)
2791 di = find_var_in_scoped_ht(name, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002792
2793 if ((tv->v_type == VAR_FUNC || tv->v_type == VAR_PARTIAL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002794 && var_check_func_name(name, di == NULL))
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002795 return;
2796
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002797 if (di != NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002798 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002799 if ((di->di_flags & DI_FLAGS_RELOAD) == 0)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002800 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002801 if (flags & LET_IS_CONST)
2802 {
2803 emsg(_(e_cannot_mod));
2804 return;
2805 }
2806
2807 if (var_check_ro(di->di_flags, name, FALSE)
2808 || var_check_lock(di->di_tv.v_lock, name, FALSE))
2809 return;
2810
2811 if ((flags & LET_NO_COMMAND) == 0
2812 && is_script_local
2813 && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2814 {
2815 semsg(_("E1041: Redefining script item %s"), name);
2816 return;
2817 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002818 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002819 else
2820 // can only redefine once
2821 di->di_flags &= ~DI_FLAGS_RELOAD;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002822
2823 // existing variable, need to clear the value
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002824
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002825 // Handle setting internal di: variables separately where needed to
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002826 // prevent changing the type.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002827 if (ht == &vimvarht)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002828 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002829 if (di->di_tv.v_type == VAR_STRING)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002830 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002831 VIM_CLEAR(di->di_tv.vval.v_string);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002832 if (copy || tv->v_type != VAR_STRING)
2833 {
2834 char_u *val = tv_get_string(tv);
2835
2836 // Careful: when assigning to v:errmsg and tv_get_string()
Bram Moolenaar4b96df52020-01-26 22:00:26 +01002837 // causes an error message the variable will already be set.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002838 if (di->di_tv.vval.v_string == NULL)
2839 di->di_tv.vval.v_string = vim_strsave(val);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002840 }
2841 else
2842 {
2843 // Take over the string to avoid an extra alloc/free.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002844 di->di_tv.vval.v_string = tv->vval.v_string;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002845 tv->vval.v_string = NULL;
2846 }
2847 return;
2848 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002849 else if (di->di_tv.v_type == VAR_NUMBER)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002850 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002851 di->di_tv.vval.v_number = tv_get_number(tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002852 if (STRCMP(varname, "searchforward") == 0)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002853 set_search_direction(di->di_tv.vval.v_number ? '/' : '?');
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002854#ifdef FEAT_SEARCH_EXTRA
2855 else if (STRCMP(varname, "hlsearch") == 0)
2856 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002857 no_hlsearch = !di->di_tv.vval.v_number;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002858 redraw_all_later(SOME_VALID);
2859 }
2860#endif
2861 return;
2862 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002863 else if (di->di_tv.v_type != tv->v_type)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002864 {
2865 semsg(_("E963: setting %s to value with wrong type"), name);
2866 return;
2867 }
2868 }
2869
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002870 clear_tv(&di->di_tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002871 }
2872 else // add a new variable
2873 {
2874 // Can't add "v:" or "a:" variable.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002875 if (ht == &vimvarht || ht == get_funccal_args_ht())
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002876 {
2877 semsg(_(e_illvar), name);
2878 return;
2879 }
2880
2881 // Make sure the variable name is valid.
2882 if (!valid_varname(varname))
2883 return;
2884
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002885 di = alloc(sizeof(dictitem_T) + STRLEN(varname));
2886 if (di == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002887 return;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002888 STRCPY(di->di_key, varname);
2889 if (hash_add(ht, DI2HIKEY(di)) == FAIL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002890 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002891 vim_free(di);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002892 return;
2893 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002894 di->di_flags = DI_FLAGS_ALLOC;
2895 if (flags & LET_IS_CONST)
2896 di->di_flags |= DI_FLAGS_LOCK;
2897
2898 if (is_script_local && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2899 {
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002900 scriptitem_T *si = SCRIPT_ITEM(current_sctx.sc_sid);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002901
2902 // Store a pointer to the typval_T, so that it can be found by
2903 // index instead of using a hastab lookup.
2904 if (ga_grow(&si->sn_var_vals, 1) == OK)
2905 {
2906 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data)
2907 + si->sn_var_vals.ga_len;
2908 sv->sv_name = di->di_key;
2909 sv->sv_tv = &di->di_tv;
2910 sv->sv_type = type == NULL ? &t_any : type;
2911 sv->sv_const = (flags & LET_IS_CONST);
2912 sv->sv_export = is_export;
2913 ++si->sn_var_vals.ga_len;
2914
2915 // let ex_export() know the export worked.
2916 is_export = FALSE;
2917 }
2918 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002919 }
2920
2921 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002922 copy_tv(tv, &di->di_tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002923 else
2924 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002925 di->di_tv = *tv;
2926 di->di_tv.v_lock = 0;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002927 init_tv(tv);
2928 }
2929
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002930 if (flags & LET_IS_CONST)
2931 di->di_tv.v_lock |= VAR_LOCKED;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002932}
2933
2934/*
2935 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
2936 * Also give an error message.
2937 */
2938 int
2939var_check_ro(int flags, char_u *name, int use_gettext)
2940{
2941 if (flags & DI_FLAGS_RO)
2942 {
2943 semsg(_(e_readonlyvar), use_gettext ? (char_u *)_(name) : name);
2944 return TRUE;
2945 }
2946 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
2947 {
2948 semsg(_(e_readonlysbx), use_gettext ? (char_u *)_(name) : name);
2949 return TRUE;
2950 }
2951 return FALSE;
2952}
2953
2954/*
2955 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
2956 * Also give an error message.
2957 */
2958 int
2959var_check_fixed(int flags, char_u *name, int use_gettext)
2960{
2961 if (flags & DI_FLAGS_FIX)
2962 {
2963 semsg(_("E795: Cannot delete variable %s"),
2964 use_gettext ? (char_u *)_(name) : name);
2965 return TRUE;
2966 }
2967 return FALSE;
2968}
2969
2970/*
2971 * Check if a funcref is assigned to a valid variable name.
2972 * Return TRUE and give an error if not.
2973 */
2974 int
2975var_check_func_name(
2976 char_u *name, // points to start of variable name
2977 int new_var) // TRUE when creating the variable
2978{
2979 // Allow for w: b: s: and t:.
2980 if (!(vim_strchr((char_u *)"wbst", name[0]) != NULL && name[1] == ':')
2981 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
2982 ? name[2] : name[0]))
2983 {
2984 semsg(_("E704: Funcref variable name must start with a capital: %s"),
2985 name);
2986 return TRUE;
2987 }
2988 // Don't allow hiding a function. When "v" is not NULL we might be
2989 // assigning another function to the same var, the type is checked
2990 // below.
2991 if (new_var && function_exists(name, FALSE))
2992 {
2993 semsg(_("E705: Variable name conflicts with existing function: %s"),
2994 name);
2995 return TRUE;
2996 }
2997 return FALSE;
2998}
2999
3000/*
3001 * Return TRUE if "flags" indicates variable "name" is locked (immutable).
3002 * Also give an error message, using "name" or _("name") when use_gettext is
3003 * TRUE.
3004 */
3005 int
3006var_check_lock(int lock, char_u *name, int use_gettext)
3007{
3008 if (lock & VAR_LOCKED)
3009 {
3010 semsg(_("E741: Value is locked: %s"),
3011 name == NULL ? (char_u *)_("Unknown")
3012 : use_gettext ? (char_u *)_(name)
3013 : name);
3014 return TRUE;
3015 }
3016 if (lock & VAR_FIXED)
3017 {
3018 semsg(_("E742: Cannot change value of %s"),
3019 name == NULL ? (char_u *)_("Unknown")
3020 : use_gettext ? (char_u *)_(name)
3021 : name);
3022 return TRUE;
3023 }
3024 return FALSE;
3025}
3026
3027/*
3028 * Check if a variable name is valid.
3029 * Return FALSE and give an error if not.
3030 */
3031 int
3032valid_varname(char_u *varname)
3033{
3034 char_u *p;
3035
3036 for (p = varname; *p != NUL; ++p)
3037 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
3038 && *p != AUTOLOAD_CHAR)
3039 {
3040 semsg(_(e_illvar), varname);
3041 return FALSE;
3042 }
3043 return TRUE;
3044}
3045
3046/*
3047 * getwinvar() and gettabwinvar()
3048 */
3049 static void
3050getwinvar(
3051 typval_T *argvars,
3052 typval_T *rettv,
3053 int off) // 1 for gettabwinvar()
3054{
3055 win_T *win;
3056 char_u *varname;
3057 dictitem_T *v;
3058 tabpage_T *tp = NULL;
3059 int done = FALSE;
3060 win_T *oldcurwin;
3061 tabpage_T *oldtabpage;
3062 int need_switch_win;
3063
3064 if (off == 1)
3065 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3066 else
3067 tp = curtab;
3068 win = find_win_by_nr(&argvars[off], tp);
3069 varname = tv_get_string_chk(&argvars[off + 1]);
3070 ++emsg_off;
3071
3072 rettv->v_type = VAR_STRING;
3073 rettv->vval.v_string = NULL;
3074
3075 if (win != NULL && varname != NULL)
3076 {
3077 // Set curwin to be our win, temporarily. Also set the tabpage,
3078 // otherwise the window is not valid. Only do this when needed,
3079 // autocommands get blocked.
3080 need_switch_win = !(tp == curtab && win == curwin);
3081 if (!need_switch_win
3082 || switch_win(&oldcurwin, &oldtabpage, win, tp, TRUE) == OK)
3083 {
3084 if (*varname == '&')
3085 {
3086 if (varname[1] == NUL)
3087 {
3088 // get all window-local options in a dict
3089 dict_T *opts = get_winbuf_options(FALSE);
3090
3091 if (opts != NULL)
3092 {
3093 rettv_dict_set(rettv, opts);
3094 done = TRUE;
3095 }
3096 }
3097 else if (get_option_tv(&varname, rettv, 1) == OK)
3098 // window-local-option
3099 done = TRUE;
3100 }
3101 else
3102 {
3103 // Look up the variable.
3104 // Let getwinvar({nr}, "") return the "w:" dictionary.
3105 v = find_var_in_ht(&win->w_vars->dv_hashtab, 'w',
3106 varname, FALSE);
3107 if (v != NULL)
3108 {
3109 copy_tv(&v->di_tv, rettv);
3110 done = TRUE;
3111 }
3112 }
3113 }
3114
3115 if (need_switch_win)
3116 // restore previous notion of curwin
3117 restore_win(oldcurwin, oldtabpage, TRUE);
3118 }
3119
3120 if (!done && argvars[off + 2].v_type != VAR_UNKNOWN)
3121 // use the default return value
3122 copy_tv(&argvars[off + 2], rettv);
3123
3124 --emsg_off;
3125}
3126
3127/*
3128 * "setwinvar()" and "settabwinvar()" functions
3129 */
3130 static void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003131setwinvar(typval_T *argvars, int off)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003132{
3133 win_T *win;
3134 win_T *save_curwin;
3135 tabpage_T *save_curtab;
3136 int need_switch_win;
3137 char_u *varname, *winvarname;
3138 typval_T *varp;
3139 char_u nbuf[NUMBUFLEN];
3140 tabpage_T *tp = NULL;
3141
3142 if (check_secure())
3143 return;
3144
3145 if (off == 1)
3146 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3147 else
3148 tp = curtab;
3149 win = find_win_by_nr(&argvars[off], tp);
3150 varname = tv_get_string_chk(&argvars[off + 1]);
3151 varp = &argvars[off + 2];
3152
3153 if (win != NULL && varname != NULL && varp != NULL)
3154 {
3155 need_switch_win = !(tp == curtab && win == curwin);
3156 if (!need_switch_win
3157 || switch_win(&save_curwin, &save_curtab, win, tp, TRUE) == OK)
3158 {
3159 if (*varname == '&')
3160 {
3161 long numval;
3162 char_u *strval;
3163 int error = FALSE;
3164
3165 ++varname;
3166 numval = (long)tv_get_number_chk(varp, &error);
3167 strval = tv_get_string_buf_chk(varp, nbuf);
3168 if (!error && strval != NULL)
3169 set_option_value(varname, numval, strval, OPT_LOCAL);
3170 }
3171 else
3172 {
3173 winvarname = alloc(STRLEN(varname) + 3);
3174 if (winvarname != NULL)
3175 {
3176 STRCPY(winvarname, "w:");
3177 STRCPY(winvarname + 2, varname);
3178 set_var(winvarname, varp, TRUE);
3179 vim_free(winvarname);
3180 }
3181 }
3182 }
3183 if (need_switch_win)
3184 restore_win(save_curwin, save_curtab, TRUE);
3185 }
3186}
3187
Bram Moolenaare5cdf152019-08-29 22:09:46 +02003188/*
3189 * reset v:option_new, v:option_old, v:option_oldlocal, v:option_oldglobal,
3190 * v:option_type, and v:option_command.
3191 */
3192 void
3193reset_v_option_vars(void)
3194{
3195 set_vim_var_string(VV_OPTION_NEW, NULL, -1);
3196 set_vim_var_string(VV_OPTION_OLD, NULL, -1);
3197 set_vim_var_string(VV_OPTION_OLDLOCAL, NULL, -1);
3198 set_vim_var_string(VV_OPTION_OLDGLOBAL, NULL, -1);
3199 set_vim_var_string(VV_OPTION_TYPE, NULL, -1);
3200 set_vim_var_string(VV_OPTION_COMMAND, NULL, -1);
3201}
3202
3203/*
3204 * Add an assert error to v:errors.
3205 */
3206 void
3207assert_error(garray_T *gap)
3208{
3209 struct vimvar *vp = &vimvars[VV_ERRORS];
3210
3211 if (vp->vv_type != VAR_LIST || vimvars[VV_ERRORS].vv_list == NULL)
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003212 // Make sure v:errors is a list.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02003213 set_vim_var_list(VV_ERRORS, list_alloc());
3214 list_append_string(vimvars[VV_ERRORS].vv_list, gap->ga_data, gap->ga_len);
3215}
3216
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003217 int
3218var_exists(char_u *var)
3219{
3220 char_u *name;
3221 char_u *tofree;
3222 typval_T tv;
3223 int len = 0;
3224 int n = FALSE;
3225
3226 // get_name_len() takes care of expanding curly braces
3227 name = var;
3228 len = get_name_len(&var, &tofree, TRUE, FALSE);
3229 if (len > 0)
3230 {
3231 if (tofree != NULL)
3232 name = tofree;
3233 n = (get_var_tv(name, len, &tv, NULL, FALSE, TRUE) == OK);
3234 if (n)
3235 {
3236 // handle d.key, l[idx], f(expr)
3237 n = (handle_subscript(&var, &tv, TRUE, FALSE, name, &name) == OK);
3238 if (n)
3239 clear_tv(&tv);
3240 }
3241 }
3242 if (*var != NUL)
3243 n = FALSE;
3244
3245 vim_free(tofree);
3246 return n;
3247}
3248
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003249static lval_T *redir_lval = NULL;
3250#define EVALCMD_BUSY (redir_lval == (lval_T *)&redir_lval)
3251static garray_T redir_ga; // only valid when redir_lval is not NULL
3252static char_u *redir_endp = NULL;
3253static char_u *redir_varname = NULL;
3254
3255/*
3256 * Start recording command output to a variable
3257 * When "append" is TRUE append to an existing variable.
3258 * Returns OK if successfully completed the setup. FAIL otherwise.
3259 */
3260 int
3261var_redir_start(char_u *name, int append)
3262{
3263 int save_emsg;
3264 int err;
3265 typval_T tv;
3266
3267 // Catch a bad name early.
3268 if (!eval_isnamec1(*name))
3269 {
3270 emsg(_(e_invarg));
3271 return FAIL;
3272 }
3273
3274 // Make a copy of the name, it is used in redir_lval until redir ends.
3275 redir_varname = vim_strsave(name);
3276 if (redir_varname == NULL)
3277 return FAIL;
3278
3279 redir_lval = ALLOC_CLEAR_ONE(lval_T);
3280 if (redir_lval == NULL)
3281 {
3282 var_redir_stop();
3283 return FAIL;
3284 }
3285
3286 // The output is stored in growarray "redir_ga" until redirection ends.
3287 ga_init2(&redir_ga, (int)sizeof(char), 500);
3288
3289 // Parse the variable name (can be a dict or list entry).
3290 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, 0,
3291 FNE_CHECK_START);
3292 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
3293 {
3294 clear_lval(redir_lval);
3295 if (redir_endp != NULL && *redir_endp != NUL)
3296 // Trailing characters are present after the variable name
3297 emsg(_(e_trailing));
3298 else
3299 emsg(_(e_invarg));
3300 redir_endp = NULL; // don't store a value, only cleanup
3301 var_redir_stop();
3302 return FAIL;
3303 }
3304
3305 // check if we can write to the variable: set it to or append an empty
3306 // string
3307 save_emsg = did_emsg;
3308 did_emsg = FALSE;
3309 tv.v_type = VAR_STRING;
3310 tv.vval.v_string = (char_u *)"";
3311 if (append)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003312 set_var_lval(redir_lval, redir_endp, &tv, TRUE, 0, (char_u *)".");
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003313 else
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003314 set_var_lval(redir_lval, redir_endp, &tv, TRUE, 0, (char_u *)"=");
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003315 clear_lval(redir_lval);
3316 err = did_emsg;
3317 did_emsg |= save_emsg;
3318 if (err)
3319 {
3320 redir_endp = NULL; // don't store a value, only cleanup
3321 var_redir_stop();
3322 return FAIL;
3323 }
3324
3325 return OK;
3326}
3327
3328/*
3329 * Append "value[value_len]" to the variable set by var_redir_start().
3330 * The actual appending is postponed until redirection ends, because the value
3331 * appended may in fact be the string we write to, changing it may cause freed
3332 * memory to be used:
3333 * :redir => foo
3334 * :let foo
3335 * :redir END
3336 */
3337 void
3338var_redir_str(char_u *value, int value_len)
3339{
3340 int len;
3341
3342 if (redir_lval == NULL)
3343 return;
3344
3345 if (value_len == -1)
3346 len = (int)STRLEN(value); // Append the entire string
3347 else
3348 len = value_len; // Append only "value_len" characters
3349
3350 if (ga_grow(&redir_ga, len) == OK)
3351 {
3352 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
3353 redir_ga.ga_len += len;
3354 }
3355 else
3356 var_redir_stop();
3357}
3358
3359/*
3360 * Stop redirecting command output to a variable.
3361 * Frees the allocated memory.
3362 */
3363 void
3364var_redir_stop(void)
3365{
3366 typval_T tv;
3367
3368 if (EVALCMD_BUSY)
3369 {
3370 redir_lval = NULL;
3371 return;
3372 }
3373
3374 if (redir_lval != NULL)
3375 {
3376 // If there was no error: assign the text to the variable.
3377 if (redir_endp != NULL)
3378 {
3379 ga_append(&redir_ga, NUL); // Append the trailing NUL.
3380 tv.v_type = VAR_STRING;
3381 tv.vval.v_string = redir_ga.ga_data;
3382 // Call get_lval() again, if it's inside a Dict or List it may
3383 // have changed.
3384 redir_endp = get_lval(redir_varname, NULL, redir_lval,
3385 FALSE, FALSE, 0, FNE_CHECK_START);
3386 if (redir_endp != NULL && redir_lval->ll_name != NULL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003387 set_var_lval(redir_lval, redir_endp, &tv, FALSE, 0,
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003388 (char_u *)".");
3389 clear_lval(redir_lval);
3390 }
3391
3392 // free the collected output
3393 VIM_CLEAR(redir_ga.ga_data);
3394
3395 VIM_CLEAR(redir_lval);
3396 }
3397 VIM_CLEAR(redir_varname);
3398}
3399
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003400/*
3401 * "gettabvar()" function
3402 */
3403 void
3404f_gettabvar(typval_T *argvars, typval_T *rettv)
3405{
3406 win_T *oldcurwin;
3407 tabpage_T *tp, *oldtabpage;
3408 dictitem_T *v;
3409 char_u *varname;
3410 int done = FALSE;
3411
3412 rettv->v_type = VAR_STRING;
3413 rettv->vval.v_string = NULL;
3414
3415 varname = tv_get_string_chk(&argvars[1]);
3416 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3417 if (tp != NULL && varname != NULL)
3418 {
3419 // Set tp to be our tabpage, temporarily. Also set the window to the
3420 // first window in the tabpage, otherwise the window is not valid.
3421 if (switch_win(&oldcurwin, &oldtabpage,
3422 tp == curtab || tp->tp_firstwin == NULL ? firstwin
3423 : tp->tp_firstwin, tp, TRUE) == OK)
3424 {
3425 // look up the variable
3426 // Let gettabvar({nr}, "") return the "t:" dictionary.
3427 v = find_var_in_ht(&tp->tp_vars->dv_hashtab, 't', varname, FALSE);
3428 if (v != NULL)
3429 {
3430 copy_tv(&v->di_tv, rettv);
3431 done = TRUE;
3432 }
3433 }
3434
3435 // restore previous notion of curwin
3436 restore_win(oldcurwin, oldtabpage, TRUE);
3437 }
3438
3439 if (!done && argvars[2].v_type != VAR_UNKNOWN)
3440 copy_tv(&argvars[2], rettv);
3441}
3442
3443/*
3444 * "gettabwinvar()" function
3445 */
3446 void
3447f_gettabwinvar(typval_T *argvars, typval_T *rettv)
3448{
3449 getwinvar(argvars, rettv, 1);
3450}
3451
3452/*
3453 * "getwinvar()" function
3454 */
3455 void
3456f_getwinvar(typval_T *argvars, typval_T *rettv)
3457{
3458 getwinvar(argvars, rettv, 0);
3459}
3460
3461/*
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003462 * "getbufvar()" function
3463 */
3464 void
3465f_getbufvar(typval_T *argvars, typval_T *rettv)
3466{
3467 buf_T *buf;
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003468 char_u *varname;
3469 dictitem_T *v;
3470 int done = FALSE;
3471
3472 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
3473 varname = tv_get_string_chk(&argvars[1]);
3474 ++emsg_off;
3475 buf = tv_get_buf(&argvars[0], FALSE);
3476
3477 rettv->v_type = VAR_STRING;
3478 rettv->vval.v_string = NULL;
3479
3480 if (buf != NULL && varname != NULL)
3481 {
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003482 if (*varname == '&')
3483 {
Bram Moolenaar86015452020-03-29 15:12:15 +02003484 buf_T *save_curbuf = curbuf;
3485
3486 // set curbuf to be our buf, temporarily
3487 curbuf = buf;
3488
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003489 if (varname[1] == NUL)
3490 {
3491 // get all buffer-local options in a dict
3492 dict_T *opts = get_winbuf_options(TRUE);
3493
3494 if (opts != NULL)
3495 {
3496 rettv_dict_set(rettv, opts);
3497 done = TRUE;
3498 }
3499 }
3500 else if (get_option_tv(&varname, rettv, TRUE) == OK)
3501 // buffer-local-option
3502 done = TRUE;
Bram Moolenaar86015452020-03-29 15:12:15 +02003503
3504 // restore previous notion of curbuf
3505 curbuf = save_curbuf;
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003506 }
3507 else
3508 {
3509 // Look up the variable.
Bram Moolenaar52592752020-04-03 18:43:35 +02003510 if (*varname == NUL)
3511 // Let getbufvar({nr}, "") return the "b:" dictionary.
3512 v = &buf->b_bufvar;
3513 else
3514 v = find_var_in_ht(&buf->b_vars->dv_hashtab, 'b',
3515 varname, FALSE);
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003516 if (v != NULL)
3517 {
3518 copy_tv(&v->di_tv, rettv);
3519 done = TRUE;
3520 }
3521 }
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003522 }
3523
3524 if (!done && argvars[2].v_type != VAR_UNKNOWN)
3525 // use the default value
3526 copy_tv(&argvars[2], rettv);
3527
3528 --emsg_off;
3529}
3530
3531/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003532 * "settabvar()" function
3533 */
3534 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003535f_settabvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003536{
3537 tabpage_T *save_curtab;
3538 tabpage_T *tp;
3539 char_u *varname, *tabvarname;
3540 typval_T *varp;
3541
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003542 if (check_secure())
3543 return;
3544
3545 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3546 varname = tv_get_string_chk(&argvars[1]);
3547 varp = &argvars[2];
3548
3549 if (varname != NULL && varp != NULL && tp != NULL)
3550 {
3551 save_curtab = curtab;
3552 goto_tabpage_tp(tp, FALSE, FALSE);
3553
3554 tabvarname = alloc(STRLEN(varname) + 3);
3555 if (tabvarname != NULL)
3556 {
3557 STRCPY(tabvarname, "t:");
3558 STRCPY(tabvarname + 2, varname);
3559 set_var(tabvarname, varp, TRUE);
3560 vim_free(tabvarname);
3561 }
3562
3563 // Restore current tabpage
3564 if (valid_tabpage(save_curtab))
3565 goto_tabpage_tp(save_curtab, FALSE, FALSE);
3566 }
3567}
3568
3569/*
3570 * "settabwinvar()" function
3571 */
3572 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003573f_settabwinvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003574{
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003575 setwinvar(argvars, 1);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003576}
3577
3578/*
3579 * "setwinvar()" function
3580 */
3581 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003582f_setwinvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003583{
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003584 setwinvar(argvars, 0);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003585}
3586
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003587/*
3588 * "setbufvar()" function
3589 */
3590 void
3591f_setbufvar(typval_T *argvars, typval_T *rettv UNUSED)
3592{
3593 buf_T *buf;
3594 char_u *varname, *bufvarname;
3595 typval_T *varp;
3596 char_u nbuf[NUMBUFLEN];
3597
3598 if (check_secure())
3599 return;
3600 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
3601 varname = tv_get_string_chk(&argvars[1]);
3602 buf = tv_get_buf(&argvars[0], FALSE);
3603 varp = &argvars[2];
3604
3605 if (buf != NULL && varname != NULL && varp != NULL)
3606 {
3607 if (*varname == '&')
3608 {
3609 long numval;
3610 char_u *strval;
3611 int error = FALSE;
3612 aco_save_T aco;
3613
3614 // set curbuf to be our buf, temporarily
3615 aucmd_prepbuf(&aco, buf);
3616
3617 ++varname;
3618 numval = (long)tv_get_number_chk(varp, &error);
3619 strval = tv_get_string_buf_chk(varp, nbuf);
3620 if (!error && strval != NULL)
3621 set_option_value(varname, numval, strval, OPT_LOCAL);
3622
3623 // reset notion of buffer
3624 aucmd_restbuf(&aco);
3625 }
3626 else
3627 {
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003628 bufvarname = alloc(STRLEN(varname) + 3);
3629 if (bufvarname != NULL)
3630 {
Bram Moolenaar86015452020-03-29 15:12:15 +02003631 buf_T *save_curbuf = curbuf;
3632
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003633 curbuf = buf;
3634 STRCPY(bufvarname, "b:");
3635 STRCPY(bufvarname + 2, varname);
3636 set_var(bufvarname, varp, TRUE);
3637 vim_free(bufvarname);
3638 curbuf = save_curbuf;
3639 }
3640 }
3641 }
3642}
3643
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003644/*
3645 * Get a callback from "arg". It can be a Funcref or a function name.
3646 * When "arg" is zero return an empty string.
3647 * "cb_name" is not allocated.
3648 * "cb_name" is set to NULL for an invalid argument.
3649 */
3650 callback_T
3651get_callback(typval_T *arg)
3652{
Bram Moolenaar14e579092020-03-07 16:59:25 +01003653 callback_T res;
3654 int r = OK;
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003655
3656 res.cb_free_name = FALSE;
3657 if (arg->v_type == VAR_PARTIAL && arg->vval.v_partial != NULL)
3658 {
3659 res.cb_partial = arg->vval.v_partial;
3660 ++res.cb_partial->pt_refcount;
3661 res.cb_name = partial_name(res.cb_partial);
3662 }
3663 else
3664 {
3665 res.cb_partial = NULL;
Bram Moolenaar14e579092020-03-07 16:59:25 +01003666 if (arg->v_type == VAR_STRING && arg->vval.v_string != NULL
3667 && isdigit(*arg->vval.v_string))
3668 r = FAIL;
3669 else if (arg->v_type == VAR_FUNC || arg->v_type == VAR_STRING)
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003670 {
3671 // Note that we don't make a copy of the string.
3672 res.cb_name = arg->vval.v_string;
3673 func_ref(res.cb_name);
3674 }
3675 else if (arg->v_type == VAR_NUMBER && arg->vval.v_number == 0)
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003676 res.cb_name = (char_u *)"";
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003677 else
Bram Moolenaar14e579092020-03-07 16:59:25 +01003678 r = FAIL;
3679
3680 if (r == FAIL)
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003681 {
3682 emsg(_("E921: Invalid callback argument"));
3683 res.cb_name = NULL;
3684 }
3685 }
3686 return res;
3687}
3688
3689/*
3690 * Copy a callback into a typval_T.
3691 */
3692 void
3693put_callback(callback_T *cb, typval_T *tv)
3694{
3695 if (cb->cb_partial != NULL)
3696 {
3697 tv->v_type = VAR_PARTIAL;
3698 tv->vval.v_partial = cb->cb_partial;
3699 ++tv->vval.v_partial->pt_refcount;
3700 }
3701 else
3702 {
3703 tv->v_type = VAR_FUNC;
3704 tv->vval.v_string = vim_strsave(cb->cb_name);
3705 func_ref(cb->cb_name);
3706 }
3707}
3708
3709/*
3710 * Make a copy of "src" into "dest", allocating the function name if needed,
3711 * without incrementing the refcount.
3712 */
3713 void
3714set_callback(callback_T *dest, callback_T *src)
3715{
3716 if (src->cb_partial == NULL)
3717 {
3718 // just a function name, make a copy
3719 dest->cb_name = vim_strsave(src->cb_name);
3720 dest->cb_free_name = TRUE;
3721 }
3722 else
3723 {
3724 // cb_name is a pointer into cb_partial
3725 dest->cb_name = src->cb_name;
3726 dest->cb_free_name = FALSE;
3727 }
3728 dest->cb_partial = src->cb_partial;
3729}
3730
3731/*
3732 * Unref/free "callback" returned by get_callback() or set_callback().
3733 */
3734 void
3735free_callback(callback_T *callback)
3736{
3737 if (callback->cb_partial != NULL)
3738 {
3739 partial_unref(callback->cb_partial);
3740 callback->cb_partial = NULL;
3741 }
3742 else if (callback->cb_name != NULL)
3743 func_unref(callback->cb_name);
3744 if (callback->cb_free_name)
3745 {
3746 vim_free(callback->cb_name);
3747 callback->cb_free_name = FALSE;
3748 }
3749 callback->cb_name = NULL;
3750}
3751
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003752#endif // FEAT_EVAL