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