blob: c4bc957fcd384b5896292ac2c5f41d8e356e0fb3 [file] [log] [blame]
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * evalvars.c: functions for dealing with variables
12 */
13
14#include "vim.h"
15
16#if defined(FEAT_EVAL) || defined(PROTO)
17
Bram Moolenaare5cdf152019-08-29 22:09:46 +020018static dictitem_T globvars_var; // variable used for g:
Bram Moolenaarda6c0332019-09-01 16:01:30 +020019static dict_T globvardict; // Dictionary with g: variables
20#define globvarht globvardict.dv_hashtab
Bram Moolenaare5cdf152019-08-29 22:09:46 +020021
22/*
23 * Old Vim variables such as "v:version" are also available without the "v:".
24 * Also in functions. We need a special hashtable for them.
25 */
26static hashtab_T compat_hashtab;
27
28/*
29 * Array to hold the value of v: variables.
30 * The value is in a dictitem, so that it can also be used in the v: scope.
31 * The reason to use this table anyway is for very quick access to the
32 * variables with the VV_ defines.
33 */
34
35// values for vv_flags:
36#define VV_COMPAT 1 // compatible, also used without "v:"
37#define VV_RO 2 // read-only
38#define VV_RO_SBX 4 // read-only in the sandbox
39
40#define VV_NAME(s, t) s, {{t, 0, {0}}, 0, {0}}
41
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010042typedef struct vimvar vimvar_T;
43
Bram Moolenaare5cdf152019-08-29 22:09:46 +020044static struct vimvar
45{
46 char *vv_name; // name of variable, without v:
47 dictitem16_T vv_di; // value and name for key (max 16 chars!)
48 char vv_flags; // VV_COMPAT, VV_RO, VV_RO_SBX
49} vimvars[VV_LEN] =
50{
Bram Moolenaar8d71b542019-08-30 15:46:30 +020051 // The order here must match the VV_ defines in vim.h!
52 // Initializing a union does not work, leave tv.vval empty to get zero's.
Bram Moolenaare5cdf152019-08-29 22:09:46 +020053 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
54 {VV_NAME("count1", VAR_NUMBER), VV_RO},
55 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
56 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
57 {VV_NAME("warningmsg", VAR_STRING), 0},
58 {VV_NAME("statusmsg", VAR_STRING), 0},
59 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
60 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
61 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
62 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
63 {VV_NAME("termresponse", VAR_STRING), VV_RO},
64 {VV_NAME("fname", VAR_STRING), VV_RO},
65 {VV_NAME("lang", VAR_STRING), VV_RO},
66 {VV_NAME("lc_time", VAR_STRING), VV_RO},
67 {VV_NAME("ctype", VAR_STRING), VV_RO},
68 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
69 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
70 {VV_NAME("fname_in", VAR_STRING), VV_RO},
71 {VV_NAME("fname_out", VAR_STRING), VV_RO},
72 {VV_NAME("fname_new", VAR_STRING), VV_RO},
73 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
74 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
75 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
76 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
77 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
78 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
79 {VV_NAME("progname", VAR_STRING), VV_RO},
80 {VV_NAME("servername", VAR_STRING), VV_RO},
81 {VV_NAME("dying", VAR_NUMBER), VV_RO},
82 {VV_NAME("exception", VAR_STRING), VV_RO},
83 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
84 {VV_NAME("register", VAR_STRING), VV_RO},
85 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
86 {VV_NAME("insertmode", VAR_STRING), VV_RO},
87 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
88 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
89 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
90 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
91 {VV_NAME("fcs_choice", VAR_STRING), 0},
92 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
93 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
94 {VV_NAME("beval_winid", VAR_NUMBER), VV_RO},
95 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
96 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
97 {VV_NAME("beval_text", VAR_STRING), VV_RO},
98 {VV_NAME("scrollstart", VAR_STRING), 0},
99 {VV_NAME("swapname", VAR_STRING), VV_RO},
100 {VV_NAME("swapchoice", VAR_STRING), 0},
101 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
102 {VV_NAME("char", VAR_STRING), 0},
103 {VV_NAME("mouse_win", VAR_NUMBER), 0},
104 {VV_NAME("mouse_winid", VAR_NUMBER), 0},
105 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
106 {VV_NAME("mouse_col", VAR_NUMBER), 0},
107 {VV_NAME("operator", VAR_STRING), VV_RO},
108 {VV_NAME("searchforward", VAR_NUMBER), 0},
109 {VV_NAME("hlsearch", VAR_NUMBER), 0},
110 {VV_NAME("oldfiles", VAR_LIST), 0},
111 {VV_NAME("windowid", VAR_NUMBER), VV_RO},
112 {VV_NAME("progpath", VAR_STRING), VV_RO},
113 {VV_NAME("completed_item", VAR_DICT), VV_RO},
114 {VV_NAME("option_new", VAR_STRING), VV_RO},
115 {VV_NAME("option_old", VAR_STRING), VV_RO},
116 {VV_NAME("option_oldlocal", VAR_STRING), VV_RO},
117 {VV_NAME("option_oldglobal", VAR_STRING), VV_RO},
118 {VV_NAME("option_command", VAR_STRING), VV_RO},
119 {VV_NAME("option_type", VAR_STRING), VV_RO},
120 {VV_NAME("errors", VAR_LIST), 0},
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +0100121 {VV_NAME("false", VAR_BOOL), VV_RO},
122 {VV_NAME("true", VAR_BOOL), VV_RO},
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200123 {VV_NAME("none", VAR_SPECIAL), VV_RO},
Bram Moolenaarf9706e92020-02-22 14:27:04 +0100124 {VV_NAME("null", VAR_SPECIAL), VV_RO},
125 {VV_NAME("numbersize", VAR_NUMBER), VV_RO},
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200126 {VV_NAME("vim_did_enter", VAR_NUMBER), VV_RO},
127 {VV_NAME("testing", VAR_NUMBER), 0},
128 {VV_NAME("t_number", VAR_NUMBER), VV_RO},
129 {VV_NAME("t_string", VAR_NUMBER), VV_RO},
130 {VV_NAME("t_func", VAR_NUMBER), VV_RO},
131 {VV_NAME("t_list", VAR_NUMBER), VV_RO},
132 {VV_NAME("t_dict", VAR_NUMBER), VV_RO},
133 {VV_NAME("t_float", VAR_NUMBER), VV_RO},
134 {VV_NAME("t_bool", VAR_NUMBER), VV_RO},
135 {VV_NAME("t_none", VAR_NUMBER), VV_RO},
136 {VV_NAME("t_job", VAR_NUMBER), VV_RO},
137 {VV_NAME("t_channel", VAR_NUMBER), VV_RO},
138 {VV_NAME("t_blob", VAR_NUMBER), VV_RO},
139 {VV_NAME("termrfgresp", VAR_STRING), VV_RO},
140 {VV_NAME("termrbgresp", VAR_STRING), VV_RO},
141 {VV_NAME("termu7resp", VAR_STRING), VV_RO},
142 {VV_NAME("termstyleresp", VAR_STRING), VV_RO},
143 {VV_NAME("termblinkresp", VAR_STRING), VV_RO},
144 {VV_NAME("event", VAR_DICT), VV_RO},
145 {VV_NAME("versionlong", VAR_NUMBER), VV_RO},
146 {VV_NAME("echospace", VAR_NUMBER), VV_RO},
Bram Moolenaar69bf6342019-10-29 04:16:57 +0100147 {VV_NAME("argv", VAR_LIST), VV_RO},
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200148};
149
150// shorthand
151#define vv_type vv_di.di_tv.v_type
152#define vv_nr vv_di.di_tv.vval.v_number
153#define vv_float vv_di.di_tv.vval.v_float
154#define vv_str vv_di.di_tv.vval.v_string
155#define vv_list vv_di.di_tv.vval.v_list
156#define vv_dict vv_di.di_tv.vval.v_dict
157#define vv_blob vv_di.di_tv.vval.v_blob
158#define vv_tv vv_di.di_tv
159
160static dictitem_T vimvars_var; // variable used for v:
Bram Moolenaarda6c0332019-09-01 16:01:30 +0200161static dict_T vimvardict; // Dictionary with v: variables
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200162#define vimvarht vimvardict.dv_hashtab
163
164// for VIM_VERSION_ defines
165#include "version.h"
166
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200167static void ex_let_const(exarg_T *eap, int is_const);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100168static char_u *skip_var_one(char_u *arg, int include_type);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200169static void list_glob_vars(int *first);
170static void list_buf_vars(int *first);
171static void list_win_vars(int *first);
172static void list_tab_vars(int *first);
173static char_u *list_arg_vars(exarg_T *eap, char_u *arg, int *first);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100174static char_u *ex_let_one(char_u *arg, typval_T *tv, int copy, int flags, char_u *endchars, char_u *op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200175static void ex_unletlock(exarg_T *eap, char_u *argstart, int deep);
176static int do_unlet_var(lval_T *lp, char_u *name_end, int forceit);
177static int do_lock_var(lval_T *lp, char_u *name_end, int deep, int lock);
178static void item_lock(typval_T *tv, int deep, int lock);
Bram Moolenaarda6c0332019-09-01 16:01:30 +0200179static void delete_var(hashtab_T *ht, hashitem_T *hi);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200180static void list_one_var(dictitem_T *v, char *prefix, int *first);
181static void list_one_var_a(char *prefix, char_u *name, int type, char_u *string, int *first);
182
183/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200184 * Initialize global and vim special variables
185 */
186 void
187evalvars_init(void)
188{
189 int i;
190 struct vimvar *p;
191
192 init_var_dict(&globvardict, &globvars_var, VAR_DEF_SCOPE);
193 init_var_dict(&vimvardict, &vimvars_var, VAR_SCOPE);
194 vimvardict.dv_lock = VAR_FIXED;
195 hash_init(&compat_hashtab);
196
197 for (i = 0; i < VV_LEN; ++i)
198 {
199 p = &vimvars[i];
200 if (STRLEN(p->vv_name) > DICTITEM16_KEY_LEN)
201 {
202 iemsg("INTERNAL: name too long, increase size of dictitem16_T");
203 getout(1);
204 }
205 STRCPY(p->vv_di.di_key, p->vv_name);
206 if (p->vv_flags & VV_RO)
207 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
208 else if (p->vv_flags & VV_RO_SBX)
209 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
210 else
211 p->vv_di.di_flags = DI_FLAGS_FIX;
212
213 // add to v: scope dict, unless the value is not always available
214 if (p->vv_type != VAR_UNKNOWN)
215 hash_add(&vimvarht, p->vv_di.di_key);
216 if (p->vv_flags & VV_COMPAT)
217 // add to compat scope dict
218 hash_add(&compat_hashtab, p->vv_di.di_key);
219 }
220 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
221 vimvars[VV_VERSIONLONG].vv_nr = VIM_VERSION_100 * 10000 + highest_patch();
222
223 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
224 set_vim_var_nr(VV_HLSEARCH, 1L);
225 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
226 set_vim_var_list(VV_ERRORS, list_alloc());
227 set_vim_var_dict(VV_EVENT, dict_alloc_lock(VAR_FIXED));
228
229 set_vim_var_nr(VV_FALSE, VVAL_FALSE);
230 set_vim_var_nr(VV_TRUE, VVAL_TRUE);
231 set_vim_var_nr(VV_NONE, VVAL_NONE);
232 set_vim_var_nr(VV_NULL, VVAL_NULL);
Bram Moolenaarf9706e92020-02-22 14:27:04 +0100233 set_vim_var_nr(VV_NUMBERSIZE, sizeof(varnumber_T) * 8);
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200234
235 set_vim_var_nr(VV_TYPE_NUMBER, VAR_TYPE_NUMBER);
236 set_vim_var_nr(VV_TYPE_STRING, VAR_TYPE_STRING);
237 set_vim_var_nr(VV_TYPE_FUNC, VAR_TYPE_FUNC);
238 set_vim_var_nr(VV_TYPE_LIST, VAR_TYPE_LIST);
239 set_vim_var_nr(VV_TYPE_DICT, VAR_TYPE_DICT);
240 set_vim_var_nr(VV_TYPE_FLOAT, VAR_TYPE_FLOAT);
241 set_vim_var_nr(VV_TYPE_BOOL, VAR_TYPE_BOOL);
242 set_vim_var_nr(VV_TYPE_NONE, VAR_TYPE_NONE);
243 set_vim_var_nr(VV_TYPE_JOB, VAR_TYPE_JOB);
244 set_vim_var_nr(VV_TYPE_CHANNEL, VAR_TYPE_CHANNEL);
245 set_vim_var_nr(VV_TYPE_BLOB, VAR_TYPE_BLOB);
246
247 set_vim_var_nr(VV_ECHOSPACE, sc_col - 1);
248
249 set_reg_var(0); // default for v:register is not 0 but '"'
250}
251
252#if defined(EXITFREE) || defined(PROTO)
253/*
254 * Free all vim variables information on exit
255 */
256 void
257evalvars_clear(void)
258{
259 int i;
260 struct vimvar *p;
261
262 for (i = 0; i < VV_LEN; ++i)
263 {
264 p = &vimvars[i];
265 if (p->vv_di.di_tv.v_type == VAR_STRING)
266 VIM_CLEAR(p->vv_str);
267 else if (p->vv_di.di_tv.v_type == VAR_LIST)
268 {
269 list_unref(p->vv_list);
270 p->vv_list = NULL;
271 }
272 }
273 hash_clear(&vimvarht);
274 hash_init(&vimvarht); // garbage_collect() will access it
275 hash_clear(&compat_hashtab);
276
277 // global variables
278 vars_clear(&globvarht);
279
Bram Moolenaar7ebcba62020-01-12 17:42:55 +0100280 // Script-local variables. Clear all the variables here.
281 // The scriptvar_T is cleared later in free_scriptnames(), because a
282 // variable in one script might hold a reference to the whole scope of
283 // another script.
284 for (i = 1; i <= script_items.ga_len; ++i)
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200285 vars_clear(&SCRIPT_VARS(i));
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200286}
287#endif
288
289 int
Bram Moolenaarda6c0332019-09-01 16:01:30 +0200290garbage_collect_globvars(int copyID)
291{
292 return set_ref_in_ht(&globvarht, copyID, NULL);
293}
294
295 int
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200296garbage_collect_vimvars(int copyID)
297{
298 return set_ref_in_ht(&vimvarht, copyID, NULL);
299}
300
301 int
302garbage_collect_scriptvars(int copyID)
303{
304 int i;
305 int abort = FALSE;
306
Bram Moolenaar7ebcba62020-01-12 17:42:55 +0100307 for (i = 1; i <= script_items.ga_len; ++i)
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200308 abort = abort || set_ref_in_ht(&SCRIPT_VARS(i), copyID, NULL);
309
310 return abort;
311}
312
313/*
314 * Set an internal variable to a string value. Creates the variable if it does
315 * not already exist.
316 */
317 void
318set_internal_string_var(char_u *name, char_u *value)
319{
320 char_u *val;
321 typval_T *tvp;
322
323 val = vim_strsave(value);
324 if (val != NULL)
325 {
326 tvp = alloc_string_tv(val);
327 if (tvp != NULL)
328 {
329 set_var(name, tvp, FALSE);
330 free_tv(tvp);
331 }
332 }
333}
334
Bram Moolenaarda6c0332019-09-01 16:01:30 +0200335 int
336eval_charconvert(
337 char_u *enc_from,
338 char_u *enc_to,
339 char_u *fname_from,
340 char_u *fname_to)
341{
342 int err = FALSE;
343
344 set_vim_var_string(VV_CC_FROM, enc_from, -1);
345 set_vim_var_string(VV_CC_TO, enc_to, -1);
346 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
347 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
348 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
349 err = TRUE;
350 set_vim_var_string(VV_CC_FROM, NULL, -1);
351 set_vim_var_string(VV_CC_TO, NULL, -1);
352 set_vim_var_string(VV_FNAME_IN, NULL, -1);
353 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
354
355 if (err)
356 return FAIL;
357 return OK;
358}
359
360# if defined(FEAT_POSTSCRIPT) || defined(PROTO)
361 int
362eval_printexpr(char_u *fname, char_u *args)
363{
364 int err = FALSE;
365
366 set_vim_var_string(VV_FNAME_IN, fname, -1);
367 set_vim_var_string(VV_CMDARG, args, -1);
368 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
369 err = TRUE;
370 set_vim_var_string(VV_FNAME_IN, NULL, -1);
371 set_vim_var_string(VV_CMDARG, NULL, -1);
372
373 if (err)
374 {
375 mch_remove(fname);
376 return FAIL;
377 }
378 return OK;
379}
380# endif
381
382# if defined(FEAT_DIFF) || defined(PROTO)
383 void
384eval_diff(
385 char_u *origfile,
386 char_u *newfile,
387 char_u *outfile)
388{
389 int err = FALSE;
390
391 set_vim_var_string(VV_FNAME_IN, origfile, -1);
392 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
393 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
394 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
395 set_vim_var_string(VV_FNAME_IN, NULL, -1);
396 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
397 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
398}
399
400 void
401eval_patch(
402 char_u *origfile,
403 char_u *difffile,
404 char_u *outfile)
405{
406 int err;
407
408 set_vim_var_string(VV_FNAME_IN, origfile, -1);
409 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
410 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
411 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
412 set_vim_var_string(VV_FNAME_IN, NULL, -1);
413 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
414 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
415}
416# endif
417
418#if defined(FEAT_SPELL) || defined(PROTO)
419/*
420 * Evaluate an expression to a list with suggestions.
421 * For the "expr:" part of 'spellsuggest'.
422 * Returns NULL when there is an error.
423 */
424 list_T *
425eval_spell_expr(char_u *badword, char_u *expr)
426{
427 typval_T save_val;
428 typval_T rettv;
429 list_T *list = NULL;
430 char_u *p = skipwhite(expr);
431
432 // Set "v:val" to the bad word.
433 prepare_vimvar(VV_VAL, &save_val);
434 set_vim_var_string(VV_VAL, badword, -1);
435 if (p_verbose == 0)
436 ++emsg_off;
437
438 if (eval1(&p, &rettv, TRUE) == OK)
439 {
440 if (rettv.v_type != VAR_LIST)
441 clear_tv(&rettv);
442 else
443 list = rettv.vval.v_list;
444 }
445
446 if (p_verbose == 0)
447 --emsg_off;
448 clear_tv(get_vim_var_tv(VV_VAL));
449 restore_vimvar(VV_VAL, &save_val);
450
451 return list;
452}
453
454/*
455 * "list" is supposed to contain two items: a word and a number. Return the
456 * word in "pp" and the number as the return value.
457 * Return -1 if anything isn't right.
458 * Used to get the good word and score from the eval_spell_expr() result.
459 */
460 int
461get_spellword(list_T *list, char_u **pp)
462{
463 listitem_T *li;
464
465 li = list->lv_first;
466 if (li == NULL)
467 return -1;
468 *pp = tv_get_string(&li->li_tv);
469
470 li = li->li_next;
471 if (li == NULL)
472 return -1;
473 return (int)tv_get_number(&li->li_tv);
474}
475#endif
476
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200477/*
478 * Prepare v: variable "idx" to be used.
Bram Moolenaar27da7de2019-09-03 17:13:37 +0200479 * Save the current typeval in "save_tv" and clear it.
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200480 * When not used yet add the variable to the v: hashtable.
481 */
482 void
483prepare_vimvar(int idx, typval_T *save_tv)
484{
485 *save_tv = vimvars[idx].vv_tv;
Bram Moolenaar27da7de2019-09-03 17:13:37 +0200486 vimvars[idx].vv_str = NULL; // don't free it now
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200487 if (vimvars[idx].vv_type == VAR_UNKNOWN)
488 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
489}
490
491/*
492 * Restore v: variable "idx" to typeval "save_tv".
Bram Moolenaar27da7de2019-09-03 17:13:37 +0200493 * Note that the v: variable must have been cleared already.
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200494 * When no longer defined, remove the variable from the v: hashtable.
495 */
496 void
497restore_vimvar(int idx, typval_T *save_tv)
498{
499 hashitem_T *hi;
500
501 vimvars[idx].vv_tv = *save_tv;
502 if (vimvars[idx].vv_type == VAR_UNKNOWN)
503 {
504 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
505 if (HASHITEM_EMPTY(hi))
506 internal_error("restore_vimvar()");
507 else
508 hash_remove(&vimvarht, hi);
509 }
510}
511
512/*
513 * List Vim variables.
514 */
515 static void
516list_vim_vars(int *first)
517{
518 list_hashtable_vars(&vimvarht, "v:", FALSE, first);
519}
520
521/*
522 * List script-local variables, if there is a script.
523 */
524 static void
525list_script_vars(int *first)
526{
Bram Moolenaar7ebcba62020-01-12 17:42:55 +0100527 if (current_sctx.sc_sid > 0 && current_sctx.sc_sid <= script_items.ga_len)
Bram Moolenaare5cdf152019-08-29 22:09:46 +0200528 list_hashtable_vars(&SCRIPT_VARS(current_sctx.sc_sid),
529 "s:", FALSE, first);
530}
531
532/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200533 * Get a list of lines from a HERE document. The here document is a list of
534 * lines surrounded by a marker.
535 * cmd << {marker}
536 * {line1}
537 * {line2}
538 * ....
539 * {marker}
540 *
541 * The {marker} is a string. If the optional 'trim' word is supplied before the
542 * marker, then the leading indentation before the lines (matching the
543 * indentation in the 'cmd' line) is stripped.
544 * Returns a List with {lines} or NULL.
545 */
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100546 list_T *
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200547heredoc_get(exarg_T *eap, char_u *cmd)
548{
549 char_u *theline;
550 char_u *marker;
551 list_T *l;
552 char_u *p;
553 int marker_indent_len = 0;
554 int text_indent_len = 0;
555 char_u *text_indent = NULL;
556
557 if (eap->getline == NULL)
558 {
559 emsg(_("E991: cannot use =<< here"));
560 return NULL;
561 }
562
563 // Check for the optional 'trim' word before the marker
564 cmd = skipwhite(cmd);
565 if (STRNCMP(cmd, "trim", 4) == 0 && (cmd[4] == NUL || VIM_ISWHITE(cmd[4])))
566 {
567 cmd = skipwhite(cmd + 4);
568
569 // Trim the indentation from all the lines in the here document.
570 // The amount of indentation trimmed is the same as the indentation of
571 // the first line after the :let command line. To find the end marker
572 // the indent of the :let command line is trimmed.
573 p = *eap->cmdlinep;
574 while (VIM_ISWHITE(*p))
575 {
576 p++;
577 marker_indent_len++;
578 }
579 text_indent_len = -1;
580 }
581
582 // The marker is the next word.
583 if (*cmd != NUL && *cmd != '"')
584 {
585 marker = skipwhite(cmd);
586 p = skiptowhite(marker);
587 if (*skipwhite(p) != NUL && *skipwhite(p) != '"')
588 {
589 emsg(_(e_trailing));
590 return NULL;
591 }
592 *p = NUL;
593 if (vim_islower(*marker))
594 {
595 emsg(_("E221: Marker cannot start with lower case letter"));
596 return NULL;
597 }
598 }
599 else
600 {
601 emsg(_("E172: Missing marker"));
602 return NULL;
603 }
604
605 l = list_alloc();
606 if (l == NULL)
607 return NULL;
608
609 for (;;)
610 {
611 int mi = 0;
612 int ti = 0;
613
614 theline = eap->getline(NUL, eap->cookie, 0, FALSE);
615 if (theline == NULL)
616 {
617 semsg(_("E990: Missing end marker '%s'"), marker);
618 break;
619 }
620
621 // with "trim": skip the indent matching the :let line to find the
622 // marker
623 if (marker_indent_len > 0
624 && STRNCMP(theline, *eap->cmdlinep, marker_indent_len) == 0)
625 mi = marker_indent_len;
626 if (STRCMP(marker, theline + mi) == 0)
627 {
628 vim_free(theline);
629 break;
630 }
631
632 if (text_indent_len == -1 && *theline != NUL)
633 {
634 // set the text indent from the first line.
635 p = theline;
636 text_indent_len = 0;
637 while (VIM_ISWHITE(*p))
638 {
639 p++;
640 text_indent_len++;
641 }
642 text_indent = vim_strnsave(theline, text_indent_len);
643 }
644 // with "trim": skip the indent matching the first line
645 if (text_indent != NULL)
646 for (ti = 0; ti < text_indent_len; ++ti)
647 if (theline[ti] != text_indent[ti])
648 break;
649
650 if (list_append_string(l, theline + ti, -1) == FAIL)
651 break;
652 vim_free(theline);
653 }
654 vim_free(text_indent);
655
656 return l;
657}
658
659/*
660 * ":let" list all variable values
661 * ":let var1 var2" list variable values
662 * ":let var = expr" assignment command.
663 * ":let var += expr" assignment command.
664 * ":let var -= expr" assignment command.
665 * ":let var *= expr" assignment command.
666 * ":let var /= expr" assignment command.
667 * ":let var %= expr" assignment command.
668 * ":let var .= expr" assignment command.
669 * ":let var ..= expr" assignment command.
670 * ":let [var1, var2] = expr" unpack list.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100671 * ":let var =<< ..." heredoc
Bram Moolenaard672dde2020-02-26 13:43:51 +0100672 * ":let var: string" Vim9 declaration
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200673 */
674 void
675ex_let(exarg_T *eap)
676{
677 ex_let_const(eap, FALSE);
678}
679
680/*
681 * ":const" list all variable values
682 * ":const var1 var2" list variable values
683 * ":const var = expr" assignment command.
684 * ":const [var1, var2] = expr" unpack list.
685 */
686 void
687ex_const(exarg_T *eap)
688{
689 ex_let_const(eap, TRUE);
690}
691
692 static void
693ex_let_const(exarg_T *eap, int is_const)
694{
695 char_u *arg = eap->arg;
696 char_u *expr = NULL;
697 typval_T rettv;
698 int i;
699 int var_count = 0;
700 int semicolon = 0;
701 char_u op[2];
702 char_u *argend;
703 int first = TRUE;
704 int concat;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100705 int flags = is_const ? LET_IS_CONST : 0;
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200706
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100707 // detect Vim9 assignment without ":let" or ":const"
708 if (eap->arg == eap->cmd)
709 flags |= LET_NO_COMMAND;
710
711 argend = skip_var_list(arg, TRUE, &var_count, &semicolon);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200712 if (argend == NULL)
713 return;
714 if (argend > arg && argend[-1] == '.') // for var.='str'
715 --argend;
716 expr = skipwhite(argend);
717 concat = expr[0] == '.'
718 && ((expr[1] == '=' && current_sctx.sc_version < 2)
719 || (expr[1] == '.' && expr[2] == '='));
720 if (*expr != '=' && !((vim_strchr((char_u *)"+-*/%", *expr) != NULL
721 && expr[1] == '=') || concat))
722 {
723 // ":let" without "=": list variables
724 if (*arg == '[')
725 emsg(_(e_invarg));
726 else if (expr[0] == '.')
727 emsg(_("E985: .= is not supported with script version 2"));
728 else if (!ends_excmd(*arg))
729 // ":let var1 var2"
730 arg = list_arg_vars(eap, arg, &first);
731 else if (!eap->skip)
732 {
733 // ":let"
734 list_glob_vars(&first);
735 list_buf_vars(&first);
736 list_win_vars(&first);
737 list_tab_vars(&first);
738 list_script_vars(&first);
739 list_func_vars(&first);
740 list_vim_vars(&first);
741 }
742 eap->nextcmd = check_nextcmd(arg);
743 }
744 else if (expr[0] == '=' && expr[1] == '<' && expr[2] == '<')
745 {
746 list_T *l;
747
748 // HERE document
749 l = heredoc_get(eap, expr + 3);
750 if (l != NULL)
751 {
752 rettv_list_set(&rettv, l);
Bram Moolenaarb1ba9ab2019-10-16 23:34:42 +0200753 if (!eap->skip)
754 {
755 op[0] = '=';
756 op[1] = NUL;
757 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100758 flags, op);
Bram Moolenaarb1ba9ab2019-10-16 23:34:42 +0200759 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200760 clear_tv(&rettv);
761 }
762 }
763 else
764 {
765 op[0] = '=';
766 op[1] = NUL;
767 if (*expr != '=')
768 {
769 if (vim_strchr((char_u *)"+-*/%.", *expr) != NULL)
770 {
771 op[0] = *expr; // +=, -=, *=, /=, %= or .=
772 if (expr[0] == '.' && expr[1] == '.') // ..=
773 ++expr;
774 }
775 expr = skipwhite(expr + 2);
776 }
777 else
778 expr = skipwhite(expr + 1);
779
780 if (eap->skip)
781 ++emsg_skip;
782 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
783 if (eap->skip)
784 {
785 if (i != FAIL)
786 clear_tv(&rettv);
787 --emsg_skip;
788 }
789 else if (i != FAIL)
790 {
791 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100792 flags, op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200793 clear_tv(&rettv);
794 }
795 }
796}
797
798/*
799 * Assign the typevalue "tv" to the variable or variables at "arg_start".
800 * Handles both "var" with any type and "[var, var; var]" with a list type.
801 * When "op" is not NULL it points to a string with characters that
802 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
803 * or concatenate.
804 * Returns OK or FAIL;
805 */
806 int
807ex_let_vars(
808 char_u *arg_start,
809 typval_T *tv,
810 int copy, // copy values from "tv", don't move
811 int semicolon, // from skip_var_list()
812 int var_count, // from skip_var_list()
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100813 int flags, // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200814 char_u *op)
815{
816 char_u *arg = arg_start;
817 list_T *l;
818 int i;
819 listitem_T *item;
820 typval_T ltv;
821
822 if (*arg != '[')
823 {
824 // ":let var = expr" or ":for var in list"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100825 if (ex_let_one(arg, tv, copy, flags, op, op) == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200826 return FAIL;
827 return OK;
828 }
829
830 // ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
831 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
832 {
833 emsg(_(e_listreq));
834 return FAIL;
835 }
836
837 i = list_len(l);
838 if (semicolon == 0 && var_count < i)
839 {
840 emsg(_("E687: Less targets than List items"));
841 return FAIL;
842 }
843 if (var_count - semicolon > i)
844 {
845 emsg(_("E688: More targets than List items"));
846 return FAIL;
847 }
848
Bram Moolenaar50985eb2020-01-27 22:09:39 +0100849 range_list_materialize(l);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200850 item = l->lv_first;
851 while (*arg != ']')
852 {
853 arg = skipwhite(arg + 1);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100854 arg = ex_let_one(arg, &item->li_tv, TRUE, flags, (char_u *)",;]", op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200855 item = item->li_next;
856 if (arg == NULL)
857 return FAIL;
858
859 arg = skipwhite(arg);
860 if (*arg == ';')
861 {
862 // Put the rest of the list (may be empty) in the var after ';'.
863 // Create a new list for this.
864 l = list_alloc();
865 if (l == NULL)
866 return FAIL;
867 while (item != NULL)
868 {
869 list_append_tv(l, &item->li_tv);
870 item = item->li_next;
871 }
872
873 ltv.v_type = VAR_LIST;
874 ltv.v_lock = 0;
875 ltv.vval.v_list = l;
876 l->lv_refcount = 1;
877
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100878 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE, flags,
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200879 (char_u *)"]", op);
880 clear_tv(&ltv);
881 if (arg == NULL)
882 return FAIL;
883 break;
884 }
885 else if (*arg != ',' && *arg != ']')
886 {
887 internal_error("ex_let_vars()");
888 return FAIL;
889 }
890 }
891
892 return OK;
893}
894
895/*
896 * Skip over assignable variable "var" or list of variables "[var, var]".
897 * Used for ":let varvar = expr" and ":for varvar in expr".
898 * For "[var, var]" increment "*var_count" for each variable.
899 * for "[var, var; var]" set "semicolon".
900 * Return NULL for an error.
901 */
902 char_u *
903skip_var_list(
904 char_u *arg,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100905 int include_type,
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200906 int *var_count,
907 int *semicolon)
908{
909 char_u *p, *s;
910
911 if (*arg == '[')
912 {
913 // "[var, var]": find the matching ']'.
914 p = arg;
915 for (;;)
916 {
917 p = skipwhite(p + 1); // skip whites after '[', ';' or ','
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100918 s = skip_var_one(p, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200919 if (s == p)
920 {
921 semsg(_(e_invarg2), p);
922 return NULL;
923 }
924 ++*var_count;
925
926 p = skipwhite(s);
927 if (*p == ']')
928 break;
929 else if (*p == ';')
930 {
931 if (*semicolon == 1)
932 {
Bram Moolenaar9be61bb2020-03-30 22:51:24 +0200933 emsg(_("E452: Double ; in list of variables"));
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200934 return NULL;
935 }
936 *semicolon = 1;
937 }
938 else if (*p != ',')
939 {
940 semsg(_(e_invarg2), p);
941 return NULL;
942 }
943 }
944 return p + 1;
945 }
946 else
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100947 return skip_var_one(arg, include_type);
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200948}
949
950/*
951 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
952 * l[idx].
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100953 * In Vim9 script also skip over ": type" if "include_type" is TRUE.
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200954 */
955 static char_u *
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100956skip_var_one(char_u *arg, int include_type)
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200957{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100958 char_u *end;
959
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200960 if (*arg == '@' && arg[1] != NUL)
961 return arg + 2;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100962 end = find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200963 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100964 if (include_type && current_sctx.sc_version == SCRIPT_VERSION_VIM9
965 && *end == ':')
966 {
967 end = skip_type(skipwhite(end + 1));
968 }
969 return end;
Bram Moolenaar0522ba02019-08-27 22:48:30 +0200970}
971
972/*
973 * List variables for hashtab "ht" with prefix "prefix".
974 * If "empty" is TRUE also list NULL strings as empty strings.
975 */
976 void
977list_hashtable_vars(
978 hashtab_T *ht,
979 char *prefix,
980 int empty,
981 int *first)
982{
983 hashitem_T *hi;
984 dictitem_T *di;
985 int todo;
986 char_u buf[IOSIZE];
987
988 todo = (int)ht->ht_used;
989 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
990 {
991 if (!HASHITEM_EMPTY(hi))
992 {
993 --todo;
994 di = HI2DI(hi);
995
996 // apply :filter /pat/ to variable name
997 vim_strncpy((char_u *)buf, (char_u *)prefix, IOSIZE - 1);
998 vim_strcat((char_u *)buf, di->di_key, IOSIZE);
999 if (message_filtered(buf))
1000 continue;
1001
1002 if (empty || di->di_tv.v_type != VAR_STRING
1003 || di->di_tv.vval.v_string != NULL)
1004 list_one_var(di, prefix, first);
1005 }
1006 }
1007}
1008
1009/*
1010 * List global variables.
1011 */
1012 static void
1013list_glob_vars(int *first)
1014{
1015 list_hashtable_vars(&globvarht, "", TRUE, first);
1016}
1017
1018/*
1019 * List buffer variables.
1020 */
1021 static void
1022list_buf_vars(int *first)
1023{
1024 list_hashtable_vars(&curbuf->b_vars->dv_hashtab, "b:", TRUE, first);
1025}
1026
1027/*
1028 * List window variables.
1029 */
1030 static void
1031list_win_vars(int *first)
1032{
1033 list_hashtable_vars(&curwin->w_vars->dv_hashtab, "w:", TRUE, first);
1034}
1035
1036/*
1037 * List tab page variables.
1038 */
1039 static void
1040list_tab_vars(int *first)
1041{
1042 list_hashtable_vars(&curtab->tp_vars->dv_hashtab, "t:", TRUE, first);
1043}
1044
1045/*
1046 * List variables in "arg".
1047 */
1048 static char_u *
1049list_arg_vars(exarg_T *eap, char_u *arg, int *first)
1050{
1051 int error = FALSE;
1052 int len;
1053 char_u *name;
1054 char_u *name_start;
1055 char_u *arg_subsc;
1056 char_u *tofree;
1057 typval_T tv;
1058
1059 while (!ends_excmd(*arg) && !got_int)
1060 {
1061 if (error || eap->skip)
1062 {
1063 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1064 if (!VIM_ISWHITE(*arg) && !ends_excmd(*arg))
1065 {
1066 emsg_severe = TRUE;
1067 emsg(_(e_trailing));
1068 break;
1069 }
1070 }
1071 else
1072 {
1073 // get_name_len() takes care of expanding curly braces
1074 name_start = name = arg;
1075 len = get_name_len(&arg, &tofree, TRUE, TRUE);
1076 if (len <= 0)
1077 {
1078 // This is mainly to keep test 49 working: when expanding
1079 // curly braces fails overrule the exception error message.
1080 if (len < 0 && !aborting())
1081 {
1082 emsg_severe = TRUE;
1083 semsg(_(e_invarg2), arg);
1084 break;
1085 }
1086 error = TRUE;
1087 }
1088 else
1089 {
1090 if (tofree != NULL)
1091 name = tofree;
1092 if (get_var_tv(name, len, &tv, NULL, TRUE, FALSE) == FAIL)
1093 error = TRUE;
1094 else
1095 {
1096 // handle d.key, l[idx], f(expr)
1097 arg_subsc = arg;
1098 if (handle_subscript(&arg, &tv, TRUE, TRUE,
1099 name, &name) == FAIL)
1100 error = TRUE;
1101 else
1102 {
1103 if (arg == arg_subsc && len == 2 && name[1] == ':')
1104 {
1105 switch (*name)
1106 {
1107 case 'g': list_glob_vars(first); break;
1108 case 'b': list_buf_vars(first); break;
1109 case 'w': list_win_vars(first); break;
1110 case 't': list_tab_vars(first); break;
1111 case 'v': list_vim_vars(first); break;
1112 case 's': list_script_vars(first); break;
1113 case 'l': list_func_vars(first); break;
1114 default:
1115 semsg(_("E738: Can't list variables for %s"), name);
1116 }
1117 }
1118 else
1119 {
1120 char_u numbuf[NUMBUFLEN];
1121 char_u *tf;
1122 int c;
1123 char_u *s;
1124
1125 s = echo_string(&tv, &tf, numbuf, 0);
1126 c = *arg;
1127 *arg = NUL;
1128 list_one_var_a("",
1129 arg == arg_subsc ? name : name_start,
1130 tv.v_type,
1131 s == NULL ? (char_u *)"" : s,
1132 first);
1133 *arg = c;
1134 vim_free(tf);
1135 }
1136 clear_tv(&tv);
1137 }
1138 }
1139 }
1140
1141 vim_free(tofree);
1142 }
1143
1144 arg = skipwhite(arg);
1145 }
1146
1147 return arg;
1148}
1149
1150/*
1151 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
1152 * Returns a pointer to the char just after the var name.
1153 * Returns NULL if there is an error.
1154 */
1155 static char_u *
1156ex_let_one(
1157 char_u *arg, // points to variable name
1158 typval_T *tv, // value to assign to variable
1159 int copy, // copy value from "tv"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001160 int flags, // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001161 char_u *endchars, // valid chars after variable name or NULL
1162 char_u *op) // "+", "-", "." or NULL
1163{
1164 int c1;
1165 char_u *name;
1166 char_u *p;
1167 char_u *arg_end = NULL;
1168 int len;
1169 int opt_flags;
1170 char_u *tofree = NULL;
1171
1172 // ":let $VAR = expr": Set environment variable.
1173 if (*arg == '$')
1174 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001175 if (flags & LET_IS_CONST)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001176 {
1177 emsg(_("E996: Cannot lock an environment variable"));
1178 return NULL;
1179 }
1180 // Find the end of the name.
1181 ++arg;
1182 name = arg;
1183 len = get_env_len(&arg);
1184 if (len == 0)
1185 semsg(_(e_invarg2), name - 1);
1186 else
1187 {
1188 if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL)
1189 semsg(_(e_letwrong), op);
1190 else if (endchars != NULL
1191 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
1192 emsg(_(e_letunexp));
1193 else if (!check_secure())
1194 {
1195 c1 = name[len];
1196 name[len] = NUL;
1197 p = tv_get_string_chk(tv);
1198 if (p != NULL && op != NULL && *op == '.')
1199 {
1200 int mustfree = FALSE;
1201 char_u *s = vim_getenv(name, &mustfree);
1202
1203 if (s != NULL)
1204 {
1205 p = tofree = concat_str(s, p);
1206 if (mustfree)
1207 vim_free(s);
1208 }
1209 }
1210 if (p != NULL)
1211 {
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01001212 vim_setenv_ext(name, p);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001213 arg_end = arg;
1214 }
1215 name[len] = c1;
1216 vim_free(tofree);
1217 }
1218 }
1219 }
1220
1221 // ":let &option = expr": Set option value.
1222 // ":let &l:option = expr": Set local option value.
1223 // ":let &g:option = expr": Set global option value.
1224 else if (*arg == '&')
1225 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001226 if (flags & LET_IS_CONST)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001227 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001228 emsg(_(e_const_option));
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001229 return NULL;
1230 }
1231 // Find the end of the name.
1232 p = find_option_end(&arg, &opt_flags);
1233 if (p == NULL || (endchars != NULL
1234 && vim_strchr(endchars, *skipwhite(p)) == NULL))
1235 emsg(_(e_letunexp));
1236 else
1237 {
1238 long n;
1239 int opt_type;
1240 long numval;
1241 char_u *stringval = NULL;
1242 char_u *s;
1243
1244 c1 = *p;
1245 *p = NUL;
1246
1247 n = (long)tv_get_number(tv);
1248 s = tv_get_string_chk(tv); // != NULL if number or string
1249 if (s != NULL && op != NULL && *op != '=')
1250 {
1251 opt_type = get_option_value(arg, &numval,
1252 &stringval, opt_flags);
1253 if ((opt_type == 1 && *op == '.')
1254 || (opt_type == 0 && *op != '.'))
1255 {
1256 semsg(_(e_letwrong), op);
1257 s = NULL; // don't set the value
1258 }
1259 else
1260 {
1261 if (opt_type == 1) // number
1262 {
1263 switch (*op)
1264 {
1265 case '+': n = numval + n; break;
1266 case '-': n = numval - n; break;
1267 case '*': n = numval * n; break;
1268 case '/': n = (long)num_divide(numval, n); break;
1269 case '%': n = (long)num_modulus(numval, n); break;
1270 }
1271 }
1272 else if (opt_type == 0 && stringval != NULL) // string
1273 {
1274 s = concat_str(stringval, s);
1275 vim_free(stringval);
1276 stringval = s;
1277 }
1278 }
1279 }
1280 if (s != NULL)
1281 {
1282 set_option_value(arg, n, s, opt_flags);
1283 arg_end = p;
1284 }
1285 *p = c1;
1286 vim_free(stringval);
1287 }
1288 }
1289
1290 // ":let @r = expr": Set register contents.
1291 else if (*arg == '@')
1292 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001293 if (flags & LET_IS_CONST)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001294 {
1295 emsg(_("E996: Cannot lock a register"));
1296 return NULL;
1297 }
1298 ++arg;
1299 if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL)
1300 semsg(_(e_letwrong), op);
1301 else if (endchars != NULL
1302 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
1303 emsg(_(e_letunexp));
1304 else
1305 {
1306 char_u *ptofree = NULL;
1307 char_u *s;
1308
1309 p = tv_get_string_chk(tv);
1310 if (p != NULL && op != NULL && *op == '.')
1311 {
1312 s = get_reg_contents(*arg == '@' ? '"' : *arg, GREG_EXPR_SRC);
1313 if (s != NULL)
1314 {
1315 p = ptofree = concat_str(s, p);
1316 vim_free(s);
1317 }
1318 }
1319 if (p != NULL)
1320 {
1321 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
1322 arg_end = arg + 1;
1323 }
1324 vim_free(ptofree);
1325 }
1326 }
1327
1328 // ":let var = expr": Set internal variable.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001329 // ":let var: type = expr": Set internal variable with type.
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001330 // ":let {expr} = expr": Idem, name made with curly braces
1331 else if (eval_isnamec1(*arg) || *arg == '{')
1332 {
1333 lval_T lv;
1334
1335 p = get_lval(arg, tv, &lv, FALSE, FALSE, 0, FNE_CHECK_START);
1336 if (p != NULL && lv.ll_name != NULL)
1337 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001338 if (endchars != NULL && vim_strchr(endchars,
1339 *skipwhite(lv.ll_name_end)) == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001340 emsg(_(e_letunexp));
1341 else
1342 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001343 set_var_lval(&lv, p, tv, copy, flags, op);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001344 arg_end = p;
1345 }
1346 }
1347 clear_lval(&lv);
1348 }
1349
1350 else
1351 semsg(_(e_invarg2), arg);
1352
1353 return arg_end;
1354}
1355
1356/*
1357 * ":unlet[!] var1 ... " command.
1358 */
1359 void
1360ex_unlet(exarg_T *eap)
1361{
1362 ex_unletlock(eap, eap->arg, 0);
1363}
1364
1365/*
1366 * ":lockvar" and ":unlockvar" commands
1367 */
1368 void
1369ex_lockvar(exarg_T *eap)
1370{
1371 char_u *arg = eap->arg;
1372 int deep = 2;
1373
1374 if (eap->forceit)
1375 deep = -1;
1376 else if (vim_isdigit(*arg))
1377 {
1378 deep = getdigits(&arg);
1379 arg = skipwhite(arg);
1380 }
1381
1382 ex_unletlock(eap, arg, deep);
1383}
1384
1385/*
1386 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
1387 */
1388 static void
1389ex_unletlock(
1390 exarg_T *eap,
1391 char_u *argstart,
1392 int deep)
1393{
1394 char_u *arg = argstart;
1395 char_u *name_end;
1396 int error = FALSE;
1397 lval_T lv;
1398
1399 do
1400 {
1401 if (*arg == '$')
1402 {
1403 char_u *name = ++arg;
1404
1405 if (get_env_len(&arg) == 0)
1406 {
1407 semsg(_(e_invarg2), name - 1);
1408 return;
1409 }
1410 vim_unsetenv(name);
1411 arg = skipwhite(arg);
1412 continue;
1413 }
1414
1415 // Parse the name and find the end.
1416 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, 0,
1417 FNE_CHECK_START);
1418 if (lv.ll_name == NULL)
1419 error = TRUE; // error but continue parsing
1420 if (name_end == NULL || (!VIM_ISWHITE(*name_end)
1421 && !ends_excmd(*name_end)))
1422 {
1423 if (name_end != NULL)
1424 {
1425 emsg_severe = TRUE;
1426 emsg(_(e_trailing));
1427 }
1428 if (!(eap->skip || error))
1429 clear_lval(&lv);
1430 break;
1431 }
1432
1433 if (!error && !eap->skip)
1434 {
1435 if (eap->cmdidx == CMD_unlet)
1436 {
1437 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
1438 error = TRUE;
1439 }
1440 else
1441 {
1442 if (do_lock_var(&lv, name_end, deep,
1443 eap->cmdidx == CMD_lockvar) == FAIL)
1444 error = TRUE;
1445 }
1446 }
1447
1448 if (!eap->skip)
1449 clear_lval(&lv);
1450
1451 arg = skipwhite(name_end);
1452 } while (!ends_excmd(*arg));
1453
1454 eap->nextcmd = check_nextcmd(arg);
1455}
1456
1457 static int
1458do_unlet_var(
1459 lval_T *lp,
1460 char_u *name_end,
1461 int forceit)
1462{
1463 int ret = OK;
1464 int cc;
1465
1466 if (lp->ll_tv == NULL)
1467 {
1468 cc = *name_end;
1469 *name_end = NUL;
1470
1471 // Normal name or expanded name.
1472 if (do_unlet(lp->ll_name, forceit) == FAIL)
1473 ret = FAIL;
1474 *name_end = cc;
1475 }
1476 else if ((lp->ll_list != NULL
1477 && var_check_lock(lp->ll_list->lv_lock, lp->ll_name, FALSE))
1478 || (lp->ll_dict != NULL
1479 && var_check_lock(lp->ll_dict->dv_lock, lp->ll_name, FALSE)))
1480 return FAIL;
1481 else if (lp->ll_range)
1482 {
1483 listitem_T *li;
1484 listitem_T *ll_li = lp->ll_li;
1485 int ll_n1 = lp->ll_n1;
1486
1487 while (ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= ll_n1))
1488 {
1489 li = ll_li->li_next;
1490 if (var_check_lock(ll_li->li_tv.v_lock, lp->ll_name, FALSE))
1491 return FAIL;
1492 ll_li = li;
1493 ++ll_n1;
1494 }
1495
1496 // Delete a range of List items.
1497 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
1498 {
1499 li = lp->ll_li->li_next;
1500 listitem_remove(lp->ll_list, lp->ll_li);
1501 lp->ll_li = li;
1502 ++lp->ll_n1;
1503 }
1504 }
1505 else
1506 {
1507 if (lp->ll_list != NULL)
1508 // unlet a List item.
1509 listitem_remove(lp->ll_list, lp->ll_li);
1510 else
1511 // unlet a Dictionary item.
1512 dictitem_remove(lp->ll_dict, lp->ll_di);
1513 }
1514
1515 return ret;
1516}
1517
1518/*
1519 * "unlet" a variable. Return OK if it existed, FAIL if not.
1520 * When "forceit" is TRUE don't complain if the variable doesn't exist.
1521 */
1522 int
1523do_unlet(char_u *name, int forceit)
1524{
1525 hashtab_T *ht;
1526 hashitem_T *hi;
1527 char_u *varname;
1528 dict_T *d;
1529 dictitem_T *di;
1530
1531 ht = find_var_ht(name, &varname);
1532 if (ht != NULL && *varname != NUL)
1533 {
1534 d = get_current_funccal_dict(ht);
1535 if (d == NULL)
1536 {
1537 if (ht == &globvarht)
1538 d = &globvardict;
Bram Moolenaare5cdf152019-08-29 22:09:46 +02001539 else if (ht == &compat_hashtab)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001540 d = &vimvardict;
1541 else
1542 {
1543 di = find_var_in_ht(ht, *name, (char_u *)"", FALSE);
1544 d = di == NULL ? NULL : di->di_tv.vval.v_dict;
1545 }
1546 if (d == NULL)
1547 {
1548 internal_error("do_unlet()");
1549 return FAIL;
1550 }
1551 }
1552 hi = hash_find(ht, varname);
1553 if (HASHITEM_EMPTY(hi))
1554 hi = find_hi_in_scoped_ht(name, &ht);
1555 if (hi != NULL && !HASHITEM_EMPTY(hi))
1556 {
1557 di = HI2DI(hi);
1558 if (var_check_fixed(di->di_flags, name, FALSE)
1559 || var_check_ro(di->di_flags, name, FALSE)
1560 || var_check_lock(d->dv_lock, name, FALSE))
1561 return FAIL;
1562
1563 delete_var(ht, hi);
1564 return OK;
1565 }
1566 }
1567 if (forceit)
1568 return OK;
1569 semsg(_("E108: No such variable: \"%s\""), name);
1570 return FAIL;
1571}
1572
1573/*
1574 * Lock or unlock variable indicated by "lp".
1575 * "deep" is the levels to go (-1 for unlimited);
1576 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
1577 */
1578 static int
1579do_lock_var(
1580 lval_T *lp,
1581 char_u *name_end,
1582 int deep,
1583 int lock)
1584{
1585 int ret = OK;
1586 int cc;
1587 dictitem_T *di;
1588
1589 if (deep == 0) // nothing to do
1590 return OK;
1591
1592 if (lp->ll_tv == NULL)
1593 {
1594 cc = *name_end;
1595 *name_end = NUL;
1596
1597 // Normal name or expanded name.
1598 di = find_var(lp->ll_name, NULL, TRUE);
1599 if (di == NULL)
1600 ret = FAIL;
1601 else if ((di->di_flags & DI_FLAGS_FIX)
1602 && di->di_tv.v_type != VAR_DICT
1603 && di->di_tv.v_type != VAR_LIST)
1604 // For historic reasons this error is not given for a list or dict.
1605 // E.g., the b: dict could be locked/unlocked.
1606 semsg(_("E940: Cannot lock or unlock variable %s"), lp->ll_name);
1607 else
1608 {
1609 if (lock)
1610 di->di_flags |= DI_FLAGS_LOCK;
1611 else
1612 di->di_flags &= ~DI_FLAGS_LOCK;
1613 item_lock(&di->di_tv, deep, lock);
1614 }
1615 *name_end = cc;
1616 }
1617 else if (lp->ll_range)
1618 {
1619 listitem_T *li = lp->ll_li;
1620
1621 // (un)lock a range of List items.
1622 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
1623 {
1624 item_lock(&li->li_tv, deep, lock);
1625 li = li->li_next;
1626 ++lp->ll_n1;
1627 }
1628 }
1629 else if (lp->ll_list != NULL)
1630 // (un)lock a List item.
1631 item_lock(&lp->ll_li->li_tv, deep, lock);
1632 else
1633 // (un)lock a Dictionary item.
1634 item_lock(&lp->ll_di->di_tv, deep, lock);
1635
1636 return ret;
1637}
1638
1639/*
1640 * Lock or unlock an item. "deep" is nr of levels to go.
1641 */
1642 static void
1643item_lock(typval_T *tv, int deep, int lock)
1644{
1645 static int recurse = 0;
1646 list_T *l;
1647 listitem_T *li;
1648 dict_T *d;
1649 blob_T *b;
1650 hashitem_T *hi;
1651 int todo;
1652
1653 if (recurse >= DICT_MAXNEST)
1654 {
1655 emsg(_("E743: variable nested too deep for (un)lock"));
1656 return;
1657 }
1658 if (deep == 0)
1659 return;
1660 ++recurse;
1661
1662 // lock/unlock the item itself
1663 if (lock)
1664 tv->v_lock |= VAR_LOCKED;
1665 else
1666 tv->v_lock &= ~VAR_LOCKED;
1667
1668 switch (tv->v_type)
1669 {
1670 case VAR_UNKNOWN:
Bram 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
Bram Moolenaaraeea7212020-04-02 18:50:46 +02001701 FOR_ALL_LIST_ITEMS(l, li)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02001702 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".
Bram Moolenaar52592752020-04-03 18:43:35 +02002385 * When "varname" is empty returns curwin/curtab/etc vars dictionary.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002386 * Returns NULL if not found.
2387 */
2388 dictitem_T *
2389find_var_in_ht(
2390 hashtab_T *ht,
2391 int htname,
2392 char_u *varname,
2393 int no_autoload)
2394{
2395 hashitem_T *hi;
2396
2397 if (*varname == NUL)
2398 {
2399 // Must be something like "s:", otherwise "ht" would be NULL.
2400 switch (htname)
2401 {
2402 case 's': return &SCRIPT_SV(current_sctx.sc_sid)->sv_var;
2403 case 'g': return &globvars_var;
2404 case 'v': return &vimvars_var;
2405 case 'b': return &curbuf->b_bufvar;
2406 case 'w': return &curwin->w_winvar;
2407 case 't': return &curtab->tp_winvar;
2408 case 'l': return get_funccal_local_var();
2409 case 'a': return get_funccal_args_var();
2410 }
2411 return NULL;
2412 }
2413
2414 hi = hash_find(ht, varname);
2415 if (HASHITEM_EMPTY(hi))
2416 {
2417 // For global variables we may try auto-loading the script. If it
2418 // worked find the variable again. Don't auto-load a script if it was
2419 // loaded already, otherwise it would be loaded every time when
2420 // checking if a function name is a Funcref variable.
2421 if (ht == &globvarht && !no_autoload)
2422 {
2423 // Note: script_autoload() may make "hi" invalid. It must either
2424 // be obtained again or not used.
2425 if (!script_autoload(varname, FALSE) || aborting())
2426 return NULL;
2427 hi = hash_find(ht, varname);
2428 }
2429 if (HASHITEM_EMPTY(hi))
2430 return NULL;
2431 }
2432 return HI2DI(hi);
2433}
2434
2435/*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002436 * Get the script-local hashtab. NULL if not in a script context.
2437 */
2438 hashtab_T *
2439get_script_local_ht(void)
2440{
2441 scid_T sid = current_sctx.sc_sid;
2442
2443 if (sid > 0 && sid <= script_items.ga_len)
2444 return &SCRIPT_VARS(sid);
2445 return NULL;
2446}
2447
2448/*
2449 * Look for "name[len]" in script-local variables.
2450 * Return -1 when not found.
2451 */
2452 int
2453lookup_scriptvar(char_u *name, size_t len, cctx_T *dummy UNUSED)
2454{
2455 hashtab_T *ht = get_script_local_ht();
2456 char_u buffer[30];
2457 char_u *p;
2458 int res;
2459 hashitem_T *hi;
2460
2461 if (ht == NULL)
2462 return -1;
2463 if (len < sizeof(buffer) - 1)
2464 {
2465 vim_strncpy(buffer, name, len);
2466 p = buffer;
2467 }
2468 else
2469 {
2470 p = vim_strnsave(name, (int)len);
2471 if (p == NULL)
2472 return -1;
2473 }
2474
2475 hi = hash_find(ht, p);
2476 res = HASHITEM_EMPTY(hi) ? -1 : 1;
2477
2478 // if not script-local, then perhaps imported
Bram Moolenaar4e12a5d2020-02-03 20:50:59 +01002479 if (res == -1 && find_imported(p, 0, NULL) != NULL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002480 res = 1;
2481
2482 if (p != buffer)
2483 vim_free(p);
2484 return res;
2485}
2486
2487/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002488 * Find the hashtab used for a variable name.
2489 * Return NULL if the name is not valid.
2490 * Set "varname" to the start of name without ':'.
2491 */
2492 hashtab_T *
2493find_var_ht(char_u *name, char_u **varname)
2494{
2495 hashitem_T *hi;
2496 hashtab_T *ht;
2497
2498 if (name[0] == NUL)
2499 return NULL;
2500 if (name[1] != ':')
2501 {
2502 // The name must not start with a colon or #.
2503 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
2504 return NULL;
2505 *varname = name;
2506
2507 // "version" is "v:version" in all scopes if scriptversion < 3.
2508 // Same for a few other variables marked with VV_COMPAT.
2509 if (current_sctx.sc_version < 3)
2510 {
2511 hi = hash_find(&compat_hashtab, name);
2512 if (!HASHITEM_EMPTY(hi))
2513 return &compat_hashtab;
2514 }
2515
2516 ht = get_funccal_local_ht();
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002517 if (ht != NULL)
2518 return ht; // local variable
2519
2520 // in Vim9 script items at the script level are script-local
2521 if (current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2522 {
2523 ht = get_script_local_ht();
2524 if (ht != NULL)
2525 return ht;
2526 }
2527
2528 return &globvarht; // global variable
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002529 }
2530 *varname = name + 2;
2531 if (*name == 'g') // global variable
2532 return &globvarht;
2533 // There must be no ':' or '#' in the rest of the name, unless g: is used
2534 if (vim_strchr(name + 2, ':') != NULL
2535 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
2536 return NULL;
2537 if (*name == 'b') // buffer variable
2538 return &curbuf->b_vars->dv_hashtab;
2539 if (*name == 'w') // window variable
2540 return &curwin->w_vars->dv_hashtab;
2541 if (*name == 't') // tab page variable
2542 return &curtab->tp_vars->dv_hashtab;
2543 if (*name == 'v') // v: variable
2544 return &vimvarht;
Bram Moolenaarb35efa52020-02-26 20:15:18 +01002545 if (get_current_funccal() != NULL
2546 && get_current_funccal()->func->uf_dfunc_idx < 0)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002547 {
Bram Moolenaarb35efa52020-02-26 20:15:18 +01002548 // a: and l: are only used in functions defined with ":function"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002549 if (*name == 'a') // a: function argument
2550 return get_funccal_args_ht();
2551 if (*name == 'l') // l: local function variable
2552 return get_funccal_local_ht();
2553 }
2554 if (*name == 's') // script variable
2555 {
2556 ht = get_script_local_ht();
2557 if (ht != NULL)
2558 return ht;
2559 }
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002560 return NULL;
2561}
2562
2563/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002564 * Get the string value of a (global/local) variable.
2565 * Note: see tv_get_string() for how long the pointer remains valid.
2566 * Returns NULL when it doesn't exist.
2567 */
2568 char_u *
2569get_var_value(char_u *name)
2570{
2571 dictitem_T *v;
2572
2573 v = find_var(name, NULL, FALSE);
2574 if (v == NULL)
2575 return NULL;
2576 return tv_get_string(&v->di_tv);
2577}
2578
2579/*
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002580 * Allocate a new hashtab for a sourced script. It will be used while
2581 * sourcing this script and when executing functions defined in the script.
2582 */
2583 void
2584new_script_vars(scid_T id)
2585{
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002586 scriptvar_T *sv;
2587
Bram Moolenaar7ebcba62020-01-12 17:42:55 +01002588 sv = ALLOC_CLEAR_ONE(scriptvar_T);
2589 if (sv == NULL)
2590 return;
2591 init_var_dict(&sv->sv_dict, &sv->sv_var, VAR_SCOPE);
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002592 SCRIPT_ITEM(id)->sn_vars = sv;
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002593}
2594
2595/*
2596 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
2597 * point to it.
2598 */
2599 void
2600init_var_dict(dict_T *dict, dictitem_T *dict_var, int scope)
2601{
2602 hash_init(&dict->dv_hashtab);
2603 dict->dv_lock = 0;
2604 dict->dv_scope = scope;
2605 dict->dv_refcount = DO_NOT_FREE_CNT;
2606 dict->dv_copyID = 0;
2607 dict_var->di_tv.vval.v_dict = dict;
2608 dict_var->di_tv.v_type = VAR_DICT;
2609 dict_var->di_tv.v_lock = VAR_FIXED;
2610 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
2611 dict_var->di_key[0] = NUL;
2612}
2613
2614/*
2615 * Unreference a dictionary initialized by init_var_dict().
2616 */
2617 void
2618unref_var_dict(dict_T *dict)
2619{
Bram Moolenaar8d71b542019-08-30 15:46:30 +02002620 // Now the dict needs to be freed if no one else is using it, go back to
2621 // normal reference counting.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002622 dict->dv_refcount -= DO_NOT_FREE_CNT - 1;
2623 dict_unref(dict);
2624}
2625
2626/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002627 * Clean up a list of internal variables.
2628 * Frees all allocated variables and the value they contain.
2629 * Clears hashtab "ht", does not free it.
2630 */
2631 void
2632vars_clear(hashtab_T *ht)
2633{
2634 vars_clear_ext(ht, TRUE);
2635}
2636
2637/*
2638 * Like vars_clear(), but only free the value if "free_val" is TRUE.
2639 */
2640 void
2641vars_clear_ext(hashtab_T *ht, int free_val)
2642{
2643 int todo;
2644 hashitem_T *hi;
2645 dictitem_T *v;
2646
2647 hash_lock(ht);
2648 todo = (int)ht->ht_used;
2649 for (hi = ht->ht_array; todo > 0; ++hi)
2650 {
2651 if (!HASHITEM_EMPTY(hi))
2652 {
2653 --todo;
2654
2655 // Free the variable. Don't remove it from the hashtab,
2656 // ht_array might change then. hash_clear() takes care of it
2657 // later.
2658 v = HI2DI(hi);
2659 if (free_val)
2660 clear_tv(&v->di_tv);
2661 if (v->di_flags & DI_FLAGS_ALLOC)
2662 vim_free(v);
2663 }
2664 }
2665 hash_clear(ht);
2666 ht->ht_used = 0;
2667}
2668
2669/*
2670 * Delete a variable from hashtab "ht" at item "hi".
2671 * Clear the variable value and free the dictitem.
2672 */
Bram Moolenaarda6c0332019-09-01 16:01:30 +02002673 static void
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002674delete_var(hashtab_T *ht, hashitem_T *hi)
2675{
2676 dictitem_T *di = HI2DI(hi);
2677
2678 hash_remove(ht, hi);
2679 clear_tv(&di->di_tv);
2680 vim_free(di);
2681}
2682
2683/*
2684 * List the value of one internal variable.
2685 */
2686 static void
2687list_one_var(dictitem_T *v, char *prefix, int *first)
2688{
2689 char_u *tofree;
2690 char_u *s;
2691 char_u numbuf[NUMBUFLEN];
2692
2693 s = echo_string(&v->di_tv, &tofree, numbuf, get_copyID());
2694 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
2695 s == NULL ? (char_u *)"" : s, first);
2696 vim_free(tofree);
2697}
2698
2699 static void
2700list_one_var_a(
2701 char *prefix,
2702 char_u *name,
2703 int type,
2704 char_u *string,
2705 int *first) // when TRUE clear rest of screen and set to FALSE
2706{
2707 // don't use msg() or msg_attr() to avoid overwriting "v:statusmsg"
2708 msg_start();
2709 msg_puts(prefix);
2710 if (name != NULL) // "a:" vars don't have a name stored
2711 msg_puts((char *)name);
2712 msg_putchar(' ');
2713 msg_advance(22);
2714 if (type == VAR_NUMBER)
2715 msg_putchar('#');
2716 else if (type == VAR_FUNC || type == VAR_PARTIAL)
2717 msg_putchar('*');
2718 else if (type == VAR_LIST)
2719 {
2720 msg_putchar('[');
2721 if (*string == '[')
2722 ++string;
2723 }
2724 else if (type == VAR_DICT)
2725 {
2726 msg_putchar('{');
2727 if (*string == '{')
2728 ++string;
2729 }
2730 else
2731 msg_putchar(' ');
2732
2733 msg_outtrans(string);
2734
2735 if (type == VAR_FUNC || type == VAR_PARTIAL)
2736 msg_puts("()");
2737 if (*first)
2738 {
2739 msg_clr_eos();
2740 *first = FALSE;
2741 }
2742}
2743
2744/*
2745 * Set variable "name" to value in "tv".
2746 * If the variable already exists, the value is updated.
2747 * Otherwise the variable is created.
2748 */
2749 void
2750set_var(
2751 char_u *name,
2752 typval_T *tv,
2753 int copy) // make copy of value in "tv"
2754{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002755 set_var_const(name, NULL, tv, copy, 0);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002756}
2757
2758/*
2759 * Set variable "name" to value in "tv".
2760 * If the variable already exists and "is_const" is FALSE the value is updated.
2761 * Otherwise the variable is created.
2762 */
2763 void
2764set_var_const(
2765 char_u *name,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002766 type_T *type,
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002767 typval_T *tv,
2768 int copy, // make copy of value in "tv"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002769 int flags) // LET_IS_CONST and/or LET_NO_COMMAND
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002770{
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002771 dictitem_T *di;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002772 char_u *varname;
2773 hashtab_T *ht;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002774 int is_script_local;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002775
2776 ht = find_var_ht(name, &varname);
2777 if (ht == NULL || *varname == NUL)
2778 {
2779 semsg(_(e_illvar), name);
2780 return;
2781 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002782 is_script_local = ht == get_script_local_ht();
2783
2784 di = find_var_in_ht(ht, 0, varname, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002785
2786 // Search in parent scope which is possible to reference from lambda
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002787 if (di == NULL)
2788 di = find_var_in_scoped_ht(name, TRUE);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002789
2790 if ((tv->v_type == VAR_FUNC || tv->v_type == VAR_PARTIAL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002791 && var_check_func_name(name, di == NULL))
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002792 return;
2793
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002794 if (di != NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002795 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002796 if ((di->di_flags & DI_FLAGS_RELOAD) == 0)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002797 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002798 if (flags & LET_IS_CONST)
2799 {
2800 emsg(_(e_cannot_mod));
2801 return;
2802 }
2803
2804 if (var_check_ro(di->di_flags, name, FALSE)
2805 || var_check_lock(di->di_tv.v_lock, name, FALSE))
2806 return;
2807
2808 if ((flags & LET_NO_COMMAND) == 0
2809 && is_script_local
2810 && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2811 {
2812 semsg(_("E1041: Redefining script item %s"), name);
2813 return;
2814 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002815 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002816 else
2817 // can only redefine once
2818 di->di_flags &= ~DI_FLAGS_RELOAD;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002819
2820 // existing variable, need to clear the value
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002821
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002822 // Handle setting internal di: variables separately where needed to
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002823 // prevent changing the type.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002824 if (ht == &vimvarht)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002825 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002826 if (di->di_tv.v_type == VAR_STRING)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002827 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002828 VIM_CLEAR(di->di_tv.vval.v_string);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002829 if (copy || tv->v_type != VAR_STRING)
2830 {
2831 char_u *val = tv_get_string(tv);
2832
2833 // Careful: when assigning to v:errmsg and tv_get_string()
Bram Moolenaar4b96df52020-01-26 22:00:26 +01002834 // causes an error message the variable will already be set.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002835 if (di->di_tv.vval.v_string == NULL)
2836 di->di_tv.vval.v_string = vim_strsave(val);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002837 }
2838 else
2839 {
2840 // Take over the string to avoid an extra alloc/free.
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002841 di->di_tv.vval.v_string = tv->vval.v_string;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002842 tv->vval.v_string = NULL;
2843 }
2844 return;
2845 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002846 else if (di->di_tv.v_type == VAR_NUMBER)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002847 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002848 di->di_tv.vval.v_number = tv_get_number(tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002849 if (STRCMP(varname, "searchforward") == 0)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002850 set_search_direction(di->di_tv.vval.v_number ? '/' : '?');
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002851#ifdef FEAT_SEARCH_EXTRA
2852 else if (STRCMP(varname, "hlsearch") == 0)
2853 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002854 no_hlsearch = !di->di_tv.vval.v_number;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002855 redraw_all_later(SOME_VALID);
2856 }
2857#endif
2858 return;
2859 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002860 else if (di->di_tv.v_type != tv->v_type)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002861 {
2862 semsg(_("E963: setting %s to value with wrong type"), name);
2863 return;
2864 }
2865 }
2866
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002867 clear_tv(&di->di_tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002868 }
2869 else // add a new variable
2870 {
2871 // Can't add "v:" or "a:" variable.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02002872 if (ht == &vimvarht || ht == get_funccal_args_ht())
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002873 {
2874 semsg(_(e_illvar), name);
2875 return;
2876 }
2877
2878 // Make sure the variable name is valid.
2879 if (!valid_varname(varname))
2880 return;
2881
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002882 di = alloc(sizeof(dictitem_T) + STRLEN(varname));
2883 if (di == NULL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002884 return;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002885 STRCPY(di->di_key, varname);
2886 if (hash_add(ht, DI2HIKEY(di)) == FAIL)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002887 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002888 vim_free(di);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002889 return;
2890 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002891 di->di_flags = DI_FLAGS_ALLOC;
2892 if (flags & LET_IS_CONST)
2893 di->di_flags |= DI_FLAGS_LOCK;
2894
2895 if (is_script_local && current_sctx.sc_version == SCRIPT_VERSION_VIM9)
2896 {
Bram Moolenaar21b9e972020-01-26 19:26:46 +01002897 scriptitem_T *si = SCRIPT_ITEM(current_sctx.sc_sid);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002898
2899 // Store a pointer to the typval_T, so that it can be found by
2900 // index instead of using a hastab lookup.
2901 if (ga_grow(&si->sn_var_vals, 1) == OK)
2902 {
2903 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data)
2904 + si->sn_var_vals.ga_len;
2905 sv->sv_name = di->di_key;
2906 sv->sv_tv = &di->di_tv;
2907 sv->sv_type = type == NULL ? &t_any : type;
2908 sv->sv_const = (flags & LET_IS_CONST);
2909 sv->sv_export = is_export;
2910 ++si->sn_var_vals.ga_len;
2911
2912 // let ex_export() know the export worked.
2913 is_export = FALSE;
2914 }
2915 }
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002916 }
2917
2918 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002919 copy_tv(tv, &di->di_tv);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002920 else
2921 {
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002922 di->di_tv = *tv;
2923 di->di_tv.v_lock = 0;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002924 init_tv(tv);
2925 }
2926
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002927 if (flags & LET_IS_CONST)
2928 di->di_tv.v_lock |= VAR_LOCKED;
Bram Moolenaar0522ba02019-08-27 22:48:30 +02002929}
2930
2931/*
2932 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
2933 * Also give an error message.
2934 */
2935 int
2936var_check_ro(int flags, char_u *name, int use_gettext)
2937{
2938 if (flags & DI_FLAGS_RO)
2939 {
2940 semsg(_(e_readonlyvar), use_gettext ? (char_u *)_(name) : name);
2941 return TRUE;
2942 }
2943 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
2944 {
2945 semsg(_(e_readonlysbx), use_gettext ? (char_u *)_(name) : name);
2946 return TRUE;
2947 }
2948 return FALSE;
2949}
2950
2951/*
2952 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
2953 * Also give an error message.
2954 */
2955 int
2956var_check_fixed(int flags, char_u *name, int use_gettext)
2957{
2958 if (flags & DI_FLAGS_FIX)
2959 {
2960 semsg(_("E795: Cannot delete variable %s"),
2961 use_gettext ? (char_u *)_(name) : name);
2962 return TRUE;
2963 }
2964 return FALSE;
2965}
2966
2967/*
2968 * Check if a funcref is assigned to a valid variable name.
2969 * Return TRUE and give an error if not.
2970 */
2971 int
2972var_check_func_name(
2973 char_u *name, // points to start of variable name
2974 int new_var) // TRUE when creating the variable
2975{
2976 // Allow for w: b: s: and t:.
2977 if (!(vim_strchr((char_u *)"wbst", name[0]) != NULL && name[1] == ':')
2978 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
2979 ? name[2] : name[0]))
2980 {
2981 semsg(_("E704: Funcref variable name must start with a capital: %s"),
2982 name);
2983 return TRUE;
2984 }
2985 // Don't allow hiding a function. When "v" is not NULL we might be
2986 // assigning another function to the same var, the type is checked
2987 // below.
2988 if (new_var && function_exists(name, FALSE))
2989 {
2990 semsg(_("E705: Variable name conflicts with existing function: %s"),
2991 name);
2992 return TRUE;
2993 }
2994 return FALSE;
2995}
2996
2997/*
2998 * Return TRUE if "flags" indicates variable "name" is locked (immutable).
2999 * Also give an error message, using "name" or _("name") when use_gettext is
3000 * TRUE.
3001 */
3002 int
3003var_check_lock(int lock, char_u *name, int use_gettext)
3004{
3005 if (lock & VAR_LOCKED)
3006 {
3007 semsg(_("E741: Value is locked: %s"),
3008 name == NULL ? (char_u *)_("Unknown")
3009 : use_gettext ? (char_u *)_(name)
3010 : name);
3011 return TRUE;
3012 }
3013 if (lock & VAR_FIXED)
3014 {
3015 semsg(_("E742: Cannot change value of %s"),
3016 name == NULL ? (char_u *)_("Unknown")
3017 : use_gettext ? (char_u *)_(name)
3018 : name);
3019 return TRUE;
3020 }
3021 return FALSE;
3022}
3023
3024/*
3025 * Check if a variable name is valid.
3026 * Return FALSE and give an error if not.
3027 */
3028 int
3029valid_varname(char_u *varname)
3030{
3031 char_u *p;
3032
3033 for (p = varname; *p != NUL; ++p)
3034 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
3035 && *p != AUTOLOAD_CHAR)
3036 {
3037 semsg(_(e_illvar), varname);
3038 return FALSE;
3039 }
3040 return TRUE;
3041}
3042
3043/*
3044 * getwinvar() and gettabwinvar()
3045 */
3046 static void
3047getwinvar(
3048 typval_T *argvars,
3049 typval_T *rettv,
3050 int off) // 1 for gettabwinvar()
3051{
3052 win_T *win;
3053 char_u *varname;
3054 dictitem_T *v;
3055 tabpage_T *tp = NULL;
3056 int done = FALSE;
3057 win_T *oldcurwin;
3058 tabpage_T *oldtabpage;
3059 int need_switch_win;
3060
3061 if (off == 1)
3062 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3063 else
3064 tp = curtab;
3065 win = find_win_by_nr(&argvars[off], tp);
3066 varname = tv_get_string_chk(&argvars[off + 1]);
3067 ++emsg_off;
3068
3069 rettv->v_type = VAR_STRING;
3070 rettv->vval.v_string = NULL;
3071
3072 if (win != NULL && varname != NULL)
3073 {
3074 // Set curwin to be our win, temporarily. Also set the tabpage,
3075 // otherwise the window is not valid. Only do this when needed,
3076 // autocommands get blocked.
3077 need_switch_win = !(tp == curtab && win == curwin);
3078 if (!need_switch_win
3079 || switch_win(&oldcurwin, &oldtabpage, win, tp, TRUE) == OK)
3080 {
3081 if (*varname == '&')
3082 {
3083 if (varname[1] == NUL)
3084 {
3085 // get all window-local options in a dict
3086 dict_T *opts = get_winbuf_options(FALSE);
3087
3088 if (opts != NULL)
3089 {
3090 rettv_dict_set(rettv, opts);
3091 done = TRUE;
3092 }
3093 }
3094 else if (get_option_tv(&varname, rettv, 1) == OK)
3095 // window-local-option
3096 done = TRUE;
3097 }
3098 else
3099 {
3100 // Look up the variable.
3101 // Let getwinvar({nr}, "") return the "w:" dictionary.
3102 v = find_var_in_ht(&win->w_vars->dv_hashtab, 'w',
3103 varname, FALSE);
3104 if (v != NULL)
3105 {
3106 copy_tv(&v->di_tv, rettv);
3107 done = TRUE;
3108 }
3109 }
3110 }
3111
3112 if (need_switch_win)
3113 // restore previous notion of curwin
3114 restore_win(oldcurwin, oldtabpage, TRUE);
3115 }
3116
3117 if (!done && argvars[off + 2].v_type != VAR_UNKNOWN)
3118 // use the default return value
3119 copy_tv(&argvars[off + 2], rettv);
3120
3121 --emsg_off;
3122}
3123
3124/*
3125 * "setwinvar()" and "settabwinvar()" functions
3126 */
3127 static void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003128setwinvar(typval_T *argvars, int off)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003129{
3130 win_T *win;
3131 win_T *save_curwin;
3132 tabpage_T *save_curtab;
3133 int need_switch_win;
3134 char_u *varname, *winvarname;
3135 typval_T *varp;
3136 char_u nbuf[NUMBUFLEN];
3137 tabpage_T *tp = NULL;
3138
3139 if (check_secure())
3140 return;
3141
3142 if (off == 1)
3143 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3144 else
3145 tp = curtab;
3146 win = find_win_by_nr(&argvars[off], tp);
3147 varname = tv_get_string_chk(&argvars[off + 1]);
3148 varp = &argvars[off + 2];
3149
3150 if (win != NULL && varname != NULL && varp != NULL)
3151 {
3152 need_switch_win = !(tp == curtab && win == curwin);
3153 if (!need_switch_win
3154 || switch_win(&save_curwin, &save_curtab, win, tp, TRUE) == OK)
3155 {
3156 if (*varname == '&')
3157 {
3158 long numval;
3159 char_u *strval;
3160 int error = FALSE;
3161
3162 ++varname;
3163 numval = (long)tv_get_number_chk(varp, &error);
3164 strval = tv_get_string_buf_chk(varp, nbuf);
3165 if (!error && strval != NULL)
3166 set_option_value(varname, numval, strval, OPT_LOCAL);
3167 }
3168 else
3169 {
3170 winvarname = alloc(STRLEN(varname) + 3);
3171 if (winvarname != NULL)
3172 {
3173 STRCPY(winvarname, "w:");
3174 STRCPY(winvarname + 2, varname);
3175 set_var(winvarname, varp, TRUE);
3176 vim_free(winvarname);
3177 }
3178 }
3179 }
3180 if (need_switch_win)
3181 restore_win(save_curwin, save_curtab, TRUE);
3182 }
3183}
3184
Bram Moolenaare5cdf152019-08-29 22:09:46 +02003185/*
3186 * reset v:option_new, v:option_old, v:option_oldlocal, v:option_oldglobal,
3187 * v:option_type, and v:option_command.
3188 */
3189 void
3190reset_v_option_vars(void)
3191{
3192 set_vim_var_string(VV_OPTION_NEW, NULL, -1);
3193 set_vim_var_string(VV_OPTION_OLD, NULL, -1);
3194 set_vim_var_string(VV_OPTION_OLDLOCAL, NULL, -1);
3195 set_vim_var_string(VV_OPTION_OLDGLOBAL, NULL, -1);
3196 set_vim_var_string(VV_OPTION_TYPE, NULL, -1);
3197 set_vim_var_string(VV_OPTION_COMMAND, NULL, -1);
3198}
3199
3200/*
3201 * Add an assert error to v:errors.
3202 */
3203 void
3204assert_error(garray_T *gap)
3205{
3206 struct vimvar *vp = &vimvars[VV_ERRORS];
3207
3208 if (vp->vv_type != VAR_LIST || vimvars[VV_ERRORS].vv_list == NULL)
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003209 // Make sure v:errors is a list.
Bram Moolenaare5cdf152019-08-29 22:09:46 +02003210 set_vim_var_list(VV_ERRORS, list_alloc());
3211 list_append_string(vimvars[VV_ERRORS].vv_list, gap->ga_data, gap->ga_len);
3212}
3213
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003214 int
3215var_exists(char_u *var)
3216{
3217 char_u *name;
3218 char_u *tofree;
3219 typval_T tv;
3220 int len = 0;
3221 int n = FALSE;
3222
3223 // get_name_len() takes care of expanding curly braces
3224 name = var;
3225 len = get_name_len(&var, &tofree, TRUE, FALSE);
3226 if (len > 0)
3227 {
3228 if (tofree != NULL)
3229 name = tofree;
3230 n = (get_var_tv(name, len, &tv, NULL, FALSE, TRUE) == OK);
3231 if (n)
3232 {
3233 // handle d.key, l[idx], f(expr)
3234 n = (handle_subscript(&var, &tv, TRUE, FALSE, name, &name) == OK);
3235 if (n)
3236 clear_tv(&tv);
3237 }
3238 }
3239 if (*var != NUL)
3240 n = FALSE;
3241
3242 vim_free(tofree);
3243 return n;
3244}
3245
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003246static lval_T *redir_lval = NULL;
3247#define EVALCMD_BUSY (redir_lval == (lval_T *)&redir_lval)
3248static garray_T redir_ga; // only valid when redir_lval is not NULL
3249static char_u *redir_endp = NULL;
3250static char_u *redir_varname = NULL;
3251
3252/*
3253 * Start recording command output to a variable
3254 * When "append" is TRUE append to an existing variable.
3255 * Returns OK if successfully completed the setup. FAIL otherwise.
3256 */
3257 int
3258var_redir_start(char_u *name, int append)
3259{
3260 int save_emsg;
3261 int err;
3262 typval_T tv;
3263
3264 // Catch a bad name early.
3265 if (!eval_isnamec1(*name))
3266 {
3267 emsg(_(e_invarg));
3268 return FAIL;
3269 }
3270
3271 // Make a copy of the name, it is used in redir_lval until redir ends.
3272 redir_varname = vim_strsave(name);
3273 if (redir_varname == NULL)
3274 return FAIL;
3275
3276 redir_lval = ALLOC_CLEAR_ONE(lval_T);
3277 if (redir_lval == NULL)
3278 {
3279 var_redir_stop();
3280 return FAIL;
3281 }
3282
3283 // The output is stored in growarray "redir_ga" until redirection ends.
3284 ga_init2(&redir_ga, (int)sizeof(char), 500);
3285
3286 // Parse the variable name (can be a dict or list entry).
3287 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, 0,
3288 FNE_CHECK_START);
3289 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
3290 {
3291 clear_lval(redir_lval);
3292 if (redir_endp != NULL && *redir_endp != NUL)
3293 // Trailing characters are present after the variable name
3294 emsg(_(e_trailing));
3295 else
3296 emsg(_(e_invarg));
3297 redir_endp = NULL; // don't store a value, only cleanup
3298 var_redir_stop();
3299 return FAIL;
3300 }
3301
3302 // check if we can write to the variable: set it to or append an empty
3303 // string
3304 save_emsg = did_emsg;
3305 did_emsg = FALSE;
3306 tv.v_type = VAR_STRING;
3307 tv.vval.v_string = (char_u *)"";
3308 if (append)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003309 set_var_lval(redir_lval, redir_endp, &tv, TRUE, 0, (char_u *)".");
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003310 else
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003311 set_var_lval(redir_lval, redir_endp, &tv, TRUE, 0, (char_u *)"=");
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003312 clear_lval(redir_lval);
3313 err = did_emsg;
3314 did_emsg |= save_emsg;
3315 if (err)
3316 {
3317 redir_endp = NULL; // don't store a value, only cleanup
3318 var_redir_stop();
3319 return FAIL;
3320 }
3321
3322 return OK;
3323}
3324
3325/*
3326 * Append "value[value_len]" to the variable set by var_redir_start().
3327 * The actual appending is postponed until redirection ends, because the value
3328 * appended may in fact be the string we write to, changing it may cause freed
3329 * memory to be used:
3330 * :redir => foo
3331 * :let foo
3332 * :redir END
3333 */
3334 void
3335var_redir_str(char_u *value, int value_len)
3336{
3337 int len;
3338
3339 if (redir_lval == NULL)
3340 return;
3341
3342 if (value_len == -1)
3343 len = (int)STRLEN(value); // Append the entire string
3344 else
3345 len = value_len; // Append only "value_len" characters
3346
3347 if (ga_grow(&redir_ga, len) == OK)
3348 {
3349 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
3350 redir_ga.ga_len += len;
3351 }
3352 else
3353 var_redir_stop();
3354}
3355
3356/*
3357 * Stop redirecting command output to a variable.
3358 * Frees the allocated memory.
3359 */
3360 void
3361var_redir_stop(void)
3362{
3363 typval_T tv;
3364
3365 if (EVALCMD_BUSY)
3366 {
3367 redir_lval = NULL;
3368 return;
3369 }
3370
3371 if (redir_lval != NULL)
3372 {
3373 // If there was no error: assign the text to the variable.
3374 if (redir_endp != NULL)
3375 {
3376 ga_append(&redir_ga, NUL); // Append the trailing NUL.
3377 tv.v_type = VAR_STRING;
3378 tv.vval.v_string = redir_ga.ga_data;
3379 // Call get_lval() again, if it's inside a Dict or List it may
3380 // have changed.
3381 redir_endp = get_lval(redir_varname, NULL, redir_lval,
3382 FALSE, FALSE, 0, FNE_CHECK_START);
3383 if (redir_endp != NULL && redir_lval->ll_name != NULL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003384 set_var_lval(redir_lval, redir_endp, &tv, FALSE, 0,
Bram Moolenaarda6c0332019-09-01 16:01:30 +02003385 (char_u *)".");
3386 clear_lval(redir_lval);
3387 }
3388
3389 // free the collected output
3390 VIM_CLEAR(redir_ga.ga_data);
3391
3392 VIM_CLEAR(redir_lval);
3393 }
3394 VIM_CLEAR(redir_varname);
3395}
3396
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003397/*
3398 * "gettabvar()" function
3399 */
3400 void
3401f_gettabvar(typval_T *argvars, typval_T *rettv)
3402{
3403 win_T *oldcurwin;
3404 tabpage_T *tp, *oldtabpage;
3405 dictitem_T *v;
3406 char_u *varname;
3407 int done = FALSE;
3408
3409 rettv->v_type = VAR_STRING;
3410 rettv->vval.v_string = NULL;
3411
3412 varname = tv_get_string_chk(&argvars[1]);
3413 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3414 if (tp != NULL && varname != NULL)
3415 {
3416 // Set tp to be our tabpage, temporarily. Also set the window to the
3417 // first window in the tabpage, otherwise the window is not valid.
3418 if (switch_win(&oldcurwin, &oldtabpage,
3419 tp == curtab || tp->tp_firstwin == NULL ? firstwin
3420 : tp->tp_firstwin, tp, TRUE) == OK)
3421 {
3422 // look up the variable
3423 // Let gettabvar({nr}, "") return the "t:" dictionary.
3424 v = find_var_in_ht(&tp->tp_vars->dv_hashtab, 't', varname, FALSE);
3425 if (v != NULL)
3426 {
3427 copy_tv(&v->di_tv, rettv);
3428 done = TRUE;
3429 }
3430 }
3431
3432 // restore previous notion of curwin
3433 restore_win(oldcurwin, oldtabpage, TRUE);
3434 }
3435
3436 if (!done && argvars[2].v_type != VAR_UNKNOWN)
3437 copy_tv(&argvars[2], rettv);
3438}
3439
3440/*
3441 * "gettabwinvar()" function
3442 */
3443 void
3444f_gettabwinvar(typval_T *argvars, typval_T *rettv)
3445{
3446 getwinvar(argvars, rettv, 1);
3447}
3448
3449/*
3450 * "getwinvar()" function
3451 */
3452 void
3453f_getwinvar(typval_T *argvars, typval_T *rettv)
3454{
3455 getwinvar(argvars, rettv, 0);
3456}
3457
3458/*
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003459 * "getbufvar()" function
3460 */
3461 void
3462f_getbufvar(typval_T *argvars, typval_T *rettv)
3463{
3464 buf_T *buf;
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003465 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 {
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003479 if (*varname == '&')
3480 {
Bram Moolenaar86015452020-03-29 15:12:15 +02003481 buf_T *save_curbuf = curbuf;
3482
3483 // set curbuf to be our buf, temporarily
3484 curbuf = buf;
3485
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003486 if (varname[1] == NUL)
3487 {
3488 // get all buffer-local options in a dict
3489 dict_T *opts = get_winbuf_options(TRUE);
3490
3491 if (opts != NULL)
3492 {
3493 rettv_dict_set(rettv, opts);
3494 done = TRUE;
3495 }
3496 }
3497 else if (get_option_tv(&varname, rettv, TRUE) == OK)
3498 // buffer-local-option
3499 done = TRUE;
Bram Moolenaar86015452020-03-29 15:12:15 +02003500
3501 // restore previous notion of curbuf
3502 curbuf = save_curbuf;
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003503 }
3504 else
3505 {
3506 // Look up the variable.
Bram Moolenaar52592752020-04-03 18:43:35 +02003507 if (*varname == NUL)
3508 // Let getbufvar({nr}, "") return the "b:" dictionary.
3509 v = &buf->b_bufvar;
3510 else
3511 v = find_var_in_ht(&buf->b_vars->dv_hashtab, 'b',
3512 varname, FALSE);
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003513 if (v != NULL)
3514 {
3515 copy_tv(&v->di_tv, rettv);
3516 done = TRUE;
3517 }
3518 }
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003519 }
3520
3521 if (!done && argvars[2].v_type != VAR_UNKNOWN)
3522 // use the default value
3523 copy_tv(&argvars[2], rettv);
3524
3525 --emsg_off;
3526}
3527
3528/*
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003529 * "settabvar()" function
3530 */
3531 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003532f_settabvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003533{
3534 tabpage_T *save_curtab;
3535 tabpage_T *tp;
3536 char_u *varname, *tabvarname;
3537 typval_T *varp;
3538
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003539 if (check_secure())
3540 return;
3541
3542 tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
3543 varname = tv_get_string_chk(&argvars[1]);
3544 varp = &argvars[2];
3545
3546 if (varname != NULL && varp != NULL && tp != NULL)
3547 {
3548 save_curtab = curtab;
3549 goto_tabpage_tp(tp, FALSE, FALSE);
3550
3551 tabvarname = alloc(STRLEN(varname) + 3);
3552 if (tabvarname != NULL)
3553 {
3554 STRCPY(tabvarname, "t:");
3555 STRCPY(tabvarname + 2, varname);
3556 set_var(tabvarname, varp, TRUE);
3557 vim_free(tabvarname);
3558 }
3559
3560 // Restore current tabpage
3561 if (valid_tabpage(save_curtab))
3562 goto_tabpage_tp(save_curtab, FALSE, FALSE);
3563 }
3564}
3565
3566/*
3567 * "settabwinvar()" function
3568 */
3569 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003570f_settabwinvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003571{
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003572 setwinvar(argvars, 1);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003573}
3574
3575/*
3576 * "setwinvar()" function
3577 */
3578 void
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003579f_setwinvar(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003580{
Bram Moolenaar3d8a5132020-01-04 16:13:49 +01003581 setwinvar(argvars, 0);
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003582}
3583
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003584/*
3585 * "setbufvar()" function
3586 */
3587 void
3588f_setbufvar(typval_T *argvars, typval_T *rettv UNUSED)
3589{
3590 buf_T *buf;
3591 char_u *varname, *bufvarname;
3592 typval_T *varp;
3593 char_u nbuf[NUMBUFLEN];
3594
3595 if (check_secure())
3596 return;
3597 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
3598 varname = tv_get_string_chk(&argvars[1]);
3599 buf = tv_get_buf(&argvars[0], FALSE);
3600 varp = &argvars[2];
3601
3602 if (buf != NULL && varname != NULL && varp != NULL)
3603 {
3604 if (*varname == '&')
3605 {
3606 long numval;
3607 char_u *strval;
3608 int error = FALSE;
3609 aco_save_T aco;
3610
3611 // set curbuf to be our buf, temporarily
3612 aucmd_prepbuf(&aco, buf);
3613
3614 ++varname;
3615 numval = (long)tv_get_number_chk(varp, &error);
3616 strval = tv_get_string_buf_chk(varp, nbuf);
3617 if (!error && strval != NULL)
3618 set_option_value(varname, numval, strval, OPT_LOCAL);
3619
3620 // reset notion of buffer
3621 aucmd_restbuf(&aco);
3622 }
3623 else
3624 {
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003625 bufvarname = alloc(STRLEN(varname) + 3);
3626 if (bufvarname != NULL)
3627 {
Bram Moolenaar86015452020-03-29 15:12:15 +02003628 buf_T *save_curbuf = curbuf;
3629
Bram Moolenaar8d71b542019-08-30 15:46:30 +02003630 curbuf = buf;
3631 STRCPY(bufvarname, "b:");
3632 STRCPY(bufvarname + 2, varname);
3633 set_var(bufvarname, varp, TRUE);
3634 vim_free(bufvarname);
3635 curbuf = save_curbuf;
3636 }
3637 }
3638 }
3639}
3640
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003641/*
3642 * Get a callback from "arg". It can be a Funcref or a function name.
3643 * When "arg" is zero return an empty string.
3644 * "cb_name" is not allocated.
3645 * "cb_name" is set to NULL for an invalid argument.
3646 */
3647 callback_T
3648get_callback(typval_T *arg)
3649{
Bram Moolenaar14e579092020-03-07 16:59:25 +01003650 callback_T res;
3651 int r = OK;
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003652
3653 res.cb_free_name = FALSE;
3654 if (arg->v_type == VAR_PARTIAL && arg->vval.v_partial != NULL)
3655 {
3656 res.cb_partial = arg->vval.v_partial;
3657 ++res.cb_partial->pt_refcount;
3658 res.cb_name = partial_name(res.cb_partial);
3659 }
3660 else
3661 {
3662 res.cb_partial = NULL;
Bram Moolenaar14e579092020-03-07 16:59:25 +01003663 if (arg->v_type == VAR_STRING && arg->vval.v_string != NULL
3664 && isdigit(*arg->vval.v_string))
3665 r = FAIL;
3666 else if (arg->v_type == VAR_FUNC || arg->v_type == VAR_STRING)
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003667 {
3668 // Note that we don't make a copy of the string.
3669 res.cb_name = arg->vval.v_string;
3670 func_ref(res.cb_name);
3671 }
3672 else if (arg->v_type == VAR_NUMBER && arg->vval.v_number == 0)
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003673 res.cb_name = (char_u *)"";
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003674 else
Bram Moolenaar14e579092020-03-07 16:59:25 +01003675 r = FAIL;
3676
3677 if (r == FAIL)
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02003678 {
3679 emsg(_("E921: Invalid callback argument"));
3680 res.cb_name = NULL;
3681 }
3682 }
3683 return res;
3684}
3685
3686/*
3687 * Copy a callback into a typval_T.
3688 */
3689 void
3690put_callback(callback_T *cb, typval_T *tv)
3691{
3692 if (cb->cb_partial != NULL)
3693 {
3694 tv->v_type = VAR_PARTIAL;
3695 tv->vval.v_partial = cb->cb_partial;
3696 ++tv->vval.v_partial->pt_refcount;
3697 }
3698 else
3699 {
3700 tv->v_type = VAR_FUNC;
3701 tv->vval.v_string = vim_strsave(cb->cb_name);
3702 func_ref(cb->cb_name);
3703 }
3704}
3705
3706/*
3707 * Make a copy of "src" into "dest", allocating the function name if needed,
3708 * without incrementing the refcount.
3709 */
3710 void
3711set_callback(callback_T *dest, callback_T *src)
3712{
3713 if (src->cb_partial == NULL)
3714 {
3715 // just a function name, make a copy
3716 dest->cb_name = vim_strsave(src->cb_name);
3717 dest->cb_free_name = TRUE;
3718 }
3719 else
3720 {
3721 // cb_name is a pointer into cb_partial
3722 dest->cb_name = src->cb_name;
3723 dest->cb_free_name = FALSE;
3724 }
3725 dest->cb_partial = src->cb_partial;
3726}
3727
3728/*
3729 * Unref/free "callback" returned by get_callback() or set_callback().
3730 */
3731 void
3732free_callback(callback_T *callback)
3733{
3734 if (callback->cb_partial != NULL)
3735 {
3736 partial_unref(callback->cb_partial);
3737 callback->cb_partial = NULL;
3738 }
3739 else if (callback->cb_name != NULL)
3740 func_unref(callback->cb_name);
3741 if (callback->cb_free_name)
3742 {
3743 vim_free(callback->cb_name);
3744 callback->cb_free_name = FALSE;
3745 }
3746 callback->cb_name = NULL;
3747}
3748
Bram Moolenaar0522ba02019-08-27 22:48:30 +02003749#endif // FEAT_EVAL