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