blob: d32b76a87b79f7f72d6fc0ac009705fa67170066 [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.
Bram Moolenaar5da356e2020-04-09 19:34:43 +02001918 * Returns DI_ flags in "di_flags".
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001919 */
1920 int
Bram Moolenaar5da356e2020-04-09 19:34:43 +02001921find_vim_var(char_u *name, int *di_flags)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001922{
Bram Moolenaar5da356e2020-04-09 19:34:43 +02001923 dictitem_T *di = find_var_in_ht(&vimvarht, 0, name, TRUE);
1924 struct vimvar *vv;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001925
1926 if (di == NULL)
1927 return -1;
Bram Moolenaar5da356e2020-04-09 19:34:43 +02001928 *di_flags = di->di_flags;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001929 vv = (struct vimvar *)((char *)di - offsetof(vimvar_T, vv_di));
1930 return (int)(vv - vimvars);
1931}
1932
1933
1934/*
Bram Moolenaar34ed68d2019-08-29 22:48:24 +02001935 * Set type of v: variable to "type".
1936 */
1937 void
1938set_vim_var_type(int idx, vartype_T type)
1939{
1940 vimvars[idx].vv_type = type;
1941}
1942
1943/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001944 * Set number v: variable to "val".
Bram Moolenaar8d71b542019-08-30 15:46:30 +02001945 * Note that this does not set the type, use set_vim_var_type() for that.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001946 */
1947 void
1948set_vim_var_nr(int idx, varnumber_T val)
1949{
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001950 vimvars[idx].vv_nr = val;
1951}
1952
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001953 char *
1954get_vim_var_name(int idx)
1955{
1956 return vimvars[idx].vv_name;
1957}
1958
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001959/*
1960 * Get typval_T v: variable value.
1961 */
1962 typval_T *
1963get_vim_var_tv(int idx)
1964{
1965 return &vimvars[idx].vv_tv;
1966}
1967
1968/*
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01001969 * Set v: variable to "tv". Only accepts the same type.
1970 * Takes over the value of "tv".
1971 */
1972 int
1973set_vim_var_tv(int idx, typval_T *tv)
1974{
1975 if (vimvars[idx].vv_type != tv->v_type)
1976 {
1977 emsg(_("E1063: type mismatch for v: variable"));
1978 clear_tv(tv);
1979 return FAIL;
1980 }
Bram Moolenaarcab27672020-04-09 20:10:55 +02001981 // VV_RO is also checked when compiling, but let's check here as well.
1982 if (vimvars[idx].vv_flags & VV_RO)
1983 {
1984 semsg(_(e_readonlyvar), vimvars[idx].vv_name);
1985 return FAIL;
1986 }
1987 if (sandbox && (vimvars[idx].vv_flags & VV_RO_SBX))
1988 {
1989 semsg(_(e_readonlysbx), vimvars[idx].vv_name);
1990 return FAIL;
1991 }
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01001992 clear_tv(&vimvars[idx].vv_di.di_tv);
1993 vimvars[idx].vv_di.di_tv = *tv;
1994 return OK;
1995}
1996
1997/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001998 * Get number v: variable value.
1999 */
2000 varnumber_T
2001get_vim_var_nr(int idx)
2002{
2003 return vimvars[idx].vv_nr;
2004}
2005
2006/*
2007 * Get string v: variable value. Uses a static buffer, can only be used once.
2008 * If the String variable has never been set, return an empty string.
2009 * Never returns NULL;
2010 */
2011 char_u *
2012get_vim_var_str(int idx)
2013{
2014 return tv_get_string(&vimvars[idx].vv_tv);
2015}
2016
2017/*
2018 * Get List v: variable value. Caller must take care of reference count when
2019 * needed.
2020 */
2021 list_T *
2022get_vim_var_list(int idx)
2023{
2024 return vimvars[idx].vv_list;
2025}
2026
2027/*
2028 * Get Dict v: variable value. Caller must take care of reference count when
2029 * needed.
2030 */
2031 dict_T *
2032get_vim_var_dict(int idx)
2033{
2034 return vimvars[idx].vv_dict;
2035}
2036
2037/*
2038 * Set v:char to character "c".
2039 */
2040 void
2041set_vim_var_char(int c)
2042{
2043 char_u buf[MB_MAXBYTES + 1];
2044
2045 if (has_mbyte)
2046 buf[(*mb_char2bytes)(c, buf)] = NUL;
2047 else
2048 {
2049 buf[0] = c;
2050 buf[1] = NUL;
2051 }
2052 set_vim_var_string(VV_CHAR, buf, -1);
2053}
2054
2055/*
2056 * Set v:count to "count" and v:count1 to "count1".
2057 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
2058 */
2059 void
2060set_vcount(
2061 long count,
2062 long count1,
2063 int set_prevcount)
2064{
2065 if (set_prevcount)
2066 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
2067 vimvars[VV_COUNT].vv_nr = count;
2068 vimvars[VV_COUNT1].vv_nr = count1;
2069}
2070
2071/*
2072 * Save variables that might be changed as a side effect. Used when executing
2073 * a timer callback.
2074 */
2075 void
2076save_vimvars(vimvars_save_T *vvsave)
2077{
2078 vvsave->vv_prevcount = vimvars[VV_PREVCOUNT].vv_nr;
2079 vvsave->vv_count = vimvars[VV_COUNT].vv_nr;
2080 vvsave->vv_count1 = vimvars[VV_COUNT1].vv_nr;
2081}
2082
2083/*
2084 * Restore variables saved by save_vimvars().
2085 */
2086 void
2087restore_vimvars(vimvars_save_T *vvsave)
2088{
2089 vimvars[VV_PREVCOUNT].vv_nr = vvsave->vv_prevcount;
2090 vimvars[VV_COUNT].vv_nr = vvsave->vv_count;
2091 vimvars[VV_COUNT1].vv_nr = vvsave->vv_count1;
2092}
2093
2094/*
2095 * Set string v: variable to a copy of "val". If 'copy' is FALSE, then set the
2096 * value.
2097 */
2098 void
2099set_vim_var_string(
2100 int idx,
2101 char_u *val,
2102 int len) // length of "val" to use or -1 (whole string)
2103{
2104 clear_tv(&vimvars[idx].vv_di.di_tv);
2105 vimvars[idx].vv_type = VAR_STRING;
2106 if (val == NULL)
2107 vimvars[idx].vv_str = NULL;
2108 else if (len == -1)
2109 vimvars[idx].vv_str = vim_strsave(val);
2110 else
2111 vimvars[idx].vv_str = vim_strnsave(val, len);
2112}
2113
2114/*
2115 * Set List v: variable to "val".
2116 */
2117 void
2118set_vim_var_list(int idx, list_T *val)
2119{
2120 clear_tv(&vimvars[idx].vv_di.di_tv);
2121 vimvars[idx].vv_type = VAR_LIST;
2122 vimvars[idx].vv_list = val;
2123 if (val != NULL)
2124 ++val->lv_refcount;
2125}
2126
2127/*
2128 * Set Dictionary v: variable to "val".
2129 */
2130 void
2131set_vim_var_dict(int idx, dict_T *val)
2132{
2133 clear_tv(&vimvars[idx].vv_di.di_tv);
2134 vimvars[idx].vv_type = VAR_DICT;
2135 vimvars[idx].vv_dict = val;
2136 if (val != NULL)
2137 {
2138 ++val->dv_refcount;
2139 dict_set_items_ro(val);
2140 }
2141}
2142
2143/*
Bram Moolenaar69bf6342019-10-29 04:16:57 +01002144 * Set the v:argv list.
2145 */
2146 void
2147set_argv_var(char **argv, int argc)
2148{
2149 list_T *l = list_alloc();
2150 int i;
2151
2152 if (l == NULL)
2153 getout(1);
2154 l->lv_lock = VAR_FIXED;
2155 for (i = 0; i < argc; ++i)
2156 {
2157 if (list_append_string(l, (char_u *)argv[i], -1) == FAIL)
2158 getout(1);
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01002159 l->lv_u.mat.lv_last->li_tv.v_lock = VAR_FIXED;
Bram Moolenaar69bf6342019-10-29 04:16:57 +01002160 }
2161 set_vim_var_list(VV_ARGV, l);
2162}
2163
2164/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002165 * Set v:register if needed.
2166 */
2167 void
2168set_reg_var(int c)
2169{
2170 char_u regname;
2171
2172 if (c == 0 || c == ' ')
2173 regname = '"';
2174 else
2175 regname = c;
2176 // Avoid free/alloc when the value is already right.
2177 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
2178 set_vim_var_string(VV_REG, &regname, 1);
2179}
2180
2181/*
2182 * Get or set v:exception. If "oldval" == NULL, return the current value.
2183 * Otherwise, restore the value to "oldval" and return NULL.
2184 * Must always be called in pairs to save and restore v:exception! Does not
2185 * take care of memory allocations.
2186 */
2187 char_u *
2188v_exception(char_u *oldval)
2189{
2190 if (oldval == NULL)
2191 return vimvars[VV_EXCEPTION].vv_str;
2192
2193 vimvars[VV_EXCEPTION].vv_str = oldval;
2194 return NULL;
2195}
2196
2197/*
2198 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
2199 * Otherwise, restore the value to "oldval" and return NULL.
2200 * Must always be called in pairs to save and restore v:throwpoint! Does not
2201 * take care of memory allocations.
2202 */
2203 char_u *
2204v_throwpoint(char_u *oldval)
2205{
2206 if (oldval == NULL)
2207 return vimvars[VV_THROWPOINT].vv_str;
2208
2209 vimvars[VV_THROWPOINT].vv_str = oldval;
2210 return NULL;
2211}
2212
2213/*
2214 * Set v:cmdarg.
2215 * If "eap" != NULL, use "eap" to generate the value and return the old value.
2216 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
2217 * Must always be called in pairs!
2218 */
2219 char_u *
2220set_cmdarg(exarg_T *eap, char_u *oldarg)
2221{
2222 char_u *oldval;
2223 char_u *newval;
2224 unsigned len;
2225
2226 oldval = vimvars[VV_CMDARG].vv_str;
2227 if (eap == NULL)
2228 {
2229 vim_free(oldval);
2230 vimvars[VV_CMDARG].vv_str = oldarg;
2231 return NULL;
2232 }
2233
2234 if (eap->force_bin == FORCE_BIN)
2235 len = 6;
2236 else if (eap->force_bin == FORCE_NOBIN)
2237 len = 8;
2238 else
2239 len = 0;
2240
2241 if (eap->read_edit)
2242 len += 7;
2243
2244 if (eap->force_ff != 0)
2245 len += 10; // " ++ff=unix"
2246 if (eap->force_enc != 0)
2247 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
2248 if (eap->bad_char != 0)
2249 len += 7 + 4; // " ++bad=" + "keep" or "drop"
2250
2251 newval = alloc(len + 1);
2252 if (newval == NULL)
2253 return NULL;
2254
2255 if (eap->force_bin == FORCE_BIN)
2256 sprintf((char *)newval, " ++bin");
2257 else if (eap->force_bin == FORCE_NOBIN)
2258 sprintf((char *)newval, " ++nobin");
2259 else
2260 *newval = NUL;
2261
2262 if (eap->read_edit)
2263 STRCAT(newval, " ++edit");
2264
2265 if (eap->force_ff != 0)
2266 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
2267 eap->force_ff == 'u' ? "unix"
2268 : eap->force_ff == 'd' ? "dos"
2269 : "mac");
2270 if (eap->force_enc != 0)
2271 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
2272 eap->cmd + eap->force_enc);
2273 if (eap->bad_char == BAD_KEEP)
2274 STRCPY(newval + STRLEN(newval), " ++bad=keep");
2275 else if (eap->bad_char == BAD_DROP)
2276 STRCPY(newval + STRLEN(newval), " ++bad=drop");
2277 else if (eap->bad_char != 0)
2278 sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
2279 vimvars[VV_CMDARG].vv_str = newval;
2280 return oldval;
2281}
2282
2283/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002284 * Get the value of internal variable "name".
2285 * Return OK or FAIL. If OK is returned "rettv" must be cleared.
2286 */
2287 int
2288get_var_tv(
2289 char_u *name,
2290 int len, // length of "name"
2291 typval_T *rettv, // NULL when only checking existence
2292 dictitem_T **dip, // non-NULL when typval's dict item is needed
2293 int verbose, // may give error message
2294 int no_autoload) // do not use script autoloading
2295{
2296 int ret = OK;
2297 typval_T *tv = NULL;
2298 dictitem_T *v;
2299 int cc;
2300
2301 // truncate the name, so that we can use strcmp()
2302 cc = name[len];
2303 name[len] = NUL;
2304
2305 // Check for user-defined variables.
2306 v = find_var(name, NULL, no_autoload);
2307 if (v != NULL)
2308 {
2309 tv = &v->di_tv;
2310 if (dip != NULL)
2311 *dip = v;
2312 }
2313
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002314 if (tv == NULL && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2315 {
Bram Moolenaar4e12a5d2020-02-03 20:50:59 +01002316 imported_T *import = find_imported(name, 0, NULL);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002317
2318 // imported variable from another script
2319 if (import != NULL)
2320 {
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002321 scriptitem_T *si = SCRIPT_ITEM(import->imp_sid);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002322 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data)
2323 + import->imp_var_vals_idx;
2324 tv = sv->sv_tv;
2325 }
2326 }
2327
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002328 if (tv == NULL)
2329 {
2330 if (rettv != NULL && verbose)
2331 semsg(_(e_undefvar), name);
2332 ret = FAIL;
2333 }
2334 else if (rettv != NULL)
2335 copy_tv(tv, rettv);
2336
2337 name[len] = cc;
2338
2339 return ret;
2340}
2341
2342/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002343 * Check if variable "name[len]" is a local variable or an argument.
2344 * If so, "*eval_lavars_used" is set to TRUE.
2345 */
2346 void
2347check_vars(char_u *name, int len)
2348{
2349 int cc;
2350 char_u *varname;
2351 hashtab_T *ht;
2352
2353 if (eval_lavars_used == NULL)
2354 return;
2355
2356 // truncate the name, so that we can use strcmp()
2357 cc = name[len];
2358 name[len] = NUL;
2359
2360 ht = find_var_ht(name, &varname);
2361 if (ht == get_funccal_local_ht() || ht == get_funccal_args_ht())
2362 {
2363 if (find_var(name, NULL, TRUE) != NULL)
2364 *eval_lavars_used = TRUE;
2365 }
2366
2367 name[len] = cc;
2368}
2369
2370/*
2371 * Find variable "name" in the list of variables.
2372 * Return a pointer to it if found, NULL if not found.
2373 * Careful: "a:0" variables don't have a name.
2374 * When "htp" is not NULL we are writing to the variable, set "htp" to the
2375 * hashtab_T used.
2376 */
2377 dictitem_T *
2378find_var(char_u *name, hashtab_T **htp, int no_autoload)
2379{
2380 char_u *varname;
2381 hashtab_T *ht;
2382 dictitem_T *ret = NULL;
2383
2384 ht = find_var_ht(name, &varname);
2385 if (htp != NULL)
2386 *htp = ht;
2387 if (ht == NULL)
2388 return NULL;
2389 ret = find_var_in_ht(ht, *name, varname, no_autoload || htp != NULL);
2390 if (ret != NULL)
2391 return ret;
2392
Bram Moolenaar8d71b542019-08-30 15:46:30 +02002393 // Search in parent scope for lambda
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002394 return find_var_in_scoped_ht(name, no_autoload || htp != NULL);
2395}
2396
2397/*
2398 * Find variable "varname" in hashtab "ht" with name "htname".
Bram Moolenaar52592752020-04-03 18:43:35 +02002399 * When "varname" is empty returns curwin/curtab/etc vars dictionary.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002400 * Returns NULL if not found.
2401 */
2402 dictitem_T *
2403find_var_in_ht(
2404 hashtab_T *ht,
2405 int htname,
2406 char_u *varname,
2407 int no_autoload)
2408{
2409 hashitem_T *hi;
2410
2411 if (*varname == NUL)
2412 {
2413 // Must be something like "s:", otherwise "ht" would be NULL.
2414 switch (htname)
2415 {
2416 case 's': return &SCRIPT_SV(current_sctx.sc_sid)->sv_var;
2417 case 'g': return &globvars_var;
2418 case 'v': return &vimvars_var;
2419 case 'b': return &curbuf->b_bufvar;
2420 case 'w': return &curwin->w_winvar;
2421 case 't': return &curtab->tp_winvar;
2422 case 'l': return get_funccal_local_var();
2423 case 'a': return get_funccal_args_var();
2424 }
2425 return NULL;
2426 }
2427
2428 hi = hash_find(ht, varname);
2429 if (HASHITEM_EMPTY(hi))
2430 {
2431 // For global variables we may try auto-loading the script. If it
2432 // worked find the variable again. Don't auto-load a script if it was
2433 // loaded already, otherwise it would be loaded every time when
2434 // checking if a function name is a Funcref variable.
2435 if (ht == &globvarht && !no_autoload)
2436 {
2437 // Note: script_autoload() may make "hi" invalid. It must either
2438 // be obtained again or not used.
2439 if (!script_autoload(varname, FALSE) || aborting())
2440 return NULL;
2441 hi = hash_find(ht, varname);
2442 }
2443 if (HASHITEM_EMPTY(hi))
2444 return NULL;
2445 }
2446 return HI2DI(hi);
2447}
2448
2449/*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002450 * Get the script-local hashtab. NULL if not in a script context.
2451 */
Bram Moolenaarbdff0122020-04-05 18:56:05 +02002452 static hashtab_T *
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002453get_script_local_ht(void)
2454{
2455 scid_T sid = current_sctx.sc_sid;
2456
2457 if (sid > 0 && sid <= script_items.ga_len)
2458 return &SCRIPT_VARS(sid);
2459 return NULL;
2460}
2461
2462/*
2463 * Look for "name[len]" in script-local variables.
2464 * Return -1 when not found.
2465 */
2466 int
2467lookup_scriptvar(char_u *name, size_t len, cctx_T *dummy UNUSED)
2468{
2469 hashtab_T *ht = get_script_local_ht();
2470 char_u buffer[30];
2471 char_u *p;
2472 int res;
2473 hashitem_T *hi;
2474
2475 if (ht == NULL)
2476 return -1;
2477 if (len < sizeof(buffer) - 1)
2478 {
2479 vim_strncpy(buffer, name, len);
2480 p = buffer;
2481 }
2482 else
2483 {
2484 p = vim_strnsave(name, (int)len);
2485 if (p == NULL)
2486 return -1;
2487 }
2488
2489 hi = hash_find(ht, p);
2490 res = HASHITEM_EMPTY(hi) ? -1 : 1;
2491
2492 // if not script-local, then perhaps imported
Bram Moolenaar4e12a5d2020-02-03 20:50:59 +01002493 if (res == -1 && find_imported(p, 0, NULL) != NULL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002494 res = 1;
2495
2496 if (p != buffer)
2497 vim_free(p);
2498 return res;
2499}
2500
2501/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002502 * Find the hashtab used for a variable name.
2503 * Return NULL if the name is not valid.
2504 * Set "varname" to the start of name without ':'.
2505 */
2506 hashtab_T *
2507find_var_ht(char_u *name, char_u **varname)
2508{
2509 hashitem_T *hi;
2510 hashtab_T *ht;
2511
2512 if (name[0] == NUL)
2513 return NULL;
2514 if (name[1] != ':')
2515 {
2516 // The name must not start with a colon or #.
2517 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
2518 return NULL;
2519 *varname = name;
2520
2521 // "version" is "v:version" in all scopes if scriptversion < 3.
2522 // Same for a few other variables marked with VV_COMPAT.
2523 if (current_sctx.sc_version < 3)
2524 {
2525 hi = hash_find(&compat_hashtab, name);
2526 if (!HASHITEM_EMPTY(hi))
2527 return &compat_hashtab;
2528 }
2529
2530 ht = get_funccal_local_ht();
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002531 if (ht != NULL)
2532 return ht; // local variable
2533
2534 // in Vim9 script items at the script level are script-local
2535 if (current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2536 {
2537 ht = get_script_local_ht();
2538 if (ht != NULL)
2539 return ht;
2540 }
2541
2542 return &globvarht; // global variable
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002543 }
2544 *varname = name + 2;
2545 if (*name == 'g') // global variable
2546 return &globvarht;
2547 // There must be no ':' or '#' in the rest of the name, unless g: is used
2548 if (vim_strchr(name + 2, ':') != NULL
2549 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
2550 return NULL;
2551 if (*name == 'b') // buffer variable
2552 return &curbuf->b_vars->dv_hashtab;
2553 if (*name == 'w') // window variable
2554 return &curwin->w_vars->dv_hashtab;
2555 if (*name == 't') // tab page variable
2556 return &curtab->tp_vars->dv_hashtab;
2557 if (*name == 'v') // v: variable
2558 return &vimvarht;
Bram Moolenaarb35efa52020-02-26 20:15:18 +01002559 if (get_current_funccal() != NULL
2560 && get_current_funccal()->func->uf_dfunc_idx < 0)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002561 {
Bram Moolenaarb35efa52020-02-26 20:15:18 +01002562 // a: and l: are only used in functions defined with ":function"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002563 if (*name == 'a') // a: function argument
2564 return get_funccal_args_ht();
2565 if (*name == 'l') // l: local function variable
2566 return get_funccal_local_ht();
2567 }
2568 if (*name == 's') // script variable
2569 {
2570 ht = get_script_local_ht();
2571 if (ht != NULL)
2572 return ht;
2573 }
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002574 return NULL;
2575}
2576
2577/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002578 * Get the string value of a (global/local) variable.
2579 * Note: see tv_get_string() for how long the pointer remains valid.
2580 * Returns NULL when it doesn't exist.
2581 */
2582 char_u *
2583get_var_value(char_u *name)
2584{
2585 dictitem_T *v;
2586
2587 v = find_var(name, NULL, FALSE);
2588 if (v == NULL)
2589 return NULL;
2590 return tv_get_string(&v->di_tv);
2591}
2592
2593/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002594 * Allocate a new hashtab for a sourced script. It will be used while
2595 * sourcing this script and when executing functions defined in the script.
2596 */
2597 void
2598new_script_vars(scid_T id)
2599{
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002600 scriptvar_T *sv;
2601
Bram Moolenaar7ebcba62020-01-12 17:42:55 +01002602 sv = ALLOC_CLEAR_ONE(scriptvar_T);
2603 if (sv == NULL)
2604 return;
2605 init_var_dict(&sv->sv_dict, &sv->sv_var, VAR_SCOPE);
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002606 SCRIPT_ITEM(id)->sn_vars = sv;
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002607}
2608
2609/*
2610 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
2611 * point to it.
2612 */
2613 void
2614init_var_dict(dict_T *dict, dictitem_T *dict_var, int scope)
2615{
2616 hash_init(&dict->dv_hashtab);
2617 dict->dv_lock = 0;
2618 dict->dv_scope = scope;
2619 dict->dv_refcount = DO_NOT_FREE_CNT;
2620 dict->dv_copyID = 0;
2621 dict_var->di_tv.vval.v_dict = dict;
2622 dict_var->di_tv.v_type = VAR_DICT;
2623 dict_var->di_tv.v_lock = VAR_FIXED;
2624 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
2625 dict_var->di_key[0] = NUL;
2626}
2627
2628/*
2629 * Unreference a dictionary initialized by init_var_dict().
2630 */
2631 void
2632unref_var_dict(dict_T *dict)
2633{
Bram Moolenaar8d71b542019-08-30 15:46:30 +02002634 // Now the dict needs to be freed if no one else is using it, go back to
2635 // normal reference counting.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002636 dict->dv_refcount -= DO_NOT_FREE_CNT - 1;
2637 dict_unref(dict);
2638}
2639
2640/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002641 * Clean up a list of internal variables.
2642 * Frees all allocated variables and the value they contain.
2643 * Clears hashtab "ht", does not free it.
2644 */
2645 void
2646vars_clear(hashtab_T *ht)
2647{
2648 vars_clear_ext(ht, TRUE);
2649}
2650
2651/*
2652 * Like vars_clear(), but only free the value if "free_val" is TRUE.
2653 */
2654 void
2655vars_clear_ext(hashtab_T *ht, int free_val)
2656{
2657 int todo;
2658 hashitem_T *hi;
2659 dictitem_T *v;
2660
2661 hash_lock(ht);
2662 todo = (int)ht->ht_used;
2663 for (hi = ht->ht_array; todo > 0; ++hi)
2664 {
2665 if (!HASHITEM_EMPTY(hi))
2666 {
2667 --todo;
2668
2669 // Free the variable. Don't remove it from the hashtab,
2670 // ht_array might change then. hash_clear() takes care of it
2671 // later.
2672 v = HI2DI(hi);
2673 if (free_val)
2674 clear_tv(&v->di_tv);
2675 if (v->di_flags & DI_FLAGS_ALLOC)
2676 vim_free(v);
2677 }
2678 }
2679 hash_clear(ht);
2680 ht->ht_used = 0;
2681}
2682
2683/*
2684 * Delete a variable from hashtab "ht" at item "hi".
2685 * Clear the variable value and free the dictitem.
2686 */
Bram Moolenaarda6c0332019-09-01 16:01:30 +02002687 static void
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002688delete_var(hashtab_T *ht, hashitem_T *hi)
2689{
2690 dictitem_T *di = HI2DI(hi);
2691
2692 hash_remove(ht, hi);
2693 clear_tv(&di->di_tv);
2694 vim_free(di);
2695}
2696
2697/*
2698 * List the value of one internal variable.
2699 */
2700 static void
2701list_one_var(dictitem_T *v, char *prefix, int *first)
2702{
2703 char_u *tofree;
2704 char_u *s;
2705 char_u numbuf[NUMBUFLEN];
2706
2707 s = echo_string(&v->di_tv, &tofree, numbuf, get_copyID());
2708 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
2709 s == NULL ? (char_u *)"" : s, first);
2710 vim_free(tofree);
2711}
2712
2713 static void
2714list_one_var_a(
2715 char *prefix,
2716 char_u *name,
2717 int type,
2718 char_u *string,
2719 int *first) // when TRUE clear rest of screen and set to FALSE
2720{
2721 // don't use msg() or msg_attr() to avoid overwriting "v:statusmsg"
2722 msg_start();
2723 msg_puts(prefix);
2724 if (name != NULL) // "a:" vars don't have a name stored
2725 msg_puts((char *)name);
2726 msg_putchar(' ');
2727 msg_advance(22);
2728 if (type == VAR_NUMBER)
2729 msg_putchar('#');
2730 else if (type == VAR_FUNC || type == VAR_PARTIAL)
2731 msg_putchar('*');
2732 else if (type == VAR_LIST)
2733 {
2734 msg_putchar('[');
2735 if (*string == '[')
2736 ++string;
2737 }
2738 else if (type == VAR_DICT)
2739 {
2740 msg_putchar('{');
2741 if (*string == '{')
2742 ++string;
2743 }
2744 else
2745 msg_putchar(' ');
2746
2747 msg_outtrans(string);
2748
2749 if (type == VAR_FUNC || type == VAR_PARTIAL)
2750 msg_puts("()");
2751 if (*first)
2752 {
2753 msg_clr_eos();
2754 *first = FALSE;
2755 }
2756}
2757
2758/*
2759 * Set variable "name" to value in "tv".
2760 * If the variable already exists, the value is updated.
2761 * Otherwise the variable is created.
2762 */
2763 void
2764set_var(
2765 char_u *name,
2766 typval_T *tv,
2767 int copy) // make copy of value in "tv"
2768{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002769 set_var_const(name, NULL, tv, copy, 0);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002770}
2771
2772/*
2773 * Set variable "name" to value in "tv".
2774 * If the variable already exists and "is_const" is FALSE the value is updated.
2775 * Otherwise the variable is created.
2776 */
2777 void
2778set_var_const(
2779 char_u *name,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002780 type_T *type,
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002781 typval_T *tv,
2782 int copy, // make copy of value in "tv"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002783 int flags) // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002784{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002785 dictitem_T *di;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002786 char_u *varname;
2787 hashtab_T *ht;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002788 int is_script_local;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002789
2790 ht = find_var_ht(name, &varname);
2791 if (ht == NULL || *varname == NUL)
2792 {
2793 semsg(_(e_illvar), name);
2794 return;
2795 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002796 is_script_local = ht == get_script_local_ht();
2797
2798 di = find_var_in_ht(ht, 0, varname, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002799
2800 // Search in parent scope which is possible to reference from lambda
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002801 if (di == NULL)
2802 di = find_var_in_scoped_ht(name, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002803
2804 if ((tv->v_type == VAR_FUNC || tv->v_type == VAR_PARTIAL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002805 && var_check_func_name(name, di == NULL))
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002806 return;
2807
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002808 if (di != NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002809 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002810 if ((di->di_flags & DI_FLAGS_RELOAD) == 0)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002811 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002812 if (flags & LET_IS_CONST)
2813 {
2814 emsg(_(e_cannot_mod));
2815 return;
2816 }
2817
2818 if (var_check_ro(di->di_flags, name, FALSE)
2819 || var_check_lock(di->di_tv.v_lock, name, FALSE))
2820 return;
2821
2822 if ((flags & LET_NO_COMMAND) == 0
2823 && is_script_local
2824 && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2825 {
2826 semsg(_("E1041: Redefining script item %s"), name);
2827 return;
2828 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002829 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002830 else
2831 // can only redefine once
2832 di->di_flags &= ~DI_FLAGS_RELOAD;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002833
2834 // existing variable, need to clear the value
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002835
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002836 // Handle setting internal di: variables separately where needed to
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002837 // prevent changing the type.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002838 if (ht == &vimvarht)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002839 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002840 if (di->di_tv.v_type == VAR_STRING)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002841 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002842 VIM_CLEAR(di->di_tv.vval.v_string);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002843 if (copy || tv->v_type != VAR_STRING)
2844 {
2845 char_u *val = tv_get_string(tv);
2846
2847 // Careful: when assigning to v:errmsg and tv_get_string()
Bram Moolenaar4b96df52020-01-26 22:00:26 +01002848 // causes an error message the variable will already be set.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002849 if (di->di_tv.vval.v_string == NULL)
2850 di->di_tv.vval.v_string = vim_strsave(val);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002851 }
2852 else
2853 {
2854 // Take over the string to avoid an extra alloc/free.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002855 di->di_tv.vval.v_string = tv->vval.v_string;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002856 tv->vval.v_string = NULL;
2857 }
2858 return;
2859 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002860 else if (di->di_tv.v_type == VAR_NUMBER)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002861 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002862 di->di_tv.vval.v_number = tv_get_number(tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002863 if (STRCMP(varname, "searchforward") == 0)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002864 set_search_direction(di->di_tv.vval.v_number ? '/' : '?');
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002865#ifdef FEAT_SEARCH_EXTRA
2866 else if (STRCMP(varname, "hlsearch") == 0)
2867 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002868 no_hlsearch = !di->di_tv.vval.v_number;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002869 redraw_all_later(SOME_VALID);
2870 }
2871#endif
2872 return;
2873 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002874 else if (di->di_tv.v_type != tv->v_type)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002875 {
2876 semsg(_("E963: setting %s to value with wrong type"), name);
2877 return;
2878 }
2879 }
2880
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002881 clear_tv(&di->di_tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002882 }
2883 else // add a new variable
2884 {
2885 // Can't add "v:" or "a:" variable.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002886 if (ht == &vimvarht || ht == get_funccal_args_ht())
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002887 {
2888 semsg(_(e_illvar), name);
2889 return;
2890 }
2891
2892 // Make sure the variable name is valid.
2893 if (!valid_varname(varname))
2894 return;
2895
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002896 di = alloc(sizeof(dictitem_T) + STRLEN(varname));
2897 if (di == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002898 return;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002899 STRCPY(di->di_key, varname);
2900 if (hash_add(ht, DI2HIKEY(di)) == FAIL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002901 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002902 vim_free(di);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002903 return;
2904 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002905 di->di_flags = DI_FLAGS_ALLOC;
2906 if (flags & LET_IS_CONST)
2907 di->di_flags |= DI_FLAGS_LOCK;
2908
2909 if (is_script_local && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2910 {
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002911 scriptitem_T *si = SCRIPT_ITEM(current_sctx.sc_sid);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002912
2913 // Store a pointer to the typval_T, so that it can be found by
2914 // index instead of using a hastab lookup.
2915 if (ga_grow(&si->sn_var_vals, 1) == OK)
2916 {
2917 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data)
2918 + si->sn_var_vals.ga_len;
2919 sv->sv_name = di->di_key;
2920 sv->sv_tv = &di->di_tv;
2921 sv->sv_type = type == NULL ? &t_any : type;
2922 sv->sv_const = (flags & LET_IS_CONST);
2923 sv->sv_export = is_export;
2924 ++si->sn_var_vals.ga_len;
2925
2926 // let ex_export() know the export worked.
2927 is_export = FALSE;
2928 }
2929 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002930 }
2931
2932 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002933 copy_tv(tv, &di->di_tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002934 else
2935 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002936 di->di_tv = *tv;
2937 di->di_tv.v_lock = 0;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002938 init_tv(tv);
2939 }
2940
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002941 if (flags & LET_IS_CONST)
2942 di->di_tv.v_lock |= VAR_LOCKED;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002943}
2944
2945/*
2946 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
2947 * Also give an error message.
2948 */
2949 int
2950var_check_ro(int flags, char_u *name, int use_gettext)
2951{
2952 if (flags & DI_FLAGS_RO)
2953 {
2954 semsg(_(e_readonlyvar), use_gettext ? (char_u *)_(name) : name);
2955 return TRUE;
2956 }
2957 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
2958 {
2959 semsg(_(e_readonlysbx), use_gettext ? (char_u *)_(name) : name);
2960 return TRUE;
2961 }
2962 return FALSE;
2963}
2964
2965/*
2966 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
2967 * Also give an error message.
2968 */
2969 int
2970var_check_fixed(int flags, char_u *name, int use_gettext)
2971{
2972 if (flags & DI_FLAGS_FIX)
2973 {
2974 semsg(_("E795: Cannot delete variable %s"),
2975 use_gettext ? (char_u *)_(name) : name);
2976 return TRUE;
2977 }
2978 return FALSE;
2979}
2980
2981/*
2982 * Check if a funcref is assigned to a valid variable name.
2983 * Return TRUE and give an error if not.
2984 */
2985 int
2986var_check_func_name(
2987 char_u *name, // points to start of variable name
2988 int new_var) // TRUE when creating the variable
2989{
2990 // Allow for w: b: s: and t:.
2991 if (!(vim_strchr((char_u *)"wbst", name[0]) != NULL && name[1] == ':')
2992 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
2993 ? name[2] : name[0]))
2994 {
2995 semsg(_("E704: Funcref variable name must start with a capital: %s"),
2996 name);
2997 return TRUE;
2998 }
2999 // Don't allow hiding a function. When "v" is not NULL we might be
3000 // assigning another function to the same var, the type is checked
3001 // below.
3002 if (new_var && function_exists(name, FALSE))
3003 {
3004 semsg(_("E705: Variable name conflicts with existing function: %s"),
3005 name);
3006 return TRUE;
3007 }
3008 return FALSE;
3009}
3010
3011/*
3012 * Return TRUE if "flags" indicates variable "name" is locked (immutable).
3013 * Also give an error message, using "name" or _("name") when use_gettext is
3014 * TRUE.
3015 */
3016 int
3017var_check_lock(int lock, char_u *name, int use_gettext)
3018{
3019 if (lock & VAR_LOCKED)
3020 {
3021 semsg(_("E741: Value is locked: %s"),
3022 name == NULL ? (char_u *)_("Unknown")
3023 : use_gettext ? (char_u *)_(name)
3024 : name);
3025 return TRUE;
3026 }
3027 if (lock & VAR_FIXED)
3028 {
3029 semsg(_("E742: Cannot change value of %s"),
3030 name == NULL ? (char_u *)_("Unknown")
3031 : use_gettext ? (char_u *)_(name)
3032 : name);
3033 return TRUE;
3034 }
3035 return FALSE;
3036}
3037
3038/*
3039 * Check if a variable name is valid.
3040 * Return FALSE and give an error if not.
3041 */
3042 int
3043valid_varname(char_u *varname)
3044{
3045 char_u *p;
3046
3047 for (p = varname; *p != NUL; ++p)
3048 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
3049 && *p != AUTOLOAD_CHAR)
3050 {
3051 semsg(_(e_illvar), varname);
3052 return FALSE;
3053 }
3054 return TRUE;
3055}
3056
3057/*
3058 * getwinvar() and gettabwinvar()
3059 */
3060 static void
3061getwinvar(
3062 typval_T *argvars,
3063 typval_T *rettv,
3064 int off) // 1 for gettabwinvar()
3065{
3066 win_T *win;
3067 char_u *varname;
3068 dictitem_T *v;
3069 tabpage_T *tp = NULL;
3070 int done = FALSE;
3071 win_T *oldcurwin;
3072 tabpage_T *oldtabpage;
3073 int need_switch_win;
3074
3075 if (off == 1)
3076 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3077 else
3078 tp = curtab;
3079 win = find_win_by_nr(&argvars[off], tp);
3080 varname = tv_get_string_chk(&argvars[off + 1]);
3081 ++emsg_off;
3082
3083 rettv->v_type = VAR_STRING;
3084 rettv->vval.v_string = NULL;
3085
3086 if (win != NULL && varname != NULL)
3087 {
3088 // Set curwin to be our win, temporarily. Also set the tabpage,
3089 // otherwise the window is not valid. Only do this when needed,
3090 // autocommands get blocked.
3091 need_switch_win = !(tp == curtab && win == curwin);
3092 if (!need_switch_win
3093 || switch_win(&oldcurwin, &oldtabpage, win, tp, TRUE) == OK)
3094 {
3095 if (*varname == '&')
3096 {
3097 if (varname[1] == NUL)
3098 {
3099 // get all window-local options in a dict
3100 dict_T *opts = get_winbuf_options(FALSE);
3101
3102 if (opts != NULL)
3103 {
3104 rettv_dict_set(rettv, opts);
3105 done = TRUE;
3106 }
3107 }
3108 else if (get_option_tv(&varname, rettv, 1) == OK)
3109 // window-local-option
3110 done = TRUE;
3111 }
3112 else
3113 {
3114 // Look up the variable.
3115 // Let getwinvar({nr}, "") return the "w:" dictionary.
3116 v = find_var_in_ht(&win->w_vars->dv_hashtab, 'w',
3117 varname, FALSE);
3118 if (v != NULL)
3119 {
3120 copy_tv(&v->di_tv, rettv);
3121 done = TRUE;
3122 }
3123 }
3124 }
3125
3126 if (need_switch_win)
3127 // restore previous notion of curwin
3128 restore_win(oldcurwin, oldtabpage, TRUE);
3129 }
3130
3131 if (!done && argvars[off + 2].v_type != VAR_UNKNOWN)
3132 // use the default return value
3133 copy_tv(&argvars[off + 2], rettv);
3134
3135 --emsg_off;
3136}
3137
3138/*
3139 * "setwinvar()" and "settabwinvar()" functions
3140 */
3141 static void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003142setwinvar(typval_T *argvars, int off)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003143{
3144 win_T *win;
3145 win_T *save_curwin;
3146 tabpage_T *save_curtab;
3147 int need_switch_win;
3148 char_u *varname, *winvarname;
3149 typval_T *varp;
3150 char_u nbuf[NUMBUFLEN];
3151 tabpage_T *tp = NULL;
3152
3153 if (check_secure())
3154 return;
3155
3156 if (off == 1)
3157 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3158 else
3159 tp = curtab;
3160 win = find_win_by_nr(&argvars[off], tp);
3161 varname = tv_get_string_chk(&argvars[off + 1]);
3162 varp = &argvars[off + 2];
3163
3164 if (win != NULL && varname != NULL && varp != NULL)
3165 {
3166 need_switch_win = !(tp == curtab && win == curwin);
3167 if (!need_switch_win
3168 || switch_win(&save_curwin, &save_curtab, win, tp, TRUE) == OK)
3169 {
3170 if (*varname == '&')
3171 {
3172 long numval;
3173 char_u *strval;
3174 int error = FALSE;
3175
3176 ++varname;
3177 numval = (long)tv_get_number_chk(varp, &error);
3178 strval = tv_get_string_buf_chk(varp, nbuf);
3179 if (!error && strval != NULL)
3180 set_option_value(varname, numval, strval, OPT_LOCAL);
3181 }
3182 else
3183 {
3184 winvarname = alloc(STRLEN(varname) + 3);
3185 if (winvarname != NULL)
3186 {
3187 STRCPY(winvarname, "w:");
3188 STRCPY(winvarname + 2, varname);
3189 set_var(winvarname, varp, TRUE);
3190 vim_free(winvarname);
3191 }
3192 }
3193 }
3194 if (need_switch_win)
3195 restore_win(save_curwin, save_curtab, TRUE);
3196 }
3197}
3198
Bram Moolenaare5cdf152019-08-29 22:09:46 +02003199/*
3200 * reset v:option_new, v:option_old, v:option_oldlocal, v:option_oldglobal,
3201 * v:option_type, and v:option_command.
3202 */
3203 void
3204reset_v_option_vars(void)
3205{
3206 set_vim_var_string(VV_OPTION_NEW, NULL, -1);
3207 set_vim_var_string(VV_OPTION_OLD, NULL, -1);
3208 set_vim_var_string(VV_OPTION_OLDLOCAL, NULL, -1);
3209 set_vim_var_string(VV_OPTION_OLDGLOBAL, NULL, -1);
3210 set_vim_var_string(VV_OPTION_TYPE, NULL, -1);
3211 set_vim_var_string(VV_OPTION_COMMAND, NULL, -1);
3212}
3213
3214/*
3215 * Add an assert error to v:errors.
3216 */
3217 void
3218assert_error(garray_T *gap)
3219{
3220 struct vimvar *vp = &vimvars[VV_ERRORS];
3221
3222 if (vp->vv_type != VAR_LIST || vimvars[VV_ERRORS].vv_list == NULL)
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003223 // Make sure v:errors is a list.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02003224 set_vim_var_list(VV_ERRORS, list_alloc());
3225 list_append_string(vimvars[VV_ERRORS].vv_list, gap->ga_data, gap->ga_len);
3226}
3227
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003228 int
3229var_exists(char_u *var)
3230{
3231 char_u *name;
3232 char_u *tofree;
3233 typval_T tv;
3234 int len = 0;
3235 int n = FALSE;
3236
3237 // get_name_len() takes care of expanding curly braces
3238 name = var;
3239 len = get_name_len(&var, &tofree, TRUE, FALSE);
3240 if (len > 0)
3241 {
3242 if (tofree != NULL)
3243 name = tofree;
3244 n = (get_var_tv(name, len, &tv, NULL, FALSE, TRUE) == OK);
3245 if (n)
3246 {
3247 // handle d.key, l[idx], f(expr)
3248 n = (handle_subscript(&var, &tv, TRUE, FALSE, name, &name) == OK);
3249 if (n)
3250 clear_tv(&tv);
3251 }
3252 }
3253 if (*var != NUL)
3254 n = FALSE;
3255
3256 vim_free(tofree);
3257 return n;
3258}
3259
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003260static lval_T *redir_lval = NULL;
3261#define EVALCMD_BUSY (redir_lval == (lval_T *)&redir_lval)
3262static garray_T redir_ga; // only valid when redir_lval is not NULL
3263static char_u *redir_endp = NULL;
3264static char_u *redir_varname = NULL;
3265
3266/*
3267 * Start recording command output to a variable
3268 * When "append" is TRUE append to an existing variable.
3269 * Returns OK if successfully completed the setup. FAIL otherwise.
3270 */
3271 int
3272var_redir_start(char_u *name, int append)
3273{
3274 int save_emsg;
3275 int err;
3276 typval_T tv;
3277
3278 // Catch a bad name early.
3279 if (!eval_isnamec1(*name))
3280 {
3281 emsg(_(e_invarg));
3282 return FAIL;
3283 }
3284
3285 // Make a copy of the name, it is used in redir_lval until redir ends.
3286 redir_varname = vim_strsave(name);
3287 if (redir_varname == NULL)
3288 return FAIL;
3289
3290 redir_lval = ALLOC_CLEAR_ONE(lval_T);
3291 if (redir_lval == NULL)
3292 {
3293 var_redir_stop();
3294 return FAIL;
3295 }
3296
3297 // The output is stored in growarray "redir_ga" until redirection ends.
3298 ga_init2(&redir_ga, (int)sizeof(char), 500);
3299
3300 // Parse the variable name (can be a dict or list entry).
3301 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, 0,
3302 FNE_CHECK_START);
3303 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
3304 {
3305 clear_lval(redir_lval);
3306 if (redir_endp != NULL && *redir_endp != NUL)
3307 // Trailing characters are present after the variable name
3308 emsg(_(e_trailing));
3309 else
3310 emsg(_(e_invarg));
3311 redir_endp = NULL; // don't store a value, only cleanup
3312 var_redir_stop();
3313 return FAIL;
3314 }
3315
3316 // check if we can write to the variable: set it to or append an empty
3317 // string
3318 save_emsg = did_emsg;
3319 did_emsg = FALSE;
3320 tv.v_type = VAR_STRING;
3321 tv.vval.v_string = (char_u *)"";
3322 if (append)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003323 set_var_lval(redir_lval, redir_endp, &tv, TRUE, 0, (char_u *)".");
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003324 else
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003325 set_var_lval(redir_lval, redir_endp, &tv, TRUE, 0, (char_u *)"=");
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003326 clear_lval(redir_lval);
3327 err = did_emsg;
3328 did_emsg |= save_emsg;
3329 if (err)
3330 {
3331 redir_endp = NULL; // don't store a value, only cleanup
3332 var_redir_stop();
3333 return FAIL;
3334 }
3335
3336 return OK;
3337}
3338
3339/*
3340 * Append "value[value_len]" to the variable set by var_redir_start().
3341 * The actual appending is postponed until redirection ends, because the value
3342 * appended may in fact be the string we write to, changing it may cause freed
3343 * memory to be used:
3344 * :redir => foo
3345 * :let foo
3346 * :redir END
3347 */
3348 void
3349var_redir_str(char_u *value, int value_len)
3350{
3351 int len;
3352
3353 if (redir_lval == NULL)
3354 return;
3355
3356 if (value_len == -1)
3357 len = (int)STRLEN(value); // Append the entire string
3358 else
3359 len = value_len; // Append only "value_len" characters
3360
3361 if (ga_grow(&redir_ga, len) == OK)
3362 {
3363 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
3364 redir_ga.ga_len += len;
3365 }
3366 else
3367 var_redir_stop();
3368}
3369
3370/*
3371 * Stop redirecting command output to a variable.
3372 * Frees the allocated memory.
3373 */
3374 void
3375var_redir_stop(void)
3376{
3377 typval_T tv;
3378
3379 if (EVALCMD_BUSY)
3380 {
3381 redir_lval = NULL;
3382 return;
3383 }
3384
3385 if (redir_lval != NULL)
3386 {
3387 // If there was no error: assign the text to the variable.
3388 if (redir_endp != NULL)
3389 {
3390 ga_append(&redir_ga, NUL); // Append the trailing NUL.
3391 tv.v_type = VAR_STRING;
3392 tv.vval.v_string = redir_ga.ga_data;
3393 // Call get_lval() again, if it's inside a Dict or List it may
3394 // have changed.
3395 redir_endp = get_lval(redir_varname, NULL, redir_lval,
3396 FALSE, FALSE, 0, FNE_CHECK_START);
3397 if (redir_endp != NULL && redir_lval->ll_name != NULL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003398 set_var_lval(redir_lval, redir_endp, &tv, FALSE, 0,
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003399 (char_u *)".");
3400 clear_lval(redir_lval);
3401 }
3402
3403 // free the collected output
3404 VIM_CLEAR(redir_ga.ga_data);
3405
3406 VIM_CLEAR(redir_lval);
3407 }
3408 VIM_CLEAR(redir_varname);
3409}
3410
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003411/*
3412 * "gettabvar()" function
3413 */
3414 void
3415f_gettabvar(typval_T *argvars, typval_T *rettv)
3416{
3417 win_T *oldcurwin;
3418 tabpage_T *tp, *oldtabpage;
3419 dictitem_T *v;
3420 char_u *varname;
3421 int done = FALSE;
3422
3423 rettv->v_type = VAR_STRING;
3424 rettv->vval.v_string = NULL;
3425
3426 varname = tv_get_string_chk(&argvars[1]);
3427 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3428 if (tp != NULL && varname != NULL)
3429 {
3430 // Set tp to be our tabpage, temporarily. Also set the window to the
3431 // first window in the tabpage, otherwise the window is not valid.
3432 if (switch_win(&oldcurwin, &oldtabpage,
3433 tp == curtab || tp->tp_firstwin == NULL ? firstwin
3434 : tp->tp_firstwin, tp, TRUE) == OK)
3435 {
3436 // look up the variable
3437 // Let gettabvar({nr}, "") return the "t:" dictionary.
3438 v = find_var_in_ht(&tp->tp_vars->dv_hashtab, 't', varname, FALSE);
3439 if (v != NULL)
3440 {
3441 copy_tv(&v->di_tv, rettv);
3442 done = TRUE;
3443 }
3444 }
3445
3446 // restore previous notion of curwin
3447 restore_win(oldcurwin, oldtabpage, TRUE);
3448 }
3449
3450 if (!done && argvars[2].v_type != VAR_UNKNOWN)
3451 copy_tv(&argvars[2], rettv);
3452}
3453
3454/*
3455 * "gettabwinvar()" function
3456 */
3457 void
3458f_gettabwinvar(typval_T *argvars, typval_T *rettv)
3459{
3460 getwinvar(argvars, rettv, 1);
3461}
3462
3463/*
3464 * "getwinvar()" function
3465 */
3466 void
3467f_getwinvar(typval_T *argvars, typval_T *rettv)
3468{
3469 getwinvar(argvars, rettv, 0);
3470}
3471
3472/*
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003473 * "getbufvar()" function
3474 */
3475 void
3476f_getbufvar(typval_T *argvars, typval_T *rettv)
3477{
3478 buf_T *buf;
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003479 char_u *varname;
3480 dictitem_T *v;
3481 int done = FALSE;
3482
3483 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
3484 varname = tv_get_string_chk(&argvars[1]);
3485 ++emsg_off;
3486 buf = tv_get_buf(&argvars[0], FALSE);
3487
3488 rettv->v_type = VAR_STRING;
3489 rettv->vval.v_string = NULL;
3490
3491 if (buf != NULL && varname != NULL)
3492 {
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003493 if (*varname == '&')
3494 {
Bram Moolenaar86015452020-03-29 15:12:15 +02003495 buf_T *save_curbuf = curbuf;
3496
3497 // set curbuf to be our buf, temporarily
3498 curbuf = buf;
3499
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003500 if (varname[1] == NUL)
3501 {
3502 // get all buffer-local options in a dict
3503 dict_T *opts = get_winbuf_options(TRUE);
3504
3505 if (opts != NULL)
3506 {
3507 rettv_dict_set(rettv, opts);
3508 done = TRUE;
3509 }
3510 }
3511 else if (get_option_tv(&varname, rettv, TRUE) == OK)
3512 // buffer-local-option
3513 done = TRUE;
Bram Moolenaar86015452020-03-29 15:12:15 +02003514
3515 // restore previous notion of curbuf
3516 curbuf = save_curbuf;
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003517 }
3518 else
3519 {
3520 // Look up the variable.
Bram Moolenaar52592752020-04-03 18:43:35 +02003521 if (*varname == NUL)
3522 // Let getbufvar({nr}, "") return the "b:" dictionary.
3523 v = &buf->b_bufvar;
3524 else
3525 v = find_var_in_ht(&buf->b_vars->dv_hashtab, 'b',
3526 varname, FALSE);
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003527 if (v != NULL)
3528 {
3529 copy_tv(&v->di_tv, rettv);
3530 done = TRUE;
3531 }
3532 }
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003533 }
3534
3535 if (!done && argvars[2].v_type != VAR_UNKNOWN)
3536 // use the default value
3537 copy_tv(&argvars[2], rettv);
3538
3539 --emsg_off;
3540}
3541
3542/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003543 * "settabvar()" function
3544 */
3545 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003546f_settabvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003547{
3548 tabpage_T *save_curtab;
3549 tabpage_T *tp;
3550 char_u *varname, *tabvarname;
3551 typval_T *varp;
3552
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003553 if (check_secure())
3554 return;
3555
3556 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3557 varname = tv_get_string_chk(&argvars[1]);
3558 varp = &argvars[2];
3559
3560 if (varname != NULL && varp != NULL && tp != NULL)
3561 {
3562 save_curtab = curtab;
3563 goto_tabpage_tp(tp, FALSE, FALSE);
3564
3565 tabvarname = alloc(STRLEN(varname) + 3);
3566 if (tabvarname != NULL)
3567 {
3568 STRCPY(tabvarname, "t:");
3569 STRCPY(tabvarname + 2, varname);
3570 set_var(tabvarname, varp, TRUE);
3571 vim_free(tabvarname);
3572 }
3573
3574 // Restore current tabpage
3575 if (valid_tabpage(save_curtab))
3576 goto_tabpage_tp(save_curtab, FALSE, FALSE);
3577 }
3578}
3579
3580/*
3581 * "settabwinvar()" function
3582 */
3583 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003584f_settabwinvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003585{
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003586 setwinvar(argvars, 1);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003587}
3588
3589/*
3590 * "setwinvar()" function
3591 */
3592 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003593f_setwinvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003594{
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003595 setwinvar(argvars, 0);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003596}
3597
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003598/*
3599 * "setbufvar()" function
3600 */
3601 void
3602f_setbufvar(typval_T *argvars, typval_T *rettv UNUSED)
3603{
3604 buf_T *buf;
3605 char_u *varname, *bufvarname;
3606 typval_T *varp;
3607 char_u nbuf[NUMBUFLEN];
3608
3609 if (check_secure())
3610 return;
3611 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
3612 varname = tv_get_string_chk(&argvars[1]);
3613 buf = tv_get_buf(&argvars[0], FALSE);
3614 varp = &argvars[2];
3615
3616 if (buf != NULL && varname != NULL && varp != NULL)
3617 {
3618 if (*varname == '&')
3619 {
3620 long numval;
3621 char_u *strval;
3622 int error = FALSE;
3623 aco_save_T aco;
3624
3625 // set curbuf to be our buf, temporarily
3626 aucmd_prepbuf(&aco, buf);
3627
3628 ++varname;
3629 numval = (long)tv_get_number_chk(varp, &error);
3630 strval = tv_get_string_buf_chk(varp, nbuf);
3631 if (!error && strval != NULL)
3632 set_option_value(varname, numval, strval, OPT_LOCAL);
3633
3634 // reset notion of buffer
3635 aucmd_restbuf(&aco);
3636 }
3637 else
3638 {
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003639 bufvarname = alloc(STRLEN(varname) + 3);
3640 if (bufvarname != NULL)
3641 {
Bram Moolenaar86015452020-03-29 15:12:15 +02003642 buf_T *save_curbuf = curbuf;
3643
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003644 curbuf = buf;
3645 STRCPY(bufvarname, "b:");
3646 STRCPY(bufvarname + 2, varname);
3647 set_var(bufvarname, varp, TRUE);
3648 vim_free(bufvarname);
3649 curbuf = save_curbuf;
3650 }
3651 }
3652 }
3653}
3654
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003655/*
3656 * Get a callback from "arg". It can be a Funcref or a function name.
3657 * When "arg" is zero return an empty string.
3658 * "cb_name" is not allocated.
3659 * "cb_name" is set to NULL for an invalid argument.
3660 */
3661 callback_T
3662get_callback(typval_T *arg)
3663{
Bram Moolenaar14e579092020-03-07 16:59:25 +01003664 callback_T res;
3665 int r = OK;
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003666
3667 res.cb_free_name = FALSE;
3668 if (arg->v_type == VAR_PARTIAL && arg->vval.v_partial != NULL)
3669 {
3670 res.cb_partial = arg->vval.v_partial;
3671 ++res.cb_partial->pt_refcount;
3672 res.cb_name = partial_name(res.cb_partial);
3673 }
3674 else
3675 {
3676 res.cb_partial = NULL;
Bram Moolenaar14e579092020-03-07 16:59:25 +01003677 if (arg->v_type == VAR_STRING && arg->vval.v_string != NULL
3678 && isdigit(*arg->vval.v_string))
3679 r = FAIL;
3680 else if (arg->v_type == VAR_FUNC || arg->v_type == VAR_STRING)
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003681 {
3682 // Note that we don't make a copy of the string.
3683 res.cb_name = arg->vval.v_string;
3684 func_ref(res.cb_name);
3685 }
3686 else if (arg->v_type == VAR_NUMBER && arg->vval.v_number == 0)
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003687 res.cb_name = (char_u *)"";
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003688 else
Bram Moolenaar14e579092020-03-07 16:59:25 +01003689 r = FAIL;
3690
3691 if (r == FAIL)
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003692 {
3693 emsg(_("E921: Invalid callback argument"));
3694 res.cb_name = NULL;
3695 }
3696 }
3697 return res;
3698}
3699
3700/*
3701 * Copy a callback into a typval_T.
3702 */
3703 void
3704put_callback(callback_T *cb, typval_T *tv)
3705{
3706 if (cb->cb_partial != NULL)
3707 {
3708 tv->v_type = VAR_PARTIAL;
3709 tv->vval.v_partial = cb->cb_partial;
3710 ++tv->vval.v_partial->pt_refcount;
3711 }
3712 else
3713 {
3714 tv->v_type = VAR_FUNC;
3715 tv->vval.v_string = vim_strsave(cb->cb_name);
3716 func_ref(cb->cb_name);
3717 }
3718}
3719
3720/*
3721 * Make a copy of "src" into "dest", allocating the function name if needed,
3722 * without incrementing the refcount.
3723 */
3724 void
3725set_callback(callback_T *dest, callback_T *src)
3726{
3727 if (src->cb_partial == NULL)
3728 {
3729 // just a function name, make a copy
3730 dest->cb_name = vim_strsave(src->cb_name);
3731 dest->cb_free_name = TRUE;
3732 }
3733 else
3734 {
3735 // cb_name is a pointer into cb_partial
3736 dest->cb_name = src->cb_name;
3737 dest->cb_free_name = FALSE;
3738 }
3739 dest->cb_partial = src->cb_partial;
3740}
3741
3742/*
3743 * Unref/free "callback" returned by get_callback() or set_callback().
3744 */
3745 void
3746free_callback(callback_T *callback)
3747{
3748 if (callback->cb_partial != NULL)
3749 {
3750 partial_unref(callback->cb_partial);
3751 callback->cb_partial = NULL;
3752 }
3753 else if (callback->cb_name != NULL)
3754 func_unref(callback->cb_name);
3755 if (callback->cb_free_name)
3756 {
3757 vim_free(callback->cb_name);
3758 callback->cb_free_name = FALSE;
3759 }
3760 callback->cb_name = NULL;
3761}
3762
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003763#endif // FEAT_EVAL