blob: 40a22f69075747e08cd91239c50057d438b24df9 [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 {
933 emsg(_("Double ; in list of variables"));
934 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 Moolenaar8a7d6542020-01-26 15:56:19 +01001671 case VAR_VOID:
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001672 case VAR_NUMBER:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001673 case VAR_BOOL:
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001674 case VAR_STRING:
1675 case VAR_FUNC:
1676 case VAR_PARTIAL:
1677 case VAR_FLOAT:
1678 case VAR_SPECIAL:
1679 case VAR_JOB:
1680 case VAR_CHANNEL:
1681 break;
1682
1683 case VAR_BLOB:
1684 if ((b = tv->vval.v_blob) != NULL)
1685 {
1686 if (lock)
1687 b->bv_lock |= VAR_LOCKED;
1688 else
1689 b->bv_lock &= ~VAR_LOCKED;
1690 }
1691 break;
1692 case VAR_LIST:
1693 if ((l = tv->vval.v_list) != NULL)
1694 {
1695 if (lock)
1696 l->lv_lock |= VAR_LOCKED;
1697 else
1698 l->lv_lock &= ~VAR_LOCKED;
Bram Moolenaar50985eb2020-01-27 22:09:39 +01001699 if ((deep < 0 || deep > 1) && l->lv_first != &range_list_item)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001700 // recursive: lock/unlock the items the List contains
1701 for (li = l->lv_first; li != NULL; li = li->li_next)
1702 item_lock(&li->li_tv, deep - 1, lock);
1703 }
1704 break;
1705 case VAR_DICT:
1706 if ((d = tv->vval.v_dict) != NULL)
1707 {
1708 if (lock)
1709 d->dv_lock |= VAR_LOCKED;
1710 else
1711 d->dv_lock &= ~VAR_LOCKED;
1712 if (deep < 0 || deep > 1)
1713 {
1714 // recursive: lock/unlock the items the List contains
1715 todo = (int)d->dv_hashtab.ht_used;
1716 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
1717 {
1718 if (!HASHITEM_EMPTY(hi))
1719 {
1720 --todo;
1721 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
1722 }
1723 }
1724 }
1725 }
1726 }
1727 --recurse;
1728}
1729
Bram Moolenaarda6c0332019-09-01 16:01:30 +02001730#if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
1731/*
1732 * Delete all "menutrans_" variables.
1733 */
1734 void
1735del_menutrans_vars(void)
1736{
1737 hashitem_T *hi;
1738 int todo;
1739
1740 hash_lock(&globvarht);
1741 todo = (int)globvarht.ht_used;
1742 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
1743 {
1744 if (!HASHITEM_EMPTY(hi))
1745 {
1746 --todo;
1747 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
1748 delete_var(&globvarht, hi);
1749 }
1750 }
1751 hash_unlock(&globvarht);
1752}
1753#endif
1754
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001755/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001756 * Local string buffer for the next two functions to store a variable name
1757 * with its prefix. Allocated in cat_prefix_varname(), freed later in
1758 * get_user_var_name().
1759 */
1760
1761static char_u *varnamebuf = NULL;
1762static int varnamebuflen = 0;
1763
1764/*
1765 * Function to concatenate a prefix and a variable name.
1766 */
1767 static char_u *
1768cat_prefix_varname(int prefix, char_u *name)
1769{
1770 int len;
1771
1772 len = (int)STRLEN(name) + 3;
1773 if (len > varnamebuflen)
1774 {
1775 vim_free(varnamebuf);
Bram Moolenaar8d71b542019-08-30 15:46:30 +02001776 len += 10; // some additional space
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001777 varnamebuf = alloc(len);
1778 if (varnamebuf == NULL)
1779 {
1780 varnamebuflen = 0;
1781 return NULL;
1782 }
1783 varnamebuflen = len;
1784 }
1785 *varnamebuf = prefix;
1786 varnamebuf[1] = ':';
1787 STRCPY(varnamebuf + 2, name);
1788 return varnamebuf;
1789}
1790
1791/*
1792 * Function given to ExpandGeneric() to obtain the list of user defined
1793 * (global/buffer/window/built-in) variable names.
1794 */
1795 char_u *
1796get_user_var_name(expand_T *xp, int idx)
1797{
1798 static long_u gdone;
1799 static long_u bdone;
1800 static long_u wdone;
1801 static long_u tdone;
1802 static int vidx;
1803 static hashitem_T *hi;
1804 hashtab_T *ht;
1805
1806 if (idx == 0)
1807 {
1808 gdone = bdone = wdone = vidx = 0;
1809 tdone = 0;
1810 }
1811
1812 // Global variables
1813 if (gdone < globvarht.ht_used)
1814 {
1815 if (gdone++ == 0)
1816 hi = globvarht.ht_array;
1817 else
1818 ++hi;
1819 while (HASHITEM_EMPTY(hi))
1820 ++hi;
1821 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
1822 return cat_prefix_varname('g', hi->hi_key);
1823 return hi->hi_key;
1824 }
1825
1826 // b: variables
1827 ht = &curbuf->b_vars->dv_hashtab;
1828 if (bdone < ht->ht_used)
1829 {
1830 if (bdone++ == 0)
1831 hi = ht->ht_array;
1832 else
1833 ++hi;
1834 while (HASHITEM_EMPTY(hi))
1835 ++hi;
1836 return cat_prefix_varname('b', hi->hi_key);
1837 }
1838
1839 // w: variables
1840 ht = &curwin->w_vars->dv_hashtab;
1841 if (wdone < ht->ht_used)
1842 {
1843 if (wdone++ == 0)
1844 hi = ht->ht_array;
1845 else
1846 ++hi;
1847 while (HASHITEM_EMPTY(hi))
1848 ++hi;
1849 return cat_prefix_varname('w', hi->hi_key);
1850 }
1851
1852 // t: variables
1853 ht = &curtab->tp_vars->dv_hashtab;
1854 if (tdone < ht->ht_used)
1855 {
1856 if (tdone++ == 0)
1857 hi = ht->ht_array;
1858 else
1859 ++hi;
1860 while (HASHITEM_EMPTY(hi))
1861 ++hi;
1862 return cat_prefix_varname('t', hi->hi_key);
1863 }
1864
1865 // v: variables
1866 if (vidx < VV_LEN)
1867 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
1868
1869 VIM_CLEAR(varnamebuf);
1870 varnamebuflen = 0;
1871 return NULL;
1872}
1873
Bram Moolenaarda6c0332019-09-01 16:01:30 +02001874 char *
1875get_var_special_name(int nr)
1876{
1877 switch (nr)
1878 {
1879 case VVAL_FALSE: return "v:false";
1880 case VVAL_TRUE: return "v:true";
1881 case VVAL_NONE: return "v:none";
1882 case VVAL_NULL: return "v:null";
1883 }
1884 internal_error("get_var_special_name()");
1885 return "42";
1886}
1887
1888/*
1889 * Returns the global variable dictionary
1890 */
1891 dict_T *
1892get_globvar_dict(void)
1893{
1894 return &globvardict;
1895}
1896
1897/*
1898 * Returns the global variable hash table
1899 */
1900 hashtab_T *
1901get_globvar_ht(void)
1902{
1903 return &globvarht;
1904}
1905
1906/*
1907 * Returns the v: variable dictionary
1908 */
1909 dict_T *
1910get_vimvar_dict(void)
1911{
1912 return &vimvardict;
1913}
1914
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001915/*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001916 * Returns the index of a v:variable. Negative if not found.
1917 */
1918 int
1919find_vim_var(char_u *name)
1920{
1921 dictitem_T *di = find_var_in_ht(&vimvarht, 0, name, TRUE);
1922 struct vimvar *vv;
1923
1924 if (di == NULL)
1925 return -1;
1926 vv = (struct vimvar *)((char *)di - offsetof(vimvar_T, vv_di));
1927 return (int)(vv - vimvars);
1928}
1929
1930
1931/*
Bram Moolenaar34ed68d2019-08-29 22:48:24 +02001932 * Set type of v: variable to "type".
1933 */
1934 void
1935set_vim_var_type(int idx, vartype_T type)
1936{
1937 vimvars[idx].vv_type = type;
1938}
1939
1940/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001941 * Set number v: variable to "val".
Bram Moolenaar8d71b542019-08-30 15:46:30 +02001942 * Note that this does not set the type, use set_vim_var_type() for that.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001943 */
1944 void
1945set_vim_var_nr(int idx, varnumber_T val)
1946{
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001947 vimvars[idx].vv_nr = val;
1948}
1949
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001950 char *
1951get_vim_var_name(int idx)
1952{
1953 return vimvars[idx].vv_name;
1954}
1955
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001956/*
1957 * Get typval_T v: variable value.
1958 */
1959 typval_T *
1960get_vim_var_tv(int idx)
1961{
1962 return &vimvars[idx].vv_tv;
1963}
1964
1965/*
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01001966 * Set v: variable to "tv". Only accepts the same type.
1967 * Takes over the value of "tv".
1968 */
1969 int
1970set_vim_var_tv(int idx, typval_T *tv)
1971{
1972 if (vimvars[idx].vv_type != tv->v_type)
1973 {
1974 emsg(_("E1063: type mismatch for v: variable"));
1975 clear_tv(tv);
1976 return FAIL;
1977 }
1978 clear_tv(&vimvars[idx].vv_di.di_tv);
1979 vimvars[idx].vv_di.di_tv = *tv;
1980 return OK;
1981}
1982
1983/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001984 * Get number v: variable value.
1985 */
1986 varnumber_T
1987get_vim_var_nr(int idx)
1988{
1989 return vimvars[idx].vv_nr;
1990}
1991
1992/*
1993 * Get string v: variable value. Uses a static buffer, can only be used once.
1994 * If the String variable has never been set, return an empty string.
1995 * Never returns NULL;
1996 */
1997 char_u *
1998get_vim_var_str(int idx)
1999{
2000 return tv_get_string(&vimvars[idx].vv_tv);
2001}
2002
2003/*
2004 * Get List v: variable value. Caller must take care of reference count when
2005 * needed.
2006 */
2007 list_T *
2008get_vim_var_list(int idx)
2009{
2010 return vimvars[idx].vv_list;
2011}
2012
2013/*
2014 * Get Dict v: variable value. Caller must take care of reference count when
2015 * needed.
2016 */
2017 dict_T *
2018get_vim_var_dict(int idx)
2019{
2020 return vimvars[idx].vv_dict;
2021}
2022
2023/*
2024 * Set v:char to character "c".
2025 */
2026 void
2027set_vim_var_char(int c)
2028{
2029 char_u buf[MB_MAXBYTES + 1];
2030
2031 if (has_mbyte)
2032 buf[(*mb_char2bytes)(c, buf)] = NUL;
2033 else
2034 {
2035 buf[0] = c;
2036 buf[1] = NUL;
2037 }
2038 set_vim_var_string(VV_CHAR, buf, -1);
2039}
2040
2041/*
2042 * Set v:count to "count" and v:count1 to "count1".
2043 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
2044 */
2045 void
2046set_vcount(
2047 long count,
2048 long count1,
2049 int set_prevcount)
2050{
2051 if (set_prevcount)
2052 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
2053 vimvars[VV_COUNT].vv_nr = count;
2054 vimvars[VV_COUNT1].vv_nr = count1;
2055}
2056
2057/*
2058 * Save variables that might be changed as a side effect. Used when executing
2059 * a timer callback.
2060 */
2061 void
2062save_vimvars(vimvars_save_T *vvsave)
2063{
2064 vvsave->vv_prevcount = vimvars[VV_PREVCOUNT].vv_nr;
2065 vvsave->vv_count = vimvars[VV_COUNT].vv_nr;
2066 vvsave->vv_count1 = vimvars[VV_COUNT1].vv_nr;
2067}
2068
2069/*
2070 * Restore variables saved by save_vimvars().
2071 */
2072 void
2073restore_vimvars(vimvars_save_T *vvsave)
2074{
2075 vimvars[VV_PREVCOUNT].vv_nr = vvsave->vv_prevcount;
2076 vimvars[VV_COUNT].vv_nr = vvsave->vv_count;
2077 vimvars[VV_COUNT1].vv_nr = vvsave->vv_count1;
2078}
2079
2080/*
2081 * Set string v: variable to a copy of "val". If 'copy' is FALSE, then set the
2082 * value.
2083 */
2084 void
2085set_vim_var_string(
2086 int idx,
2087 char_u *val,
2088 int len) // length of "val" to use or -1 (whole string)
2089{
2090 clear_tv(&vimvars[idx].vv_di.di_tv);
2091 vimvars[idx].vv_type = VAR_STRING;
2092 if (val == NULL)
2093 vimvars[idx].vv_str = NULL;
2094 else if (len == -1)
2095 vimvars[idx].vv_str = vim_strsave(val);
2096 else
2097 vimvars[idx].vv_str = vim_strnsave(val, len);
2098}
2099
2100/*
2101 * Set List v: variable to "val".
2102 */
2103 void
2104set_vim_var_list(int idx, list_T *val)
2105{
2106 clear_tv(&vimvars[idx].vv_di.di_tv);
2107 vimvars[idx].vv_type = VAR_LIST;
2108 vimvars[idx].vv_list = val;
2109 if (val != NULL)
2110 ++val->lv_refcount;
2111}
2112
2113/*
2114 * Set Dictionary v: variable to "val".
2115 */
2116 void
2117set_vim_var_dict(int idx, dict_T *val)
2118{
2119 clear_tv(&vimvars[idx].vv_di.di_tv);
2120 vimvars[idx].vv_type = VAR_DICT;
2121 vimvars[idx].vv_dict = val;
2122 if (val != NULL)
2123 {
2124 ++val->dv_refcount;
2125 dict_set_items_ro(val);
2126 }
2127}
2128
2129/*
Bram Moolenaar69bf6342019-10-29 04:16:57 +01002130 * Set the v:argv list.
2131 */
2132 void
2133set_argv_var(char **argv, int argc)
2134{
2135 list_T *l = list_alloc();
2136 int i;
2137
2138 if (l == NULL)
2139 getout(1);
2140 l->lv_lock = VAR_FIXED;
2141 for (i = 0; i < argc; ++i)
2142 {
2143 if (list_append_string(l, (char_u *)argv[i], -1) == FAIL)
2144 getout(1);
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01002145 l->lv_u.mat.lv_last->li_tv.v_lock = VAR_FIXED;
Bram Moolenaar69bf6342019-10-29 04:16:57 +01002146 }
2147 set_vim_var_list(VV_ARGV, l);
2148}
2149
2150/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002151 * Set v:register if needed.
2152 */
2153 void
2154set_reg_var(int c)
2155{
2156 char_u regname;
2157
2158 if (c == 0 || c == ' ')
2159 regname = '"';
2160 else
2161 regname = c;
2162 // Avoid free/alloc when the value is already right.
2163 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
2164 set_vim_var_string(VV_REG, &regname, 1);
2165}
2166
2167/*
2168 * Get or set v:exception. If "oldval" == NULL, return the current value.
2169 * Otherwise, restore the value to "oldval" and return NULL.
2170 * Must always be called in pairs to save and restore v:exception! Does not
2171 * take care of memory allocations.
2172 */
2173 char_u *
2174v_exception(char_u *oldval)
2175{
2176 if (oldval == NULL)
2177 return vimvars[VV_EXCEPTION].vv_str;
2178
2179 vimvars[VV_EXCEPTION].vv_str = oldval;
2180 return NULL;
2181}
2182
2183/*
2184 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
2185 * Otherwise, restore the value to "oldval" and return NULL.
2186 * Must always be called in pairs to save and restore v:throwpoint! Does not
2187 * take care of memory allocations.
2188 */
2189 char_u *
2190v_throwpoint(char_u *oldval)
2191{
2192 if (oldval == NULL)
2193 return vimvars[VV_THROWPOINT].vv_str;
2194
2195 vimvars[VV_THROWPOINT].vv_str = oldval;
2196 return NULL;
2197}
2198
2199/*
2200 * Set v:cmdarg.
2201 * If "eap" != NULL, use "eap" to generate the value and return the old value.
2202 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
2203 * Must always be called in pairs!
2204 */
2205 char_u *
2206set_cmdarg(exarg_T *eap, char_u *oldarg)
2207{
2208 char_u *oldval;
2209 char_u *newval;
2210 unsigned len;
2211
2212 oldval = vimvars[VV_CMDARG].vv_str;
2213 if (eap == NULL)
2214 {
2215 vim_free(oldval);
2216 vimvars[VV_CMDARG].vv_str = oldarg;
2217 return NULL;
2218 }
2219
2220 if (eap->force_bin == FORCE_BIN)
2221 len = 6;
2222 else if (eap->force_bin == FORCE_NOBIN)
2223 len = 8;
2224 else
2225 len = 0;
2226
2227 if (eap->read_edit)
2228 len += 7;
2229
2230 if (eap->force_ff != 0)
2231 len += 10; // " ++ff=unix"
2232 if (eap->force_enc != 0)
2233 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
2234 if (eap->bad_char != 0)
2235 len += 7 + 4; // " ++bad=" + "keep" or "drop"
2236
2237 newval = alloc(len + 1);
2238 if (newval == NULL)
2239 return NULL;
2240
2241 if (eap->force_bin == FORCE_BIN)
2242 sprintf((char *)newval, " ++bin");
2243 else if (eap->force_bin == FORCE_NOBIN)
2244 sprintf((char *)newval, " ++nobin");
2245 else
2246 *newval = NUL;
2247
2248 if (eap->read_edit)
2249 STRCAT(newval, " ++edit");
2250
2251 if (eap->force_ff != 0)
2252 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
2253 eap->force_ff == 'u' ? "unix"
2254 : eap->force_ff == 'd' ? "dos"
2255 : "mac");
2256 if (eap->force_enc != 0)
2257 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
2258 eap->cmd + eap->force_enc);
2259 if (eap->bad_char == BAD_KEEP)
2260 STRCPY(newval + STRLEN(newval), " ++bad=keep");
2261 else if (eap->bad_char == BAD_DROP)
2262 STRCPY(newval + STRLEN(newval), " ++bad=drop");
2263 else if (eap->bad_char != 0)
2264 sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
2265 vimvars[VV_CMDARG].vv_str = newval;
2266 return oldval;
2267}
2268
2269/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002270 * Get the value of internal variable "name".
2271 * Return OK or FAIL. If OK is returned "rettv" must be cleared.
2272 */
2273 int
2274get_var_tv(
2275 char_u *name,
2276 int len, // length of "name"
2277 typval_T *rettv, // NULL when only checking existence
2278 dictitem_T **dip, // non-NULL when typval's dict item is needed
2279 int verbose, // may give error message
2280 int no_autoload) // do not use script autoloading
2281{
2282 int ret = OK;
2283 typval_T *tv = NULL;
2284 dictitem_T *v;
2285 int cc;
2286
2287 // truncate the name, so that we can use strcmp()
2288 cc = name[len];
2289 name[len] = NUL;
2290
2291 // Check for user-defined variables.
2292 v = find_var(name, NULL, no_autoload);
2293 if (v != NULL)
2294 {
2295 tv = &v->di_tv;
2296 if (dip != NULL)
2297 *dip = v;
2298 }
2299
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002300 if (tv == NULL && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2301 {
Bram Moolenaar4e12a5d2020-02-03 20:50:59 +01002302 imported_T *import = find_imported(name, 0, NULL);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002303
2304 // imported variable from another script
2305 if (import != NULL)
2306 {
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002307 scriptitem_T *si = SCRIPT_ITEM(import->imp_sid);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002308 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data)
2309 + import->imp_var_vals_idx;
2310 tv = sv->sv_tv;
2311 }
2312 }
2313
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002314 if (tv == NULL)
2315 {
2316 if (rettv != NULL && verbose)
2317 semsg(_(e_undefvar), name);
2318 ret = FAIL;
2319 }
2320 else if (rettv != NULL)
2321 copy_tv(tv, rettv);
2322
2323 name[len] = cc;
2324
2325 return ret;
2326}
2327
2328/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002329 * Check if variable "name[len]" is a local variable or an argument.
2330 * If so, "*eval_lavars_used" is set to TRUE.
2331 */
2332 void
2333check_vars(char_u *name, int len)
2334{
2335 int cc;
2336 char_u *varname;
2337 hashtab_T *ht;
2338
2339 if (eval_lavars_used == NULL)
2340 return;
2341
2342 // truncate the name, so that we can use strcmp()
2343 cc = name[len];
2344 name[len] = NUL;
2345
2346 ht = find_var_ht(name, &varname);
2347 if (ht == get_funccal_local_ht() || ht == get_funccal_args_ht())
2348 {
2349 if (find_var(name, NULL, TRUE) != NULL)
2350 *eval_lavars_used = TRUE;
2351 }
2352
2353 name[len] = cc;
2354}
2355
2356/*
2357 * Find variable "name" in the list of variables.
2358 * Return a pointer to it if found, NULL if not found.
2359 * Careful: "a:0" variables don't have a name.
2360 * When "htp" is not NULL we are writing to the variable, set "htp" to the
2361 * hashtab_T used.
2362 */
2363 dictitem_T *
2364find_var(char_u *name, hashtab_T **htp, int no_autoload)
2365{
2366 char_u *varname;
2367 hashtab_T *ht;
2368 dictitem_T *ret = NULL;
2369
2370 ht = find_var_ht(name, &varname);
2371 if (htp != NULL)
2372 *htp = ht;
2373 if (ht == NULL)
2374 return NULL;
2375 ret = find_var_in_ht(ht, *name, varname, no_autoload || htp != NULL);
2376 if (ret != NULL)
2377 return ret;
2378
Bram Moolenaar8d71b542019-08-30 15:46:30 +02002379 // Search in parent scope for lambda
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002380 return find_var_in_scoped_ht(name, no_autoload || htp != NULL);
2381}
2382
2383/*
2384 * Find variable "varname" in hashtab "ht" with name "htname".
2385 * Returns NULL if not found.
2386 */
2387 dictitem_T *
2388find_var_in_ht(
2389 hashtab_T *ht,
2390 int htname,
2391 char_u *varname,
2392 int no_autoload)
2393{
2394 hashitem_T *hi;
2395
2396 if (*varname == NUL)
2397 {
2398 // Must be something like "s:", otherwise "ht" would be NULL.
2399 switch (htname)
2400 {
2401 case 's': return &SCRIPT_SV(current_sctx.sc_sid)->sv_var;
2402 case 'g': return &globvars_var;
2403 case 'v': return &vimvars_var;
2404 case 'b': return &curbuf->b_bufvar;
2405 case 'w': return &curwin->w_winvar;
2406 case 't': return &curtab->tp_winvar;
2407 case 'l': return get_funccal_local_var();
2408 case 'a': return get_funccal_args_var();
2409 }
2410 return NULL;
2411 }
2412
2413 hi = hash_find(ht, varname);
2414 if (HASHITEM_EMPTY(hi))
2415 {
2416 // For global variables we may try auto-loading the script. If it
2417 // worked find the variable again. Don't auto-load a script if it was
2418 // loaded already, otherwise it would be loaded every time when
2419 // checking if a function name is a Funcref variable.
2420 if (ht == &globvarht && !no_autoload)
2421 {
2422 // Note: script_autoload() may make "hi" invalid. It must either
2423 // be obtained again or not used.
2424 if (!script_autoload(varname, FALSE) || aborting())
2425 return NULL;
2426 hi = hash_find(ht, varname);
2427 }
2428 if (HASHITEM_EMPTY(hi))
2429 return NULL;
2430 }
2431 return HI2DI(hi);
2432}
2433
2434/*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002435 * Get the script-local hashtab. NULL if not in a script context.
2436 */
2437 hashtab_T *
2438get_script_local_ht(void)
2439{
2440 scid_T sid = current_sctx.sc_sid;
2441
2442 if (sid > 0 && sid <= script_items.ga_len)
2443 return &SCRIPT_VARS(sid);
2444 return NULL;
2445}
2446
2447/*
2448 * Look for "name[len]" in script-local variables.
2449 * Return -1 when not found.
2450 */
2451 int
2452lookup_scriptvar(char_u *name, size_t len, cctx_T *dummy UNUSED)
2453{
2454 hashtab_T *ht = get_script_local_ht();
2455 char_u buffer[30];
2456 char_u *p;
2457 int res;
2458 hashitem_T *hi;
2459
2460 if (ht == NULL)
2461 return -1;
2462 if (len < sizeof(buffer) - 1)
2463 {
2464 vim_strncpy(buffer, name, len);
2465 p = buffer;
2466 }
2467 else
2468 {
2469 p = vim_strnsave(name, (int)len);
2470 if (p == NULL)
2471 return -1;
2472 }
2473
2474 hi = hash_find(ht, p);
2475 res = HASHITEM_EMPTY(hi) ? -1 : 1;
2476
2477 // if not script-local, then perhaps imported
Bram Moolenaar4e12a5d2020-02-03 20:50:59 +01002478 if (res == -1 && find_imported(p, 0, NULL) != NULL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002479 res = 1;
2480
2481 if (p != buffer)
2482 vim_free(p);
2483 return res;
2484}
2485
2486/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002487 * Find the hashtab used for a variable name.
2488 * Return NULL if the name is not valid.
2489 * Set "varname" to the start of name without ':'.
2490 */
2491 hashtab_T *
2492find_var_ht(char_u *name, char_u **varname)
2493{
2494 hashitem_T *hi;
2495 hashtab_T *ht;
2496
2497 if (name[0] == NUL)
2498 return NULL;
2499 if (name[1] != ':')
2500 {
2501 // The name must not start with a colon or #.
2502 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
2503 return NULL;
2504 *varname = name;
2505
2506 // "version" is "v:version" in all scopes if scriptversion < 3.
2507 // Same for a few other variables marked with VV_COMPAT.
2508 if (current_sctx.sc_version < 3)
2509 {
2510 hi = hash_find(&compat_hashtab, name);
2511 if (!HASHITEM_EMPTY(hi))
2512 return &compat_hashtab;
2513 }
2514
2515 ht = get_funccal_local_ht();
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002516 if (ht != NULL)
2517 return ht; // local variable
2518
2519 // in Vim9 script items at the script level are script-local
2520 if (current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2521 {
2522 ht = get_script_local_ht();
2523 if (ht != NULL)
2524 return ht;
2525 }
2526
2527 return &globvarht; // global variable
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002528 }
2529 *varname = name + 2;
2530 if (*name == 'g') // global variable
2531 return &globvarht;
2532 // There must be no ':' or '#' in the rest of the name, unless g: is used
2533 if (vim_strchr(name + 2, ':') != NULL
2534 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
2535 return NULL;
2536 if (*name == 'b') // buffer variable
2537 return &curbuf->b_vars->dv_hashtab;
2538 if (*name == 'w') // window variable
2539 return &curwin->w_vars->dv_hashtab;
2540 if (*name == 't') // tab page variable
2541 return &curtab->tp_vars->dv_hashtab;
2542 if (*name == 'v') // v: variable
2543 return &vimvarht;
Bram Moolenaarb35efa52020-02-26 20:15:18 +01002544 if (get_current_funccal() != NULL
2545 && get_current_funccal()->func->uf_dfunc_idx < 0)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002546 {
Bram Moolenaarb35efa52020-02-26 20:15:18 +01002547 // a: and l: are only used in functions defined with ":function"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002548 if (*name == 'a') // a: function argument
2549 return get_funccal_args_ht();
2550 if (*name == 'l') // l: local function variable
2551 return get_funccal_local_ht();
2552 }
2553 if (*name == 's') // script variable
2554 {
2555 ht = get_script_local_ht();
2556 if (ht != NULL)
2557 return ht;
2558 }
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002559 return NULL;
2560}
2561
2562/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002563 * Get the string value of a (global/local) variable.
2564 * Note: see tv_get_string() for how long the pointer remains valid.
2565 * Returns NULL when it doesn't exist.
2566 */
2567 char_u *
2568get_var_value(char_u *name)
2569{
2570 dictitem_T *v;
2571
2572 v = find_var(name, NULL, FALSE);
2573 if (v == NULL)
2574 return NULL;
2575 return tv_get_string(&v->di_tv);
2576}
2577
2578/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002579 * Allocate a new hashtab for a sourced script. It will be used while
2580 * sourcing this script and when executing functions defined in the script.
2581 */
2582 void
2583new_script_vars(scid_T id)
2584{
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002585 scriptvar_T *sv;
2586
Bram Moolenaar7ebcba62020-01-12 17:42:55 +01002587 sv = ALLOC_CLEAR_ONE(scriptvar_T);
2588 if (sv == NULL)
2589 return;
2590 init_var_dict(&sv->sv_dict, &sv->sv_var, VAR_SCOPE);
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002591 SCRIPT_ITEM(id)->sn_vars = sv;
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002592}
2593
2594/*
2595 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
2596 * point to it.
2597 */
2598 void
2599init_var_dict(dict_T *dict, dictitem_T *dict_var, int scope)
2600{
2601 hash_init(&dict->dv_hashtab);
2602 dict->dv_lock = 0;
2603 dict->dv_scope = scope;
2604 dict->dv_refcount = DO_NOT_FREE_CNT;
2605 dict->dv_copyID = 0;
2606 dict_var->di_tv.vval.v_dict = dict;
2607 dict_var->di_tv.v_type = VAR_DICT;
2608 dict_var->di_tv.v_lock = VAR_FIXED;
2609 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
2610 dict_var->di_key[0] = NUL;
2611}
2612
2613/*
2614 * Unreference a dictionary initialized by init_var_dict().
2615 */
2616 void
2617unref_var_dict(dict_T *dict)
2618{
Bram Moolenaar8d71b542019-08-30 15:46:30 +02002619 // Now the dict needs to be freed if no one else is using it, go back to
2620 // normal reference counting.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002621 dict->dv_refcount -= DO_NOT_FREE_CNT - 1;
2622 dict_unref(dict);
2623}
2624
2625/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002626 * Clean up a list of internal variables.
2627 * Frees all allocated variables and the value they contain.
2628 * Clears hashtab "ht", does not free it.
2629 */
2630 void
2631vars_clear(hashtab_T *ht)
2632{
2633 vars_clear_ext(ht, TRUE);
2634}
2635
2636/*
2637 * Like vars_clear(), but only free the value if "free_val" is TRUE.
2638 */
2639 void
2640vars_clear_ext(hashtab_T *ht, int free_val)
2641{
2642 int todo;
2643 hashitem_T *hi;
2644 dictitem_T *v;
2645
2646 hash_lock(ht);
2647 todo = (int)ht->ht_used;
2648 for (hi = ht->ht_array; todo > 0; ++hi)
2649 {
2650 if (!HASHITEM_EMPTY(hi))
2651 {
2652 --todo;
2653
2654 // Free the variable. Don't remove it from the hashtab,
2655 // ht_array might change then. hash_clear() takes care of it
2656 // later.
2657 v = HI2DI(hi);
2658 if (free_val)
2659 clear_tv(&v->di_tv);
2660 if (v->di_flags & DI_FLAGS_ALLOC)
2661 vim_free(v);
2662 }
2663 }
2664 hash_clear(ht);
2665 ht->ht_used = 0;
2666}
2667
2668/*
2669 * Delete a variable from hashtab "ht" at item "hi".
2670 * Clear the variable value and free the dictitem.
2671 */
Bram Moolenaarda6c0332019-09-01 16:01:30 +02002672 static void
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002673delete_var(hashtab_T *ht, hashitem_T *hi)
2674{
2675 dictitem_T *di = HI2DI(hi);
2676
2677 hash_remove(ht, hi);
2678 clear_tv(&di->di_tv);
2679 vim_free(di);
2680}
2681
2682/*
2683 * List the value of one internal variable.
2684 */
2685 static void
2686list_one_var(dictitem_T *v, char *prefix, int *first)
2687{
2688 char_u *tofree;
2689 char_u *s;
2690 char_u numbuf[NUMBUFLEN];
2691
2692 s = echo_string(&v->di_tv, &tofree, numbuf, get_copyID());
2693 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
2694 s == NULL ? (char_u *)"" : s, first);
2695 vim_free(tofree);
2696}
2697
2698 static void
2699list_one_var_a(
2700 char *prefix,
2701 char_u *name,
2702 int type,
2703 char_u *string,
2704 int *first) // when TRUE clear rest of screen and set to FALSE
2705{
2706 // don't use msg() or msg_attr() to avoid overwriting "v:statusmsg"
2707 msg_start();
2708 msg_puts(prefix);
2709 if (name != NULL) // "a:" vars don't have a name stored
2710 msg_puts((char *)name);
2711 msg_putchar(' ');
2712 msg_advance(22);
2713 if (type == VAR_NUMBER)
2714 msg_putchar('#');
2715 else if (type == VAR_FUNC || type == VAR_PARTIAL)
2716 msg_putchar('*');
2717 else if (type == VAR_LIST)
2718 {
2719 msg_putchar('[');
2720 if (*string == '[')
2721 ++string;
2722 }
2723 else if (type == VAR_DICT)
2724 {
2725 msg_putchar('{');
2726 if (*string == '{')
2727 ++string;
2728 }
2729 else
2730 msg_putchar(' ');
2731
2732 msg_outtrans(string);
2733
2734 if (type == VAR_FUNC || type == VAR_PARTIAL)
2735 msg_puts("()");
2736 if (*first)
2737 {
2738 msg_clr_eos();
2739 *first = FALSE;
2740 }
2741}
2742
2743/*
2744 * Set variable "name" to value in "tv".
2745 * If the variable already exists, the value is updated.
2746 * Otherwise the variable is created.
2747 */
2748 void
2749set_var(
2750 char_u *name,
2751 typval_T *tv,
2752 int copy) // make copy of value in "tv"
2753{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002754 set_var_const(name, NULL, tv, copy, 0);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002755}
2756
2757/*
2758 * Set variable "name" to value in "tv".
2759 * If the variable already exists and "is_const" is FALSE the value is updated.
2760 * Otherwise the variable is created.
2761 */
2762 void
2763set_var_const(
2764 char_u *name,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002765 type_T *type,
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002766 typval_T *tv,
2767 int copy, // make copy of value in "tv"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002768 int flags) // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002769{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002770 dictitem_T *di;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002771 char_u *varname;
2772 hashtab_T *ht;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002773 int is_script_local;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002774
2775 ht = find_var_ht(name, &varname);
2776 if (ht == NULL || *varname == NUL)
2777 {
2778 semsg(_(e_illvar), name);
2779 return;
2780 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002781 is_script_local = ht == get_script_local_ht();
2782
2783 di = find_var_in_ht(ht, 0, varname, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002784
2785 // Search in parent scope which is possible to reference from lambda
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002786 if (di == NULL)
2787 di = find_var_in_scoped_ht(name, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002788
2789 if ((tv->v_type == VAR_FUNC || tv->v_type == VAR_PARTIAL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002790 && var_check_func_name(name, di == NULL))
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002791 return;
2792
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002793 if (di != NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002794 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002795 if ((di->di_flags & DI_FLAGS_RELOAD) == 0)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002796 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002797 if (flags & LET_IS_CONST)
2798 {
2799 emsg(_(e_cannot_mod));
2800 return;
2801 }
2802
2803 if (var_check_ro(di->di_flags, name, FALSE)
2804 || var_check_lock(di->di_tv.v_lock, name, FALSE))
2805 return;
2806
2807 if ((flags & LET_NO_COMMAND) == 0
2808 && is_script_local
2809 && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2810 {
2811 semsg(_("E1041: Redefining script item %s"), name);
2812 return;
2813 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002814 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002815 else
2816 // can only redefine once
2817 di->di_flags &= ~DI_FLAGS_RELOAD;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002818
2819 // existing variable, need to clear the value
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002820
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002821 // Handle setting internal di: variables separately where needed to
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002822 // prevent changing the type.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002823 if (ht == &vimvarht)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002824 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002825 if (di->di_tv.v_type == VAR_STRING)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002826 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002827 VIM_CLEAR(di->di_tv.vval.v_string);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002828 if (copy || tv->v_type != VAR_STRING)
2829 {
2830 char_u *val = tv_get_string(tv);
2831
2832 // Careful: when assigning to v:errmsg and tv_get_string()
Bram Moolenaar4b96df52020-01-26 22:00:26 +01002833 // causes an error message the variable will already be set.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002834 if (di->di_tv.vval.v_string == NULL)
2835 di->di_tv.vval.v_string = vim_strsave(val);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002836 }
2837 else
2838 {
2839 // Take over the string to avoid an extra alloc/free.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002840 di->di_tv.vval.v_string = tv->vval.v_string;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002841 tv->vval.v_string = NULL;
2842 }
2843 return;
2844 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002845 else if (di->di_tv.v_type == VAR_NUMBER)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002846 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002847 di->di_tv.vval.v_number = tv_get_number(tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002848 if (STRCMP(varname, "searchforward") == 0)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002849 set_search_direction(di->di_tv.vval.v_number ? '/' : '?');
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002850#ifdef FEAT_SEARCH_EXTRA
2851 else if (STRCMP(varname, "hlsearch") == 0)
2852 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002853 no_hlsearch = !di->di_tv.vval.v_number;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002854 redraw_all_later(SOME_VALID);
2855 }
2856#endif
2857 return;
2858 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002859 else if (di->di_tv.v_type != tv->v_type)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002860 {
2861 semsg(_("E963: setting %s to value with wrong type"), name);
2862 return;
2863 }
2864 }
2865
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002866 clear_tv(&di->di_tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002867 }
2868 else // add a new variable
2869 {
2870 // Can't add "v:" or "a:" variable.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002871 if (ht == &vimvarht || ht == get_funccal_args_ht())
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002872 {
2873 semsg(_(e_illvar), name);
2874 return;
2875 }
2876
2877 // Make sure the variable name is valid.
2878 if (!valid_varname(varname))
2879 return;
2880
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002881 di = alloc(sizeof(dictitem_T) + STRLEN(varname));
2882 if (di == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002883 return;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002884 STRCPY(di->di_key, varname);
2885 if (hash_add(ht, DI2HIKEY(di)) == FAIL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002886 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002887 vim_free(di);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002888 return;
2889 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002890 di->di_flags = DI_FLAGS_ALLOC;
2891 if (flags & LET_IS_CONST)
2892 di->di_flags |= DI_FLAGS_LOCK;
2893
2894 if (is_script_local && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2895 {
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002896 scriptitem_T *si = SCRIPT_ITEM(current_sctx.sc_sid);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002897
2898 // Store a pointer to the typval_T, so that it can be found by
2899 // index instead of using a hastab lookup.
2900 if (ga_grow(&si->sn_var_vals, 1) == OK)
2901 {
2902 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data)
2903 + si->sn_var_vals.ga_len;
2904 sv->sv_name = di->di_key;
2905 sv->sv_tv = &di->di_tv;
2906 sv->sv_type = type == NULL ? &t_any : type;
2907 sv->sv_const = (flags & LET_IS_CONST);
2908 sv->sv_export = is_export;
2909 ++si->sn_var_vals.ga_len;
2910
2911 // let ex_export() know the export worked.
2912 is_export = FALSE;
2913 }
2914 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002915 }
2916
2917 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002918 copy_tv(tv, &di->di_tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002919 else
2920 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002921 di->di_tv = *tv;
2922 di->di_tv.v_lock = 0;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002923 init_tv(tv);
2924 }
2925
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002926 if (flags & LET_IS_CONST)
2927 di->di_tv.v_lock |= VAR_LOCKED;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002928}
2929
2930/*
2931 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
2932 * Also give an error message.
2933 */
2934 int
2935var_check_ro(int flags, char_u *name, int use_gettext)
2936{
2937 if (flags & DI_FLAGS_RO)
2938 {
2939 semsg(_(e_readonlyvar), use_gettext ? (char_u *)_(name) : name);
2940 return TRUE;
2941 }
2942 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
2943 {
2944 semsg(_(e_readonlysbx), use_gettext ? (char_u *)_(name) : name);
2945 return TRUE;
2946 }
2947 return FALSE;
2948}
2949
2950/*
2951 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
2952 * Also give an error message.
2953 */
2954 int
2955var_check_fixed(int flags, char_u *name, int use_gettext)
2956{
2957 if (flags & DI_FLAGS_FIX)
2958 {
2959 semsg(_("E795: Cannot delete variable %s"),
2960 use_gettext ? (char_u *)_(name) : name);
2961 return TRUE;
2962 }
2963 return FALSE;
2964}
2965
2966/*
2967 * Check if a funcref is assigned to a valid variable name.
2968 * Return TRUE and give an error if not.
2969 */
2970 int
2971var_check_func_name(
2972 char_u *name, // points to start of variable name
2973 int new_var) // TRUE when creating the variable
2974{
2975 // Allow for w: b: s: and t:.
2976 if (!(vim_strchr((char_u *)"wbst", name[0]) != NULL && name[1] == ':')
2977 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
2978 ? name[2] : name[0]))
2979 {
2980 semsg(_("E704: Funcref variable name must start with a capital: %s"),
2981 name);
2982 return TRUE;
2983 }
2984 // Don't allow hiding a function. When "v" is not NULL we might be
2985 // assigning another function to the same var, the type is checked
2986 // below.
2987 if (new_var && function_exists(name, FALSE))
2988 {
2989 semsg(_("E705: Variable name conflicts with existing function: %s"),
2990 name);
2991 return TRUE;
2992 }
2993 return FALSE;
2994}
2995
2996/*
2997 * Return TRUE if "flags" indicates variable "name" is locked (immutable).
2998 * Also give an error message, using "name" or _("name") when use_gettext is
2999 * TRUE.
3000 */
3001 int
3002var_check_lock(int lock, char_u *name, int use_gettext)
3003{
3004 if (lock & VAR_LOCKED)
3005 {
3006 semsg(_("E741: Value is locked: %s"),
3007 name == NULL ? (char_u *)_("Unknown")
3008 : use_gettext ? (char_u *)_(name)
3009 : name);
3010 return TRUE;
3011 }
3012 if (lock & VAR_FIXED)
3013 {
3014 semsg(_("E742: Cannot change value of %s"),
3015 name == NULL ? (char_u *)_("Unknown")
3016 : use_gettext ? (char_u *)_(name)
3017 : name);
3018 return TRUE;
3019 }
3020 return FALSE;
3021}
3022
3023/*
3024 * Check if a variable name is valid.
3025 * Return FALSE and give an error if not.
3026 */
3027 int
3028valid_varname(char_u *varname)
3029{
3030 char_u *p;
3031
3032 for (p = varname; *p != NUL; ++p)
3033 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
3034 && *p != AUTOLOAD_CHAR)
3035 {
3036 semsg(_(e_illvar), varname);
3037 return FALSE;
3038 }
3039 return TRUE;
3040}
3041
3042/*
3043 * getwinvar() and gettabwinvar()
3044 */
3045 static void
3046getwinvar(
3047 typval_T *argvars,
3048 typval_T *rettv,
3049 int off) // 1 for gettabwinvar()
3050{
3051 win_T *win;
3052 char_u *varname;
3053 dictitem_T *v;
3054 tabpage_T *tp = NULL;
3055 int done = FALSE;
3056 win_T *oldcurwin;
3057 tabpage_T *oldtabpage;
3058 int need_switch_win;
3059
3060 if (off == 1)
3061 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3062 else
3063 tp = curtab;
3064 win = find_win_by_nr(&argvars[off], tp);
3065 varname = tv_get_string_chk(&argvars[off + 1]);
3066 ++emsg_off;
3067
3068 rettv->v_type = VAR_STRING;
3069 rettv->vval.v_string = NULL;
3070
3071 if (win != NULL && varname != NULL)
3072 {
3073 // Set curwin to be our win, temporarily. Also set the tabpage,
3074 // otherwise the window is not valid. Only do this when needed,
3075 // autocommands get blocked.
3076 need_switch_win = !(tp == curtab && win == curwin);
3077 if (!need_switch_win
3078 || switch_win(&oldcurwin, &oldtabpage, win, tp, TRUE) == OK)
3079 {
3080 if (*varname == '&')
3081 {
3082 if (varname[1] == NUL)
3083 {
3084 // get all window-local options in a dict
3085 dict_T *opts = get_winbuf_options(FALSE);
3086
3087 if (opts != NULL)
3088 {
3089 rettv_dict_set(rettv, opts);
3090 done = TRUE;
3091 }
3092 }
3093 else if (get_option_tv(&varname, rettv, 1) == OK)
3094 // window-local-option
3095 done = TRUE;
3096 }
3097 else
3098 {
3099 // Look up the variable.
3100 // Let getwinvar({nr}, "") return the "w:" dictionary.
3101 v = find_var_in_ht(&win->w_vars->dv_hashtab, 'w',
3102 varname, FALSE);
3103 if (v != NULL)
3104 {
3105 copy_tv(&v->di_tv, rettv);
3106 done = TRUE;
3107 }
3108 }
3109 }
3110
3111 if (need_switch_win)
3112 // restore previous notion of curwin
3113 restore_win(oldcurwin, oldtabpage, TRUE);
3114 }
3115
3116 if (!done && argvars[off + 2].v_type != VAR_UNKNOWN)
3117 // use the default return value
3118 copy_tv(&argvars[off + 2], rettv);
3119
3120 --emsg_off;
3121}
3122
3123/*
3124 * "setwinvar()" and "settabwinvar()" functions
3125 */
3126 static void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003127setwinvar(typval_T *argvars, int off)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003128{
3129 win_T *win;
3130 win_T *save_curwin;
3131 tabpage_T *save_curtab;
3132 int need_switch_win;
3133 char_u *varname, *winvarname;
3134 typval_T *varp;
3135 char_u nbuf[NUMBUFLEN];
3136 tabpage_T *tp = NULL;
3137
3138 if (check_secure())
3139 return;
3140
3141 if (off == 1)
3142 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3143 else
3144 tp = curtab;
3145 win = find_win_by_nr(&argvars[off], tp);
3146 varname = tv_get_string_chk(&argvars[off + 1]);
3147 varp = &argvars[off + 2];
3148
3149 if (win != NULL && varname != NULL && varp != NULL)
3150 {
3151 need_switch_win = !(tp == curtab && win == curwin);
3152 if (!need_switch_win
3153 || switch_win(&save_curwin, &save_curtab, win, tp, TRUE) == OK)
3154 {
3155 if (*varname == '&')
3156 {
3157 long numval;
3158 char_u *strval;
3159 int error = FALSE;
3160
3161 ++varname;
3162 numval = (long)tv_get_number_chk(varp, &error);
3163 strval = tv_get_string_buf_chk(varp, nbuf);
3164 if (!error && strval != NULL)
3165 set_option_value(varname, numval, strval, OPT_LOCAL);
3166 }
3167 else
3168 {
3169 winvarname = alloc(STRLEN(varname) + 3);
3170 if (winvarname != NULL)
3171 {
3172 STRCPY(winvarname, "w:");
3173 STRCPY(winvarname + 2, varname);
3174 set_var(winvarname, varp, TRUE);
3175 vim_free(winvarname);
3176 }
3177 }
3178 }
3179 if (need_switch_win)
3180 restore_win(save_curwin, save_curtab, TRUE);
3181 }
3182}
3183
Bram Moolenaare5cdf152019-08-29 22:09:46 +02003184/*
3185 * reset v:option_new, v:option_old, v:option_oldlocal, v:option_oldglobal,
3186 * v:option_type, and v:option_command.
3187 */
3188 void
3189reset_v_option_vars(void)
3190{
3191 set_vim_var_string(VV_OPTION_NEW, NULL, -1);
3192 set_vim_var_string(VV_OPTION_OLD, NULL, -1);
3193 set_vim_var_string(VV_OPTION_OLDLOCAL, NULL, -1);
3194 set_vim_var_string(VV_OPTION_OLDGLOBAL, NULL, -1);
3195 set_vim_var_string(VV_OPTION_TYPE, NULL, -1);
3196 set_vim_var_string(VV_OPTION_COMMAND, NULL, -1);
3197}
3198
3199/*
3200 * Add an assert error to v:errors.
3201 */
3202 void
3203assert_error(garray_T *gap)
3204{
3205 struct vimvar *vp = &vimvars[VV_ERRORS];
3206
3207 if (vp->vv_type != VAR_LIST || vimvars[VV_ERRORS].vv_list == NULL)
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003208 // Make sure v:errors is a list.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02003209 set_vim_var_list(VV_ERRORS, list_alloc());
3210 list_append_string(vimvars[VV_ERRORS].vv_list, gap->ga_data, gap->ga_len);
3211}
3212
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003213 int
3214var_exists(char_u *var)
3215{
3216 char_u *name;
3217 char_u *tofree;
3218 typval_T tv;
3219 int len = 0;
3220 int n = FALSE;
3221
3222 // get_name_len() takes care of expanding curly braces
3223 name = var;
3224 len = get_name_len(&var, &tofree, TRUE, FALSE);
3225 if (len > 0)
3226 {
3227 if (tofree != NULL)
3228 name = tofree;
3229 n = (get_var_tv(name, len, &tv, NULL, FALSE, TRUE) == OK);
3230 if (n)
3231 {
3232 // handle d.key, l[idx], f(expr)
3233 n = (handle_subscript(&var, &tv, TRUE, FALSE, name, &name) == OK);
3234 if (n)
3235 clear_tv(&tv);
3236 }
3237 }
3238 if (*var != NUL)
3239 n = FALSE;
3240
3241 vim_free(tofree);
3242 return n;
3243}
3244
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003245static lval_T *redir_lval = NULL;
3246#define EVALCMD_BUSY (redir_lval == (lval_T *)&redir_lval)
3247static garray_T redir_ga; // only valid when redir_lval is not NULL
3248static char_u *redir_endp = NULL;
3249static char_u *redir_varname = NULL;
3250
3251/*
3252 * Start recording command output to a variable
3253 * When "append" is TRUE append to an existing variable.
3254 * Returns OK if successfully completed the setup. FAIL otherwise.
3255 */
3256 int
3257var_redir_start(char_u *name, int append)
3258{
3259 int save_emsg;
3260 int err;
3261 typval_T tv;
3262
3263 // Catch a bad name early.
3264 if (!eval_isnamec1(*name))
3265 {
3266 emsg(_(e_invarg));
3267 return FAIL;
3268 }
3269
3270 // Make a copy of the name, it is used in redir_lval until redir ends.
3271 redir_varname = vim_strsave(name);
3272 if (redir_varname == NULL)
3273 return FAIL;
3274
3275 redir_lval = ALLOC_CLEAR_ONE(lval_T);
3276 if (redir_lval == NULL)
3277 {
3278 var_redir_stop();
3279 return FAIL;
3280 }
3281
3282 // The output is stored in growarray "redir_ga" until redirection ends.
3283 ga_init2(&redir_ga, (int)sizeof(char), 500);
3284
3285 // Parse the variable name (can be a dict or list entry).
3286 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, 0,
3287 FNE_CHECK_START);
3288 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
3289 {
3290 clear_lval(redir_lval);
3291 if (redir_endp != NULL && *redir_endp != NUL)
3292 // Trailing characters are present after the variable name
3293 emsg(_(e_trailing));
3294 else
3295 emsg(_(e_invarg));
3296 redir_endp = NULL; // don't store a value, only cleanup
3297 var_redir_stop();
3298 return FAIL;
3299 }
3300
3301 // check if we can write to the variable: set it to or append an empty
3302 // string
3303 save_emsg = did_emsg;
3304 did_emsg = FALSE;
3305 tv.v_type = VAR_STRING;
3306 tv.vval.v_string = (char_u *)"";
3307 if (append)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003308 set_var_lval(redir_lval, redir_endp, &tv, TRUE, 0, (char_u *)".");
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003309 else
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003310 set_var_lval(redir_lval, redir_endp, &tv, TRUE, 0, (char_u *)"=");
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003311 clear_lval(redir_lval);
3312 err = did_emsg;
3313 did_emsg |= save_emsg;
3314 if (err)
3315 {
3316 redir_endp = NULL; // don't store a value, only cleanup
3317 var_redir_stop();
3318 return FAIL;
3319 }
3320
3321 return OK;
3322}
3323
3324/*
3325 * Append "value[value_len]" to the variable set by var_redir_start().
3326 * The actual appending is postponed until redirection ends, because the value
3327 * appended may in fact be the string we write to, changing it may cause freed
3328 * memory to be used:
3329 * :redir => foo
3330 * :let foo
3331 * :redir END
3332 */
3333 void
3334var_redir_str(char_u *value, int value_len)
3335{
3336 int len;
3337
3338 if (redir_lval == NULL)
3339 return;
3340
3341 if (value_len == -1)
3342 len = (int)STRLEN(value); // Append the entire string
3343 else
3344 len = value_len; // Append only "value_len" characters
3345
3346 if (ga_grow(&redir_ga, len) == OK)
3347 {
3348 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
3349 redir_ga.ga_len += len;
3350 }
3351 else
3352 var_redir_stop();
3353}
3354
3355/*
3356 * Stop redirecting command output to a variable.
3357 * Frees the allocated memory.
3358 */
3359 void
3360var_redir_stop(void)
3361{
3362 typval_T tv;
3363
3364 if (EVALCMD_BUSY)
3365 {
3366 redir_lval = NULL;
3367 return;
3368 }
3369
3370 if (redir_lval != NULL)
3371 {
3372 // If there was no error: assign the text to the variable.
3373 if (redir_endp != NULL)
3374 {
3375 ga_append(&redir_ga, NUL); // Append the trailing NUL.
3376 tv.v_type = VAR_STRING;
3377 tv.vval.v_string = redir_ga.ga_data;
3378 // Call get_lval() again, if it's inside a Dict or List it may
3379 // have changed.
3380 redir_endp = get_lval(redir_varname, NULL, redir_lval,
3381 FALSE, FALSE, 0, FNE_CHECK_START);
3382 if (redir_endp != NULL && redir_lval->ll_name != NULL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003383 set_var_lval(redir_lval, redir_endp, &tv, FALSE, 0,
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003384 (char_u *)".");
3385 clear_lval(redir_lval);
3386 }
3387
3388 // free the collected output
3389 VIM_CLEAR(redir_ga.ga_data);
3390
3391 VIM_CLEAR(redir_lval);
3392 }
3393 VIM_CLEAR(redir_varname);
3394}
3395
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003396/*
3397 * "gettabvar()" function
3398 */
3399 void
3400f_gettabvar(typval_T *argvars, typval_T *rettv)
3401{
3402 win_T *oldcurwin;
3403 tabpage_T *tp, *oldtabpage;
3404 dictitem_T *v;
3405 char_u *varname;
3406 int done = FALSE;
3407
3408 rettv->v_type = VAR_STRING;
3409 rettv->vval.v_string = NULL;
3410
3411 varname = tv_get_string_chk(&argvars[1]);
3412 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3413 if (tp != NULL && varname != NULL)
3414 {
3415 // Set tp to be our tabpage, temporarily. Also set the window to the
3416 // first window in the tabpage, otherwise the window is not valid.
3417 if (switch_win(&oldcurwin, &oldtabpage,
3418 tp == curtab || tp->tp_firstwin == NULL ? firstwin
3419 : tp->tp_firstwin, tp, TRUE) == OK)
3420 {
3421 // look up the variable
3422 // Let gettabvar({nr}, "") return the "t:" dictionary.
3423 v = find_var_in_ht(&tp->tp_vars->dv_hashtab, 't', varname, FALSE);
3424 if (v != NULL)
3425 {
3426 copy_tv(&v->di_tv, rettv);
3427 done = TRUE;
3428 }
3429 }
3430
3431 // restore previous notion of curwin
3432 restore_win(oldcurwin, oldtabpage, TRUE);
3433 }
3434
3435 if (!done && argvars[2].v_type != VAR_UNKNOWN)
3436 copy_tv(&argvars[2], rettv);
3437}
3438
3439/*
3440 * "gettabwinvar()" function
3441 */
3442 void
3443f_gettabwinvar(typval_T *argvars, typval_T *rettv)
3444{
3445 getwinvar(argvars, rettv, 1);
3446}
3447
3448/*
3449 * "getwinvar()" function
3450 */
3451 void
3452f_getwinvar(typval_T *argvars, typval_T *rettv)
3453{
3454 getwinvar(argvars, rettv, 0);
3455}
3456
3457/*
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003458 * "getbufvar()" function
3459 */
3460 void
3461f_getbufvar(typval_T *argvars, typval_T *rettv)
3462{
3463 buf_T *buf;
3464 buf_T *save_curbuf;
3465 char_u *varname;
3466 dictitem_T *v;
3467 int done = FALSE;
3468
3469 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
3470 varname = tv_get_string_chk(&argvars[1]);
3471 ++emsg_off;
3472 buf = tv_get_buf(&argvars[0], FALSE);
3473
3474 rettv->v_type = VAR_STRING;
3475 rettv->vval.v_string = NULL;
3476
3477 if (buf != NULL && varname != NULL)
3478 {
3479 // set curbuf to be our buf, temporarily
3480 save_curbuf = curbuf;
3481 curbuf = buf;
3482
3483 if (*varname == '&')
3484 {
3485 if (varname[1] == NUL)
3486 {
3487 // get all buffer-local options in a dict
3488 dict_T *opts = get_winbuf_options(TRUE);
3489
3490 if (opts != NULL)
3491 {
3492 rettv_dict_set(rettv, opts);
3493 done = TRUE;
3494 }
3495 }
3496 else if (get_option_tv(&varname, rettv, TRUE) == OK)
3497 // buffer-local-option
3498 done = TRUE;
3499 }
3500 else
3501 {
3502 // Look up the variable.
3503 // Let getbufvar({nr}, "") return the "b:" dictionary.
3504 v = find_var_in_ht(&curbuf->b_vars->dv_hashtab,
3505 'b', varname, FALSE);
3506 if (v != NULL)
3507 {
3508 copy_tv(&v->di_tv, rettv);
3509 done = TRUE;
3510 }
3511 }
3512
3513 // restore previous notion of curbuf
3514 curbuf = save_curbuf;
3515 }
3516
3517 if (!done && argvars[2].v_type != VAR_UNKNOWN)
3518 // use the default value
3519 copy_tv(&argvars[2], rettv);
3520
3521 --emsg_off;
3522}
3523
3524/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003525 * "settabvar()" function
3526 */
3527 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003528f_settabvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003529{
3530 tabpage_T *save_curtab;
3531 tabpage_T *tp;
3532 char_u *varname, *tabvarname;
3533 typval_T *varp;
3534
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003535 if (check_secure())
3536 return;
3537
3538 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3539 varname = tv_get_string_chk(&argvars[1]);
3540 varp = &argvars[2];
3541
3542 if (varname != NULL && varp != NULL && tp != NULL)
3543 {
3544 save_curtab = curtab;
3545 goto_tabpage_tp(tp, FALSE, FALSE);
3546
3547 tabvarname = alloc(STRLEN(varname) + 3);
3548 if (tabvarname != NULL)
3549 {
3550 STRCPY(tabvarname, "t:");
3551 STRCPY(tabvarname + 2, varname);
3552 set_var(tabvarname, varp, TRUE);
3553 vim_free(tabvarname);
3554 }
3555
3556 // Restore current tabpage
3557 if (valid_tabpage(save_curtab))
3558 goto_tabpage_tp(save_curtab, FALSE, FALSE);
3559 }
3560}
3561
3562/*
3563 * "settabwinvar()" function
3564 */
3565 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003566f_settabwinvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003567{
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003568 setwinvar(argvars, 1);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003569}
3570
3571/*
3572 * "setwinvar()" function
3573 */
3574 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003575f_setwinvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003576{
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003577 setwinvar(argvars, 0);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003578}
3579
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003580/*
3581 * "setbufvar()" function
3582 */
3583 void
3584f_setbufvar(typval_T *argvars, typval_T *rettv UNUSED)
3585{
3586 buf_T *buf;
3587 char_u *varname, *bufvarname;
3588 typval_T *varp;
3589 char_u nbuf[NUMBUFLEN];
3590
3591 if (check_secure())
3592 return;
3593 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
3594 varname = tv_get_string_chk(&argvars[1]);
3595 buf = tv_get_buf(&argvars[0], FALSE);
3596 varp = &argvars[2];
3597
3598 if (buf != NULL && varname != NULL && varp != NULL)
3599 {
3600 if (*varname == '&')
3601 {
3602 long numval;
3603 char_u *strval;
3604 int error = FALSE;
3605 aco_save_T aco;
3606
3607 // set curbuf to be our buf, temporarily
3608 aucmd_prepbuf(&aco, buf);
3609
3610 ++varname;
3611 numval = (long)tv_get_number_chk(varp, &error);
3612 strval = tv_get_string_buf_chk(varp, nbuf);
3613 if (!error && strval != NULL)
3614 set_option_value(varname, numval, strval, OPT_LOCAL);
3615
3616 // reset notion of buffer
3617 aucmd_restbuf(&aco);
3618 }
3619 else
3620 {
3621 buf_T *save_curbuf = curbuf;
3622
3623 bufvarname = alloc(STRLEN(varname) + 3);
3624 if (bufvarname != NULL)
3625 {
3626 curbuf = buf;
3627 STRCPY(bufvarname, "b:");
3628 STRCPY(bufvarname + 2, varname);
3629 set_var(bufvarname, varp, TRUE);
3630 vim_free(bufvarname);
3631 curbuf = save_curbuf;
3632 }
3633 }
3634 }
3635}
3636
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003637/*
3638 * Get a callback from "arg". It can be a Funcref or a function name.
3639 * When "arg" is zero return an empty string.
3640 * "cb_name" is not allocated.
3641 * "cb_name" is set to NULL for an invalid argument.
3642 */
3643 callback_T
3644get_callback(typval_T *arg)
3645{
Bram Moolenaar14e579092020-03-07 16:59:25 +01003646 callback_T res;
3647 int r = OK;
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003648
3649 res.cb_free_name = FALSE;
3650 if (arg->v_type == VAR_PARTIAL && arg->vval.v_partial != NULL)
3651 {
3652 res.cb_partial = arg->vval.v_partial;
3653 ++res.cb_partial->pt_refcount;
3654 res.cb_name = partial_name(res.cb_partial);
3655 }
3656 else
3657 {
3658 res.cb_partial = NULL;
Bram Moolenaar14e579092020-03-07 16:59:25 +01003659 if (arg->v_type == VAR_STRING && arg->vval.v_string != NULL
3660 && isdigit(*arg->vval.v_string))
3661 r = FAIL;
3662 else if (arg->v_type == VAR_FUNC || arg->v_type == VAR_STRING)
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003663 {
3664 // Note that we don't make a copy of the string.
3665 res.cb_name = arg->vval.v_string;
3666 func_ref(res.cb_name);
3667 }
3668 else if (arg->v_type == VAR_NUMBER && arg->vval.v_number == 0)
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003669 res.cb_name = (char_u *)"";
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003670 else
Bram Moolenaar14e579092020-03-07 16:59:25 +01003671 r = FAIL;
3672
3673 if (r == FAIL)
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003674 {
3675 emsg(_("E921: Invalid callback argument"));
3676 res.cb_name = NULL;
3677 }
3678 }
3679 return res;
3680}
3681
3682/*
3683 * Copy a callback into a typval_T.
3684 */
3685 void
3686put_callback(callback_T *cb, typval_T *tv)
3687{
3688 if (cb->cb_partial != NULL)
3689 {
3690 tv->v_type = VAR_PARTIAL;
3691 tv->vval.v_partial = cb->cb_partial;
3692 ++tv->vval.v_partial->pt_refcount;
3693 }
3694 else
3695 {
3696 tv->v_type = VAR_FUNC;
3697 tv->vval.v_string = vim_strsave(cb->cb_name);
3698 func_ref(cb->cb_name);
3699 }
3700}
3701
3702/*
3703 * Make a copy of "src" into "dest", allocating the function name if needed,
3704 * without incrementing the refcount.
3705 */
3706 void
3707set_callback(callback_T *dest, callback_T *src)
3708{
3709 if (src->cb_partial == NULL)
3710 {
3711 // just a function name, make a copy
3712 dest->cb_name = vim_strsave(src->cb_name);
3713 dest->cb_free_name = TRUE;
3714 }
3715 else
3716 {
3717 // cb_name is a pointer into cb_partial
3718 dest->cb_name = src->cb_name;
3719 dest->cb_free_name = FALSE;
3720 }
3721 dest->cb_partial = src->cb_partial;
3722}
3723
3724/*
3725 * Unref/free "callback" returned by get_callback() or set_callback().
3726 */
3727 void
3728free_callback(callback_T *callback)
3729{
3730 if (callback->cb_partial != NULL)
3731 {
3732 partial_unref(callback->cb_partial);
3733 callback->cb_partial = NULL;
3734 }
3735 else if (callback->cb_name != NULL)
3736 func_unref(callback->cb_name);
3737 if (callback->cb_free_name)
3738 {
3739 vim_free(callback->cb_name);
3740 callback->cb_free_name = FALSE;
3741 }
3742 callback->cb_name = NULL;
3743}
3744
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003745#endif // FEAT_EVAL