blob: cc4a70f75756082a3439806b5526a5f008cc4488 [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("null", VAR_SPECIAL), VV_RO},
124 {VV_NAME("none", VAR_SPECIAL), VV_RO},
125 {VV_NAME("vim_did_enter", VAR_NUMBER), VV_RO},
126 {VV_NAME("testing", VAR_NUMBER), 0},
127 {VV_NAME("t_number", VAR_NUMBER), VV_RO},
128 {VV_NAME("t_string", VAR_NUMBER), VV_RO},
129 {VV_NAME("t_func", VAR_NUMBER), VV_RO},
130 {VV_NAME("t_list", VAR_NUMBER), VV_RO},
131 {VV_NAME("t_dict", VAR_NUMBER), VV_RO},
132 {VV_NAME("t_float", VAR_NUMBER), VV_RO},
133 {VV_NAME("t_bool", VAR_NUMBER), VV_RO},
134 {VV_NAME("t_none", VAR_NUMBER), VV_RO},
135 {VV_NAME("t_job", VAR_NUMBER), VV_RO},
136 {VV_NAME("t_channel", VAR_NUMBER), VV_RO},
137 {VV_NAME("t_blob", VAR_NUMBER), VV_RO},
138 {VV_NAME("termrfgresp", VAR_STRING), VV_RO},
139 {VV_NAME("termrbgresp", VAR_STRING), VV_RO},
140 {VV_NAME("termu7resp", VAR_STRING), VV_RO},
141 {VV_NAME("termstyleresp", VAR_STRING), VV_RO},
142 {VV_NAME("termblinkresp", VAR_STRING), VV_RO},
143 {VV_NAME("event", VAR_DICT), VV_RO},
144 {VV_NAME("versionlong", VAR_NUMBER), VV_RO},
145 {VV_NAME("echospace", VAR_NUMBER), VV_RO},
Bram Moolenaar69bf6342019-10-29 04:16:57 +0100146 {VV_NAME("argv", VAR_LIST), VV_RO},
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200147};
148
149// shorthand
150#define vv_type vv_di.di_tv.v_type
151#define vv_nr vv_di.di_tv.vval.v_number
152#define vv_float vv_di.di_tv.vval.v_float
153#define vv_str vv_di.di_tv.vval.v_string
154#define vv_list vv_di.di_tv.vval.v_list
155#define vv_dict vv_di.di_tv.vval.v_dict
156#define vv_blob vv_di.di_tv.vval.v_blob
157#define vv_tv vv_di.di_tv
158
159static dictitem_T vimvars_var; // variable used for v:
Bram Moolenaarda6c0332019-09-01 16:01:30 +0200160static dict_T vimvardict; // Dictionary with v: variables
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200161#define vimvarht vimvardict.dv_hashtab
162
163// for VIM_VERSION_ defines
164#include "version.h"
165
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200166static void ex_let_const(exarg_T *eap, int is_const);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100167static char_u *skip_var_one(char_u *arg, int include_type);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200168static void list_glob_vars(int *first);
169static void list_buf_vars(int *first);
170static void list_win_vars(int *first);
171static void list_tab_vars(int *first);
172static char_u *list_arg_vars(exarg_T *eap, char_u *arg, int *first);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100173static 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 +0200174static void ex_unletlock(exarg_T *eap, char_u *argstart, int deep);
175static int do_unlet_var(lval_T *lp, char_u *name_end, int forceit);
176static int do_lock_var(lval_T *lp, char_u *name_end, int deep, int lock);
177static void item_lock(typval_T *tv, int deep, int lock);
Bram Moolenaarda6c0332019-09-01 16:01:30 +0200178static void delete_var(hashtab_T *ht, hashitem_T *hi);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200179static void list_one_var(dictitem_T *v, char *prefix, int *first);
180static void list_one_var_a(char *prefix, char_u *name, int type, char_u *string, int *first);
181
182/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200183 * Initialize global and vim special variables
184 */
185 void
186evalvars_init(void)
187{
188 int i;
189 struct vimvar *p;
190
191 init_var_dict(&globvardict, &globvars_var, VAR_DEF_SCOPE);
192 init_var_dict(&vimvardict, &vimvars_var, VAR_SCOPE);
193 vimvardict.dv_lock = VAR_FIXED;
194 hash_init(&compat_hashtab);
195
196 for (i = 0; i < VV_LEN; ++i)
197 {
198 p = &vimvars[i];
199 if (STRLEN(p->vv_name) > DICTITEM16_KEY_LEN)
200 {
201 iemsg("INTERNAL: name too long, increase size of dictitem16_T");
202 getout(1);
203 }
204 STRCPY(p->vv_di.di_key, p->vv_name);
205 if (p->vv_flags & VV_RO)
206 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
207 else if (p->vv_flags & VV_RO_SBX)
208 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
209 else
210 p->vv_di.di_flags = DI_FLAGS_FIX;
211
212 // add to v: scope dict, unless the value is not always available
213 if (p->vv_type != VAR_UNKNOWN)
214 hash_add(&vimvarht, p->vv_di.di_key);
215 if (p->vv_flags & VV_COMPAT)
216 // add to compat scope dict
217 hash_add(&compat_hashtab, p->vv_di.di_key);
218 }
219 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
220 vimvars[VV_VERSIONLONG].vv_nr = VIM_VERSION_100 * 10000 + highest_patch();
221
222 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
223 set_vim_var_nr(VV_HLSEARCH, 1L);
224 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
225 set_vim_var_list(VV_ERRORS, list_alloc());
226 set_vim_var_dict(VV_EVENT, dict_alloc_lock(VAR_FIXED));
227
228 set_vim_var_nr(VV_FALSE, VVAL_FALSE);
229 set_vim_var_nr(VV_TRUE, VVAL_TRUE);
230 set_vim_var_nr(VV_NONE, VVAL_NONE);
231 set_vim_var_nr(VV_NULL, VVAL_NULL);
232
233 set_vim_var_nr(VV_TYPE_NUMBER, VAR_TYPE_NUMBER);
234 set_vim_var_nr(VV_TYPE_STRING, VAR_TYPE_STRING);
235 set_vim_var_nr(VV_TYPE_FUNC, VAR_TYPE_FUNC);
236 set_vim_var_nr(VV_TYPE_LIST, VAR_TYPE_LIST);
237 set_vim_var_nr(VV_TYPE_DICT, VAR_TYPE_DICT);
238 set_vim_var_nr(VV_TYPE_FLOAT, VAR_TYPE_FLOAT);
239 set_vim_var_nr(VV_TYPE_BOOL, VAR_TYPE_BOOL);
240 set_vim_var_nr(VV_TYPE_NONE, VAR_TYPE_NONE);
241 set_vim_var_nr(VV_TYPE_JOB, VAR_TYPE_JOB);
242 set_vim_var_nr(VV_TYPE_CHANNEL, VAR_TYPE_CHANNEL);
243 set_vim_var_nr(VV_TYPE_BLOB, VAR_TYPE_BLOB);
244
245 set_vim_var_nr(VV_ECHOSPACE, sc_col - 1);
246
247 set_reg_var(0); // default for v:register is not 0 but '"'
248}
249
250#if defined(EXITFREE) || defined(PROTO)
251/*
252 * Free all vim variables information on exit
253 */
254 void
255evalvars_clear(void)
256{
257 int i;
258 struct vimvar *p;
259
260 for (i = 0; i < VV_LEN; ++i)
261 {
262 p = &vimvars[i];
263 if (p->vv_di.di_tv.v_type == VAR_STRING)
264 VIM_CLEAR(p->vv_str);
265 else if (p->vv_di.di_tv.v_type == VAR_LIST)
266 {
267 list_unref(p->vv_list);
268 p->vv_list = NULL;
269 }
270 }
271 hash_clear(&vimvarht);
272 hash_init(&vimvarht); // garbage_collect() will access it
273 hash_clear(&compat_hashtab);
274
275 // global variables
276 vars_clear(&globvarht);
277
Bram Moolenaar7ebcba62020-01-12 17:42:55 +0100278 // Script-local variables. Clear all the variables here.
279 // The scriptvar_T is cleared later in free_scriptnames(), because a
280 // variable in one script might hold a reference to the whole scope of
281 // another script.
282 for (i = 1; i <= script_items.ga_len; ++i)
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200283 vars_clear(&SCRIPT_VARS(i));
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200284}
285#endif
286
287 int
Bram Moolenaarda6c0332019-09-01 16:01:30 +0200288garbage_collect_globvars(int copyID)
289{
290 return set_ref_in_ht(&globvarht, copyID, NULL);
291}
292
293 int
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200294garbage_collect_vimvars(int copyID)
295{
296 return set_ref_in_ht(&vimvarht, copyID, NULL);
297}
298
299 int
300garbage_collect_scriptvars(int copyID)
301{
302 int i;
303 int abort = FALSE;
304
Bram Moolenaar7ebcba62020-01-12 17:42:55 +0100305 for (i = 1; i <= script_items.ga_len; ++i)
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200306 abort = abort || set_ref_in_ht(&SCRIPT_VARS(i), copyID, NULL);
307
308 return abort;
309}
310
311/*
312 * Set an internal variable to a string value. Creates the variable if it does
313 * not already exist.
314 */
315 void
316set_internal_string_var(char_u *name, char_u *value)
317{
318 char_u *val;
319 typval_T *tvp;
320
321 val = vim_strsave(value);
322 if (val != NULL)
323 {
324 tvp = alloc_string_tv(val);
325 if (tvp != NULL)
326 {
327 set_var(name, tvp, FALSE);
328 free_tv(tvp);
329 }
330 }
331}
332
Bram Moolenaarda6c0332019-09-01 16:01:30 +0200333 int
334eval_charconvert(
335 char_u *enc_from,
336 char_u *enc_to,
337 char_u *fname_from,
338 char_u *fname_to)
339{
340 int err = FALSE;
341
342 set_vim_var_string(VV_CC_FROM, enc_from, -1);
343 set_vim_var_string(VV_CC_TO, enc_to, -1);
344 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
345 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
346 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
347 err = TRUE;
348 set_vim_var_string(VV_CC_FROM, NULL, -1);
349 set_vim_var_string(VV_CC_TO, NULL, -1);
350 set_vim_var_string(VV_FNAME_IN, NULL, -1);
351 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
352
353 if (err)
354 return FAIL;
355 return OK;
356}
357
358# if defined(FEAT_POSTSCRIPT) || defined(PROTO)
359 int
360eval_printexpr(char_u *fname, char_u *args)
361{
362 int err = FALSE;
363
364 set_vim_var_string(VV_FNAME_IN, fname, -1);
365 set_vim_var_string(VV_CMDARG, args, -1);
366 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
367 err = TRUE;
368 set_vim_var_string(VV_FNAME_IN, NULL, -1);
369 set_vim_var_string(VV_CMDARG, NULL, -1);
370
371 if (err)
372 {
373 mch_remove(fname);
374 return FAIL;
375 }
376 return OK;
377}
378# endif
379
380# if defined(FEAT_DIFF) || defined(PROTO)
381 void
382eval_diff(
383 char_u *origfile,
384 char_u *newfile,
385 char_u *outfile)
386{
387 int err = FALSE;
388
389 set_vim_var_string(VV_FNAME_IN, origfile, -1);
390 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
391 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
392 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
393 set_vim_var_string(VV_FNAME_IN, NULL, -1);
394 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
395 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
396}
397
398 void
399eval_patch(
400 char_u *origfile,
401 char_u *difffile,
402 char_u *outfile)
403{
404 int err;
405
406 set_vim_var_string(VV_FNAME_IN, origfile, -1);
407 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
408 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
409 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
410 set_vim_var_string(VV_FNAME_IN, NULL, -1);
411 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
412 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
413}
414# endif
415
416#if defined(FEAT_SPELL) || defined(PROTO)
417/*
418 * Evaluate an expression to a list with suggestions.
419 * For the "expr:" part of 'spellsuggest'.
420 * Returns NULL when there is an error.
421 */
422 list_T *
423eval_spell_expr(char_u *badword, char_u *expr)
424{
425 typval_T save_val;
426 typval_T rettv;
427 list_T *list = NULL;
428 char_u *p = skipwhite(expr);
429
430 // Set "v:val" to the bad word.
431 prepare_vimvar(VV_VAL, &save_val);
432 set_vim_var_string(VV_VAL, badword, -1);
433 if (p_verbose == 0)
434 ++emsg_off;
435
436 if (eval1(&p, &rettv, TRUE) == OK)
437 {
438 if (rettv.v_type != VAR_LIST)
439 clear_tv(&rettv);
440 else
441 list = rettv.vval.v_list;
442 }
443
444 if (p_verbose == 0)
445 --emsg_off;
446 clear_tv(get_vim_var_tv(VV_VAL));
447 restore_vimvar(VV_VAL, &save_val);
448
449 return list;
450}
451
452/*
453 * "list" is supposed to contain two items: a word and a number. Return the
454 * word in "pp" and the number as the return value.
455 * Return -1 if anything isn't right.
456 * Used to get the good word and score from the eval_spell_expr() result.
457 */
458 int
459get_spellword(list_T *list, char_u **pp)
460{
461 listitem_T *li;
462
463 li = list->lv_first;
464 if (li == NULL)
465 return -1;
466 *pp = tv_get_string(&li->li_tv);
467
468 li = li->li_next;
469 if (li == NULL)
470 return -1;
471 return (int)tv_get_number(&li->li_tv);
472}
473#endif
474
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200475/*
476 * Prepare v: variable "idx" to be used.
Bram Moolenaar27da7de2019-09-03 17:13:37 +0200477 * Save the current typeval in "save_tv" and clear it.
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200478 * When not used yet add the variable to the v: hashtable.
479 */
480 void
481prepare_vimvar(int idx, typval_T *save_tv)
482{
483 *save_tv = vimvars[idx].vv_tv;
Bram Moolenaar27da7de2019-09-03 17:13:37 +0200484 vimvars[idx].vv_str = NULL; // don't free it now
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200485 if (vimvars[idx].vv_type == VAR_UNKNOWN)
486 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
487}
488
489/*
490 * Restore v: variable "idx" to typeval "save_tv".
Bram Moolenaar27da7de2019-09-03 17:13:37 +0200491 * Note that the v: variable must have been cleared already.
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200492 * When no longer defined, remove the variable from the v: hashtable.
493 */
494 void
495restore_vimvar(int idx, typval_T *save_tv)
496{
497 hashitem_T *hi;
498
499 vimvars[idx].vv_tv = *save_tv;
500 if (vimvars[idx].vv_type == VAR_UNKNOWN)
501 {
502 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
503 if (HASHITEM_EMPTY(hi))
504 internal_error("restore_vimvar()");
505 else
506 hash_remove(&vimvarht, hi);
507 }
508}
509
510/*
511 * List Vim variables.
512 */
513 static void
514list_vim_vars(int *first)
515{
516 list_hashtable_vars(&vimvarht, "v:", FALSE, first);
517}
518
519/*
520 * List script-local variables, if there is a script.
521 */
522 static void
523list_script_vars(int *first)
524{
Bram Moolenaar7ebcba62020-01-12 17:42:55 +0100525 if (current_sctx.sc_sid > 0 && current_sctx.sc_sid <= script_items.ga_len)
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200526 list_hashtable_vars(&SCRIPT_VARS(current_sctx.sc_sid),
527 "s:", FALSE, first);
528}
529
530/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200531 * Get a list of lines from a HERE document. The here document is a list of
532 * lines surrounded by a marker.
533 * cmd << {marker}
534 * {line1}
535 * {line2}
536 * ....
537 * {marker}
538 *
539 * The {marker} is a string. If the optional 'trim' word is supplied before the
540 * marker, then the leading indentation before the lines (matching the
541 * indentation in the 'cmd' line) is stripped.
542 * Returns a List with {lines} or NULL.
543 */
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100544 list_T *
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200545heredoc_get(exarg_T *eap, char_u *cmd)
546{
547 char_u *theline;
548 char_u *marker;
549 list_T *l;
550 char_u *p;
551 int marker_indent_len = 0;
552 int text_indent_len = 0;
553 char_u *text_indent = NULL;
554
555 if (eap->getline == NULL)
556 {
557 emsg(_("E991: cannot use =<< here"));
558 return NULL;
559 }
560
561 // Check for the optional 'trim' word before the marker
562 cmd = skipwhite(cmd);
563 if (STRNCMP(cmd, "trim", 4) == 0 && (cmd[4] == NUL || VIM_ISWHITE(cmd[4])))
564 {
565 cmd = skipwhite(cmd + 4);
566
567 // Trim the indentation from all the lines in the here document.
568 // The amount of indentation trimmed is the same as the indentation of
569 // the first line after the :let command line. To find the end marker
570 // the indent of the :let command line is trimmed.
571 p = *eap->cmdlinep;
572 while (VIM_ISWHITE(*p))
573 {
574 p++;
575 marker_indent_len++;
576 }
577 text_indent_len = -1;
578 }
579
580 // The marker is the next word.
581 if (*cmd != NUL && *cmd != '"')
582 {
583 marker = skipwhite(cmd);
584 p = skiptowhite(marker);
585 if (*skipwhite(p) != NUL && *skipwhite(p) != '"')
586 {
587 emsg(_(e_trailing));
588 return NULL;
589 }
590 *p = NUL;
591 if (vim_islower(*marker))
592 {
593 emsg(_("E221: Marker cannot start with lower case letter"));
594 return NULL;
595 }
596 }
597 else
598 {
599 emsg(_("E172: Missing marker"));
600 return NULL;
601 }
602
603 l = list_alloc();
604 if (l == NULL)
605 return NULL;
606
607 for (;;)
608 {
609 int mi = 0;
610 int ti = 0;
611
612 theline = eap->getline(NUL, eap->cookie, 0, FALSE);
613 if (theline == NULL)
614 {
615 semsg(_("E990: Missing end marker '%s'"), marker);
616 break;
617 }
618
619 // with "trim": skip the indent matching the :let line to find the
620 // marker
621 if (marker_indent_len > 0
622 && STRNCMP(theline, *eap->cmdlinep, marker_indent_len) == 0)
623 mi = marker_indent_len;
624 if (STRCMP(marker, theline + mi) == 0)
625 {
626 vim_free(theline);
627 break;
628 }
629
630 if (text_indent_len == -1 && *theline != NUL)
631 {
632 // set the text indent from the first line.
633 p = theline;
634 text_indent_len = 0;
635 while (VIM_ISWHITE(*p))
636 {
637 p++;
638 text_indent_len++;
639 }
640 text_indent = vim_strnsave(theline, text_indent_len);
641 }
642 // with "trim": skip the indent matching the first line
643 if (text_indent != NULL)
644 for (ti = 0; ti < text_indent_len; ++ti)
645 if (theline[ti] != text_indent[ti])
646 break;
647
648 if (list_append_string(l, theline + ti, -1) == FAIL)
649 break;
650 vim_free(theline);
651 }
652 vim_free(text_indent);
653
654 return l;
655}
656
657/*
658 * ":let" list all variable values
659 * ":let var1 var2" list variable values
660 * ":let var = expr" assignment command.
661 * ":let var += expr" assignment command.
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 [var1, var2] = expr" unpack list.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100669 * ":let var =<< ..." heredoc
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200670 */
671 void
672ex_let(exarg_T *eap)
673{
674 ex_let_const(eap, FALSE);
675}
676
677/*
678 * ":const" list all variable values
679 * ":const var1 var2" list variable values
680 * ":const var = expr" assignment command.
681 * ":const [var1, var2] = expr" unpack list.
682 */
683 void
684ex_const(exarg_T *eap)
685{
686 ex_let_const(eap, TRUE);
687}
688
689 static void
690ex_let_const(exarg_T *eap, int is_const)
691{
692 char_u *arg = eap->arg;
693 char_u *expr = NULL;
694 typval_T rettv;
695 int i;
696 int var_count = 0;
697 int semicolon = 0;
698 char_u op[2];
699 char_u *argend;
700 int first = TRUE;
701 int concat;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100702 int flags = is_const ? LET_IS_CONST : 0;
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200703
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100704 // detect Vim9 assignment without ":let" or ":const"
705 if (eap->arg == eap->cmd)
706 flags |= LET_NO_COMMAND;
707
708 argend = skip_var_list(arg, TRUE, &var_count, &semicolon);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200709 if (argend == NULL)
710 return;
711 if (argend > arg && argend[-1] == '.') // for var.='str'
712 --argend;
713 expr = skipwhite(argend);
714 concat = expr[0] == '.'
715 && ((expr[1] == '=' && current_sctx.sc_version < 2)
716 || (expr[1] == '.' && expr[2] == '='));
717 if (*expr != '=' && !((vim_strchr((char_u *)"+-*/%", *expr) != NULL
718 && expr[1] == '=') || concat))
719 {
720 // ":let" without "=": list variables
721 if (*arg == '[')
722 emsg(_(e_invarg));
723 else if (expr[0] == '.')
724 emsg(_("E985: .= is not supported with script version 2"));
725 else if (!ends_excmd(*arg))
726 // ":let var1 var2"
727 arg = list_arg_vars(eap, arg, &first);
728 else if (!eap->skip)
729 {
730 // ":let"
731 list_glob_vars(&first);
732 list_buf_vars(&first);
733 list_win_vars(&first);
734 list_tab_vars(&first);
735 list_script_vars(&first);
736 list_func_vars(&first);
737 list_vim_vars(&first);
738 }
739 eap->nextcmd = check_nextcmd(arg);
740 }
741 else if (expr[0] == '=' && expr[1] == '<' && expr[2] == '<')
742 {
743 list_T *l;
744
745 // HERE document
746 l = heredoc_get(eap, expr + 3);
747 if (l != NULL)
748 {
749 rettv_list_set(&rettv, l);
Bram Moolenaarb1ba9ab2019-10-16 23:34:42 +0200750 if (!eap->skip)
751 {
752 op[0] = '=';
753 op[1] = NUL;
754 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100755 flags, op);
Bram Moolenaarb1ba9ab2019-10-16 23:34:42 +0200756 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200757 clear_tv(&rettv);
758 }
759 }
760 else
761 {
762 op[0] = '=';
763 op[1] = NUL;
764 if (*expr != '=')
765 {
766 if (vim_strchr((char_u *)"+-*/%.", *expr) != NULL)
767 {
768 op[0] = *expr; // +=, -=, *=, /=, %= or .=
769 if (expr[0] == '.' && expr[1] == '.') // ..=
770 ++expr;
771 }
772 expr = skipwhite(expr + 2);
773 }
774 else
775 expr = skipwhite(expr + 1);
776
777 if (eap->skip)
778 ++emsg_skip;
779 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
780 if (eap->skip)
781 {
782 if (i != FAIL)
783 clear_tv(&rettv);
784 --emsg_skip;
785 }
786 else if (i != FAIL)
787 {
788 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100789 flags, op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200790 clear_tv(&rettv);
791 }
792 }
793}
794
795/*
796 * Assign the typevalue "tv" to the variable or variables at "arg_start".
797 * Handles both "var" with any type and "[var, var; var]" with a list type.
798 * When "op" is not NULL it points to a string with characters that
799 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
800 * or concatenate.
801 * Returns OK or FAIL;
802 */
803 int
804ex_let_vars(
805 char_u *arg_start,
806 typval_T *tv,
807 int copy, // copy values from "tv", don't move
808 int semicolon, // from skip_var_list()
809 int var_count, // from skip_var_list()
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100810 int flags, // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200811 char_u *op)
812{
813 char_u *arg = arg_start;
814 list_T *l;
815 int i;
816 listitem_T *item;
817 typval_T ltv;
818
819 if (*arg != '[')
820 {
821 // ":let var = expr" or ":for var in list"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100822 if (ex_let_one(arg, tv, copy, flags, op, op) == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200823 return FAIL;
824 return OK;
825 }
826
827 // ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
828 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
829 {
830 emsg(_(e_listreq));
831 return FAIL;
832 }
833
834 i = list_len(l);
835 if (semicolon == 0 && var_count < i)
836 {
837 emsg(_("E687: Less targets than List items"));
838 return FAIL;
839 }
840 if (var_count - semicolon > i)
841 {
842 emsg(_("E688: More targets than List items"));
843 return FAIL;
844 }
845
Bram Moolenaar50985eb2020-01-27 22:09:39 +0100846 range_list_materialize(l);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200847 item = l->lv_first;
848 while (*arg != ']')
849 {
850 arg = skipwhite(arg + 1);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100851 arg = ex_let_one(arg, &item->li_tv, TRUE, flags, (char_u *)",;]", op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200852 item = item->li_next;
853 if (arg == NULL)
854 return FAIL;
855
856 arg = skipwhite(arg);
857 if (*arg == ';')
858 {
859 // Put the rest of the list (may be empty) in the var after ';'.
860 // Create a new list for this.
861 l = list_alloc();
862 if (l == NULL)
863 return FAIL;
864 while (item != NULL)
865 {
866 list_append_tv(l, &item->li_tv);
867 item = item->li_next;
868 }
869
870 ltv.v_type = VAR_LIST;
871 ltv.v_lock = 0;
872 ltv.vval.v_list = l;
873 l->lv_refcount = 1;
874
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100875 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE, flags,
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200876 (char_u *)"]", op);
877 clear_tv(&ltv);
878 if (arg == NULL)
879 return FAIL;
880 break;
881 }
882 else if (*arg != ',' && *arg != ']')
883 {
884 internal_error("ex_let_vars()");
885 return FAIL;
886 }
887 }
888
889 return OK;
890}
891
892/*
893 * Skip over assignable variable "var" or list of variables "[var, var]".
894 * Used for ":let varvar = expr" and ":for varvar in expr".
895 * For "[var, var]" increment "*var_count" for each variable.
896 * for "[var, var; var]" set "semicolon".
897 * Return NULL for an error.
898 */
899 char_u *
900skip_var_list(
901 char_u *arg,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100902 int include_type,
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200903 int *var_count,
904 int *semicolon)
905{
906 char_u *p, *s;
907
908 if (*arg == '[')
909 {
910 // "[var, var]": find the matching ']'.
911 p = arg;
912 for (;;)
913 {
914 p = skipwhite(p + 1); // skip whites after '[', ';' or ','
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100915 s = skip_var_one(p, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200916 if (s == p)
917 {
918 semsg(_(e_invarg2), p);
919 return NULL;
920 }
921 ++*var_count;
922
923 p = skipwhite(s);
924 if (*p == ']')
925 break;
926 else if (*p == ';')
927 {
928 if (*semicolon == 1)
929 {
930 emsg(_("Double ; in list of variables"));
931 return NULL;
932 }
933 *semicolon = 1;
934 }
935 else if (*p != ',')
936 {
937 semsg(_(e_invarg2), p);
938 return NULL;
939 }
940 }
941 return p + 1;
942 }
943 else
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100944 return skip_var_one(arg, include_type);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200945}
946
947/*
948 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
949 * l[idx].
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100950 * In Vim9 script also skip over ": type" if "include_type" is TRUE.
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200951 */
952 static char_u *
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100953skip_var_one(char_u *arg, int include_type)
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200954{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100955 char_u *end;
956
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200957 if (*arg == '@' && arg[1] != NUL)
958 return arg + 2;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100959 end = find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200960 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100961 if (include_type && current_sctx.sc_version == SCRIPT_VERSION_VIM9
962 && *end == ':')
963 {
964 end = skip_type(skipwhite(end + 1));
965 }
966 return end;
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200967}
968
969/*
970 * List variables for hashtab "ht" with prefix "prefix".
971 * If "empty" is TRUE also list NULL strings as empty strings.
972 */
973 void
974list_hashtable_vars(
975 hashtab_T *ht,
976 char *prefix,
977 int empty,
978 int *first)
979{
980 hashitem_T *hi;
981 dictitem_T *di;
982 int todo;
983 char_u buf[IOSIZE];
984
985 todo = (int)ht->ht_used;
986 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
987 {
988 if (!HASHITEM_EMPTY(hi))
989 {
990 --todo;
991 di = HI2DI(hi);
992
993 // apply :filter /pat/ to variable name
994 vim_strncpy((char_u *)buf, (char_u *)prefix, IOSIZE - 1);
995 vim_strcat((char_u *)buf, di->di_key, IOSIZE);
996 if (message_filtered(buf))
997 continue;
998
999 if (empty || di->di_tv.v_type != VAR_STRING
1000 || di->di_tv.vval.v_string != NULL)
1001 list_one_var(di, prefix, first);
1002 }
1003 }
1004}
1005
1006/*
1007 * List global variables.
1008 */
1009 static void
1010list_glob_vars(int *first)
1011{
1012 list_hashtable_vars(&globvarht, "", TRUE, first);
1013}
1014
1015/*
1016 * List buffer variables.
1017 */
1018 static void
1019list_buf_vars(int *first)
1020{
1021 list_hashtable_vars(&curbuf->b_vars->dv_hashtab, "b:", TRUE, first);
1022}
1023
1024/*
1025 * List window variables.
1026 */
1027 static void
1028list_win_vars(int *first)
1029{
1030 list_hashtable_vars(&curwin->w_vars->dv_hashtab, "w:", TRUE, first);
1031}
1032
1033/*
1034 * List tab page variables.
1035 */
1036 static void
1037list_tab_vars(int *first)
1038{
1039 list_hashtable_vars(&curtab->tp_vars->dv_hashtab, "t:", TRUE, first);
1040}
1041
1042/*
1043 * List variables in "arg".
1044 */
1045 static char_u *
1046list_arg_vars(exarg_T *eap, char_u *arg, int *first)
1047{
1048 int error = FALSE;
1049 int len;
1050 char_u *name;
1051 char_u *name_start;
1052 char_u *arg_subsc;
1053 char_u *tofree;
1054 typval_T tv;
1055
1056 while (!ends_excmd(*arg) && !got_int)
1057 {
1058 if (error || eap->skip)
1059 {
1060 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1061 if (!VIM_ISWHITE(*arg) && !ends_excmd(*arg))
1062 {
1063 emsg_severe = TRUE;
1064 emsg(_(e_trailing));
1065 break;
1066 }
1067 }
1068 else
1069 {
1070 // get_name_len() takes care of expanding curly braces
1071 name_start = name = arg;
1072 len = get_name_len(&arg, &tofree, TRUE, TRUE);
1073 if (len <= 0)
1074 {
1075 // This is mainly to keep test 49 working: when expanding
1076 // curly braces fails overrule the exception error message.
1077 if (len < 0 && !aborting())
1078 {
1079 emsg_severe = TRUE;
1080 semsg(_(e_invarg2), arg);
1081 break;
1082 }
1083 error = TRUE;
1084 }
1085 else
1086 {
1087 if (tofree != NULL)
1088 name = tofree;
1089 if (get_var_tv(name, len, &tv, NULL, TRUE, FALSE) == FAIL)
1090 error = TRUE;
1091 else
1092 {
1093 // handle d.key, l[idx], f(expr)
1094 arg_subsc = arg;
1095 if (handle_subscript(&arg, &tv, TRUE, TRUE,
1096 name, &name) == FAIL)
1097 error = TRUE;
1098 else
1099 {
1100 if (arg == arg_subsc && len == 2 && name[1] == ':')
1101 {
1102 switch (*name)
1103 {
1104 case 'g': list_glob_vars(first); break;
1105 case 'b': list_buf_vars(first); break;
1106 case 'w': list_win_vars(first); break;
1107 case 't': list_tab_vars(first); break;
1108 case 'v': list_vim_vars(first); break;
1109 case 's': list_script_vars(first); break;
1110 case 'l': list_func_vars(first); break;
1111 default:
1112 semsg(_("E738: Can't list variables for %s"), name);
1113 }
1114 }
1115 else
1116 {
1117 char_u numbuf[NUMBUFLEN];
1118 char_u *tf;
1119 int c;
1120 char_u *s;
1121
1122 s = echo_string(&tv, &tf, numbuf, 0);
1123 c = *arg;
1124 *arg = NUL;
1125 list_one_var_a("",
1126 arg == arg_subsc ? name : name_start,
1127 tv.v_type,
1128 s == NULL ? (char_u *)"" : s,
1129 first);
1130 *arg = c;
1131 vim_free(tf);
1132 }
1133 clear_tv(&tv);
1134 }
1135 }
1136 }
1137
1138 vim_free(tofree);
1139 }
1140
1141 arg = skipwhite(arg);
1142 }
1143
1144 return arg;
1145}
1146
1147/*
1148 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
1149 * Returns a pointer to the char just after the var name.
1150 * Returns NULL if there is an error.
1151 */
1152 static char_u *
1153ex_let_one(
1154 char_u *arg, // points to variable name
1155 typval_T *tv, // value to assign to variable
1156 int copy, // copy value from "tv"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001157 int flags, // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001158 char_u *endchars, // valid chars after variable name or NULL
1159 char_u *op) // "+", "-", "." or NULL
1160{
1161 int c1;
1162 char_u *name;
1163 char_u *p;
1164 char_u *arg_end = NULL;
1165 int len;
1166 int opt_flags;
1167 char_u *tofree = NULL;
1168
1169 // ":let $VAR = expr": Set environment variable.
1170 if (*arg == '$')
1171 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001172 if (flags & LET_IS_CONST)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001173 {
1174 emsg(_("E996: Cannot lock an environment variable"));
1175 return NULL;
1176 }
1177 // Find the end of the name.
1178 ++arg;
1179 name = arg;
1180 len = get_env_len(&arg);
1181 if (len == 0)
1182 semsg(_(e_invarg2), name - 1);
1183 else
1184 {
1185 if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL)
1186 semsg(_(e_letwrong), op);
1187 else if (endchars != NULL
1188 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
1189 emsg(_(e_letunexp));
1190 else if (!check_secure())
1191 {
1192 c1 = name[len];
1193 name[len] = NUL;
1194 p = tv_get_string_chk(tv);
1195 if (p != NULL && op != NULL && *op == '.')
1196 {
1197 int mustfree = FALSE;
1198 char_u *s = vim_getenv(name, &mustfree);
1199
1200 if (s != NULL)
1201 {
1202 p = tofree = concat_str(s, p);
1203 if (mustfree)
1204 vim_free(s);
1205 }
1206 }
1207 if (p != NULL)
1208 {
1209 vim_setenv(name, p);
1210 if (STRICMP(name, "HOME") == 0)
1211 init_homedir();
1212 else if (didset_vim && STRICMP(name, "VIM") == 0)
1213 didset_vim = FALSE;
1214 else if (didset_vimruntime
1215 && STRICMP(name, "VIMRUNTIME") == 0)
1216 didset_vimruntime = FALSE;
1217 arg_end = arg;
1218 }
1219 name[len] = c1;
1220 vim_free(tofree);
1221 }
1222 }
1223 }
1224
1225 // ":let &option = expr": Set option value.
1226 // ":let &l:option = expr": Set local option value.
1227 // ":let &g:option = expr": Set global option value.
1228 else if (*arg == '&')
1229 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001230 if (flags & LET_IS_CONST)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001231 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001232 emsg(_(e_const_option));
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001233 return NULL;
1234 }
1235 // Find the end of the name.
1236 p = find_option_end(&arg, &opt_flags);
1237 if (p == NULL || (endchars != NULL
1238 && vim_strchr(endchars, *skipwhite(p)) == NULL))
1239 emsg(_(e_letunexp));
1240 else
1241 {
1242 long n;
1243 int opt_type;
1244 long numval;
1245 char_u *stringval = NULL;
1246 char_u *s;
1247
1248 c1 = *p;
1249 *p = NUL;
1250
1251 n = (long)tv_get_number(tv);
1252 s = tv_get_string_chk(tv); // != NULL if number or string
1253 if (s != NULL && op != NULL && *op != '=')
1254 {
1255 opt_type = get_option_value(arg, &numval,
1256 &stringval, opt_flags);
1257 if ((opt_type == 1 && *op == '.')
1258 || (opt_type == 0 && *op != '.'))
1259 {
1260 semsg(_(e_letwrong), op);
1261 s = NULL; // don't set the value
1262 }
1263 else
1264 {
1265 if (opt_type == 1) // number
1266 {
1267 switch (*op)
1268 {
1269 case '+': n = numval + n; break;
1270 case '-': n = numval - n; break;
1271 case '*': n = numval * n; break;
1272 case '/': n = (long)num_divide(numval, n); break;
1273 case '%': n = (long)num_modulus(numval, n); break;
1274 }
1275 }
1276 else if (opt_type == 0 && stringval != NULL) // string
1277 {
1278 s = concat_str(stringval, s);
1279 vim_free(stringval);
1280 stringval = s;
1281 }
1282 }
1283 }
1284 if (s != NULL)
1285 {
1286 set_option_value(arg, n, s, opt_flags);
1287 arg_end = p;
1288 }
1289 *p = c1;
1290 vim_free(stringval);
1291 }
1292 }
1293
1294 // ":let @r = expr": Set register contents.
1295 else if (*arg == '@')
1296 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001297 if (flags & LET_IS_CONST)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001298 {
1299 emsg(_("E996: Cannot lock a register"));
1300 return NULL;
1301 }
1302 ++arg;
1303 if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL)
1304 semsg(_(e_letwrong), op);
1305 else if (endchars != NULL
1306 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
1307 emsg(_(e_letunexp));
1308 else
1309 {
1310 char_u *ptofree = NULL;
1311 char_u *s;
1312
1313 p = tv_get_string_chk(tv);
1314 if (p != NULL && op != NULL && *op == '.')
1315 {
1316 s = get_reg_contents(*arg == '@' ? '"' : *arg, GREG_EXPR_SRC);
1317 if (s != NULL)
1318 {
1319 p = ptofree = concat_str(s, p);
1320 vim_free(s);
1321 }
1322 }
1323 if (p != NULL)
1324 {
1325 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
1326 arg_end = arg + 1;
1327 }
1328 vim_free(ptofree);
1329 }
1330 }
1331
1332 // ":let var = expr": Set internal variable.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001333 // ":let var: type = expr": Set internal variable with type.
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001334 // ":let {expr} = expr": Idem, name made with curly braces
1335 else if (eval_isnamec1(*arg) || *arg == '{')
1336 {
1337 lval_T lv;
1338
1339 p = get_lval(arg, tv, &lv, FALSE, FALSE, 0, FNE_CHECK_START);
1340 if (p != NULL && lv.ll_name != NULL)
1341 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001342 if (endchars != NULL && vim_strchr(endchars,
1343 *skipwhite(lv.ll_name_end)) == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001344 emsg(_(e_letunexp));
1345 else
1346 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001347 set_var_lval(&lv, p, tv, copy, flags, op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001348 arg_end = p;
1349 }
1350 }
1351 clear_lval(&lv);
1352 }
1353
1354 else
1355 semsg(_(e_invarg2), arg);
1356
1357 return arg_end;
1358}
1359
1360/*
1361 * ":unlet[!] var1 ... " command.
1362 */
1363 void
1364ex_unlet(exarg_T *eap)
1365{
1366 ex_unletlock(eap, eap->arg, 0);
1367}
1368
1369/*
1370 * ":lockvar" and ":unlockvar" commands
1371 */
1372 void
1373ex_lockvar(exarg_T *eap)
1374{
1375 char_u *arg = eap->arg;
1376 int deep = 2;
1377
1378 if (eap->forceit)
1379 deep = -1;
1380 else if (vim_isdigit(*arg))
1381 {
1382 deep = getdigits(&arg);
1383 arg = skipwhite(arg);
1384 }
1385
1386 ex_unletlock(eap, arg, deep);
1387}
1388
1389/*
1390 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
1391 */
1392 static void
1393ex_unletlock(
1394 exarg_T *eap,
1395 char_u *argstart,
1396 int deep)
1397{
1398 char_u *arg = argstart;
1399 char_u *name_end;
1400 int error = FALSE;
1401 lval_T lv;
1402
1403 do
1404 {
1405 if (*arg == '$')
1406 {
1407 char_u *name = ++arg;
1408
1409 if (get_env_len(&arg) == 0)
1410 {
1411 semsg(_(e_invarg2), name - 1);
1412 return;
1413 }
1414 vim_unsetenv(name);
1415 arg = skipwhite(arg);
1416 continue;
1417 }
1418
1419 // Parse the name and find the end.
1420 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, 0,
1421 FNE_CHECK_START);
1422 if (lv.ll_name == NULL)
1423 error = TRUE; // error but continue parsing
1424 if (name_end == NULL || (!VIM_ISWHITE(*name_end)
1425 && !ends_excmd(*name_end)))
1426 {
1427 if (name_end != NULL)
1428 {
1429 emsg_severe = TRUE;
1430 emsg(_(e_trailing));
1431 }
1432 if (!(eap->skip || error))
1433 clear_lval(&lv);
1434 break;
1435 }
1436
1437 if (!error && !eap->skip)
1438 {
1439 if (eap->cmdidx == CMD_unlet)
1440 {
1441 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
1442 error = TRUE;
1443 }
1444 else
1445 {
1446 if (do_lock_var(&lv, name_end, deep,
1447 eap->cmdidx == CMD_lockvar) == FAIL)
1448 error = TRUE;
1449 }
1450 }
1451
1452 if (!eap->skip)
1453 clear_lval(&lv);
1454
1455 arg = skipwhite(name_end);
1456 } while (!ends_excmd(*arg));
1457
1458 eap->nextcmd = check_nextcmd(arg);
1459}
1460
1461 static int
1462do_unlet_var(
1463 lval_T *lp,
1464 char_u *name_end,
1465 int forceit)
1466{
1467 int ret = OK;
1468 int cc;
1469
1470 if (lp->ll_tv == NULL)
1471 {
1472 cc = *name_end;
1473 *name_end = NUL;
1474
1475 // Normal name or expanded name.
1476 if (do_unlet(lp->ll_name, forceit) == FAIL)
1477 ret = FAIL;
1478 *name_end = cc;
1479 }
1480 else if ((lp->ll_list != NULL
1481 && var_check_lock(lp->ll_list->lv_lock, lp->ll_name, FALSE))
1482 || (lp->ll_dict != NULL
1483 && var_check_lock(lp->ll_dict->dv_lock, lp->ll_name, FALSE)))
1484 return FAIL;
1485 else if (lp->ll_range)
1486 {
1487 listitem_T *li;
1488 listitem_T *ll_li = lp->ll_li;
1489 int ll_n1 = lp->ll_n1;
1490
1491 while (ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= ll_n1))
1492 {
1493 li = ll_li->li_next;
1494 if (var_check_lock(ll_li->li_tv.v_lock, lp->ll_name, FALSE))
1495 return FAIL;
1496 ll_li = li;
1497 ++ll_n1;
1498 }
1499
1500 // Delete a range of List items.
1501 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
1502 {
1503 li = lp->ll_li->li_next;
1504 listitem_remove(lp->ll_list, lp->ll_li);
1505 lp->ll_li = li;
1506 ++lp->ll_n1;
1507 }
1508 }
1509 else
1510 {
1511 if (lp->ll_list != NULL)
1512 // unlet a List item.
1513 listitem_remove(lp->ll_list, lp->ll_li);
1514 else
1515 // unlet a Dictionary item.
1516 dictitem_remove(lp->ll_dict, lp->ll_di);
1517 }
1518
1519 return ret;
1520}
1521
1522/*
1523 * "unlet" a variable. Return OK if it existed, FAIL if not.
1524 * When "forceit" is TRUE don't complain if the variable doesn't exist.
1525 */
1526 int
1527do_unlet(char_u *name, int forceit)
1528{
1529 hashtab_T *ht;
1530 hashitem_T *hi;
1531 char_u *varname;
1532 dict_T *d;
1533 dictitem_T *di;
1534
1535 ht = find_var_ht(name, &varname);
1536 if (ht != NULL && *varname != NUL)
1537 {
1538 d = get_current_funccal_dict(ht);
1539 if (d == NULL)
1540 {
1541 if (ht == &globvarht)
1542 d = &globvardict;
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001543 else if (ht == &compat_hashtab)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001544 d = &vimvardict;
1545 else
1546 {
1547 di = find_var_in_ht(ht, *name, (char_u *)"", FALSE);
1548 d = di == NULL ? NULL : di->di_tv.vval.v_dict;
1549 }
1550 if (d == NULL)
1551 {
1552 internal_error("do_unlet()");
1553 return FAIL;
1554 }
1555 }
1556 hi = hash_find(ht, varname);
1557 if (HASHITEM_EMPTY(hi))
1558 hi = find_hi_in_scoped_ht(name, &ht);
1559 if (hi != NULL && !HASHITEM_EMPTY(hi))
1560 {
1561 di = HI2DI(hi);
1562 if (var_check_fixed(di->di_flags, name, FALSE)
1563 || var_check_ro(di->di_flags, name, FALSE)
1564 || var_check_lock(d->dv_lock, name, FALSE))
1565 return FAIL;
1566
1567 delete_var(ht, hi);
1568 return OK;
1569 }
1570 }
1571 if (forceit)
1572 return OK;
1573 semsg(_("E108: No such variable: \"%s\""), name);
1574 return FAIL;
1575}
1576
1577/*
1578 * Lock or unlock variable indicated by "lp".
1579 * "deep" is the levels to go (-1 for unlimited);
1580 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
1581 */
1582 static int
1583do_lock_var(
1584 lval_T *lp,
1585 char_u *name_end,
1586 int deep,
1587 int lock)
1588{
1589 int ret = OK;
1590 int cc;
1591 dictitem_T *di;
1592
1593 if (deep == 0) // nothing to do
1594 return OK;
1595
1596 if (lp->ll_tv == NULL)
1597 {
1598 cc = *name_end;
1599 *name_end = NUL;
1600
1601 // Normal name or expanded name.
1602 di = find_var(lp->ll_name, NULL, TRUE);
1603 if (di == NULL)
1604 ret = FAIL;
1605 else if ((di->di_flags & DI_FLAGS_FIX)
1606 && di->di_tv.v_type != VAR_DICT
1607 && di->di_tv.v_type != VAR_LIST)
1608 // For historic reasons this error is not given for a list or dict.
1609 // E.g., the b: dict could be locked/unlocked.
1610 semsg(_("E940: Cannot lock or unlock variable %s"), lp->ll_name);
1611 else
1612 {
1613 if (lock)
1614 di->di_flags |= DI_FLAGS_LOCK;
1615 else
1616 di->di_flags &= ~DI_FLAGS_LOCK;
1617 item_lock(&di->di_tv, deep, lock);
1618 }
1619 *name_end = cc;
1620 }
1621 else if (lp->ll_range)
1622 {
1623 listitem_T *li = lp->ll_li;
1624
1625 // (un)lock a range of List items.
1626 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
1627 {
1628 item_lock(&li->li_tv, deep, lock);
1629 li = li->li_next;
1630 ++lp->ll_n1;
1631 }
1632 }
1633 else if (lp->ll_list != NULL)
1634 // (un)lock a List item.
1635 item_lock(&lp->ll_li->li_tv, deep, lock);
1636 else
1637 // (un)lock a Dictionary item.
1638 item_lock(&lp->ll_di->di_tv, deep, lock);
1639
1640 return ret;
1641}
1642
1643/*
1644 * Lock or unlock an item. "deep" is nr of levels to go.
1645 */
1646 static void
1647item_lock(typval_T *tv, int deep, int lock)
1648{
1649 static int recurse = 0;
1650 list_T *l;
1651 listitem_T *li;
1652 dict_T *d;
1653 blob_T *b;
1654 hashitem_T *hi;
1655 int todo;
1656
1657 if (recurse >= DICT_MAXNEST)
1658 {
1659 emsg(_("E743: variable nested too deep for (un)lock"));
1660 return;
1661 }
1662 if (deep == 0)
1663 return;
1664 ++recurse;
1665
1666 // lock/unlock the item itself
1667 if (lock)
1668 tv->v_lock |= VAR_LOCKED;
1669 else
1670 tv->v_lock &= ~VAR_LOCKED;
1671
1672 switch (tv->v_type)
1673 {
1674 case VAR_UNKNOWN:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001675 case VAR_VOID:
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001676 case VAR_NUMBER:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001677 case VAR_BOOL:
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001678 case VAR_STRING:
1679 case VAR_FUNC:
1680 case VAR_PARTIAL:
1681 case VAR_FLOAT:
1682 case VAR_SPECIAL:
1683 case VAR_JOB:
1684 case VAR_CHANNEL:
1685 break;
1686
1687 case VAR_BLOB:
1688 if ((b = tv->vval.v_blob) != NULL)
1689 {
1690 if (lock)
1691 b->bv_lock |= VAR_LOCKED;
1692 else
1693 b->bv_lock &= ~VAR_LOCKED;
1694 }
1695 break;
1696 case VAR_LIST:
1697 if ((l = tv->vval.v_list) != NULL)
1698 {
1699 if (lock)
1700 l->lv_lock |= VAR_LOCKED;
1701 else
1702 l->lv_lock &= ~VAR_LOCKED;
Bram Moolenaar50985eb2020-01-27 22:09:39 +01001703 if ((deep < 0 || deep > 1) && l->lv_first != &range_list_item)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001704 // recursive: lock/unlock the items the List contains
1705 for (li = l->lv_first; li != NULL; li = li->li_next)
1706 item_lock(&li->li_tv, deep - 1, lock);
1707 }
1708 break;
1709 case VAR_DICT:
1710 if ((d = tv->vval.v_dict) != NULL)
1711 {
1712 if (lock)
1713 d->dv_lock |= VAR_LOCKED;
1714 else
1715 d->dv_lock &= ~VAR_LOCKED;
1716 if (deep < 0 || deep > 1)
1717 {
1718 // recursive: lock/unlock the items the List contains
1719 todo = (int)d->dv_hashtab.ht_used;
1720 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
1721 {
1722 if (!HASHITEM_EMPTY(hi))
1723 {
1724 --todo;
1725 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
1726 }
1727 }
1728 }
1729 }
1730 }
1731 --recurse;
1732}
1733
Bram Moolenaarda6c0332019-09-01 16:01:30 +02001734#if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
1735/*
1736 * Delete all "menutrans_" variables.
1737 */
1738 void
1739del_menutrans_vars(void)
1740{
1741 hashitem_T *hi;
1742 int todo;
1743
1744 hash_lock(&globvarht);
1745 todo = (int)globvarht.ht_used;
1746 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
1747 {
1748 if (!HASHITEM_EMPTY(hi))
1749 {
1750 --todo;
1751 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
1752 delete_var(&globvarht, hi);
1753 }
1754 }
1755 hash_unlock(&globvarht);
1756}
1757#endif
1758
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001759/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001760 * Local string buffer for the next two functions to store a variable name
1761 * with its prefix. Allocated in cat_prefix_varname(), freed later in
1762 * get_user_var_name().
1763 */
1764
1765static char_u *varnamebuf = NULL;
1766static int varnamebuflen = 0;
1767
1768/*
1769 * Function to concatenate a prefix and a variable name.
1770 */
1771 static char_u *
1772cat_prefix_varname(int prefix, char_u *name)
1773{
1774 int len;
1775
1776 len = (int)STRLEN(name) + 3;
1777 if (len > varnamebuflen)
1778 {
1779 vim_free(varnamebuf);
Bram Moolenaar8d71b542019-08-30 15:46:30 +02001780 len += 10; // some additional space
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001781 varnamebuf = alloc(len);
1782 if (varnamebuf == NULL)
1783 {
1784 varnamebuflen = 0;
1785 return NULL;
1786 }
1787 varnamebuflen = len;
1788 }
1789 *varnamebuf = prefix;
1790 varnamebuf[1] = ':';
1791 STRCPY(varnamebuf + 2, name);
1792 return varnamebuf;
1793}
1794
1795/*
1796 * Function given to ExpandGeneric() to obtain the list of user defined
1797 * (global/buffer/window/built-in) variable names.
1798 */
1799 char_u *
1800get_user_var_name(expand_T *xp, int idx)
1801{
1802 static long_u gdone;
1803 static long_u bdone;
1804 static long_u wdone;
1805 static long_u tdone;
1806 static int vidx;
1807 static hashitem_T *hi;
1808 hashtab_T *ht;
1809
1810 if (idx == 0)
1811 {
1812 gdone = bdone = wdone = vidx = 0;
1813 tdone = 0;
1814 }
1815
1816 // Global variables
1817 if (gdone < globvarht.ht_used)
1818 {
1819 if (gdone++ == 0)
1820 hi = globvarht.ht_array;
1821 else
1822 ++hi;
1823 while (HASHITEM_EMPTY(hi))
1824 ++hi;
1825 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
1826 return cat_prefix_varname('g', hi->hi_key);
1827 return hi->hi_key;
1828 }
1829
1830 // b: variables
1831 ht = &curbuf->b_vars->dv_hashtab;
1832 if (bdone < ht->ht_used)
1833 {
1834 if (bdone++ == 0)
1835 hi = ht->ht_array;
1836 else
1837 ++hi;
1838 while (HASHITEM_EMPTY(hi))
1839 ++hi;
1840 return cat_prefix_varname('b', hi->hi_key);
1841 }
1842
1843 // w: variables
1844 ht = &curwin->w_vars->dv_hashtab;
1845 if (wdone < ht->ht_used)
1846 {
1847 if (wdone++ == 0)
1848 hi = ht->ht_array;
1849 else
1850 ++hi;
1851 while (HASHITEM_EMPTY(hi))
1852 ++hi;
1853 return cat_prefix_varname('w', hi->hi_key);
1854 }
1855
1856 // t: variables
1857 ht = &curtab->tp_vars->dv_hashtab;
1858 if (tdone < ht->ht_used)
1859 {
1860 if (tdone++ == 0)
1861 hi = ht->ht_array;
1862 else
1863 ++hi;
1864 while (HASHITEM_EMPTY(hi))
1865 ++hi;
1866 return cat_prefix_varname('t', hi->hi_key);
1867 }
1868
1869 // v: variables
1870 if (vidx < VV_LEN)
1871 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
1872
1873 VIM_CLEAR(varnamebuf);
1874 varnamebuflen = 0;
1875 return NULL;
1876}
1877
Bram Moolenaarda6c0332019-09-01 16:01:30 +02001878 char *
1879get_var_special_name(int nr)
1880{
1881 switch (nr)
1882 {
1883 case VVAL_FALSE: return "v:false";
1884 case VVAL_TRUE: return "v:true";
1885 case VVAL_NONE: return "v:none";
1886 case VVAL_NULL: return "v:null";
1887 }
1888 internal_error("get_var_special_name()");
1889 return "42";
1890}
1891
1892/*
1893 * Returns the global variable dictionary
1894 */
1895 dict_T *
1896get_globvar_dict(void)
1897{
1898 return &globvardict;
1899}
1900
1901/*
1902 * Returns the global variable hash table
1903 */
1904 hashtab_T *
1905get_globvar_ht(void)
1906{
1907 return &globvarht;
1908}
1909
1910/*
1911 * Returns the v: variable dictionary
1912 */
1913 dict_T *
1914get_vimvar_dict(void)
1915{
1916 return &vimvardict;
1917}
1918
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001919/*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001920 * Returns the index of a v:variable. Negative if not found.
1921 */
1922 int
1923find_vim_var(char_u *name)
1924{
1925 dictitem_T *di = find_var_in_ht(&vimvarht, 0, name, TRUE);
1926 struct vimvar *vv;
1927
1928 if (di == NULL)
1929 return -1;
1930 vv = (struct vimvar *)((char *)di - offsetof(vimvar_T, vv_di));
1931 return (int)(vv - vimvars);
1932}
1933
1934
1935/*
Bram Moolenaar34ed68d2019-08-29 22:48:24 +02001936 * Set type of v: variable to "type".
1937 */
1938 void
1939set_vim_var_type(int idx, vartype_T type)
1940{
1941 vimvars[idx].vv_type = type;
1942}
1943
1944/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001945 * Set number v: variable to "val".
Bram Moolenaar8d71b542019-08-30 15:46:30 +02001946 * Note that this does not set the type, use set_vim_var_type() for that.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001947 */
1948 void
1949set_vim_var_nr(int idx, varnumber_T val)
1950{
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001951 vimvars[idx].vv_nr = val;
1952}
1953
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001954 char *
1955get_vim_var_name(int idx)
1956{
1957 return vimvars[idx].vv_name;
1958}
1959
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001960/*
1961 * Get typval_T v: variable value.
1962 */
1963 typval_T *
1964get_vim_var_tv(int idx)
1965{
1966 return &vimvars[idx].vv_tv;
1967}
1968
1969/*
1970 * Get number v: variable value.
1971 */
1972 varnumber_T
1973get_vim_var_nr(int idx)
1974{
1975 return vimvars[idx].vv_nr;
1976}
1977
1978/*
1979 * Get string v: variable value. Uses a static buffer, can only be used once.
1980 * If the String variable has never been set, return an empty string.
1981 * Never returns NULL;
1982 */
1983 char_u *
1984get_vim_var_str(int idx)
1985{
1986 return tv_get_string(&vimvars[idx].vv_tv);
1987}
1988
1989/*
1990 * Get List v: variable value. Caller must take care of reference count when
1991 * needed.
1992 */
1993 list_T *
1994get_vim_var_list(int idx)
1995{
1996 return vimvars[idx].vv_list;
1997}
1998
1999/*
2000 * Get Dict v: variable value. Caller must take care of reference count when
2001 * needed.
2002 */
2003 dict_T *
2004get_vim_var_dict(int idx)
2005{
2006 return vimvars[idx].vv_dict;
2007}
2008
2009/*
2010 * Set v:char to character "c".
2011 */
2012 void
2013set_vim_var_char(int c)
2014{
2015 char_u buf[MB_MAXBYTES + 1];
2016
2017 if (has_mbyte)
2018 buf[(*mb_char2bytes)(c, buf)] = NUL;
2019 else
2020 {
2021 buf[0] = c;
2022 buf[1] = NUL;
2023 }
2024 set_vim_var_string(VV_CHAR, buf, -1);
2025}
2026
2027/*
2028 * Set v:count to "count" and v:count1 to "count1".
2029 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
2030 */
2031 void
2032set_vcount(
2033 long count,
2034 long count1,
2035 int set_prevcount)
2036{
2037 if (set_prevcount)
2038 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
2039 vimvars[VV_COUNT].vv_nr = count;
2040 vimvars[VV_COUNT1].vv_nr = count1;
2041}
2042
2043/*
2044 * Save variables that might be changed as a side effect. Used when executing
2045 * a timer callback.
2046 */
2047 void
2048save_vimvars(vimvars_save_T *vvsave)
2049{
2050 vvsave->vv_prevcount = vimvars[VV_PREVCOUNT].vv_nr;
2051 vvsave->vv_count = vimvars[VV_COUNT].vv_nr;
2052 vvsave->vv_count1 = vimvars[VV_COUNT1].vv_nr;
2053}
2054
2055/*
2056 * Restore variables saved by save_vimvars().
2057 */
2058 void
2059restore_vimvars(vimvars_save_T *vvsave)
2060{
2061 vimvars[VV_PREVCOUNT].vv_nr = vvsave->vv_prevcount;
2062 vimvars[VV_COUNT].vv_nr = vvsave->vv_count;
2063 vimvars[VV_COUNT1].vv_nr = vvsave->vv_count1;
2064}
2065
2066/*
2067 * Set string v: variable to a copy of "val". If 'copy' is FALSE, then set the
2068 * value.
2069 */
2070 void
2071set_vim_var_string(
2072 int idx,
2073 char_u *val,
2074 int len) // length of "val" to use or -1 (whole string)
2075{
2076 clear_tv(&vimvars[idx].vv_di.di_tv);
2077 vimvars[idx].vv_type = VAR_STRING;
2078 if (val == NULL)
2079 vimvars[idx].vv_str = NULL;
2080 else if (len == -1)
2081 vimvars[idx].vv_str = vim_strsave(val);
2082 else
2083 vimvars[idx].vv_str = vim_strnsave(val, len);
2084}
2085
2086/*
2087 * Set List v: variable to "val".
2088 */
2089 void
2090set_vim_var_list(int idx, list_T *val)
2091{
2092 clear_tv(&vimvars[idx].vv_di.di_tv);
2093 vimvars[idx].vv_type = VAR_LIST;
2094 vimvars[idx].vv_list = val;
2095 if (val != NULL)
2096 ++val->lv_refcount;
2097}
2098
2099/*
2100 * Set Dictionary v: variable to "val".
2101 */
2102 void
2103set_vim_var_dict(int idx, dict_T *val)
2104{
2105 clear_tv(&vimvars[idx].vv_di.di_tv);
2106 vimvars[idx].vv_type = VAR_DICT;
2107 vimvars[idx].vv_dict = val;
2108 if (val != NULL)
2109 {
2110 ++val->dv_refcount;
2111 dict_set_items_ro(val);
2112 }
2113}
2114
2115/*
Bram Moolenaar69bf6342019-10-29 04:16:57 +01002116 * Set the v:argv list.
2117 */
2118 void
2119set_argv_var(char **argv, int argc)
2120{
2121 list_T *l = list_alloc();
2122 int i;
2123
2124 if (l == NULL)
2125 getout(1);
2126 l->lv_lock = VAR_FIXED;
2127 for (i = 0; i < argc; ++i)
2128 {
2129 if (list_append_string(l, (char_u *)argv[i], -1) == FAIL)
2130 getout(1);
2131 l->lv_last->li_tv.v_lock = VAR_FIXED;
2132 }
2133 set_vim_var_list(VV_ARGV, l);
2134}
2135
2136/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002137 * Set v:register if needed.
2138 */
2139 void
2140set_reg_var(int c)
2141{
2142 char_u regname;
2143
2144 if (c == 0 || c == ' ')
2145 regname = '"';
2146 else
2147 regname = c;
2148 // Avoid free/alloc when the value is already right.
2149 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
2150 set_vim_var_string(VV_REG, &regname, 1);
2151}
2152
2153/*
2154 * Get or set v:exception. If "oldval" == NULL, return the current value.
2155 * Otherwise, restore the value to "oldval" and return NULL.
2156 * Must always be called in pairs to save and restore v:exception! Does not
2157 * take care of memory allocations.
2158 */
2159 char_u *
2160v_exception(char_u *oldval)
2161{
2162 if (oldval == NULL)
2163 return vimvars[VV_EXCEPTION].vv_str;
2164
2165 vimvars[VV_EXCEPTION].vv_str = oldval;
2166 return NULL;
2167}
2168
2169/*
2170 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
2171 * Otherwise, restore the value to "oldval" and return NULL.
2172 * Must always be called in pairs to save and restore v:throwpoint! Does not
2173 * take care of memory allocations.
2174 */
2175 char_u *
2176v_throwpoint(char_u *oldval)
2177{
2178 if (oldval == NULL)
2179 return vimvars[VV_THROWPOINT].vv_str;
2180
2181 vimvars[VV_THROWPOINT].vv_str = oldval;
2182 return NULL;
2183}
2184
2185/*
2186 * Set v:cmdarg.
2187 * If "eap" != NULL, use "eap" to generate the value and return the old value.
2188 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
2189 * Must always be called in pairs!
2190 */
2191 char_u *
2192set_cmdarg(exarg_T *eap, char_u *oldarg)
2193{
2194 char_u *oldval;
2195 char_u *newval;
2196 unsigned len;
2197
2198 oldval = vimvars[VV_CMDARG].vv_str;
2199 if (eap == NULL)
2200 {
2201 vim_free(oldval);
2202 vimvars[VV_CMDARG].vv_str = oldarg;
2203 return NULL;
2204 }
2205
2206 if (eap->force_bin == FORCE_BIN)
2207 len = 6;
2208 else if (eap->force_bin == FORCE_NOBIN)
2209 len = 8;
2210 else
2211 len = 0;
2212
2213 if (eap->read_edit)
2214 len += 7;
2215
2216 if (eap->force_ff != 0)
2217 len += 10; // " ++ff=unix"
2218 if (eap->force_enc != 0)
2219 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
2220 if (eap->bad_char != 0)
2221 len += 7 + 4; // " ++bad=" + "keep" or "drop"
2222
2223 newval = alloc(len + 1);
2224 if (newval == NULL)
2225 return NULL;
2226
2227 if (eap->force_bin == FORCE_BIN)
2228 sprintf((char *)newval, " ++bin");
2229 else if (eap->force_bin == FORCE_NOBIN)
2230 sprintf((char *)newval, " ++nobin");
2231 else
2232 *newval = NUL;
2233
2234 if (eap->read_edit)
2235 STRCAT(newval, " ++edit");
2236
2237 if (eap->force_ff != 0)
2238 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
2239 eap->force_ff == 'u' ? "unix"
2240 : eap->force_ff == 'd' ? "dos"
2241 : "mac");
2242 if (eap->force_enc != 0)
2243 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
2244 eap->cmd + eap->force_enc);
2245 if (eap->bad_char == BAD_KEEP)
2246 STRCPY(newval + STRLEN(newval), " ++bad=keep");
2247 else if (eap->bad_char == BAD_DROP)
2248 STRCPY(newval + STRLEN(newval), " ++bad=drop");
2249 else if (eap->bad_char != 0)
2250 sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
2251 vimvars[VV_CMDARG].vv_str = newval;
2252 return oldval;
2253}
2254
2255/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002256 * Get the value of internal variable "name".
2257 * Return OK or FAIL. If OK is returned "rettv" must be cleared.
2258 */
2259 int
2260get_var_tv(
2261 char_u *name,
2262 int len, // length of "name"
2263 typval_T *rettv, // NULL when only checking existence
2264 dictitem_T **dip, // non-NULL when typval's dict item is needed
2265 int verbose, // may give error message
2266 int no_autoload) // do not use script autoloading
2267{
2268 int ret = OK;
2269 typval_T *tv = NULL;
2270 dictitem_T *v;
2271 int cc;
2272
2273 // truncate the name, so that we can use strcmp()
2274 cc = name[len];
2275 name[len] = NUL;
2276
2277 // Check for user-defined variables.
2278 v = find_var(name, NULL, no_autoload);
2279 if (v != NULL)
2280 {
2281 tv = &v->di_tv;
2282 if (dip != NULL)
2283 *dip = v;
2284 }
2285
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002286 if (tv == NULL && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2287 {
2288 imported_T *import = find_imported(name, NULL);
2289
2290 // imported variable from another script
2291 if (import != NULL)
2292 {
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002293 scriptitem_T *si = SCRIPT_ITEM(import->imp_sid);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002294 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data)
2295 + import->imp_var_vals_idx;
2296 tv = sv->sv_tv;
2297 }
2298 }
2299
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002300 if (tv == NULL)
2301 {
2302 if (rettv != NULL && verbose)
2303 semsg(_(e_undefvar), name);
2304 ret = FAIL;
2305 }
2306 else if (rettv != NULL)
2307 copy_tv(tv, rettv);
2308
2309 name[len] = cc;
2310
2311 return ret;
2312}
2313
2314/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002315 * Check if variable "name[len]" is a local variable or an argument.
2316 * If so, "*eval_lavars_used" is set to TRUE.
2317 */
2318 void
2319check_vars(char_u *name, int len)
2320{
2321 int cc;
2322 char_u *varname;
2323 hashtab_T *ht;
2324
2325 if (eval_lavars_used == NULL)
2326 return;
2327
2328 // truncate the name, so that we can use strcmp()
2329 cc = name[len];
2330 name[len] = NUL;
2331
2332 ht = find_var_ht(name, &varname);
2333 if (ht == get_funccal_local_ht() || ht == get_funccal_args_ht())
2334 {
2335 if (find_var(name, NULL, TRUE) != NULL)
2336 *eval_lavars_used = TRUE;
2337 }
2338
2339 name[len] = cc;
2340}
2341
2342/*
2343 * Find variable "name" in the list of variables.
2344 * Return a pointer to it if found, NULL if not found.
2345 * Careful: "a:0" variables don't have a name.
2346 * When "htp" is not NULL we are writing to the variable, set "htp" to the
2347 * hashtab_T used.
2348 */
2349 dictitem_T *
2350find_var(char_u *name, hashtab_T **htp, int no_autoload)
2351{
2352 char_u *varname;
2353 hashtab_T *ht;
2354 dictitem_T *ret = NULL;
2355
2356 ht = find_var_ht(name, &varname);
2357 if (htp != NULL)
2358 *htp = ht;
2359 if (ht == NULL)
2360 return NULL;
2361 ret = find_var_in_ht(ht, *name, varname, no_autoload || htp != NULL);
2362 if (ret != NULL)
2363 return ret;
2364
Bram Moolenaar8d71b542019-08-30 15:46:30 +02002365 // Search in parent scope for lambda
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002366 return find_var_in_scoped_ht(name, no_autoload || htp != NULL);
2367}
2368
2369/*
2370 * Find variable "varname" in hashtab "ht" with name "htname".
2371 * Returns NULL if not found.
2372 */
2373 dictitem_T *
2374find_var_in_ht(
2375 hashtab_T *ht,
2376 int htname,
2377 char_u *varname,
2378 int no_autoload)
2379{
2380 hashitem_T *hi;
2381
2382 if (*varname == NUL)
2383 {
2384 // Must be something like "s:", otherwise "ht" would be NULL.
2385 switch (htname)
2386 {
2387 case 's': return &SCRIPT_SV(current_sctx.sc_sid)->sv_var;
2388 case 'g': return &globvars_var;
2389 case 'v': return &vimvars_var;
2390 case 'b': return &curbuf->b_bufvar;
2391 case 'w': return &curwin->w_winvar;
2392 case 't': return &curtab->tp_winvar;
2393 case 'l': return get_funccal_local_var();
2394 case 'a': return get_funccal_args_var();
2395 }
2396 return NULL;
2397 }
2398
2399 hi = hash_find(ht, varname);
2400 if (HASHITEM_EMPTY(hi))
2401 {
2402 // For global variables we may try auto-loading the script. If it
2403 // worked find the variable again. Don't auto-load a script if it was
2404 // loaded already, otherwise it would be loaded every time when
2405 // checking if a function name is a Funcref variable.
2406 if (ht == &globvarht && !no_autoload)
2407 {
2408 // Note: script_autoload() may make "hi" invalid. It must either
2409 // be obtained again or not used.
2410 if (!script_autoload(varname, FALSE) || aborting())
2411 return NULL;
2412 hi = hash_find(ht, varname);
2413 }
2414 if (HASHITEM_EMPTY(hi))
2415 return NULL;
2416 }
2417 return HI2DI(hi);
2418}
2419
2420/*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002421 * Get the script-local hashtab. NULL if not in a script context.
2422 */
2423 hashtab_T *
2424get_script_local_ht(void)
2425{
2426 scid_T sid = current_sctx.sc_sid;
2427
2428 if (sid > 0 && sid <= script_items.ga_len)
2429 return &SCRIPT_VARS(sid);
2430 return NULL;
2431}
2432
2433/*
2434 * Look for "name[len]" in script-local variables.
2435 * Return -1 when not found.
2436 */
2437 int
2438lookup_scriptvar(char_u *name, size_t len, cctx_T *dummy UNUSED)
2439{
2440 hashtab_T *ht = get_script_local_ht();
2441 char_u buffer[30];
2442 char_u *p;
2443 int res;
2444 hashitem_T *hi;
2445
2446 if (ht == NULL)
2447 return -1;
2448 if (len < sizeof(buffer) - 1)
2449 {
2450 vim_strncpy(buffer, name, len);
2451 p = buffer;
2452 }
2453 else
2454 {
2455 p = vim_strnsave(name, (int)len);
2456 if (p == NULL)
2457 return -1;
2458 }
2459
2460 hi = hash_find(ht, p);
2461 res = HASHITEM_EMPTY(hi) ? -1 : 1;
2462
2463 // if not script-local, then perhaps imported
2464 if (res == -1 && find_imported(p, NULL) != NULL)
2465 res = 1;
2466
2467 if (p != buffer)
2468 vim_free(p);
2469 return res;
2470}
2471
2472/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002473 * Find the hashtab used for a variable name.
2474 * Return NULL if the name is not valid.
2475 * Set "varname" to the start of name without ':'.
2476 */
2477 hashtab_T *
2478find_var_ht(char_u *name, char_u **varname)
2479{
2480 hashitem_T *hi;
2481 hashtab_T *ht;
2482
2483 if (name[0] == NUL)
2484 return NULL;
2485 if (name[1] != ':')
2486 {
2487 // The name must not start with a colon or #.
2488 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
2489 return NULL;
2490 *varname = name;
2491
2492 // "version" is "v:version" in all scopes if scriptversion < 3.
2493 // Same for a few other variables marked with VV_COMPAT.
2494 if (current_sctx.sc_version < 3)
2495 {
2496 hi = hash_find(&compat_hashtab, name);
2497 if (!HASHITEM_EMPTY(hi))
2498 return &compat_hashtab;
2499 }
2500
2501 ht = get_funccal_local_ht();
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002502 if (ht != NULL)
2503 return ht; // local variable
2504
2505 // in Vim9 script items at the script level are script-local
2506 if (current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2507 {
2508 ht = get_script_local_ht();
2509 if (ht != NULL)
2510 return ht;
2511 }
2512
2513 return &globvarht; // global variable
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002514 }
2515 *varname = name + 2;
2516 if (*name == 'g') // global variable
2517 return &globvarht;
2518 // There must be no ':' or '#' in the rest of the name, unless g: is used
2519 if (vim_strchr(name + 2, ':') != NULL
2520 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
2521 return NULL;
2522 if (*name == 'b') // buffer variable
2523 return &curbuf->b_vars->dv_hashtab;
2524 if (*name == 'w') // window variable
2525 return &curwin->w_vars->dv_hashtab;
2526 if (*name == 't') // tab page variable
2527 return &curtab->tp_vars->dv_hashtab;
2528 if (*name == 'v') // v: variable
2529 return &vimvarht;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002530 if (current_sctx.sc_version != SCRIPT_VERSION_VIM9)
2531 {
2532 if (*name == 'a') // a: function argument
2533 return get_funccal_args_ht();
2534 if (*name == 'l') // l: local function variable
2535 return get_funccal_local_ht();
2536 }
2537 if (*name == 's') // script variable
2538 {
2539 ht = get_script_local_ht();
2540 if (ht != NULL)
2541 return ht;
2542 }
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002543 return NULL;
2544}
2545
2546/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002547 * Get the string value of a (global/local) variable.
2548 * Note: see tv_get_string() for how long the pointer remains valid.
2549 * Returns NULL when it doesn't exist.
2550 */
2551 char_u *
2552get_var_value(char_u *name)
2553{
2554 dictitem_T *v;
2555
2556 v = find_var(name, NULL, FALSE);
2557 if (v == NULL)
2558 return NULL;
2559 return tv_get_string(&v->di_tv);
2560}
2561
2562/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002563 * Allocate a new hashtab for a sourced script. It will be used while
2564 * sourcing this script and when executing functions defined in the script.
2565 */
2566 void
2567new_script_vars(scid_T id)
2568{
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002569 scriptvar_T *sv;
2570
Bram Moolenaar7ebcba62020-01-12 17:42:55 +01002571 sv = ALLOC_CLEAR_ONE(scriptvar_T);
2572 if (sv == NULL)
2573 return;
2574 init_var_dict(&sv->sv_dict, &sv->sv_var, VAR_SCOPE);
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002575 SCRIPT_ITEM(id)->sn_vars = sv;
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002576}
2577
2578/*
2579 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
2580 * point to it.
2581 */
2582 void
2583init_var_dict(dict_T *dict, dictitem_T *dict_var, int scope)
2584{
2585 hash_init(&dict->dv_hashtab);
2586 dict->dv_lock = 0;
2587 dict->dv_scope = scope;
2588 dict->dv_refcount = DO_NOT_FREE_CNT;
2589 dict->dv_copyID = 0;
2590 dict_var->di_tv.vval.v_dict = dict;
2591 dict_var->di_tv.v_type = VAR_DICT;
2592 dict_var->di_tv.v_lock = VAR_FIXED;
2593 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
2594 dict_var->di_key[0] = NUL;
2595}
2596
2597/*
2598 * Unreference a dictionary initialized by init_var_dict().
2599 */
2600 void
2601unref_var_dict(dict_T *dict)
2602{
Bram Moolenaar8d71b542019-08-30 15:46:30 +02002603 // Now the dict needs to be freed if no one else is using it, go back to
2604 // normal reference counting.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002605 dict->dv_refcount -= DO_NOT_FREE_CNT - 1;
2606 dict_unref(dict);
2607}
2608
2609/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002610 * Clean up a list of internal variables.
2611 * Frees all allocated variables and the value they contain.
2612 * Clears hashtab "ht", does not free it.
2613 */
2614 void
2615vars_clear(hashtab_T *ht)
2616{
2617 vars_clear_ext(ht, TRUE);
2618}
2619
2620/*
2621 * Like vars_clear(), but only free the value if "free_val" is TRUE.
2622 */
2623 void
2624vars_clear_ext(hashtab_T *ht, int free_val)
2625{
2626 int todo;
2627 hashitem_T *hi;
2628 dictitem_T *v;
2629
2630 hash_lock(ht);
2631 todo = (int)ht->ht_used;
2632 for (hi = ht->ht_array; todo > 0; ++hi)
2633 {
2634 if (!HASHITEM_EMPTY(hi))
2635 {
2636 --todo;
2637
2638 // Free the variable. Don't remove it from the hashtab,
2639 // ht_array might change then. hash_clear() takes care of it
2640 // later.
2641 v = HI2DI(hi);
2642 if (free_val)
2643 clear_tv(&v->di_tv);
2644 if (v->di_flags & DI_FLAGS_ALLOC)
2645 vim_free(v);
2646 }
2647 }
2648 hash_clear(ht);
2649 ht->ht_used = 0;
2650}
2651
2652/*
2653 * Delete a variable from hashtab "ht" at item "hi".
2654 * Clear the variable value and free the dictitem.
2655 */
Bram Moolenaarda6c0332019-09-01 16:01:30 +02002656 static void
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002657delete_var(hashtab_T *ht, hashitem_T *hi)
2658{
2659 dictitem_T *di = HI2DI(hi);
2660
2661 hash_remove(ht, hi);
2662 clear_tv(&di->di_tv);
2663 vim_free(di);
2664}
2665
2666/*
2667 * List the value of one internal variable.
2668 */
2669 static void
2670list_one_var(dictitem_T *v, char *prefix, int *first)
2671{
2672 char_u *tofree;
2673 char_u *s;
2674 char_u numbuf[NUMBUFLEN];
2675
2676 s = echo_string(&v->di_tv, &tofree, numbuf, get_copyID());
2677 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
2678 s == NULL ? (char_u *)"" : s, first);
2679 vim_free(tofree);
2680}
2681
2682 static void
2683list_one_var_a(
2684 char *prefix,
2685 char_u *name,
2686 int type,
2687 char_u *string,
2688 int *first) // when TRUE clear rest of screen and set to FALSE
2689{
2690 // don't use msg() or msg_attr() to avoid overwriting "v:statusmsg"
2691 msg_start();
2692 msg_puts(prefix);
2693 if (name != NULL) // "a:" vars don't have a name stored
2694 msg_puts((char *)name);
2695 msg_putchar(' ');
2696 msg_advance(22);
2697 if (type == VAR_NUMBER)
2698 msg_putchar('#');
2699 else if (type == VAR_FUNC || type == VAR_PARTIAL)
2700 msg_putchar('*');
2701 else if (type == VAR_LIST)
2702 {
2703 msg_putchar('[');
2704 if (*string == '[')
2705 ++string;
2706 }
2707 else if (type == VAR_DICT)
2708 {
2709 msg_putchar('{');
2710 if (*string == '{')
2711 ++string;
2712 }
2713 else
2714 msg_putchar(' ');
2715
2716 msg_outtrans(string);
2717
2718 if (type == VAR_FUNC || type == VAR_PARTIAL)
2719 msg_puts("()");
2720 if (*first)
2721 {
2722 msg_clr_eos();
2723 *first = FALSE;
2724 }
2725}
2726
2727/*
2728 * Set variable "name" to value in "tv".
2729 * If the variable already exists, the value is updated.
2730 * Otherwise the variable is created.
2731 */
2732 void
2733set_var(
2734 char_u *name,
2735 typval_T *tv,
2736 int copy) // make copy of value in "tv"
2737{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002738 set_var_const(name, NULL, tv, copy, 0);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002739}
2740
2741/*
2742 * Set variable "name" to value in "tv".
2743 * If the variable already exists and "is_const" is FALSE the value is updated.
2744 * Otherwise the variable is created.
2745 */
2746 void
2747set_var_const(
2748 char_u *name,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002749 type_T *type,
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002750 typval_T *tv,
2751 int copy, // make copy of value in "tv"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002752 int flags) // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002753{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002754 dictitem_T *di;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002755 char_u *varname;
2756 hashtab_T *ht;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002757 int is_script_local;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002758
2759 ht = find_var_ht(name, &varname);
2760 if (ht == NULL || *varname == NUL)
2761 {
2762 semsg(_(e_illvar), name);
2763 return;
2764 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002765 is_script_local = ht == get_script_local_ht();
2766
2767 di = find_var_in_ht(ht, 0, varname, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002768
2769 // Search in parent scope which is possible to reference from lambda
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002770 if (di == NULL)
2771 di = find_var_in_scoped_ht(name, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002772
2773 if ((tv->v_type == VAR_FUNC || tv->v_type == VAR_PARTIAL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002774 && var_check_func_name(name, di == NULL))
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002775 return;
2776
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002777 if (di != NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002778 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002779 if ((di->di_flags & DI_FLAGS_RELOAD) == 0)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002780 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002781 if (flags & LET_IS_CONST)
2782 {
2783 emsg(_(e_cannot_mod));
2784 return;
2785 }
2786
2787 if (var_check_ro(di->di_flags, name, FALSE)
2788 || var_check_lock(di->di_tv.v_lock, name, FALSE))
2789 return;
2790
2791 if ((flags & LET_NO_COMMAND) == 0
2792 && is_script_local
2793 && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2794 {
2795 semsg(_("E1041: Redefining script item %s"), name);
2796 return;
2797 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002798 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002799 else
2800 // can only redefine once
2801 di->di_flags &= ~DI_FLAGS_RELOAD;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002802
2803 // existing variable, need to clear the value
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002804
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002805 // Handle setting internal di: variables separately where needed to
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002806 // prevent changing the type.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002807 if (ht == &vimvarht)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002808 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002809 if (di->di_tv.v_type == VAR_STRING)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002810 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002811 VIM_CLEAR(di->di_tv.vval.v_string);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002812 if (copy || tv->v_type != VAR_STRING)
2813 {
2814 char_u *val = tv_get_string(tv);
2815
2816 // Careful: when assigning to v:errmsg and tv_get_string()
Bram Moolenaar4b96df52020-01-26 22:00:26 +01002817 // causes an error message the variable will already be set.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002818 if (di->di_tv.vval.v_string == NULL)
2819 di->di_tv.vval.v_string = vim_strsave(val);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002820 }
2821 else
2822 {
2823 // Take over the string to avoid an extra alloc/free.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002824 di->di_tv.vval.v_string = tv->vval.v_string;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002825 tv->vval.v_string = NULL;
2826 }
2827 return;
2828 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002829 else if (di->di_tv.v_type == VAR_NUMBER)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002830 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002831 di->di_tv.vval.v_number = tv_get_number(tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002832 if (STRCMP(varname, "searchforward") == 0)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002833 set_search_direction(di->di_tv.vval.v_number ? '/' : '?');
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002834#ifdef FEAT_SEARCH_EXTRA
2835 else if (STRCMP(varname, "hlsearch") == 0)
2836 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002837 no_hlsearch = !di->di_tv.vval.v_number;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002838 redraw_all_later(SOME_VALID);
2839 }
2840#endif
2841 return;
2842 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002843 else if (di->di_tv.v_type != tv->v_type)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002844 {
2845 semsg(_("E963: setting %s to value with wrong type"), name);
2846 return;
2847 }
2848 }
2849
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002850 clear_tv(&di->di_tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002851 }
2852 else // add a new variable
2853 {
2854 // Can't add "v:" or "a:" variable.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002855 if (ht == &vimvarht || ht == get_funccal_args_ht())
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002856 {
2857 semsg(_(e_illvar), name);
2858 return;
2859 }
2860
2861 // Make sure the variable name is valid.
2862 if (!valid_varname(varname))
2863 return;
2864
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002865 di = alloc(sizeof(dictitem_T) + STRLEN(varname));
2866 if (di == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002867 return;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002868 STRCPY(di->di_key, varname);
2869 if (hash_add(ht, DI2HIKEY(di)) == FAIL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002870 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002871 vim_free(di);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002872 return;
2873 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002874 di->di_flags = DI_FLAGS_ALLOC;
2875 if (flags & LET_IS_CONST)
2876 di->di_flags |= DI_FLAGS_LOCK;
2877
2878 if (is_script_local && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2879 {
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002880 scriptitem_T *si = SCRIPT_ITEM(current_sctx.sc_sid);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002881
2882 // Store a pointer to the typval_T, so that it can be found by
2883 // index instead of using a hastab lookup.
2884 if (ga_grow(&si->sn_var_vals, 1) == OK)
2885 {
2886 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data)
2887 + si->sn_var_vals.ga_len;
2888 sv->sv_name = di->di_key;
2889 sv->sv_tv = &di->di_tv;
2890 sv->sv_type = type == NULL ? &t_any : type;
2891 sv->sv_const = (flags & LET_IS_CONST);
2892 sv->sv_export = is_export;
2893 ++si->sn_var_vals.ga_len;
2894
2895 // let ex_export() know the export worked.
2896 is_export = FALSE;
2897 }
2898 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002899 }
2900
2901 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002902 copy_tv(tv, &di->di_tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002903 else
2904 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002905 di->di_tv = *tv;
2906 di->di_tv.v_lock = 0;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002907 init_tv(tv);
2908 }
2909
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002910 if (flags & LET_IS_CONST)
2911 di->di_tv.v_lock |= VAR_LOCKED;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002912}
2913
2914/*
2915 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
2916 * Also give an error message.
2917 */
2918 int
2919var_check_ro(int flags, char_u *name, int use_gettext)
2920{
2921 if (flags & DI_FLAGS_RO)
2922 {
2923 semsg(_(e_readonlyvar), use_gettext ? (char_u *)_(name) : name);
2924 return TRUE;
2925 }
2926 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
2927 {
2928 semsg(_(e_readonlysbx), use_gettext ? (char_u *)_(name) : name);
2929 return TRUE;
2930 }
2931 return FALSE;
2932}
2933
2934/*
2935 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
2936 * Also give an error message.
2937 */
2938 int
2939var_check_fixed(int flags, char_u *name, int use_gettext)
2940{
2941 if (flags & DI_FLAGS_FIX)
2942 {
2943 semsg(_("E795: Cannot delete variable %s"),
2944 use_gettext ? (char_u *)_(name) : name);
2945 return TRUE;
2946 }
2947 return FALSE;
2948}
2949
2950/*
2951 * Check if a funcref is assigned to a valid variable name.
2952 * Return TRUE and give an error if not.
2953 */
2954 int
2955var_check_func_name(
2956 char_u *name, // points to start of variable name
2957 int new_var) // TRUE when creating the variable
2958{
2959 // Allow for w: b: s: and t:.
2960 if (!(vim_strchr((char_u *)"wbst", name[0]) != NULL && name[1] == ':')
2961 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
2962 ? name[2] : name[0]))
2963 {
2964 semsg(_("E704: Funcref variable name must start with a capital: %s"),
2965 name);
2966 return TRUE;
2967 }
2968 // Don't allow hiding a function. When "v" is not NULL we might be
2969 // assigning another function to the same var, the type is checked
2970 // below.
2971 if (new_var && function_exists(name, FALSE))
2972 {
2973 semsg(_("E705: Variable name conflicts with existing function: %s"),
2974 name);
2975 return TRUE;
2976 }
2977 return FALSE;
2978}
2979
2980/*
2981 * Return TRUE if "flags" indicates variable "name" is locked (immutable).
2982 * Also give an error message, using "name" or _("name") when use_gettext is
2983 * TRUE.
2984 */
2985 int
2986var_check_lock(int lock, char_u *name, int use_gettext)
2987{
2988 if (lock & VAR_LOCKED)
2989 {
2990 semsg(_("E741: Value is locked: %s"),
2991 name == NULL ? (char_u *)_("Unknown")
2992 : use_gettext ? (char_u *)_(name)
2993 : name);
2994 return TRUE;
2995 }
2996 if (lock & VAR_FIXED)
2997 {
2998 semsg(_("E742: Cannot change value of %s"),
2999 name == NULL ? (char_u *)_("Unknown")
3000 : use_gettext ? (char_u *)_(name)
3001 : name);
3002 return TRUE;
3003 }
3004 return FALSE;
3005}
3006
3007/*
3008 * Check if a variable name is valid.
3009 * Return FALSE and give an error if not.
3010 */
3011 int
3012valid_varname(char_u *varname)
3013{
3014 char_u *p;
3015
3016 for (p = varname; *p != NUL; ++p)
3017 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
3018 && *p != AUTOLOAD_CHAR)
3019 {
3020 semsg(_(e_illvar), varname);
3021 return FALSE;
3022 }
3023 return TRUE;
3024}
3025
3026/*
3027 * getwinvar() and gettabwinvar()
3028 */
3029 static void
3030getwinvar(
3031 typval_T *argvars,
3032 typval_T *rettv,
3033 int off) // 1 for gettabwinvar()
3034{
3035 win_T *win;
3036 char_u *varname;
3037 dictitem_T *v;
3038 tabpage_T *tp = NULL;
3039 int done = FALSE;
3040 win_T *oldcurwin;
3041 tabpage_T *oldtabpage;
3042 int need_switch_win;
3043
3044 if (off == 1)
3045 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3046 else
3047 tp = curtab;
3048 win = find_win_by_nr(&argvars[off], tp);
3049 varname = tv_get_string_chk(&argvars[off + 1]);
3050 ++emsg_off;
3051
3052 rettv->v_type = VAR_STRING;
3053 rettv->vval.v_string = NULL;
3054
3055 if (win != NULL && varname != NULL)
3056 {
3057 // Set curwin to be our win, temporarily. Also set the tabpage,
3058 // otherwise the window is not valid. Only do this when needed,
3059 // autocommands get blocked.
3060 need_switch_win = !(tp == curtab && win == curwin);
3061 if (!need_switch_win
3062 || switch_win(&oldcurwin, &oldtabpage, win, tp, TRUE) == OK)
3063 {
3064 if (*varname == '&')
3065 {
3066 if (varname[1] == NUL)
3067 {
3068 // get all window-local options in a dict
3069 dict_T *opts = get_winbuf_options(FALSE);
3070
3071 if (opts != NULL)
3072 {
3073 rettv_dict_set(rettv, opts);
3074 done = TRUE;
3075 }
3076 }
3077 else if (get_option_tv(&varname, rettv, 1) == OK)
3078 // window-local-option
3079 done = TRUE;
3080 }
3081 else
3082 {
3083 // Look up the variable.
3084 // Let getwinvar({nr}, "") return the "w:" dictionary.
3085 v = find_var_in_ht(&win->w_vars->dv_hashtab, 'w',
3086 varname, FALSE);
3087 if (v != NULL)
3088 {
3089 copy_tv(&v->di_tv, rettv);
3090 done = TRUE;
3091 }
3092 }
3093 }
3094
3095 if (need_switch_win)
3096 // restore previous notion of curwin
3097 restore_win(oldcurwin, oldtabpage, TRUE);
3098 }
3099
3100 if (!done && argvars[off + 2].v_type != VAR_UNKNOWN)
3101 // use the default return value
3102 copy_tv(&argvars[off + 2], rettv);
3103
3104 --emsg_off;
3105}
3106
3107/*
3108 * "setwinvar()" and "settabwinvar()" functions
3109 */
3110 static void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003111setwinvar(typval_T *argvars, int off)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003112{
3113 win_T *win;
3114 win_T *save_curwin;
3115 tabpage_T *save_curtab;
3116 int need_switch_win;
3117 char_u *varname, *winvarname;
3118 typval_T *varp;
3119 char_u nbuf[NUMBUFLEN];
3120 tabpage_T *tp = NULL;
3121
3122 if (check_secure())
3123 return;
3124
3125 if (off == 1)
3126 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3127 else
3128 tp = curtab;
3129 win = find_win_by_nr(&argvars[off], tp);
3130 varname = tv_get_string_chk(&argvars[off + 1]);
3131 varp = &argvars[off + 2];
3132
3133 if (win != NULL && varname != NULL && varp != NULL)
3134 {
3135 need_switch_win = !(tp == curtab && win == curwin);
3136 if (!need_switch_win
3137 || switch_win(&save_curwin, &save_curtab, win, tp, TRUE) == OK)
3138 {
3139 if (*varname == '&')
3140 {
3141 long numval;
3142 char_u *strval;
3143 int error = FALSE;
3144
3145 ++varname;
3146 numval = (long)tv_get_number_chk(varp, &error);
3147 strval = tv_get_string_buf_chk(varp, nbuf);
3148 if (!error && strval != NULL)
3149 set_option_value(varname, numval, strval, OPT_LOCAL);
3150 }
3151 else
3152 {
3153 winvarname = alloc(STRLEN(varname) + 3);
3154 if (winvarname != NULL)
3155 {
3156 STRCPY(winvarname, "w:");
3157 STRCPY(winvarname + 2, varname);
3158 set_var(winvarname, varp, TRUE);
3159 vim_free(winvarname);
3160 }
3161 }
3162 }
3163 if (need_switch_win)
3164 restore_win(save_curwin, save_curtab, TRUE);
3165 }
3166}
3167
Bram Moolenaare5cdf152019-08-29 22:09:46 +02003168/*
3169 * reset v:option_new, v:option_old, v:option_oldlocal, v:option_oldglobal,
3170 * v:option_type, and v:option_command.
3171 */
3172 void
3173reset_v_option_vars(void)
3174{
3175 set_vim_var_string(VV_OPTION_NEW, NULL, -1);
3176 set_vim_var_string(VV_OPTION_OLD, NULL, -1);
3177 set_vim_var_string(VV_OPTION_OLDLOCAL, NULL, -1);
3178 set_vim_var_string(VV_OPTION_OLDGLOBAL, NULL, -1);
3179 set_vim_var_string(VV_OPTION_TYPE, NULL, -1);
3180 set_vim_var_string(VV_OPTION_COMMAND, NULL, -1);
3181}
3182
3183/*
3184 * Add an assert error to v:errors.
3185 */
3186 void
3187assert_error(garray_T *gap)
3188{
3189 struct vimvar *vp = &vimvars[VV_ERRORS];
3190
3191 if (vp->vv_type != VAR_LIST || vimvars[VV_ERRORS].vv_list == NULL)
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003192 // Make sure v:errors is a list.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02003193 set_vim_var_list(VV_ERRORS, list_alloc());
3194 list_append_string(vimvars[VV_ERRORS].vv_list, gap->ga_data, gap->ga_len);
3195}
3196
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003197 int
3198var_exists(char_u *var)
3199{
3200 char_u *name;
3201 char_u *tofree;
3202 typval_T tv;
3203 int len = 0;
3204 int n = FALSE;
3205
3206 // get_name_len() takes care of expanding curly braces
3207 name = var;
3208 len = get_name_len(&var, &tofree, TRUE, FALSE);
3209 if (len > 0)
3210 {
3211 if (tofree != NULL)
3212 name = tofree;
3213 n = (get_var_tv(name, len, &tv, NULL, FALSE, TRUE) == OK);
3214 if (n)
3215 {
3216 // handle d.key, l[idx], f(expr)
3217 n = (handle_subscript(&var, &tv, TRUE, FALSE, name, &name) == OK);
3218 if (n)
3219 clear_tv(&tv);
3220 }
3221 }
3222 if (*var != NUL)
3223 n = FALSE;
3224
3225 vim_free(tofree);
3226 return n;
3227}
3228
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003229static lval_T *redir_lval = NULL;
3230#define EVALCMD_BUSY (redir_lval == (lval_T *)&redir_lval)
3231static garray_T redir_ga; // only valid when redir_lval is not NULL
3232static char_u *redir_endp = NULL;
3233static char_u *redir_varname = NULL;
3234
3235/*
3236 * Start recording command output to a variable
3237 * When "append" is TRUE append to an existing variable.
3238 * Returns OK if successfully completed the setup. FAIL otherwise.
3239 */
3240 int
3241var_redir_start(char_u *name, int append)
3242{
3243 int save_emsg;
3244 int err;
3245 typval_T tv;
3246
3247 // Catch a bad name early.
3248 if (!eval_isnamec1(*name))
3249 {
3250 emsg(_(e_invarg));
3251 return FAIL;
3252 }
3253
3254 // Make a copy of the name, it is used in redir_lval until redir ends.
3255 redir_varname = vim_strsave(name);
3256 if (redir_varname == NULL)
3257 return FAIL;
3258
3259 redir_lval = ALLOC_CLEAR_ONE(lval_T);
3260 if (redir_lval == NULL)
3261 {
3262 var_redir_stop();
3263 return FAIL;
3264 }
3265
3266 // The output is stored in growarray "redir_ga" until redirection ends.
3267 ga_init2(&redir_ga, (int)sizeof(char), 500);
3268
3269 // Parse the variable name (can be a dict or list entry).
3270 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, 0,
3271 FNE_CHECK_START);
3272 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
3273 {
3274 clear_lval(redir_lval);
3275 if (redir_endp != NULL && *redir_endp != NUL)
3276 // Trailing characters are present after the variable name
3277 emsg(_(e_trailing));
3278 else
3279 emsg(_(e_invarg));
3280 redir_endp = NULL; // don't store a value, only cleanup
3281 var_redir_stop();
3282 return FAIL;
3283 }
3284
3285 // check if we can write to the variable: set it to or append an empty
3286 // string
3287 save_emsg = did_emsg;
3288 did_emsg = FALSE;
3289 tv.v_type = VAR_STRING;
3290 tv.vval.v_string = (char_u *)"";
3291 if (append)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003292 set_var_lval(redir_lval, redir_endp, &tv, TRUE, 0, (char_u *)".");
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003293 else
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003294 set_var_lval(redir_lval, redir_endp, &tv, TRUE, 0, (char_u *)"=");
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003295 clear_lval(redir_lval);
3296 err = did_emsg;
3297 did_emsg |= save_emsg;
3298 if (err)
3299 {
3300 redir_endp = NULL; // don't store a value, only cleanup
3301 var_redir_stop();
3302 return FAIL;
3303 }
3304
3305 return OK;
3306}
3307
3308/*
3309 * Append "value[value_len]" to the variable set by var_redir_start().
3310 * The actual appending is postponed until redirection ends, because the value
3311 * appended may in fact be the string we write to, changing it may cause freed
3312 * memory to be used:
3313 * :redir => foo
3314 * :let foo
3315 * :redir END
3316 */
3317 void
3318var_redir_str(char_u *value, int value_len)
3319{
3320 int len;
3321
3322 if (redir_lval == NULL)
3323 return;
3324
3325 if (value_len == -1)
3326 len = (int)STRLEN(value); // Append the entire string
3327 else
3328 len = value_len; // Append only "value_len" characters
3329
3330 if (ga_grow(&redir_ga, len) == OK)
3331 {
3332 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
3333 redir_ga.ga_len += len;
3334 }
3335 else
3336 var_redir_stop();
3337}
3338
3339/*
3340 * Stop redirecting command output to a variable.
3341 * Frees the allocated memory.
3342 */
3343 void
3344var_redir_stop(void)
3345{
3346 typval_T tv;
3347
3348 if (EVALCMD_BUSY)
3349 {
3350 redir_lval = NULL;
3351 return;
3352 }
3353
3354 if (redir_lval != NULL)
3355 {
3356 // If there was no error: assign the text to the variable.
3357 if (redir_endp != NULL)
3358 {
3359 ga_append(&redir_ga, NUL); // Append the trailing NUL.
3360 tv.v_type = VAR_STRING;
3361 tv.vval.v_string = redir_ga.ga_data;
3362 // Call get_lval() again, if it's inside a Dict or List it may
3363 // have changed.
3364 redir_endp = get_lval(redir_varname, NULL, redir_lval,
3365 FALSE, FALSE, 0, FNE_CHECK_START);
3366 if (redir_endp != NULL && redir_lval->ll_name != NULL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003367 set_var_lval(redir_lval, redir_endp, &tv, FALSE, 0,
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003368 (char_u *)".");
3369 clear_lval(redir_lval);
3370 }
3371
3372 // free the collected output
3373 VIM_CLEAR(redir_ga.ga_data);
3374
3375 VIM_CLEAR(redir_lval);
3376 }
3377 VIM_CLEAR(redir_varname);
3378}
3379
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003380/*
3381 * "gettabvar()" function
3382 */
3383 void
3384f_gettabvar(typval_T *argvars, typval_T *rettv)
3385{
3386 win_T *oldcurwin;
3387 tabpage_T *tp, *oldtabpage;
3388 dictitem_T *v;
3389 char_u *varname;
3390 int done = FALSE;
3391
3392 rettv->v_type = VAR_STRING;
3393 rettv->vval.v_string = NULL;
3394
3395 varname = tv_get_string_chk(&argvars[1]);
3396 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3397 if (tp != NULL && varname != NULL)
3398 {
3399 // Set tp to be our tabpage, temporarily. Also set the window to the
3400 // first window in the tabpage, otherwise the window is not valid.
3401 if (switch_win(&oldcurwin, &oldtabpage,
3402 tp == curtab || tp->tp_firstwin == NULL ? firstwin
3403 : tp->tp_firstwin, tp, TRUE) == OK)
3404 {
3405 // look up the variable
3406 // Let gettabvar({nr}, "") return the "t:" dictionary.
3407 v = find_var_in_ht(&tp->tp_vars->dv_hashtab, 't', varname, FALSE);
3408 if (v != NULL)
3409 {
3410 copy_tv(&v->di_tv, rettv);
3411 done = TRUE;
3412 }
3413 }
3414
3415 // restore previous notion of curwin
3416 restore_win(oldcurwin, oldtabpage, TRUE);
3417 }
3418
3419 if (!done && argvars[2].v_type != VAR_UNKNOWN)
3420 copy_tv(&argvars[2], rettv);
3421}
3422
3423/*
3424 * "gettabwinvar()" function
3425 */
3426 void
3427f_gettabwinvar(typval_T *argvars, typval_T *rettv)
3428{
3429 getwinvar(argvars, rettv, 1);
3430}
3431
3432/*
3433 * "getwinvar()" function
3434 */
3435 void
3436f_getwinvar(typval_T *argvars, typval_T *rettv)
3437{
3438 getwinvar(argvars, rettv, 0);
3439}
3440
3441/*
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003442 * "getbufvar()" function
3443 */
3444 void
3445f_getbufvar(typval_T *argvars, typval_T *rettv)
3446{
3447 buf_T *buf;
3448 buf_T *save_curbuf;
3449 char_u *varname;
3450 dictitem_T *v;
3451 int done = FALSE;
3452
3453 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
3454 varname = tv_get_string_chk(&argvars[1]);
3455 ++emsg_off;
3456 buf = tv_get_buf(&argvars[0], FALSE);
3457
3458 rettv->v_type = VAR_STRING;
3459 rettv->vval.v_string = NULL;
3460
3461 if (buf != NULL && varname != NULL)
3462 {
3463 // set curbuf to be our buf, temporarily
3464 save_curbuf = curbuf;
3465 curbuf = buf;
3466
3467 if (*varname == '&')
3468 {
3469 if (varname[1] == NUL)
3470 {
3471 // get all buffer-local options in a dict
3472 dict_T *opts = get_winbuf_options(TRUE);
3473
3474 if (opts != NULL)
3475 {
3476 rettv_dict_set(rettv, opts);
3477 done = TRUE;
3478 }
3479 }
3480 else if (get_option_tv(&varname, rettv, TRUE) == OK)
3481 // buffer-local-option
3482 done = TRUE;
3483 }
3484 else
3485 {
3486 // Look up the variable.
3487 // Let getbufvar({nr}, "") return the "b:" dictionary.
3488 v = find_var_in_ht(&curbuf->b_vars->dv_hashtab,
3489 'b', varname, FALSE);
3490 if (v != NULL)
3491 {
3492 copy_tv(&v->di_tv, rettv);
3493 done = TRUE;
3494 }
3495 }
3496
3497 // restore previous notion of curbuf
3498 curbuf = save_curbuf;
3499 }
3500
3501 if (!done && argvars[2].v_type != VAR_UNKNOWN)
3502 // use the default value
3503 copy_tv(&argvars[2], rettv);
3504
3505 --emsg_off;
3506}
3507
3508/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003509 * "settabvar()" function
3510 */
3511 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003512f_settabvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003513{
3514 tabpage_T *save_curtab;
3515 tabpage_T *tp;
3516 char_u *varname, *tabvarname;
3517 typval_T *varp;
3518
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003519 if (check_secure())
3520 return;
3521
3522 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3523 varname = tv_get_string_chk(&argvars[1]);
3524 varp = &argvars[2];
3525
3526 if (varname != NULL && varp != NULL && tp != NULL)
3527 {
3528 save_curtab = curtab;
3529 goto_tabpage_tp(tp, FALSE, FALSE);
3530
3531 tabvarname = alloc(STRLEN(varname) + 3);
3532 if (tabvarname != NULL)
3533 {
3534 STRCPY(tabvarname, "t:");
3535 STRCPY(tabvarname + 2, varname);
3536 set_var(tabvarname, varp, TRUE);
3537 vim_free(tabvarname);
3538 }
3539
3540 // Restore current tabpage
3541 if (valid_tabpage(save_curtab))
3542 goto_tabpage_tp(save_curtab, FALSE, FALSE);
3543 }
3544}
3545
3546/*
3547 * "settabwinvar()" function
3548 */
3549 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003550f_settabwinvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003551{
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003552 setwinvar(argvars, 1);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003553}
3554
3555/*
3556 * "setwinvar()" function
3557 */
3558 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003559f_setwinvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003560{
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003561 setwinvar(argvars, 0);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003562}
3563
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003564/*
3565 * "setbufvar()" function
3566 */
3567 void
3568f_setbufvar(typval_T *argvars, typval_T *rettv UNUSED)
3569{
3570 buf_T *buf;
3571 char_u *varname, *bufvarname;
3572 typval_T *varp;
3573 char_u nbuf[NUMBUFLEN];
3574
3575 if (check_secure())
3576 return;
3577 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
3578 varname = tv_get_string_chk(&argvars[1]);
3579 buf = tv_get_buf(&argvars[0], FALSE);
3580 varp = &argvars[2];
3581
3582 if (buf != NULL && varname != NULL && varp != NULL)
3583 {
3584 if (*varname == '&')
3585 {
3586 long numval;
3587 char_u *strval;
3588 int error = FALSE;
3589 aco_save_T aco;
3590
3591 // set curbuf to be our buf, temporarily
3592 aucmd_prepbuf(&aco, buf);
3593
3594 ++varname;
3595 numval = (long)tv_get_number_chk(varp, &error);
3596 strval = tv_get_string_buf_chk(varp, nbuf);
3597 if (!error && strval != NULL)
3598 set_option_value(varname, numval, strval, OPT_LOCAL);
3599
3600 // reset notion of buffer
3601 aucmd_restbuf(&aco);
3602 }
3603 else
3604 {
3605 buf_T *save_curbuf = curbuf;
3606
3607 bufvarname = alloc(STRLEN(varname) + 3);
3608 if (bufvarname != NULL)
3609 {
3610 curbuf = buf;
3611 STRCPY(bufvarname, "b:");
3612 STRCPY(bufvarname + 2, varname);
3613 set_var(bufvarname, varp, TRUE);
3614 vim_free(bufvarname);
3615 curbuf = save_curbuf;
3616 }
3617 }
3618 }
3619}
3620
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003621/*
3622 * Get a callback from "arg". It can be a Funcref or a function name.
3623 * When "arg" is zero return an empty string.
3624 * "cb_name" is not allocated.
3625 * "cb_name" is set to NULL for an invalid argument.
3626 */
3627 callback_T
3628get_callback(typval_T *arg)
3629{
3630 callback_T res;
3631
3632 res.cb_free_name = FALSE;
3633 if (arg->v_type == VAR_PARTIAL && arg->vval.v_partial != NULL)
3634 {
3635 res.cb_partial = arg->vval.v_partial;
3636 ++res.cb_partial->pt_refcount;
3637 res.cb_name = partial_name(res.cb_partial);
3638 }
3639 else
3640 {
3641 res.cb_partial = NULL;
3642 if (arg->v_type == VAR_FUNC || arg->v_type == VAR_STRING)
3643 {
3644 // Note that we don't make a copy of the string.
3645 res.cb_name = arg->vval.v_string;
3646 func_ref(res.cb_name);
3647 }
3648 else if (arg->v_type == VAR_NUMBER && arg->vval.v_number == 0)
3649 {
3650 res.cb_name = (char_u *)"";
3651 }
3652 else
3653 {
3654 emsg(_("E921: Invalid callback argument"));
3655 res.cb_name = NULL;
3656 }
3657 }
3658 return res;
3659}
3660
3661/*
3662 * Copy a callback into a typval_T.
3663 */
3664 void
3665put_callback(callback_T *cb, typval_T *tv)
3666{
3667 if (cb->cb_partial != NULL)
3668 {
3669 tv->v_type = VAR_PARTIAL;
3670 tv->vval.v_partial = cb->cb_partial;
3671 ++tv->vval.v_partial->pt_refcount;
3672 }
3673 else
3674 {
3675 tv->v_type = VAR_FUNC;
3676 tv->vval.v_string = vim_strsave(cb->cb_name);
3677 func_ref(cb->cb_name);
3678 }
3679}
3680
3681/*
3682 * Make a copy of "src" into "dest", allocating the function name if needed,
3683 * without incrementing the refcount.
3684 */
3685 void
3686set_callback(callback_T *dest, callback_T *src)
3687{
3688 if (src->cb_partial == NULL)
3689 {
3690 // just a function name, make a copy
3691 dest->cb_name = vim_strsave(src->cb_name);
3692 dest->cb_free_name = TRUE;
3693 }
3694 else
3695 {
3696 // cb_name is a pointer into cb_partial
3697 dest->cb_name = src->cb_name;
3698 dest->cb_free_name = FALSE;
3699 }
3700 dest->cb_partial = src->cb_partial;
3701}
3702
3703/*
3704 * Unref/free "callback" returned by get_callback() or set_callback().
3705 */
3706 void
3707free_callback(callback_T *callback)
3708{
3709 if (callback->cb_partial != NULL)
3710 {
3711 partial_unref(callback->cb_partial);
3712 callback->cb_partial = NULL;
3713 }
3714 else if (callback->cb_name != NULL)
3715 func_unref(callback->cb_name);
3716 if (callback->cb_free_name)
3717 {
3718 vim_free(callback->cb_name);
3719 callback->cb_free_name = FALSE;
3720 }
3721 callback->cb_name = NULL;
3722}
3723
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003724#endif // FEAT_EVAL