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