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