blob: ebb30dd22e2677cfe3c15f2be52fe1bf3d5f4da6 [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
846 item = l->lv_first;
847 while (*arg != ']')
848 {
849 arg = skipwhite(arg + 1);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100850 arg = ex_let_one(arg, &item->li_tv, TRUE, flags, (char_u *)",;]", op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200851 item = item->li_next;
852 if (arg == NULL)
853 return FAIL;
854
855 arg = skipwhite(arg);
856 if (*arg == ';')
857 {
858 // Put the rest of the list (may be empty) in the var after ';'.
859 // Create a new list for this.
860 l = list_alloc();
861 if (l == NULL)
862 return FAIL;
863 while (item != NULL)
864 {
865 list_append_tv(l, &item->li_tv);
866 item = item->li_next;
867 }
868
869 ltv.v_type = VAR_LIST;
870 ltv.v_lock = 0;
871 ltv.vval.v_list = l;
872 l->lv_refcount = 1;
873
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100874 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE, flags,
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200875 (char_u *)"]", op);
876 clear_tv(&ltv);
877 if (arg == NULL)
878 return FAIL;
879 break;
880 }
881 else if (*arg != ',' && *arg != ']')
882 {
883 internal_error("ex_let_vars()");
884 return FAIL;
885 }
886 }
887
888 return OK;
889}
890
891/*
892 * Skip over assignable variable "var" or list of variables "[var, var]".
893 * Used for ":let varvar = expr" and ":for varvar in expr".
894 * For "[var, var]" increment "*var_count" for each variable.
895 * for "[var, var; var]" set "semicolon".
896 * Return NULL for an error.
897 */
898 char_u *
899skip_var_list(
900 char_u *arg,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100901 int include_type,
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200902 int *var_count,
903 int *semicolon)
904{
905 char_u *p, *s;
906
907 if (*arg == '[')
908 {
909 // "[var, var]": find the matching ']'.
910 p = arg;
911 for (;;)
912 {
913 p = skipwhite(p + 1); // skip whites after '[', ';' or ','
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100914 s = skip_var_one(p, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200915 if (s == p)
916 {
917 semsg(_(e_invarg2), p);
918 return NULL;
919 }
920 ++*var_count;
921
922 p = skipwhite(s);
923 if (*p == ']')
924 break;
925 else if (*p == ';')
926 {
927 if (*semicolon == 1)
928 {
929 emsg(_("Double ; in list of variables"));
930 return NULL;
931 }
932 *semicolon = 1;
933 }
934 else if (*p != ',')
935 {
936 semsg(_(e_invarg2), p);
937 return NULL;
938 }
939 }
940 return p + 1;
941 }
942 else
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100943 return skip_var_one(arg, include_type);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200944}
945
946/*
947 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
948 * l[idx].
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100949 * In Vim9 script also skip over ": type" if "include_type" is TRUE.
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200950 */
951 static char_u *
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100952skip_var_one(char_u *arg, int include_type)
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200953{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100954 char_u *end;
955
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200956 if (*arg == '@' && arg[1] != NUL)
957 return arg + 2;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100958 end = find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200959 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100960 if (include_type && current_sctx.sc_version == SCRIPT_VERSION_VIM9
961 && *end == ':')
962 {
963 end = skip_type(skipwhite(end + 1));
964 }
965 return end;
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200966}
967
968/*
969 * List variables for hashtab "ht" with prefix "prefix".
970 * If "empty" is TRUE also list NULL strings as empty strings.
971 */
972 void
973list_hashtable_vars(
974 hashtab_T *ht,
975 char *prefix,
976 int empty,
977 int *first)
978{
979 hashitem_T *hi;
980 dictitem_T *di;
981 int todo;
982 char_u buf[IOSIZE];
983
984 todo = (int)ht->ht_used;
985 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
986 {
987 if (!HASHITEM_EMPTY(hi))
988 {
989 --todo;
990 di = HI2DI(hi);
991
992 // apply :filter /pat/ to variable name
993 vim_strncpy((char_u *)buf, (char_u *)prefix, IOSIZE - 1);
994 vim_strcat((char_u *)buf, di->di_key, IOSIZE);
995 if (message_filtered(buf))
996 continue;
997
998 if (empty || di->di_tv.v_type != VAR_STRING
999 || di->di_tv.vval.v_string != NULL)
1000 list_one_var(di, prefix, first);
1001 }
1002 }
1003}
1004
1005/*
1006 * List global variables.
1007 */
1008 static void
1009list_glob_vars(int *first)
1010{
1011 list_hashtable_vars(&globvarht, "", TRUE, first);
1012}
1013
1014/*
1015 * List buffer variables.
1016 */
1017 static void
1018list_buf_vars(int *first)
1019{
1020 list_hashtable_vars(&curbuf->b_vars->dv_hashtab, "b:", TRUE, first);
1021}
1022
1023/*
1024 * List window variables.
1025 */
1026 static void
1027list_win_vars(int *first)
1028{
1029 list_hashtable_vars(&curwin->w_vars->dv_hashtab, "w:", TRUE, first);
1030}
1031
1032/*
1033 * List tab page variables.
1034 */
1035 static void
1036list_tab_vars(int *first)
1037{
1038 list_hashtable_vars(&curtab->tp_vars->dv_hashtab, "t:", TRUE, first);
1039}
1040
1041/*
1042 * List variables in "arg".
1043 */
1044 static char_u *
1045list_arg_vars(exarg_T *eap, char_u *arg, int *first)
1046{
1047 int error = FALSE;
1048 int len;
1049 char_u *name;
1050 char_u *name_start;
1051 char_u *arg_subsc;
1052 char_u *tofree;
1053 typval_T tv;
1054
1055 while (!ends_excmd(*arg) && !got_int)
1056 {
1057 if (error || eap->skip)
1058 {
1059 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1060 if (!VIM_ISWHITE(*arg) && !ends_excmd(*arg))
1061 {
1062 emsg_severe = TRUE;
1063 emsg(_(e_trailing));
1064 break;
1065 }
1066 }
1067 else
1068 {
1069 // get_name_len() takes care of expanding curly braces
1070 name_start = name = arg;
1071 len = get_name_len(&arg, &tofree, TRUE, TRUE);
1072 if (len <= 0)
1073 {
1074 // This is mainly to keep test 49 working: when expanding
1075 // curly braces fails overrule the exception error message.
1076 if (len < 0 && !aborting())
1077 {
1078 emsg_severe = TRUE;
1079 semsg(_(e_invarg2), arg);
1080 break;
1081 }
1082 error = TRUE;
1083 }
1084 else
1085 {
1086 if (tofree != NULL)
1087 name = tofree;
1088 if (get_var_tv(name, len, &tv, NULL, TRUE, FALSE) == FAIL)
1089 error = TRUE;
1090 else
1091 {
1092 // handle d.key, l[idx], f(expr)
1093 arg_subsc = arg;
1094 if (handle_subscript(&arg, &tv, TRUE, TRUE,
1095 name, &name) == FAIL)
1096 error = TRUE;
1097 else
1098 {
1099 if (arg == arg_subsc && len == 2 && name[1] == ':')
1100 {
1101 switch (*name)
1102 {
1103 case 'g': list_glob_vars(first); break;
1104 case 'b': list_buf_vars(first); break;
1105 case 'w': list_win_vars(first); break;
1106 case 't': list_tab_vars(first); break;
1107 case 'v': list_vim_vars(first); break;
1108 case 's': list_script_vars(first); break;
1109 case 'l': list_func_vars(first); break;
1110 default:
1111 semsg(_("E738: Can't list variables for %s"), name);
1112 }
1113 }
1114 else
1115 {
1116 char_u numbuf[NUMBUFLEN];
1117 char_u *tf;
1118 int c;
1119 char_u *s;
1120
1121 s = echo_string(&tv, &tf, numbuf, 0);
1122 c = *arg;
1123 *arg = NUL;
1124 list_one_var_a("",
1125 arg == arg_subsc ? name : name_start,
1126 tv.v_type,
1127 s == NULL ? (char_u *)"" : s,
1128 first);
1129 *arg = c;
1130 vim_free(tf);
1131 }
1132 clear_tv(&tv);
1133 }
1134 }
1135 }
1136
1137 vim_free(tofree);
1138 }
1139
1140 arg = skipwhite(arg);
1141 }
1142
1143 return arg;
1144}
1145
1146/*
1147 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
1148 * Returns a pointer to the char just after the var name.
1149 * Returns NULL if there is an error.
1150 */
1151 static char_u *
1152ex_let_one(
1153 char_u *arg, // points to variable name
1154 typval_T *tv, // value to assign to variable
1155 int copy, // copy value from "tv"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001156 int flags, // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001157 char_u *endchars, // valid chars after variable name or NULL
1158 char_u *op) // "+", "-", "." or NULL
1159{
1160 int c1;
1161 char_u *name;
1162 char_u *p;
1163 char_u *arg_end = NULL;
1164 int len;
1165 int opt_flags;
1166 char_u *tofree = NULL;
1167
1168 // ":let $VAR = expr": Set environment variable.
1169 if (*arg == '$')
1170 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001171 if (flags & LET_IS_CONST)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001172 {
1173 emsg(_("E996: Cannot lock an environment variable"));
1174 return NULL;
1175 }
1176 // Find the end of the name.
1177 ++arg;
1178 name = arg;
1179 len = get_env_len(&arg);
1180 if (len == 0)
1181 semsg(_(e_invarg2), name - 1);
1182 else
1183 {
1184 if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL)
1185 semsg(_(e_letwrong), op);
1186 else if (endchars != NULL
1187 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
1188 emsg(_(e_letunexp));
1189 else if (!check_secure())
1190 {
1191 c1 = name[len];
1192 name[len] = NUL;
1193 p = tv_get_string_chk(tv);
1194 if (p != NULL && op != NULL && *op == '.')
1195 {
1196 int mustfree = FALSE;
1197 char_u *s = vim_getenv(name, &mustfree);
1198
1199 if (s != NULL)
1200 {
1201 p = tofree = concat_str(s, p);
1202 if (mustfree)
1203 vim_free(s);
1204 }
1205 }
1206 if (p != NULL)
1207 {
1208 vim_setenv(name, p);
1209 if (STRICMP(name, "HOME") == 0)
1210 init_homedir();
1211 else if (didset_vim && STRICMP(name, "VIM") == 0)
1212 didset_vim = FALSE;
1213 else if (didset_vimruntime
1214 && STRICMP(name, "VIMRUNTIME") == 0)
1215 didset_vimruntime = FALSE;
1216 arg_end = arg;
1217 }
1218 name[len] = c1;
1219 vim_free(tofree);
1220 }
1221 }
1222 }
1223
1224 // ":let &option = expr": Set option value.
1225 // ":let &l:option = expr": Set local option value.
1226 // ":let &g:option = expr": Set global option value.
1227 else if (*arg == '&')
1228 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001229 if (flags & LET_IS_CONST)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001230 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001231 emsg(_(e_const_option));
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001232 return NULL;
1233 }
1234 // Find the end of the name.
1235 p = find_option_end(&arg, &opt_flags);
1236 if (p == NULL || (endchars != NULL
1237 && vim_strchr(endchars, *skipwhite(p)) == NULL))
1238 emsg(_(e_letunexp));
1239 else
1240 {
1241 long n;
1242 int opt_type;
1243 long numval;
1244 char_u *stringval = NULL;
1245 char_u *s;
1246
1247 c1 = *p;
1248 *p = NUL;
1249
1250 n = (long)tv_get_number(tv);
1251 s = tv_get_string_chk(tv); // != NULL if number or string
1252 if (s != NULL && op != NULL && *op != '=')
1253 {
1254 opt_type = get_option_value(arg, &numval,
1255 &stringval, opt_flags);
1256 if ((opt_type == 1 && *op == '.')
1257 || (opt_type == 0 && *op != '.'))
1258 {
1259 semsg(_(e_letwrong), op);
1260 s = NULL; // don't set the value
1261 }
1262 else
1263 {
1264 if (opt_type == 1) // number
1265 {
1266 switch (*op)
1267 {
1268 case '+': n = numval + n; break;
1269 case '-': n = numval - n; break;
1270 case '*': n = numval * n; break;
1271 case '/': n = (long)num_divide(numval, n); break;
1272 case '%': n = (long)num_modulus(numval, n); break;
1273 }
1274 }
1275 else if (opt_type == 0 && stringval != NULL) // string
1276 {
1277 s = concat_str(stringval, s);
1278 vim_free(stringval);
1279 stringval = s;
1280 }
1281 }
1282 }
1283 if (s != NULL)
1284 {
1285 set_option_value(arg, n, s, opt_flags);
1286 arg_end = p;
1287 }
1288 *p = c1;
1289 vim_free(stringval);
1290 }
1291 }
1292
1293 // ":let @r = expr": Set register contents.
1294 else if (*arg == '@')
1295 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001296 if (flags & LET_IS_CONST)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001297 {
1298 emsg(_("E996: Cannot lock a register"));
1299 return NULL;
1300 }
1301 ++arg;
1302 if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL)
1303 semsg(_(e_letwrong), op);
1304 else if (endchars != NULL
1305 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
1306 emsg(_(e_letunexp));
1307 else
1308 {
1309 char_u *ptofree = NULL;
1310 char_u *s;
1311
1312 p = tv_get_string_chk(tv);
1313 if (p != NULL && op != NULL && *op == '.')
1314 {
1315 s = get_reg_contents(*arg == '@' ? '"' : *arg, GREG_EXPR_SRC);
1316 if (s != NULL)
1317 {
1318 p = ptofree = concat_str(s, p);
1319 vim_free(s);
1320 }
1321 }
1322 if (p != NULL)
1323 {
1324 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
1325 arg_end = arg + 1;
1326 }
1327 vim_free(ptofree);
1328 }
1329 }
1330
1331 // ":let var = expr": Set internal variable.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001332 // ":let var: type = expr": Set internal variable with type.
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001333 // ":let {expr} = expr": Idem, name made with curly braces
1334 else if (eval_isnamec1(*arg) || *arg == '{')
1335 {
1336 lval_T lv;
1337
1338 p = get_lval(arg, tv, &lv, FALSE, FALSE, 0, FNE_CHECK_START);
1339 if (p != NULL && lv.ll_name != NULL)
1340 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001341 if (endchars != NULL && vim_strchr(endchars,
1342 *skipwhite(lv.ll_name_end)) == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001343 emsg(_(e_letunexp));
1344 else
1345 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001346 set_var_lval(&lv, p, tv, copy, flags, op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001347 arg_end = p;
1348 }
1349 }
1350 clear_lval(&lv);
1351 }
1352
1353 else
1354 semsg(_(e_invarg2), arg);
1355
1356 return arg_end;
1357}
1358
1359/*
1360 * ":unlet[!] var1 ... " command.
1361 */
1362 void
1363ex_unlet(exarg_T *eap)
1364{
1365 ex_unletlock(eap, eap->arg, 0);
1366}
1367
1368/*
1369 * ":lockvar" and ":unlockvar" commands
1370 */
1371 void
1372ex_lockvar(exarg_T *eap)
1373{
1374 char_u *arg = eap->arg;
1375 int deep = 2;
1376
1377 if (eap->forceit)
1378 deep = -1;
1379 else if (vim_isdigit(*arg))
1380 {
1381 deep = getdigits(&arg);
1382 arg = skipwhite(arg);
1383 }
1384
1385 ex_unletlock(eap, arg, deep);
1386}
1387
1388/*
1389 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
1390 */
1391 static void
1392ex_unletlock(
1393 exarg_T *eap,
1394 char_u *argstart,
1395 int deep)
1396{
1397 char_u *arg = argstart;
1398 char_u *name_end;
1399 int error = FALSE;
1400 lval_T lv;
1401
1402 do
1403 {
1404 if (*arg == '$')
1405 {
1406 char_u *name = ++arg;
1407
1408 if (get_env_len(&arg) == 0)
1409 {
1410 semsg(_(e_invarg2), name - 1);
1411 return;
1412 }
1413 vim_unsetenv(name);
1414 arg = skipwhite(arg);
1415 continue;
1416 }
1417
1418 // Parse the name and find the end.
1419 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, 0,
1420 FNE_CHECK_START);
1421 if (lv.ll_name == NULL)
1422 error = TRUE; // error but continue parsing
1423 if (name_end == NULL || (!VIM_ISWHITE(*name_end)
1424 && !ends_excmd(*name_end)))
1425 {
1426 if (name_end != NULL)
1427 {
1428 emsg_severe = TRUE;
1429 emsg(_(e_trailing));
1430 }
1431 if (!(eap->skip || error))
1432 clear_lval(&lv);
1433 break;
1434 }
1435
1436 if (!error && !eap->skip)
1437 {
1438 if (eap->cmdidx == CMD_unlet)
1439 {
1440 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
1441 error = TRUE;
1442 }
1443 else
1444 {
1445 if (do_lock_var(&lv, name_end, deep,
1446 eap->cmdidx == CMD_lockvar) == FAIL)
1447 error = TRUE;
1448 }
1449 }
1450
1451 if (!eap->skip)
1452 clear_lval(&lv);
1453
1454 arg = skipwhite(name_end);
1455 } while (!ends_excmd(*arg));
1456
1457 eap->nextcmd = check_nextcmd(arg);
1458}
1459
1460 static int
1461do_unlet_var(
1462 lval_T *lp,
1463 char_u *name_end,
1464 int forceit)
1465{
1466 int ret = OK;
1467 int cc;
1468
1469 if (lp->ll_tv == NULL)
1470 {
1471 cc = *name_end;
1472 *name_end = NUL;
1473
1474 // Normal name or expanded name.
1475 if (do_unlet(lp->ll_name, forceit) == FAIL)
1476 ret = FAIL;
1477 *name_end = cc;
1478 }
1479 else if ((lp->ll_list != NULL
1480 && var_check_lock(lp->ll_list->lv_lock, lp->ll_name, FALSE))
1481 || (lp->ll_dict != NULL
1482 && var_check_lock(lp->ll_dict->dv_lock, lp->ll_name, FALSE)))
1483 return FAIL;
1484 else if (lp->ll_range)
1485 {
1486 listitem_T *li;
1487 listitem_T *ll_li = lp->ll_li;
1488 int ll_n1 = lp->ll_n1;
1489
1490 while (ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= ll_n1))
1491 {
1492 li = ll_li->li_next;
1493 if (var_check_lock(ll_li->li_tv.v_lock, lp->ll_name, FALSE))
1494 return FAIL;
1495 ll_li = li;
1496 ++ll_n1;
1497 }
1498
1499 // Delete a range of List items.
1500 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
1501 {
1502 li = lp->ll_li->li_next;
1503 listitem_remove(lp->ll_list, lp->ll_li);
1504 lp->ll_li = li;
1505 ++lp->ll_n1;
1506 }
1507 }
1508 else
1509 {
1510 if (lp->ll_list != NULL)
1511 // unlet a List item.
1512 listitem_remove(lp->ll_list, lp->ll_li);
1513 else
1514 // unlet a Dictionary item.
1515 dictitem_remove(lp->ll_dict, lp->ll_di);
1516 }
1517
1518 return ret;
1519}
1520
1521/*
1522 * "unlet" a variable. Return OK if it existed, FAIL if not.
1523 * When "forceit" is TRUE don't complain if the variable doesn't exist.
1524 */
1525 int
1526do_unlet(char_u *name, int forceit)
1527{
1528 hashtab_T *ht;
1529 hashitem_T *hi;
1530 char_u *varname;
1531 dict_T *d;
1532 dictitem_T *di;
1533
1534 ht = find_var_ht(name, &varname);
1535 if (ht != NULL && *varname != NUL)
1536 {
1537 d = get_current_funccal_dict(ht);
1538 if (d == NULL)
1539 {
1540 if (ht == &globvarht)
1541 d = &globvardict;
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001542 else if (ht == &compat_hashtab)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001543 d = &vimvardict;
1544 else
1545 {
1546 di = find_var_in_ht(ht, *name, (char_u *)"", FALSE);
1547 d = di == NULL ? NULL : di->di_tv.vval.v_dict;
1548 }
1549 if (d == NULL)
1550 {
1551 internal_error("do_unlet()");
1552 return FAIL;
1553 }
1554 }
1555 hi = hash_find(ht, varname);
1556 if (HASHITEM_EMPTY(hi))
1557 hi = find_hi_in_scoped_ht(name, &ht);
1558 if (hi != NULL && !HASHITEM_EMPTY(hi))
1559 {
1560 di = HI2DI(hi);
1561 if (var_check_fixed(di->di_flags, name, FALSE)
1562 || var_check_ro(di->di_flags, name, FALSE)
1563 || var_check_lock(d->dv_lock, name, FALSE))
1564 return FAIL;
1565
1566 delete_var(ht, hi);
1567 return OK;
1568 }
1569 }
1570 if (forceit)
1571 return OK;
1572 semsg(_("E108: No such variable: \"%s\""), name);
1573 return FAIL;
1574}
1575
1576/*
1577 * Lock or unlock variable indicated by "lp".
1578 * "deep" is the levels to go (-1 for unlimited);
1579 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
1580 */
1581 static int
1582do_lock_var(
1583 lval_T *lp,
1584 char_u *name_end,
1585 int deep,
1586 int lock)
1587{
1588 int ret = OK;
1589 int cc;
1590 dictitem_T *di;
1591
1592 if (deep == 0) // nothing to do
1593 return OK;
1594
1595 if (lp->ll_tv == NULL)
1596 {
1597 cc = *name_end;
1598 *name_end = NUL;
1599
1600 // Normal name or expanded name.
1601 di = find_var(lp->ll_name, NULL, TRUE);
1602 if (di == NULL)
1603 ret = FAIL;
1604 else if ((di->di_flags & DI_FLAGS_FIX)
1605 && di->di_tv.v_type != VAR_DICT
1606 && di->di_tv.v_type != VAR_LIST)
1607 // For historic reasons this error is not given for a list or dict.
1608 // E.g., the b: dict could be locked/unlocked.
1609 semsg(_("E940: Cannot lock or unlock variable %s"), lp->ll_name);
1610 else
1611 {
1612 if (lock)
1613 di->di_flags |= DI_FLAGS_LOCK;
1614 else
1615 di->di_flags &= ~DI_FLAGS_LOCK;
1616 item_lock(&di->di_tv, deep, lock);
1617 }
1618 *name_end = cc;
1619 }
1620 else if (lp->ll_range)
1621 {
1622 listitem_T *li = lp->ll_li;
1623
1624 // (un)lock a range of List items.
1625 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
1626 {
1627 item_lock(&li->li_tv, deep, lock);
1628 li = li->li_next;
1629 ++lp->ll_n1;
1630 }
1631 }
1632 else if (lp->ll_list != NULL)
1633 // (un)lock a List item.
1634 item_lock(&lp->ll_li->li_tv, deep, lock);
1635 else
1636 // (un)lock a Dictionary item.
1637 item_lock(&lp->ll_di->di_tv, deep, lock);
1638
1639 return ret;
1640}
1641
1642/*
1643 * Lock or unlock an item. "deep" is nr of levels to go.
1644 */
1645 static void
1646item_lock(typval_T *tv, int deep, int lock)
1647{
1648 static int recurse = 0;
1649 list_T *l;
1650 listitem_T *li;
1651 dict_T *d;
1652 blob_T *b;
1653 hashitem_T *hi;
1654 int todo;
1655
1656 if (recurse >= DICT_MAXNEST)
1657 {
1658 emsg(_("E743: variable nested too deep for (un)lock"));
1659 return;
1660 }
1661 if (deep == 0)
1662 return;
1663 ++recurse;
1664
1665 // lock/unlock the item itself
1666 if (lock)
1667 tv->v_lock |= VAR_LOCKED;
1668 else
1669 tv->v_lock &= ~VAR_LOCKED;
1670
1671 switch (tv->v_type)
1672 {
1673 case VAR_UNKNOWN:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001674 case VAR_VOID:
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001675 case VAR_NUMBER:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001676 case VAR_BOOL:
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001677 case VAR_STRING:
1678 case VAR_FUNC:
1679 case VAR_PARTIAL:
1680 case VAR_FLOAT:
1681 case VAR_SPECIAL:
1682 case VAR_JOB:
1683 case VAR_CHANNEL:
1684 break;
1685
1686 case VAR_BLOB:
1687 if ((b = tv->vval.v_blob) != NULL)
1688 {
1689 if (lock)
1690 b->bv_lock |= VAR_LOCKED;
1691 else
1692 b->bv_lock &= ~VAR_LOCKED;
1693 }
1694 break;
1695 case VAR_LIST:
1696 if ((l = tv->vval.v_list) != NULL)
1697 {
1698 if (lock)
1699 l->lv_lock |= VAR_LOCKED;
1700 else
1701 l->lv_lock &= ~VAR_LOCKED;
1702 if (deep < 0 || deep > 1)
1703 // recursive: lock/unlock the items the List contains
1704 for (li = l->lv_first; li != NULL; li = li->li_next)
1705 item_lock(&li->li_tv, deep - 1, lock);
1706 }
1707 break;
1708 case VAR_DICT:
1709 if ((d = tv->vval.v_dict) != NULL)
1710 {
1711 if (lock)
1712 d->dv_lock |= VAR_LOCKED;
1713 else
1714 d->dv_lock &= ~VAR_LOCKED;
1715 if (deep < 0 || deep > 1)
1716 {
1717 // recursive: lock/unlock the items the List contains
1718 todo = (int)d->dv_hashtab.ht_used;
1719 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
1720 {
1721 if (!HASHITEM_EMPTY(hi))
1722 {
1723 --todo;
1724 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
1725 }
1726 }
1727 }
1728 }
1729 }
1730 --recurse;
1731}
1732
Bram Moolenaarda6c0332019-09-01 16:01:30 +02001733#if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
1734/*
1735 * Delete all "menutrans_" variables.
1736 */
1737 void
1738del_menutrans_vars(void)
1739{
1740 hashitem_T *hi;
1741 int todo;
1742
1743 hash_lock(&globvarht);
1744 todo = (int)globvarht.ht_used;
1745 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
1746 {
1747 if (!HASHITEM_EMPTY(hi))
1748 {
1749 --todo;
1750 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
1751 delete_var(&globvarht, hi);
1752 }
1753 }
1754 hash_unlock(&globvarht);
1755}
1756#endif
1757
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001758/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001759 * Local string buffer for the next two functions to store a variable name
1760 * with its prefix. Allocated in cat_prefix_varname(), freed later in
1761 * get_user_var_name().
1762 */
1763
1764static char_u *varnamebuf = NULL;
1765static int varnamebuflen = 0;
1766
1767/*
1768 * Function to concatenate a prefix and a variable name.
1769 */
1770 static char_u *
1771cat_prefix_varname(int prefix, char_u *name)
1772{
1773 int len;
1774
1775 len = (int)STRLEN(name) + 3;
1776 if (len > varnamebuflen)
1777 {
1778 vim_free(varnamebuf);
Bram Moolenaar8d71b542019-08-30 15:46:30 +02001779 len += 10; // some additional space
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001780 varnamebuf = alloc(len);
1781 if (varnamebuf == NULL)
1782 {
1783 varnamebuflen = 0;
1784 return NULL;
1785 }
1786 varnamebuflen = len;
1787 }
1788 *varnamebuf = prefix;
1789 varnamebuf[1] = ':';
1790 STRCPY(varnamebuf + 2, name);
1791 return varnamebuf;
1792}
1793
1794/*
1795 * Function given to ExpandGeneric() to obtain the list of user defined
1796 * (global/buffer/window/built-in) variable names.
1797 */
1798 char_u *
1799get_user_var_name(expand_T *xp, int idx)
1800{
1801 static long_u gdone;
1802 static long_u bdone;
1803 static long_u wdone;
1804 static long_u tdone;
1805 static int vidx;
1806 static hashitem_T *hi;
1807 hashtab_T *ht;
1808
1809 if (idx == 0)
1810 {
1811 gdone = bdone = wdone = vidx = 0;
1812 tdone = 0;
1813 }
1814
1815 // Global variables
1816 if (gdone < globvarht.ht_used)
1817 {
1818 if (gdone++ == 0)
1819 hi = globvarht.ht_array;
1820 else
1821 ++hi;
1822 while (HASHITEM_EMPTY(hi))
1823 ++hi;
1824 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
1825 return cat_prefix_varname('g', hi->hi_key);
1826 return hi->hi_key;
1827 }
1828
1829 // b: variables
1830 ht = &curbuf->b_vars->dv_hashtab;
1831 if (bdone < ht->ht_used)
1832 {
1833 if (bdone++ == 0)
1834 hi = ht->ht_array;
1835 else
1836 ++hi;
1837 while (HASHITEM_EMPTY(hi))
1838 ++hi;
1839 return cat_prefix_varname('b', hi->hi_key);
1840 }
1841
1842 // w: variables
1843 ht = &curwin->w_vars->dv_hashtab;
1844 if (wdone < ht->ht_used)
1845 {
1846 if (wdone++ == 0)
1847 hi = ht->ht_array;
1848 else
1849 ++hi;
1850 while (HASHITEM_EMPTY(hi))
1851 ++hi;
1852 return cat_prefix_varname('w', hi->hi_key);
1853 }
1854
1855 // t: variables
1856 ht = &curtab->tp_vars->dv_hashtab;
1857 if (tdone < ht->ht_used)
1858 {
1859 if (tdone++ == 0)
1860 hi = ht->ht_array;
1861 else
1862 ++hi;
1863 while (HASHITEM_EMPTY(hi))
1864 ++hi;
1865 return cat_prefix_varname('t', hi->hi_key);
1866 }
1867
1868 // v: variables
1869 if (vidx < VV_LEN)
1870 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
1871
1872 VIM_CLEAR(varnamebuf);
1873 varnamebuflen = 0;
1874 return NULL;
1875}
1876
Bram Moolenaarda6c0332019-09-01 16:01:30 +02001877 char *
1878get_var_special_name(int nr)
1879{
1880 switch (nr)
1881 {
1882 case VVAL_FALSE: return "v:false";
1883 case VVAL_TRUE: return "v:true";
1884 case VVAL_NONE: return "v:none";
1885 case VVAL_NULL: return "v:null";
1886 }
1887 internal_error("get_var_special_name()");
1888 return "42";
1889}
1890
1891/*
1892 * Returns the global variable dictionary
1893 */
1894 dict_T *
1895get_globvar_dict(void)
1896{
1897 return &globvardict;
1898}
1899
1900/*
1901 * Returns the global variable hash table
1902 */
1903 hashtab_T *
1904get_globvar_ht(void)
1905{
1906 return &globvarht;
1907}
1908
1909/*
1910 * Returns the v: variable dictionary
1911 */
1912 dict_T *
1913get_vimvar_dict(void)
1914{
1915 return &vimvardict;
1916}
1917
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001918/*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001919 * Returns the index of a v:variable. Negative if not found.
1920 */
1921 int
1922find_vim_var(char_u *name)
1923{
1924 dictitem_T *di = find_var_in_ht(&vimvarht, 0, name, TRUE);
1925 struct vimvar *vv;
1926
1927 if (di == NULL)
1928 return -1;
1929 vv = (struct vimvar *)((char *)di - offsetof(vimvar_T, vv_di));
1930 return (int)(vv - vimvars);
1931}
1932
1933
1934/*
Bram Moolenaar34ed68d2019-08-29 22:48:24 +02001935 * Set type of v: variable to "type".
1936 */
1937 void
1938set_vim_var_type(int idx, vartype_T type)
1939{
1940 vimvars[idx].vv_type = type;
1941}
1942
1943/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001944 * Set number v: variable to "val".
Bram Moolenaar8d71b542019-08-30 15:46:30 +02001945 * Note that this does not set the type, use set_vim_var_type() for that.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001946 */
1947 void
1948set_vim_var_nr(int idx, varnumber_T val)
1949{
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001950 vimvars[idx].vv_nr = val;
1951}
1952
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001953 char *
1954get_vim_var_name(int idx)
1955{
1956 return vimvars[idx].vv_name;
1957}
1958
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001959/*
1960 * Get typval_T v: variable value.
1961 */
1962 typval_T *
1963get_vim_var_tv(int idx)
1964{
1965 return &vimvars[idx].vv_tv;
1966}
1967
1968/*
1969 * Get number v: variable value.
1970 */
1971 varnumber_T
1972get_vim_var_nr(int idx)
1973{
1974 return vimvars[idx].vv_nr;
1975}
1976
1977/*
1978 * Get string v: variable value. Uses a static buffer, can only be used once.
1979 * If the String variable has never been set, return an empty string.
1980 * Never returns NULL;
1981 */
1982 char_u *
1983get_vim_var_str(int idx)
1984{
1985 return tv_get_string(&vimvars[idx].vv_tv);
1986}
1987
1988/*
1989 * Get List v: variable value. Caller must take care of reference count when
1990 * needed.
1991 */
1992 list_T *
1993get_vim_var_list(int idx)
1994{
1995 return vimvars[idx].vv_list;
1996}
1997
1998/*
1999 * Get Dict v: variable value. Caller must take care of reference count when
2000 * needed.
2001 */
2002 dict_T *
2003get_vim_var_dict(int idx)
2004{
2005 return vimvars[idx].vv_dict;
2006}
2007
2008/*
2009 * Set v:char to character "c".
2010 */
2011 void
2012set_vim_var_char(int c)
2013{
2014 char_u buf[MB_MAXBYTES + 1];
2015
2016 if (has_mbyte)
2017 buf[(*mb_char2bytes)(c, buf)] = NUL;
2018 else
2019 {
2020 buf[0] = c;
2021 buf[1] = NUL;
2022 }
2023 set_vim_var_string(VV_CHAR, buf, -1);
2024}
2025
2026/*
2027 * Set v:count to "count" and v:count1 to "count1".
2028 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
2029 */
2030 void
2031set_vcount(
2032 long count,
2033 long count1,
2034 int set_prevcount)
2035{
2036 if (set_prevcount)
2037 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
2038 vimvars[VV_COUNT].vv_nr = count;
2039 vimvars[VV_COUNT1].vv_nr = count1;
2040}
2041
2042/*
2043 * Save variables that might be changed as a side effect. Used when executing
2044 * a timer callback.
2045 */
2046 void
2047save_vimvars(vimvars_save_T *vvsave)
2048{
2049 vvsave->vv_prevcount = vimvars[VV_PREVCOUNT].vv_nr;
2050 vvsave->vv_count = vimvars[VV_COUNT].vv_nr;
2051 vvsave->vv_count1 = vimvars[VV_COUNT1].vv_nr;
2052}
2053
2054/*
2055 * Restore variables saved by save_vimvars().
2056 */
2057 void
2058restore_vimvars(vimvars_save_T *vvsave)
2059{
2060 vimvars[VV_PREVCOUNT].vv_nr = vvsave->vv_prevcount;
2061 vimvars[VV_COUNT].vv_nr = vvsave->vv_count;
2062 vimvars[VV_COUNT1].vv_nr = vvsave->vv_count1;
2063}
2064
2065/*
2066 * Set string v: variable to a copy of "val". If 'copy' is FALSE, then set the
2067 * value.
2068 */
2069 void
2070set_vim_var_string(
2071 int idx,
2072 char_u *val,
2073 int len) // length of "val" to use or -1 (whole string)
2074{
2075 clear_tv(&vimvars[idx].vv_di.di_tv);
2076 vimvars[idx].vv_type = VAR_STRING;
2077 if (val == NULL)
2078 vimvars[idx].vv_str = NULL;
2079 else if (len == -1)
2080 vimvars[idx].vv_str = vim_strsave(val);
2081 else
2082 vimvars[idx].vv_str = vim_strnsave(val, len);
2083}
2084
2085/*
2086 * Set List v: variable to "val".
2087 */
2088 void
2089set_vim_var_list(int idx, list_T *val)
2090{
2091 clear_tv(&vimvars[idx].vv_di.di_tv);
2092 vimvars[idx].vv_type = VAR_LIST;
2093 vimvars[idx].vv_list = val;
2094 if (val != NULL)
2095 ++val->lv_refcount;
2096}
2097
2098/*
2099 * Set Dictionary v: variable to "val".
2100 */
2101 void
2102set_vim_var_dict(int idx, dict_T *val)
2103{
2104 clear_tv(&vimvars[idx].vv_di.di_tv);
2105 vimvars[idx].vv_type = VAR_DICT;
2106 vimvars[idx].vv_dict = val;
2107 if (val != NULL)
2108 {
2109 ++val->dv_refcount;
2110 dict_set_items_ro(val);
2111 }
2112}
2113
2114/*
Bram Moolenaar69bf6342019-10-29 04:16:57 +01002115 * Set the v:argv list.
2116 */
2117 void
2118set_argv_var(char **argv, int argc)
2119{
2120 list_T *l = list_alloc();
2121 int i;
2122
2123 if (l == NULL)
2124 getout(1);
2125 l->lv_lock = VAR_FIXED;
2126 for (i = 0; i < argc; ++i)
2127 {
2128 if (list_append_string(l, (char_u *)argv[i], -1) == FAIL)
2129 getout(1);
2130 l->lv_last->li_tv.v_lock = VAR_FIXED;
2131 }
2132 set_vim_var_list(VV_ARGV, l);
2133}
2134
2135/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002136 * Set v:register if needed.
2137 */
2138 void
2139set_reg_var(int c)
2140{
2141 char_u regname;
2142
2143 if (c == 0 || c == ' ')
2144 regname = '"';
2145 else
2146 regname = c;
2147 // Avoid free/alloc when the value is already right.
2148 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
2149 set_vim_var_string(VV_REG, &regname, 1);
2150}
2151
2152/*
2153 * Get or set v:exception. If "oldval" == NULL, return the current value.
2154 * Otherwise, restore the value to "oldval" and return NULL.
2155 * Must always be called in pairs to save and restore v:exception! Does not
2156 * take care of memory allocations.
2157 */
2158 char_u *
2159v_exception(char_u *oldval)
2160{
2161 if (oldval == NULL)
2162 return vimvars[VV_EXCEPTION].vv_str;
2163
2164 vimvars[VV_EXCEPTION].vv_str = oldval;
2165 return NULL;
2166}
2167
2168/*
2169 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
2170 * Otherwise, restore the value to "oldval" and return NULL.
2171 * Must always be called in pairs to save and restore v:throwpoint! Does not
2172 * take care of memory allocations.
2173 */
2174 char_u *
2175v_throwpoint(char_u *oldval)
2176{
2177 if (oldval == NULL)
2178 return vimvars[VV_THROWPOINT].vv_str;
2179
2180 vimvars[VV_THROWPOINT].vv_str = oldval;
2181 return NULL;
2182}
2183
2184/*
2185 * Set v:cmdarg.
2186 * If "eap" != NULL, use "eap" to generate the value and return the old value.
2187 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
2188 * Must always be called in pairs!
2189 */
2190 char_u *
2191set_cmdarg(exarg_T *eap, char_u *oldarg)
2192{
2193 char_u *oldval;
2194 char_u *newval;
2195 unsigned len;
2196
2197 oldval = vimvars[VV_CMDARG].vv_str;
2198 if (eap == NULL)
2199 {
2200 vim_free(oldval);
2201 vimvars[VV_CMDARG].vv_str = oldarg;
2202 return NULL;
2203 }
2204
2205 if (eap->force_bin == FORCE_BIN)
2206 len = 6;
2207 else if (eap->force_bin == FORCE_NOBIN)
2208 len = 8;
2209 else
2210 len = 0;
2211
2212 if (eap->read_edit)
2213 len += 7;
2214
2215 if (eap->force_ff != 0)
2216 len += 10; // " ++ff=unix"
2217 if (eap->force_enc != 0)
2218 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
2219 if (eap->bad_char != 0)
2220 len += 7 + 4; // " ++bad=" + "keep" or "drop"
2221
2222 newval = alloc(len + 1);
2223 if (newval == NULL)
2224 return NULL;
2225
2226 if (eap->force_bin == FORCE_BIN)
2227 sprintf((char *)newval, " ++bin");
2228 else if (eap->force_bin == FORCE_NOBIN)
2229 sprintf((char *)newval, " ++nobin");
2230 else
2231 *newval = NUL;
2232
2233 if (eap->read_edit)
2234 STRCAT(newval, " ++edit");
2235
2236 if (eap->force_ff != 0)
2237 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
2238 eap->force_ff == 'u' ? "unix"
2239 : eap->force_ff == 'd' ? "dos"
2240 : "mac");
2241 if (eap->force_enc != 0)
2242 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
2243 eap->cmd + eap->force_enc);
2244 if (eap->bad_char == BAD_KEEP)
2245 STRCPY(newval + STRLEN(newval), " ++bad=keep");
2246 else if (eap->bad_char == BAD_DROP)
2247 STRCPY(newval + STRLEN(newval), " ++bad=drop");
2248 else if (eap->bad_char != 0)
2249 sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
2250 vimvars[VV_CMDARG].vv_str = newval;
2251 return oldval;
2252}
2253
2254/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002255 * Get the value of internal variable "name".
2256 * Return OK or FAIL. If OK is returned "rettv" must be cleared.
2257 */
2258 int
2259get_var_tv(
2260 char_u *name,
2261 int len, // length of "name"
2262 typval_T *rettv, // NULL when only checking existence
2263 dictitem_T **dip, // non-NULL when typval's dict item is needed
2264 int verbose, // may give error message
2265 int no_autoload) // do not use script autoloading
2266{
2267 int ret = OK;
2268 typval_T *tv = NULL;
2269 dictitem_T *v;
2270 int cc;
2271
2272 // truncate the name, so that we can use strcmp()
2273 cc = name[len];
2274 name[len] = NUL;
2275
2276 // Check for user-defined variables.
2277 v = find_var(name, NULL, no_autoload);
2278 if (v != NULL)
2279 {
2280 tv = &v->di_tv;
2281 if (dip != NULL)
2282 *dip = v;
2283 }
2284
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002285 if (tv == NULL && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2286 {
2287 imported_T *import = find_imported(name, NULL);
2288
2289 // imported variable from another script
2290 if (import != NULL)
2291 {
2292 scriptitem_T *si = &SCRIPT_ITEM(import->imp_sid);
2293 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data)
2294 + import->imp_var_vals_idx;
2295 tv = sv->sv_tv;
2296 }
2297 }
2298
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002299 if (tv == NULL)
2300 {
2301 if (rettv != NULL && verbose)
2302 semsg(_(e_undefvar), name);
2303 ret = FAIL;
2304 }
2305 else if (rettv != NULL)
2306 copy_tv(tv, rettv);
2307
2308 name[len] = cc;
2309
2310 return ret;
2311}
2312
2313/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002314 * Check if variable "name[len]" is a local variable or an argument.
2315 * If so, "*eval_lavars_used" is set to TRUE.
2316 */
2317 void
2318check_vars(char_u *name, int len)
2319{
2320 int cc;
2321 char_u *varname;
2322 hashtab_T *ht;
2323
2324 if (eval_lavars_used == NULL)
2325 return;
2326
2327 // truncate the name, so that we can use strcmp()
2328 cc = name[len];
2329 name[len] = NUL;
2330
2331 ht = find_var_ht(name, &varname);
2332 if (ht == get_funccal_local_ht() || ht == get_funccal_args_ht())
2333 {
2334 if (find_var(name, NULL, TRUE) != NULL)
2335 *eval_lavars_used = TRUE;
2336 }
2337
2338 name[len] = cc;
2339}
2340
2341/*
2342 * Find variable "name" in the list of variables.
2343 * Return a pointer to it if found, NULL if not found.
2344 * Careful: "a:0" variables don't have a name.
2345 * When "htp" is not NULL we are writing to the variable, set "htp" to the
2346 * hashtab_T used.
2347 */
2348 dictitem_T *
2349find_var(char_u *name, hashtab_T **htp, int no_autoload)
2350{
2351 char_u *varname;
2352 hashtab_T *ht;
2353 dictitem_T *ret = NULL;
2354
2355 ht = find_var_ht(name, &varname);
2356 if (htp != NULL)
2357 *htp = ht;
2358 if (ht == NULL)
2359 return NULL;
2360 ret = find_var_in_ht(ht, *name, varname, no_autoload || htp != NULL);
2361 if (ret != NULL)
2362 return ret;
2363
Bram Moolenaar8d71b542019-08-30 15:46:30 +02002364 // Search in parent scope for lambda
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002365 return find_var_in_scoped_ht(name, no_autoload || htp != NULL);
2366}
2367
2368/*
2369 * Find variable "varname" in hashtab "ht" with name "htname".
2370 * Returns NULL if not found.
2371 */
2372 dictitem_T *
2373find_var_in_ht(
2374 hashtab_T *ht,
2375 int htname,
2376 char_u *varname,
2377 int no_autoload)
2378{
2379 hashitem_T *hi;
2380
2381 if (*varname == NUL)
2382 {
2383 // Must be something like "s:", otherwise "ht" would be NULL.
2384 switch (htname)
2385 {
2386 case 's': return &SCRIPT_SV(current_sctx.sc_sid)->sv_var;
2387 case 'g': return &globvars_var;
2388 case 'v': return &vimvars_var;
2389 case 'b': return &curbuf->b_bufvar;
2390 case 'w': return &curwin->w_winvar;
2391 case 't': return &curtab->tp_winvar;
2392 case 'l': return get_funccal_local_var();
2393 case 'a': return get_funccal_args_var();
2394 }
2395 return NULL;
2396 }
2397
2398 hi = hash_find(ht, varname);
2399 if (HASHITEM_EMPTY(hi))
2400 {
2401 // For global variables we may try auto-loading the script. If it
2402 // worked find the variable again. Don't auto-load a script if it was
2403 // loaded already, otherwise it would be loaded every time when
2404 // checking if a function name is a Funcref variable.
2405 if (ht == &globvarht && !no_autoload)
2406 {
2407 // Note: script_autoload() may make "hi" invalid. It must either
2408 // be obtained again or not used.
2409 if (!script_autoload(varname, FALSE) || aborting())
2410 return NULL;
2411 hi = hash_find(ht, varname);
2412 }
2413 if (HASHITEM_EMPTY(hi))
2414 return NULL;
2415 }
2416 return HI2DI(hi);
2417}
2418
2419/*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002420 * Get the script-local hashtab. NULL if not in a script context.
2421 */
2422 hashtab_T *
2423get_script_local_ht(void)
2424{
2425 scid_T sid = current_sctx.sc_sid;
2426
2427 if (sid > 0 && sid <= script_items.ga_len)
2428 return &SCRIPT_VARS(sid);
2429 return NULL;
2430}
2431
2432/*
2433 * Look for "name[len]" in script-local variables.
2434 * Return -1 when not found.
2435 */
2436 int
2437lookup_scriptvar(char_u *name, size_t len, cctx_T *dummy UNUSED)
2438{
2439 hashtab_T *ht = get_script_local_ht();
2440 char_u buffer[30];
2441 char_u *p;
2442 int res;
2443 hashitem_T *hi;
2444
2445 if (ht == NULL)
2446 return -1;
2447 if (len < sizeof(buffer) - 1)
2448 {
2449 vim_strncpy(buffer, name, len);
2450 p = buffer;
2451 }
2452 else
2453 {
2454 p = vim_strnsave(name, (int)len);
2455 if (p == NULL)
2456 return -1;
2457 }
2458
2459 hi = hash_find(ht, p);
2460 res = HASHITEM_EMPTY(hi) ? -1 : 1;
2461
2462 // if not script-local, then perhaps imported
2463 if (res == -1 && find_imported(p, NULL) != NULL)
2464 res = 1;
2465
2466 if (p != buffer)
2467 vim_free(p);
2468 return res;
2469}
2470
2471/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002472 * Find the hashtab used for a variable name.
2473 * Return NULL if the name is not valid.
2474 * Set "varname" to the start of name without ':'.
2475 */
2476 hashtab_T *
2477find_var_ht(char_u *name, char_u **varname)
2478{
2479 hashitem_T *hi;
2480 hashtab_T *ht;
2481
2482 if (name[0] == NUL)
2483 return NULL;
2484 if (name[1] != ':')
2485 {
2486 // The name must not start with a colon or #.
2487 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
2488 return NULL;
2489 *varname = name;
2490
2491 // "version" is "v:version" in all scopes if scriptversion < 3.
2492 // Same for a few other variables marked with VV_COMPAT.
2493 if (current_sctx.sc_version < 3)
2494 {
2495 hi = hash_find(&compat_hashtab, name);
2496 if (!HASHITEM_EMPTY(hi))
2497 return &compat_hashtab;
2498 }
2499
2500 ht = get_funccal_local_ht();
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002501 if (ht != NULL)
2502 return ht; // local variable
2503
2504 // in Vim9 script items at the script level are script-local
2505 if (current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2506 {
2507 ht = get_script_local_ht();
2508 if (ht != NULL)
2509 return ht;
2510 }
2511
2512 return &globvarht; // global variable
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002513 }
2514 *varname = name + 2;
2515 if (*name == 'g') // global variable
2516 return &globvarht;
2517 // There must be no ':' or '#' in the rest of the name, unless g: is used
2518 if (vim_strchr(name + 2, ':') != NULL
2519 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
2520 return NULL;
2521 if (*name == 'b') // buffer variable
2522 return &curbuf->b_vars->dv_hashtab;
2523 if (*name == 'w') // window variable
2524 return &curwin->w_vars->dv_hashtab;
2525 if (*name == 't') // tab page variable
2526 return &curtab->tp_vars->dv_hashtab;
2527 if (*name == 'v') // v: variable
2528 return &vimvarht;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002529 if (current_sctx.sc_version != SCRIPT_VERSION_VIM9)
2530 {
2531 if (*name == 'a') // a: function argument
2532 return get_funccal_args_ht();
2533 if (*name == 'l') // l: local function variable
2534 return get_funccal_local_ht();
2535 }
2536 if (*name == 's') // script variable
2537 {
2538 ht = get_script_local_ht();
2539 if (ht != NULL)
2540 return ht;
2541 }
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002542 return NULL;
2543}
2544
2545/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002546 * Get the string value of a (global/local) variable.
2547 * Note: see tv_get_string() for how long the pointer remains valid.
2548 * Returns NULL when it doesn't exist.
2549 */
2550 char_u *
2551get_var_value(char_u *name)
2552{
2553 dictitem_T *v;
2554
2555 v = find_var(name, NULL, FALSE);
2556 if (v == NULL)
2557 return NULL;
2558 return tv_get_string(&v->di_tv);
2559}
2560
2561/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002562 * Allocate a new hashtab for a sourced script. It will be used while
2563 * sourcing this script and when executing functions defined in the script.
2564 */
2565 void
2566new_script_vars(scid_T id)
2567{
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002568 scriptvar_T *sv;
2569
Bram Moolenaar7ebcba62020-01-12 17:42:55 +01002570 sv = ALLOC_CLEAR_ONE(scriptvar_T);
2571 if (sv == NULL)
2572 return;
2573 init_var_dict(&sv->sv_dict, &sv->sv_var, VAR_SCOPE);
2574 SCRIPT_ITEM(id).sn_vars = sv;
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002575}
2576
2577/*
2578 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
2579 * point to it.
2580 */
2581 void
2582init_var_dict(dict_T *dict, dictitem_T *dict_var, int scope)
2583{
2584 hash_init(&dict->dv_hashtab);
2585 dict->dv_lock = 0;
2586 dict->dv_scope = scope;
2587 dict->dv_refcount = DO_NOT_FREE_CNT;
2588 dict->dv_copyID = 0;
2589 dict_var->di_tv.vval.v_dict = dict;
2590 dict_var->di_tv.v_type = VAR_DICT;
2591 dict_var->di_tv.v_lock = VAR_FIXED;
2592 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
2593 dict_var->di_key[0] = NUL;
2594}
2595
2596/*
2597 * Unreference a dictionary initialized by init_var_dict().
2598 */
2599 void
2600unref_var_dict(dict_T *dict)
2601{
Bram Moolenaar8d71b542019-08-30 15:46:30 +02002602 // Now the dict needs to be freed if no one else is using it, go back to
2603 // normal reference counting.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002604 dict->dv_refcount -= DO_NOT_FREE_CNT - 1;
2605 dict_unref(dict);
2606}
2607
2608/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002609 * Clean up a list of internal variables.
2610 * Frees all allocated variables and the value they contain.
2611 * Clears hashtab "ht", does not free it.
2612 */
2613 void
2614vars_clear(hashtab_T *ht)
2615{
2616 vars_clear_ext(ht, TRUE);
2617}
2618
2619/*
2620 * Like vars_clear(), but only free the value if "free_val" is TRUE.
2621 */
2622 void
2623vars_clear_ext(hashtab_T *ht, int free_val)
2624{
2625 int todo;
2626 hashitem_T *hi;
2627 dictitem_T *v;
2628
2629 hash_lock(ht);
2630 todo = (int)ht->ht_used;
2631 for (hi = ht->ht_array; todo > 0; ++hi)
2632 {
2633 if (!HASHITEM_EMPTY(hi))
2634 {
2635 --todo;
2636
2637 // Free the variable. Don't remove it from the hashtab,
2638 // ht_array might change then. hash_clear() takes care of it
2639 // later.
2640 v = HI2DI(hi);
2641 if (free_val)
2642 clear_tv(&v->di_tv);
2643 if (v->di_flags & DI_FLAGS_ALLOC)
2644 vim_free(v);
2645 }
2646 }
2647 hash_clear(ht);
2648 ht->ht_used = 0;
2649}
2650
2651/*
2652 * Delete a variable from hashtab "ht" at item "hi".
2653 * Clear the variable value and free the dictitem.
2654 */
Bram Moolenaarda6c0332019-09-01 16:01:30 +02002655 static void
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002656delete_var(hashtab_T *ht, hashitem_T *hi)
2657{
2658 dictitem_T *di = HI2DI(hi);
2659
2660 hash_remove(ht, hi);
2661 clear_tv(&di->di_tv);
2662 vim_free(di);
2663}
2664
2665/*
2666 * List the value of one internal variable.
2667 */
2668 static void
2669list_one_var(dictitem_T *v, char *prefix, int *first)
2670{
2671 char_u *tofree;
2672 char_u *s;
2673 char_u numbuf[NUMBUFLEN];
2674
2675 s = echo_string(&v->di_tv, &tofree, numbuf, get_copyID());
2676 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
2677 s == NULL ? (char_u *)"" : s, first);
2678 vim_free(tofree);
2679}
2680
2681 static void
2682list_one_var_a(
2683 char *prefix,
2684 char_u *name,
2685 int type,
2686 char_u *string,
2687 int *first) // when TRUE clear rest of screen and set to FALSE
2688{
2689 // don't use msg() or msg_attr() to avoid overwriting "v:statusmsg"
2690 msg_start();
2691 msg_puts(prefix);
2692 if (name != NULL) // "a:" vars don't have a name stored
2693 msg_puts((char *)name);
2694 msg_putchar(' ');
2695 msg_advance(22);
2696 if (type == VAR_NUMBER)
2697 msg_putchar('#');
2698 else if (type == VAR_FUNC || type == VAR_PARTIAL)
2699 msg_putchar('*');
2700 else if (type == VAR_LIST)
2701 {
2702 msg_putchar('[');
2703 if (*string == '[')
2704 ++string;
2705 }
2706 else if (type == VAR_DICT)
2707 {
2708 msg_putchar('{');
2709 if (*string == '{')
2710 ++string;
2711 }
2712 else
2713 msg_putchar(' ');
2714
2715 msg_outtrans(string);
2716
2717 if (type == VAR_FUNC || type == VAR_PARTIAL)
2718 msg_puts("()");
2719 if (*first)
2720 {
2721 msg_clr_eos();
2722 *first = FALSE;
2723 }
2724}
2725
2726/*
2727 * Set variable "name" to value in "tv".
2728 * If the variable already exists, the value is updated.
2729 * Otherwise the variable is created.
2730 */
2731 void
2732set_var(
2733 char_u *name,
2734 typval_T *tv,
2735 int copy) // make copy of value in "tv"
2736{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002737 set_var_const(name, NULL, tv, copy, 0);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002738}
2739
2740/*
2741 * Set variable "name" to value in "tv".
2742 * If the variable already exists and "is_const" is FALSE the value is updated.
2743 * Otherwise the variable is created.
2744 */
2745 void
2746set_var_const(
2747 char_u *name,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002748 type_T *type,
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002749 typval_T *tv,
2750 int copy, // make copy of value in "tv"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002751 int flags) // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002752{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002753 dictitem_T *di;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002754 char_u *varname;
2755 hashtab_T *ht;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002756 int is_script_local;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002757
2758 ht = find_var_ht(name, &varname);
2759 if (ht == NULL || *varname == NUL)
2760 {
2761 semsg(_(e_illvar), name);
2762 return;
2763 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002764 is_script_local = ht == get_script_local_ht();
2765
2766 di = find_var_in_ht(ht, 0, varname, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002767
2768 // Search in parent scope which is possible to reference from lambda
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002769 if (di == NULL)
2770 di = find_var_in_scoped_ht(name, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002771
2772 if ((tv->v_type == VAR_FUNC || tv->v_type == VAR_PARTIAL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002773 && var_check_func_name(name, di == NULL))
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002774 return;
2775
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002776 if (di != NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002777 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002778 if ((di->di_flags & DI_FLAGS_RELOAD) == 0)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002779 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002780 if (flags & LET_IS_CONST)
2781 {
2782 emsg(_(e_cannot_mod));
2783 return;
2784 }
2785
2786 if (var_check_ro(di->di_flags, name, FALSE)
2787 || var_check_lock(di->di_tv.v_lock, name, FALSE))
2788 return;
2789
2790 if ((flags & LET_NO_COMMAND) == 0
2791 && is_script_local
2792 && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2793 {
2794 semsg(_("E1041: Redefining script item %s"), name);
2795 return;
2796 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002797 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002798 else
2799 // can only redefine once
2800 di->di_flags &= ~DI_FLAGS_RELOAD;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002801
2802 // existing variable, need to clear the value
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002803
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002804 // Handle setting internal di: variables separately where needed to
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002805 // prevent changing the type.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002806 if (ht == &vimvarht)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002807 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002808 if (di->di_tv.v_type == VAR_STRING)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002809 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002810 VIM_CLEAR(di->di_tv.vval.v_string);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002811 if (copy || tv->v_type != VAR_STRING)
2812 {
2813 char_u *val = tv_get_string(tv);
2814
2815 // Careful: when assigning to v:errmsg and tv_get_string()
2816 // causes an error message the variable will alrady be set.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002817 if (di->di_tv.vval.v_string == NULL)
2818 di->di_tv.vval.v_string = vim_strsave(val);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002819 }
2820 else
2821 {
2822 // Take over the string to avoid an extra alloc/free.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002823 di->di_tv.vval.v_string = tv->vval.v_string;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002824 tv->vval.v_string = NULL;
2825 }
2826 return;
2827 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002828 else if (di->di_tv.v_type == VAR_NUMBER)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002829 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002830 di->di_tv.vval.v_number = tv_get_number(tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002831 if (STRCMP(varname, "searchforward") == 0)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002832 set_search_direction(di->di_tv.vval.v_number ? '/' : '?');
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002833#ifdef FEAT_SEARCH_EXTRA
2834 else if (STRCMP(varname, "hlsearch") == 0)
2835 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002836 no_hlsearch = !di->di_tv.vval.v_number;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002837 redraw_all_later(SOME_VALID);
2838 }
2839#endif
2840 return;
2841 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002842 else if (di->di_tv.v_type != tv->v_type)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002843 {
2844 semsg(_("E963: setting %s to value with wrong type"), name);
2845 return;
2846 }
2847 }
2848
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002849 clear_tv(&di->di_tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002850 }
2851 else // add a new variable
2852 {
2853 // Can't add "v:" or "a:" variable.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002854 if (ht == &vimvarht || ht == get_funccal_args_ht())
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002855 {
2856 semsg(_(e_illvar), name);
2857 return;
2858 }
2859
2860 // Make sure the variable name is valid.
2861 if (!valid_varname(varname))
2862 return;
2863
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002864 di = alloc(sizeof(dictitem_T) + STRLEN(varname));
2865 if (di == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002866 return;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002867 STRCPY(di->di_key, varname);
2868 if (hash_add(ht, DI2HIKEY(di)) == FAIL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002869 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002870 vim_free(di);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002871 return;
2872 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002873 di->di_flags = DI_FLAGS_ALLOC;
2874 if (flags & LET_IS_CONST)
2875 di->di_flags |= DI_FLAGS_LOCK;
2876
2877 if (is_script_local && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2878 {
2879 scriptitem_T *si = &SCRIPT_ITEM(current_sctx.sc_sid);
2880
2881 // Store a pointer to the typval_T, so that it can be found by
2882 // index instead of using a hastab lookup.
2883 if (ga_grow(&si->sn_var_vals, 1) == OK)
2884 {
2885 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data)
2886 + si->sn_var_vals.ga_len;
2887 sv->sv_name = di->di_key;
2888 sv->sv_tv = &di->di_tv;
2889 sv->sv_type = type == NULL ? &t_any : type;
2890 sv->sv_const = (flags & LET_IS_CONST);
2891 sv->sv_export = is_export;
2892 ++si->sn_var_vals.ga_len;
2893
2894 // let ex_export() know the export worked.
2895 is_export = FALSE;
2896 }
2897 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002898 }
2899
2900 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002901 copy_tv(tv, &di->di_tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002902 else
2903 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002904 di->di_tv = *tv;
2905 di->di_tv.v_lock = 0;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002906 init_tv(tv);
2907 }
2908
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002909 if (flags & LET_IS_CONST)
2910 di->di_tv.v_lock |= VAR_LOCKED;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002911}
2912
2913/*
2914 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
2915 * Also give an error message.
2916 */
2917 int
2918var_check_ro(int flags, char_u *name, int use_gettext)
2919{
2920 if (flags & DI_FLAGS_RO)
2921 {
2922 semsg(_(e_readonlyvar), use_gettext ? (char_u *)_(name) : name);
2923 return TRUE;
2924 }
2925 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
2926 {
2927 semsg(_(e_readonlysbx), use_gettext ? (char_u *)_(name) : name);
2928 return TRUE;
2929 }
2930 return FALSE;
2931}
2932
2933/*
2934 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
2935 * Also give an error message.
2936 */
2937 int
2938var_check_fixed(int flags, char_u *name, int use_gettext)
2939{
2940 if (flags & DI_FLAGS_FIX)
2941 {
2942 semsg(_("E795: Cannot delete variable %s"),
2943 use_gettext ? (char_u *)_(name) : name);
2944 return TRUE;
2945 }
2946 return FALSE;
2947}
2948
2949/*
2950 * Check if a funcref is assigned to a valid variable name.
2951 * Return TRUE and give an error if not.
2952 */
2953 int
2954var_check_func_name(
2955 char_u *name, // points to start of variable name
2956 int new_var) // TRUE when creating the variable
2957{
2958 // Allow for w: b: s: and t:.
2959 if (!(vim_strchr((char_u *)"wbst", name[0]) != NULL && name[1] == ':')
2960 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
2961 ? name[2] : name[0]))
2962 {
2963 semsg(_("E704: Funcref variable name must start with a capital: %s"),
2964 name);
2965 return TRUE;
2966 }
2967 // Don't allow hiding a function. When "v" is not NULL we might be
2968 // assigning another function to the same var, the type is checked
2969 // below.
2970 if (new_var && function_exists(name, FALSE))
2971 {
2972 semsg(_("E705: Variable name conflicts with existing function: %s"),
2973 name);
2974 return TRUE;
2975 }
2976 return FALSE;
2977}
2978
2979/*
2980 * Return TRUE if "flags" indicates variable "name" is locked (immutable).
2981 * Also give an error message, using "name" or _("name") when use_gettext is
2982 * TRUE.
2983 */
2984 int
2985var_check_lock(int lock, char_u *name, int use_gettext)
2986{
2987 if (lock & VAR_LOCKED)
2988 {
2989 semsg(_("E741: Value is locked: %s"),
2990 name == NULL ? (char_u *)_("Unknown")
2991 : use_gettext ? (char_u *)_(name)
2992 : name);
2993 return TRUE;
2994 }
2995 if (lock & VAR_FIXED)
2996 {
2997 semsg(_("E742: Cannot change value of %s"),
2998 name == NULL ? (char_u *)_("Unknown")
2999 : use_gettext ? (char_u *)_(name)
3000 : name);
3001 return TRUE;
3002 }
3003 return FALSE;
3004}
3005
3006/*
3007 * Check if a variable name is valid.
3008 * Return FALSE and give an error if not.
3009 */
3010 int
3011valid_varname(char_u *varname)
3012{
3013 char_u *p;
3014
3015 for (p = varname; *p != NUL; ++p)
3016 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
3017 && *p != AUTOLOAD_CHAR)
3018 {
3019 semsg(_(e_illvar), varname);
3020 return FALSE;
3021 }
3022 return TRUE;
3023}
3024
3025/*
3026 * getwinvar() and gettabwinvar()
3027 */
3028 static void
3029getwinvar(
3030 typval_T *argvars,
3031 typval_T *rettv,
3032 int off) // 1 for gettabwinvar()
3033{
3034 win_T *win;
3035 char_u *varname;
3036 dictitem_T *v;
3037 tabpage_T *tp = NULL;
3038 int done = FALSE;
3039 win_T *oldcurwin;
3040 tabpage_T *oldtabpage;
3041 int need_switch_win;
3042
3043 if (off == 1)
3044 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3045 else
3046 tp = curtab;
3047 win = find_win_by_nr(&argvars[off], tp);
3048 varname = tv_get_string_chk(&argvars[off + 1]);
3049 ++emsg_off;
3050
3051 rettv->v_type = VAR_STRING;
3052 rettv->vval.v_string = NULL;
3053
3054 if (win != NULL && varname != NULL)
3055 {
3056 // Set curwin to be our win, temporarily. Also set the tabpage,
3057 // otherwise the window is not valid. Only do this when needed,
3058 // autocommands get blocked.
3059 need_switch_win = !(tp == curtab && win == curwin);
3060 if (!need_switch_win
3061 || switch_win(&oldcurwin, &oldtabpage, win, tp, TRUE) == OK)
3062 {
3063 if (*varname == '&')
3064 {
3065 if (varname[1] == NUL)
3066 {
3067 // get all window-local options in a dict
3068 dict_T *opts = get_winbuf_options(FALSE);
3069
3070 if (opts != NULL)
3071 {
3072 rettv_dict_set(rettv, opts);
3073 done = TRUE;
3074 }
3075 }
3076 else if (get_option_tv(&varname, rettv, 1) == OK)
3077 // window-local-option
3078 done = TRUE;
3079 }
3080 else
3081 {
3082 // Look up the variable.
3083 // Let getwinvar({nr}, "") return the "w:" dictionary.
3084 v = find_var_in_ht(&win->w_vars->dv_hashtab, 'w',
3085 varname, FALSE);
3086 if (v != NULL)
3087 {
3088 copy_tv(&v->di_tv, rettv);
3089 done = TRUE;
3090 }
3091 }
3092 }
3093
3094 if (need_switch_win)
3095 // restore previous notion of curwin
3096 restore_win(oldcurwin, oldtabpage, TRUE);
3097 }
3098
3099 if (!done && argvars[off + 2].v_type != VAR_UNKNOWN)
3100 // use the default return value
3101 copy_tv(&argvars[off + 2], rettv);
3102
3103 --emsg_off;
3104}
3105
3106/*
3107 * "setwinvar()" and "settabwinvar()" functions
3108 */
3109 static void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003110setwinvar(typval_T *argvars, int off)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003111{
3112 win_T *win;
3113 win_T *save_curwin;
3114 tabpage_T *save_curtab;
3115 int need_switch_win;
3116 char_u *varname, *winvarname;
3117 typval_T *varp;
3118 char_u nbuf[NUMBUFLEN];
3119 tabpage_T *tp = NULL;
3120
3121 if (check_secure())
3122 return;
3123
3124 if (off == 1)
3125 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3126 else
3127 tp = curtab;
3128 win = find_win_by_nr(&argvars[off], tp);
3129 varname = tv_get_string_chk(&argvars[off + 1]);
3130 varp = &argvars[off + 2];
3131
3132 if (win != NULL && varname != NULL && varp != NULL)
3133 {
3134 need_switch_win = !(tp == curtab && win == curwin);
3135 if (!need_switch_win
3136 || switch_win(&save_curwin, &save_curtab, win, tp, TRUE) == OK)
3137 {
3138 if (*varname == '&')
3139 {
3140 long numval;
3141 char_u *strval;
3142 int error = FALSE;
3143
3144 ++varname;
3145 numval = (long)tv_get_number_chk(varp, &error);
3146 strval = tv_get_string_buf_chk(varp, nbuf);
3147 if (!error && strval != NULL)
3148 set_option_value(varname, numval, strval, OPT_LOCAL);
3149 }
3150 else
3151 {
3152 winvarname = alloc(STRLEN(varname) + 3);
3153 if (winvarname != NULL)
3154 {
3155 STRCPY(winvarname, "w:");
3156 STRCPY(winvarname + 2, varname);
3157 set_var(winvarname, varp, TRUE);
3158 vim_free(winvarname);
3159 }
3160 }
3161 }
3162 if (need_switch_win)
3163 restore_win(save_curwin, save_curtab, TRUE);
3164 }
3165}
3166
Bram Moolenaare5cdf152019-08-29 22:09:46 +02003167/*
3168 * reset v:option_new, v:option_old, v:option_oldlocal, v:option_oldglobal,
3169 * v:option_type, and v:option_command.
3170 */
3171 void
3172reset_v_option_vars(void)
3173{
3174 set_vim_var_string(VV_OPTION_NEW, NULL, -1);
3175 set_vim_var_string(VV_OPTION_OLD, NULL, -1);
3176 set_vim_var_string(VV_OPTION_OLDLOCAL, NULL, -1);
3177 set_vim_var_string(VV_OPTION_OLDGLOBAL, NULL, -1);
3178 set_vim_var_string(VV_OPTION_TYPE, NULL, -1);
3179 set_vim_var_string(VV_OPTION_COMMAND, NULL, -1);
3180}
3181
3182/*
3183 * Add an assert error to v:errors.
3184 */
3185 void
3186assert_error(garray_T *gap)
3187{
3188 struct vimvar *vp = &vimvars[VV_ERRORS];
3189
3190 if (vp->vv_type != VAR_LIST || vimvars[VV_ERRORS].vv_list == NULL)
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003191 // Make sure v:errors is a list.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02003192 set_vim_var_list(VV_ERRORS, list_alloc());
3193 list_append_string(vimvars[VV_ERRORS].vv_list, gap->ga_data, gap->ga_len);
3194}
3195
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003196 int
3197var_exists(char_u *var)
3198{
3199 char_u *name;
3200 char_u *tofree;
3201 typval_T tv;
3202 int len = 0;
3203 int n = FALSE;
3204
3205 // get_name_len() takes care of expanding curly braces
3206 name = var;
3207 len = get_name_len(&var, &tofree, TRUE, FALSE);
3208 if (len > 0)
3209 {
3210 if (tofree != NULL)
3211 name = tofree;
3212 n = (get_var_tv(name, len, &tv, NULL, FALSE, TRUE) == OK);
3213 if (n)
3214 {
3215 // handle d.key, l[idx], f(expr)
3216 n = (handle_subscript(&var, &tv, TRUE, FALSE, name, &name) == OK);
3217 if (n)
3218 clear_tv(&tv);
3219 }
3220 }
3221 if (*var != NUL)
3222 n = FALSE;
3223
3224 vim_free(tofree);
3225 return n;
3226}
3227
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003228static lval_T *redir_lval = NULL;
3229#define EVALCMD_BUSY (redir_lval == (lval_T *)&redir_lval)
3230static garray_T redir_ga; // only valid when redir_lval is not NULL
3231static char_u *redir_endp = NULL;
3232static char_u *redir_varname = NULL;
3233
3234/*
3235 * Start recording command output to a variable
3236 * When "append" is TRUE append to an existing variable.
3237 * Returns OK if successfully completed the setup. FAIL otherwise.
3238 */
3239 int
3240var_redir_start(char_u *name, int append)
3241{
3242 int save_emsg;
3243 int err;
3244 typval_T tv;
3245
3246 // Catch a bad name early.
3247 if (!eval_isnamec1(*name))
3248 {
3249 emsg(_(e_invarg));
3250 return FAIL;
3251 }
3252
3253 // Make a copy of the name, it is used in redir_lval until redir ends.
3254 redir_varname = vim_strsave(name);
3255 if (redir_varname == NULL)
3256 return FAIL;
3257
3258 redir_lval = ALLOC_CLEAR_ONE(lval_T);
3259 if (redir_lval == NULL)
3260 {
3261 var_redir_stop();
3262 return FAIL;
3263 }
3264
3265 // The output is stored in growarray "redir_ga" until redirection ends.
3266 ga_init2(&redir_ga, (int)sizeof(char), 500);
3267
3268 // Parse the variable name (can be a dict or list entry).
3269 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, 0,
3270 FNE_CHECK_START);
3271 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
3272 {
3273 clear_lval(redir_lval);
3274 if (redir_endp != NULL && *redir_endp != NUL)
3275 // Trailing characters are present after the variable name
3276 emsg(_(e_trailing));
3277 else
3278 emsg(_(e_invarg));
3279 redir_endp = NULL; // don't store a value, only cleanup
3280 var_redir_stop();
3281 return FAIL;
3282 }
3283
3284 // check if we can write to the variable: set it to or append an empty
3285 // string
3286 save_emsg = did_emsg;
3287 did_emsg = FALSE;
3288 tv.v_type = VAR_STRING;
3289 tv.vval.v_string = (char_u *)"";
3290 if (append)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003291 set_var_lval(redir_lval, redir_endp, &tv, TRUE, 0, (char_u *)".");
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003292 else
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003293 set_var_lval(redir_lval, redir_endp, &tv, TRUE, 0, (char_u *)"=");
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003294 clear_lval(redir_lval);
3295 err = did_emsg;
3296 did_emsg |= save_emsg;
3297 if (err)
3298 {
3299 redir_endp = NULL; // don't store a value, only cleanup
3300 var_redir_stop();
3301 return FAIL;
3302 }
3303
3304 return OK;
3305}
3306
3307/*
3308 * Append "value[value_len]" to the variable set by var_redir_start().
3309 * The actual appending is postponed until redirection ends, because the value
3310 * appended may in fact be the string we write to, changing it may cause freed
3311 * memory to be used:
3312 * :redir => foo
3313 * :let foo
3314 * :redir END
3315 */
3316 void
3317var_redir_str(char_u *value, int value_len)
3318{
3319 int len;
3320
3321 if (redir_lval == NULL)
3322 return;
3323
3324 if (value_len == -1)
3325 len = (int)STRLEN(value); // Append the entire string
3326 else
3327 len = value_len; // Append only "value_len" characters
3328
3329 if (ga_grow(&redir_ga, len) == OK)
3330 {
3331 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
3332 redir_ga.ga_len += len;
3333 }
3334 else
3335 var_redir_stop();
3336}
3337
3338/*
3339 * Stop redirecting command output to a variable.
3340 * Frees the allocated memory.
3341 */
3342 void
3343var_redir_stop(void)
3344{
3345 typval_T tv;
3346
3347 if (EVALCMD_BUSY)
3348 {
3349 redir_lval = NULL;
3350 return;
3351 }
3352
3353 if (redir_lval != NULL)
3354 {
3355 // If there was no error: assign the text to the variable.
3356 if (redir_endp != NULL)
3357 {
3358 ga_append(&redir_ga, NUL); // Append the trailing NUL.
3359 tv.v_type = VAR_STRING;
3360 tv.vval.v_string = redir_ga.ga_data;
3361 // Call get_lval() again, if it's inside a Dict or List it may
3362 // have changed.
3363 redir_endp = get_lval(redir_varname, NULL, redir_lval,
3364 FALSE, FALSE, 0, FNE_CHECK_START);
3365 if (redir_endp != NULL && redir_lval->ll_name != NULL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003366 set_var_lval(redir_lval, redir_endp, &tv, FALSE, 0,
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003367 (char_u *)".");
3368 clear_lval(redir_lval);
3369 }
3370
3371 // free the collected output
3372 VIM_CLEAR(redir_ga.ga_data);
3373
3374 VIM_CLEAR(redir_lval);
3375 }
3376 VIM_CLEAR(redir_varname);
3377}
3378
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003379/*
3380 * "gettabvar()" function
3381 */
3382 void
3383f_gettabvar(typval_T *argvars, typval_T *rettv)
3384{
3385 win_T *oldcurwin;
3386 tabpage_T *tp, *oldtabpage;
3387 dictitem_T *v;
3388 char_u *varname;
3389 int done = FALSE;
3390
3391 rettv->v_type = VAR_STRING;
3392 rettv->vval.v_string = NULL;
3393
3394 varname = tv_get_string_chk(&argvars[1]);
3395 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3396 if (tp != NULL && varname != NULL)
3397 {
3398 // Set tp to be our tabpage, temporarily. Also set the window to the
3399 // first window in the tabpage, otherwise the window is not valid.
3400 if (switch_win(&oldcurwin, &oldtabpage,
3401 tp == curtab || tp->tp_firstwin == NULL ? firstwin
3402 : tp->tp_firstwin, tp, TRUE) == OK)
3403 {
3404 // look up the variable
3405 // Let gettabvar({nr}, "") return the "t:" dictionary.
3406 v = find_var_in_ht(&tp->tp_vars->dv_hashtab, 't', varname, FALSE);
3407 if (v != NULL)
3408 {
3409 copy_tv(&v->di_tv, rettv);
3410 done = TRUE;
3411 }
3412 }
3413
3414 // restore previous notion of curwin
3415 restore_win(oldcurwin, oldtabpage, TRUE);
3416 }
3417
3418 if (!done && argvars[2].v_type != VAR_UNKNOWN)
3419 copy_tv(&argvars[2], rettv);
3420}
3421
3422/*
3423 * "gettabwinvar()" function
3424 */
3425 void
3426f_gettabwinvar(typval_T *argvars, typval_T *rettv)
3427{
3428 getwinvar(argvars, rettv, 1);
3429}
3430
3431/*
3432 * "getwinvar()" function
3433 */
3434 void
3435f_getwinvar(typval_T *argvars, typval_T *rettv)
3436{
3437 getwinvar(argvars, rettv, 0);
3438}
3439
3440/*
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003441 * "getbufvar()" function
3442 */
3443 void
3444f_getbufvar(typval_T *argvars, typval_T *rettv)
3445{
3446 buf_T *buf;
3447 buf_T *save_curbuf;
3448 char_u *varname;
3449 dictitem_T *v;
3450 int done = FALSE;
3451
3452 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
3453 varname = tv_get_string_chk(&argvars[1]);
3454 ++emsg_off;
3455 buf = tv_get_buf(&argvars[0], FALSE);
3456
3457 rettv->v_type = VAR_STRING;
3458 rettv->vval.v_string = NULL;
3459
3460 if (buf != NULL && varname != NULL)
3461 {
3462 // set curbuf to be our buf, temporarily
3463 save_curbuf = curbuf;
3464 curbuf = buf;
3465
3466 if (*varname == '&')
3467 {
3468 if (varname[1] == NUL)
3469 {
3470 // get all buffer-local options in a dict
3471 dict_T *opts = get_winbuf_options(TRUE);
3472
3473 if (opts != NULL)
3474 {
3475 rettv_dict_set(rettv, opts);
3476 done = TRUE;
3477 }
3478 }
3479 else if (get_option_tv(&varname, rettv, TRUE) == OK)
3480 // buffer-local-option
3481 done = TRUE;
3482 }
3483 else
3484 {
3485 // Look up the variable.
3486 // Let getbufvar({nr}, "") return the "b:" dictionary.
3487 v = find_var_in_ht(&curbuf->b_vars->dv_hashtab,
3488 'b', varname, FALSE);
3489 if (v != NULL)
3490 {
3491 copy_tv(&v->di_tv, rettv);
3492 done = TRUE;
3493 }
3494 }
3495
3496 // restore previous notion of curbuf
3497 curbuf = save_curbuf;
3498 }
3499
3500 if (!done && argvars[2].v_type != VAR_UNKNOWN)
3501 // use the default value
3502 copy_tv(&argvars[2], rettv);
3503
3504 --emsg_off;
3505}
3506
3507/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003508 * "settabvar()" function
3509 */
3510 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003511f_settabvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003512{
3513 tabpage_T *save_curtab;
3514 tabpage_T *tp;
3515 char_u *varname, *tabvarname;
3516 typval_T *varp;
3517
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003518 if (check_secure())
3519 return;
3520
3521 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3522 varname = tv_get_string_chk(&argvars[1]);
3523 varp = &argvars[2];
3524
3525 if (varname != NULL && varp != NULL && tp != NULL)
3526 {
3527 save_curtab = curtab;
3528 goto_tabpage_tp(tp, FALSE, FALSE);
3529
3530 tabvarname = alloc(STRLEN(varname) + 3);
3531 if (tabvarname != NULL)
3532 {
3533 STRCPY(tabvarname, "t:");
3534 STRCPY(tabvarname + 2, varname);
3535 set_var(tabvarname, varp, TRUE);
3536 vim_free(tabvarname);
3537 }
3538
3539 // Restore current tabpage
3540 if (valid_tabpage(save_curtab))
3541 goto_tabpage_tp(save_curtab, FALSE, FALSE);
3542 }
3543}
3544
3545/*
3546 * "settabwinvar()" function
3547 */
3548 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003549f_settabwinvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003550{
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003551 setwinvar(argvars, 1);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003552}
3553
3554/*
3555 * "setwinvar()" function
3556 */
3557 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003558f_setwinvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003559{
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003560 setwinvar(argvars, 0);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003561}
3562
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003563/*
3564 * "setbufvar()" function
3565 */
3566 void
3567f_setbufvar(typval_T *argvars, typval_T *rettv UNUSED)
3568{
3569 buf_T *buf;
3570 char_u *varname, *bufvarname;
3571 typval_T *varp;
3572 char_u nbuf[NUMBUFLEN];
3573
3574 if (check_secure())
3575 return;
3576 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
3577 varname = tv_get_string_chk(&argvars[1]);
3578 buf = tv_get_buf(&argvars[0], FALSE);
3579 varp = &argvars[2];
3580
3581 if (buf != NULL && varname != NULL && varp != NULL)
3582 {
3583 if (*varname == '&')
3584 {
3585 long numval;
3586 char_u *strval;
3587 int error = FALSE;
3588 aco_save_T aco;
3589
3590 // set curbuf to be our buf, temporarily
3591 aucmd_prepbuf(&aco, buf);
3592
3593 ++varname;
3594 numval = (long)tv_get_number_chk(varp, &error);
3595 strval = tv_get_string_buf_chk(varp, nbuf);
3596 if (!error && strval != NULL)
3597 set_option_value(varname, numval, strval, OPT_LOCAL);
3598
3599 // reset notion of buffer
3600 aucmd_restbuf(&aco);
3601 }
3602 else
3603 {
3604 buf_T *save_curbuf = curbuf;
3605
3606 bufvarname = alloc(STRLEN(varname) + 3);
3607 if (bufvarname != NULL)
3608 {
3609 curbuf = buf;
3610 STRCPY(bufvarname, "b:");
3611 STRCPY(bufvarname + 2, varname);
3612 set_var(bufvarname, varp, TRUE);
3613 vim_free(bufvarname);
3614 curbuf = save_curbuf;
3615 }
3616 }
3617 }
3618}
3619
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003620/*
3621 * Get a callback from "arg". It can be a Funcref or a function name.
3622 * When "arg" is zero return an empty string.
3623 * "cb_name" is not allocated.
3624 * "cb_name" is set to NULL for an invalid argument.
3625 */
3626 callback_T
3627get_callback(typval_T *arg)
3628{
3629 callback_T res;
3630
3631 res.cb_free_name = FALSE;
3632 if (arg->v_type == VAR_PARTIAL && arg->vval.v_partial != NULL)
3633 {
3634 res.cb_partial = arg->vval.v_partial;
3635 ++res.cb_partial->pt_refcount;
3636 res.cb_name = partial_name(res.cb_partial);
3637 }
3638 else
3639 {
3640 res.cb_partial = NULL;
3641 if (arg->v_type == VAR_FUNC || arg->v_type == VAR_STRING)
3642 {
3643 // Note that we don't make a copy of the string.
3644 res.cb_name = arg->vval.v_string;
3645 func_ref(res.cb_name);
3646 }
3647 else if (arg->v_type == VAR_NUMBER && arg->vval.v_number == 0)
3648 {
3649 res.cb_name = (char_u *)"";
3650 }
3651 else
3652 {
3653 emsg(_("E921: Invalid callback argument"));
3654 res.cb_name = NULL;
3655 }
3656 }
3657 return res;
3658}
3659
3660/*
3661 * Copy a callback into a typval_T.
3662 */
3663 void
3664put_callback(callback_T *cb, typval_T *tv)
3665{
3666 if (cb->cb_partial != NULL)
3667 {
3668 tv->v_type = VAR_PARTIAL;
3669 tv->vval.v_partial = cb->cb_partial;
3670 ++tv->vval.v_partial->pt_refcount;
3671 }
3672 else
3673 {
3674 tv->v_type = VAR_FUNC;
3675 tv->vval.v_string = vim_strsave(cb->cb_name);
3676 func_ref(cb->cb_name);
3677 }
3678}
3679
3680/*
3681 * Make a copy of "src" into "dest", allocating the function name if needed,
3682 * without incrementing the refcount.
3683 */
3684 void
3685set_callback(callback_T *dest, callback_T *src)
3686{
3687 if (src->cb_partial == NULL)
3688 {
3689 // just a function name, make a copy
3690 dest->cb_name = vim_strsave(src->cb_name);
3691 dest->cb_free_name = TRUE;
3692 }
3693 else
3694 {
3695 // cb_name is a pointer into cb_partial
3696 dest->cb_name = src->cb_name;
3697 dest->cb_free_name = FALSE;
3698 }
3699 dest->cb_partial = src->cb_partial;
3700}
3701
3702/*
3703 * Unref/free "callback" returned by get_callback() or set_callback().
3704 */
3705 void
3706free_callback(callback_T *callback)
3707{
3708 if (callback->cb_partial != NULL)
3709 {
3710 partial_unref(callback->cb_partial);
3711 callback->cb_partial = NULL;
3712 }
3713 else if (callback->cb_name != NULL)
3714 func_unref(callback->cb_name);
3715 if (callback->cb_free_name)
3716 {
3717 vim_free(callback->cb_name);
3718 callback->cb_free_name = FALSE;
3719 }
3720 callback->cb_name = NULL;
3721}
3722
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003723#endif // FEAT_EVAL