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