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