xref: /vim-8.2.3635/src/eval.c (revision 6ef8f9ea)
1 /* 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  * eval.c: Expression evaluation.
12  */
13 #define USING_FLOAT_STUFF
14 
15 #include "vim.h"
16 
17 #if defined(FEAT_EVAL) || defined(PROTO)
18 
19 #ifdef VMS
20 # include <float.h>
21 #endif
22 
23 #define DICT_MAXNEST 100	/* maximum nesting of lists and dicts */
24 
25 static char *e_letunexp	= N_("E18: Unexpected characters in :let");
26 static char *e_undefvar = N_("E121: Undefined variable: %s");
27 static char *e_missbrac = N_("E111: Missing ']'");
28 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
29 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
30 static char *e_illvar = N_("E461: Illegal variable name: %s");
31 #ifdef FEAT_FLOAT
32 static char *e_float_as_string = N_("E806: using Float as a String");
33 #endif
34 
35 #define NAMESPACE_CHAR	(char_u *)"abglstvw"
36 
37 static dictitem_T	globvars_var;		/* variable used for g: */
38 #define globvarht globvardict.dv_hashtab
39 
40 /*
41  * Old Vim variables such as "v:version" are also available without the "v:".
42  * Also in functions.  We need a special hashtable for them.
43  */
44 static hashtab_T	compat_hashtab;
45 
46 /*
47  * When recursively copying lists and dicts we need to remember which ones we
48  * have done to avoid endless recursiveness.  This unique ID is used for that.
49  * The last bit is used for previous_funccal, ignored when comparing.
50  */
51 static int current_copyID = 0;
52 
53 /*
54  * Array to hold the hashtab with variables local to each sourced script.
55  * Each item holds a variable (nameless) that points to the dict_T.
56  */
57 typedef struct
58 {
59     dictitem_T	sv_var;
60     dict_T	sv_dict;
61 } scriptvar_T;
62 
63 static garray_T	    ga_scripts = {0, 0, sizeof(scriptvar_T *), 4, NULL};
64 #define SCRIPT_SV(id) (((scriptvar_T **)ga_scripts.ga_data)[(id) - 1])
65 #define SCRIPT_VARS(id) (SCRIPT_SV(id)->sv_dict.dv_hashtab)
66 
67 static int echo_attr = 0;   /* attributes used for ":echo" */
68 
69 /* The names of packages that once were loaded are remembered. */
70 static garray_T		ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
71 
72 /*
73  * Info used by a ":for" loop.
74  */
75 typedef struct
76 {
77     int		fi_semicolon;	/* TRUE if ending in '; var]' */
78     int		fi_varcount;	/* nr of variables in the list */
79     listwatch_T	fi_lw;		/* keep an eye on the item used. */
80     list_T	*fi_list;	/* list being used */
81     int		fi_bi;		/* index of blob */
82     blob_T	*fi_blob;	/* blob being used */
83 } forinfo_T;
84 
85 
86 /*
87  * Array to hold the value of v: variables.
88  * The value is in a dictitem, so that it can also be used in the v: scope.
89  * The reason to use this table anyway is for very quick access to the
90  * variables with the VV_ defines.
91  */
92 
93 /* values for vv_flags: */
94 #define VV_COMPAT	1	/* compatible, also used without "v:" */
95 #define VV_RO		2	/* read-only */
96 #define VV_RO_SBX	4	/* read-only in the sandbox */
97 
98 #define VV_NAME(s, t)	s, {{t, 0, {0}}, 0, {0}}
99 
100 static struct vimvar
101 {
102     char	*vv_name;	/* name of variable, without v: */
103     dictitem16_T vv_di;		/* value and name for key (max 16 chars!) */
104     char	vv_flags;	/* VV_COMPAT, VV_RO, VV_RO_SBX */
105 } vimvars[VV_LEN] =
106 {
107     /*
108      * The order here must match the VV_ defines in vim.h!
109      * Initializing a union does not work, leave tv.vval empty to get zero's.
110      */
111     {VV_NAME("count",		 VAR_NUMBER), VV_COMPAT+VV_RO},
112     {VV_NAME("count1",		 VAR_NUMBER), VV_RO},
113     {VV_NAME("prevcount",	 VAR_NUMBER), VV_RO},
114     {VV_NAME("errmsg",		 VAR_STRING), VV_COMPAT},
115     {VV_NAME("warningmsg",	 VAR_STRING), 0},
116     {VV_NAME("statusmsg",	 VAR_STRING), 0},
117     {VV_NAME("shell_error",	 VAR_NUMBER), VV_COMPAT+VV_RO},
118     {VV_NAME("this_session",	 VAR_STRING), VV_COMPAT},
119     {VV_NAME("version",		 VAR_NUMBER), VV_COMPAT+VV_RO},
120     {VV_NAME("lnum",		 VAR_NUMBER), VV_RO_SBX},
121     {VV_NAME("termresponse",	 VAR_STRING), VV_RO},
122     {VV_NAME("fname",		 VAR_STRING), VV_RO},
123     {VV_NAME("lang",		 VAR_STRING), VV_RO},
124     {VV_NAME("lc_time",		 VAR_STRING), VV_RO},
125     {VV_NAME("ctype",		 VAR_STRING), VV_RO},
126     {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
127     {VV_NAME("charconvert_to",	 VAR_STRING), VV_RO},
128     {VV_NAME("fname_in",	 VAR_STRING), VV_RO},
129     {VV_NAME("fname_out",	 VAR_STRING), VV_RO},
130     {VV_NAME("fname_new",	 VAR_STRING), VV_RO},
131     {VV_NAME("fname_diff",	 VAR_STRING), VV_RO},
132     {VV_NAME("cmdarg",		 VAR_STRING), VV_RO},
133     {VV_NAME("foldstart",	 VAR_NUMBER), VV_RO_SBX},
134     {VV_NAME("foldend",		 VAR_NUMBER), VV_RO_SBX},
135     {VV_NAME("folddashes",	 VAR_STRING), VV_RO_SBX},
136     {VV_NAME("foldlevel",	 VAR_NUMBER), VV_RO_SBX},
137     {VV_NAME("progname",	 VAR_STRING), VV_RO},
138     {VV_NAME("servername",	 VAR_STRING), VV_RO},
139     {VV_NAME("dying",		 VAR_NUMBER), VV_RO},
140     {VV_NAME("exception",	 VAR_STRING), VV_RO},
141     {VV_NAME("throwpoint",	 VAR_STRING), VV_RO},
142     {VV_NAME("register",	 VAR_STRING), VV_RO},
143     {VV_NAME("cmdbang",		 VAR_NUMBER), VV_RO},
144     {VV_NAME("insertmode",	 VAR_STRING), VV_RO},
145     {VV_NAME("val",		 VAR_UNKNOWN), VV_RO},
146     {VV_NAME("key",		 VAR_UNKNOWN), VV_RO},
147     {VV_NAME("profiling",	 VAR_NUMBER), VV_RO},
148     {VV_NAME("fcs_reason",	 VAR_STRING), VV_RO},
149     {VV_NAME("fcs_choice",	 VAR_STRING), 0},
150     {VV_NAME("beval_bufnr",	 VAR_NUMBER), VV_RO},
151     {VV_NAME("beval_winnr",	 VAR_NUMBER), VV_RO},
152     {VV_NAME("beval_winid",	 VAR_NUMBER), VV_RO},
153     {VV_NAME("beval_lnum",	 VAR_NUMBER), VV_RO},
154     {VV_NAME("beval_col",	 VAR_NUMBER), VV_RO},
155     {VV_NAME("beval_text",	 VAR_STRING), VV_RO},
156     {VV_NAME("scrollstart",	 VAR_STRING), 0},
157     {VV_NAME("swapname",	 VAR_STRING), VV_RO},
158     {VV_NAME("swapchoice",	 VAR_STRING), 0},
159     {VV_NAME("swapcommand",	 VAR_STRING), VV_RO},
160     {VV_NAME("char",		 VAR_STRING), 0},
161     {VV_NAME("mouse_win",	 VAR_NUMBER), 0},
162     {VV_NAME("mouse_winid",	 VAR_NUMBER), 0},
163     {VV_NAME("mouse_lnum",	 VAR_NUMBER), 0},
164     {VV_NAME("mouse_col",	 VAR_NUMBER), 0},
165     {VV_NAME("operator",	 VAR_STRING), VV_RO},
166     {VV_NAME("searchforward",	 VAR_NUMBER), 0},
167     {VV_NAME("hlsearch",	 VAR_NUMBER), 0},
168     {VV_NAME("oldfiles",	 VAR_LIST), 0},
169     {VV_NAME("windowid",	 VAR_NUMBER), VV_RO},
170     {VV_NAME("progpath",	 VAR_STRING), VV_RO},
171     {VV_NAME("completed_item",	 VAR_DICT), VV_RO},
172     {VV_NAME("option_new",	 VAR_STRING), VV_RO},
173     {VV_NAME("option_old",	 VAR_STRING), VV_RO},
174     {VV_NAME("option_type",	 VAR_STRING), VV_RO},
175     {VV_NAME("errors",		 VAR_LIST), 0},
176     {VV_NAME("false",		 VAR_SPECIAL), VV_RO},
177     {VV_NAME("true",		 VAR_SPECIAL), VV_RO},
178     {VV_NAME("null",		 VAR_SPECIAL), VV_RO},
179     {VV_NAME("none",		 VAR_SPECIAL), VV_RO},
180     {VV_NAME("vim_did_enter",	 VAR_NUMBER), VV_RO},
181     {VV_NAME("testing",		 VAR_NUMBER), 0},
182     {VV_NAME("t_number",	 VAR_NUMBER), VV_RO},
183     {VV_NAME("t_string",	 VAR_NUMBER), VV_RO},
184     {VV_NAME("t_func",		 VAR_NUMBER), VV_RO},
185     {VV_NAME("t_list",		 VAR_NUMBER), VV_RO},
186     {VV_NAME("t_dict",		 VAR_NUMBER), VV_RO},
187     {VV_NAME("t_float",		 VAR_NUMBER), VV_RO},
188     {VV_NAME("t_bool",		 VAR_NUMBER), VV_RO},
189     {VV_NAME("t_none",		 VAR_NUMBER), VV_RO},
190     {VV_NAME("t_job",		 VAR_NUMBER), VV_RO},
191     {VV_NAME("t_channel",	 VAR_NUMBER), VV_RO},
192     {VV_NAME("t_blob",		 VAR_NUMBER), VV_RO},
193     {VV_NAME("termrfgresp",	 VAR_STRING), VV_RO},
194     {VV_NAME("termrbgresp",	 VAR_STRING), VV_RO},
195     {VV_NAME("termu7resp",	 VAR_STRING), VV_RO},
196     {VV_NAME("termstyleresp",	VAR_STRING), VV_RO},
197     {VV_NAME("termblinkresp",	VAR_STRING), VV_RO},
198     {VV_NAME("event",		VAR_DICT), VV_RO},
199 };
200 
201 /* shorthand */
202 #define vv_type		vv_di.di_tv.v_type
203 #define vv_nr		vv_di.di_tv.vval.v_number
204 #define vv_float	vv_di.di_tv.vval.v_float
205 #define vv_str		vv_di.di_tv.vval.v_string
206 #define vv_list		vv_di.di_tv.vval.v_list
207 #define vv_dict		vv_di.di_tv.vval.v_dict
208 #define vv_blob		vv_di.di_tv.vval.v_blob
209 #define vv_tv		vv_di.di_tv
210 
211 static dictitem_T	vimvars_var;		/* variable used for v: */
212 #define vimvarht  vimvardict.dv_hashtab
213 
214 static int ex_let_vars(char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars);
215 static char_u *skip_var_list(char_u *arg, int *var_count, int *semicolon);
216 static char_u *skip_var_one(char_u *arg);
217 static void list_glob_vars(int *first);
218 static void list_buf_vars(int *first);
219 static void list_win_vars(int *first);
220 static void list_tab_vars(int *first);
221 static void list_vim_vars(int *first);
222 static void list_script_vars(int *first);
223 static char_u *list_arg_vars(exarg_T *eap, char_u *arg, int *first);
224 static char_u *ex_let_one(char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op);
225 static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op);
226 static int tv_op(typval_T *tv1, typval_T *tv2, char_u  *op);
227 static void ex_unletlock(exarg_T *eap, char_u *argstart, int deep);
228 static int do_unlet_var(lval_T *lp, char_u *name_end, int forceit);
229 static int do_lock_var(lval_T *lp, char_u *name_end, int deep, int lock);
230 static void item_lock(typval_T *tv, int deep, int lock);
231 
232 static int eval2(char_u **arg, typval_T *rettv, int evaluate);
233 static int eval3(char_u **arg, typval_T *rettv, int evaluate);
234 static int eval4(char_u **arg, typval_T *rettv, int evaluate);
235 static int eval5(char_u **arg, typval_T *rettv, int evaluate);
236 static int eval6(char_u **arg, typval_T *rettv, int evaluate, int want_string);
237 static int eval7(char_u **arg, typval_T *rettv, int evaluate, int want_string);
238 
239 static int get_string_tv(char_u **arg, typval_T *rettv, int evaluate);
240 static int get_lit_string_tv(char_u **arg, typval_T *rettv, int evaluate);
241 static int free_unref_items(int copyID);
242 static int get_env_tv(char_u **arg, typval_T *rettv, int evaluate);
243 static int get_env_len(char_u **arg);
244 static char_u * make_expanded_name(char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end);
245 static void check_vars(char_u *name, int len);
246 static typval_T *alloc_string_tv(char_u *string);
247 static void delete_var(hashtab_T *ht, hashitem_T *hi);
248 static void list_one_var(dictitem_T *v, char *prefix, int *first);
249 static void list_one_var_a(char *prefix, char_u *name, int type, char_u *string, int *first);
250 static int tv_check_lock(typval_T *tv, char_u *name, int use_gettext);
251 static char_u *find_option_end(char_u **arg, int *opt_flags);
252 
253 /* for VIM_VERSION_ defines */
254 #include "version.h"
255 
256 
257 #if defined(EBCDIC) || defined(PROTO)
258 /*
259  * Compare struct fst by function name.
260  */
261     static int
262 compare_func_name(const void *s1, const void *s2)
263 {
264     struct fst *p1 = (struct fst *)s1;
265     struct fst *p2 = (struct fst *)s2;
266 
267     return STRCMP(p1->f_name, p2->f_name);
268 }
269 
270 /*
271  * Sort the function table by function name.
272  * The sorting of the table above is ASCII dependent.
273  * On machines using EBCDIC we have to sort it.
274  */
275     static void
276 sortFunctions(void)
277 {
278     int		funcCnt = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
279 
280     qsort(functions, (size_t)funcCnt, sizeof(struct fst), compare_func_name);
281 }
282 #endif
283 
284 
285 /*
286  * Initialize the global and v: variables.
287  */
288     void
289 eval_init(void)
290 {
291     int		    i;
292     struct vimvar   *p;
293 
294     init_var_dict(&globvardict, &globvars_var, VAR_DEF_SCOPE);
295     init_var_dict(&vimvardict, &vimvars_var, VAR_SCOPE);
296     vimvardict.dv_lock = VAR_FIXED;
297     hash_init(&compat_hashtab);
298     func_init();
299 
300     for (i = 0; i < VV_LEN; ++i)
301     {
302 	p = &vimvars[i];
303 	if (STRLEN(p->vv_name) > 16)
304 	{
305 	    iemsg("INTERNAL: name too long, increase size of dictitem16_T");
306 	    getout(1);
307 	}
308 	STRCPY(p->vv_di.di_key, p->vv_name);
309 	if (p->vv_flags & VV_RO)
310 	    p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
311 	else if (p->vv_flags & VV_RO_SBX)
312 	    p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
313 	else
314 	    p->vv_di.di_flags = DI_FLAGS_FIX;
315 
316 	/* add to v: scope dict, unless the value is not always available */
317 	if (p->vv_type != VAR_UNKNOWN)
318 	    hash_add(&vimvarht, p->vv_di.di_key);
319 	if (p->vv_flags & VV_COMPAT)
320 	    /* add to compat scope dict */
321 	    hash_add(&compat_hashtab, p->vv_di.di_key);
322     }
323     vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
324 
325     set_vim_var_nr(VV_SEARCHFORWARD, 1L);
326     set_vim_var_nr(VV_HLSEARCH, 1L);
327     set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
328     set_vim_var_list(VV_ERRORS, list_alloc());
329     set_vim_var_dict(VV_EVENT, dict_alloc_lock(VAR_FIXED));
330 
331     set_vim_var_nr(VV_FALSE, VVAL_FALSE);
332     set_vim_var_nr(VV_TRUE, VVAL_TRUE);
333     set_vim_var_nr(VV_NONE, VVAL_NONE);
334     set_vim_var_nr(VV_NULL, VVAL_NULL);
335 
336     set_vim_var_nr(VV_TYPE_NUMBER,  VAR_TYPE_NUMBER);
337     set_vim_var_nr(VV_TYPE_STRING,  VAR_TYPE_STRING);
338     set_vim_var_nr(VV_TYPE_FUNC,    VAR_TYPE_FUNC);
339     set_vim_var_nr(VV_TYPE_LIST,    VAR_TYPE_LIST);
340     set_vim_var_nr(VV_TYPE_DICT,    VAR_TYPE_DICT);
341     set_vim_var_nr(VV_TYPE_FLOAT,   VAR_TYPE_FLOAT);
342     set_vim_var_nr(VV_TYPE_BOOL,    VAR_TYPE_BOOL);
343     set_vim_var_nr(VV_TYPE_NONE,    VAR_TYPE_NONE);
344     set_vim_var_nr(VV_TYPE_JOB,     VAR_TYPE_JOB);
345     set_vim_var_nr(VV_TYPE_CHANNEL, VAR_TYPE_CHANNEL);
346     set_vim_var_nr(VV_TYPE_BLOB,    VAR_TYPE_BLOB);
347 
348     set_reg_var(0);  /* default for v:register is not 0 but '"' */
349 
350 #ifdef EBCDIC
351     /*
352      * Sort the function table, to enable binary search.
353      */
354     sortFunctions();
355 #endif
356 }
357 
358 #if defined(EXITFREE) || defined(PROTO)
359     void
360 eval_clear(void)
361 {
362     int		    i;
363     struct vimvar   *p;
364 
365     for (i = 0; i < VV_LEN; ++i)
366     {
367 	p = &vimvars[i];
368 	if (p->vv_di.di_tv.v_type == VAR_STRING)
369 	    VIM_CLEAR(p->vv_str);
370 	else if (p->vv_di.di_tv.v_type == VAR_LIST)
371 	{
372 	    list_unref(p->vv_list);
373 	    p->vv_list = NULL;
374 	}
375     }
376     hash_clear(&vimvarht);
377     hash_init(&vimvarht);  /* garbage_collect() will access it */
378     hash_clear(&compat_hashtab);
379 
380     free_scriptnames();
381 # if defined(FEAT_CMDL_COMPL)
382     free_locales();
383 # endif
384 
385     /* global variables */
386     vars_clear(&globvarht);
387 
388     /* autoloaded script names */
389     ga_clear_strings(&ga_loaded);
390 
391     /* Script-local variables. First clear all the variables and in a second
392      * loop free the scriptvar_T, because a variable in one script might hold
393      * a reference to the whole scope of another script. */
394     for (i = 1; i <= ga_scripts.ga_len; ++i)
395 	vars_clear(&SCRIPT_VARS(i));
396     for (i = 1; i <= ga_scripts.ga_len; ++i)
397 	vim_free(SCRIPT_SV(i));
398     ga_clear(&ga_scripts);
399 
400     /* unreferenced lists and dicts */
401     (void)garbage_collect(FALSE);
402 
403     /* functions */
404     free_all_functions();
405 }
406 #endif
407 
408 
409 /*
410  * Set an internal variable to a string value. Creates the variable if it does
411  * not already exist.
412  */
413     void
414 set_internal_string_var(char_u *name, char_u *value)
415 {
416     char_u	*val;
417     typval_T	*tvp;
418 
419     val = vim_strsave(value);
420     if (val != NULL)
421     {
422 	tvp = alloc_string_tv(val);
423 	if (tvp != NULL)
424 	{
425 	    set_var(name, tvp, FALSE);
426 	    free_tv(tvp);
427 	}
428     }
429 }
430 
431 static lval_T	*redir_lval = NULL;
432 #define EVALCMD_BUSY (redir_lval == (lval_T *)&redir_lval)
433 static garray_T redir_ga;	/* only valid when redir_lval is not NULL */
434 static char_u	*redir_endp = NULL;
435 static char_u	*redir_varname = NULL;
436 
437 /*
438  * Start recording command output to a variable
439  * When "append" is TRUE append to an existing variable.
440  * Returns OK if successfully completed the setup.  FAIL otherwise.
441  */
442     int
443 var_redir_start(char_u *name, int append)
444 {
445     int		save_emsg;
446     int		err;
447     typval_T	tv;
448 
449     /* Catch a bad name early. */
450     if (!eval_isnamec1(*name))
451     {
452 	emsg(_(e_invarg));
453 	return FAIL;
454     }
455 
456     /* Make a copy of the name, it is used in redir_lval until redir ends. */
457     redir_varname = vim_strsave(name);
458     if (redir_varname == NULL)
459 	return FAIL;
460 
461     redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
462     if (redir_lval == NULL)
463     {
464 	var_redir_stop();
465 	return FAIL;
466     }
467 
468     /* The output is stored in growarray "redir_ga" until redirection ends. */
469     ga_init2(&redir_ga, (int)sizeof(char), 500);
470 
471     /* Parse the variable name (can be a dict or list entry). */
472     redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, 0,
473 							     FNE_CHECK_START);
474     if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
475     {
476 	clear_lval(redir_lval);
477 	if (redir_endp != NULL && *redir_endp != NUL)
478 	    /* Trailing characters are present after the variable name */
479 	    emsg(_(e_trailing));
480 	else
481 	    emsg(_(e_invarg));
482 	redir_endp = NULL;  /* don't store a value, only cleanup */
483 	var_redir_stop();
484 	return FAIL;
485     }
486 
487     /* check if we can write to the variable: set it to or append an empty
488      * string */
489     save_emsg = did_emsg;
490     did_emsg = FALSE;
491     tv.v_type = VAR_STRING;
492     tv.vval.v_string = (char_u *)"";
493     if (append)
494 	set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
495     else
496 	set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
497     clear_lval(redir_lval);
498     err = did_emsg;
499     did_emsg |= save_emsg;
500     if (err)
501     {
502 	redir_endp = NULL;  /* don't store a value, only cleanup */
503 	var_redir_stop();
504 	return FAIL;
505     }
506 
507     return OK;
508 }
509 
510 /*
511  * Append "value[value_len]" to the variable set by var_redir_start().
512  * The actual appending is postponed until redirection ends, because the value
513  * appended may in fact be the string we write to, changing it may cause freed
514  * memory to be used:
515  *   :redir => foo
516  *   :let foo
517  *   :redir END
518  */
519     void
520 var_redir_str(char_u *value, int value_len)
521 {
522     int		len;
523 
524     if (redir_lval == NULL)
525 	return;
526 
527     if (value_len == -1)
528 	len = (int)STRLEN(value);	/* Append the entire string */
529     else
530 	len = value_len;		/* Append only "value_len" characters */
531 
532     if (ga_grow(&redir_ga, len) == OK)
533     {
534 	mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
535 	redir_ga.ga_len += len;
536     }
537     else
538 	var_redir_stop();
539 }
540 
541 /*
542  * Stop redirecting command output to a variable.
543  * Frees the allocated memory.
544  */
545     void
546 var_redir_stop(void)
547 {
548     typval_T	tv;
549 
550     if (EVALCMD_BUSY)
551     {
552 	redir_lval = NULL;
553 	return;
554     }
555 
556     if (redir_lval != NULL)
557     {
558 	/* If there was no error: assign the text to the variable. */
559 	if (redir_endp != NULL)
560 	{
561 	    ga_append(&redir_ga, NUL);  /* Append the trailing NUL. */
562 	    tv.v_type = VAR_STRING;
563 	    tv.vval.v_string = redir_ga.ga_data;
564 	    /* Call get_lval() again, if it's inside a Dict or List it may
565 	     * have changed. */
566 	    redir_endp = get_lval(redir_varname, NULL, redir_lval,
567 					FALSE, FALSE, 0, FNE_CHECK_START);
568 	    if (redir_endp != NULL && redir_lval->ll_name != NULL)
569 		set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
570 	    clear_lval(redir_lval);
571 	}
572 
573 	/* free the collected output */
574 	VIM_CLEAR(redir_ga.ga_data);
575 
576 	VIM_CLEAR(redir_lval);
577     }
578     VIM_CLEAR(redir_varname);
579 }
580 
581     int
582 eval_charconvert(
583     char_u	*enc_from,
584     char_u	*enc_to,
585     char_u	*fname_from,
586     char_u	*fname_to)
587 {
588     int		err = FALSE;
589 
590     set_vim_var_string(VV_CC_FROM, enc_from, -1);
591     set_vim_var_string(VV_CC_TO, enc_to, -1);
592     set_vim_var_string(VV_FNAME_IN, fname_from, -1);
593     set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
594     if (eval_to_bool(p_ccv, &err, NULL, FALSE))
595 	err = TRUE;
596     set_vim_var_string(VV_CC_FROM, NULL, -1);
597     set_vim_var_string(VV_CC_TO, NULL, -1);
598     set_vim_var_string(VV_FNAME_IN, NULL, -1);
599     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
600 
601     if (err)
602 	return FAIL;
603     return OK;
604 }
605 
606 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
607     int
608 eval_printexpr(char_u *fname, char_u *args)
609 {
610     int		err = FALSE;
611 
612     set_vim_var_string(VV_FNAME_IN, fname, -1);
613     set_vim_var_string(VV_CMDARG, args, -1);
614     if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
615 	err = TRUE;
616     set_vim_var_string(VV_FNAME_IN, NULL, -1);
617     set_vim_var_string(VV_CMDARG, NULL, -1);
618 
619     if (err)
620     {
621 	mch_remove(fname);
622 	return FAIL;
623     }
624     return OK;
625 }
626 # endif
627 
628 # if defined(FEAT_DIFF) || defined(PROTO)
629     void
630 eval_diff(
631     char_u	*origfile,
632     char_u	*newfile,
633     char_u	*outfile)
634 {
635     int		err = FALSE;
636 
637     set_vim_var_string(VV_FNAME_IN, origfile, -1);
638     set_vim_var_string(VV_FNAME_NEW, newfile, -1);
639     set_vim_var_string(VV_FNAME_OUT, outfile, -1);
640     (void)eval_to_bool(p_dex, &err, NULL, FALSE);
641     set_vim_var_string(VV_FNAME_IN, NULL, -1);
642     set_vim_var_string(VV_FNAME_NEW, NULL, -1);
643     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
644 }
645 
646     void
647 eval_patch(
648     char_u	*origfile,
649     char_u	*difffile,
650     char_u	*outfile)
651 {
652     int		err;
653 
654     set_vim_var_string(VV_FNAME_IN, origfile, -1);
655     set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
656     set_vim_var_string(VV_FNAME_OUT, outfile, -1);
657     (void)eval_to_bool(p_pex, &err, NULL, FALSE);
658     set_vim_var_string(VV_FNAME_IN, NULL, -1);
659     set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
660     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
661 }
662 # endif
663 
664 /*
665  * Top level evaluation function, returning a boolean.
666  * Sets "error" to TRUE if there was an error.
667  * Return TRUE or FALSE.
668  */
669     int
670 eval_to_bool(
671     char_u	*arg,
672     int		*error,
673     char_u	**nextcmd,
674     int		skip)	    /* only parse, don't execute */
675 {
676     typval_T	tv;
677     varnumber_T	retval = FALSE;
678 
679     if (skip)
680 	++emsg_skip;
681     if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
682 	*error = TRUE;
683     else
684     {
685 	*error = FALSE;
686 	if (!skip)
687 	{
688 	    retval = (tv_get_number_chk(&tv, error) != 0);
689 	    clear_tv(&tv);
690 	}
691     }
692     if (skip)
693 	--emsg_skip;
694 
695     return (int)retval;
696 }
697 
698 /*
699  * Call eval1() and give an error message if not done at a lower level.
700  */
701     static int
702 eval1_emsg(char_u **arg, typval_T *rettv, int evaluate)
703 {
704     char_u	*start = *arg;
705     int		ret;
706     int		did_emsg_before = did_emsg;
707     int		called_emsg_before = called_emsg;
708 
709     ret = eval1(arg, rettv, evaluate);
710     if (ret == FAIL)
711     {
712 	// Report the invalid expression unless the expression evaluation has
713 	// been cancelled due to an aborting error, an interrupt, or an
714 	// exception, or we already gave a more specific error.
715 	// Also check called_emsg for when using assert_fails().
716 	if (!aborting() && did_emsg == did_emsg_before
717 					  && called_emsg == called_emsg_before)
718 	    semsg(_(e_invexpr2), start);
719     }
720     return ret;
721 }
722 
723     static int
724 eval_expr_typval(typval_T *expr, typval_T *argv, int argc, typval_T *rettv)
725 {
726     char_u	*s;
727     int		dummy;
728     char_u	buf[NUMBUFLEN];
729 
730     if (expr->v_type == VAR_FUNC)
731     {
732 	s = expr->vval.v_string;
733 	if (s == NULL || *s == NUL)
734 	    return FAIL;
735 	if (call_func(s, (int)STRLEN(s), rettv, argc, argv, NULL,
736 				     0L, 0L, &dummy, TRUE, NULL, NULL) == FAIL)
737 	    return FAIL;
738     }
739     else if (expr->v_type == VAR_PARTIAL)
740     {
741 	partial_T   *partial = expr->vval.v_partial;
742 
743 	s = partial_name(partial);
744 	if (s == NULL || *s == NUL)
745 	    return FAIL;
746 	if (call_func(s, (int)STRLEN(s), rettv, argc, argv, NULL,
747 				  0L, 0L, &dummy, TRUE, partial, NULL) == FAIL)
748 	    return FAIL;
749     }
750     else
751     {
752 	s = tv_get_string_buf_chk(expr, buf);
753 	if (s == NULL)
754 	    return FAIL;
755 	s = skipwhite(s);
756 	if (eval1_emsg(&s, rettv, TRUE) == FAIL)
757 	    return FAIL;
758 	if (*s != NUL)  /* check for trailing chars after expr */
759 	{
760 	    clear_tv(rettv);
761 	    semsg(_(e_invexpr2), s);
762 	    return FAIL;
763 	}
764     }
765     return OK;
766 }
767 
768 /*
769  * Like eval_to_bool() but using a typval_T instead of a string.
770  * Works for string, funcref and partial.
771  */
772     int
773 eval_expr_to_bool(typval_T *expr, int *error)
774 {
775     typval_T	rettv;
776     int		res;
777 
778     if (eval_expr_typval(expr, NULL, 0, &rettv) == FAIL)
779     {
780 	*error = TRUE;
781 	return FALSE;
782     }
783     res = (tv_get_number_chk(&rettv, error) != 0);
784     clear_tv(&rettv);
785     return res;
786 }
787 
788 /*
789  * Top level evaluation function, returning a string.  If "skip" is TRUE,
790  * only parsing to "nextcmd" is done, without reporting errors.  Return
791  * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
792  */
793     char_u *
794 eval_to_string_skip(
795     char_u	*arg,
796     char_u	**nextcmd,
797     int		skip)	    /* only parse, don't execute */
798 {
799     typval_T	tv;
800     char_u	*retval;
801 
802     if (skip)
803 	++emsg_skip;
804     if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
805 	retval = NULL;
806     else
807     {
808 	retval = vim_strsave(tv_get_string(&tv));
809 	clear_tv(&tv);
810     }
811     if (skip)
812 	--emsg_skip;
813 
814     return retval;
815 }
816 
817 /*
818  * Skip over an expression at "*pp".
819  * Return FAIL for an error, OK otherwise.
820  */
821     int
822 skip_expr(char_u **pp)
823 {
824     typval_T	rettv;
825 
826     *pp = skipwhite(*pp);
827     return eval1(pp, &rettv, FALSE);
828 }
829 
830 /*
831  * Top level evaluation function, returning a string.
832  * When "convert" is TRUE convert a List into a sequence of lines and convert
833  * a Float to a String.
834  * Return pointer to allocated memory, or NULL for failure.
835  */
836     char_u *
837 eval_to_string(
838     char_u	*arg,
839     char_u	**nextcmd,
840     int		convert)
841 {
842     typval_T	tv;
843     char_u	*retval;
844     garray_T	ga;
845 #ifdef FEAT_FLOAT
846     char_u	numbuf[NUMBUFLEN];
847 #endif
848 
849     if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
850 	retval = NULL;
851     else
852     {
853 	if (convert && tv.v_type == VAR_LIST)
854 	{
855 	    ga_init2(&ga, (int)sizeof(char), 80);
856 	    if (tv.vval.v_list != NULL)
857 	    {
858 		list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, FALSE, 0);
859 		if (tv.vval.v_list->lv_len > 0)
860 		    ga_append(&ga, NL);
861 	    }
862 	    ga_append(&ga, NUL);
863 	    retval = (char_u *)ga.ga_data;
864 	}
865 #ifdef FEAT_FLOAT
866 	else if (convert && tv.v_type == VAR_FLOAT)
867 	{
868 	    vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
869 	    retval = vim_strsave(numbuf);
870 	}
871 #endif
872 	else
873 	    retval = vim_strsave(tv_get_string(&tv));
874 	clear_tv(&tv);
875     }
876 
877     return retval;
878 }
879 
880 /*
881  * Call eval_to_string() without using current local variables and using
882  * textlock.  When "use_sandbox" is TRUE use the sandbox.
883  */
884     char_u *
885 eval_to_string_safe(
886     char_u	*arg,
887     char_u	**nextcmd,
888     int		use_sandbox)
889 {
890     char_u	*retval;
891     funccal_entry_T funccal_entry;
892 
893     save_funccal(&funccal_entry);
894     if (use_sandbox)
895 	++sandbox;
896     ++textlock;
897     retval = eval_to_string(arg, nextcmd, FALSE);
898     if (use_sandbox)
899 	--sandbox;
900     --textlock;
901     restore_funccal();
902     return retval;
903 }
904 
905 /*
906  * Top level evaluation function, returning a number.
907  * Evaluates "expr" silently.
908  * Returns -1 for an error.
909  */
910     varnumber_T
911 eval_to_number(char_u *expr)
912 {
913     typval_T	rettv;
914     varnumber_T	retval;
915     char_u	*p = skipwhite(expr);
916 
917     ++emsg_off;
918 
919     if (eval1(&p, &rettv, TRUE) == FAIL)
920 	retval = -1;
921     else
922     {
923 	retval = tv_get_number_chk(&rettv, NULL);
924 	clear_tv(&rettv);
925     }
926     --emsg_off;
927 
928     return retval;
929 }
930 
931 /*
932  * Prepare v: variable "idx" to be used.
933  * Save the current typeval in "save_tv".
934  * When not used yet add the variable to the v: hashtable.
935  */
936     static void
937 prepare_vimvar(int idx, typval_T *save_tv)
938 {
939     *save_tv = vimvars[idx].vv_tv;
940     if (vimvars[idx].vv_type == VAR_UNKNOWN)
941 	hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
942 }
943 
944 /*
945  * Restore v: variable "idx" to typeval "save_tv".
946  * When no longer defined, remove the variable from the v: hashtable.
947  */
948     static void
949 restore_vimvar(int idx, typval_T *save_tv)
950 {
951     hashitem_T	*hi;
952 
953     vimvars[idx].vv_tv = *save_tv;
954     if (vimvars[idx].vv_type == VAR_UNKNOWN)
955     {
956 	hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
957 	if (HASHITEM_EMPTY(hi))
958 	    internal_error("restore_vimvar()");
959 	else
960 	    hash_remove(&vimvarht, hi);
961     }
962 }
963 
964 #if defined(FEAT_SPELL) || defined(PROTO)
965 /*
966  * Evaluate an expression to a list with suggestions.
967  * For the "expr:" part of 'spellsuggest'.
968  * Returns NULL when there is an error.
969  */
970     list_T *
971 eval_spell_expr(char_u *badword, char_u *expr)
972 {
973     typval_T	save_val;
974     typval_T	rettv;
975     list_T	*list = NULL;
976     char_u	*p = skipwhite(expr);
977 
978     /* Set "v:val" to the bad word. */
979     prepare_vimvar(VV_VAL, &save_val);
980     vimvars[VV_VAL].vv_type = VAR_STRING;
981     vimvars[VV_VAL].vv_str = badword;
982     if (p_verbose == 0)
983 	++emsg_off;
984 
985     if (eval1(&p, &rettv, TRUE) == OK)
986     {
987 	if (rettv.v_type != VAR_LIST)
988 	    clear_tv(&rettv);
989 	else
990 	    list = rettv.vval.v_list;
991     }
992 
993     if (p_verbose == 0)
994 	--emsg_off;
995     restore_vimvar(VV_VAL, &save_val);
996 
997     return list;
998 }
999 
1000 /*
1001  * "list" is supposed to contain two items: a word and a number.  Return the
1002  * word in "pp" and the number as the return value.
1003  * Return -1 if anything isn't right.
1004  * Used to get the good word and score from the eval_spell_expr() result.
1005  */
1006     int
1007 get_spellword(list_T *list, char_u **pp)
1008 {
1009     listitem_T	*li;
1010 
1011     li = list->lv_first;
1012     if (li == NULL)
1013 	return -1;
1014     *pp = tv_get_string(&li->li_tv);
1015 
1016     li = li->li_next;
1017     if (li == NULL)
1018 	return -1;
1019     return (int)tv_get_number(&li->li_tv);
1020 }
1021 #endif
1022 
1023 /*
1024  * Top level evaluation function.
1025  * Returns an allocated typval_T with the result.
1026  * Returns NULL when there is an error.
1027  */
1028     typval_T *
1029 eval_expr(char_u *arg, char_u **nextcmd)
1030 {
1031     typval_T	*tv;
1032 
1033     tv = (typval_T *)alloc(sizeof(typval_T));
1034     if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1035 	VIM_CLEAR(tv);
1036 
1037     return tv;
1038 }
1039 
1040 
1041 /*
1042  * Call some Vim script function and return the result in "*rettv".
1043  * Uses argv[0] to argv[argc - 1] for the function arguments.  argv[argc]
1044  * should have type VAR_UNKNOWN.
1045  * Returns OK or FAIL.
1046  */
1047     int
1048 call_vim_function(
1049     char_u      *func,
1050     int		argc,
1051     typval_T	*argv,
1052     typval_T	*rettv)
1053 {
1054     int		doesrange;
1055     int		ret;
1056 
1057     rettv->v_type = VAR_UNKNOWN;		/* clear_tv() uses this */
1058     ret = call_func(func, (int)STRLEN(func), rettv, argc, argv, NULL,
1059 		    curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1060 		    &doesrange, TRUE, NULL, NULL);
1061     if (ret == FAIL)
1062 	clear_tv(rettv);
1063 
1064     return ret;
1065 }
1066 
1067 /*
1068  * Call Vim script function "func" and return the result as a number.
1069  * Returns -1 when calling the function fails.
1070  * Uses argv[0] to argv[argc - 1] for the function arguments. argv[argc] should
1071  * have type VAR_UNKNOWN.
1072  */
1073     varnumber_T
1074 call_func_retnr(
1075     char_u      *func,
1076     int		argc,
1077     typval_T	*argv)
1078 {
1079     typval_T	rettv;
1080     varnumber_T	retval;
1081 
1082     if (call_vim_function(func, argc, argv, &rettv) == FAIL)
1083 	return -1;
1084 
1085     retval = tv_get_number_chk(&rettv, NULL);
1086     clear_tv(&rettv);
1087     return retval;
1088 }
1089 
1090 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1091 	|| defined(FEAT_COMPL_FUNC) || defined(PROTO)
1092 
1093 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1094 /*
1095  * Call Vim script function "func" and return the result as a string.
1096  * Returns NULL when calling the function fails.
1097  * Uses argv[0] to argv[argc - 1] for the function arguments. argv[argc] should
1098  * have type VAR_UNKNOWN.
1099  */
1100     void *
1101 call_func_retstr(
1102     char_u      *func,
1103     int		argc,
1104     typval_T	*argv)
1105 {
1106     typval_T	rettv;
1107     char_u	*retval;
1108 
1109     if (call_vim_function(func, argc, argv, &rettv) == FAIL)
1110 	return NULL;
1111 
1112     retval = vim_strsave(tv_get_string(&rettv));
1113     clear_tv(&rettv);
1114     return retval;
1115 }
1116 # endif
1117 
1118 /*
1119  * Call Vim script function "func" and return the result as a List.
1120  * Uses argv[0] to argv[argc - 1] for the function arguments. argv[argc] should
1121  * have type VAR_UNKNOWN.
1122  * Returns NULL when there is something wrong.
1123  */
1124     void *
1125 call_func_retlist(
1126     char_u      *func,
1127     int		argc,
1128     typval_T	*argv)
1129 {
1130     typval_T	rettv;
1131 
1132     if (call_vim_function(func, argc, argv, &rettv) == FAIL)
1133 	return NULL;
1134 
1135     if (rettv.v_type != VAR_LIST)
1136     {
1137 	clear_tv(&rettv);
1138 	return NULL;
1139     }
1140 
1141     return rettv.vval.v_list;
1142 }
1143 #endif
1144 
1145 
1146 #ifdef FEAT_FOLDING
1147 /*
1148  * Evaluate 'foldexpr'.  Returns the foldlevel, and any character preceding
1149  * it in "*cp".  Doesn't give error messages.
1150  */
1151     int
1152 eval_foldexpr(char_u *arg, int *cp)
1153 {
1154     typval_T	tv;
1155     varnumber_T	retval;
1156     char_u	*s;
1157     int		use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1158 								   OPT_LOCAL);
1159 
1160     ++emsg_off;
1161     if (use_sandbox)
1162 	++sandbox;
1163     ++textlock;
1164     *cp = NUL;
1165     if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1166 	retval = 0;
1167     else
1168     {
1169 	/* If the result is a number, just return the number. */
1170 	if (tv.v_type == VAR_NUMBER)
1171 	    retval = tv.vval.v_number;
1172 	else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1173 	    retval = 0;
1174 	else
1175 	{
1176 	    /* If the result is a string, check if there is a non-digit before
1177 	     * the number. */
1178 	    s = tv.vval.v_string;
1179 	    if (!VIM_ISDIGIT(*s) && *s != '-')
1180 		*cp = *s++;
1181 	    retval = atol((char *)s);
1182 	}
1183 	clear_tv(&tv);
1184     }
1185     --emsg_off;
1186     if (use_sandbox)
1187 	--sandbox;
1188     --textlock;
1189 
1190     return (int)retval;
1191 }
1192 #endif
1193 
1194 /*
1195  * ":let"			list all variable values
1196  * ":let var1 var2"		list variable values
1197  * ":let var = expr"		assignment command.
1198  * ":let var += expr"		assignment command.
1199  * ":let var -= expr"		assignment command.
1200  * ":let var *= expr"		assignment command.
1201  * ":let var /= expr"		assignment command.
1202  * ":let var %= expr"		assignment command.
1203  * ":let var .= expr"		assignment command.
1204  * ":let [var1, var2] = expr"	unpack list.
1205  */
1206     void
1207 ex_let(exarg_T *eap)
1208 {
1209     char_u	*arg = eap->arg;
1210     char_u	*expr = NULL;
1211     typval_T	rettv;
1212     int		i;
1213     int		var_count = 0;
1214     int		semicolon = 0;
1215     char_u	op[2];
1216     char_u	*argend;
1217     int		first = TRUE;
1218 
1219     argend = skip_var_list(arg, &var_count, &semicolon);
1220     if (argend == NULL)
1221 	return;
1222     if (argend > arg && argend[-1] == '.')  // for var.='str'
1223 	--argend;
1224     expr = skipwhite(argend);
1225     if (*expr != '=' && !(vim_strchr((char_u *)"+-*/%.", *expr) != NULL
1226 			  && expr[1] == '='))
1227     {
1228 	/*
1229 	 * ":let" without "=": list variables
1230 	 */
1231 	if (*arg == '[')
1232 	    emsg(_(e_invarg));
1233 	else if (!ends_excmd(*arg))
1234 	    /* ":let var1 var2" */
1235 	    arg = list_arg_vars(eap, arg, &first);
1236 	else if (!eap->skip)
1237 	{
1238 	    /* ":let" */
1239 	    list_glob_vars(&first);
1240 	    list_buf_vars(&first);
1241 	    list_win_vars(&first);
1242 	    list_tab_vars(&first);
1243 	    list_script_vars(&first);
1244 	    list_func_vars(&first);
1245 	    list_vim_vars(&first);
1246 	}
1247 	eap->nextcmd = check_nextcmd(arg);
1248     }
1249     else
1250     {
1251 	op[0] = '=';
1252 	op[1] = NUL;
1253 	if (*expr != '=')
1254 	{
1255 	    if (vim_strchr((char_u *)"+-*/%.", *expr) != NULL)
1256 		op[0] = *expr;   // +=, -=, *=, /=, %= or .=
1257 	    expr = skipwhite(expr + 2);
1258 	}
1259 	else
1260 	    expr = skipwhite(expr + 1);
1261 
1262 	if (eap->skip)
1263 	    ++emsg_skip;
1264 	i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1265 	if (eap->skip)
1266 	{
1267 	    if (i != FAIL)
1268 		clear_tv(&rettv);
1269 	    --emsg_skip;
1270 	}
1271 	else if (i != FAIL)
1272 	{
1273 	    (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1274 									  op);
1275 	    clear_tv(&rettv);
1276 	}
1277     }
1278 }
1279 
1280 /*
1281  * Assign the typevalue "tv" to the variable or variables at "arg_start".
1282  * Handles both "var" with any type and "[var, var; var]" with a list type.
1283  * When "nextchars" is not NULL it points to a string with characters that
1284  * must appear after the variable(s).  Use "+", "-" or "." for add, subtract
1285  * or concatenate.
1286  * Returns OK or FAIL;
1287  */
1288     static int
1289 ex_let_vars(
1290     char_u	*arg_start,
1291     typval_T	*tv,
1292     int		copy,		/* copy values from "tv", don't move */
1293     int		semicolon,	/* from skip_var_list() */
1294     int		var_count,	/* from skip_var_list() */
1295     char_u	*nextchars)
1296 {
1297     char_u	*arg = arg_start;
1298     list_T	*l;
1299     int		i;
1300     listitem_T	*item;
1301     typval_T	ltv;
1302 
1303     if (*arg != '[')
1304     {
1305 	/*
1306 	 * ":let var = expr" or ":for var in list"
1307 	 */
1308 	if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1309 	    return FAIL;
1310 	return OK;
1311     }
1312 
1313     /*
1314      * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1315      */
1316     if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1317     {
1318 	emsg(_(e_listreq));
1319 	return FAIL;
1320     }
1321 
1322     i = list_len(l);
1323     if (semicolon == 0 && var_count < i)
1324     {
1325 	emsg(_("E687: Less targets than List items"));
1326 	return FAIL;
1327     }
1328     if (var_count - semicolon > i)
1329     {
1330 	emsg(_("E688: More targets than List items"));
1331 	return FAIL;
1332     }
1333 
1334     item = l->lv_first;
1335     while (*arg != ']')
1336     {
1337 	arg = skipwhite(arg + 1);
1338 	arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1339 	item = item->li_next;
1340 	if (arg == NULL)
1341 	    return FAIL;
1342 
1343 	arg = skipwhite(arg);
1344 	if (*arg == ';')
1345 	{
1346 	    /* Put the rest of the list (may be empty) in the var after ';'.
1347 	     * Create a new list for this. */
1348 	    l = list_alloc();
1349 	    if (l == NULL)
1350 		return FAIL;
1351 	    while (item != NULL)
1352 	    {
1353 		list_append_tv(l, &item->li_tv);
1354 		item = item->li_next;
1355 	    }
1356 
1357 	    ltv.v_type = VAR_LIST;
1358 	    ltv.v_lock = 0;
1359 	    ltv.vval.v_list = l;
1360 	    l->lv_refcount = 1;
1361 
1362 	    arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1363 						    (char_u *)"]", nextchars);
1364 	    clear_tv(&ltv);
1365 	    if (arg == NULL)
1366 		return FAIL;
1367 	    break;
1368 	}
1369 	else if (*arg != ',' && *arg != ']')
1370 	{
1371 	    internal_error("ex_let_vars()");
1372 	    return FAIL;
1373 	}
1374     }
1375 
1376     return OK;
1377 }
1378 
1379 /*
1380  * Skip over assignable variable "var" or list of variables "[var, var]".
1381  * Used for ":let varvar = expr" and ":for varvar in expr".
1382  * For "[var, var]" increment "*var_count" for each variable.
1383  * for "[var, var; var]" set "semicolon".
1384  * Return NULL for an error.
1385  */
1386     static char_u *
1387 skip_var_list(
1388     char_u	*arg,
1389     int		*var_count,
1390     int		*semicolon)
1391 {
1392     char_u	*p, *s;
1393 
1394     if (*arg == '[')
1395     {
1396 	/* "[var, var]": find the matching ']'. */
1397 	p = arg;
1398 	for (;;)
1399 	{
1400 	    p = skipwhite(p + 1);	/* skip whites after '[', ';' or ',' */
1401 	    s = skip_var_one(p);
1402 	    if (s == p)
1403 	    {
1404 		semsg(_(e_invarg2), p);
1405 		return NULL;
1406 	    }
1407 	    ++*var_count;
1408 
1409 	    p = skipwhite(s);
1410 	    if (*p == ']')
1411 		break;
1412 	    else if (*p == ';')
1413 	    {
1414 		if (*semicolon == 1)
1415 		{
1416 		    emsg(_("Double ; in list of variables"));
1417 		    return NULL;
1418 		}
1419 		*semicolon = 1;
1420 	    }
1421 	    else if (*p != ',')
1422 	    {
1423 		semsg(_(e_invarg2), p);
1424 		return NULL;
1425 	    }
1426 	}
1427 	return p + 1;
1428     }
1429     else
1430 	return skip_var_one(arg);
1431 }
1432 
1433 /*
1434  * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1435  * l[idx].
1436  */
1437     static char_u *
1438 skip_var_one(char_u *arg)
1439 {
1440     if (*arg == '@' && arg[1] != NUL)
1441 	return arg + 2;
1442     return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1443 				   NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1444 }
1445 
1446 /*
1447  * List variables for hashtab "ht" with prefix "prefix".
1448  * If "empty" is TRUE also list NULL strings as empty strings.
1449  */
1450     void
1451 list_hashtable_vars(
1452     hashtab_T	*ht,
1453     char	*prefix,
1454     int		empty,
1455     int		*first)
1456 {
1457     hashitem_T	*hi;
1458     dictitem_T	*di;
1459     int		todo;
1460     char_u	buf[IOSIZE];
1461 
1462     todo = (int)ht->ht_used;
1463     for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
1464     {
1465 	if (!HASHITEM_EMPTY(hi))
1466 	{
1467 	    --todo;
1468 	    di = HI2DI(hi);
1469 
1470 	    // apply :filter /pat/ to variable name
1471 	    vim_strncpy((char_u *)buf, (char_u *)prefix, IOSIZE - 1);
1472 	    vim_strcat((char_u *)buf, di->di_key, IOSIZE);
1473 	    if (message_filtered(buf))
1474 		continue;
1475 
1476 	    if (empty || di->di_tv.v_type != VAR_STRING
1477 					   || di->di_tv.vval.v_string != NULL)
1478 		list_one_var(di, prefix, first);
1479 	}
1480     }
1481 }
1482 
1483 /*
1484  * List global variables.
1485  */
1486     static void
1487 list_glob_vars(int *first)
1488 {
1489     list_hashtable_vars(&globvarht, "", TRUE, first);
1490 }
1491 
1492 /*
1493  * List buffer variables.
1494  */
1495     static void
1496 list_buf_vars(int *first)
1497 {
1498     list_hashtable_vars(&curbuf->b_vars->dv_hashtab, "b:", TRUE, first);
1499 }
1500 
1501 /*
1502  * List window variables.
1503  */
1504     static void
1505 list_win_vars(int *first)
1506 {
1507     list_hashtable_vars(&curwin->w_vars->dv_hashtab, "w:", TRUE, first);
1508 }
1509 
1510 /*
1511  * List tab page variables.
1512  */
1513     static void
1514 list_tab_vars(int *first)
1515 {
1516     list_hashtable_vars(&curtab->tp_vars->dv_hashtab, "t:", TRUE, first);
1517 }
1518 
1519 /*
1520  * List Vim variables.
1521  */
1522     static void
1523 list_vim_vars(int *first)
1524 {
1525     list_hashtable_vars(&vimvarht, "v:", FALSE, first);
1526 }
1527 
1528 /*
1529  * List script-local variables, if there is a script.
1530  */
1531     static void
1532 list_script_vars(int *first)
1533 {
1534     if (current_sctx.sc_sid > 0 && current_sctx.sc_sid <= ga_scripts.ga_len)
1535 	list_hashtable_vars(&SCRIPT_VARS(current_sctx.sc_sid),
1536 							   "s:", FALSE, first);
1537 }
1538 
1539 /*
1540  * List variables in "arg".
1541  */
1542     static char_u *
1543 list_arg_vars(exarg_T *eap, char_u *arg, int *first)
1544 {
1545     int		error = FALSE;
1546     int		len;
1547     char_u	*name;
1548     char_u	*name_start;
1549     char_u	*arg_subsc;
1550     char_u	*tofree;
1551     typval_T    tv;
1552 
1553     while (!ends_excmd(*arg) && !got_int)
1554     {
1555 	if (error || eap->skip)
1556 	{
1557 	    arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1558 	    if (!VIM_ISWHITE(*arg) && !ends_excmd(*arg))
1559 	    {
1560 		emsg_severe = TRUE;
1561 		emsg(_(e_trailing));
1562 		break;
1563 	    }
1564 	}
1565 	else
1566 	{
1567 	    /* get_name_len() takes care of expanding curly braces */
1568 	    name_start = name = arg;
1569 	    len = get_name_len(&arg, &tofree, TRUE, TRUE);
1570 	    if (len <= 0)
1571 	    {
1572 		/* This is mainly to keep test 49 working: when expanding
1573 		 * curly braces fails overrule the exception error message. */
1574 		if (len < 0 && !aborting())
1575 		{
1576 		    emsg_severe = TRUE;
1577 		    semsg(_(e_invarg2), arg);
1578 		    break;
1579 		}
1580 		error = TRUE;
1581 	    }
1582 	    else
1583 	    {
1584 		if (tofree != NULL)
1585 		    name = tofree;
1586 		if (get_var_tv(name, len, &tv, NULL, TRUE, FALSE) == FAIL)
1587 		    error = TRUE;
1588 		else
1589 		{
1590 		    /* handle d.key, l[idx], f(expr) */
1591 		    arg_subsc = arg;
1592 		    if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
1593 			error = TRUE;
1594 		    else
1595 		    {
1596 			if (arg == arg_subsc && len == 2 && name[1] == ':')
1597 			{
1598 			    switch (*name)
1599 			    {
1600 				case 'g': list_glob_vars(first); break;
1601 				case 'b': list_buf_vars(first); break;
1602 				case 'w': list_win_vars(first); break;
1603 				case 't': list_tab_vars(first); break;
1604 				case 'v': list_vim_vars(first); break;
1605 				case 's': list_script_vars(first); break;
1606 				case 'l': list_func_vars(first); break;
1607 				default:
1608 					  semsg(_("E738: Can't list variables for %s"), name);
1609 			    }
1610 			}
1611 			else
1612 			{
1613 			    char_u	numbuf[NUMBUFLEN];
1614 			    char_u	*tf;
1615 			    int		c;
1616 			    char_u	*s;
1617 
1618 			    s = echo_string(&tv, &tf, numbuf, 0);
1619 			    c = *arg;
1620 			    *arg = NUL;
1621 			    list_one_var_a("",
1622 				    arg == arg_subsc ? name : name_start,
1623 				    tv.v_type,
1624 				    s == NULL ? (char_u *)"" : s,
1625 				    first);
1626 			    *arg = c;
1627 			    vim_free(tf);
1628 			}
1629 			clear_tv(&tv);
1630 		    }
1631 		}
1632 	    }
1633 
1634 	    vim_free(tofree);
1635 	}
1636 
1637 	arg = skipwhite(arg);
1638     }
1639 
1640     return arg;
1641 }
1642 
1643 /*
1644  * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
1645  * Returns a pointer to the char just after the var name.
1646  * Returns NULL if there is an error.
1647  */
1648     static char_u *
1649 ex_let_one(
1650     char_u	*arg,		/* points to variable name */
1651     typval_T	*tv,		/* value to assign to variable */
1652     int		copy,		/* copy value from "tv" */
1653     char_u	*endchars,	/* valid chars after variable name  or NULL */
1654     char_u	*op)		/* "+", "-", "."  or NULL*/
1655 {
1656     int		c1;
1657     char_u	*name;
1658     char_u	*p;
1659     char_u	*arg_end = NULL;
1660     int		len;
1661     int		opt_flags;
1662     char_u	*tofree = NULL;
1663 
1664     /*
1665      * ":let $VAR = expr": Set environment variable.
1666      */
1667     if (*arg == '$')
1668     {
1669 	/* Find the end of the name. */
1670 	++arg;
1671 	name = arg;
1672 	len = get_env_len(&arg);
1673 	if (len == 0)
1674 	    semsg(_(e_invarg2), name - 1);
1675 	else
1676 	{
1677 	    if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL)
1678 		semsg(_(e_letwrong), op);
1679 	    else if (endchars != NULL
1680 			     && vim_strchr(endchars, *skipwhite(arg)) == NULL)
1681 		emsg(_(e_letunexp));
1682 	    else if (!check_secure())
1683 	    {
1684 		c1 = name[len];
1685 		name[len] = NUL;
1686 		p = tv_get_string_chk(tv);
1687 		if (p != NULL && op != NULL && *op == '.')
1688 		{
1689 		    int	    mustfree = FALSE;
1690 		    char_u  *s = vim_getenv(name, &mustfree);
1691 
1692 		    if (s != NULL)
1693 		    {
1694 			p = tofree = concat_str(s, p);
1695 			if (mustfree)
1696 			    vim_free(s);
1697 		    }
1698 		}
1699 		if (p != NULL)
1700 		{
1701 		    vim_setenv(name, p);
1702 		    if (STRICMP(name, "HOME") == 0)
1703 			init_homedir();
1704 		    else if (didset_vim && STRICMP(name, "VIM") == 0)
1705 			didset_vim = FALSE;
1706 		    else if (didset_vimruntime
1707 					&& STRICMP(name, "VIMRUNTIME") == 0)
1708 			didset_vimruntime = FALSE;
1709 		    arg_end = arg;
1710 		}
1711 		name[len] = c1;
1712 		vim_free(tofree);
1713 	    }
1714 	}
1715     }
1716 
1717     /*
1718      * ":let &option = expr": Set option value.
1719      * ":let &l:option = expr": Set local option value.
1720      * ":let &g:option = expr": Set global option value.
1721      */
1722     else if (*arg == '&')
1723     {
1724 	/* Find the end of the name. */
1725 	p = find_option_end(&arg, &opt_flags);
1726 	if (p == NULL || (endchars != NULL
1727 			      && vim_strchr(endchars, *skipwhite(p)) == NULL))
1728 	    emsg(_(e_letunexp));
1729 	else
1730 	{
1731 	    long	n;
1732 	    int		opt_type;
1733 	    long	numval;
1734 	    char_u	*stringval = NULL;
1735 	    char_u	*s;
1736 
1737 	    c1 = *p;
1738 	    *p = NUL;
1739 
1740 	    n = (long)tv_get_number(tv);
1741 	    s = tv_get_string_chk(tv);	    /* != NULL if number or string */
1742 	    if (s != NULL && op != NULL && *op != '=')
1743 	    {
1744 		opt_type = get_option_value(arg, &numval,
1745 						       &stringval, opt_flags);
1746 		if ((opt_type == 1 && *op == '.')
1747 			|| (opt_type == 0 && *op != '.'))
1748 		{
1749 		    semsg(_(e_letwrong), op);
1750 		    s = NULL;  // don't set the value
1751 		}
1752 		else
1753 		{
1754 		    if (opt_type == 1)  // number
1755 		    {
1756 			switch (*op)
1757 			{
1758 			    case '+': n = numval + n; break;
1759 			    case '-': n = numval - n; break;
1760 			    case '*': n = numval * n; break;
1761 			    case '/': n = numval / n; break;
1762 			    case '%': n = numval % n; break;
1763 			}
1764 		    }
1765 		    else if (opt_type == 0 && stringval != NULL) // string
1766 		    {
1767 			s = concat_str(stringval, s);
1768 			vim_free(stringval);
1769 			stringval = s;
1770 		    }
1771 		}
1772 	    }
1773 	    if (s != NULL)
1774 	    {
1775 		set_option_value(arg, n, s, opt_flags);
1776 		arg_end = p;
1777 	    }
1778 	    *p = c1;
1779 	    vim_free(stringval);
1780 	}
1781     }
1782 
1783     /*
1784      * ":let @r = expr": Set register contents.
1785      */
1786     else if (*arg == '@')
1787     {
1788 	++arg;
1789 	if (op != NULL && vim_strchr((char_u *)"+-*/%", *op) != NULL)
1790 	    semsg(_(e_letwrong), op);
1791 	else if (endchars != NULL
1792 			 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
1793 	    emsg(_(e_letunexp));
1794 	else
1795 	{
1796 	    char_u	*ptofree = NULL;
1797 	    char_u	*s;
1798 
1799 	    p = tv_get_string_chk(tv);
1800 	    if (p != NULL && op != NULL && *op == '.')
1801 	    {
1802 		s = get_reg_contents(*arg == '@' ? '"' : *arg, GREG_EXPR_SRC);
1803 		if (s != NULL)
1804 		{
1805 		    p = ptofree = concat_str(s, p);
1806 		    vim_free(s);
1807 		}
1808 	    }
1809 	    if (p != NULL)
1810 	    {
1811 		write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
1812 		arg_end = arg + 1;
1813 	    }
1814 	    vim_free(ptofree);
1815 	}
1816     }
1817 
1818     /*
1819      * ":let var = expr": Set internal variable.
1820      * ":let {expr} = expr": Idem, name made with curly braces
1821      */
1822     else if (eval_isnamec1(*arg) || *arg == '{')
1823     {
1824 	lval_T	lv;
1825 
1826 	p = get_lval(arg, tv, &lv, FALSE, FALSE, 0, FNE_CHECK_START);
1827 	if (p != NULL && lv.ll_name != NULL)
1828 	{
1829 	    if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
1830 		emsg(_(e_letunexp));
1831 	    else
1832 	    {
1833 		set_var_lval(&lv, p, tv, copy, op);
1834 		arg_end = p;
1835 	    }
1836 	}
1837 	clear_lval(&lv);
1838     }
1839 
1840     else
1841 	semsg(_(e_invarg2), arg);
1842 
1843     return arg_end;
1844 }
1845 
1846 /*
1847  * Get an lval: variable, Dict item or List item that can be assigned a value
1848  * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
1849  * "name.key", "name.key[expr]" etc.
1850  * Indexing only works if "name" is an existing List or Dictionary.
1851  * "name" points to the start of the name.
1852  * If "rettv" is not NULL it points to the value to be assigned.
1853  * "unlet" is TRUE for ":unlet": slightly different behavior when something is
1854  * wrong; must end in space or cmd separator.
1855  *
1856  * flags:
1857  *  GLV_QUIET:       do not give error messages
1858  *  GLV_READ_ONLY:   will not change the variable
1859  *  GLV_NO_AUTOLOAD: do not use script autoloading
1860  *
1861  * Returns a pointer to just after the name, including indexes.
1862  * When an evaluation error occurs "lp->ll_name" is NULL;
1863  * Returns NULL for a parsing error.  Still need to free items in "lp"!
1864  */
1865     char_u *
1866 get_lval(
1867     char_u	*name,
1868     typval_T	*rettv,
1869     lval_T	*lp,
1870     int		unlet,
1871     int		skip,
1872     int		flags,	    /* GLV_ values */
1873     int		fne_flags)  /* flags for find_name_end() */
1874 {
1875     char_u	*p;
1876     char_u	*expr_start, *expr_end;
1877     int		cc;
1878     dictitem_T	*v;
1879     typval_T	var1;
1880     typval_T	var2;
1881     int		empty1 = FALSE;
1882     listitem_T	*ni;
1883     char_u	*key = NULL;
1884     int		len;
1885     hashtab_T	*ht;
1886     int		quiet = flags & GLV_QUIET;
1887 
1888     /* Clear everything in "lp". */
1889     vim_memset(lp, 0, sizeof(lval_T));
1890 
1891     if (skip)
1892     {
1893 	/* When skipping just find the end of the name. */
1894 	lp->ll_name = name;
1895 	return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
1896     }
1897 
1898     /* Find the end of the name. */
1899     p = find_name_end(name, &expr_start, &expr_end, fne_flags);
1900     if (expr_start != NULL)
1901     {
1902 	/* Don't expand the name when we already know there is an error. */
1903 	if (unlet && !VIM_ISWHITE(*p) && !ends_excmd(*p)
1904 						    && *p != '[' && *p != '.')
1905 	{
1906 	    emsg(_(e_trailing));
1907 	    return NULL;
1908 	}
1909 
1910 	lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
1911 	if (lp->ll_exp_name == NULL)
1912 	{
1913 	    /* Report an invalid expression in braces, unless the
1914 	     * expression evaluation has been cancelled due to an
1915 	     * aborting error, an interrupt, or an exception. */
1916 	    if (!aborting() && !quiet)
1917 	    {
1918 		emsg_severe = TRUE;
1919 		semsg(_(e_invarg2), name);
1920 		return NULL;
1921 	    }
1922 	}
1923 	lp->ll_name = lp->ll_exp_name;
1924     }
1925     else
1926 	lp->ll_name = name;
1927 
1928     /* Without [idx] or .key we are done. */
1929     if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
1930 	return p;
1931 
1932     cc = *p;
1933     *p = NUL;
1934     /* Only pass &ht when we would write to the variable, it prevents autoload
1935      * as well. */
1936     v = find_var(lp->ll_name, (flags & GLV_READ_ONLY) ? NULL : &ht,
1937 						      flags & GLV_NO_AUTOLOAD);
1938     if (v == NULL && !quiet)
1939 	semsg(_(e_undefvar), lp->ll_name);
1940     *p = cc;
1941     if (v == NULL)
1942 	return NULL;
1943 
1944     /*
1945      * Loop until no more [idx] or .key is following.
1946      */
1947     lp->ll_tv = &v->di_tv;
1948     var1.v_type = VAR_UNKNOWN;
1949     var2.v_type = VAR_UNKNOWN;
1950     while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
1951     {
1952 	if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
1953 		&& !(lp->ll_tv->v_type == VAR_DICT
1954 					   && lp->ll_tv->vval.v_dict != NULL)
1955 		&& !(lp->ll_tv->v_type == VAR_BLOB
1956 					   && lp->ll_tv->vval.v_blob != NULL))
1957 	{
1958 	    if (!quiet)
1959 		emsg(_("E689: Can only index a List, Dictionary or Blob"));
1960 	    return NULL;
1961 	}
1962 	if (lp->ll_range)
1963 	{
1964 	    if (!quiet)
1965 		emsg(_("E708: [:] must come last"));
1966 	    return NULL;
1967 	}
1968 
1969 	len = -1;
1970 	if (*p == '.')
1971 	{
1972 	    key = p + 1;
1973 	    for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
1974 		;
1975 	    if (len == 0)
1976 	    {
1977 		if (!quiet)
1978 		    emsg(_(e_emptykey));
1979 		return NULL;
1980 	    }
1981 	    p = key + len;
1982 	}
1983 	else
1984 	{
1985 	    /* Get the index [expr] or the first index [expr: ]. */
1986 	    p = skipwhite(p + 1);
1987 	    if (*p == ':')
1988 		empty1 = TRUE;
1989 	    else
1990 	    {
1991 		empty1 = FALSE;
1992 		if (eval1(&p, &var1, TRUE) == FAIL)	/* recursive! */
1993 		    return NULL;
1994 		if (tv_get_string_chk(&var1) == NULL)
1995 		{
1996 		    /* not a number or string */
1997 		    clear_tv(&var1);
1998 		    return NULL;
1999 		}
2000 	    }
2001 
2002 	    /* Optionally get the second index [ :expr]. */
2003 	    if (*p == ':')
2004 	    {
2005 		if (lp->ll_tv->v_type == VAR_DICT)
2006 		{
2007 		    if (!quiet)
2008 			emsg(_(e_dictrange));
2009 		    clear_tv(&var1);
2010 		    return NULL;
2011 		}
2012 		if (rettv != NULL
2013 			&& !(rettv->v_type == VAR_LIST
2014 						 && rettv->vval.v_list != NULL)
2015 			&& !(rettv->v_type == VAR_BLOB
2016 						&& rettv->vval.v_blob != NULL))
2017 		{
2018 		    if (!quiet)
2019 			emsg(_("E709: [:] requires a List or Blob value"));
2020 		    clear_tv(&var1);
2021 		    return NULL;
2022 		}
2023 		p = skipwhite(p + 1);
2024 		if (*p == ']')
2025 		    lp->ll_empty2 = TRUE;
2026 		else
2027 		{
2028 		    lp->ll_empty2 = FALSE;
2029 		    if (eval1(&p, &var2, TRUE) == FAIL)	/* recursive! */
2030 		    {
2031 			clear_tv(&var1);
2032 			return NULL;
2033 		    }
2034 		    if (tv_get_string_chk(&var2) == NULL)
2035 		    {
2036 			/* not a number or string */
2037 			clear_tv(&var1);
2038 			clear_tv(&var2);
2039 			return NULL;
2040 		    }
2041 		}
2042 		lp->ll_range = TRUE;
2043 	    }
2044 	    else
2045 		lp->ll_range = FALSE;
2046 
2047 	    if (*p != ']')
2048 	    {
2049 		if (!quiet)
2050 		    emsg(_(e_missbrac));
2051 		clear_tv(&var1);
2052 		clear_tv(&var2);
2053 		return NULL;
2054 	    }
2055 
2056 	    /* Skip to past ']'. */
2057 	    ++p;
2058 	}
2059 
2060 	if (lp->ll_tv->v_type == VAR_DICT)
2061 	{
2062 	    if (len == -1)
2063 	    {
2064 		/* "[key]": get key from "var1" */
2065 		key = tv_get_string_chk(&var1);	/* is number or string */
2066 		if (key == NULL)
2067 		{
2068 		    clear_tv(&var1);
2069 		    return NULL;
2070 		}
2071 	    }
2072 	    lp->ll_list = NULL;
2073 	    lp->ll_dict = lp->ll_tv->vval.v_dict;
2074 	    lp->ll_di = dict_find(lp->ll_dict, key, len);
2075 
2076 	    /* When assigning to a scope dictionary check that a function and
2077 	     * variable name is valid (only variable name unless it is l: or
2078 	     * g: dictionary). Disallow overwriting a builtin function. */
2079 	    if (rettv != NULL && lp->ll_dict->dv_scope != 0)
2080 	    {
2081 		int prevval;
2082 		int wrong;
2083 
2084 		if (len != -1)
2085 		{
2086 		    prevval = key[len];
2087 		    key[len] = NUL;
2088 		}
2089 		else
2090 		    prevval = 0; /* avoid compiler warning */
2091 		wrong = (lp->ll_dict->dv_scope == VAR_DEF_SCOPE
2092 			       && rettv->v_type == VAR_FUNC
2093 			       && var_check_func_name(key, lp->ll_di == NULL))
2094 			|| !valid_varname(key);
2095 		if (len != -1)
2096 		    key[len] = prevval;
2097 		if (wrong)
2098 		    return NULL;
2099 	    }
2100 
2101 	    if (lp->ll_di == NULL)
2102 	    {
2103 		// Can't add "v:" or "a:" variable.
2104 		if (lp->ll_dict == &vimvardict
2105 			 || &lp->ll_dict->dv_hashtab == get_funccal_args_ht())
2106 		{
2107 		    semsg(_(e_illvar), name);
2108 		    return NULL;
2109 		}
2110 
2111 		// Key does not exist in dict: may need to add it.
2112 		if (*p == '[' || *p == '.' || unlet)
2113 		{
2114 		    if (!quiet)
2115 			semsg(_(e_dictkey), key);
2116 		    clear_tv(&var1);
2117 		    return NULL;
2118 		}
2119 		if (len == -1)
2120 		    lp->ll_newkey = vim_strsave(key);
2121 		else
2122 		    lp->ll_newkey = vim_strnsave(key, len);
2123 		clear_tv(&var1);
2124 		if (lp->ll_newkey == NULL)
2125 		    p = NULL;
2126 		break;
2127 	    }
2128 	    /* existing variable, need to check if it can be changed */
2129 	    else if ((flags & GLV_READ_ONLY) == 0
2130 			     && var_check_ro(lp->ll_di->di_flags, name, FALSE))
2131 	    {
2132 		clear_tv(&var1);
2133 		return NULL;
2134 	    }
2135 
2136 	    clear_tv(&var1);
2137 	    lp->ll_tv = &lp->ll_di->di_tv;
2138 	}
2139 	else if (lp->ll_tv->v_type == VAR_BLOB)
2140 	{
2141 	    long bloblen = blob_len(lp->ll_tv->vval.v_blob);
2142 
2143 	    /*
2144 	     * Get the number and item for the only or first index of the List.
2145 	     */
2146 	    if (empty1)
2147 		lp->ll_n1 = 0;
2148 	    else
2149 		// is number or string
2150 		lp->ll_n1 = (long)tv_get_number(&var1);
2151 	    clear_tv(&var1);
2152 
2153 	    if (lp->ll_n1 < 0
2154 		    || lp->ll_n1 > bloblen
2155 		    || (lp->ll_range && lp->ll_n1 == bloblen))
2156 	    {
2157 		if (!quiet)
2158 		    semsg(_(e_blobidx), lp->ll_n1);
2159 		clear_tv(&var2);
2160 		return NULL;
2161 	    }
2162 	    if (lp->ll_range && !lp->ll_empty2)
2163 	    {
2164 		lp->ll_n2 = (long)tv_get_number(&var2);
2165 		clear_tv(&var2);
2166 		if (lp->ll_n2 < 0
2167 			|| lp->ll_n2 >= bloblen
2168 			|| lp->ll_n2 < lp->ll_n1)
2169 		{
2170 		    if (!quiet)
2171 			semsg(_(e_blobidx), lp->ll_n2);
2172 		    return NULL;
2173 		}
2174 	    }
2175 	    lp->ll_blob = lp->ll_tv->vval.v_blob;
2176 	    lp->ll_tv = NULL;
2177 	}
2178 	else
2179 	{
2180 	    /*
2181 	     * Get the number and item for the only or first index of the List.
2182 	     */
2183 	    if (empty1)
2184 		lp->ll_n1 = 0;
2185 	    else
2186 		/* is number or string */
2187 		lp->ll_n1 = (long)tv_get_number(&var1);
2188 	    clear_tv(&var1);
2189 
2190 	    lp->ll_dict = NULL;
2191 	    lp->ll_list = lp->ll_tv->vval.v_list;
2192 	    lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2193 	    if (lp->ll_li == NULL)
2194 	    {
2195 		if (lp->ll_n1 < 0)
2196 		{
2197 		    lp->ll_n1 = 0;
2198 		    lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2199 		}
2200 	    }
2201 	    if (lp->ll_li == NULL)
2202 	    {
2203 		clear_tv(&var2);
2204 		if (!quiet)
2205 		    semsg(_(e_listidx), lp->ll_n1);
2206 		return NULL;
2207 	    }
2208 
2209 	    /*
2210 	     * May need to find the item or absolute index for the second
2211 	     * index of a range.
2212 	     * When no index given: "lp->ll_empty2" is TRUE.
2213 	     * Otherwise "lp->ll_n2" is set to the second index.
2214 	     */
2215 	    if (lp->ll_range && !lp->ll_empty2)
2216 	    {
2217 		lp->ll_n2 = (long)tv_get_number(&var2);
2218 						    /* is number or string */
2219 		clear_tv(&var2);
2220 		if (lp->ll_n2 < 0)
2221 		{
2222 		    ni = list_find(lp->ll_list, lp->ll_n2);
2223 		    if (ni == NULL)
2224 		    {
2225 			if (!quiet)
2226 			    semsg(_(e_listidx), lp->ll_n2);
2227 			return NULL;
2228 		    }
2229 		    lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2230 		}
2231 
2232 		/* Check that lp->ll_n2 isn't before lp->ll_n1. */
2233 		if (lp->ll_n1 < 0)
2234 		    lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2235 		if (lp->ll_n2 < lp->ll_n1)
2236 		{
2237 		    if (!quiet)
2238 			semsg(_(e_listidx), lp->ll_n2);
2239 		    return NULL;
2240 		}
2241 	    }
2242 
2243 	    lp->ll_tv = &lp->ll_li->li_tv;
2244 	}
2245     }
2246 
2247     clear_tv(&var1);
2248     return p;
2249 }
2250 
2251 /*
2252  * Clear lval "lp" that was filled by get_lval().
2253  */
2254     void
2255 clear_lval(lval_T *lp)
2256 {
2257     vim_free(lp->ll_exp_name);
2258     vim_free(lp->ll_newkey);
2259 }
2260 
2261 /*
2262  * Set a variable that was parsed by get_lval() to "rettv".
2263  * "endp" points to just after the parsed name.
2264  * "op" is NULL, "+" for "+=", "-" for "-=", "*" for "*=", "/" for "/=",
2265  * "%" for "%=", "." for ".=" or "=" for "=".
2266  */
2267     static void
2268 set_var_lval(
2269     lval_T	*lp,
2270     char_u	*endp,
2271     typval_T	*rettv,
2272     int		copy,
2273     char_u	*op)
2274 {
2275     int		cc;
2276     listitem_T	*ri;
2277     dictitem_T	*di;
2278 
2279     if (lp->ll_tv == NULL)
2280     {
2281 	cc = *endp;
2282 	*endp = NUL;
2283 	if (lp->ll_blob != NULL)
2284 	{
2285 	    int	    error = FALSE, val;
2286 
2287 	    if (op != NULL && *op != '=')
2288 	    {
2289 		semsg(_(e_letwrong), op);
2290 		return;
2291 	    }
2292 
2293 	    if (lp->ll_range && rettv->v_type == VAR_BLOB)
2294 	    {
2295 		int	il, ir;
2296 
2297 		if (lp->ll_empty2)
2298 		    lp->ll_n2 = blob_len(lp->ll_blob) - 1;
2299 
2300 		if (lp->ll_n2 - lp->ll_n1 + 1 != blob_len(rettv->vval.v_blob))
2301 		{
2302 		    emsg(_("E972: Blob value does not have the right number of bytes"));
2303 		    return;
2304 		}
2305 		if (lp->ll_empty2)
2306 		    lp->ll_n2 = blob_len(lp->ll_blob);
2307 
2308 		ir = 0;
2309 		for (il = lp->ll_n1; il <= lp->ll_n2; il++)
2310 		    blob_set(lp->ll_blob, il,
2311 			    blob_get(rettv->vval.v_blob, ir++));
2312 	    }
2313 	    else
2314 	    {
2315 		val = (int)tv_get_number_chk(rettv, &error);
2316 		if (!error)
2317 		{
2318 		    garray_T *gap = &lp->ll_blob->bv_ga;
2319 
2320 		    // Allow for appending a byte.  Setting a byte beyond
2321 		    // the end is an error otherwise.
2322 		    if (lp->ll_n1 < gap->ga_len
2323 			    || (lp->ll_n1 == gap->ga_len
2324 				&& ga_grow(&lp->ll_blob->bv_ga, 1) == OK))
2325 		    {
2326 			blob_set(lp->ll_blob, lp->ll_n1, val);
2327 			if (lp->ll_n1 == gap->ga_len)
2328 			    ++gap->ga_len;
2329 		    }
2330 		    // error for invalid range was already given in get_lval()
2331 		}
2332 	    }
2333 	}
2334 	else if (op != NULL && *op != '=')
2335 	{
2336 	    typval_T tv;
2337 
2338 	    // handle +=, -=, *=, /=, %= and .=
2339 	    di = NULL;
2340 	    if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2341 					     &tv, &di, TRUE, FALSE) == OK)
2342 	    {
2343 		if ((di == NULL
2344 			 || (!var_check_ro(di->di_flags, lp->ll_name, FALSE)
2345 			   && !tv_check_lock(&di->di_tv, lp->ll_name, FALSE)))
2346 			&& tv_op(&tv, rettv, op) == OK)
2347 		    set_var(lp->ll_name, &tv, FALSE);
2348 		clear_tv(&tv);
2349 	    }
2350 	}
2351 	else
2352 	    set_var(lp->ll_name, rettv, copy);
2353 	*endp = cc;
2354     }
2355     else if (var_check_lock(lp->ll_newkey == NULL
2356 		? lp->ll_tv->v_lock
2357 		: lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name, FALSE))
2358 	;
2359     else if (lp->ll_range)
2360     {
2361 	listitem_T *ll_li = lp->ll_li;
2362 	int	    ll_n1 = lp->ll_n1;
2363 
2364 	/*
2365 	 * Check whether any of the list items is locked
2366 	 */
2367 	for (ri = rettv->vval.v_list->lv_first; ri != NULL && ll_li != NULL; )
2368 	{
2369 	    if (var_check_lock(ll_li->li_tv.v_lock, lp->ll_name, FALSE))
2370 		return;
2371 	    ri = ri->li_next;
2372 	    if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == ll_n1))
2373 		break;
2374 	    ll_li = ll_li->li_next;
2375 	    ++ll_n1;
2376 	}
2377 
2378 	/*
2379 	 * Assign the List values to the list items.
2380 	 */
2381 	for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2382 	{
2383 	    if (op != NULL && *op != '=')
2384 		tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2385 	    else
2386 	    {
2387 		clear_tv(&lp->ll_li->li_tv);
2388 		copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2389 	    }
2390 	    ri = ri->li_next;
2391 	    if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2392 		break;
2393 	    if (lp->ll_li->li_next == NULL)
2394 	    {
2395 		/* Need to add an empty item. */
2396 		if (list_append_number(lp->ll_list, 0) == FAIL)
2397 		{
2398 		    ri = NULL;
2399 		    break;
2400 		}
2401 	    }
2402 	    lp->ll_li = lp->ll_li->li_next;
2403 	    ++lp->ll_n1;
2404 	}
2405 	if (ri != NULL)
2406 	    emsg(_("E710: List value has more items than target"));
2407 	else if (lp->ll_empty2
2408 		? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2409 		: lp->ll_n1 != lp->ll_n2)
2410 	    emsg(_("E711: List value has not enough items"));
2411     }
2412     else
2413     {
2414 	/*
2415 	 * Assign to a List or Dictionary item.
2416 	 */
2417 	if (lp->ll_newkey != NULL)
2418 	{
2419 	    if (op != NULL && *op != '=')
2420 	    {
2421 		semsg(_(e_letwrong), op);
2422 		return;
2423 	    }
2424 
2425 	    /* Need to add an item to the Dictionary. */
2426 	    di = dictitem_alloc(lp->ll_newkey);
2427 	    if (di == NULL)
2428 		return;
2429 	    if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2430 	    {
2431 		vim_free(di);
2432 		return;
2433 	    }
2434 	    lp->ll_tv = &di->di_tv;
2435 	}
2436 	else if (op != NULL && *op != '=')
2437 	{
2438 	    tv_op(lp->ll_tv, rettv, op);
2439 	    return;
2440 	}
2441 	else
2442 	    clear_tv(lp->ll_tv);
2443 
2444 	/*
2445 	 * Assign the value to the variable or list item.
2446 	 */
2447 	if (copy)
2448 	    copy_tv(rettv, lp->ll_tv);
2449 	else
2450 	{
2451 	    *lp->ll_tv = *rettv;
2452 	    lp->ll_tv->v_lock = 0;
2453 	    init_tv(rettv);
2454 	}
2455     }
2456 }
2457 
2458 /*
2459  * Handle "tv1 += tv2", "tv1 -= tv2", "tv1 *= tv2", "tv1 /= tv2", "tv1 %= tv2"
2460  * and "tv1 .= tv2"
2461  * Returns OK or FAIL.
2462  */
2463     static int
2464 tv_op(typval_T *tv1, typval_T *tv2, char_u *op)
2465 {
2466     varnumber_T	n;
2467     char_u	numbuf[NUMBUFLEN];
2468     char_u	*s;
2469 
2470     /* Can't do anything with a Funcref, Dict, v:true on the right. */
2471     if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT
2472 						&& tv2->v_type != VAR_SPECIAL)
2473     {
2474 	switch (tv1->v_type)
2475 	{
2476 	    case VAR_UNKNOWN:
2477 	    case VAR_DICT:
2478 	    case VAR_FUNC:
2479 	    case VAR_PARTIAL:
2480 	    case VAR_SPECIAL:
2481 	    case VAR_JOB:
2482 	    case VAR_CHANNEL:
2483 		break;
2484 
2485 	    case VAR_BLOB:
2486 		if (*op != '+' || tv2->v_type != VAR_BLOB)
2487 		    break;
2488 		// BLOB += BLOB
2489 		if (tv1->vval.v_blob != NULL && tv2->vval.v_blob != NULL)
2490 		{
2491 		    blob_T  *b1 = tv1->vval.v_blob;
2492 		    blob_T  *b2 = tv2->vval.v_blob;
2493 		    int	i, len = blob_len(b2);
2494 		    for (i = 0; i < len; i++)
2495 			ga_append(&b1->bv_ga, blob_get(b2, i));
2496 		}
2497 		return OK;
2498 
2499 	    case VAR_LIST:
2500 		if (*op != '+' || tv2->v_type != VAR_LIST)
2501 		    break;
2502 		// List += List
2503 		if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2504 		    list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2505 		return OK;
2506 
2507 	    case VAR_NUMBER:
2508 	    case VAR_STRING:
2509 		if (tv2->v_type == VAR_LIST)
2510 		    break;
2511 		if (vim_strchr((char_u *)"+-*/%", *op) != NULL)
2512 		{
2513 		    // nr += nr , nr -= nr , nr *=nr , nr /= nr , nr %= nr
2514 		    n = tv_get_number(tv1);
2515 #ifdef FEAT_FLOAT
2516 		    if (tv2->v_type == VAR_FLOAT)
2517 		    {
2518 			float_T f = n;
2519 
2520 			if (*op == '%')
2521 			    break;
2522 			switch (*op)
2523 			{
2524 			    case '+': f += tv2->vval.v_float; break;
2525 			    case '-': f -= tv2->vval.v_float; break;
2526 			    case '*': f *= tv2->vval.v_float; break;
2527 			    case '/': f /= tv2->vval.v_float; break;
2528 			}
2529 			clear_tv(tv1);
2530 			tv1->v_type = VAR_FLOAT;
2531 			tv1->vval.v_float = f;
2532 		    }
2533 		    else
2534 #endif
2535 		    {
2536 			switch (*op)
2537 			{
2538 			    case '+': n += tv_get_number(tv2); break;
2539 			    case '-': n -= tv_get_number(tv2); break;
2540 			    case '*': n *= tv_get_number(tv2); break;
2541 			    case '/': n /= tv_get_number(tv2); break;
2542 			    case '%': n %= tv_get_number(tv2); break;
2543 			}
2544 			clear_tv(tv1);
2545 			tv1->v_type = VAR_NUMBER;
2546 			tv1->vval.v_number = n;
2547 		    }
2548 		}
2549 		else
2550 		{
2551 		    if (tv2->v_type == VAR_FLOAT)
2552 			break;
2553 
2554 		    // str .= str
2555 		    s = tv_get_string(tv1);
2556 		    s = concat_str(s, tv_get_string_buf(tv2, numbuf));
2557 		    clear_tv(tv1);
2558 		    tv1->v_type = VAR_STRING;
2559 		    tv1->vval.v_string = s;
2560 		}
2561 		return OK;
2562 
2563 	    case VAR_FLOAT:
2564 #ifdef FEAT_FLOAT
2565 		{
2566 		    float_T f;
2567 
2568 		    if (*op == '%' || *op == '.'
2569 				   || (tv2->v_type != VAR_FLOAT
2570 				    && tv2->v_type != VAR_NUMBER
2571 				    && tv2->v_type != VAR_STRING))
2572 			break;
2573 		    if (tv2->v_type == VAR_FLOAT)
2574 			f = tv2->vval.v_float;
2575 		    else
2576 			f = tv_get_number(tv2);
2577 		    switch (*op)
2578 		    {
2579 			case '+': tv1->vval.v_float += f; break;
2580 			case '-': tv1->vval.v_float -= f; break;
2581 			case '*': tv1->vval.v_float *= f; break;
2582 			case '/': tv1->vval.v_float /= f; break;
2583 		    }
2584 		}
2585 #endif
2586 		return OK;
2587 	}
2588     }
2589 
2590     semsg(_(e_letwrong), op);
2591     return FAIL;
2592 }
2593 
2594 /*
2595  * Evaluate the expression used in a ":for var in expr" command.
2596  * "arg" points to "var".
2597  * Set "*errp" to TRUE for an error, FALSE otherwise;
2598  * Return a pointer that holds the info.  Null when there is an error.
2599  */
2600     void *
2601 eval_for_line(
2602     char_u	*arg,
2603     int		*errp,
2604     char_u	**nextcmdp,
2605     int		skip)
2606 {
2607     forinfo_T	*fi;
2608     char_u	*expr;
2609     typval_T	tv;
2610     list_T	*l;
2611 
2612     *errp = TRUE;	/* default: there is an error */
2613 
2614     fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
2615     if (fi == NULL)
2616 	return NULL;
2617 
2618     expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
2619     if (expr == NULL)
2620 	return fi;
2621 
2622     expr = skipwhite(expr);
2623     if (expr[0] != 'i' || expr[1] != 'n' || !VIM_ISWHITE(expr[2]))
2624     {
2625 	emsg(_("E690: Missing \"in\" after :for"));
2626 	return fi;
2627     }
2628 
2629     if (skip)
2630 	++emsg_skip;
2631     if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
2632     {
2633 	*errp = FALSE;
2634 	if (!skip)
2635 	{
2636 	    if (tv.v_type == VAR_LIST)
2637 	    {
2638 		l = tv.vval.v_list;
2639 		if (l == NULL)
2640 		{
2641 		    // a null list is like an empty list: do nothing
2642 		    clear_tv(&tv);
2643 		}
2644 		else
2645 		{
2646 		    // No need to increment the refcount, it's already set for
2647 		    // the list being used in "tv".
2648 		    fi->fi_list = l;
2649 		    list_add_watch(l, &fi->fi_lw);
2650 		    fi->fi_lw.lw_item = l->lv_first;
2651 		}
2652 	    }
2653 	    else if (tv.v_type == VAR_BLOB)
2654 	    {
2655 		fi->fi_bi = 0;
2656 		if (tv.vval.v_blob != NULL)
2657 		{
2658 		    typval_T btv;
2659 
2660 		    // Make a copy, so that the iteration still works when the
2661 		    // blob is changed.
2662 		    blob_copy(&tv, &btv);
2663 		    fi->fi_blob = btv.vval.v_blob;
2664 		}
2665 		clear_tv(&tv);
2666 	    }
2667 	    else
2668 	    {
2669 		emsg(_(e_listreq));
2670 		clear_tv(&tv);
2671 	    }
2672 	}
2673     }
2674     if (skip)
2675 	--emsg_skip;
2676 
2677     return fi;
2678 }
2679 
2680 /*
2681  * Use the first item in a ":for" list.  Advance to the next.
2682  * Assign the values to the variable (list).  "arg" points to the first one.
2683  * Return TRUE when a valid item was found, FALSE when at end of list or
2684  * something wrong.
2685  */
2686     int
2687 next_for_item(void *fi_void, char_u *arg)
2688 {
2689     forinfo_T	*fi = (forinfo_T *)fi_void;
2690     int		result;
2691     listitem_T	*item;
2692 
2693     if (fi->fi_blob != NULL)
2694     {
2695 	typval_T	tv;
2696 
2697 	if (fi->fi_bi >= blob_len(fi->fi_blob))
2698 	    return FALSE;
2699 	tv.v_type = VAR_NUMBER;
2700 	tv.v_lock = VAR_FIXED;
2701 	tv.vval.v_number = blob_get(fi->fi_blob, fi->fi_bi);
2702 	++fi->fi_bi;
2703 	return ex_let_vars(arg, &tv, TRUE,
2704 			      fi->fi_semicolon, fi->fi_varcount, NULL) == OK;
2705     }
2706 
2707     item = fi->fi_lw.lw_item;
2708     if (item == NULL)
2709 	result = FALSE;
2710     else
2711     {
2712 	fi->fi_lw.lw_item = item->li_next;
2713 	result = (ex_let_vars(arg, &item->li_tv, TRUE,
2714 			      fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
2715     }
2716     return result;
2717 }
2718 
2719 /*
2720  * Free the structure used to store info used by ":for".
2721  */
2722     void
2723 free_for_info(void *fi_void)
2724 {
2725     forinfo_T    *fi = (forinfo_T *)fi_void;
2726 
2727     if (fi != NULL && fi->fi_list != NULL)
2728     {
2729 	list_rem_watch(fi->fi_list, &fi->fi_lw);
2730 	list_unref(fi->fi_list);
2731     }
2732     if (fi != NULL && fi->fi_blob != NULL)
2733 	blob_unref(fi->fi_blob);
2734     vim_free(fi);
2735 }
2736 
2737 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2738 
2739     void
2740 set_context_for_expression(
2741     expand_T	*xp,
2742     char_u	*arg,
2743     cmdidx_T	cmdidx)
2744 {
2745     int		got_eq = FALSE;
2746     int		c;
2747     char_u	*p;
2748 
2749     if (cmdidx == CMD_let)
2750     {
2751 	xp->xp_context = EXPAND_USER_VARS;
2752 	if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
2753 	{
2754 	    /* ":let var1 var2 ...": find last space. */
2755 	    for (p = arg + STRLEN(arg); p >= arg; )
2756 	    {
2757 		xp->xp_pattern = p;
2758 		MB_PTR_BACK(arg, p);
2759 		if (VIM_ISWHITE(*p))
2760 		    break;
2761 	    }
2762 	    return;
2763 	}
2764     }
2765     else
2766 	xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
2767 							  : EXPAND_EXPRESSION;
2768     while ((xp->xp_pattern = vim_strpbrk(arg,
2769 				  (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
2770     {
2771 	c = *xp->xp_pattern;
2772 	if (c == '&')
2773 	{
2774 	    c = xp->xp_pattern[1];
2775 	    if (c == '&')
2776 	    {
2777 		++xp->xp_pattern;
2778 		xp->xp_context = cmdidx != CMD_let || got_eq
2779 					 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
2780 	    }
2781 	    else if (c != ' ')
2782 	    {
2783 		xp->xp_context = EXPAND_SETTINGS;
2784 		if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
2785 		    xp->xp_pattern += 2;
2786 
2787 	    }
2788 	}
2789 	else if (c == '$')
2790 	{
2791 	    /* environment variable */
2792 	    xp->xp_context = EXPAND_ENV_VARS;
2793 	}
2794 	else if (c == '=')
2795 	{
2796 	    got_eq = TRUE;
2797 	    xp->xp_context = EXPAND_EXPRESSION;
2798 	}
2799 	else if (c == '#'
2800 		&& xp->xp_context == EXPAND_EXPRESSION)
2801 	{
2802 	    /* Autoload function/variable contains '#'. */
2803 	    break;
2804 	}
2805 	else if ((c == '<' || c == '#')
2806 		&& xp->xp_context == EXPAND_FUNCTIONS
2807 		&& vim_strchr(xp->xp_pattern, '(') == NULL)
2808 	{
2809 	    /* Function name can start with "<SNR>" and contain '#'. */
2810 	    break;
2811 	}
2812 	else if (cmdidx != CMD_let || got_eq)
2813 	{
2814 	    if (c == '"')	    /* string */
2815 	    {
2816 		while ((c = *++xp->xp_pattern) != NUL && c != '"')
2817 		    if (c == '\\' && xp->xp_pattern[1] != NUL)
2818 			++xp->xp_pattern;
2819 		xp->xp_context = EXPAND_NOTHING;
2820 	    }
2821 	    else if (c == '\'')	    /* literal string */
2822 	    {
2823 		/* Trick: '' is like stopping and starting a literal string. */
2824 		while ((c = *++xp->xp_pattern) != NUL && c != '\'')
2825 		    /* skip */ ;
2826 		xp->xp_context = EXPAND_NOTHING;
2827 	    }
2828 	    else if (c == '|')
2829 	    {
2830 		if (xp->xp_pattern[1] == '|')
2831 		{
2832 		    ++xp->xp_pattern;
2833 		    xp->xp_context = EXPAND_EXPRESSION;
2834 		}
2835 		else
2836 		    xp->xp_context = EXPAND_COMMANDS;
2837 	    }
2838 	    else
2839 		xp->xp_context = EXPAND_EXPRESSION;
2840 	}
2841 	else
2842 	    /* Doesn't look like something valid, expand as an expression
2843 	     * anyway. */
2844 	    xp->xp_context = EXPAND_EXPRESSION;
2845 	arg = xp->xp_pattern;
2846 	if (*arg != NUL)
2847 	    while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
2848 		/* skip */ ;
2849     }
2850     xp->xp_pattern = arg;
2851 }
2852 
2853 #endif /* FEAT_CMDL_COMPL */
2854 
2855 /*
2856  * ":unlet[!] var1 ... " command.
2857  */
2858     void
2859 ex_unlet(exarg_T *eap)
2860 {
2861     ex_unletlock(eap, eap->arg, 0);
2862 }
2863 
2864 /*
2865  * ":lockvar" and ":unlockvar" commands
2866  */
2867     void
2868 ex_lockvar(exarg_T *eap)
2869 {
2870     char_u	*arg = eap->arg;
2871     int		deep = 2;
2872 
2873     if (eap->forceit)
2874 	deep = -1;
2875     else if (vim_isdigit(*arg))
2876     {
2877 	deep = getdigits(&arg);
2878 	arg = skipwhite(arg);
2879     }
2880 
2881     ex_unletlock(eap, arg, deep);
2882 }
2883 
2884 /*
2885  * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
2886  */
2887     static void
2888 ex_unletlock(
2889     exarg_T	*eap,
2890     char_u	*argstart,
2891     int		deep)
2892 {
2893     char_u	*arg = argstart;
2894     char_u	*name_end;
2895     int		error = FALSE;
2896     lval_T	lv;
2897 
2898     do
2899     {
2900 	if (*arg == '$')
2901 	{
2902 	    char_u    *name = ++arg;
2903 
2904 	    if (get_env_len(&arg) == 0)
2905 	    {
2906 		semsg(_(e_invarg2), name - 1);
2907 		return;
2908 	    }
2909 	    vim_unsetenv(name);
2910 	    arg = skipwhite(arg);
2911 	    continue;
2912 	}
2913 
2914 	/* Parse the name and find the end. */
2915 	name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, 0,
2916 							     FNE_CHECK_START);
2917 	if (lv.ll_name == NULL)
2918 	    error = TRUE;	    /* error but continue parsing */
2919 	if (name_end == NULL || (!VIM_ISWHITE(*name_end)
2920 						   && !ends_excmd(*name_end)))
2921 	{
2922 	    if (name_end != NULL)
2923 	    {
2924 		emsg_severe = TRUE;
2925 		emsg(_(e_trailing));
2926 	    }
2927 	    if (!(eap->skip || error))
2928 		clear_lval(&lv);
2929 	    break;
2930 	}
2931 
2932 	if (!error && !eap->skip)
2933 	{
2934 	    if (eap->cmdidx == CMD_unlet)
2935 	    {
2936 		if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
2937 		    error = TRUE;
2938 	    }
2939 	    else
2940 	    {
2941 		if (do_lock_var(&lv, name_end, deep,
2942 					  eap->cmdidx == CMD_lockvar) == FAIL)
2943 		    error = TRUE;
2944 	    }
2945 	}
2946 
2947 	if (!eap->skip)
2948 	    clear_lval(&lv);
2949 
2950 	arg = skipwhite(name_end);
2951     } while (!ends_excmd(*arg));
2952 
2953     eap->nextcmd = check_nextcmd(arg);
2954 }
2955 
2956     static int
2957 do_unlet_var(
2958     lval_T	*lp,
2959     char_u	*name_end,
2960     int		forceit)
2961 {
2962     int		ret = OK;
2963     int		cc;
2964 
2965     if (lp->ll_tv == NULL)
2966     {
2967 	cc = *name_end;
2968 	*name_end = NUL;
2969 
2970 	/* Normal name or expanded name. */
2971 	if (do_unlet(lp->ll_name, forceit) == FAIL)
2972 	    ret = FAIL;
2973 	*name_end = cc;
2974     }
2975     else if ((lp->ll_list != NULL
2976 		 && var_check_lock(lp->ll_list->lv_lock, lp->ll_name, FALSE))
2977 	    || (lp->ll_dict != NULL
2978 		 && var_check_lock(lp->ll_dict->dv_lock, lp->ll_name, FALSE)))
2979 	return FAIL;
2980     else if (lp->ll_range)
2981     {
2982 	listitem_T    *li;
2983 	listitem_T    *ll_li = lp->ll_li;
2984 	int	      ll_n1 = lp->ll_n1;
2985 
2986 	while (ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= ll_n1))
2987 	{
2988 	    li = ll_li->li_next;
2989 	    if (var_check_lock(ll_li->li_tv.v_lock, lp->ll_name, FALSE))
2990 		return FAIL;
2991 	    ll_li = li;
2992 	    ++ll_n1;
2993 	}
2994 
2995 	/* Delete a range of List items. */
2996 	while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
2997 	{
2998 	    li = lp->ll_li->li_next;
2999 	    listitem_remove(lp->ll_list, lp->ll_li);
3000 	    lp->ll_li = li;
3001 	    ++lp->ll_n1;
3002 	}
3003     }
3004     else
3005     {
3006 	if (lp->ll_list != NULL)
3007 	    /* unlet a List item. */
3008 	    listitem_remove(lp->ll_list, lp->ll_li);
3009 	else
3010 	    /* unlet a Dictionary item. */
3011 	    dictitem_remove(lp->ll_dict, lp->ll_di);
3012     }
3013 
3014     return ret;
3015 }
3016 
3017 /*
3018  * "unlet" a variable.  Return OK if it existed, FAIL if not.
3019  * When "forceit" is TRUE don't complain if the variable doesn't exist.
3020  */
3021     int
3022 do_unlet(char_u *name, int forceit)
3023 {
3024     hashtab_T	*ht;
3025     hashitem_T	*hi;
3026     char_u	*varname;
3027     dict_T	*d;
3028     dictitem_T	*di;
3029 
3030     ht = find_var_ht(name, &varname);
3031     if (ht != NULL && *varname != NUL)
3032     {
3033 	d = get_current_funccal_dict(ht);
3034 	if (d == NULL)
3035 	{
3036 	    if (ht == &globvarht)
3037 		d = &globvardict;
3038 	    else if (ht == &compat_hashtab)
3039 		d = &vimvardict;
3040 	    else
3041 	    {
3042 		di = find_var_in_ht(ht, *name, (char_u *)"", FALSE);
3043 		d = di == NULL ? NULL : di->di_tv.vval.v_dict;
3044 	    }
3045 	    if (d == NULL)
3046 	    {
3047 		internal_error("do_unlet()");
3048 		return FAIL;
3049 	    }
3050 	}
3051 	hi = hash_find(ht, varname);
3052 	if (HASHITEM_EMPTY(hi))
3053 	    hi = find_hi_in_scoped_ht(name, &ht);
3054 	if (hi != NULL && !HASHITEM_EMPTY(hi))
3055 	{
3056 	    di = HI2DI(hi);
3057 	    if (var_check_fixed(di->di_flags, name, FALSE)
3058 		    || var_check_ro(di->di_flags, name, FALSE)
3059 		    || var_check_lock(d->dv_lock, name, FALSE))
3060 		return FAIL;
3061 
3062 	    delete_var(ht, hi);
3063 	    return OK;
3064 	}
3065     }
3066     if (forceit)
3067 	return OK;
3068     semsg(_("E108: No such variable: \"%s\""), name);
3069     return FAIL;
3070 }
3071 
3072 /*
3073  * Lock or unlock variable indicated by "lp".
3074  * "deep" is the levels to go (-1 for unlimited);
3075  * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3076  */
3077     static int
3078 do_lock_var(
3079     lval_T	*lp,
3080     char_u	*name_end,
3081     int		deep,
3082     int		lock)
3083 {
3084     int		ret = OK;
3085     int		cc;
3086     dictitem_T	*di;
3087 
3088     if (deep == 0)	/* nothing to do */
3089 	return OK;
3090 
3091     if (lp->ll_tv == NULL)
3092     {
3093 	cc = *name_end;
3094 	*name_end = NUL;
3095 
3096 	/* Normal name or expanded name. */
3097 	di = find_var(lp->ll_name, NULL, TRUE);
3098 	if (di == NULL)
3099 	    ret = FAIL;
3100 	else if ((di->di_flags & DI_FLAGS_FIX)
3101 			&& di->di_tv.v_type != VAR_DICT
3102 			&& di->di_tv.v_type != VAR_LIST)
3103 	    /* For historic reasons this error is not given for a list or dict.
3104 	     * E.g., the b: dict could be locked/unlocked. */
3105 	    semsg(_("E940: Cannot lock or unlock variable %s"), lp->ll_name);
3106 	else
3107 	{
3108 	    if (lock)
3109 		di->di_flags |= DI_FLAGS_LOCK;
3110 	    else
3111 		di->di_flags &= ~DI_FLAGS_LOCK;
3112 	    item_lock(&di->di_tv, deep, lock);
3113 	}
3114 	*name_end = cc;
3115     }
3116     else if (lp->ll_range)
3117     {
3118 	listitem_T    *li = lp->ll_li;
3119 
3120 	/* (un)lock a range of List items. */
3121 	while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3122 	{
3123 	    item_lock(&li->li_tv, deep, lock);
3124 	    li = li->li_next;
3125 	    ++lp->ll_n1;
3126 	}
3127     }
3128     else if (lp->ll_list != NULL)
3129 	/* (un)lock a List item. */
3130 	item_lock(&lp->ll_li->li_tv, deep, lock);
3131     else
3132 	/* (un)lock a Dictionary item. */
3133 	item_lock(&lp->ll_di->di_tv, deep, lock);
3134 
3135     return ret;
3136 }
3137 
3138 /*
3139  * Lock or unlock an item.  "deep" is nr of levels to go.
3140  */
3141     static void
3142 item_lock(typval_T *tv, int deep, int lock)
3143 {
3144     static int	recurse = 0;
3145     list_T	*l;
3146     listitem_T	*li;
3147     dict_T	*d;
3148     blob_T	*b;
3149     hashitem_T	*hi;
3150     int		todo;
3151 
3152     if (recurse >= DICT_MAXNEST)
3153     {
3154 	emsg(_("E743: variable nested too deep for (un)lock"));
3155 	return;
3156     }
3157     if (deep == 0)
3158 	return;
3159     ++recurse;
3160 
3161     /* lock/unlock the item itself */
3162     if (lock)
3163 	tv->v_lock |= VAR_LOCKED;
3164     else
3165 	tv->v_lock &= ~VAR_LOCKED;
3166 
3167     switch (tv->v_type)
3168     {
3169 	case VAR_UNKNOWN:
3170 	case VAR_NUMBER:
3171 	case VAR_STRING:
3172 	case VAR_FUNC:
3173 	case VAR_PARTIAL:
3174 	case VAR_FLOAT:
3175 	case VAR_SPECIAL:
3176 	case VAR_JOB:
3177 	case VAR_CHANNEL:
3178 	    break;
3179 
3180 	case VAR_BLOB:
3181 	    if ((b = tv->vval.v_blob) != NULL)
3182 	    {
3183 		if (lock)
3184 		    b->bv_lock |= VAR_LOCKED;
3185 		else
3186 		    b->bv_lock &= ~VAR_LOCKED;
3187 	    }
3188 	    break;
3189 	case VAR_LIST:
3190 	    if ((l = tv->vval.v_list) != NULL)
3191 	    {
3192 		if (lock)
3193 		    l->lv_lock |= VAR_LOCKED;
3194 		else
3195 		    l->lv_lock &= ~VAR_LOCKED;
3196 		if (deep < 0 || deep > 1)
3197 		    /* recursive: lock/unlock the items the List contains */
3198 		    for (li = l->lv_first; li != NULL; li = li->li_next)
3199 			item_lock(&li->li_tv, deep - 1, lock);
3200 	    }
3201 	    break;
3202 	case VAR_DICT:
3203 	    if ((d = tv->vval.v_dict) != NULL)
3204 	    {
3205 		if (lock)
3206 		    d->dv_lock |= VAR_LOCKED;
3207 		else
3208 		    d->dv_lock &= ~VAR_LOCKED;
3209 		if (deep < 0 || deep > 1)
3210 		{
3211 		    /* recursive: lock/unlock the items the List contains */
3212 		    todo = (int)d->dv_hashtab.ht_used;
3213 		    for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3214 		    {
3215 			if (!HASHITEM_EMPTY(hi))
3216 			{
3217 			    --todo;
3218 			    item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3219 			}
3220 		    }
3221 		}
3222 	    }
3223     }
3224     --recurse;
3225 }
3226 
3227 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3228 /*
3229  * Delete all "menutrans_" variables.
3230  */
3231     void
3232 del_menutrans_vars(void)
3233 {
3234     hashitem_T	*hi;
3235     int		todo;
3236 
3237     hash_lock(&globvarht);
3238     todo = (int)globvarht.ht_used;
3239     for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3240     {
3241 	if (!HASHITEM_EMPTY(hi))
3242 	{
3243 	    --todo;
3244 	    if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3245 		delete_var(&globvarht, hi);
3246 	}
3247     }
3248     hash_unlock(&globvarht);
3249 }
3250 #endif
3251 
3252 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3253 
3254 /*
3255  * Local string buffer for the next two functions to store a variable name
3256  * with its prefix. Allocated in cat_prefix_varname(), freed later in
3257  * get_user_var_name().
3258  */
3259 
3260 static char_u	*varnamebuf = NULL;
3261 static int	varnamebuflen = 0;
3262 
3263 /*
3264  * Function to concatenate a prefix and a variable name.
3265  */
3266     static char_u *
3267 cat_prefix_varname(int prefix, char_u *name)
3268 {
3269     int		len;
3270 
3271     len = (int)STRLEN(name) + 3;
3272     if (len > varnamebuflen)
3273     {
3274 	vim_free(varnamebuf);
3275 	len += 10;			/* some additional space */
3276 	varnamebuf = alloc(len);
3277 	if (varnamebuf == NULL)
3278 	{
3279 	    varnamebuflen = 0;
3280 	    return NULL;
3281 	}
3282 	varnamebuflen = len;
3283     }
3284     *varnamebuf = prefix;
3285     varnamebuf[1] = ':';
3286     STRCPY(varnamebuf + 2, name);
3287     return varnamebuf;
3288 }
3289 
3290 /*
3291  * Function given to ExpandGeneric() to obtain the list of user defined
3292  * (global/buffer/window/built-in) variable names.
3293  */
3294     char_u *
3295 get_user_var_name(expand_T *xp, int idx)
3296 {
3297     static long_u	gdone;
3298     static long_u	bdone;
3299     static long_u	wdone;
3300     static long_u	tdone;
3301     static int		vidx;
3302     static hashitem_T	*hi;
3303     hashtab_T		*ht;
3304 
3305     if (idx == 0)
3306     {
3307 	gdone = bdone = wdone = vidx = 0;
3308 	tdone = 0;
3309     }
3310 
3311     /* Global variables */
3312     if (gdone < globvarht.ht_used)
3313     {
3314 	if (gdone++ == 0)
3315 	    hi = globvarht.ht_array;
3316 	else
3317 	    ++hi;
3318 	while (HASHITEM_EMPTY(hi))
3319 	    ++hi;
3320 	if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3321 	    return cat_prefix_varname('g', hi->hi_key);
3322 	return hi->hi_key;
3323     }
3324 
3325     /* b: variables */
3326     ht = &curbuf->b_vars->dv_hashtab;
3327     if (bdone < ht->ht_used)
3328     {
3329 	if (bdone++ == 0)
3330 	    hi = ht->ht_array;
3331 	else
3332 	    ++hi;
3333 	while (HASHITEM_EMPTY(hi))
3334 	    ++hi;
3335 	return cat_prefix_varname('b', hi->hi_key);
3336     }
3337 
3338     /* w: variables */
3339     ht = &curwin->w_vars->dv_hashtab;
3340     if (wdone < ht->ht_used)
3341     {
3342 	if (wdone++ == 0)
3343 	    hi = ht->ht_array;
3344 	else
3345 	    ++hi;
3346 	while (HASHITEM_EMPTY(hi))
3347 	    ++hi;
3348 	return cat_prefix_varname('w', hi->hi_key);
3349     }
3350 
3351     /* t: variables */
3352     ht = &curtab->tp_vars->dv_hashtab;
3353     if (tdone < ht->ht_used)
3354     {
3355 	if (tdone++ == 0)
3356 	    hi = ht->ht_array;
3357 	else
3358 	    ++hi;
3359 	while (HASHITEM_EMPTY(hi))
3360 	    ++hi;
3361 	return cat_prefix_varname('t', hi->hi_key);
3362     }
3363 
3364     /* v: variables */
3365     if (vidx < VV_LEN)
3366 	return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3367 
3368     VIM_CLEAR(varnamebuf);
3369     varnamebuflen = 0;
3370     return NULL;
3371 }
3372 
3373 #endif /* FEAT_CMDL_COMPL */
3374 
3375 /*
3376  * Return TRUE if "pat" matches "text".
3377  * Does not use 'cpo' and always uses 'magic'.
3378  */
3379     static int
3380 pattern_match(char_u *pat, char_u *text, int ic)
3381 {
3382     int		matches = FALSE;
3383     char_u	*save_cpo;
3384     regmatch_T	regmatch;
3385 
3386     /* avoid 'l' flag in 'cpoptions' */
3387     save_cpo = p_cpo;
3388     p_cpo = (char_u *)"";
3389     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
3390     if (regmatch.regprog != NULL)
3391     {
3392 	regmatch.rm_ic = ic;
3393 	matches = vim_regexec_nl(&regmatch, text, (colnr_T)0);
3394 	vim_regfree(regmatch.regprog);
3395     }
3396     p_cpo = save_cpo;
3397     return matches;
3398 }
3399 
3400 /*
3401  * The "evaluate" argument: When FALSE, the argument is only parsed but not
3402  * executed.  The function may return OK, but the rettv will be of type
3403  * VAR_UNKNOWN.  The function still returns FAIL for a syntax error.
3404  */
3405 
3406 /*
3407  * Handle zero level expression.
3408  * This calls eval1() and handles error message and nextcmd.
3409  * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3410  * Note: "rettv.v_lock" is not set.
3411  * Return OK or FAIL.
3412  */
3413     int
3414 eval0(
3415     char_u	*arg,
3416     typval_T	*rettv,
3417     char_u	**nextcmd,
3418     int		evaluate)
3419 {
3420     int		ret;
3421     char_u	*p;
3422     int		did_emsg_before = did_emsg;
3423     int		called_emsg_before = called_emsg;
3424 
3425     p = skipwhite(arg);
3426     ret = eval1(&p, rettv, evaluate);
3427     if (ret == FAIL || !ends_excmd(*p))
3428     {
3429 	if (ret != FAIL)
3430 	    clear_tv(rettv);
3431 	/*
3432 	 * Report the invalid expression unless the expression evaluation has
3433 	 * been cancelled due to an aborting error, an interrupt, or an
3434 	 * exception, or we already gave a more specific error.
3435 	 * Also check called_emsg for when using assert_fails().
3436 	 */
3437 	if (!aborting() && did_emsg == did_emsg_before
3438 					  && called_emsg == called_emsg_before)
3439 	    semsg(_(e_invexpr2), arg);
3440 	ret = FAIL;
3441     }
3442     if (nextcmd != NULL)
3443 	*nextcmd = check_nextcmd(p);
3444 
3445     return ret;
3446 }
3447 
3448 /*
3449  * Handle top level expression:
3450  *	expr2 ? expr1 : expr1
3451  *
3452  * "arg" must point to the first non-white of the expression.
3453  * "arg" is advanced to the next non-white after the recognized expression.
3454  *
3455  * Note: "rettv.v_lock" is not set.
3456  *
3457  * Return OK or FAIL.
3458  */
3459     int
3460 eval1(char_u **arg, typval_T *rettv, int evaluate)
3461 {
3462     int		result;
3463     typval_T	var2;
3464 
3465     /*
3466      * Get the first variable.
3467      */
3468     if (eval2(arg, rettv, evaluate) == FAIL)
3469 	return FAIL;
3470 
3471     if ((*arg)[0] == '?')
3472     {
3473 	result = FALSE;
3474 	if (evaluate)
3475 	{
3476 	    int		error = FALSE;
3477 
3478 	    if (tv_get_number_chk(rettv, &error) != 0)
3479 		result = TRUE;
3480 	    clear_tv(rettv);
3481 	    if (error)
3482 		return FAIL;
3483 	}
3484 
3485 	/*
3486 	 * Get the second variable.
3487 	 */
3488 	*arg = skipwhite(*arg + 1);
3489 	if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3490 	    return FAIL;
3491 
3492 	/*
3493 	 * Check for the ":".
3494 	 */
3495 	if ((*arg)[0] != ':')
3496 	{
3497 	    emsg(_("E109: Missing ':' after '?'"));
3498 	    if (evaluate && result)
3499 		clear_tv(rettv);
3500 	    return FAIL;
3501 	}
3502 
3503 	/*
3504 	 * Get the third variable.
3505 	 */
3506 	*arg = skipwhite(*arg + 1);
3507 	if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3508 	{
3509 	    if (evaluate && result)
3510 		clear_tv(rettv);
3511 	    return FAIL;
3512 	}
3513 	if (evaluate && !result)
3514 	    *rettv = var2;
3515     }
3516 
3517     return OK;
3518 }
3519 
3520 /*
3521  * Handle first level expression:
3522  *	expr2 || expr2 || expr2	    logical OR
3523  *
3524  * "arg" must point to the first non-white of the expression.
3525  * "arg" is advanced to the next non-white after the recognized expression.
3526  *
3527  * Return OK or FAIL.
3528  */
3529     static int
3530 eval2(char_u **arg, typval_T *rettv, int evaluate)
3531 {
3532     typval_T	var2;
3533     long	result;
3534     int		first;
3535     int		error = FALSE;
3536 
3537     /*
3538      * Get the first variable.
3539      */
3540     if (eval3(arg, rettv, evaluate) == FAIL)
3541 	return FAIL;
3542 
3543     /*
3544      * Repeat until there is no following "||".
3545      */
3546     first = TRUE;
3547     result = FALSE;
3548     while ((*arg)[0] == '|' && (*arg)[1] == '|')
3549     {
3550 	if (evaluate && first)
3551 	{
3552 	    if (tv_get_number_chk(rettv, &error) != 0)
3553 		result = TRUE;
3554 	    clear_tv(rettv);
3555 	    if (error)
3556 		return FAIL;
3557 	    first = FALSE;
3558 	}
3559 
3560 	/*
3561 	 * Get the second variable.
3562 	 */
3563 	*arg = skipwhite(*arg + 2);
3564 	if (eval3(arg, &var2, evaluate && !result) == FAIL)
3565 	    return FAIL;
3566 
3567 	/*
3568 	 * Compute the result.
3569 	 */
3570 	if (evaluate && !result)
3571 	{
3572 	    if (tv_get_number_chk(&var2, &error) != 0)
3573 		result = TRUE;
3574 	    clear_tv(&var2);
3575 	    if (error)
3576 		return FAIL;
3577 	}
3578 	if (evaluate)
3579 	{
3580 	    rettv->v_type = VAR_NUMBER;
3581 	    rettv->vval.v_number = result;
3582 	}
3583     }
3584 
3585     return OK;
3586 }
3587 
3588 /*
3589  * Handle second level expression:
3590  *	expr3 && expr3 && expr3	    logical AND
3591  *
3592  * "arg" must point to the first non-white of the expression.
3593  * "arg" is advanced to the next non-white after the recognized expression.
3594  *
3595  * Return OK or FAIL.
3596  */
3597     static int
3598 eval3(char_u **arg, typval_T *rettv, int evaluate)
3599 {
3600     typval_T	var2;
3601     long	result;
3602     int		first;
3603     int		error = FALSE;
3604 
3605     /*
3606      * Get the first variable.
3607      */
3608     if (eval4(arg, rettv, evaluate) == FAIL)
3609 	return FAIL;
3610 
3611     /*
3612      * Repeat until there is no following "&&".
3613      */
3614     first = TRUE;
3615     result = TRUE;
3616     while ((*arg)[0] == '&' && (*arg)[1] == '&')
3617     {
3618 	if (evaluate && first)
3619 	{
3620 	    if (tv_get_number_chk(rettv, &error) == 0)
3621 		result = FALSE;
3622 	    clear_tv(rettv);
3623 	    if (error)
3624 		return FAIL;
3625 	    first = FALSE;
3626 	}
3627 
3628 	/*
3629 	 * Get the second variable.
3630 	 */
3631 	*arg = skipwhite(*arg + 2);
3632 	if (eval4(arg, &var2, evaluate && result) == FAIL)
3633 	    return FAIL;
3634 
3635 	/*
3636 	 * Compute the result.
3637 	 */
3638 	if (evaluate && result)
3639 	{
3640 	    if (tv_get_number_chk(&var2, &error) == 0)
3641 		result = FALSE;
3642 	    clear_tv(&var2);
3643 	    if (error)
3644 		return FAIL;
3645 	}
3646 	if (evaluate)
3647 	{
3648 	    rettv->v_type = VAR_NUMBER;
3649 	    rettv->vval.v_number = result;
3650 	}
3651     }
3652 
3653     return OK;
3654 }
3655 
3656 /*
3657  * Handle third level expression:
3658  *	var1 == var2
3659  *	var1 =~ var2
3660  *	var1 != var2
3661  *	var1 !~ var2
3662  *	var1 > var2
3663  *	var1 >= var2
3664  *	var1 < var2
3665  *	var1 <= var2
3666  *	var1 is var2
3667  *	var1 isnot var2
3668  *
3669  * "arg" must point to the first non-white of the expression.
3670  * "arg" is advanced to the next non-white after the recognized expression.
3671  *
3672  * Return OK or FAIL.
3673  */
3674     static int
3675 eval4(char_u **arg, typval_T *rettv, int evaluate)
3676 {
3677     typval_T	var2;
3678     char_u	*p;
3679     int		i;
3680     exptype_T	type = TYPE_UNKNOWN;
3681     int		type_is = FALSE;    /* TRUE for "is" and "isnot" */
3682     int		len = 2;
3683     int		ic;
3684 
3685     /*
3686      * Get the first variable.
3687      */
3688     if (eval5(arg, rettv, evaluate) == FAIL)
3689 	return FAIL;
3690 
3691     p = *arg;
3692     switch (p[0])
3693     {
3694 	case '=':   if (p[1] == '=')
3695 			type = TYPE_EQUAL;
3696 		    else if (p[1] == '~')
3697 			type = TYPE_MATCH;
3698 		    break;
3699 	case '!':   if (p[1] == '=')
3700 			type = TYPE_NEQUAL;
3701 		    else if (p[1] == '~')
3702 			type = TYPE_NOMATCH;
3703 		    break;
3704 	case '>':   if (p[1] != '=')
3705 		    {
3706 			type = TYPE_GREATER;
3707 			len = 1;
3708 		    }
3709 		    else
3710 			type = TYPE_GEQUAL;
3711 		    break;
3712 	case '<':   if (p[1] != '=')
3713 		    {
3714 			type = TYPE_SMALLER;
3715 			len = 1;
3716 		    }
3717 		    else
3718 			type = TYPE_SEQUAL;
3719 		    break;
3720 	case 'i':   if (p[1] == 's')
3721 		    {
3722 			if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
3723 			    len = 5;
3724 			i = p[len];
3725 			if (!isalnum(i) && i != '_')
3726 			{
3727 			    type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
3728 			    type_is = TRUE;
3729 			}
3730 		    }
3731 		    break;
3732     }
3733 
3734     /*
3735      * If there is a comparative operator, use it.
3736      */
3737     if (type != TYPE_UNKNOWN)
3738     {
3739 	/* extra question mark appended: ignore case */
3740 	if (p[len] == '?')
3741 	{
3742 	    ic = TRUE;
3743 	    ++len;
3744 	}
3745 	/* extra '#' appended: match case */
3746 	else if (p[len] == '#')
3747 	{
3748 	    ic = FALSE;
3749 	    ++len;
3750 	}
3751 	/* nothing appended: use 'ignorecase' */
3752 	else
3753 	    ic = p_ic;
3754 
3755 	/*
3756 	 * Get the second variable.
3757 	 */
3758 	*arg = skipwhite(p + len);
3759 	if (eval5(arg, &var2, evaluate) == FAIL)
3760 	{
3761 	    clear_tv(rettv);
3762 	    return FAIL;
3763 	}
3764 	if (evaluate)
3765 	{
3766 	    int ret = typval_compare(rettv, &var2, type, type_is, ic);
3767 
3768 	    clear_tv(&var2);
3769 	    return ret;
3770 	}
3771     }
3772 
3773     return OK;
3774 }
3775 
3776 /*
3777  * Handle fourth level expression:
3778  *	+	number addition
3779  *	-	number subtraction
3780  *	.	string concatenation
3781  *
3782  * "arg" must point to the first non-white of the expression.
3783  * "arg" is advanced to the next non-white after the recognized expression.
3784  *
3785  * Return OK or FAIL.
3786  */
3787     static int
3788 eval5(char_u **arg, typval_T *rettv, int evaluate)
3789 {
3790     typval_T	var2;
3791     typval_T	var3;
3792     int		op;
3793     varnumber_T	n1, n2;
3794 #ifdef FEAT_FLOAT
3795     float_T	f1 = 0, f2 = 0;
3796 #endif
3797     char_u	*s1, *s2;
3798     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
3799     char_u	*p;
3800 
3801     /*
3802      * Get the first variable.
3803      */
3804     if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
3805 	return FAIL;
3806 
3807     /*
3808      * Repeat computing, until no '+', '-' or '.' is following.
3809      */
3810     for (;;)
3811     {
3812 	op = **arg;
3813 	if (op != '+' && op != '-' && op != '.')
3814 	    break;
3815 
3816 	if ((op != '+' || (rettv->v_type != VAR_LIST
3817 						 && rettv->v_type != VAR_BLOB))
3818 #ifdef FEAT_FLOAT
3819 		&& (op == '.' || rettv->v_type != VAR_FLOAT)
3820 #endif
3821 		)
3822 	{
3823 	    /* For "list + ...", an illegal use of the first operand as
3824 	     * a number cannot be determined before evaluating the 2nd
3825 	     * operand: if this is also a list, all is ok.
3826 	     * For "something . ...", "something - ..." or "non-list + ...",
3827 	     * we know that the first operand needs to be a string or number
3828 	     * without evaluating the 2nd operand.  So check before to avoid
3829 	     * side effects after an error. */
3830 	    if (evaluate && tv_get_string_chk(rettv) == NULL)
3831 	    {
3832 		clear_tv(rettv);
3833 		return FAIL;
3834 	    }
3835 	}
3836 
3837 	/*
3838 	 * Get the second variable.
3839 	 */
3840 	*arg = skipwhite(*arg + 1);
3841 	if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
3842 	{
3843 	    clear_tv(rettv);
3844 	    return FAIL;
3845 	}
3846 
3847 	if (evaluate)
3848 	{
3849 	    /*
3850 	     * Compute the result.
3851 	     */
3852 	    if (op == '.')
3853 	    {
3854 		s1 = tv_get_string_buf(rettv, buf1);	/* already checked */
3855 		s2 = tv_get_string_buf_chk(&var2, buf2);
3856 		if (s2 == NULL)		/* type error ? */
3857 		{
3858 		    clear_tv(rettv);
3859 		    clear_tv(&var2);
3860 		    return FAIL;
3861 		}
3862 		p = concat_str(s1, s2);
3863 		clear_tv(rettv);
3864 		rettv->v_type = VAR_STRING;
3865 		rettv->vval.v_string = p;
3866 	    }
3867 	    else if (op == '+' && rettv->v_type == VAR_BLOB
3868 						   && var2.v_type == VAR_BLOB)
3869 	    {
3870 		blob_T  *b1 = rettv->vval.v_blob;
3871 		blob_T  *b2 = var2.vval.v_blob;
3872 		blob_T	*b = blob_alloc();
3873 		int	i;
3874 
3875 		if (b != NULL)
3876 		{
3877 		    for (i = 0; i < blob_len(b1); i++)
3878 			ga_append(&b->bv_ga, blob_get(b1, i));
3879 		    for (i = 0; i < blob_len(b2); i++)
3880 			ga_append(&b->bv_ga, blob_get(b2, i));
3881 
3882 		    clear_tv(rettv);
3883 		    rettv_blob_set(rettv, b);
3884 		}
3885 	    }
3886 	    else if (op == '+' && rettv->v_type == VAR_LIST
3887 						   && var2.v_type == VAR_LIST)
3888 	    {
3889 		/* concatenate Lists */
3890 		if (list_concat(rettv->vval.v_list, var2.vval.v_list,
3891 							       &var3) == FAIL)
3892 		{
3893 		    clear_tv(rettv);
3894 		    clear_tv(&var2);
3895 		    return FAIL;
3896 		}
3897 		clear_tv(rettv);
3898 		*rettv = var3;
3899 	    }
3900 	    else
3901 	    {
3902 		int	    error = FALSE;
3903 
3904 #ifdef FEAT_FLOAT
3905 		if (rettv->v_type == VAR_FLOAT)
3906 		{
3907 		    f1 = rettv->vval.v_float;
3908 		    n1 = 0;
3909 		}
3910 		else
3911 #endif
3912 		{
3913 		    n1 = tv_get_number_chk(rettv, &error);
3914 		    if (error)
3915 		    {
3916 			/* This can only happen for "list + non-list".  For
3917 			 * "non-list + ..." or "something - ...", we returned
3918 			 * before evaluating the 2nd operand. */
3919 			clear_tv(rettv);
3920 			return FAIL;
3921 		    }
3922 #ifdef FEAT_FLOAT
3923 		    if (var2.v_type == VAR_FLOAT)
3924 			f1 = n1;
3925 #endif
3926 		}
3927 #ifdef FEAT_FLOAT
3928 		if (var2.v_type == VAR_FLOAT)
3929 		{
3930 		    f2 = var2.vval.v_float;
3931 		    n2 = 0;
3932 		}
3933 		else
3934 #endif
3935 		{
3936 		    n2 = tv_get_number_chk(&var2, &error);
3937 		    if (error)
3938 		    {
3939 			clear_tv(rettv);
3940 			clear_tv(&var2);
3941 			return FAIL;
3942 		    }
3943 #ifdef FEAT_FLOAT
3944 		    if (rettv->v_type == VAR_FLOAT)
3945 			f2 = n2;
3946 #endif
3947 		}
3948 		clear_tv(rettv);
3949 
3950 #ifdef FEAT_FLOAT
3951 		/* If there is a float on either side the result is a float. */
3952 		if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
3953 		{
3954 		    if (op == '+')
3955 			f1 = f1 + f2;
3956 		    else
3957 			f1 = f1 - f2;
3958 		    rettv->v_type = VAR_FLOAT;
3959 		    rettv->vval.v_float = f1;
3960 		}
3961 		else
3962 #endif
3963 		{
3964 		    if (op == '+')
3965 			n1 = n1 + n2;
3966 		    else
3967 			n1 = n1 - n2;
3968 		    rettv->v_type = VAR_NUMBER;
3969 		    rettv->vval.v_number = n1;
3970 		}
3971 	    }
3972 	    clear_tv(&var2);
3973 	}
3974     }
3975     return OK;
3976 }
3977 
3978 /*
3979  * Handle fifth level expression:
3980  *	*	number multiplication
3981  *	/	number division
3982  *	%	number modulo
3983  *
3984  * "arg" must point to the first non-white of the expression.
3985  * "arg" is advanced to the next non-white after the recognized expression.
3986  *
3987  * Return OK or FAIL.
3988  */
3989     static int
3990 eval6(
3991     char_u	**arg,
3992     typval_T	*rettv,
3993     int		evaluate,
3994     int		want_string)  /* after "." operator */
3995 {
3996     typval_T	var2;
3997     int		op;
3998     varnumber_T	n1, n2;
3999 #ifdef FEAT_FLOAT
4000     int		use_float = FALSE;
4001     float_T	f1 = 0, f2;
4002 #endif
4003     int		error = FALSE;
4004 
4005     /*
4006      * Get the first variable.
4007      */
4008     if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4009 	return FAIL;
4010 
4011     /*
4012      * Repeat computing, until no '*', '/' or '%' is following.
4013      */
4014     for (;;)
4015     {
4016 	op = **arg;
4017 	if (op != '*' && op != '/' && op != '%')
4018 	    break;
4019 
4020 	if (evaluate)
4021 	{
4022 #ifdef FEAT_FLOAT
4023 	    if (rettv->v_type == VAR_FLOAT)
4024 	    {
4025 		f1 = rettv->vval.v_float;
4026 		use_float = TRUE;
4027 		n1 = 0;
4028 	    }
4029 	    else
4030 #endif
4031 		n1 = tv_get_number_chk(rettv, &error);
4032 	    clear_tv(rettv);
4033 	    if (error)
4034 		return FAIL;
4035 	}
4036 	else
4037 	    n1 = 0;
4038 
4039 	/*
4040 	 * Get the second variable.
4041 	 */
4042 	*arg = skipwhite(*arg + 1);
4043 	if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4044 	    return FAIL;
4045 
4046 	if (evaluate)
4047 	{
4048 #ifdef FEAT_FLOAT
4049 	    if (var2.v_type == VAR_FLOAT)
4050 	    {
4051 		if (!use_float)
4052 		{
4053 		    f1 = n1;
4054 		    use_float = TRUE;
4055 		}
4056 		f2 = var2.vval.v_float;
4057 		n2 = 0;
4058 	    }
4059 	    else
4060 #endif
4061 	    {
4062 		n2 = tv_get_number_chk(&var2, &error);
4063 		clear_tv(&var2);
4064 		if (error)
4065 		    return FAIL;
4066 #ifdef FEAT_FLOAT
4067 		if (use_float)
4068 		    f2 = n2;
4069 #endif
4070 	    }
4071 
4072 	    /*
4073 	     * Compute the result.
4074 	     * When either side is a float the result is a float.
4075 	     */
4076 #ifdef FEAT_FLOAT
4077 	    if (use_float)
4078 	    {
4079 		if (op == '*')
4080 		    f1 = f1 * f2;
4081 		else if (op == '/')
4082 		{
4083 # ifdef VMS
4084 		    /* VMS crashes on divide by zero, work around it */
4085 		    if (f2 == 0.0)
4086 		    {
4087 			if (f1 == 0)
4088 			    f1 = -1 * __F_FLT_MAX - 1L;   /* similar to NaN */
4089 			else if (f1 < 0)
4090 			    f1 = -1 * __F_FLT_MAX;
4091 			else
4092 			    f1 = __F_FLT_MAX;
4093 		    }
4094 		    else
4095 			f1 = f1 / f2;
4096 # else
4097 		    /* We rely on the floating point library to handle divide
4098 		     * by zero to result in "inf" and not a crash. */
4099 		    f1 = f1 / f2;
4100 # endif
4101 		}
4102 		else
4103 		{
4104 		    emsg(_("E804: Cannot use '%' with Float"));
4105 		    return FAIL;
4106 		}
4107 		rettv->v_type = VAR_FLOAT;
4108 		rettv->vval.v_float = f1;
4109 	    }
4110 	    else
4111 #endif
4112 	    {
4113 		if (op == '*')
4114 		    n1 = n1 * n2;
4115 		else if (op == '/')
4116 		{
4117 		    if (n2 == 0)	/* give an error message? */
4118 		    {
4119 			if (n1 == 0)
4120 			    n1 = VARNUM_MIN; /* similar to NaN */
4121 			else if (n1 < 0)
4122 			    n1 = -VARNUM_MAX;
4123 			else
4124 			    n1 = VARNUM_MAX;
4125 		    }
4126 		    else
4127 			n1 = n1 / n2;
4128 		}
4129 		else
4130 		{
4131 		    if (n2 == 0)	/* give an error message? */
4132 			n1 = 0;
4133 		    else
4134 			n1 = n1 % n2;
4135 		}
4136 		rettv->v_type = VAR_NUMBER;
4137 		rettv->vval.v_number = n1;
4138 	    }
4139 	}
4140     }
4141 
4142     return OK;
4143 }
4144 
4145 /*
4146  * Handle sixth level expression:
4147  *  number		number constant
4148  *  0zFFFFFFFF		Blob constant
4149  *  "string"		string constant
4150  *  'string'		literal string constant
4151  *  &option-name	option value
4152  *  @r			register contents
4153  *  identifier		variable value
4154  *  function()		function call
4155  *  $VAR		environment variable
4156  *  (expression)	nested expression
4157  *  [expr, expr]	List
4158  *  {key: val, key: val}  Dictionary
4159  *
4160  *  Also handle:
4161  *  ! in front		logical NOT
4162  *  - in front		unary minus
4163  *  + in front		unary plus (ignored)
4164  *  trailing []		subscript in String or List
4165  *  trailing .name	entry in Dictionary
4166  *
4167  * "arg" must point to the first non-white of the expression.
4168  * "arg" is advanced to the next non-white after the recognized expression.
4169  *
4170  * Return OK or FAIL.
4171  */
4172     static int
4173 eval7(
4174     char_u	**arg,
4175     typval_T	*rettv,
4176     int		evaluate,
4177     int		want_string UNUSED)	/* after "." operator */
4178 {
4179     varnumber_T	n;
4180     int		len;
4181     char_u	*s;
4182     char_u	*start_leader, *end_leader;
4183     int		ret = OK;
4184     char_u	*alias;
4185 
4186     /*
4187      * Initialise variable so that clear_tv() can't mistake this for a
4188      * string and free a string that isn't there.
4189      */
4190     rettv->v_type = VAR_UNKNOWN;
4191 
4192     /*
4193      * Skip '!', '-' and '+' characters.  They are handled later.
4194      */
4195     start_leader = *arg;
4196     while (**arg == '!' || **arg == '-' || **arg == '+')
4197 	*arg = skipwhite(*arg + 1);
4198     end_leader = *arg;
4199 
4200     switch (**arg)
4201     {
4202     /*
4203      * Number constant.
4204      */
4205     case '0':
4206     case '1':
4207     case '2':
4208     case '3':
4209     case '4':
4210     case '5':
4211     case '6':
4212     case '7':
4213     case '8':
4214     case '9':
4215 	{
4216 #ifdef FEAT_FLOAT
4217 		char_u *p = skipdigits(*arg + 1);
4218 		int    get_float = FALSE;
4219 
4220 		/* We accept a float when the format matches
4221 		 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?".  This is very
4222 		 * strict to avoid backwards compatibility problems.
4223 		 * Don't look for a float after the "." operator, so that
4224 		 * ":let vers = 1.2.3" doesn't fail. */
4225 		if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
4226 		{
4227 		    get_float = TRUE;
4228 		    p = skipdigits(p + 2);
4229 		    if (*p == 'e' || *p == 'E')
4230 		    {
4231 			++p;
4232 			if (*p == '-' || *p == '+')
4233 			    ++p;
4234 			if (!vim_isdigit(*p))
4235 			    get_float = FALSE;
4236 			else
4237 			    p = skipdigits(p + 1);
4238 		    }
4239 		    if (ASCII_ISALPHA(*p) || *p == '.')
4240 			get_float = FALSE;
4241 		}
4242 		if (get_float)
4243 		{
4244 		    float_T	f;
4245 
4246 		    *arg += string2float(*arg, &f);
4247 		    if (evaluate)
4248 		    {
4249 			rettv->v_type = VAR_FLOAT;
4250 			rettv->vval.v_float = f;
4251 		    }
4252 		}
4253 		else
4254 #endif
4255 		if (**arg == '0' && ((*arg)[1] == 'z' || (*arg)[1] == 'Z'))
4256 		{
4257 		    char_u  *bp;
4258 		    blob_T  *blob = NULL;  // init for gcc
4259 
4260 		    // Blob constant: 0z0123456789abcdef
4261 		    if (evaluate)
4262 			blob = blob_alloc();
4263 		    for (bp = *arg + 2; vim_isxdigit(bp[0]); bp += 2)
4264 		    {
4265 			if (!vim_isxdigit(bp[1]))
4266 			{
4267 			    if (blob != NULL)
4268 			    {
4269 				emsg(_("E973: Blob literal should have an even number of hex characters"));
4270 				ga_clear(&blob->bv_ga);
4271 				VIM_CLEAR(blob);
4272 			    }
4273 			    ret = FAIL;
4274 			    break;
4275 			}
4276 			if (blob != NULL)
4277 			    ga_append(&blob->bv_ga,
4278 					 (hex2nr(*bp) << 4) + hex2nr(*(bp+1)));
4279 			if (bp[2] == '.' && vim_isxdigit(bp[3]))
4280 			    ++bp;
4281 		    }
4282 		    if (blob != NULL)
4283 			rettv_blob_set(rettv, blob);
4284 		    *arg = bp;
4285 		}
4286 		else
4287 		{
4288 		    // decimal, hex or octal number
4289 		    vim_str2nr(*arg, NULL, &len, STR2NR_ALL, &n, NULL, 0);
4290 		    *arg += len;
4291 		    if (evaluate)
4292 		    {
4293 			rettv->v_type = VAR_NUMBER;
4294 			rettv->vval.v_number = n;
4295 		    }
4296 		}
4297 		break;
4298 	}
4299 
4300     /*
4301      * String constant: "string".
4302      */
4303     case '"':	ret = get_string_tv(arg, rettv, evaluate);
4304 		break;
4305 
4306     /*
4307      * Literal string constant: 'str''ing'.
4308      */
4309     case '\'':	ret = get_lit_string_tv(arg, rettv, evaluate);
4310 		break;
4311 
4312     /*
4313      * List: [expr, expr]
4314      */
4315     case '[':	ret = get_list_tv(arg, rettv, evaluate);
4316 		break;
4317 
4318     /*
4319      * Lambda: {arg, arg -> expr}
4320      * Dictionary: {key: val, key: val}
4321      */
4322     case '{':	ret = get_lambda_tv(arg, rettv, evaluate);
4323 		if (ret == NOTDONE)
4324 		    ret = dict_get_tv(arg, rettv, evaluate);
4325 		break;
4326 
4327     /*
4328      * Option value: &name
4329      */
4330     case '&':	ret = get_option_tv(arg, rettv, evaluate);
4331 		break;
4332 
4333     /*
4334      * Environment variable: $VAR.
4335      */
4336     case '$':	ret = get_env_tv(arg, rettv, evaluate);
4337 		break;
4338 
4339     /*
4340      * Register contents: @r.
4341      */
4342     case '@':	++*arg;
4343 		if (evaluate)
4344 		{
4345 		    rettv->v_type = VAR_STRING;
4346 		    rettv->vval.v_string = get_reg_contents(**arg,
4347 							    GREG_EXPR_SRC);
4348 		}
4349 		if (**arg != NUL)
4350 		    ++*arg;
4351 		break;
4352 
4353     /*
4354      * nested expression: (expression).
4355      */
4356     case '(':	*arg = skipwhite(*arg + 1);
4357 		ret = eval1(arg, rettv, evaluate);	/* recursive! */
4358 		if (**arg == ')')
4359 		    ++*arg;
4360 		else if (ret == OK)
4361 		{
4362 		    emsg(_("E110: Missing ')'"));
4363 		    clear_tv(rettv);
4364 		    ret = FAIL;
4365 		}
4366 		break;
4367 
4368     default:	ret = NOTDONE;
4369 		break;
4370     }
4371 
4372     if (ret == NOTDONE)
4373     {
4374 	/*
4375 	 * Must be a variable or function name.
4376 	 * Can also be a curly-braces kind of name: {expr}.
4377 	 */
4378 	s = *arg;
4379 	len = get_name_len(arg, &alias, evaluate, TRUE);
4380 	if (alias != NULL)
4381 	    s = alias;
4382 
4383 	if (len <= 0)
4384 	    ret = FAIL;
4385 	else
4386 	{
4387 	    if (**arg == '(')		/* recursive! */
4388 	    {
4389 		partial_T *partial;
4390 
4391 		if (!evaluate)
4392 		    check_vars(s, len);
4393 
4394 		/* If "s" is the name of a variable of type VAR_FUNC
4395 		 * use its contents. */
4396 		s = deref_func_name(s, &len, &partial, !evaluate);
4397 
4398 		/* Need to make a copy, in case evaluating the arguments makes
4399 		 * the name invalid. */
4400 		s = vim_strsave(s);
4401 		if (s == NULL)
4402 		    ret = FAIL;
4403 		else
4404 		    /* Invoke the function. */
4405 		    ret = get_func_tv(s, len, rettv, arg,
4406 			      curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4407 			      &len, evaluate, partial, NULL);
4408 		vim_free(s);
4409 
4410 		/* If evaluate is FALSE rettv->v_type was not set in
4411 		 * get_func_tv, but it's needed in handle_subscript() to parse
4412 		 * what follows. So set it here. */
4413 		if (rettv->v_type == VAR_UNKNOWN && !evaluate && **arg == '(')
4414 		{
4415 		    rettv->vval.v_string = NULL;
4416 		    rettv->v_type = VAR_FUNC;
4417 		}
4418 
4419 		/* Stop the expression evaluation when immediately
4420 		 * aborting on error, or when an interrupt occurred or
4421 		 * an exception was thrown but not caught. */
4422 		if (aborting())
4423 		{
4424 		    if (ret == OK)
4425 			clear_tv(rettv);
4426 		    ret = FAIL;
4427 		}
4428 	    }
4429 	    else if (evaluate)
4430 		ret = get_var_tv(s, len, rettv, NULL, TRUE, FALSE);
4431 	    else
4432 	    {
4433 		check_vars(s, len);
4434 		ret = OK;
4435 	    }
4436 	}
4437 	vim_free(alias);
4438     }
4439 
4440     *arg = skipwhite(*arg);
4441 
4442     /* Handle following '[', '(' and '.' for expr[expr], expr.name,
4443      * expr(expr). */
4444     if (ret == OK)
4445 	ret = handle_subscript(arg, rettv, evaluate, TRUE);
4446 
4447     /*
4448      * Apply logical NOT and unary '-', from right to left, ignore '+'.
4449      */
4450     if (ret == OK && evaluate && end_leader > start_leader)
4451     {
4452 	int	    error = FALSE;
4453 	varnumber_T val = 0;
4454 #ifdef FEAT_FLOAT
4455 	float_T	    f = 0.0;
4456 
4457 	if (rettv->v_type == VAR_FLOAT)
4458 	    f = rettv->vval.v_float;
4459 	else
4460 #endif
4461 	    val = tv_get_number_chk(rettv, &error);
4462 	if (error)
4463 	{
4464 	    clear_tv(rettv);
4465 	    ret = FAIL;
4466 	}
4467 	else
4468 	{
4469 	    while (end_leader > start_leader)
4470 	    {
4471 		--end_leader;
4472 		if (*end_leader == '!')
4473 		{
4474 #ifdef FEAT_FLOAT
4475 		    if (rettv->v_type == VAR_FLOAT)
4476 			f = !f;
4477 		    else
4478 #endif
4479 			val = !val;
4480 		}
4481 		else if (*end_leader == '-')
4482 		{
4483 #ifdef FEAT_FLOAT
4484 		    if (rettv->v_type == VAR_FLOAT)
4485 			f = -f;
4486 		    else
4487 #endif
4488 			val = -val;
4489 		}
4490 	    }
4491 #ifdef FEAT_FLOAT
4492 	    if (rettv->v_type == VAR_FLOAT)
4493 	    {
4494 		clear_tv(rettv);
4495 		rettv->vval.v_float = f;
4496 	    }
4497 	    else
4498 #endif
4499 	    {
4500 		clear_tv(rettv);
4501 		rettv->v_type = VAR_NUMBER;
4502 		rettv->vval.v_number = val;
4503 	    }
4504 	}
4505     }
4506 
4507     return ret;
4508 }
4509 
4510 /*
4511  * Evaluate an "[expr]" or "[expr:expr]" index.  Also "dict.key".
4512  * "*arg" points to the '[' or '.'.
4513  * Returns FAIL or OK. "*arg" is advanced to after the ']'.
4514  */
4515     static int
4516 eval_index(
4517     char_u	**arg,
4518     typval_T	*rettv,
4519     int		evaluate,
4520     int		verbose)	/* give error messages */
4521 {
4522     int		empty1 = FALSE, empty2 = FALSE;
4523     typval_T	var1, var2;
4524     long	i;
4525     long	n1, n2 = 0;
4526     long	len = -1;
4527     int		range = FALSE;
4528     char_u	*s;
4529     char_u	*key = NULL;
4530 
4531     switch (rettv->v_type)
4532     {
4533 	case VAR_FUNC:
4534 	case VAR_PARTIAL:
4535 	    if (verbose)
4536 		emsg(_("E695: Cannot index a Funcref"));
4537 	    return FAIL;
4538 	case VAR_FLOAT:
4539 #ifdef FEAT_FLOAT
4540 	    if (verbose)
4541 		emsg(_(e_float_as_string));
4542 	    return FAIL;
4543 #endif
4544 	case VAR_SPECIAL:
4545 	case VAR_JOB:
4546 	case VAR_CHANNEL:
4547 	    if (verbose)
4548 		emsg(_("E909: Cannot index a special variable"));
4549 	    return FAIL;
4550 	case VAR_UNKNOWN:
4551 	    if (evaluate)
4552 		return FAIL;
4553 	    /* FALLTHROUGH */
4554 
4555 	case VAR_STRING:
4556 	case VAR_NUMBER:
4557 	case VAR_LIST:
4558 	case VAR_DICT:
4559 	case VAR_BLOB:
4560 	    break;
4561     }
4562 
4563     init_tv(&var1);
4564     init_tv(&var2);
4565     if (**arg == '.')
4566     {
4567 	/*
4568 	 * dict.name
4569 	 */
4570 	key = *arg + 1;
4571 	for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
4572 	    ;
4573 	if (len == 0)
4574 	    return FAIL;
4575 	*arg = skipwhite(key + len);
4576     }
4577     else
4578     {
4579 	/*
4580 	 * something[idx]
4581 	 *
4582 	 * Get the (first) variable from inside the [].
4583 	 */
4584 	*arg = skipwhite(*arg + 1);
4585 	if (**arg == ':')
4586 	    empty1 = TRUE;
4587 	else if (eval1(arg, &var1, evaluate) == FAIL)	/* recursive! */
4588 	    return FAIL;
4589 	else if (evaluate && tv_get_string_chk(&var1) == NULL)
4590 	{
4591 	    /* not a number or string */
4592 	    clear_tv(&var1);
4593 	    return FAIL;
4594 	}
4595 
4596 	/*
4597 	 * Get the second variable from inside the [:].
4598 	 */
4599 	if (**arg == ':')
4600 	{
4601 	    range = TRUE;
4602 	    *arg = skipwhite(*arg + 1);
4603 	    if (**arg == ']')
4604 		empty2 = TRUE;
4605 	    else if (eval1(arg, &var2, evaluate) == FAIL)	/* recursive! */
4606 	    {
4607 		if (!empty1)
4608 		    clear_tv(&var1);
4609 		return FAIL;
4610 	    }
4611 	    else if (evaluate && tv_get_string_chk(&var2) == NULL)
4612 	    {
4613 		/* not a number or string */
4614 		if (!empty1)
4615 		    clear_tv(&var1);
4616 		clear_tv(&var2);
4617 		return FAIL;
4618 	    }
4619 	}
4620 
4621 	/* Check for the ']'. */
4622 	if (**arg != ']')
4623 	{
4624 	    if (verbose)
4625 		emsg(_(e_missbrac));
4626 	    clear_tv(&var1);
4627 	    if (range)
4628 		clear_tv(&var2);
4629 	    return FAIL;
4630 	}
4631 	*arg = skipwhite(*arg + 1);	/* skip the ']' */
4632     }
4633 
4634     if (evaluate)
4635     {
4636 	n1 = 0;
4637 	if (!empty1 && rettv->v_type != VAR_DICT)
4638 	{
4639 	    n1 = tv_get_number(&var1);
4640 	    clear_tv(&var1);
4641 	}
4642 	if (range)
4643 	{
4644 	    if (empty2)
4645 		n2 = -1;
4646 	    else
4647 	    {
4648 		n2 = tv_get_number(&var2);
4649 		clear_tv(&var2);
4650 	    }
4651 	}
4652 
4653 	switch (rettv->v_type)
4654 	{
4655 	    case VAR_UNKNOWN:
4656 	    case VAR_FUNC:
4657 	    case VAR_PARTIAL:
4658 	    case VAR_FLOAT:
4659 	    case VAR_SPECIAL:
4660 	    case VAR_JOB:
4661 	    case VAR_CHANNEL:
4662 		break; /* not evaluating, skipping over subscript */
4663 
4664 	    case VAR_NUMBER:
4665 	    case VAR_STRING:
4666 		s = tv_get_string(rettv);
4667 		len = (long)STRLEN(s);
4668 		if (range)
4669 		{
4670 		    /* The resulting variable is a substring.  If the indexes
4671 		     * are out of range the result is empty. */
4672 		    if (n1 < 0)
4673 		    {
4674 			n1 = len + n1;
4675 			if (n1 < 0)
4676 			    n1 = 0;
4677 		    }
4678 		    if (n2 < 0)
4679 			n2 = len + n2;
4680 		    else if (n2 >= len)
4681 			n2 = len;
4682 		    if (n1 >= len || n2 < 0 || n1 > n2)
4683 			s = NULL;
4684 		    else
4685 			s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
4686 		}
4687 		else
4688 		{
4689 		    /* The resulting variable is a string of a single
4690 		     * character.  If the index is too big or negative the
4691 		     * result is empty. */
4692 		    if (n1 >= len || n1 < 0)
4693 			s = NULL;
4694 		    else
4695 			s = vim_strnsave(s + n1, 1);
4696 		}
4697 		clear_tv(rettv);
4698 		rettv->v_type = VAR_STRING;
4699 		rettv->vval.v_string = s;
4700 		break;
4701 
4702 	    case VAR_BLOB:
4703 		len = blob_len(rettv->vval.v_blob);
4704 		if (range)
4705 		{
4706 		    // The resulting variable is a sub-blob.  If the indexes
4707 		    // are out of range the result is empty.
4708 		    if (n1 < 0)
4709 		    {
4710 			n1 = len + n1;
4711 			if (n1 < 0)
4712 			    n1 = 0;
4713 		    }
4714 		    if (n2 < 0)
4715 			n2 = len + n2;
4716 		    else if (n2 >= len)
4717 			n2 = len - 1;
4718 		    if (n1 >= len || n2 < 0 || n1 > n2)
4719 		    {
4720 			clear_tv(rettv);
4721 			rettv->v_type = VAR_BLOB;
4722 			rettv->vval.v_blob = NULL;
4723 		    }
4724 		    else
4725 		    {
4726 			blob_T  *blob = blob_alloc();
4727 
4728 			if (blob != NULL)
4729 			{
4730 			    if (ga_grow(&blob->bv_ga, n2 - n1 + 1) == FAIL)
4731 			    {
4732 				blob_free(blob);
4733 				return FAIL;
4734 			    }
4735 			    blob->bv_ga.ga_len = n2 - n1 + 1;
4736 			    for (i = n1; i <= n2; i++)
4737 				blob_set(blob, i - n1,
4738 					      blob_get(rettv->vval.v_blob, i));
4739 
4740 			    clear_tv(rettv);
4741 			    rettv_blob_set(rettv, blob);
4742 			}
4743 		    }
4744 		}
4745 		else
4746 		{
4747 		    // The resulting variable is a byte value.
4748 		    // If the index is too big or negative that is an error.
4749 		    if (n1 < 0)
4750 			n1 = len + n1;
4751 		    if (n1 < len && n1 >= 0)
4752 		    {
4753 			int v = blob_get(rettv->vval.v_blob, n1);
4754 
4755 			clear_tv(rettv);
4756 			rettv->v_type = VAR_NUMBER;
4757 			rettv->vval.v_number = v;
4758 		    }
4759 		    else
4760 			semsg(_(e_blobidx), n1);
4761 		}
4762 		break;
4763 
4764 	    case VAR_LIST:
4765 		len = list_len(rettv->vval.v_list);
4766 		if (n1 < 0)
4767 		    n1 = len + n1;
4768 		if (!empty1 && (n1 < 0 || n1 >= len))
4769 		{
4770 		    /* For a range we allow invalid values and return an empty
4771 		     * list.  A list index out of range is an error. */
4772 		    if (!range)
4773 		    {
4774 			if (verbose)
4775 			    semsg(_(e_listidx), n1);
4776 			return FAIL;
4777 		    }
4778 		    n1 = len;
4779 		}
4780 		if (range)
4781 		{
4782 		    list_T	*l;
4783 		    listitem_T	*item;
4784 
4785 		    if (n2 < 0)
4786 			n2 = len + n2;
4787 		    else if (n2 >= len)
4788 			n2 = len - 1;
4789 		    if (!empty2 && (n2 < 0 || n2 + 1 < n1))
4790 			n2 = -1;
4791 		    l = list_alloc();
4792 		    if (l == NULL)
4793 			return FAIL;
4794 		    for (item = list_find(rettv->vval.v_list, n1);
4795 							       n1 <= n2; ++n1)
4796 		    {
4797 			if (list_append_tv(l, &item->li_tv) == FAIL)
4798 			{
4799 			    list_free(l);
4800 			    return FAIL;
4801 			}
4802 			item = item->li_next;
4803 		    }
4804 		    clear_tv(rettv);
4805 		    rettv_list_set(rettv, l);
4806 		}
4807 		else
4808 		{
4809 		    copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
4810 		    clear_tv(rettv);
4811 		    *rettv = var1;
4812 		}
4813 		break;
4814 
4815 	    case VAR_DICT:
4816 		if (range)
4817 		{
4818 		    if (verbose)
4819 			emsg(_(e_dictrange));
4820 		    if (len == -1)
4821 			clear_tv(&var1);
4822 		    return FAIL;
4823 		}
4824 		{
4825 		    dictitem_T	*item;
4826 
4827 		    if (len == -1)
4828 		    {
4829 			key = tv_get_string_chk(&var1);
4830 			if (key == NULL)
4831 			{
4832 			    clear_tv(&var1);
4833 			    return FAIL;
4834 			}
4835 		    }
4836 
4837 		    item = dict_find(rettv->vval.v_dict, key, (int)len);
4838 
4839 		    if (item == NULL && verbose)
4840 			semsg(_(e_dictkey), key);
4841 		    if (len == -1)
4842 			clear_tv(&var1);
4843 		    if (item == NULL)
4844 			return FAIL;
4845 
4846 		    copy_tv(&item->di_tv, &var1);
4847 		    clear_tv(rettv);
4848 		    *rettv = var1;
4849 		}
4850 		break;
4851 	}
4852     }
4853 
4854     return OK;
4855 }
4856 
4857 /*
4858  * Get an option value.
4859  * "arg" points to the '&' or '+' before the option name.
4860  * "arg" is advanced to character after the option name.
4861  * Return OK or FAIL.
4862  */
4863     int
4864 get_option_tv(
4865     char_u	**arg,
4866     typval_T	*rettv,	/* when NULL, only check if option exists */
4867     int		evaluate)
4868 {
4869     char_u	*option_end;
4870     long	numval;
4871     char_u	*stringval;
4872     int		opt_type;
4873     int		c;
4874     int		working = (**arg == '+');    /* has("+option") */
4875     int		ret = OK;
4876     int		opt_flags;
4877 
4878     /*
4879      * Isolate the option name and find its value.
4880      */
4881     option_end = find_option_end(arg, &opt_flags);
4882     if (option_end == NULL)
4883     {
4884 	if (rettv != NULL)
4885 	    semsg(_("E112: Option name missing: %s"), *arg);
4886 	return FAIL;
4887     }
4888 
4889     if (!evaluate)
4890     {
4891 	*arg = option_end;
4892 	return OK;
4893     }
4894 
4895     c = *option_end;
4896     *option_end = NUL;
4897     opt_type = get_option_value(*arg, &numval,
4898 			       rettv == NULL ? NULL : &stringval, opt_flags);
4899 
4900     if (opt_type == -3)			/* invalid name */
4901     {
4902 	if (rettv != NULL)
4903 	    semsg(_("E113: Unknown option: %s"), *arg);
4904 	ret = FAIL;
4905     }
4906     else if (rettv != NULL)
4907     {
4908 	if (opt_type == -2)		/* hidden string option */
4909 	{
4910 	    rettv->v_type = VAR_STRING;
4911 	    rettv->vval.v_string = NULL;
4912 	}
4913 	else if (opt_type == -1)	/* hidden number option */
4914 	{
4915 	    rettv->v_type = VAR_NUMBER;
4916 	    rettv->vval.v_number = 0;
4917 	}
4918 	else if (opt_type == 1)		/* number option */
4919 	{
4920 	    rettv->v_type = VAR_NUMBER;
4921 	    rettv->vval.v_number = numval;
4922 	}
4923 	else				/* string option */
4924 	{
4925 	    rettv->v_type = VAR_STRING;
4926 	    rettv->vval.v_string = stringval;
4927 	}
4928     }
4929     else if (working && (opt_type == -2 || opt_type == -1))
4930 	ret = FAIL;
4931 
4932     *option_end = c;		    /* put back for error messages */
4933     *arg = option_end;
4934 
4935     return ret;
4936 }
4937 
4938 /*
4939  * Allocate a variable for a string constant.
4940  * Return OK or FAIL.
4941  */
4942     static int
4943 get_string_tv(char_u **arg, typval_T *rettv, int evaluate)
4944 {
4945     char_u	*p;
4946     char_u	*name;
4947     int		extra = 0;
4948 
4949     /*
4950      * Find the end of the string, skipping backslashed characters.
4951      */
4952     for (p = *arg + 1; *p != NUL && *p != '"'; MB_PTR_ADV(p))
4953     {
4954 	if (*p == '\\' && p[1] != NUL)
4955 	{
4956 	    ++p;
4957 	    /* A "\<x>" form occupies at least 4 characters, and produces up
4958 	     * to 6 characters: reserve space for 2 extra */
4959 	    if (*p == '<')
4960 		extra += 2;
4961 	}
4962     }
4963 
4964     if (*p != '"')
4965     {
4966 	semsg(_("E114: Missing quote: %s"), *arg);
4967 	return FAIL;
4968     }
4969 
4970     /* If only parsing, set *arg and return here */
4971     if (!evaluate)
4972     {
4973 	*arg = p + 1;
4974 	return OK;
4975     }
4976 
4977     /*
4978      * Copy the string into allocated memory, handling backslashed
4979      * characters.
4980      */
4981     name = alloc((unsigned)(p - *arg + extra));
4982     if (name == NULL)
4983 	return FAIL;
4984     rettv->v_type = VAR_STRING;
4985     rettv->vval.v_string = name;
4986 
4987     for (p = *arg + 1; *p != NUL && *p != '"'; )
4988     {
4989 	if (*p == '\\')
4990 	{
4991 	    switch (*++p)
4992 	    {
4993 		case 'b': *name++ = BS; ++p; break;
4994 		case 'e': *name++ = ESC; ++p; break;
4995 		case 'f': *name++ = FF; ++p; break;
4996 		case 'n': *name++ = NL; ++p; break;
4997 		case 'r': *name++ = CAR; ++p; break;
4998 		case 't': *name++ = TAB; ++p; break;
4999 
5000 		case 'X': /* hex: "\x1", "\x12" */
5001 		case 'x':
5002 		case 'u': /* Unicode: "\u0023" */
5003 		case 'U':
5004 			  if (vim_isxdigit(p[1]))
5005 			  {
5006 			      int	n, nr;
5007 			      int	c = toupper(*p);
5008 
5009 			      if (c == 'X')
5010 				  n = 2;
5011 			      else if (*p == 'u')
5012 				  n = 4;
5013 			      else
5014 				  n = 8;
5015 			      nr = 0;
5016 			      while (--n >= 0 && vim_isxdigit(p[1]))
5017 			      {
5018 				  ++p;
5019 				  nr = (nr << 4) + hex2nr(*p);
5020 			      }
5021 			      ++p;
5022 			      /* For "\u" store the number according to
5023 			       * 'encoding'. */
5024 			      if (c != 'X')
5025 				  name += (*mb_char2bytes)(nr, name);
5026 			      else
5027 				  *name++ = nr;
5028 			  }
5029 			  break;
5030 
5031 			  /* octal: "\1", "\12", "\123" */
5032 		case '0':
5033 		case '1':
5034 		case '2':
5035 		case '3':
5036 		case '4':
5037 		case '5':
5038 		case '6':
5039 		case '7': *name = *p++ - '0';
5040 			  if (*p >= '0' && *p <= '7')
5041 			  {
5042 			      *name = (*name << 3) + *p++ - '0';
5043 			      if (*p >= '0' && *p <= '7')
5044 				  *name = (*name << 3) + *p++ - '0';
5045 			  }
5046 			  ++name;
5047 			  break;
5048 
5049 			    /* Special key, e.g.: "\<C-W>" */
5050 		case '<': extra = trans_special(&p, name, TRUE, TRUE);
5051 			  if (extra != 0)
5052 			  {
5053 			      name += extra;
5054 			      break;
5055 			  }
5056 			  /* FALLTHROUGH */
5057 
5058 		default:  MB_COPY_CHAR(p, name);
5059 			  break;
5060 	    }
5061 	}
5062 	else
5063 	    MB_COPY_CHAR(p, name);
5064 
5065     }
5066     *name = NUL;
5067     if (*p != NUL) /* just in case */
5068 	++p;
5069     *arg = p;
5070 
5071     return OK;
5072 }
5073 
5074 /*
5075  * Allocate a variable for a 'str''ing' constant.
5076  * Return OK or FAIL.
5077  */
5078     static int
5079 get_lit_string_tv(char_u **arg, typval_T *rettv, int evaluate)
5080 {
5081     char_u	*p;
5082     char_u	*str;
5083     int		reduce = 0;
5084 
5085     /*
5086      * Find the end of the string, skipping ''.
5087      */
5088     for (p = *arg + 1; *p != NUL; MB_PTR_ADV(p))
5089     {
5090 	if (*p == '\'')
5091 	{
5092 	    if (p[1] != '\'')
5093 		break;
5094 	    ++reduce;
5095 	    ++p;
5096 	}
5097     }
5098 
5099     if (*p != '\'')
5100     {
5101 	semsg(_("E115: Missing quote: %s"), *arg);
5102 	return FAIL;
5103     }
5104 
5105     /* If only parsing return after setting "*arg" */
5106     if (!evaluate)
5107     {
5108 	*arg = p + 1;
5109 	return OK;
5110     }
5111 
5112     /*
5113      * Copy the string into allocated memory, handling '' to ' reduction.
5114      */
5115     str = alloc((unsigned)((p - *arg) - reduce));
5116     if (str == NULL)
5117 	return FAIL;
5118     rettv->v_type = VAR_STRING;
5119     rettv->vval.v_string = str;
5120 
5121     for (p = *arg + 1; *p != NUL; )
5122     {
5123 	if (*p == '\'')
5124 	{
5125 	    if (p[1] != '\'')
5126 		break;
5127 	    ++p;
5128 	}
5129 	MB_COPY_CHAR(p, str);
5130     }
5131     *str = NUL;
5132     *arg = p + 1;
5133 
5134     return OK;
5135 }
5136 
5137 /*
5138  * Return the function name of the partial.
5139  */
5140     char_u *
5141 partial_name(partial_T *pt)
5142 {
5143     if (pt->pt_name != NULL)
5144 	return pt->pt_name;
5145     return pt->pt_func->uf_name;
5146 }
5147 
5148     static void
5149 partial_free(partial_T *pt)
5150 {
5151     int i;
5152 
5153     for (i = 0; i < pt->pt_argc; ++i)
5154 	clear_tv(&pt->pt_argv[i]);
5155     vim_free(pt->pt_argv);
5156     dict_unref(pt->pt_dict);
5157     if (pt->pt_name != NULL)
5158     {
5159 	func_unref(pt->pt_name);
5160 	vim_free(pt->pt_name);
5161     }
5162     else
5163 	func_ptr_unref(pt->pt_func);
5164     vim_free(pt);
5165 }
5166 
5167 /*
5168  * Unreference a closure: decrement the reference count and free it when it
5169  * becomes zero.
5170  */
5171     void
5172 partial_unref(partial_T *pt)
5173 {
5174     if (pt != NULL && --pt->pt_refcount <= 0)
5175 	partial_free(pt);
5176 }
5177 
5178 static int tv_equal_recurse_limit;
5179 
5180     static int
5181 func_equal(
5182     typval_T *tv1,
5183     typval_T *tv2,
5184     int	     ic)	    /* ignore case */
5185 {
5186     char_u	*s1, *s2;
5187     dict_T	*d1, *d2;
5188     int		a1, a2;
5189     int		i;
5190 
5191     /* empty and NULL function name considered the same */
5192     s1 = tv1->v_type == VAR_FUNC ? tv1->vval.v_string
5193 					   : partial_name(tv1->vval.v_partial);
5194     if (s1 != NULL && *s1 == NUL)
5195 	s1 = NULL;
5196     s2 = tv2->v_type == VAR_FUNC ? tv2->vval.v_string
5197 					   : partial_name(tv2->vval.v_partial);
5198     if (s2 != NULL && *s2 == NUL)
5199 	s2 = NULL;
5200     if (s1 == NULL || s2 == NULL)
5201     {
5202 	if (s1 != s2)
5203 	    return FALSE;
5204     }
5205     else if (STRCMP(s1, s2) != 0)
5206 	return FALSE;
5207 
5208     /* empty dict and NULL dict is different */
5209     d1 = tv1->v_type == VAR_FUNC ? NULL : tv1->vval.v_partial->pt_dict;
5210     d2 = tv2->v_type == VAR_FUNC ? NULL : tv2->vval.v_partial->pt_dict;
5211     if (d1 == NULL || d2 == NULL)
5212     {
5213 	if (d1 != d2)
5214 	    return FALSE;
5215     }
5216     else if (!dict_equal(d1, d2, ic, TRUE))
5217 	return FALSE;
5218 
5219     /* empty list and no list considered the same */
5220     a1 = tv1->v_type == VAR_FUNC ? 0 : tv1->vval.v_partial->pt_argc;
5221     a2 = tv2->v_type == VAR_FUNC ? 0 : tv2->vval.v_partial->pt_argc;
5222     if (a1 != a2)
5223 	return FALSE;
5224     for (i = 0; i < a1; ++i)
5225 	if (!tv_equal(tv1->vval.v_partial->pt_argv + i,
5226 		      tv2->vval.v_partial->pt_argv + i, ic, TRUE))
5227 	    return FALSE;
5228 
5229     return TRUE;
5230 }
5231 
5232 /*
5233  * Return TRUE if "tv1" and "tv2" have the same value.
5234  * Compares the items just like "==" would compare them, but strings and
5235  * numbers are different.  Floats and numbers are also different.
5236  */
5237     int
5238 tv_equal(
5239     typval_T *tv1,
5240     typval_T *tv2,
5241     int	     ic,	    /* ignore case */
5242     int	     recursive)	    /* TRUE when used recursively */
5243 {
5244     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5245     char_u	*s1, *s2;
5246     static int  recursive_cnt = 0;	    /* catch recursive loops */
5247     int		r;
5248 
5249     /* Catch lists and dicts that have an endless loop by limiting
5250      * recursiveness to a limit.  We guess they are equal then.
5251      * A fixed limit has the problem of still taking an awful long time.
5252      * Reduce the limit every time running into it. That should work fine for
5253      * deeply linked structures that are not recursively linked and catch
5254      * recursiveness quickly. */
5255     if (!recursive)
5256 	tv_equal_recurse_limit = 1000;
5257     if (recursive_cnt >= tv_equal_recurse_limit)
5258     {
5259 	--tv_equal_recurse_limit;
5260 	return TRUE;
5261     }
5262 
5263     /* For VAR_FUNC and VAR_PARTIAL compare the function name, bound dict and
5264      * arguments. */
5265     if ((tv1->v_type == VAR_FUNC
5266 		|| (tv1->v_type == VAR_PARTIAL && tv1->vval.v_partial != NULL))
5267 	    && (tv2->v_type == VAR_FUNC
5268 		|| (tv2->v_type == VAR_PARTIAL && tv2->vval.v_partial != NULL)))
5269     {
5270 	++recursive_cnt;
5271 	r = func_equal(tv1, tv2, ic);
5272 	--recursive_cnt;
5273 	return r;
5274     }
5275 
5276     if (tv1->v_type != tv2->v_type)
5277 	return FALSE;
5278 
5279     switch (tv1->v_type)
5280     {
5281 	case VAR_LIST:
5282 	    ++recursive_cnt;
5283 	    r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic, TRUE);
5284 	    --recursive_cnt;
5285 	    return r;
5286 
5287 	case VAR_DICT:
5288 	    ++recursive_cnt;
5289 	    r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic, TRUE);
5290 	    --recursive_cnt;
5291 	    return r;
5292 
5293 	case VAR_BLOB:
5294 	    return blob_equal(tv1->vval.v_blob, tv2->vval.v_blob);
5295 
5296 	case VAR_NUMBER:
5297 	    return tv1->vval.v_number == tv2->vval.v_number;
5298 
5299 	case VAR_STRING:
5300 	    s1 = tv_get_string_buf(tv1, buf1);
5301 	    s2 = tv_get_string_buf(tv2, buf2);
5302 	    return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5303 
5304 	case VAR_SPECIAL:
5305 	    return tv1->vval.v_number == tv2->vval.v_number;
5306 
5307 	case VAR_FLOAT:
5308 #ifdef FEAT_FLOAT
5309 	    return tv1->vval.v_float == tv2->vval.v_float;
5310 #endif
5311 	case VAR_JOB:
5312 #ifdef FEAT_JOB_CHANNEL
5313 	    return tv1->vval.v_job == tv2->vval.v_job;
5314 #endif
5315 	case VAR_CHANNEL:
5316 #ifdef FEAT_JOB_CHANNEL
5317 	    return tv1->vval.v_channel == tv2->vval.v_channel;
5318 #endif
5319 	case VAR_FUNC:
5320 	case VAR_PARTIAL:
5321 	case VAR_UNKNOWN:
5322 	    break;
5323     }
5324 
5325     /* VAR_UNKNOWN can be the result of a invalid expression, let's say it
5326      * does not equal anything, not even itself. */
5327     return FALSE;
5328 }
5329 
5330 /*
5331  * Return the next (unique) copy ID.
5332  * Used for serializing nested structures.
5333  */
5334     int
5335 get_copyID(void)
5336 {
5337     current_copyID += COPYID_INC;
5338     return current_copyID;
5339 }
5340 
5341 /*
5342  * Garbage collection for lists and dictionaries.
5343  *
5344  * We use reference counts to be able to free most items right away when they
5345  * are no longer used.  But for composite items it's possible that it becomes
5346  * unused while the reference count is > 0: When there is a recursive
5347  * reference.  Example:
5348  *	:let l = [1, 2, 3]
5349  *	:let d = {9: l}
5350  *	:let l[1] = d
5351  *
5352  * Since this is quite unusual we handle this with garbage collection: every
5353  * once in a while find out which lists and dicts are not referenced from any
5354  * variable.
5355  *
5356  * Here is a good reference text about garbage collection (refers to Python
5357  * but it applies to all reference-counting mechanisms):
5358  *	http://python.ca/nas/python/gc/
5359  */
5360 
5361 /*
5362  * Do garbage collection for lists and dicts.
5363  * When "testing" is TRUE this is called from test_garbagecollect_now().
5364  * Return TRUE if some memory was freed.
5365  */
5366     int
5367 garbage_collect(int testing)
5368 {
5369     int		copyID;
5370     int		abort = FALSE;
5371     buf_T	*buf;
5372     win_T	*wp;
5373     int		i;
5374     int		did_free = FALSE;
5375     tabpage_T	*tp;
5376 
5377     if (!testing)
5378     {
5379 	/* Only do this once. */
5380 	want_garbage_collect = FALSE;
5381 	may_garbage_collect = FALSE;
5382 	garbage_collect_at_exit = FALSE;
5383     }
5384 
5385     /* We advance by two because we add one for items referenced through
5386      * previous_funccal. */
5387     copyID = get_copyID();
5388 
5389     /*
5390      * 1. Go through all accessible variables and mark all lists and dicts
5391      *    with copyID.
5392      */
5393 
5394     /* Don't free variables in the previous_funccal list unless they are only
5395      * referenced through previous_funccal.  This must be first, because if
5396      * the item is referenced elsewhere the funccal must not be freed. */
5397     abort = abort || set_ref_in_previous_funccal(copyID);
5398 
5399     /* script-local variables */
5400     for (i = 1; i <= ga_scripts.ga_len; ++i)
5401 	abort = abort || set_ref_in_ht(&SCRIPT_VARS(i), copyID, NULL);
5402 
5403     /* buffer-local variables */
5404     FOR_ALL_BUFFERS(buf)
5405 	abort = abort || set_ref_in_item(&buf->b_bufvar.di_tv, copyID,
5406 								  NULL, NULL);
5407 
5408     /* window-local variables */
5409     FOR_ALL_TAB_WINDOWS(tp, wp)
5410 	abort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,
5411 								  NULL, NULL);
5412     if (aucmd_win != NULL)
5413 	abort = abort || set_ref_in_item(&aucmd_win->w_winvar.di_tv, copyID,
5414 								  NULL, NULL);
5415 
5416     /* tabpage-local variables */
5417     FOR_ALL_TABPAGES(tp)
5418 	abort = abort || set_ref_in_item(&tp->tp_winvar.di_tv, copyID,
5419 								  NULL, NULL);
5420     /* global variables */
5421     abort = abort || set_ref_in_ht(&globvarht, copyID, NULL);
5422 
5423     /* function-local variables */
5424     abort = abort || set_ref_in_call_stack(copyID);
5425 
5426     /* named functions (matters for closures) */
5427     abort = abort || set_ref_in_functions(copyID);
5428 
5429     /* function call arguments, if v:testing is set. */
5430     abort = abort || set_ref_in_func_args(copyID);
5431 
5432     /* v: vars */
5433     abort = abort || set_ref_in_ht(&vimvarht, copyID, NULL);
5434 
5435 #ifdef FEAT_LUA
5436     abort = abort || set_ref_in_lua(copyID);
5437 #endif
5438 
5439 #ifdef FEAT_PYTHON
5440     abort = abort || set_ref_in_python(copyID);
5441 #endif
5442 
5443 #ifdef FEAT_PYTHON3
5444     abort = abort || set_ref_in_python3(copyID);
5445 #endif
5446 
5447 #ifdef FEAT_JOB_CHANNEL
5448     abort = abort || set_ref_in_channel(copyID);
5449     abort = abort || set_ref_in_job(copyID);
5450 #endif
5451 #ifdef FEAT_NETBEANS_INTG
5452     abort = abort || set_ref_in_nb_channel(copyID);
5453 #endif
5454 
5455 #ifdef FEAT_TIMERS
5456     abort = abort || set_ref_in_timer(copyID);
5457 #endif
5458 
5459 #ifdef FEAT_QUICKFIX
5460     abort = abort || set_ref_in_quickfix(copyID);
5461 #endif
5462 
5463 #ifdef FEAT_TERMINAL
5464     abort = abort || set_ref_in_term(copyID);
5465 #endif
5466 
5467     if (!abort)
5468     {
5469 	/*
5470 	 * 2. Free lists and dictionaries that are not referenced.
5471 	 */
5472 	did_free = free_unref_items(copyID);
5473 
5474 	/*
5475 	 * 3. Check if any funccal can be freed now.
5476 	 *    This may call us back recursively.
5477 	 */
5478 	free_unref_funccal(copyID, testing);
5479     }
5480     else if (p_verbose > 0)
5481     {
5482 	verb_msg(_("Not enough memory to set references, garbage collection aborted!"));
5483     }
5484 
5485     return did_free;
5486 }
5487 
5488 /*
5489  * Free lists, dictionaries, channels and jobs that are no longer referenced.
5490  */
5491     static int
5492 free_unref_items(int copyID)
5493 {
5494     int		did_free = FALSE;
5495 
5496     /* Let all "free" functions know that we are here.  This means no
5497      * dictionaries, lists, channels or jobs are to be freed, because we will
5498      * do that here. */
5499     in_free_unref_items = TRUE;
5500 
5501     /*
5502      * PASS 1: free the contents of the items.  We don't free the items
5503      * themselves yet, so that it is possible to decrement refcount counters
5504      */
5505 
5506     /* Go through the list of dicts and free items without the copyID. */
5507     did_free |= dict_free_nonref(copyID);
5508 
5509     /* Go through the list of lists and free items without the copyID. */
5510     did_free |= list_free_nonref(copyID);
5511 
5512 #ifdef FEAT_JOB_CHANNEL
5513     /* Go through the list of jobs and free items without the copyID. This
5514      * must happen before doing channels, because jobs refer to channels, but
5515      * the reference from the channel to the job isn't tracked. */
5516     did_free |= free_unused_jobs_contents(copyID, COPYID_MASK);
5517 
5518     /* Go through the list of channels and free items without the copyID.  */
5519     did_free |= free_unused_channels_contents(copyID, COPYID_MASK);
5520 #endif
5521 
5522     /*
5523      * PASS 2: free the items themselves.
5524      */
5525     dict_free_items(copyID);
5526     list_free_items(copyID);
5527 
5528 #ifdef FEAT_JOB_CHANNEL
5529     /* Go through the list of jobs and free items without the copyID. This
5530      * must happen before doing channels, because jobs refer to channels, but
5531      * the reference from the channel to the job isn't tracked. */
5532     free_unused_jobs(copyID, COPYID_MASK);
5533 
5534     /* Go through the list of channels and free items without the copyID.  */
5535     free_unused_channels(copyID, COPYID_MASK);
5536 #endif
5537 
5538     in_free_unref_items = FALSE;
5539 
5540     return did_free;
5541 }
5542 
5543 /*
5544  * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
5545  * "list_stack" is used to add lists to be marked.  Can be NULL.
5546  *
5547  * Returns TRUE if setting references failed somehow.
5548  */
5549     int
5550 set_ref_in_ht(hashtab_T *ht, int copyID, list_stack_T **list_stack)
5551 {
5552     int		todo;
5553     int		abort = FALSE;
5554     hashitem_T	*hi;
5555     hashtab_T	*cur_ht;
5556     ht_stack_T	*ht_stack = NULL;
5557     ht_stack_T	*tempitem;
5558 
5559     cur_ht = ht;
5560     for (;;)
5561     {
5562 	if (!abort)
5563 	{
5564 	    /* Mark each item in the hashtab.  If the item contains a hashtab
5565 	     * it is added to ht_stack, if it contains a list it is added to
5566 	     * list_stack. */
5567 	    todo = (int)cur_ht->ht_used;
5568 	    for (hi = cur_ht->ht_array; todo > 0; ++hi)
5569 		if (!HASHITEM_EMPTY(hi))
5570 		{
5571 		    --todo;
5572 		    abort = abort || set_ref_in_item(&HI2DI(hi)->di_tv, copyID,
5573 						       &ht_stack, list_stack);
5574 		}
5575 	}
5576 
5577 	if (ht_stack == NULL)
5578 	    break;
5579 
5580 	/* take an item from the stack */
5581 	cur_ht = ht_stack->ht;
5582 	tempitem = ht_stack;
5583 	ht_stack = ht_stack->prev;
5584 	free(tempitem);
5585     }
5586 
5587     return abort;
5588 }
5589 
5590 /*
5591  * Mark all lists and dicts referenced through list "l" with "copyID".
5592  * "ht_stack" is used to add hashtabs to be marked.  Can be NULL.
5593  *
5594  * Returns TRUE if setting references failed somehow.
5595  */
5596     int
5597 set_ref_in_list(list_T *l, int copyID, ht_stack_T **ht_stack)
5598 {
5599     listitem_T	 *li;
5600     int		 abort = FALSE;
5601     list_T	 *cur_l;
5602     list_stack_T *list_stack = NULL;
5603     list_stack_T *tempitem;
5604 
5605     cur_l = l;
5606     for (;;)
5607     {
5608 	if (!abort)
5609 	    /* Mark each item in the list.  If the item contains a hashtab
5610 	     * it is added to ht_stack, if it contains a list it is added to
5611 	     * list_stack. */
5612 	    for (li = cur_l->lv_first; !abort && li != NULL; li = li->li_next)
5613 		abort = abort || set_ref_in_item(&li->li_tv, copyID,
5614 						       ht_stack, &list_stack);
5615 	if (list_stack == NULL)
5616 	    break;
5617 
5618 	/* take an item from the stack */
5619 	cur_l = list_stack->list;
5620 	tempitem = list_stack;
5621 	list_stack = list_stack->prev;
5622 	free(tempitem);
5623     }
5624 
5625     return abort;
5626 }
5627 
5628 /*
5629  * Mark all lists and dicts referenced through typval "tv" with "copyID".
5630  * "list_stack" is used to add lists to be marked.  Can be NULL.
5631  * "ht_stack" is used to add hashtabs to be marked.  Can be NULL.
5632  *
5633  * Returns TRUE if setting references failed somehow.
5634  */
5635     int
5636 set_ref_in_item(
5637     typval_T	    *tv,
5638     int		    copyID,
5639     ht_stack_T	    **ht_stack,
5640     list_stack_T    **list_stack)
5641 {
5642     int		abort = FALSE;
5643 
5644     if (tv->v_type == VAR_DICT)
5645     {
5646 	dict_T	*dd = tv->vval.v_dict;
5647 
5648 	if (dd != NULL && dd->dv_copyID != copyID)
5649 	{
5650 	    /* Didn't see this dict yet. */
5651 	    dd->dv_copyID = copyID;
5652 	    if (ht_stack == NULL)
5653 	    {
5654 		abort = set_ref_in_ht(&dd->dv_hashtab, copyID, list_stack);
5655 	    }
5656 	    else
5657 	    {
5658 		ht_stack_T *newitem = (ht_stack_T*)malloc(sizeof(ht_stack_T));
5659 		if (newitem == NULL)
5660 		    abort = TRUE;
5661 		else
5662 		{
5663 		    newitem->ht = &dd->dv_hashtab;
5664 		    newitem->prev = *ht_stack;
5665 		    *ht_stack = newitem;
5666 		}
5667 	    }
5668 	}
5669     }
5670     else if (tv->v_type == VAR_LIST)
5671     {
5672 	list_T	*ll = tv->vval.v_list;
5673 
5674 	if (ll != NULL && ll->lv_copyID != copyID)
5675 	{
5676 	    /* Didn't see this list yet. */
5677 	    ll->lv_copyID = copyID;
5678 	    if (list_stack == NULL)
5679 	    {
5680 		abort = set_ref_in_list(ll, copyID, ht_stack);
5681 	    }
5682 	    else
5683 	    {
5684 		list_stack_T *newitem = (list_stack_T*)malloc(
5685 							sizeof(list_stack_T));
5686 		if (newitem == NULL)
5687 		    abort = TRUE;
5688 		else
5689 		{
5690 		    newitem->list = ll;
5691 		    newitem->prev = *list_stack;
5692 		    *list_stack = newitem;
5693 		}
5694 	    }
5695 	}
5696     }
5697     else if (tv->v_type == VAR_FUNC)
5698     {
5699 	abort = set_ref_in_func(tv->vval.v_string, NULL, copyID);
5700     }
5701     else if (tv->v_type == VAR_PARTIAL)
5702     {
5703 	partial_T	*pt = tv->vval.v_partial;
5704 	int		i;
5705 
5706 	/* A partial does not have a copyID, because it cannot contain itself.
5707 	 */
5708 	if (pt != NULL)
5709 	{
5710 	    abort = set_ref_in_func(pt->pt_name, pt->pt_func, copyID);
5711 
5712 	    if (pt->pt_dict != NULL)
5713 	    {
5714 		typval_T dtv;
5715 
5716 		dtv.v_type = VAR_DICT;
5717 		dtv.vval.v_dict = pt->pt_dict;
5718 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5719 	    }
5720 
5721 	    for (i = 0; i < pt->pt_argc; ++i)
5722 		abort = abort || set_ref_in_item(&pt->pt_argv[i], copyID,
5723 							ht_stack, list_stack);
5724 	}
5725     }
5726 #ifdef FEAT_JOB_CHANNEL
5727     else if (tv->v_type == VAR_JOB)
5728     {
5729 	job_T	    *job = tv->vval.v_job;
5730 	typval_T    dtv;
5731 
5732 	if (job != NULL && job->jv_copyID != copyID)
5733 	{
5734 	    job->jv_copyID = copyID;
5735 	    if (job->jv_channel != NULL)
5736 	    {
5737 		dtv.v_type = VAR_CHANNEL;
5738 		dtv.vval.v_channel = job->jv_channel;
5739 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5740 	    }
5741 	    if (job->jv_exit_partial != NULL)
5742 	    {
5743 		dtv.v_type = VAR_PARTIAL;
5744 		dtv.vval.v_partial = job->jv_exit_partial;
5745 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5746 	    }
5747 	}
5748     }
5749     else if (tv->v_type == VAR_CHANNEL)
5750     {
5751 	channel_T   *ch =tv->vval.v_channel;
5752 	ch_part_T   part;
5753 	typval_T    dtv;
5754 	jsonq_T	    *jq;
5755 	cbq_T	    *cq;
5756 
5757 	if (ch != NULL && ch->ch_copyID != copyID)
5758 	{
5759 	    ch->ch_copyID = copyID;
5760 	    for (part = PART_SOCK; part < PART_COUNT; ++part)
5761 	    {
5762 		for (jq = ch->ch_part[part].ch_json_head.jq_next; jq != NULL;
5763 							     jq = jq->jq_next)
5764 		    set_ref_in_item(jq->jq_value, copyID, ht_stack, list_stack);
5765 		for (cq = ch->ch_part[part].ch_cb_head.cq_next; cq != NULL;
5766 							     cq = cq->cq_next)
5767 		    if (cq->cq_partial != NULL)
5768 		    {
5769 			dtv.v_type = VAR_PARTIAL;
5770 			dtv.vval.v_partial = cq->cq_partial;
5771 			set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5772 		    }
5773 		if (ch->ch_part[part].ch_partial != NULL)
5774 		{
5775 		    dtv.v_type = VAR_PARTIAL;
5776 		    dtv.vval.v_partial = ch->ch_part[part].ch_partial;
5777 		    set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5778 		}
5779 	    }
5780 	    if (ch->ch_partial != NULL)
5781 	    {
5782 		dtv.v_type = VAR_PARTIAL;
5783 		dtv.vval.v_partial = ch->ch_partial;
5784 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5785 	    }
5786 	    if (ch->ch_close_partial != NULL)
5787 	    {
5788 		dtv.v_type = VAR_PARTIAL;
5789 		dtv.vval.v_partial = ch->ch_close_partial;
5790 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5791 	    }
5792 	}
5793     }
5794 #endif
5795     return abort;
5796 }
5797 
5798     static char *
5799 get_var_special_name(int nr)
5800 {
5801     switch (nr)
5802     {
5803 	case VVAL_FALSE: return "v:false";
5804 	case VVAL_TRUE:  return "v:true";
5805 	case VVAL_NONE:  return "v:none";
5806 	case VVAL_NULL:  return "v:null";
5807     }
5808     internal_error("get_var_special_name()");
5809     return "42";
5810 }
5811 
5812 /*
5813  * Return a string with the string representation of a variable.
5814  * If the memory is allocated "tofree" is set to it, otherwise NULL.
5815  * "numbuf" is used for a number.
5816  * When "copyID" is not NULL replace recursive lists and dicts with "...".
5817  * When both "echo_style" and "composite_val" are FALSE, put quotes around
5818  * stings as "string()", otherwise does not put quotes around strings, as
5819  * ":echo" displays values.
5820  * When "restore_copyID" is FALSE, repeated items in dictionaries and lists
5821  * are replaced with "...".
5822  * May return NULL.
5823  */
5824     char_u *
5825 echo_string_core(
5826     typval_T	*tv,
5827     char_u	**tofree,
5828     char_u	*numbuf,
5829     int		copyID,
5830     int		echo_style,
5831     int		restore_copyID,
5832     int		composite_val)
5833 {
5834     static int	recurse = 0;
5835     char_u	*r = NULL;
5836 
5837     if (recurse >= DICT_MAXNEST)
5838     {
5839 	if (!did_echo_string_emsg)
5840 	{
5841 	    /* Only give this message once for a recursive call to avoid
5842 	     * flooding the user with errors.  And stop iterating over lists
5843 	     * and dicts. */
5844 	    did_echo_string_emsg = TRUE;
5845 	    emsg(_("E724: variable nested too deep for displaying"));
5846 	}
5847 	*tofree = NULL;
5848 	return (char_u *)"{E724}";
5849     }
5850     ++recurse;
5851 
5852     switch (tv->v_type)
5853     {
5854 	case VAR_STRING:
5855 	    if (echo_style && !composite_val)
5856 	    {
5857 		*tofree = NULL;
5858 		r = tv->vval.v_string;
5859 		if (r == NULL)
5860 		    r = (char_u *)"";
5861 	    }
5862 	    else
5863 	    {
5864 		*tofree = string_quote(tv->vval.v_string, FALSE);
5865 		r = *tofree;
5866 	    }
5867 	    break;
5868 
5869 	case VAR_FUNC:
5870 	    if (echo_style)
5871 	    {
5872 		*tofree = NULL;
5873 		r = tv->vval.v_string;
5874 	    }
5875 	    else
5876 	    {
5877 		*tofree = string_quote(tv->vval.v_string, TRUE);
5878 		r = *tofree;
5879 	    }
5880 	    break;
5881 
5882 	case VAR_PARTIAL:
5883 	    {
5884 		partial_T   *pt = tv->vval.v_partial;
5885 		char_u	    *fname = string_quote(pt == NULL ? NULL
5886 						    : partial_name(pt), FALSE);
5887 		garray_T    ga;
5888 		int	    i;
5889 		char_u	    *tf;
5890 
5891 		ga_init2(&ga, 1, 100);
5892 		ga_concat(&ga, (char_u *)"function(");
5893 		if (fname != NULL)
5894 		{
5895 		    ga_concat(&ga, fname);
5896 		    vim_free(fname);
5897 		}
5898 		if (pt != NULL && pt->pt_argc > 0)
5899 		{
5900 		    ga_concat(&ga, (char_u *)", [");
5901 		    for (i = 0; i < pt->pt_argc; ++i)
5902 		    {
5903 			if (i > 0)
5904 			    ga_concat(&ga, (char_u *)", ");
5905 			ga_concat(&ga,
5906 			     tv2string(&pt->pt_argv[i], &tf, numbuf, copyID));
5907 			vim_free(tf);
5908 		    }
5909 		    ga_concat(&ga, (char_u *)"]");
5910 		}
5911 		if (pt != NULL && pt->pt_dict != NULL)
5912 		{
5913 		    typval_T dtv;
5914 
5915 		    ga_concat(&ga, (char_u *)", ");
5916 		    dtv.v_type = VAR_DICT;
5917 		    dtv.vval.v_dict = pt->pt_dict;
5918 		    ga_concat(&ga, tv2string(&dtv, &tf, numbuf, copyID));
5919 		    vim_free(tf);
5920 		}
5921 		ga_concat(&ga, (char_u *)")");
5922 
5923 		*tofree = ga.ga_data;
5924 		r = *tofree;
5925 		break;
5926 	    }
5927 
5928 	case VAR_BLOB:
5929 	    r = blob2string(tv->vval.v_blob, tofree, numbuf);
5930 	    break;
5931 
5932 	case VAR_LIST:
5933 	    if (tv->vval.v_list == NULL)
5934 	    {
5935 		*tofree = NULL;
5936 		r = NULL;
5937 	    }
5938 	    else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID
5939 		    && tv->vval.v_list->lv_len > 0)
5940 	    {
5941 		*tofree = NULL;
5942 		r = (char_u *)"[...]";
5943 	    }
5944 	    else
5945 	    {
5946 		int old_copyID = tv->vval.v_list->lv_copyID;
5947 
5948 		tv->vval.v_list->lv_copyID = copyID;
5949 		*tofree = list2string(tv, copyID, restore_copyID);
5950 		if (restore_copyID)
5951 		    tv->vval.v_list->lv_copyID = old_copyID;
5952 		r = *tofree;
5953 	    }
5954 	    break;
5955 
5956 	case VAR_DICT:
5957 	    if (tv->vval.v_dict == NULL)
5958 	    {
5959 		*tofree = NULL;
5960 		r = NULL;
5961 	    }
5962 	    else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID
5963 		    && tv->vval.v_dict->dv_hashtab.ht_used != 0)
5964 	    {
5965 		*tofree = NULL;
5966 		r = (char_u *)"{...}";
5967 	    }
5968 	    else
5969 	    {
5970 		int old_copyID = tv->vval.v_dict->dv_copyID;
5971 		tv->vval.v_dict->dv_copyID = copyID;
5972 		*tofree = dict2string(tv, copyID, restore_copyID);
5973 		if (restore_copyID)
5974 		    tv->vval.v_dict->dv_copyID = old_copyID;
5975 		r = *tofree;
5976 	    }
5977 	    break;
5978 
5979 	case VAR_NUMBER:
5980 	case VAR_UNKNOWN:
5981 	    *tofree = NULL;
5982 	    r = tv_get_string_buf(tv, numbuf);
5983 	    break;
5984 
5985 	case VAR_JOB:
5986 	case VAR_CHANNEL:
5987 	    *tofree = NULL;
5988 	    r = tv_get_string_buf(tv, numbuf);
5989 	    if (composite_val)
5990 	    {
5991 		*tofree = string_quote(r, FALSE);
5992 		r = *tofree;
5993 	    }
5994 	    break;
5995 
5996 	case VAR_FLOAT:
5997 #ifdef FEAT_FLOAT
5998 	    *tofree = NULL;
5999 	    vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
6000 	    r = numbuf;
6001 	    break;
6002 #endif
6003 
6004 	case VAR_SPECIAL:
6005 	    *tofree = NULL;
6006 	    r = (char_u *)get_var_special_name(tv->vval.v_number);
6007 	    break;
6008     }
6009 
6010     if (--recurse == 0)
6011 	did_echo_string_emsg = FALSE;
6012     return r;
6013 }
6014 
6015 /*
6016  * Return a string with the string representation of a variable.
6017  * If the memory is allocated "tofree" is set to it, otherwise NULL.
6018  * "numbuf" is used for a number.
6019  * Does not put quotes around strings, as ":echo" displays values.
6020  * When "copyID" is not NULL replace recursive lists and dicts with "...".
6021  * May return NULL.
6022  */
6023     char_u *
6024 echo_string(
6025     typval_T	*tv,
6026     char_u	**tofree,
6027     char_u	*numbuf,
6028     int		copyID)
6029 {
6030     return echo_string_core(tv, tofree, numbuf, copyID, TRUE, FALSE, FALSE);
6031 }
6032 
6033 /*
6034  * Return a string with the string representation of a variable.
6035  * If the memory is allocated "tofree" is set to it, otherwise NULL.
6036  * "numbuf" is used for a number.
6037  * Puts quotes around strings, so that they can be parsed back by eval().
6038  * May return NULL.
6039  */
6040     char_u *
6041 tv2string(
6042     typval_T	*tv,
6043     char_u	**tofree,
6044     char_u	*numbuf,
6045     int		copyID)
6046 {
6047     return echo_string_core(tv, tofree, numbuf, copyID, FALSE, TRUE, FALSE);
6048 }
6049 
6050 /*
6051  * Return string "str" in ' quotes, doubling ' characters.
6052  * If "str" is NULL an empty string is assumed.
6053  * If "function" is TRUE make it function('string').
6054  */
6055     char_u *
6056 string_quote(char_u *str, int function)
6057 {
6058     unsigned	len;
6059     char_u	*p, *r, *s;
6060 
6061     len = (function ? 13 : 3);
6062     if (str != NULL)
6063     {
6064 	len += (unsigned)STRLEN(str);
6065 	for (p = str; *p != NUL; MB_PTR_ADV(p))
6066 	    if (*p == '\'')
6067 		++len;
6068     }
6069     s = r = alloc(len);
6070     if (r != NULL)
6071     {
6072 	if (function)
6073 	{
6074 	    STRCPY(r, "function('");
6075 	    r += 10;
6076 	}
6077 	else
6078 	    *r++ = '\'';
6079 	if (str != NULL)
6080 	    for (p = str; *p != NUL; )
6081 	    {
6082 		if (*p == '\'')
6083 		    *r++ = '\'';
6084 		MB_COPY_CHAR(p, r);
6085 	    }
6086 	*r++ = '\'';
6087 	if (function)
6088 	    *r++ = ')';
6089 	*r++ = NUL;
6090     }
6091     return s;
6092 }
6093 
6094 #if defined(FEAT_FLOAT) || defined(PROTO)
6095 /*
6096  * Convert the string "text" to a floating point number.
6097  * This uses strtod().  setlocale(LC_NUMERIC, "C") has been used to make sure
6098  * this always uses a decimal point.
6099  * Returns the length of the text that was consumed.
6100  */
6101     int
6102 string2float(
6103     char_u	*text,
6104     float_T	*value)	    /* result stored here */
6105 {
6106     char	*s = (char *)text;
6107     float_T	f;
6108 
6109     /* MS-Windows does not deal with "inf" and "nan" properly. */
6110     if (STRNICMP(text, "inf", 3) == 0)
6111     {
6112 	*value = INFINITY;
6113 	return 3;
6114     }
6115     if (STRNICMP(text, "-inf", 3) == 0)
6116     {
6117 	*value = -INFINITY;
6118 	return 4;
6119     }
6120     if (STRNICMP(text, "nan", 3) == 0)
6121     {
6122 	*value = NAN;
6123 	return 3;
6124     }
6125     f = strtod(s, &s);
6126     *value = f;
6127     return (int)((char_u *)s - text);
6128 }
6129 #endif
6130 
6131 /*
6132  * Get the value of an environment variable.
6133  * "arg" is pointing to the '$'.  It is advanced to after the name.
6134  * If the environment variable was not set, silently assume it is empty.
6135  * Return FAIL if the name is invalid.
6136  */
6137     static int
6138 get_env_tv(char_u **arg, typval_T *rettv, int evaluate)
6139 {
6140     char_u	*string = NULL;
6141     int		len;
6142     int		cc;
6143     char_u	*name;
6144     int		mustfree = FALSE;
6145 
6146     ++*arg;
6147     name = *arg;
6148     len = get_env_len(arg);
6149     if (evaluate)
6150     {
6151 	if (len == 0)
6152 	    return FAIL; /* invalid empty name */
6153 
6154 	cc = name[len];
6155 	name[len] = NUL;
6156 	/* first try vim_getenv(), fast for normal environment vars */
6157 	string = vim_getenv(name, &mustfree);
6158 	if (string != NULL && *string != NUL)
6159 	{
6160 	    if (!mustfree)
6161 		string = vim_strsave(string);
6162 	}
6163 	else
6164 	{
6165 	    if (mustfree)
6166 		vim_free(string);
6167 
6168 	    /* next try expanding things like $VIM and ${HOME} */
6169 	    string = expand_env_save(name - 1);
6170 	    if (string != NULL && *string == '$')
6171 		VIM_CLEAR(string);
6172 	}
6173 	name[len] = cc;
6174 
6175 	rettv->v_type = VAR_STRING;
6176 	rettv->vval.v_string = string;
6177     }
6178 
6179     return OK;
6180 }
6181 
6182 
6183 
6184 /*
6185  * Translate a String variable into a position.
6186  * Returns NULL when there is an error.
6187  */
6188     pos_T *
6189 var2fpos(
6190     typval_T	*varp,
6191     int		dollar_lnum,	/* TRUE when $ is last line */
6192     int		*fnum)		/* set to fnum for '0, 'A, etc. */
6193 {
6194     char_u		*name;
6195     static pos_T	pos;
6196     pos_T		*pp;
6197 
6198     /* Argument can be [lnum, col, coladd]. */
6199     if (varp->v_type == VAR_LIST)
6200     {
6201 	list_T		*l;
6202 	int		len;
6203 	int		error = FALSE;
6204 	listitem_T	*li;
6205 
6206 	l = varp->vval.v_list;
6207 	if (l == NULL)
6208 	    return NULL;
6209 
6210 	/* Get the line number */
6211 	pos.lnum = list_find_nr(l, 0L, &error);
6212 	if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
6213 	    return NULL;	/* invalid line number */
6214 
6215 	/* Get the column number */
6216 	pos.col = list_find_nr(l, 1L, &error);
6217 	if (error)
6218 	    return NULL;
6219 	len = (long)STRLEN(ml_get(pos.lnum));
6220 
6221 	/* We accept "$" for the column number: last column. */
6222 	li = list_find(l, 1L);
6223 	if (li != NULL && li->li_tv.v_type == VAR_STRING
6224 		&& li->li_tv.vval.v_string != NULL
6225 		&& STRCMP(li->li_tv.vval.v_string, "$") == 0)
6226 	    pos.col = len + 1;
6227 
6228 	/* Accept a position up to the NUL after the line. */
6229 	if (pos.col == 0 || (int)pos.col > len + 1)
6230 	    return NULL;	/* invalid column number */
6231 	--pos.col;
6232 
6233 	/* Get the virtual offset.  Defaults to zero. */
6234 	pos.coladd = list_find_nr(l, 2L, &error);
6235 	if (error)
6236 	    pos.coladd = 0;
6237 
6238 	return &pos;
6239     }
6240 
6241     name = tv_get_string_chk(varp);
6242     if (name == NULL)
6243 	return NULL;
6244     if (name[0] == '.')				/* cursor */
6245 	return &curwin->w_cursor;
6246     if (name[0] == 'v' && name[1] == NUL)	/* Visual start */
6247     {
6248 	if (VIsual_active)
6249 	    return &VIsual;
6250 	return &curwin->w_cursor;
6251     }
6252     if (name[0] == '\'')			/* mark */
6253     {
6254 	pp = getmark_buf_fnum(curbuf, name[1], FALSE, fnum);
6255 	if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
6256 	    return NULL;
6257 	return pp;
6258     }
6259 
6260     pos.coladd = 0;
6261 
6262     if (name[0] == 'w' && dollar_lnum)
6263     {
6264 	pos.col = 0;
6265 	if (name[1] == '0')		/* "w0": first visible line */
6266 	{
6267 	    update_topline();
6268 	    /* In silent Ex mode topline is zero, but that's not a valid line
6269 	     * number; use one instead. */
6270 	    pos.lnum = curwin->w_topline > 0 ? curwin->w_topline : 1;
6271 	    return &pos;
6272 	}
6273 	else if (name[1] == '$')	/* "w$": last visible line */
6274 	{
6275 	    validate_botline();
6276 	    /* In silent Ex mode botline is zero, return zero then. */
6277 	    pos.lnum = curwin->w_botline > 0 ? curwin->w_botline - 1 : 0;
6278 	    return &pos;
6279 	}
6280     }
6281     else if (name[0] == '$')		/* last column or line */
6282     {
6283 	if (dollar_lnum)
6284 	{
6285 	    pos.lnum = curbuf->b_ml.ml_line_count;
6286 	    pos.col = 0;
6287 	}
6288 	else
6289 	{
6290 	    pos.lnum = curwin->w_cursor.lnum;
6291 	    pos.col = (colnr_T)STRLEN(ml_get_curline());
6292 	}
6293 	return &pos;
6294     }
6295     return NULL;
6296 }
6297 
6298 /*
6299  * Convert list in "arg" into a position and optional file number.
6300  * When "fnump" is NULL there is no file number, only 3 items.
6301  * Note that the column is passed on as-is, the caller may want to decrement
6302  * it to use 1 for the first column.
6303  * Return FAIL when conversion is not possible, doesn't check the position for
6304  * validity.
6305  */
6306     int
6307 list2fpos(
6308     typval_T	*arg,
6309     pos_T	*posp,
6310     int		*fnump,
6311     colnr_T	*curswantp)
6312 {
6313     list_T	*l = arg->vval.v_list;
6314     long	i = 0;
6315     long	n;
6316 
6317     /* List must be: [fnum, lnum, col, coladd, curswant], where "fnum" is only
6318      * there when "fnump" isn't NULL; "coladd" and "curswant" are optional. */
6319     if (arg->v_type != VAR_LIST
6320 	    || l == NULL
6321 	    || l->lv_len < (fnump == NULL ? 2 : 3)
6322 	    || l->lv_len > (fnump == NULL ? 4 : 5))
6323 	return FAIL;
6324 
6325     if (fnump != NULL)
6326     {
6327 	n = list_find_nr(l, i++, NULL);	/* fnum */
6328 	if (n < 0)
6329 	    return FAIL;
6330 	if (n == 0)
6331 	    n = curbuf->b_fnum;		/* current buffer */
6332 	*fnump = n;
6333     }
6334 
6335     n = list_find_nr(l, i++, NULL);	/* lnum */
6336     if (n < 0)
6337 	return FAIL;
6338     posp->lnum = n;
6339 
6340     n = list_find_nr(l, i++, NULL);	/* col */
6341     if (n < 0)
6342 	return FAIL;
6343     posp->col = n;
6344 
6345     n = list_find_nr(l, i, NULL);	/* off */
6346     if (n < 0)
6347 	posp->coladd = 0;
6348     else
6349 	posp->coladd = n;
6350 
6351     if (curswantp != NULL)
6352 	*curswantp = list_find_nr(l, i + 1, NULL);  /* curswant */
6353 
6354     return OK;
6355 }
6356 
6357 /*
6358  * Get the length of an environment variable name.
6359  * Advance "arg" to the first character after the name.
6360  * Return 0 for error.
6361  */
6362     static int
6363 get_env_len(char_u **arg)
6364 {
6365     char_u	*p;
6366     int		len;
6367 
6368     for (p = *arg; vim_isIDc(*p); ++p)
6369 	;
6370     if (p == *arg)	    /* no name found */
6371 	return 0;
6372 
6373     len = (int)(p - *arg);
6374     *arg = p;
6375     return len;
6376 }
6377 
6378 /*
6379  * Get the length of the name of a function or internal variable.
6380  * "arg" is advanced to the first non-white character after the name.
6381  * Return 0 if something is wrong.
6382  */
6383     int
6384 get_id_len(char_u **arg)
6385 {
6386     char_u	*p;
6387     int		len;
6388 
6389     /* Find the end of the name. */
6390     for (p = *arg; eval_isnamec(*p); ++p)
6391     {
6392 	if (*p == ':')
6393 	{
6394 	    /* "s:" is start of "s:var", but "n:" is not and can be used in
6395 	     * slice "[n:]".  Also "xx:" is not a namespace. */
6396 	    len = (int)(p - *arg);
6397 	    if ((len == 1 && vim_strchr(NAMESPACE_CHAR, **arg) == NULL)
6398 		    || len > 1)
6399 		break;
6400 	}
6401     }
6402     if (p == *arg)	    /* no name found */
6403 	return 0;
6404 
6405     len = (int)(p - *arg);
6406     *arg = skipwhite(p);
6407 
6408     return len;
6409 }
6410 
6411 /*
6412  * Get the length of the name of a variable or function.
6413  * Only the name is recognized, does not handle ".key" or "[idx]".
6414  * "arg" is advanced to the first non-white character after the name.
6415  * Return -1 if curly braces expansion failed.
6416  * Return 0 if something else is wrong.
6417  * If the name contains 'magic' {}'s, expand them and return the
6418  * expanded name in an allocated string via 'alias' - caller must free.
6419  */
6420     int
6421 get_name_len(
6422     char_u	**arg,
6423     char_u	**alias,
6424     int		evaluate,
6425     int		verbose)
6426 {
6427     int		len;
6428     char_u	*p;
6429     char_u	*expr_start;
6430     char_u	*expr_end;
6431 
6432     *alias = NULL;  /* default to no alias */
6433 
6434     if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
6435 						  && (*arg)[2] == (int)KE_SNR)
6436     {
6437 	/* hard coded <SNR>, already translated */
6438 	*arg += 3;
6439 	return get_id_len(arg) + 3;
6440     }
6441     len = eval_fname_script(*arg);
6442     if (len > 0)
6443     {
6444 	/* literal "<SID>", "s:" or "<SNR>" */
6445 	*arg += len;
6446     }
6447 
6448     /*
6449      * Find the end of the name; check for {} construction.
6450      */
6451     p = find_name_end(*arg, &expr_start, &expr_end,
6452 					       len > 0 ? 0 : FNE_CHECK_START);
6453     if (expr_start != NULL)
6454     {
6455 	char_u	*temp_string;
6456 
6457 	if (!evaluate)
6458 	{
6459 	    len += (int)(p - *arg);
6460 	    *arg = skipwhite(p);
6461 	    return len;
6462 	}
6463 
6464 	/*
6465 	 * Include any <SID> etc in the expanded string:
6466 	 * Thus the -len here.
6467 	 */
6468 	temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
6469 	if (temp_string == NULL)
6470 	    return -1;
6471 	*alias = temp_string;
6472 	*arg = skipwhite(p);
6473 	return (int)STRLEN(temp_string);
6474     }
6475 
6476     len += get_id_len(arg);
6477     // Only give an error when there is something, otherwise it will be
6478     // reported at a higher level.
6479     if (len == 0 && verbose && **arg != NUL)
6480 	semsg(_(e_invexpr2), *arg);
6481 
6482     return len;
6483 }
6484 
6485 /*
6486  * Find the end of a variable or function name, taking care of magic braces.
6487  * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
6488  * start and end of the first magic braces item.
6489  * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
6490  * Return a pointer to just after the name.  Equal to "arg" if there is no
6491  * valid name.
6492  */
6493     char_u *
6494 find_name_end(
6495     char_u	*arg,
6496     char_u	**expr_start,
6497     char_u	**expr_end,
6498     int		flags)
6499 {
6500     int		mb_nest = 0;
6501     int		br_nest = 0;
6502     char_u	*p;
6503     int		len;
6504 
6505     if (expr_start != NULL)
6506     {
6507 	*expr_start = NULL;
6508 	*expr_end = NULL;
6509     }
6510 
6511     /* Quick check for valid starting character. */
6512     if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
6513 	return arg;
6514 
6515     for (p = arg; *p != NUL
6516 		    && (eval_isnamec(*p)
6517 			|| *p == '{'
6518 			|| ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
6519 			|| mb_nest != 0
6520 			|| br_nest != 0); MB_PTR_ADV(p))
6521     {
6522 	if (*p == '\'')
6523 	{
6524 	    /* skip over 'string' to avoid counting [ and ] inside it. */
6525 	    for (p = p + 1; *p != NUL && *p != '\''; MB_PTR_ADV(p))
6526 		;
6527 	    if (*p == NUL)
6528 		break;
6529 	}
6530 	else if (*p == '"')
6531 	{
6532 	    /* skip over "str\"ing" to avoid counting [ and ] inside it. */
6533 	    for (p = p + 1; *p != NUL && *p != '"'; MB_PTR_ADV(p))
6534 		if (*p == '\\' && p[1] != NUL)
6535 		    ++p;
6536 	    if (*p == NUL)
6537 		break;
6538 	}
6539 	else if (br_nest == 0 && mb_nest == 0 && *p == ':')
6540 	{
6541 	    /* "s:" is start of "s:var", but "n:" is not and can be used in
6542 	     * slice "[n:]".  Also "xx:" is not a namespace. But {ns}: is. */
6543 	    len = (int)(p - arg);
6544 	    if ((len == 1 && vim_strchr(NAMESPACE_CHAR, *arg) == NULL)
6545 		    || (len > 1 && p[-1] != '}'))
6546 		break;
6547 	}
6548 
6549 	if (mb_nest == 0)
6550 	{
6551 	    if (*p == '[')
6552 		++br_nest;
6553 	    else if (*p == ']')
6554 		--br_nest;
6555 	}
6556 
6557 	if (br_nest == 0)
6558 	{
6559 	    if (*p == '{')
6560 	    {
6561 		mb_nest++;
6562 		if (expr_start != NULL && *expr_start == NULL)
6563 		    *expr_start = p;
6564 	    }
6565 	    else if (*p == '}')
6566 	    {
6567 		mb_nest--;
6568 		if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
6569 		    *expr_end = p;
6570 	    }
6571 	}
6572     }
6573 
6574     return p;
6575 }
6576 
6577 /*
6578  * Expands out the 'magic' {}'s in a variable/function name.
6579  * Note that this can call itself recursively, to deal with
6580  * constructs like foo{bar}{baz}{bam}
6581  * The four pointer arguments point to "foo{expre}ss{ion}bar"
6582  *			"in_start"      ^
6583  *			"expr_start"	   ^
6584  *			"expr_end"		 ^
6585  *			"in_end"			    ^
6586  *
6587  * Returns a new allocated string, which the caller must free.
6588  * Returns NULL for failure.
6589  */
6590     static char_u *
6591 make_expanded_name(
6592     char_u	*in_start,
6593     char_u	*expr_start,
6594     char_u	*expr_end,
6595     char_u	*in_end)
6596 {
6597     char_u	c1;
6598     char_u	*retval = NULL;
6599     char_u	*temp_result;
6600     char_u	*nextcmd = NULL;
6601 
6602     if (expr_end == NULL || in_end == NULL)
6603 	return NULL;
6604     *expr_start	= NUL;
6605     *expr_end = NUL;
6606     c1 = *in_end;
6607     *in_end = NUL;
6608 
6609     temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
6610     if (temp_result != NULL && nextcmd == NULL)
6611     {
6612 	retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
6613 						   + (in_end - expr_end) + 1));
6614 	if (retval != NULL)
6615 	{
6616 	    STRCPY(retval, in_start);
6617 	    STRCAT(retval, temp_result);
6618 	    STRCAT(retval, expr_end + 1);
6619 	}
6620     }
6621     vim_free(temp_result);
6622 
6623     *in_end = c1;		/* put char back for error messages */
6624     *expr_start = '{';
6625     *expr_end = '}';
6626 
6627     if (retval != NULL)
6628     {
6629 	temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
6630 	if (expr_start != NULL)
6631 	{
6632 	    /* Further expansion! */
6633 	    temp_result = make_expanded_name(retval, expr_start,
6634 						       expr_end, temp_result);
6635 	    vim_free(retval);
6636 	    retval = temp_result;
6637 	}
6638     }
6639 
6640     return retval;
6641 }
6642 
6643 /*
6644  * Return TRUE if character "c" can be used in a variable or function name.
6645  * Does not include '{' or '}' for magic braces.
6646  */
6647     int
6648 eval_isnamec(int c)
6649 {
6650     return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
6651 }
6652 
6653 /*
6654  * Return TRUE if character "c" can be used as the first character in a
6655  * variable or function name (excluding '{' and '}').
6656  */
6657     int
6658 eval_isnamec1(int c)
6659 {
6660     return (ASCII_ISALPHA(c) || c == '_');
6661 }
6662 
6663 /*
6664  * Set number v: variable to "val".
6665  */
6666     void
6667 set_vim_var_nr(int idx, varnumber_T val)
6668 {
6669     vimvars[idx].vv_nr = val;
6670 }
6671 
6672 /*
6673  * Get number v: variable value.
6674  */
6675     varnumber_T
6676 get_vim_var_nr(int idx)
6677 {
6678     return vimvars[idx].vv_nr;
6679 }
6680 
6681 /*
6682  * Get string v: variable value.  Uses a static buffer, can only be used once.
6683  * If the String variable has never been set, return an empty string.
6684  * Never returns NULL;
6685  */
6686     char_u *
6687 get_vim_var_str(int idx)
6688 {
6689     return tv_get_string(&vimvars[idx].vv_tv);
6690 }
6691 
6692 /*
6693  * Get List v: variable value.  Caller must take care of reference count when
6694  * needed.
6695  */
6696     list_T *
6697 get_vim_var_list(int idx)
6698 {
6699     return vimvars[idx].vv_list;
6700 }
6701 
6702 /*
6703  * Get Dict v: variable value.  Caller must take care of reference count when
6704  * needed.
6705  */
6706     dict_T *
6707 get_vim_var_dict(int idx)
6708 {
6709     return vimvars[idx].vv_dict;
6710 }
6711 
6712 /*
6713  * Set v:char to character "c".
6714  */
6715     void
6716 set_vim_var_char(int c)
6717 {
6718     char_u	buf[MB_MAXBYTES + 1];
6719 
6720     if (has_mbyte)
6721 	buf[(*mb_char2bytes)(c, buf)] = NUL;
6722     else
6723     {
6724 	buf[0] = c;
6725 	buf[1] = NUL;
6726     }
6727     set_vim_var_string(VV_CHAR, buf, -1);
6728 }
6729 
6730 /*
6731  * Set v:count to "count" and v:count1 to "count1".
6732  * When "set_prevcount" is TRUE first set v:prevcount from v:count.
6733  */
6734     void
6735 set_vcount(
6736     long	count,
6737     long	count1,
6738     int		set_prevcount)
6739 {
6740     if (set_prevcount)
6741 	vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
6742     vimvars[VV_COUNT].vv_nr = count;
6743     vimvars[VV_COUNT1].vv_nr = count1;
6744 }
6745 
6746 /*
6747  * Save variables that might be changed as a side effect.  Used when executing
6748  * a timer callback.
6749  */
6750     void
6751 save_vimvars(vimvars_save_T *vvsave)
6752 {
6753     vvsave->vv_prevcount = vimvars[VV_PREVCOUNT].vv_nr;
6754     vvsave->vv_count = vimvars[VV_COUNT].vv_nr;
6755     vvsave->vv_count1 = vimvars[VV_COUNT1].vv_nr;
6756 }
6757 
6758 /*
6759  * Restore variables saved by save_vimvars().
6760  */
6761     void
6762 restore_vimvars(vimvars_save_T *vvsave)
6763 {
6764     vimvars[VV_PREVCOUNT].vv_nr = vvsave->vv_prevcount;
6765     vimvars[VV_COUNT].vv_nr = vvsave->vv_count;
6766     vimvars[VV_COUNT1].vv_nr = vvsave->vv_count1;
6767 }
6768 
6769 /*
6770  * Set string v: variable to a copy of "val".
6771  */
6772     void
6773 set_vim_var_string(
6774     int		idx,
6775     char_u	*val,
6776     int		len)	    /* length of "val" to use or -1 (whole string) */
6777 {
6778     clear_tv(&vimvars[idx].vv_di.di_tv);
6779     vimvars[idx].vv_type = VAR_STRING;
6780     if (val == NULL)
6781 	vimvars[idx].vv_str = NULL;
6782     else if (len == -1)
6783 	vimvars[idx].vv_str = vim_strsave(val);
6784     else
6785 	vimvars[idx].vv_str = vim_strnsave(val, len);
6786 }
6787 
6788 /*
6789  * Set List v: variable to "val".
6790  */
6791     void
6792 set_vim_var_list(int idx, list_T *val)
6793 {
6794     clear_tv(&vimvars[idx].vv_di.di_tv);
6795     vimvars[idx].vv_type = VAR_LIST;
6796     vimvars[idx].vv_list = val;
6797     if (val != NULL)
6798 	++val->lv_refcount;
6799 }
6800 
6801 /*
6802  * Set Dictionary v: variable to "val".
6803  */
6804     void
6805 set_vim_var_dict(int idx, dict_T *val)
6806 {
6807     clear_tv(&vimvars[idx].vv_di.di_tv);
6808     vimvars[idx].vv_type = VAR_DICT;
6809     vimvars[idx].vv_dict = val;
6810     if (val != NULL)
6811     {
6812 	++val->dv_refcount;
6813 	dict_set_items_ro(val);
6814     }
6815 }
6816 
6817 /*
6818  * Set v:register if needed.
6819  */
6820     void
6821 set_reg_var(int c)
6822 {
6823     char_u	regname;
6824 
6825     if (c == 0 || c == ' ')
6826 	regname = '"';
6827     else
6828 	regname = c;
6829     /* Avoid free/alloc when the value is already right. */
6830     if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
6831 	set_vim_var_string(VV_REG, &regname, 1);
6832 }
6833 
6834 /*
6835  * Get or set v:exception.  If "oldval" == NULL, return the current value.
6836  * Otherwise, restore the value to "oldval" and return NULL.
6837  * Must always be called in pairs to save and restore v:exception!  Does not
6838  * take care of memory allocations.
6839  */
6840     char_u *
6841 v_exception(char_u *oldval)
6842 {
6843     if (oldval == NULL)
6844 	return vimvars[VV_EXCEPTION].vv_str;
6845 
6846     vimvars[VV_EXCEPTION].vv_str = oldval;
6847     return NULL;
6848 }
6849 
6850 /*
6851  * Get or set v:throwpoint.  If "oldval" == NULL, return the current value.
6852  * Otherwise, restore the value to "oldval" and return NULL.
6853  * Must always be called in pairs to save and restore v:throwpoint!  Does not
6854  * take care of memory allocations.
6855  */
6856     char_u *
6857 v_throwpoint(char_u *oldval)
6858 {
6859     if (oldval == NULL)
6860 	return vimvars[VV_THROWPOINT].vv_str;
6861 
6862     vimvars[VV_THROWPOINT].vv_str = oldval;
6863     return NULL;
6864 }
6865 
6866 /*
6867  * Set v:cmdarg.
6868  * If "eap" != NULL, use "eap" to generate the value and return the old value.
6869  * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
6870  * Must always be called in pairs!
6871  */
6872     char_u *
6873 set_cmdarg(exarg_T *eap, char_u *oldarg)
6874 {
6875     char_u	*oldval;
6876     char_u	*newval;
6877     unsigned	len;
6878 
6879     oldval = vimvars[VV_CMDARG].vv_str;
6880     if (eap == NULL)
6881     {
6882 	vim_free(oldval);
6883 	vimvars[VV_CMDARG].vv_str = oldarg;
6884 	return NULL;
6885     }
6886 
6887     if (eap->force_bin == FORCE_BIN)
6888 	len = 6;
6889     else if (eap->force_bin == FORCE_NOBIN)
6890 	len = 8;
6891     else
6892 	len = 0;
6893 
6894     if (eap->read_edit)
6895 	len += 7;
6896 
6897     if (eap->force_ff != 0)
6898 	len += 10; /* " ++ff=unix" */
6899     if (eap->force_enc != 0)
6900 	len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
6901     if (eap->bad_char != 0)
6902 	len += 7 + 4;  /* " ++bad=" + "keep" or "drop" */
6903 
6904     newval = alloc(len + 1);
6905     if (newval == NULL)
6906 	return NULL;
6907 
6908     if (eap->force_bin == FORCE_BIN)
6909 	sprintf((char *)newval, " ++bin");
6910     else if (eap->force_bin == FORCE_NOBIN)
6911 	sprintf((char *)newval, " ++nobin");
6912     else
6913 	*newval = NUL;
6914 
6915     if (eap->read_edit)
6916 	STRCAT(newval, " ++edit");
6917 
6918     if (eap->force_ff != 0)
6919 	sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
6920 						eap->force_ff == 'u' ? "unix"
6921 						: eap->force_ff == 'd' ? "dos"
6922 						: "mac");
6923     if (eap->force_enc != 0)
6924 	sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
6925 					       eap->cmd + eap->force_enc);
6926     if (eap->bad_char == BAD_KEEP)
6927 	STRCPY(newval + STRLEN(newval), " ++bad=keep");
6928     else if (eap->bad_char == BAD_DROP)
6929 	STRCPY(newval + STRLEN(newval), " ++bad=drop");
6930     else if (eap->bad_char != 0)
6931 	sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
6932     vimvars[VV_CMDARG].vv_str = newval;
6933     return oldval;
6934 }
6935 
6936 /*
6937  * Get the value of internal variable "name".
6938  * Return OK or FAIL.  If OK is returned "rettv" must be cleared.
6939  */
6940     int
6941 get_var_tv(
6942     char_u	*name,
6943     int		len,		/* length of "name" */
6944     typval_T	*rettv,		/* NULL when only checking existence */
6945     dictitem_T	**dip,		/* non-NULL when typval's dict item is needed */
6946     int		verbose,	/* may give error message */
6947     int		no_autoload)	/* do not use script autoloading */
6948 {
6949     int		ret = OK;
6950     typval_T	*tv = NULL;
6951     dictitem_T	*v;
6952     int		cc;
6953 
6954     /* truncate the name, so that we can use strcmp() */
6955     cc = name[len];
6956     name[len] = NUL;
6957 
6958     /*
6959      * Check for user-defined variables.
6960      */
6961     v = find_var(name, NULL, no_autoload);
6962     if (v != NULL)
6963     {
6964 	tv = &v->di_tv;
6965 	if (dip != NULL)
6966 	    *dip = v;
6967     }
6968 
6969     if (tv == NULL)
6970     {
6971 	if (rettv != NULL && verbose)
6972 	    semsg(_(e_undefvar), name);
6973 	ret = FAIL;
6974     }
6975     else if (rettv != NULL)
6976 	copy_tv(tv, rettv);
6977 
6978     name[len] = cc;
6979 
6980     return ret;
6981 }
6982 
6983 /*
6984  * Check if variable "name[len]" is a local variable or an argument.
6985  * If so, "*eval_lavars_used" is set to TRUE.
6986  */
6987     static void
6988 check_vars(char_u *name, int len)
6989 {
6990     int		cc;
6991     char_u	*varname;
6992     hashtab_T	*ht;
6993 
6994     if (eval_lavars_used == NULL)
6995 	return;
6996 
6997     /* truncate the name, so that we can use strcmp() */
6998     cc = name[len];
6999     name[len] = NUL;
7000 
7001     ht = find_var_ht(name, &varname);
7002     if (ht == get_funccal_local_ht() || ht == get_funccal_args_ht())
7003     {
7004 	if (find_var(name, NULL, TRUE) != NULL)
7005 	    *eval_lavars_used = TRUE;
7006     }
7007 
7008     name[len] = cc;
7009 }
7010 
7011 /*
7012  * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
7013  * Also handle function call with Funcref variable: func(expr)
7014  * Can all be combined: dict.func(expr)[idx]['func'](expr)
7015  */
7016     int
7017 handle_subscript(
7018     char_u	**arg,
7019     typval_T	*rettv,
7020     int		evaluate,	/* do more than finding the end */
7021     int		verbose)	/* give error messages */
7022 {
7023     int		ret = OK;
7024     dict_T	*selfdict = NULL;
7025     char_u	*s;
7026     int		len;
7027     typval_T	functv;
7028 
7029     while (ret == OK
7030 	    && (**arg == '['
7031 		|| (**arg == '.' && rettv->v_type == VAR_DICT)
7032 		|| (**arg == '(' && (!evaluate || rettv->v_type == VAR_FUNC
7033 					    || rettv->v_type == VAR_PARTIAL)))
7034 	    && !VIM_ISWHITE(*(*arg - 1)))
7035     {
7036 	if (**arg == '(')
7037 	{
7038 	    partial_T	*pt = NULL;
7039 
7040 	    /* need to copy the funcref so that we can clear rettv */
7041 	    if (evaluate)
7042 	    {
7043 		functv = *rettv;
7044 		rettv->v_type = VAR_UNKNOWN;
7045 
7046 		/* Invoke the function.  Recursive! */
7047 		if (functv.v_type == VAR_PARTIAL)
7048 		{
7049 		    pt = functv.vval.v_partial;
7050 		    s = partial_name(pt);
7051 		}
7052 		else
7053 		    s = functv.vval.v_string;
7054 	    }
7055 	    else
7056 		s = (char_u *)"";
7057 	    ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
7058 			curwin->w_cursor.lnum, curwin->w_cursor.lnum,
7059 			&len, evaluate, pt, selfdict);
7060 
7061 	    /* Clear the funcref afterwards, so that deleting it while
7062 	     * evaluating the arguments is possible (see test55). */
7063 	    if (evaluate)
7064 		clear_tv(&functv);
7065 
7066 	    /* Stop the expression evaluation when immediately aborting on
7067 	     * error, or when an interrupt occurred or an exception was thrown
7068 	     * but not caught. */
7069 	    if (aborting())
7070 	    {
7071 		if (ret == OK)
7072 		    clear_tv(rettv);
7073 		ret = FAIL;
7074 	    }
7075 	    dict_unref(selfdict);
7076 	    selfdict = NULL;
7077 	}
7078 	else /* **arg == '[' || **arg == '.' */
7079 	{
7080 	    dict_unref(selfdict);
7081 	    if (rettv->v_type == VAR_DICT)
7082 	    {
7083 		selfdict = rettv->vval.v_dict;
7084 		if (selfdict != NULL)
7085 		    ++selfdict->dv_refcount;
7086 	    }
7087 	    else
7088 		selfdict = NULL;
7089 	    if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
7090 	    {
7091 		clear_tv(rettv);
7092 		ret = FAIL;
7093 	    }
7094 	}
7095     }
7096 
7097     /* Turn "dict.Func" into a partial for "Func" bound to "dict".
7098      * Don't do this when "Func" is already a partial that was bound
7099      * explicitly (pt_auto is FALSE). */
7100     if (selfdict != NULL
7101 	    && (rettv->v_type == VAR_FUNC
7102 		|| (rettv->v_type == VAR_PARTIAL
7103 		    && (rettv->vval.v_partial->pt_auto
7104 			|| rettv->vval.v_partial->pt_dict == NULL))))
7105 	selfdict = make_partial(selfdict, rettv);
7106 
7107     dict_unref(selfdict);
7108     return ret;
7109 }
7110 
7111 /*
7112  * Allocate memory for a variable type-value, and make it empty (0 or NULL
7113  * value).
7114  */
7115     typval_T *
7116 alloc_tv(void)
7117 {
7118     return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
7119 }
7120 
7121 /*
7122  * Allocate memory for a variable type-value, and assign a string to it.
7123  * The string "s" must have been allocated, it is consumed.
7124  * Return NULL for out of memory, the variable otherwise.
7125  */
7126     static typval_T *
7127 alloc_string_tv(char_u *s)
7128 {
7129     typval_T	*rettv;
7130 
7131     rettv = alloc_tv();
7132     if (rettv != NULL)
7133     {
7134 	rettv->v_type = VAR_STRING;
7135 	rettv->vval.v_string = s;
7136     }
7137     else
7138 	vim_free(s);
7139     return rettv;
7140 }
7141 
7142 /*
7143  * Free the memory for a variable type-value.
7144  */
7145     void
7146 free_tv(typval_T *varp)
7147 {
7148     if (varp != NULL)
7149     {
7150 	switch (varp->v_type)
7151 	{
7152 	    case VAR_FUNC:
7153 		func_unref(varp->vval.v_string);
7154 		/* FALLTHROUGH */
7155 	    case VAR_STRING:
7156 		vim_free(varp->vval.v_string);
7157 		break;
7158 	    case VAR_PARTIAL:
7159 		partial_unref(varp->vval.v_partial);
7160 		break;
7161 	    case VAR_BLOB:
7162 		blob_unref(varp->vval.v_blob);
7163 		break;
7164 	    case VAR_LIST:
7165 		list_unref(varp->vval.v_list);
7166 		break;
7167 	    case VAR_DICT:
7168 		dict_unref(varp->vval.v_dict);
7169 		break;
7170 	    case VAR_JOB:
7171 #ifdef FEAT_JOB_CHANNEL
7172 		job_unref(varp->vval.v_job);
7173 		break;
7174 #endif
7175 	    case VAR_CHANNEL:
7176 #ifdef FEAT_JOB_CHANNEL
7177 		channel_unref(varp->vval.v_channel);
7178 		break;
7179 #endif
7180 	    case VAR_NUMBER:
7181 	    case VAR_FLOAT:
7182 	    case VAR_UNKNOWN:
7183 	    case VAR_SPECIAL:
7184 		break;
7185 	}
7186 	vim_free(varp);
7187     }
7188 }
7189 
7190 /*
7191  * Free the memory for a variable value and set the value to NULL or 0.
7192  */
7193     void
7194 clear_tv(typval_T *varp)
7195 {
7196     if (varp != NULL)
7197     {
7198 	switch (varp->v_type)
7199 	{
7200 	    case VAR_FUNC:
7201 		func_unref(varp->vval.v_string);
7202 		/* FALLTHROUGH */
7203 	    case VAR_STRING:
7204 		VIM_CLEAR(varp->vval.v_string);
7205 		break;
7206 	    case VAR_PARTIAL:
7207 		partial_unref(varp->vval.v_partial);
7208 		varp->vval.v_partial = NULL;
7209 		break;
7210 	    case VAR_BLOB:
7211 		blob_unref(varp->vval.v_blob);
7212 		varp->vval.v_blob = NULL;
7213 		break;
7214 	    case VAR_LIST:
7215 		list_unref(varp->vval.v_list);
7216 		varp->vval.v_list = NULL;
7217 		break;
7218 	    case VAR_DICT:
7219 		dict_unref(varp->vval.v_dict);
7220 		varp->vval.v_dict = NULL;
7221 		break;
7222 	    case VAR_NUMBER:
7223 	    case VAR_SPECIAL:
7224 		varp->vval.v_number = 0;
7225 		break;
7226 	    case VAR_FLOAT:
7227 #ifdef FEAT_FLOAT
7228 		varp->vval.v_float = 0.0;
7229 		break;
7230 #endif
7231 	    case VAR_JOB:
7232 #ifdef FEAT_JOB_CHANNEL
7233 		job_unref(varp->vval.v_job);
7234 		varp->vval.v_job = NULL;
7235 #endif
7236 		break;
7237 	    case VAR_CHANNEL:
7238 #ifdef FEAT_JOB_CHANNEL
7239 		channel_unref(varp->vval.v_channel);
7240 		varp->vval.v_channel = NULL;
7241 #endif
7242 	    case VAR_UNKNOWN:
7243 		break;
7244 	}
7245 	varp->v_lock = 0;
7246     }
7247 }
7248 
7249 /*
7250  * Set the value of a variable to NULL without freeing items.
7251  */
7252     void
7253 init_tv(typval_T *varp)
7254 {
7255     if (varp != NULL)
7256 	vim_memset(varp, 0, sizeof(typval_T));
7257 }
7258 
7259 /*
7260  * Get the number value of a variable.
7261  * If it is a String variable, uses vim_str2nr().
7262  * For incompatible types, return 0.
7263  * tv_get_number_chk() is similar to tv_get_number(), but informs the
7264  * caller of incompatible types: it sets *denote to TRUE if "denote"
7265  * is not NULL or returns -1 otherwise.
7266  */
7267     varnumber_T
7268 tv_get_number(typval_T *varp)
7269 {
7270     int		error = FALSE;
7271 
7272     return tv_get_number_chk(varp, &error);	/* return 0L on error */
7273 }
7274 
7275     varnumber_T
7276 tv_get_number_chk(typval_T *varp, int *denote)
7277 {
7278     varnumber_T	n = 0L;
7279 
7280     switch (varp->v_type)
7281     {
7282 	case VAR_NUMBER:
7283 	    return varp->vval.v_number;
7284 	case VAR_FLOAT:
7285 #ifdef FEAT_FLOAT
7286 	    emsg(_("E805: Using a Float as a Number"));
7287 	    break;
7288 #endif
7289 	case VAR_FUNC:
7290 	case VAR_PARTIAL:
7291 	    emsg(_("E703: Using a Funcref as a Number"));
7292 	    break;
7293 	case VAR_STRING:
7294 	    if (varp->vval.v_string != NULL)
7295 		vim_str2nr(varp->vval.v_string, NULL, NULL,
7296 						    STR2NR_ALL, &n, NULL, 0);
7297 	    return n;
7298 	case VAR_LIST:
7299 	    emsg(_("E745: Using a List as a Number"));
7300 	    break;
7301 	case VAR_DICT:
7302 	    emsg(_("E728: Using a Dictionary as a Number"));
7303 	    break;
7304 	case VAR_SPECIAL:
7305 	    return varp->vval.v_number == VVAL_TRUE ? 1 : 0;
7306 	    break;
7307 	case VAR_JOB:
7308 #ifdef FEAT_JOB_CHANNEL
7309 	    emsg(_("E910: Using a Job as a Number"));
7310 	    break;
7311 #endif
7312 	case VAR_CHANNEL:
7313 #ifdef FEAT_JOB_CHANNEL
7314 	    emsg(_("E913: Using a Channel as a Number"));
7315 	    break;
7316 #endif
7317 	case VAR_BLOB:
7318 	    emsg(_("E974: Using a Blob as a Number"));
7319 	    break;
7320 	case VAR_UNKNOWN:
7321 	    internal_error("tv_get_number(UNKNOWN)");
7322 	    break;
7323     }
7324     if (denote == NULL)		/* useful for values that must be unsigned */
7325 	n = -1;
7326     else
7327 	*denote = TRUE;
7328     return n;
7329 }
7330 
7331 #ifdef FEAT_FLOAT
7332     float_T
7333 tv_get_float(typval_T *varp)
7334 {
7335     switch (varp->v_type)
7336     {
7337 	case VAR_NUMBER:
7338 	    return (float_T)(varp->vval.v_number);
7339 	case VAR_FLOAT:
7340 	    return varp->vval.v_float;
7341 	case VAR_FUNC:
7342 	case VAR_PARTIAL:
7343 	    emsg(_("E891: Using a Funcref as a Float"));
7344 	    break;
7345 	case VAR_STRING:
7346 	    emsg(_("E892: Using a String as a Float"));
7347 	    break;
7348 	case VAR_LIST:
7349 	    emsg(_("E893: Using a List as a Float"));
7350 	    break;
7351 	case VAR_DICT:
7352 	    emsg(_("E894: Using a Dictionary as a Float"));
7353 	    break;
7354 	case VAR_SPECIAL:
7355 	    emsg(_("E907: Using a special value as a Float"));
7356 	    break;
7357 	case VAR_JOB:
7358 # ifdef FEAT_JOB_CHANNEL
7359 	    emsg(_("E911: Using a Job as a Float"));
7360 	    break;
7361 # endif
7362 	case VAR_CHANNEL:
7363 # ifdef FEAT_JOB_CHANNEL
7364 	    emsg(_("E914: Using a Channel as a Float"));
7365 	    break;
7366 # endif
7367 	case VAR_BLOB:
7368 	    emsg(_("E975: Using a Blob as a Float"));
7369 	    break;
7370 	case VAR_UNKNOWN:
7371 	    internal_error("tv_get_float(UNKNOWN)");
7372 	    break;
7373     }
7374     return 0;
7375 }
7376 #endif
7377 
7378 /*
7379  * Get the string value of a variable.
7380  * If it is a Number variable, the number is converted into a string.
7381  * tv_get_string() uses a single, static buffer.  YOU CAN ONLY USE IT ONCE!
7382  * tv_get_string_buf() uses a given buffer.
7383  * If the String variable has never been set, return an empty string.
7384  * Never returns NULL;
7385  * tv_get_string_chk() and tv_get_string_buf_chk() are similar, but return
7386  * NULL on error.
7387  */
7388     char_u *
7389 tv_get_string(typval_T *varp)
7390 {
7391     static char_u   mybuf[NUMBUFLEN];
7392 
7393     return tv_get_string_buf(varp, mybuf);
7394 }
7395 
7396     char_u *
7397 tv_get_string_buf(typval_T *varp, char_u *buf)
7398 {
7399     char_u	*res =  tv_get_string_buf_chk(varp, buf);
7400 
7401     return res != NULL ? res : (char_u *)"";
7402 }
7403 
7404 /*
7405  * Careful: This uses a single, static buffer.  YOU CAN ONLY USE IT ONCE!
7406  */
7407     char_u *
7408 tv_get_string_chk(typval_T *varp)
7409 {
7410     static char_u   mybuf[NUMBUFLEN];
7411 
7412     return tv_get_string_buf_chk(varp, mybuf);
7413 }
7414 
7415     char_u *
7416 tv_get_string_buf_chk(typval_T *varp, char_u *buf)
7417 {
7418     switch (varp->v_type)
7419     {
7420 	case VAR_NUMBER:
7421 	    vim_snprintf((char *)buf, NUMBUFLEN, "%lld",
7422 					    (long_long_T)varp->vval.v_number);
7423 	    return buf;
7424 	case VAR_FUNC:
7425 	case VAR_PARTIAL:
7426 	    emsg(_("E729: using Funcref as a String"));
7427 	    break;
7428 	case VAR_LIST:
7429 	    emsg(_("E730: using List as a String"));
7430 	    break;
7431 	case VAR_DICT:
7432 	    emsg(_("E731: using Dictionary as a String"));
7433 	    break;
7434 	case VAR_FLOAT:
7435 #ifdef FEAT_FLOAT
7436 	    emsg(_(e_float_as_string));
7437 	    break;
7438 #endif
7439 	case VAR_STRING:
7440 	    if (varp->vval.v_string != NULL)
7441 		return varp->vval.v_string;
7442 	    return (char_u *)"";
7443 	case VAR_SPECIAL:
7444 	    STRCPY(buf, get_var_special_name(varp->vval.v_number));
7445 	    return buf;
7446         case VAR_BLOB:
7447 	    emsg(_("E976: using Blob as a String"));
7448 	    break;
7449 	case VAR_JOB:
7450 #ifdef FEAT_JOB_CHANNEL
7451 	    {
7452 		job_T *job = varp->vval.v_job;
7453 		char  *status;
7454 
7455 		if (job == NULL)
7456 		    return (char_u *)"no process";
7457 		status = job->jv_status == JOB_FAILED ? "fail"
7458 				: job->jv_status >= JOB_ENDED ? "dead"
7459 				: "run";
7460 # ifdef UNIX
7461 		vim_snprintf((char *)buf, NUMBUFLEN,
7462 			    "process %ld %s", (long)job->jv_pid, status);
7463 # elif defined(MSWIN)
7464 		vim_snprintf((char *)buf, NUMBUFLEN,
7465 			    "process %ld %s",
7466 			    (long)job->jv_proc_info.dwProcessId,
7467 			    status);
7468 # else
7469 		/* fall-back */
7470 		vim_snprintf((char *)buf, NUMBUFLEN, "process ? %s", status);
7471 # endif
7472 		return buf;
7473 	    }
7474 #endif
7475 	    break;
7476 	case VAR_CHANNEL:
7477 #ifdef FEAT_JOB_CHANNEL
7478 	    {
7479 		channel_T *channel = varp->vval.v_channel;
7480 		char      *status = channel_status(channel, -1);
7481 
7482 		if (channel == NULL)
7483 		    vim_snprintf((char *)buf, NUMBUFLEN, "channel %s", status);
7484 		else
7485 		    vim_snprintf((char *)buf, NUMBUFLEN,
7486 				     "channel %d %s", channel->ch_id, status);
7487 		return buf;
7488 	    }
7489 #endif
7490 	    break;
7491 	case VAR_UNKNOWN:
7492 	    emsg(_("E908: using an invalid value as a String"));
7493 	    break;
7494     }
7495     return NULL;
7496 }
7497 
7498 /*
7499  * Turn a typeval into a string.  Similar to tv_get_string_buf() but uses
7500  * string() on Dict, List, etc.
7501  */
7502     char_u *
7503 tv_stringify(typval_T *varp, char_u *buf)
7504 {
7505     if (varp->v_type == VAR_LIST
7506 	    || varp->v_type == VAR_DICT
7507 	    || varp->v_type == VAR_FUNC
7508 	    || varp->v_type == VAR_PARTIAL
7509 	    || varp->v_type == VAR_FLOAT)
7510     {
7511 	typval_T tmp;
7512 
7513 	f_string(varp, &tmp);
7514 	tv_get_string_buf(&tmp, buf);
7515 	clear_tv(varp);
7516 	*varp = tmp;
7517 	return tmp.vval.v_string;
7518     }
7519     return tv_get_string_buf(varp, buf);
7520 }
7521 
7522 /*
7523  * Find variable "name" in the list of variables.
7524  * Return a pointer to it if found, NULL if not found.
7525  * Careful: "a:0" variables don't have a name.
7526  * When "htp" is not NULL we are writing to the variable, set "htp" to the
7527  * hashtab_T used.
7528  */
7529     dictitem_T *
7530 find_var(char_u *name, hashtab_T **htp, int no_autoload)
7531 {
7532     char_u	*varname;
7533     hashtab_T	*ht;
7534     dictitem_T	*ret = NULL;
7535 
7536     ht = find_var_ht(name, &varname);
7537     if (htp != NULL)
7538 	*htp = ht;
7539     if (ht == NULL)
7540 	return NULL;
7541     ret = find_var_in_ht(ht, *name, varname, no_autoload || htp != NULL);
7542     if (ret != NULL)
7543 	return ret;
7544 
7545     /* Search in parent scope for lambda */
7546     return find_var_in_scoped_ht(name, no_autoload || htp != NULL);
7547 }
7548 
7549 /*
7550  * Find variable "varname" in hashtab "ht" with name "htname".
7551  * Returns NULL if not found.
7552  */
7553     dictitem_T *
7554 find_var_in_ht(
7555     hashtab_T	*ht,
7556     int		htname,
7557     char_u	*varname,
7558     int		no_autoload)
7559 {
7560     hashitem_T	*hi;
7561 
7562     if (*varname == NUL)
7563     {
7564 	/* Must be something like "s:", otherwise "ht" would be NULL. */
7565 	switch (htname)
7566 	{
7567 	    case 's': return &SCRIPT_SV(current_sctx.sc_sid)->sv_var;
7568 	    case 'g': return &globvars_var;
7569 	    case 'v': return &vimvars_var;
7570 	    case 'b': return &curbuf->b_bufvar;
7571 	    case 'w': return &curwin->w_winvar;
7572 	    case 't': return &curtab->tp_winvar;
7573 	    case 'l': return get_funccal_local_var();
7574 	    case 'a': return get_funccal_args_var();
7575 	}
7576 	return NULL;
7577     }
7578 
7579     hi = hash_find(ht, varname);
7580     if (HASHITEM_EMPTY(hi))
7581     {
7582 	/* For global variables we may try auto-loading the script.  If it
7583 	 * worked find the variable again.  Don't auto-load a script if it was
7584 	 * loaded already, otherwise it would be loaded every time when
7585 	 * checking if a function name is a Funcref variable. */
7586 	if (ht == &globvarht && !no_autoload)
7587 	{
7588 	    /* Note: script_autoload() may make "hi" invalid. It must either
7589 	     * be obtained again or not used. */
7590 	    if (!script_autoload(varname, FALSE) || aborting())
7591 		return NULL;
7592 	    hi = hash_find(ht, varname);
7593 	}
7594 	if (HASHITEM_EMPTY(hi))
7595 	    return NULL;
7596     }
7597     return HI2DI(hi);
7598 }
7599 
7600 /*
7601  * Find the hashtab used for a variable name.
7602  * Return NULL if the name is not valid.
7603  * Set "varname" to the start of name without ':'.
7604  */
7605     hashtab_T *
7606 find_var_ht(char_u *name, char_u **varname)
7607 {
7608     hashitem_T	*hi;
7609     hashtab_T	*ht;
7610 
7611     if (name[0] == NUL)
7612 	return NULL;
7613     if (name[1] != ':')
7614     {
7615 	/* The name must not start with a colon or #. */
7616 	if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
7617 	    return NULL;
7618 	*varname = name;
7619 
7620 	/* "version" is "v:version" in all scopes */
7621 	hi = hash_find(&compat_hashtab, name);
7622 	if (!HASHITEM_EMPTY(hi))
7623 	    return &compat_hashtab;
7624 
7625 	ht = get_funccal_local_ht();
7626 	if (ht == NULL)
7627 	    return &globvarht;			/* global variable */
7628 	return ht;				/* local variable */
7629     }
7630     *varname = name + 2;
7631     if (*name == 'g')				/* global variable */
7632 	return &globvarht;
7633     /* There must be no ':' or '#' in the rest of the name, unless g: is used
7634      */
7635     if (vim_strchr(name + 2, ':') != NULL
7636 			       || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
7637 	return NULL;
7638     if (*name == 'b')				/* buffer variable */
7639 	return &curbuf->b_vars->dv_hashtab;
7640     if (*name == 'w')				/* window variable */
7641 	return &curwin->w_vars->dv_hashtab;
7642     if (*name == 't')				/* tab page variable */
7643 	return &curtab->tp_vars->dv_hashtab;
7644     if (*name == 'v')				/* v: variable */
7645 	return &vimvarht;
7646     if (*name == 'a')				/* a: function argument */
7647 	return get_funccal_args_ht();
7648     if (*name == 'l')				/* l: local function variable */
7649 	return get_funccal_local_ht();
7650     if (*name == 's'				/* script variable */
7651 	    && current_sctx.sc_sid > 0 && current_sctx.sc_sid <= ga_scripts.ga_len)
7652 	return &SCRIPT_VARS(current_sctx.sc_sid);
7653     return NULL;
7654 }
7655 
7656 /*
7657  * Get the string value of a (global/local) variable.
7658  * Note: see tv_get_string() for how long the pointer remains valid.
7659  * Returns NULL when it doesn't exist.
7660  */
7661     char_u *
7662 get_var_value(char_u *name)
7663 {
7664     dictitem_T	*v;
7665 
7666     v = find_var(name, NULL, FALSE);
7667     if (v == NULL)
7668 	return NULL;
7669     return tv_get_string(&v->di_tv);
7670 }
7671 
7672 /*
7673  * Allocate a new hashtab for a sourced script.  It will be used while
7674  * sourcing this script and when executing functions defined in the script.
7675  */
7676     void
7677 new_script_vars(scid_T id)
7678 {
7679     int		i;
7680     hashtab_T	*ht;
7681     scriptvar_T *sv;
7682 
7683     if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
7684     {
7685 	/* Re-allocating ga_data means that an ht_array pointing to
7686 	 * ht_smallarray becomes invalid.  We can recognize this: ht_mask is
7687 	 * at its init value.  Also reset "v_dict", it's always the same. */
7688 	for (i = 1; i <= ga_scripts.ga_len; ++i)
7689 	{
7690 	    ht = &SCRIPT_VARS(i);
7691 	    if (ht->ht_mask == HT_INIT_SIZE - 1)
7692 		ht->ht_array = ht->ht_smallarray;
7693 	    sv = SCRIPT_SV(i);
7694 	    sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
7695 	}
7696 
7697 	while (ga_scripts.ga_len < id)
7698 	{
7699 	    sv = SCRIPT_SV(ga_scripts.ga_len + 1) =
7700 		(scriptvar_T *)alloc_clear(sizeof(scriptvar_T));
7701 	    init_var_dict(&sv->sv_dict, &sv->sv_var, VAR_SCOPE);
7702 	    ++ga_scripts.ga_len;
7703 	}
7704     }
7705 }
7706 
7707 /*
7708  * Initialize dictionary "dict" as a scope and set variable "dict_var" to
7709  * point to it.
7710  */
7711     void
7712 init_var_dict(dict_T *dict, dictitem_T *dict_var, int scope)
7713 {
7714     hash_init(&dict->dv_hashtab);
7715     dict->dv_lock = 0;
7716     dict->dv_scope = scope;
7717     dict->dv_refcount = DO_NOT_FREE_CNT;
7718     dict->dv_copyID = 0;
7719     dict_var->di_tv.vval.v_dict = dict;
7720     dict_var->di_tv.v_type = VAR_DICT;
7721     dict_var->di_tv.v_lock = VAR_FIXED;
7722     dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
7723     dict_var->di_key[0] = NUL;
7724 }
7725 
7726 /*
7727  * Unreference a dictionary initialized by init_var_dict().
7728  */
7729     void
7730 unref_var_dict(dict_T *dict)
7731 {
7732     /* Now the dict needs to be freed if no one else is using it, go back to
7733      * normal reference counting. */
7734     dict->dv_refcount -= DO_NOT_FREE_CNT - 1;
7735     dict_unref(dict);
7736 }
7737 
7738 /*
7739  * Clean up a list of internal variables.
7740  * Frees all allocated variables and the value they contain.
7741  * Clears hashtab "ht", does not free it.
7742  */
7743     void
7744 vars_clear(hashtab_T *ht)
7745 {
7746     vars_clear_ext(ht, TRUE);
7747 }
7748 
7749 /*
7750  * Like vars_clear(), but only free the value if "free_val" is TRUE.
7751  */
7752     void
7753 vars_clear_ext(hashtab_T *ht, int free_val)
7754 {
7755     int		todo;
7756     hashitem_T	*hi;
7757     dictitem_T	*v;
7758 
7759     hash_lock(ht);
7760     todo = (int)ht->ht_used;
7761     for (hi = ht->ht_array; todo > 0; ++hi)
7762     {
7763 	if (!HASHITEM_EMPTY(hi))
7764 	{
7765 	    --todo;
7766 
7767 	    /* Free the variable.  Don't remove it from the hashtab,
7768 	     * ht_array might change then.  hash_clear() takes care of it
7769 	     * later. */
7770 	    v = HI2DI(hi);
7771 	    if (free_val)
7772 		clear_tv(&v->di_tv);
7773 	    if (v->di_flags & DI_FLAGS_ALLOC)
7774 		vim_free(v);
7775 	}
7776     }
7777     hash_clear(ht);
7778     ht->ht_used = 0;
7779 }
7780 
7781 /*
7782  * Delete a variable from hashtab "ht" at item "hi".
7783  * Clear the variable value and free the dictitem.
7784  */
7785     static void
7786 delete_var(hashtab_T *ht, hashitem_T *hi)
7787 {
7788     dictitem_T	*di = HI2DI(hi);
7789 
7790     hash_remove(ht, hi);
7791     clear_tv(&di->di_tv);
7792     vim_free(di);
7793 }
7794 
7795 /*
7796  * List the value of one internal variable.
7797  */
7798     static void
7799 list_one_var(dictitem_T *v, char *prefix, int *first)
7800 {
7801     char_u	*tofree;
7802     char_u	*s;
7803     char_u	numbuf[NUMBUFLEN];
7804 
7805     s = echo_string(&v->di_tv, &tofree, numbuf, get_copyID());
7806     list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
7807 					 s == NULL ? (char_u *)"" : s, first);
7808     vim_free(tofree);
7809 }
7810 
7811     static void
7812 list_one_var_a(
7813     char	*prefix,
7814     char_u	*name,
7815     int		type,
7816     char_u	*string,
7817     int		*first)  /* when TRUE clear rest of screen and set to FALSE */
7818 {
7819     /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
7820     msg_start();
7821     msg_puts(prefix);
7822     if (name != NULL)	/* "a:" vars don't have a name stored */
7823 	msg_puts((char *)name);
7824     msg_putchar(' ');
7825     msg_advance(22);
7826     if (type == VAR_NUMBER)
7827 	msg_putchar('#');
7828     else if (type == VAR_FUNC || type == VAR_PARTIAL)
7829 	msg_putchar('*');
7830     else if (type == VAR_LIST)
7831     {
7832 	msg_putchar('[');
7833 	if (*string == '[')
7834 	    ++string;
7835     }
7836     else if (type == VAR_DICT)
7837     {
7838 	msg_putchar('{');
7839 	if (*string == '{')
7840 	    ++string;
7841     }
7842     else
7843 	msg_putchar(' ');
7844 
7845     msg_outtrans(string);
7846 
7847     if (type == VAR_FUNC || type == VAR_PARTIAL)
7848 	msg_puts("()");
7849     if (*first)
7850     {
7851 	msg_clr_eos();
7852 	*first = FALSE;
7853     }
7854 }
7855 
7856 /*
7857  * Set variable "name" to value in "tv".
7858  * If the variable already exists, the value is updated.
7859  * Otherwise the variable is created.
7860  */
7861     void
7862 set_var(
7863     char_u	*name,
7864     typval_T	*tv,
7865     int		copy)	    /* make copy of value in "tv" */
7866 {
7867     dictitem_T	*v;
7868     char_u	*varname;
7869     hashtab_T	*ht;
7870 
7871     ht = find_var_ht(name, &varname);
7872     if (ht == NULL || *varname == NUL)
7873     {
7874 	semsg(_(e_illvar), name);
7875 	return;
7876     }
7877     v = find_var_in_ht(ht, 0, varname, TRUE);
7878 
7879     /* Search in parent scope which is possible to reference from lambda */
7880     if (v == NULL)
7881 	v = find_var_in_scoped_ht(name, TRUE);
7882 
7883     if ((tv->v_type == VAR_FUNC || tv->v_type == VAR_PARTIAL)
7884 				      && var_check_func_name(name, v == NULL))
7885 	return;
7886 
7887     if (v != NULL)
7888     {
7889 	/* existing variable, need to clear the value */
7890 	if (var_check_ro(v->di_flags, name, FALSE)
7891 			      || var_check_lock(v->di_tv.v_lock, name, FALSE))
7892 	    return;
7893 
7894 	/*
7895 	 * Handle setting internal v: variables separately where needed to
7896 	 * prevent changing the type.
7897 	 */
7898 	if (ht == &vimvarht)
7899 	{
7900 	    if (v->di_tv.v_type == VAR_STRING)
7901 	    {
7902 		VIM_CLEAR(v->di_tv.vval.v_string);
7903 		if (copy || tv->v_type != VAR_STRING)
7904 		{
7905 		    char_u *val = tv_get_string(tv);
7906 
7907 		    // Careful: when assigning to v:errmsg and tv_get_string()
7908 		    // causes an error message the variable will alrady be set.
7909 		    if (v->di_tv.vval.v_string == NULL)
7910 			v->di_tv.vval.v_string = vim_strsave(val);
7911 		}
7912 		else
7913 		{
7914 		    /* Take over the string to avoid an extra alloc/free. */
7915 		    v->di_tv.vval.v_string = tv->vval.v_string;
7916 		    tv->vval.v_string = NULL;
7917 		}
7918 		return;
7919 	    }
7920 	    else if (v->di_tv.v_type == VAR_NUMBER)
7921 	    {
7922 		v->di_tv.vval.v_number = tv_get_number(tv);
7923 		if (STRCMP(varname, "searchforward") == 0)
7924 		    set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
7925 #ifdef FEAT_SEARCH_EXTRA
7926 		else if (STRCMP(varname, "hlsearch") == 0)
7927 		{
7928 		    no_hlsearch = !v->di_tv.vval.v_number;
7929 		    redraw_all_later(SOME_VALID);
7930 		}
7931 #endif
7932 		return;
7933 	    }
7934 	    else if (v->di_tv.v_type != tv->v_type)
7935 	    {
7936 		semsg(_("E963: setting %s to value with wrong type"), name);
7937 		return;
7938 	    }
7939 	}
7940 
7941 	clear_tv(&v->di_tv);
7942     }
7943     else		    /* add a new variable */
7944     {
7945 	// Can't add "v:" or "a:" variable.
7946 	if (ht == &vimvarht || ht == get_funccal_args_ht())
7947 	{
7948 	    semsg(_(e_illvar), name);
7949 	    return;
7950 	}
7951 
7952 	// Make sure the variable name is valid.
7953 	if (!valid_varname(varname))
7954 	    return;
7955 
7956 	v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
7957 							  + STRLEN(varname)));
7958 	if (v == NULL)
7959 	    return;
7960 	STRCPY(v->di_key, varname);
7961 	if (hash_add(ht, DI2HIKEY(v)) == FAIL)
7962 	{
7963 	    vim_free(v);
7964 	    return;
7965 	}
7966 	v->di_flags = DI_FLAGS_ALLOC;
7967     }
7968 
7969     if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
7970 	copy_tv(tv, &v->di_tv);
7971     else
7972     {
7973 	v->di_tv = *tv;
7974 	v->di_tv.v_lock = 0;
7975 	init_tv(tv);
7976     }
7977 }
7978 
7979 /*
7980  * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
7981  * Also give an error message.
7982  */
7983     int
7984 var_check_ro(int flags, char_u *name, int use_gettext)
7985 {
7986     if (flags & DI_FLAGS_RO)
7987     {
7988 	semsg(_(e_readonlyvar), use_gettext ? (char_u *)_(name) : name);
7989 	return TRUE;
7990     }
7991     if ((flags & DI_FLAGS_RO_SBX) && sandbox)
7992     {
7993 	semsg(_(e_readonlysbx), use_gettext ? (char_u *)_(name) : name);
7994 	return TRUE;
7995     }
7996     return FALSE;
7997 }
7998 
7999 /*
8000  * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
8001  * Also give an error message.
8002  */
8003     int
8004 var_check_fixed(int flags, char_u *name, int use_gettext)
8005 {
8006     if (flags & DI_FLAGS_FIX)
8007     {
8008 	semsg(_("E795: Cannot delete variable %s"),
8009 				      use_gettext ? (char_u *)_(name) : name);
8010 	return TRUE;
8011     }
8012     return FALSE;
8013 }
8014 
8015 /*
8016  * Check if a funcref is assigned to a valid variable name.
8017  * Return TRUE and give an error if not.
8018  */
8019     int
8020 var_check_func_name(
8021     char_u *name,    /* points to start of variable name */
8022     int    new_var)  /* TRUE when creating the variable */
8023 {
8024     /* Allow for w: b: s: and t:. */
8025     if (!(vim_strchr((char_u *)"wbst", name[0]) != NULL && name[1] == ':')
8026 	    && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
8027 						     ? name[2] : name[0]))
8028     {
8029 	semsg(_("E704: Funcref variable name must start with a capital: %s"),
8030 									name);
8031 	return TRUE;
8032     }
8033     /* Don't allow hiding a function.  When "v" is not NULL we might be
8034      * assigning another function to the same var, the type is checked
8035      * below. */
8036     if (new_var && function_exists(name, FALSE))
8037     {
8038 	semsg(_("E705: Variable name conflicts with existing function: %s"),
8039 								    name);
8040 	return TRUE;
8041     }
8042     return FALSE;
8043 }
8044 
8045 /*
8046  * Return TRUE if "flags" indicates variable "name" is locked (immutable).
8047  * Also give an error message, using "name" or _("name") when use_gettext is
8048  * TRUE.
8049  */
8050     int
8051 var_check_lock(int lock, char_u *name, int use_gettext)
8052 {
8053     if (lock & VAR_LOCKED)
8054     {
8055 	semsg(_("E741: Value is locked: %s"),
8056 				name == NULL ? (char_u *)_("Unknown")
8057 					     : use_gettext ? (char_u *)_(name)
8058 					     : name);
8059 	return TRUE;
8060     }
8061     if (lock & VAR_FIXED)
8062     {
8063 	semsg(_("E742: Cannot change value of %s"),
8064 				name == NULL ? (char_u *)_("Unknown")
8065 					     : use_gettext ? (char_u *)_(name)
8066 					     : name);
8067 	return TRUE;
8068     }
8069     return FALSE;
8070 }
8071 
8072 /*
8073  * Return TRUE if typeval "tv" and its value are set to be locked (immutable).
8074  * Also give an error message, using "name" or _("name") when use_gettext is
8075  * TRUE.
8076  */
8077     static int
8078 tv_check_lock(typval_T *tv, char_u *name, int use_gettext)
8079 {
8080     int	lock = 0;
8081 
8082     switch (tv->v_type)
8083     {
8084 	case VAR_BLOB:
8085 	    if (tv->vval.v_blob != NULL)
8086 		lock = tv->vval.v_blob->bv_lock;
8087 	    break;
8088 	case VAR_LIST:
8089 	    if (tv->vval.v_list != NULL)
8090 		lock = tv->vval.v_list->lv_lock;
8091 	    break;
8092 	case VAR_DICT:
8093 	    if (tv->vval.v_dict != NULL)
8094 		lock = tv->vval.v_dict->dv_lock;
8095 	    break;
8096 	default:
8097 	    break;
8098     }
8099     return var_check_lock(tv->v_lock, name, use_gettext)
8100 		    || (lock != 0 && var_check_lock(lock, name, use_gettext));
8101 }
8102 
8103 /*
8104  * Check if a variable name is valid.
8105  * Return FALSE and give an error if not.
8106  */
8107     int
8108 valid_varname(char_u *varname)
8109 {
8110     char_u *p;
8111 
8112     for (p = varname; *p != NUL; ++p)
8113 	if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
8114 						   && *p != AUTOLOAD_CHAR)
8115 	{
8116 	    semsg(_(e_illvar), varname);
8117 	    return FALSE;
8118 	}
8119     return TRUE;
8120 }
8121 
8122 /*
8123  * Copy the values from typval_T "from" to typval_T "to".
8124  * When needed allocates string or increases reference count.
8125  * Does not make a copy of a list, blob or dict but copies the reference!
8126  * It is OK for "from" and "to" to point to the same item.  This is used to
8127  * make a copy later.
8128  */
8129     void
8130 copy_tv(typval_T *from, typval_T *to)
8131 {
8132     to->v_type = from->v_type;
8133     to->v_lock = 0;
8134     switch (from->v_type)
8135     {
8136 	case VAR_NUMBER:
8137 	case VAR_SPECIAL:
8138 	    to->vval.v_number = from->vval.v_number;
8139 	    break;
8140 	case VAR_FLOAT:
8141 #ifdef FEAT_FLOAT
8142 	    to->vval.v_float = from->vval.v_float;
8143 	    break;
8144 #endif
8145 	case VAR_JOB:
8146 #ifdef FEAT_JOB_CHANNEL
8147 	    to->vval.v_job = from->vval.v_job;
8148 	    if (to->vval.v_job != NULL)
8149 		++to->vval.v_job->jv_refcount;
8150 	    break;
8151 #endif
8152 	case VAR_CHANNEL:
8153 #ifdef FEAT_JOB_CHANNEL
8154 	    to->vval.v_channel = from->vval.v_channel;
8155 	    if (to->vval.v_channel != NULL)
8156 		++to->vval.v_channel->ch_refcount;
8157 	    break;
8158 #endif
8159 	case VAR_STRING:
8160 	case VAR_FUNC:
8161 	    if (from->vval.v_string == NULL)
8162 		to->vval.v_string = NULL;
8163 	    else
8164 	    {
8165 		to->vval.v_string = vim_strsave(from->vval.v_string);
8166 		if (from->v_type == VAR_FUNC)
8167 		    func_ref(to->vval.v_string);
8168 	    }
8169 	    break;
8170 	case VAR_PARTIAL:
8171 	    if (from->vval.v_partial == NULL)
8172 		to->vval.v_partial = NULL;
8173 	    else
8174 	    {
8175 		to->vval.v_partial = from->vval.v_partial;
8176 		++to->vval.v_partial->pt_refcount;
8177 	    }
8178 	    break;
8179 	case VAR_BLOB:
8180 	    if (from->vval.v_blob == NULL)
8181 		to->vval.v_blob = NULL;
8182 	    else
8183 	    {
8184 		to->vval.v_blob = from->vval.v_blob;
8185 		++to->vval.v_blob->bv_refcount;
8186 	    }
8187 	    break;
8188 	case VAR_LIST:
8189 	    if (from->vval.v_list == NULL)
8190 		to->vval.v_list = NULL;
8191 	    else
8192 	    {
8193 		to->vval.v_list = from->vval.v_list;
8194 		++to->vval.v_list->lv_refcount;
8195 	    }
8196 	    break;
8197 	case VAR_DICT:
8198 	    if (from->vval.v_dict == NULL)
8199 		to->vval.v_dict = NULL;
8200 	    else
8201 	    {
8202 		to->vval.v_dict = from->vval.v_dict;
8203 		++to->vval.v_dict->dv_refcount;
8204 	    }
8205 	    break;
8206 	case VAR_UNKNOWN:
8207 	    internal_error("copy_tv(UNKNOWN)");
8208 	    break;
8209     }
8210 }
8211 
8212 /*
8213  * Make a copy of an item.
8214  * Lists and Dictionaries are also copied.  A deep copy if "deep" is set.
8215  * For deepcopy() "copyID" is zero for a full copy or the ID for when a
8216  * reference to an already copied list/dict can be used.
8217  * Returns FAIL or OK.
8218  */
8219     int
8220 item_copy(
8221     typval_T	*from,
8222     typval_T	*to,
8223     int		deep,
8224     int		copyID)
8225 {
8226     static int	recurse = 0;
8227     int		ret = OK;
8228 
8229     if (recurse >= DICT_MAXNEST)
8230     {
8231 	emsg(_("E698: variable nested too deep for making a copy"));
8232 	return FAIL;
8233     }
8234     ++recurse;
8235 
8236     switch (from->v_type)
8237     {
8238 	case VAR_NUMBER:
8239 	case VAR_FLOAT:
8240 	case VAR_STRING:
8241 	case VAR_FUNC:
8242 	case VAR_PARTIAL:
8243 	case VAR_SPECIAL:
8244 	case VAR_JOB:
8245 	case VAR_CHANNEL:
8246 	    copy_tv(from, to);
8247 	    break;
8248 	case VAR_LIST:
8249 	    to->v_type = VAR_LIST;
8250 	    to->v_lock = 0;
8251 	    if (from->vval.v_list == NULL)
8252 		to->vval.v_list = NULL;
8253 	    else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
8254 	    {
8255 		/* use the copy made earlier */
8256 		to->vval.v_list = from->vval.v_list->lv_copylist;
8257 		++to->vval.v_list->lv_refcount;
8258 	    }
8259 	    else
8260 		to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
8261 	    if (to->vval.v_list == NULL)
8262 		ret = FAIL;
8263 	    break;
8264 	case VAR_BLOB:
8265 	    ret = blob_copy(from, to);
8266 	    break;
8267 	case VAR_DICT:
8268 	    to->v_type = VAR_DICT;
8269 	    to->v_lock = 0;
8270 	    if (from->vval.v_dict == NULL)
8271 		to->vval.v_dict = NULL;
8272 	    else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
8273 	    {
8274 		/* use the copy made earlier */
8275 		to->vval.v_dict = from->vval.v_dict->dv_copydict;
8276 		++to->vval.v_dict->dv_refcount;
8277 	    }
8278 	    else
8279 		to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
8280 	    if (to->vval.v_dict == NULL)
8281 		ret = FAIL;
8282 	    break;
8283 	case VAR_UNKNOWN:
8284 	    internal_error("item_copy(UNKNOWN)");
8285 	    ret = FAIL;
8286     }
8287     --recurse;
8288     return ret;
8289 }
8290 
8291 /*
8292  * This function is used by f_input() and f_inputdialog() functions. The third
8293  * argument to f_input() specifies the type of completion to use at the
8294  * prompt. The third argument to f_inputdialog() specifies the value to return
8295  * when the user cancels the prompt.
8296  */
8297     void
8298 get_user_input(
8299     typval_T	*argvars,
8300     typval_T	*rettv,
8301     int		inputdialog,
8302     int		secret)
8303 {
8304     char_u	*prompt = tv_get_string_chk(&argvars[0]);
8305     char_u	*p = NULL;
8306     int		c;
8307     char_u	buf[NUMBUFLEN];
8308     int		cmd_silent_save = cmd_silent;
8309     char_u	*defstr = (char_u *)"";
8310     int		xp_type = EXPAND_NOTHING;
8311     char_u	*xp_arg = NULL;
8312 
8313     rettv->v_type = VAR_STRING;
8314     rettv->vval.v_string = NULL;
8315 
8316 #ifdef NO_CONSOLE_INPUT
8317     /* While starting up, there is no place to enter text. When running tests
8318      * with --not-a-term we assume feedkeys() will be used. */
8319     if (no_console_input() && !is_not_a_term())
8320 	return;
8321 #endif
8322 
8323     cmd_silent = FALSE;		/* Want to see the prompt. */
8324     if (prompt != NULL)
8325     {
8326 	/* Only the part of the message after the last NL is considered as
8327 	 * prompt for the command line */
8328 	p = vim_strrchr(prompt, '\n');
8329 	if (p == NULL)
8330 	    p = prompt;
8331 	else
8332 	{
8333 	    ++p;
8334 	    c = *p;
8335 	    *p = NUL;
8336 	    msg_start();
8337 	    msg_clr_eos();
8338 	    msg_puts_attr((char *)prompt, echo_attr);
8339 	    msg_didout = FALSE;
8340 	    msg_starthere();
8341 	    *p = c;
8342 	}
8343 	cmdline_row = msg_row;
8344 
8345 	if (argvars[1].v_type != VAR_UNKNOWN)
8346 	{
8347 	    defstr = tv_get_string_buf_chk(&argvars[1], buf);
8348 	    if (defstr != NULL)
8349 		stuffReadbuffSpec(defstr);
8350 
8351 	    if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
8352 	    {
8353 		char_u	*xp_name;
8354 		int	xp_namelen;
8355 		long	argt;
8356 
8357 		/* input() with a third argument: completion */
8358 		rettv->vval.v_string = NULL;
8359 
8360 		xp_name = tv_get_string_buf_chk(&argvars[2], buf);
8361 		if (xp_name == NULL)
8362 		    return;
8363 
8364 		xp_namelen = (int)STRLEN(xp_name);
8365 
8366 		if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
8367 							     &xp_arg) == FAIL)
8368 		    return;
8369 	    }
8370 	}
8371 
8372 	if (defstr != NULL)
8373 	{
8374 	    int save_ex_normal_busy = ex_normal_busy;
8375 
8376 	    ex_normal_busy = 0;
8377 	    rettv->vval.v_string =
8378 		getcmdline_prompt(secret ? NUL : '@', p, echo_attr,
8379 							      xp_type, xp_arg);
8380 	    ex_normal_busy = save_ex_normal_busy;
8381 	}
8382 	if (inputdialog && rettv->vval.v_string == NULL
8383 		&& argvars[1].v_type != VAR_UNKNOWN
8384 		&& argvars[2].v_type != VAR_UNKNOWN)
8385 	    rettv->vval.v_string = vim_strsave(tv_get_string_buf(
8386 							   &argvars[2], buf));
8387 
8388 	vim_free(xp_arg);
8389 
8390 	/* since the user typed this, no need to wait for return */
8391 	need_wait_return = FALSE;
8392 	msg_didout = FALSE;
8393     }
8394     cmd_silent = cmd_silent_save;
8395 }
8396 
8397 /*
8398  * ":echo expr1 ..."	print each argument separated with a space, add a
8399  *			newline at the end.
8400  * ":echon expr1 ..."	print each argument plain.
8401  */
8402     void
8403 ex_echo(exarg_T *eap)
8404 {
8405     char_u	*arg = eap->arg;
8406     typval_T	rettv;
8407     char_u	*tofree;
8408     char_u	*p;
8409     int		needclr = TRUE;
8410     int		atstart = TRUE;
8411     char_u	numbuf[NUMBUFLEN];
8412     int		did_emsg_before = did_emsg;
8413     int		called_emsg_before = called_emsg;
8414 
8415     if (eap->skip)
8416 	++emsg_skip;
8417     while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
8418     {
8419 	/* If eval1() causes an error message the text from the command may
8420 	 * still need to be cleared. E.g., "echo 22,44". */
8421 	need_clr_eos = needclr;
8422 
8423 	p = arg;
8424 	if (eval1(&arg, &rettv, !eap->skip) == FAIL)
8425 	{
8426 	    /*
8427 	     * Report the invalid expression unless the expression evaluation
8428 	     * has been cancelled due to an aborting error, an interrupt, or an
8429 	     * exception.
8430 	     */
8431 	    if (!aborting() && did_emsg == did_emsg_before
8432 					  && called_emsg == called_emsg_before)
8433 		semsg(_(e_invexpr2), p);
8434 	    need_clr_eos = FALSE;
8435 	    break;
8436 	}
8437 	need_clr_eos = FALSE;
8438 
8439 	if (!eap->skip)
8440 	{
8441 	    if (atstart)
8442 	    {
8443 		atstart = FALSE;
8444 		/* Call msg_start() after eval1(), evaluating the expression
8445 		 * may cause a message to appear. */
8446 		if (eap->cmdidx == CMD_echo)
8447 		{
8448 		    /* Mark the saved text as finishing the line, so that what
8449 		     * follows is displayed on a new line when scrolling back
8450 		     * at the more prompt. */
8451 		    msg_sb_eol();
8452 		    msg_start();
8453 		}
8454 	    }
8455 	    else if (eap->cmdidx == CMD_echo)
8456 		msg_puts_attr(" ", echo_attr);
8457 	    p = echo_string(&rettv, &tofree, numbuf, get_copyID());
8458 	    if (p != NULL)
8459 		for ( ; *p != NUL && !got_int; ++p)
8460 		{
8461 		    if (*p == '\n' || *p == '\r' || *p == TAB)
8462 		    {
8463 			if (*p != TAB && needclr)
8464 			{
8465 			    /* remove any text still there from the command */
8466 			    msg_clr_eos();
8467 			    needclr = FALSE;
8468 			}
8469 			msg_putchar_attr(*p, echo_attr);
8470 		    }
8471 		    else
8472 		    {
8473 			if (has_mbyte)
8474 			{
8475 			    int i = (*mb_ptr2len)(p);
8476 
8477 			    (void)msg_outtrans_len_attr(p, i, echo_attr);
8478 			    p += i - 1;
8479 			}
8480 			else
8481 			    (void)msg_outtrans_len_attr(p, 1, echo_attr);
8482 		    }
8483 		}
8484 	    vim_free(tofree);
8485 	}
8486 	clear_tv(&rettv);
8487 	arg = skipwhite(arg);
8488     }
8489     eap->nextcmd = check_nextcmd(arg);
8490 
8491     if (eap->skip)
8492 	--emsg_skip;
8493     else
8494     {
8495 	/* remove text that may still be there from the command */
8496 	if (needclr)
8497 	    msg_clr_eos();
8498 	if (eap->cmdidx == CMD_echo)
8499 	    msg_end();
8500     }
8501 }
8502 
8503 /*
8504  * ":echohl {name}".
8505  */
8506     void
8507 ex_echohl(exarg_T *eap)
8508 {
8509     echo_attr = syn_name2attr(eap->arg);
8510 }
8511 
8512 /*
8513  * ":execute expr1 ..."	execute the result of an expression.
8514  * ":echomsg expr1 ..."	Print a message
8515  * ":echoerr expr1 ..."	Print an error
8516  * Each gets spaces around each argument and a newline at the end for
8517  * echo commands
8518  */
8519     void
8520 ex_execute(exarg_T *eap)
8521 {
8522     char_u	*arg = eap->arg;
8523     typval_T	rettv;
8524     int		ret = OK;
8525     char_u	*p;
8526     garray_T	ga;
8527     int		len;
8528     int		save_did_emsg = did_emsg;
8529 
8530     ga_init2(&ga, 1, 80);
8531 
8532     if (eap->skip)
8533 	++emsg_skip;
8534     while (*arg != NUL && *arg != '|' && *arg != '\n')
8535     {
8536 	p = arg;
8537 	ret = eval1_emsg(&arg, &rettv, !eap->skip);
8538 	if (ret == FAIL)
8539 	    break;
8540 
8541 	if (!eap->skip)
8542 	{
8543 	    char_u   buf[NUMBUFLEN];
8544 
8545 	    if (eap->cmdidx == CMD_execute)
8546 		p = tv_get_string_buf(&rettv, buf);
8547 	    else
8548 		p = tv_stringify(&rettv, buf);
8549 	    len = (int)STRLEN(p);
8550 	    if (ga_grow(&ga, len + 2) == FAIL)
8551 	    {
8552 		clear_tv(&rettv);
8553 		ret = FAIL;
8554 		break;
8555 	    }
8556 	    if (ga.ga_len)
8557 		((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
8558 	    STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
8559 	    ga.ga_len += len;
8560 	}
8561 
8562 	clear_tv(&rettv);
8563 	arg = skipwhite(arg);
8564     }
8565 
8566     if (ret != FAIL && ga.ga_data != NULL)
8567     {
8568 	if (eap->cmdidx == CMD_echomsg || eap->cmdidx == CMD_echoerr)
8569 	{
8570 	    /* Mark the already saved text as finishing the line, so that what
8571 	     * follows is displayed on a new line when scrolling back at the
8572 	     * more prompt. */
8573 	    msg_sb_eol();
8574 	}
8575 
8576 	if (eap->cmdidx == CMD_echomsg)
8577 	{
8578 	    msg_attr(ga.ga_data, echo_attr);
8579 	    out_flush();
8580 	}
8581 	else if (eap->cmdidx == CMD_echoerr)
8582 	{
8583 	    /* We don't want to abort following commands, restore did_emsg. */
8584 	    save_did_emsg = did_emsg;
8585 	    emsg(ga.ga_data);
8586 	    if (!force_abort)
8587 		did_emsg = save_did_emsg;
8588 	}
8589 	else if (eap->cmdidx == CMD_execute)
8590 	    do_cmdline((char_u *)ga.ga_data,
8591 		       eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
8592     }
8593 
8594     ga_clear(&ga);
8595 
8596     if (eap->skip)
8597 	--emsg_skip;
8598 
8599     eap->nextcmd = check_nextcmd(arg);
8600 }
8601 
8602 /*
8603  * Find window specified by "vp" in tabpage "tp".
8604  */
8605     win_T *
8606 find_win_by_nr(
8607     typval_T	*vp,
8608     tabpage_T	*tp)	/* NULL for current tab page */
8609 {
8610     win_T	*wp;
8611     int		nr = (int)tv_get_number_chk(vp, NULL);
8612 
8613     if (nr < 0)
8614 	return NULL;
8615     if (nr == 0)
8616 	return curwin;
8617 
8618     FOR_ALL_WINDOWS_IN_TAB(tp, wp)
8619     {
8620 	if (nr >= LOWEST_WIN_ID)
8621 	{
8622 	    if (wp->w_id == nr)
8623 		return wp;
8624 	}
8625 	else if (--nr <= 0)
8626 	    break;
8627     }
8628     if (nr >= LOWEST_WIN_ID)
8629 	return NULL;
8630     return wp;
8631 }
8632 
8633 /*
8634  * Find a window: When using a Window ID in any tab page, when using a number
8635  * in the current tab page.
8636  */
8637     win_T *
8638 find_win_by_nr_or_id(typval_T *vp)
8639 {
8640     int	nr = (int)tv_get_number_chk(vp, NULL);
8641 
8642     if (nr >= LOWEST_WIN_ID)
8643 	return win_id2wp(tv_get_number(vp));
8644     return find_win_by_nr(vp, NULL);
8645 }
8646 
8647 /*
8648  * Find window specified by "wvp" in tabpage "tvp".
8649  */
8650     win_T *
8651 find_tabwin(
8652     typval_T	*wvp,	/* VAR_UNKNOWN for current window */
8653     typval_T	*tvp)	/* VAR_UNKNOWN for current tab page */
8654 {
8655     win_T	*wp = NULL;
8656     tabpage_T	*tp = NULL;
8657     long	n;
8658 
8659     if (wvp->v_type != VAR_UNKNOWN)
8660     {
8661 	if (tvp->v_type != VAR_UNKNOWN)
8662 	{
8663 	    n = (long)tv_get_number(tvp);
8664 	    if (n >= 0)
8665 		tp = find_tabpage(n);
8666 	}
8667 	else
8668 	    tp = curtab;
8669 
8670 	if (tp != NULL)
8671 	    wp = find_win_by_nr(wvp, tp);
8672     }
8673     else
8674 	wp = curwin;
8675 
8676     return wp;
8677 }
8678 
8679 /*
8680  * getwinvar() and gettabwinvar()
8681  */
8682     void
8683 getwinvar(
8684     typval_T	*argvars,
8685     typval_T	*rettv,
8686     int		off)	    /* 1 for gettabwinvar() */
8687 {
8688     win_T	*win;
8689     char_u	*varname;
8690     dictitem_T	*v;
8691     tabpage_T	*tp = NULL;
8692     int		done = FALSE;
8693     win_T	*oldcurwin;
8694     tabpage_T	*oldtabpage;
8695     int		need_switch_win;
8696 
8697     if (off == 1)
8698 	tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
8699     else
8700 	tp = curtab;
8701     win = find_win_by_nr(&argvars[off], tp);
8702     varname = tv_get_string_chk(&argvars[off + 1]);
8703     ++emsg_off;
8704 
8705     rettv->v_type = VAR_STRING;
8706     rettv->vval.v_string = NULL;
8707 
8708     if (win != NULL && varname != NULL)
8709     {
8710 	/* Set curwin to be our win, temporarily.  Also set the tabpage,
8711 	 * otherwise the window is not valid. Only do this when needed,
8712 	 * autocommands get blocked. */
8713 	need_switch_win = !(tp == curtab && win == curwin);
8714 	if (!need_switch_win
8715 		  || switch_win(&oldcurwin, &oldtabpage, win, tp, TRUE) == OK)
8716 	{
8717 	    if (*varname == '&')
8718 	    {
8719 		if (varname[1] == NUL)
8720 		{
8721 		    /* get all window-local options in a dict */
8722 		    dict_T	*opts = get_winbuf_options(FALSE);
8723 
8724 		    if (opts != NULL)
8725 		    {
8726 			rettv_dict_set(rettv, opts);
8727 			done = TRUE;
8728 		    }
8729 		}
8730 		else if (get_option_tv(&varname, rettv, 1) == OK)
8731 		    /* window-local-option */
8732 		    done = TRUE;
8733 	    }
8734 	    else
8735 	    {
8736 		/* Look up the variable. */
8737 		/* Let getwinvar({nr}, "") return the "w:" dictionary. */
8738 		v = find_var_in_ht(&win->w_vars->dv_hashtab, 'w',
8739 							      varname, FALSE);
8740 		if (v != NULL)
8741 		{
8742 		    copy_tv(&v->di_tv, rettv);
8743 		    done = TRUE;
8744 		}
8745 	    }
8746 	}
8747 
8748 	if (need_switch_win)
8749 	    /* restore previous notion of curwin */
8750 	    restore_win(oldcurwin, oldtabpage, TRUE);
8751     }
8752 
8753     if (!done && argvars[off + 2].v_type != VAR_UNKNOWN)
8754 	/* use the default return value */
8755 	copy_tv(&argvars[off + 2], rettv);
8756 
8757     --emsg_off;
8758 }
8759 
8760 /*
8761  * "setwinvar()" and "settabwinvar()" functions
8762  */
8763     void
8764 setwinvar(typval_T *argvars, typval_T *rettv UNUSED, int off)
8765 {
8766     win_T	*win;
8767     win_T	*save_curwin;
8768     tabpage_T	*save_curtab;
8769     int		need_switch_win;
8770     char_u	*varname, *winvarname;
8771     typval_T	*varp;
8772     char_u	nbuf[NUMBUFLEN];
8773     tabpage_T	*tp = NULL;
8774 
8775     if (check_secure())
8776 	return;
8777 
8778     if (off == 1)
8779 	tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL));
8780     else
8781 	tp = curtab;
8782     win = find_win_by_nr(&argvars[off], tp);
8783     varname = tv_get_string_chk(&argvars[off + 1]);
8784     varp = &argvars[off + 2];
8785 
8786     if (win != NULL && varname != NULL && varp != NULL)
8787     {
8788 	need_switch_win = !(tp == curtab && win == curwin);
8789 	if (!need_switch_win
8790 	       || switch_win(&save_curwin, &save_curtab, win, tp, TRUE) == OK)
8791 	{
8792 	    if (*varname == '&')
8793 	    {
8794 		long	numval;
8795 		char_u	*strval;
8796 		int		error = FALSE;
8797 
8798 		++varname;
8799 		numval = (long)tv_get_number_chk(varp, &error);
8800 		strval = tv_get_string_buf_chk(varp, nbuf);
8801 		if (!error && strval != NULL)
8802 		    set_option_value(varname, numval, strval, OPT_LOCAL);
8803 	    }
8804 	    else
8805 	    {
8806 		winvarname = alloc((unsigned)STRLEN(varname) + 3);
8807 		if (winvarname != NULL)
8808 		{
8809 		    STRCPY(winvarname, "w:");
8810 		    STRCPY(winvarname + 2, varname);
8811 		    set_var(winvarname, varp, TRUE);
8812 		    vim_free(winvarname);
8813 		}
8814 	    }
8815 	}
8816 	if (need_switch_win)
8817 	    restore_win(save_curwin, save_curtab, TRUE);
8818     }
8819 }
8820 
8821 /*
8822  * Skip over the name of an option: "&option", "&g:option" or "&l:option".
8823  * "arg" points to the "&" or '+' when called, to "option" when returning.
8824  * Returns NULL when no option name found.  Otherwise pointer to the char
8825  * after the option name.
8826  */
8827     static char_u *
8828 find_option_end(char_u **arg, int *opt_flags)
8829 {
8830     char_u	*p = *arg;
8831 
8832     ++p;
8833     if (*p == 'g' && p[1] == ':')
8834     {
8835 	*opt_flags = OPT_GLOBAL;
8836 	p += 2;
8837     }
8838     else if (*p == 'l' && p[1] == ':')
8839     {
8840 	*opt_flags = OPT_LOCAL;
8841 	p += 2;
8842     }
8843     else
8844 	*opt_flags = 0;
8845 
8846     if (!ASCII_ISALPHA(*p))
8847 	return NULL;
8848     *arg = p;
8849 
8850     if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
8851 	p += 4;	    /* termcap option */
8852     else
8853 	while (ASCII_ISALPHA(*p))
8854 	    ++p;
8855     return p;
8856 }
8857 
8858 /*
8859  * Return the autoload script name for a function or variable name.
8860  * Returns NULL when out of memory.
8861  */
8862     char_u *
8863 autoload_name(char_u *name)
8864 {
8865     char_u	*p;
8866     char_u	*scriptname;
8867 
8868     /* Get the script file name: replace '#' with '/', append ".vim". */
8869     scriptname = alloc((unsigned)(STRLEN(name) + 14));
8870     if (scriptname == NULL)
8871 	return FALSE;
8872     STRCPY(scriptname, "autoload/");
8873     STRCAT(scriptname, name);
8874     *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
8875     STRCAT(scriptname, ".vim");
8876     while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
8877 	*p = '/';
8878     return scriptname;
8879 }
8880 
8881 /*
8882  * If "name" has a package name try autoloading the script for it.
8883  * Return TRUE if a package was loaded.
8884  */
8885     int
8886 script_autoload(
8887     char_u	*name,
8888     int		reload)	    /* load script again when already loaded */
8889 {
8890     char_u	*p;
8891     char_u	*scriptname, *tofree;
8892     int		ret = FALSE;
8893     int		i;
8894 
8895     /* If there is no '#' after name[0] there is no package name. */
8896     p = vim_strchr(name, AUTOLOAD_CHAR);
8897     if (p == NULL || p == name)
8898 	return FALSE;
8899 
8900     tofree = scriptname = autoload_name(name);
8901 
8902     /* Find the name in the list of previously loaded package names.  Skip
8903      * "autoload/", it's always the same. */
8904     for (i = 0; i < ga_loaded.ga_len; ++i)
8905 	if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
8906 	    break;
8907     if (!reload && i < ga_loaded.ga_len)
8908 	ret = FALSE;	    /* was loaded already */
8909     else
8910     {
8911 	/* Remember the name if it wasn't loaded already. */
8912 	if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
8913 	{
8914 	    ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
8915 	    tofree = NULL;
8916 	}
8917 
8918 	/* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
8919 	if (source_runtime(scriptname, 0) == OK)
8920 	    ret = TRUE;
8921     }
8922 
8923     vim_free(tofree);
8924     return ret;
8925 }
8926 
8927 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
8928 typedef enum
8929 {
8930     VAR_FLAVOUR_DEFAULT,	/* doesn't start with uppercase */
8931     VAR_FLAVOUR_SESSION,	/* starts with uppercase, some lower */
8932     VAR_FLAVOUR_VIMINFO		/* all uppercase */
8933 } var_flavour_T;
8934 
8935     static var_flavour_T
8936 var_flavour(char_u *varname)
8937 {
8938     char_u *p = varname;
8939 
8940     if (ASCII_ISUPPER(*p))
8941     {
8942 	while (*(++p))
8943 	    if (ASCII_ISLOWER(*p))
8944 		return VAR_FLAVOUR_SESSION;
8945 	return VAR_FLAVOUR_VIMINFO;
8946     }
8947     else
8948 	return VAR_FLAVOUR_DEFAULT;
8949 }
8950 #endif
8951 
8952 #if defined(FEAT_VIMINFO) || defined(PROTO)
8953 /*
8954  * Restore global vars that start with a capital from the viminfo file
8955  */
8956     int
8957 read_viminfo_varlist(vir_T *virp, int writing)
8958 {
8959     char_u	*tab;
8960     int		type = VAR_NUMBER;
8961     typval_T	tv;
8962     funccal_entry_T funccal_entry;
8963 
8964     if (!writing && (find_viminfo_parameter('!') != NULL))
8965     {
8966 	tab = vim_strchr(virp->vir_line + 1, '\t');
8967 	if (tab != NULL)
8968 	{
8969 	    *tab++ = '\0';	/* isolate the variable name */
8970 	    switch (*tab)
8971 	    {
8972 		case 'S': type = VAR_STRING; break;
8973 #ifdef FEAT_FLOAT
8974 		case 'F': type = VAR_FLOAT; break;
8975 #endif
8976 		case 'D': type = VAR_DICT; break;
8977 		case 'L': type = VAR_LIST; break;
8978 		case 'B': type = VAR_BLOB; break;
8979 		case 'X': type = VAR_SPECIAL; break;
8980 	    }
8981 
8982 	    tab = vim_strchr(tab, '\t');
8983 	    if (tab != NULL)
8984 	    {
8985 		tv.v_type = type;
8986 		if (type == VAR_STRING || type == VAR_DICT
8987 			|| type == VAR_LIST || type == VAR_BLOB)
8988 		    tv.vval.v_string = viminfo_readstring(virp,
8989 				       (int)(tab - virp->vir_line + 1), TRUE);
8990 #ifdef FEAT_FLOAT
8991 		else if (type == VAR_FLOAT)
8992 		    (void)string2float(tab + 1, &tv.vval.v_float);
8993 #endif
8994 		else
8995 		    tv.vval.v_number = atol((char *)tab + 1);
8996 		if (type == VAR_DICT || type == VAR_LIST)
8997 		{
8998 		    typval_T *etv = eval_expr(tv.vval.v_string, NULL);
8999 
9000 		    if (etv == NULL)
9001 			/* Failed to parse back the dict or list, use it as a
9002 			 * string. */
9003 			tv.v_type = VAR_STRING;
9004 		    else
9005 		    {
9006 			vim_free(tv.vval.v_string);
9007 			tv = *etv;
9008 			vim_free(etv);
9009 		    }
9010 		}
9011 		else if (type == VAR_BLOB)
9012 		{
9013 		    blob_T *blob = string2blob(tv.vval.v_string);
9014 
9015 		    if (blob == NULL)
9016 			// Failed to parse back the blob, use it as a string.
9017 			tv.v_type = VAR_STRING;
9018 		    else
9019 		    {
9020 			vim_free(tv.vval.v_string);
9021 			tv.v_type = VAR_BLOB;
9022 			tv.vval.v_blob = blob;
9023 		    }
9024 		}
9025 
9026 		/* when in a function use global variables */
9027 		save_funccal(&funccal_entry);
9028 		set_var(virp->vir_line + 1, &tv, FALSE);
9029 		restore_funccal();
9030 
9031 		if (tv.v_type == VAR_STRING)
9032 		    vim_free(tv.vval.v_string);
9033 		else if (tv.v_type == VAR_DICT || tv.v_type == VAR_LIST ||
9034 			tv.v_type == VAR_BLOB)
9035 		    clear_tv(&tv);
9036 	    }
9037 	}
9038     }
9039 
9040     return viminfo_readline(virp);
9041 }
9042 
9043 /*
9044  * Write global vars that start with a capital to the viminfo file
9045  */
9046     void
9047 write_viminfo_varlist(FILE *fp)
9048 {
9049     hashitem_T	*hi;
9050     dictitem_T	*this_var;
9051     int		todo;
9052     char	*s = "";
9053     char_u	*p;
9054     char_u	*tofree;
9055     char_u	numbuf[NUMBUFLEN];
9056 
9057     if (find_viminfo_parameter('!') == NULL)
9058 	return;
9059 
9060     fputs(_("\n# global variables:\n"), fp);
9061 
9062     todo = (int)globvarht.ht_used;
9063     for (hi = globvarht.ht_array; todo > 0; ++hi)
9064     {
9065 	if (!HASHITEM_EMPTY(hi))
9066 	{
9067 	    --todo;
9068 	    this_var = HI2DI(hi);
9069 	    if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
9070 	    {
9071 		switch (this_var->di_tv.v_type)
9072 		{
9073 		    case VAR_STRING: s = "STR"; break;
9074 		    case VAR_NUMBER: s = "NUM"; break;
9075 		    case VAR_FLOAT:  s = "FLO"; break;
9076 		    case VAR_DICT:   s = "DIC"; break;
9077 		    case VAR_LIST:   s = "LIS"; break;
9078 		    case VAR_BLOB:   s = "BLO"; break;
9079 		    case VAR_SPECIAL: s = "XPL"; break;
9080 
9081 		    case VAR_UNKNOWN:
9082 		    case VAR_FUNC:
9083 		    case VAR_PARTIAL:
9084 		    case VAR_JOB:
9085 		    case VAR_CHANNEL:
9086 				     continue;
9087 		}
9088 		fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
9089 		if (this_var->di_tv.v_type == VAR_SPECIAL)
9090 		{
9091 		    sprintf((char *)numbuf, "%ld",
9092 					  (long)this_var->di_tv.vval.v_number);
9093 		    p = numbuf;
9094 		    tofree = NULL;
9095 		}
9096 		else
9097 		    p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
9098 		if (p != NULL)
9099 		    viminfo_writestring(fp, p);
9100 		vim_free(tofree);
9101 	    }
9102 	}
9103     }
9104 }
9105 #endif
9106 
9107 #if defined(FEAT_SESSION) || defined(PROTO)
9108     int
9109 store_session_globals(FILE *fd)
9110 {
9111     hashitem_T	*hi;
9112     dictitem_T	*this_var;
9113     int		todo;
9114     char_u	*p, *t;
9115 
9116     todo = (int)globvarht.ht_used;
9117     for (hi = globvarht.ht_array; todo > 0; ++hi)
9118     {
9119 	if (!HASHITEM_EMPTY(hi))
9120 	{
9121 	    --todo;
9122 	    this_var = HI2DI(hi);
9123 	    if ((this_var->di_tv.v_type == VAR_NUMBER
9124 			|| this_var->di_tv.v_type == VAR_STRING)
9125 		    && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
9126 	    {
9127 		/* Escape special characters with a backslash.  Turn a LF and
9128 		 * CR into \n and \r. */
9129 		p = vim_strsave_escaped(tv_get_string(&this_var->di_tv),
9130 							(char_u *)"\\\"\n\r");
9131 		if (p == NULL)	    /* out of memory */
9132 		    break;
9133 		for (t = p; *t != NUL; ++t)
9134 		    if (*t == '\n')
9135 			*t = 'n';
9136 		    else if (*t == '\r')
9137 			*t = 'r';
9138 		if ((fprintf(fd, "let %s = %c%s%c",
9139 				this_var->di_key,
9140 				(this_var->di_tv.v_type == VAR_STRING) ? '"'
9141 									: ' ',
9142 				p,
9143 				(this_var->di_tv.v_type == VAR_STRING) ? '"'
9144 								   : ' ') < 0)
9145 			|| put_eol(fd) == FAIL)
9146 		{
9147 		    vim_free(p);
9148 		    return FAIL;
9149 		}
9150 		vim_free(p);
9151 	    }
9152 #ifdef FEAT_FLOAT
9153 	    else if (this_var->di_tv.v_type == VAR_FLOAT
9154 		    && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
9155 	    {
9156 		float_T f = this_var->di_tv.vval.v_float;
9157 		int sign = ' ';
9158 
9159 		if (f < 0)
9160 		{
9161 		    f = -f;
9162 		    sign = '-';
9163 		}
9164 		if ((fprintf(fd, "let %s = %c%f",
9165 					       this_var->di_key, sign, f) < 0)
9166 			|| put_eol(fd) == FAIL)
9167 		    return FAIL;
9168 	    }
9169 #endif
9170 	}
9171     }
9172     return OK;
9173 }
9174 #endif
9175 
9176 /*
9177  * Display script name where an item was last set.
9178  * Should only be invoked when 'verbose' is non-zero.
9179  */
9180     void
9181 last_set_msg(sctx_T script_ctx)
9182 {
9183     char_u *p;
9184 
9185     if (script_ctx.sc_sid != 0)
9186     {
9187 	p = home_replace_save(NULL, get_scriptname(script_ctx.sc_sid));
9188 	if (p != NULL)
9189 	{
9190 	    verbose_enter();
9191 	    msg_puts(_("\n\tLast set from "));
9192 	    msg_puts((char *)p);
9193 	    if (script_ctx.sc_lnum > 0)
9194 	    {
9195 		msg_puts(_(" line "));
9196 		msg_outnum((long)script_ctx.sc_lnum);
9197 	    }
9198 	    verbose_leave();
9199 	    vim_free(p);
9200 	}
9201     }
9202 }
9203 
9204 /* reset v:option_new, v:option_old and v:option_type */
9205     void
9206 reset_v_option_vars(void)
9207 {
9208     set_vim_var_string(VV_OPTION_NEW,  NULL, -1);
9209     set_vim_var_string(VV_OPTION_OLD,  NULL, -1);
9210     set_vim_var_string(VV_OPTION_TYPE, NULL, -1);
9211 }
9212 
9213 /*
9214  * Prepare "gap" for an assert error and add the sourcing position.
9215  */
9216     void
9217 prepare_assert_error(garray_T *gap)
9218 {
9219     char buf[NUMBUFLEN];
9220 
9221     ga_init2(gap, 1, 100);
9222     if (sourcing_name != NULL)
9223     {
9224 	ga_concat(gap, sourcing_name);
9225 	if (sourcing_lnum > 0)
9226 	    ga_concat(gap, (char_u *)" ");
9227     }
9228     if (sourcing_lnum > 0)
9229     {
9230 	sprintf(buf, "line %ld", (long)sourcing_lnum);
9231 	ga_concat(gap, (char_u *)buf);
9232     }
9233     if (sourcing_name != NULL || sourcing_lnum > 0)
9234 	ga_concat(gap, (char_u *)": ");
9235 }
9236 
9237 /*
9238  * Add an assert error to v:errors.
9239  */
9240     void
9241 assert_error(garray_T *gap)
9242 {
9243     struct vimvar   *vp = &vimvars[VV_ERRORS];
9244 
9245     if (vp->vv_type != VAR_LIST || vimvars[VV_ERRORS].vv_list == NULL)
9246 	/* Make sure v:errors is a list. */
9247 	set_vim_var_list(VV_ERRORS, list_alloc());
9248     list_append_string(vimvars[VV_ERRORS].vv_list, gap->ga_data, gap->ga_len);
9249 }
9250 
9251     int
9252 assert_equal_common(typval_T *argvars, assert_type_T atype)
9253 {
9254     garray_T	ga;
9255 
9256     if (tv_equal(&argvars[0], &argvars[1], FALSE, FALSE)
9257 						   != (atype == ASSERT_EQUAL))
9258     {
9259 	prepare_assert_error(&ga);
9260 	fill_assert_error(&ga, &argvars[2], NULL, &argvars[0], &argvars[1],
9261 								       atype);
9262 	assert_error(&ga);
9263 	ga_clear(&ga);
9264 	return 1;
9265     }
9266     return 0;
9267 }
9268 
9269     int
9270 assert_equalfile(typval_T *argvars)
9271 {
9272     char_u	buf1[NUMBUFLEN];
9273     char_u	buf2[NUMBUFLEN];
9274     char_u	*fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
9275     char_u	*fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
9276     garray_T	ga;
9277     FILE	*fd1;
9278     FILE	*fd2;
9279 
9280     if (fname1 == NULL || fname2 == NULL)
9281 	return 0;
9282 
9283     IObuff[0] = NUL;
9284     fd1 = mch_fopen((char *)fname1, READBIN);
9285     if (fd1 == NULL)
9286     {
9287 	vim_snprintf((char *)IObuff, IOSIZE, (char *)e_notread, fname1);
9288     }
9289     else
9290     {
9291 	fd2 = mch_fopen((char *)fname2, READBIN);
9292 	if (fd2 == NULL)
9293 	{
9294 	    fclose(fd1);
9295 	    vim_snprintf((char *)IObuff, IOSIZE, (char *)e_notread, fname2);
9296 	}
9297 	else
9298 	{
9299 	    int c1, c2;
9300 	    long count = 0;
9301 
9302 	    for (;;)
9303 	    {
9304 		c1 = fgetc(fd1);
9305 		c2 = fgetc(fd2);
9306 		if (c1 == EOF)
9307 		{
9308 		    if (c2 != EOF)
9309 			STRCPY(IObuff, "first file is shorter");
9310 		    break;
9311 		}
9312 		else if (c2 == EOF)
9313 		{
9314 		    STRCPY(IObuff, "second file is shorter");
9315 		    break;
9316 		}
9317 		else if (c1 != c2)
9318 		{
9319 		    vim_snprintf((char *)IObuff, IOSIZE,
9320 					      "difference at byte %ld", count);
9321 		    break;
9322 		}
9323 		++count;
9324 	    }
9325 	    fclose(fd1);
9326 	    fclose(fd2);
9327 	}
9328     }
9329     if (IObuff[0] != NUL)
9330     {
9331 	prepare_assert_error(&ga);
9332 	ga_concat(&ga, IObuff);
9333 	assert_error(&ga);
9334 	ga_clear(&ga);
9335 	return 1;
9336     }
9337     return 0;
9338 }
9339 
9340     int
9341 assert_match_common(typval_T *argvars, assert_type_T atype)
9342 {
9343     garray_T	ga;
9344     char_u	buf1[NUMBUFLEN];
9345     char_u	buf2[NUMBUFLEN];
9346     char_u	*pat = tv_get_string_buf_chk(&argvars[0], buf1);
9347     char_u	*text = tv_get_string_buf_chk(&argvars[1], buf2);
9348 
9349     if (pat == NULL || text == NULL)
9350 	emsg(_(e_invarg));
9351     else if (pattern_match(pat, text, FALSE) != (atype == ASSERT_MATCH))
9352     {
9353 	prepare_assert_error(&ga);
9354 	fill_assert_error(&ga, &argvars[2], NULL, &argvars[0], &argvars[1],
9355 									atype);
9356 	assert_error(&ga);
9357 	ga_clear(&ga);
9358 	return 1;
9359     }
9360     return 0;
9361 }
9362 
9363     int
9364 assert_inrange(typval_T *argvars)
9365 {
9366     garray_T	ga;
9367     int		error = FALSE;
9368     char_u	*tofree;
9369     char	msg[200];
9370     char_u	numbuf[NUMBUFLEN];
9371 
9372 #ifdef FEAT_FLOAT
9373     if (argvars[0].v_type == VAR_FLOAT
9374 	    || argvars[1].v_type == VAR_FLOAT
9375 	    || argvars[2].v_type == VAR_FLOAT)
9376     {
9377 	float_T flower = tv_get_float(&argvars[0]);
9378 	float_T fupper = tv_get_float(&argvars[1]);
9379 	float_T factual = tv_get_float(&argvars[2]);
9380 
9381 	if (factual < flower || factual > fupper)
9382 	{
9383 	    prepare_assert_error(&ga);
9384 	    if (argvars[3].v_type != VAR_UNKNOWN)
9385 	    {
9386 		ga_concat(&ga, tv2string(&argvars[3], &tofree, numbuf, 0));
9387 		vim_free(tofree);
9388 	    }
9389 	    else
9390 	    {
9391 		vim_snprintf(msg, 200, "Expected range %g - %g, but got %g",
9392 						      flower, fupper, factual);
9393 		ga_concat(&ga, (char_u *)msg);
9394 	    }
9395 	    assert_error(&ga);
9396 	    ga_clear(&ga);
9397 	    return 1;
9398 	}
9399     }
9400     else
9401 #endif
9402     {
9403 	varnumber_T	lower = tv_get_number_chk(&argvars[0], &error);
9404 	varnumber_T	upper = tv_get_number_chk(&argvars[1], &error);
9405 	varnumber_T	actual = tv_get_number_chk(&argvars[2], &error);
9406 
9407 	if (error)
9408 	    return 0;
9409 	if (actual < lower || actual > upper)
9410 	{
9411 	    prepare_assert_error(&ga);
9412 	    if (argvars[3].v_type != VAR_UNKNOWN)
9413 	    {
9414 		ga_concat(&ga, tv2string(&argvars[3], &tofree, numbuf, 0));
9415 		vim_free(tofree);
9416 	    }
9417 	    else
9418 	    {
9419 		vim_snprintf(msg, 200, "Expected range %ld - %ld, but got %ld",
9420 				       (long)lower, (long)upper, (long)actual);
9421 		ga_concat(&ga, (char_u *)msg);
9422 	    }
9423 	    assert_error(&ga);
9424 	    ga_clear(&ga);
9425 	    return 1;
9426 	}
9427     }
9428     return 0;
9429 }
9430 
9431 /*
9432  * Common for assert_true() and assert_false().
9433  * Return non-zero for failure.
9434  */
9435     int
9436 assert_bool(typval_T *argvars, int isTrue)
9437 {
9438     int		error = FALSE;
9439     garray_T	ga;
9440 
9441     if (argvars[0].v_type == VAR_SPECIAL
9442 	    && argvars[0].vval.v_number == (isTrue ? VVAL_TRUE : VVAL_FALSE))
9443 	return 0;
9444     if (argvars[0].v_type != VAR_NUMBER
9445 	    || (tv_get_number_chk(&argvars[0], &error) == 0) == isTrue
9446 	    || error)
9447     {
9448 	prepare_assert_error(&ga);
9449 	fill_assert_error(&ga, &argvars[1],
9450 		(char_u *)(isTrue ? "True" : "False"),
9451 		NULL, &argvars[0], ASSERT_OTHER);
9452 	assert_error(&ga);
9453 	ga_clear(&ga);
9454 	return 1;
9455     }
9456     return 0;
9457 }
9458 
9459     int
9460 assert_report(typval_T *argvars)
9461 {
9462     garray_T	ga;
9463 
9464     prepare_assert_error(&ga);
9465     ga_concat(&ga, tv_get_string(&argvars[0]));
9466     assert_error(&ga);
9467     ga_clear(&ga);
9468     return 1;
9469 }
9470 
9471     int
9472 assert_exception(typval_T *argvars)
9473 {
9474     garray_T	ga;
9475     char_u	*error = tv_get_string_chk(&argvars[0]);
9476 
9477     if (vimvars[VV_EXCEPTION].vv_str == NULL)
9478     {
9479 	prepare_assert_error(&ga);
9480 	ga_concat(&ga, (char_u *)"v:exception is not set");
9481 	assert_error(&ga);
9482 	ga_clear(&ga);
9483 	return 1;
9484     }
9485     else if (error != NULL
9486 	&& strstr((char *)vimvars[VV_EXCEPTION].vv_str, (char *)error) == NULL)
9487     {
9488 	prepare_assert_error(&ga);
9489 	fill_assert_error(&ga, &argvars[1], NULL, &argvars[0],
9490 				  &vimvars[VV_EXCEPTION].vv_tv, ASSERT_OTHER);
9491 	assert_error(&ga);
9492 	ga_clear(&ga);
9493 	return 1;
9494     }
9495     return 0;
9496 }
9497 
9498     int
9499 assert_beeps(typval_T *argvars)
9500 {
9501     char_u	*cmd = tv_get_string_chk(&argvars[0]);
9502     garray_T	ga;
9503     int		ret = 0;
9504 
9505     called_vim_beep = FALSE;
9506     suppress_errthrow = TRUE;
9507     emsg_silent = FALSE;
9508     do_cmdline_cmd(cmd);
9509     if (!called_vim_beep)
9510     {
9511 	prepare_assert_error(&ga);
9512 	ga_concat(&ga, (char_u *)"command did not beep: ");
9513 	ga_concat(&ga, cmd);
9514 	assert_error(&ga);
9515 	ga_clear(&ga);
9516 	ret = 1;
9517     }
9518 
9519     suppress_errthrow = FALSE;
9520     emsg_on_display = FALSE;
9521     return ret;
9522 }
9523 
9524     int
9525 assert_fails(typval_T *argvars)
9526 {
9527     char_u	*cmd = tv_get_string_chk(&argvars[0]);
9528     garray_T	ga;
9529     int		ret = 0;
9530     char_u	numbuf[NUMBUFLEN];
9531     char_u	*tofree;
9532 
9533     called_emsg = FALSE;
9534     suppress_errthrow = TRUE;
9535     emsg_silent = TRUE;
9536     do_cmdline_cmd(cmd);
9537     if (!called_emsg)
9538     {
9539 	prepare_assert_error(&ga);
9540 	ga_concat(&ga, (char_u *)"command did not fail: ");
9541 	if (argvars[1].v_type != VAR_UNKNOWN
9542 					   && argvars[2].v_type != VAR_UNKNOWN)
9543 	{
9544 	    ga_concat(&ga, echo_string(&argvars[2], &tofree, numbuf, 0));
9545 	    vim_free(tofree);
9546 	}
9547 	else
9548 	    ga_concat(&ga, cmd);
9549 	assert_error(&ga);
9550 	ga_clear(&ga);
9551 	ret = 1;
9552     }
9553     else if (argvars[1].v_type != VAR_UNKNOWN)
9554     {
9555 	char_u	buf[NUMBUFLEN];
9556 	char	*error = (char *)tv_get_string_buf_chk(&argvars[1], buf);
9557 
9558 	if (error == NULL
9559 		  || strstr((char *)vimvars[VV_ERRMSG].vv_str, error) == NULL)
9560 	{
9561 	    prepare_assert_error(&ga);
9562 	    fill_assert_error(&ga, &argvars[2], NULL, &argvars[1],
9563 				     &vimvars[VV_ERRMSG].vv_tv, ASSERT_OTHER);
9564 	    assert_error(&ga);
9565 	    ga_clear(&ga);
9566 	ret = 1;
9567 	}
9568     }
9569 
9570     called_emsg = FALSE;
9571     suppress_errthrow = FALSE;
9572     emsg_silent = FALSE;
9573     emsg_on_display = FALSE;
9574     set_vim_var_string(VV_ERRMSG, NULL, 0);
9575     return ret;
9576 }
9577 
9578 /*
9579  * Append "p[clen]" to "gap", escaping unprintable characters.
9580  * Changes NL to \n, CR to \r, etc.
9581  */
9582     static void
9583 ga_concat_esc(garray_T *gap, char_u *p, int clen)
9584 {
9585     char_u  buf[NUMBUFLEN];
9586 
9587     if (clen > 1)
9588     {
9589 	mch_memmove(buf, p, clen);
9590 	buf[clen] = NUL;
9591 	ga_concat(gap, buf);
9592     }
9593     else switch (*p)
9594     {
9595 	case BS: ga_concat(gap, (char_u *)"\\b"); break;
9596 	case ESC: ga_concat(gap, (char_u *)"\\e"); break;
9597 	case FF: ga_concat(gap, (char_u *)"\\f"); break;
9598 	case NL: ga_concat(gap, (char_u *)"\\n"); break;
9599 	case TAB: ga_concat(gap, (char_u *)"\\t"); break;
9600 	case CAR: ga_concat(gap, (char_u *)"\\r"); break;
9601 	case '\\': ga_concat(gap, (char_u *)"\\\\"); break;
9602 	default:
9603 		   if (*p < ' ')
9604 		   {
9605 		       vim_snprintf((char *)buf, NUMBUFLEN, "\\x%02x", *p);
9606 		       ga_concat(gap, buf);
9607 		   }
9608 		   else
9609 		       ga_append(gap, *p);
9610 		   break;
9611     }
9612 }
9613 
9614 /*
9615  * Append "str" to "gap", escaping unprintable characters.
9616  * Changes NL to \n, CR to \r, etc.
9617  */
9618     static void
9619 ga_concat_shorten_esc(garray_T *gap, char_u *str)
9620 {
9621     char_u  *p;
9622     char_u  *s;
9623     int	    c;
9624     int	    clen;
9625     char_u  buf[NUMBUFLEN];
9626     int	    same_len;
9627 
9628     if (str == NULL)
9629     {
9630 	ga_concat(gap, (char_u *)"NULL");
9631 	return;
9632     }
9633 
9634     for (p = str; *p != NUL; ++p)
9635     {
9636 	same_len = 1;
9637 	s = p;
9638 	c = mb_ptr2char_adv(&s);
9639 	clen = s - p;
9640 	while (*s != NUL && c == mb_ptr2char(s))
9641 	{
9642 	    ++same_len;
9643 	    s += clen;
9644 	}
9645 	if (same_len > 20)
9646 	{
9647 	    ga_concat(gap, (char_u *)"\\[");
9648 	    ga_concat_esc(gap, p, clen);
9649 	    ga_concat(gap, (char_u *)" occurs ");
9650 	    vim_snprintf((char *)buf, NUMBUFLEN, "%d", same_len);
9651 	    ga_concat(gap, buf);
9652 	    ga_concat(gap, (char_u *)" times]");
9653 	    p = s - 1;
9654 	}
9655 	else
9656 	    ga_concat_esc(gap, p, clen);
9657     }
9658 }
9659 
9660 /*
9661  * Fill "gap" with information about an assert error.
9662  */
9663     void
9664 fill_assert_error(
9665     garray_T	*gap,
9666     typval_T	*opt_msg_tv,
9667     char_u      *exp_str,
9668     typval_T	*exp_tv,
9669     typval_T	*got_tv,
9670     assert_type_T atype)
9671 {
9672     char_u	numbuf[NUMBUFLEN];
9673     char_u	*tofree;
9674 
9675     if (opt_msg_tv->v_type != VAR_UNKNOWN)
9676     {
9677 	ga_concat(gap, echo_string(opt_msg_tv, &tofree, numbuf, 0));
9678 	vim_free(tofree);
9679 	ga_concat(gap, (char_u *)": ");
9680     }
9681 
9682     if (atype == ASSERT_MATCH || atype == ASSERT_NOTMATCH)
9683 	ga_concat(gap, (char_u *)"Pattern ");
9684     else if (atype == ASSERT_NOTEQUAL)
9685 	ga_concat(gap, (char_u *)"Expected not equal to ");
9686     else
9687 	ga_concat(gap, (char_u *)"Expected ");
9688     if (exp_str == NULL)
9689     {
9690 	ga_concat_shorten_esc(gap, tv2string(exp_tv, &tofree, numbuf, 0));
9691 	vim_free(tofree);
9692     }
9693     else
9694 	ga_concat_shorten_esc(gap, exp_str);
9695     if (atype != ASSERT_NOTEQUAL)
9696     {
9697 	if (atype == ASSERT_MATCH)
9698 	    ga_concat(gap, (char_u *)" does not match ");
9699 	else if (atype == ASSERT_NOTMATCH)
9700 	    ga_concat(gap, (char_u *)" does match ");
9701 	else
9702 	    ga_concat(gap, (char_u *)" but got ");
9703 	ga_concat_shorten_esc(gap, tv2string(got_tv, &tofree, numbuf, 0));
9704 	vim_free(tofree);
9705     }
9706 }
9707 
9708 /*
9709  * Compare "typ1" and "typ2".  Put the result in "typ1".
9710  */
9711     int
9712 typval_compare(
9713     typval_T	*typ1,   /* first operand */
9714     typval_T	*typ2,   /* second operand */
9715     exptype_T	type,    /* operator */
9716     int		type_is, /* TRUE for "is" and "isnot" */
9717     int		ic)      /* ignore case */
9718 {
9719     int		i;
9720     varnumber_T	n1, n2;
9721     char_u	*s1, *s2;
9722     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
9723 
9724     if (type_is && typ1->v_type != typ2->v_type)
9725     {
9726 	/* For "is" a different type always means FALSE, for "notis"
9727 	    * it means TRUE. */
9728 	n1 = (type == TYPE_NEQUAL);
9729     }
9730     else if (typ1->v_type == VAR_BLOB || typ2->v_type == VAR_BLOB)
9731     {
9732 	if (type_is)
9733 	{
9734 	    n1 = (typ1->v_type == typ2->v_type
9735 			    && typ1->vval.v_blob == typ2->vval.v_blob);
9736 	    if (type == TYPE_NEQUAL)
9737 		n1 = !n1;
9738 	}
9739 	else if (typ1->v_type != typ2->v_type
9740 		|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
9741 	{
9742 	    if (typ1->v_type != typ2->v_type)
9743 		emsg(_("E977: Can only compare Blob with Blob"));
9744 	    else
9745 		emsg(_(e_invalblob));
9746 	    clear_tv(typ1);
9747 	    return FAIL;
9748 	}
9749 	else
9750 	{
9751 	    // Compare two Blobs for being equal or unequal.
9752 	    n1 = blob_equal(typ1->vval.v_blob, typ2->vval.v_blob);
9753 	    if (type == TYPE_NEQUAL)
9754 		n1 = !n1;
9755 	}
9756     }
9757     else if (typ1->v_type == VAR_LIST || typ2->v_type == VAR_LIST)
9758     {
9759 	if (type_is)
9760 	{
9761 	    n1 = (typ1->v_type == typ2->v_type
9762 			    && typ1->vval.v_list == typ2->vval.v_list);
9763 	    if (type == TYPE_NEQUAL)
9764 		n1 = !n1;
9765 	}
9766 	else if (typ1->v_type != typ2->v_type
9767 		|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
9768 	{
9769 	    if (typ1->v_type != typ2->v_type)
9770 		emsg(_("E691: Can only compare List with List"));
9771 	    else
9772 		emsg(_("E692: Invalid operation for List"));
9773 	    clear_tv(typ1);
9774 	    return FAIL;
9775 	}
9776 	else
9777 	{
9778 	    /* Compare two Lists for being equal or unequal. */
9779 	    n1 = list_equal(typ1->vval.v_list, typ2->vval.v_list,
9780 							    ic, FALSE);
9781 	    if (type == TYPE_NEQUAL)
9782 		n1 = !n1;
9783 	}
9784     }
9785 
9786     else if (typ1->v_type == VAR_DICT || typ2->v_type == VAR_DICT)
9787     {
9788 	if (type_is)
9789 	{
9790 	    n1 = (typ1->v_type == typ2->v_type
9791 			    && typ1->vval.v_dict == typ2->vval.v_dict);
9792 	    if (type == TYPE_NEQUAL)
9793 		n1 = !n1;
9794 	}
9795 	else if (typ1->v_type != typ2->v_type
9796 		|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
9797 	{
9798 	    if (typ1->v_type != typ2->v_type)
9799 		emsg(_("E735: Can only compare Dictionary with Dictionary"));
9800 	    else
9801 		emsg(_("E736: Invalid operation for Dictionary"));
9802 	    clear_tv(typ1);
9803 	    return FAIL;
9804 	}
9805 	else
9806 	{
9807 	    /* Compare two Dictionaries for being equal or unequal. */
9808 	    n1 = dict_equal(typ1->vval.v_dict, typ2->vval.v_dict,
9809 							    ic, FALSE);
9810 	    if (type == TYPE_NEQUAL)
9811 		n1 = !n1;
9812 	}
9813     }
9814 
9815     else if (typ1->v_type == VAR_FUNC || typ2->v_type == VAR_FUNC
9816 	|| typ1->v_type == VAR_PARTIAL || typ2->v_type == VAR_PARTIAL)
9817     {
9818 	if (type != TYPE_EQUAL && type != TYPE_NEQUAL)
9819 	{
9820 	    emsg(_("E694: Invalid operation for Funcrefs"));
9821 	    clear_tv(typ1);
9822 	    return FAIL;
9823 	}
9824 	if ((typ1->v_type == VAR_PARTIAL
9825 					&& typ1->vval.v_partial == NULL)
9826 		|| (typ2->v_type == VAR_PARTIAL
9827 					&& typ2->vval.v_partial == NULL))
9828 	    /* when a partial is NULL assume not equal */
9829 	    n1 = FALSE;
9830 	else if (type_is)
9831 	{
9832 	    if (typ1->v_type == VAR_FUNC && typ2->v_type == VAR_FUNC)
9833 		/* strings are considered the same if their value is
9834 		    * the same */
9835 		n1 = tv_equal(typ1, typ2, ic, FALSE);
9836 	    else if (typ1->v_type == VAR_PARTIAL
9837 					&& typ2->v_type == VAR_PARTIAL)
9838 		n1 = (typ1->vval.v_partial == typ2->vval.v_partial);
9839 	    else
9840 		n1 = FALSE;
9841 	}
9842 	else
9843 	    n1 = tv_equal(typ1, typ2, ic, FALSE);
9844 	if (type == TYPE_NEQUAL)
9845 	    n1 = !n1;
9846     }
9847 
9848 #ifdef FEAT_FLOAT
9849     /*
9850 	* If one of the two variables is a float, compare as a float.
9851 	* When using "=~" or "!~", always compare as string.
9852 	*/
9853     else if ((typ1->v_type == VAR_FLOAT || typ2->v_type == VAR_FLOAT)
9854 	    && type != TYPE_MATCH && type != TYPE_NOMATCH)
9855     {
9856 	float_T f1, f2;
9857 
9858 	f1 = tv_get_float(typ1);
9859 	f2 = tv_get_float(typ2);
9860 	n1 = FALSE;
9861 	switch (type)
9862 	{
9863 	    case TYPE_EQUAL:    n1 = (f1 == f2); break;
9864 	    case TYPE_NEQUAL:   n1 = (f1 != f2); break;
9865 	    case TYPE_GREATER:  n1 = (f1 > f2); break;
9866 	    case TYPE_GEQUAL:   n1 = (f1 >= f2); break;
9867 	    case TYPE_SMALLER:  n1 = (f1 < f2); break;
9868 	    case TYPE_SEQUAL:   n1 = (f1 <= f2); break;
9869 	    case TYPE_UNKNOWN:
9870 	    case TYPE_MATCH:
9871 	    case TYPE_NOMATCH:  break;  /* avoid gcc warning */
9872 	}
9873     }
9874 #endif
9875 
9876     /*
9877 	* If one of the two variables is a number, compare as a number.
9878 	* When using "=~" or "!~", always compare as string.
9879 	*/
9880     else if ((typ1->v_type == VAR_NUMBER || typ2->v_type == VAR_NUMBER)
9881 	    && type != TYPE_MATCH && type != TYPE_NOMATCH)
9882     {
9883 	n1 = tv_get_number(typ1);
9884 	n2 = tv_get_number(typ2);
9885 	switch (type)
9886 	{
9887 	    case TYPE_EQUAL:    n1 = (n1 == n2); break;
9888 	    case TYPE_NEQUAL:   n1 = (n1 != n2); break;
9889 	    case TYPE_GREATER:  n1 = (n1 > n2); break;
9890 	    case TYPE_GEQUAL:   n1 = (n1 >= n2); break;
9891 	    case TYPE_SMALLER:  n1 = (n1 < n2); break;
9892 	    case TYPE_SEQUAL:   n1 = (n1 <= n2); break;
9893 	    case TYPE_UNKNOWN:
9894 	    case TYPE_MATCH:
9895 	    case TYPE_NOMATCH:  break;  /* avoid gcc warning */
9896 	}
9897     }
9898     else
9899     {
9900 	s1 = tv_get_string_buf(typ1, buf1);
9901 	s2 = tv_get_string_buf(typ2, buf2);
9902 	if (type != TYPE_MATCH && type != TYPE_NOMATCH)
9903 	    i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
9904 	else
9905 	    i = 0;
9906 	n1 = FALSE;
9907 	switch (type)
9908 	{
9909 	    case TYPE_EQUAL:    n1 = (i == 0); break;
9910 	    case TYPE_NEQUAL:   n1 = (i != 0); break;
9911 	    case TYPE_GREATER:  n1 = (i > 0); break;
9912 	    case TYPE_GEQUAL:   n1 = (i >= 0); break;
9913 	    case TYPE_SMALLER:  n1 = (i < 0); break;
9914 	    case TYPE_SEQUAL:   n1 = (i <= 0); break;
9915 
9916 	    case TYPE_MATCH:
9917 	    case TYPE_NOMATCH:
9918 		    n1 = pattern_match(s2, s1, ic);
9919 		    if (type == TYPE_NOMATCH)
9920 			n1 = !n1;
9921 		    break;
9922 
9923 	    case TYPE_UNKNOWN:  break;  /* avoid gcc warning */
9924 	}
9925     }
9926     clear_tv(typ1);
9927     typ1->v_type = VAR_NUMBER;
9928     typ1->vval.v_number = n1;
9929 
9930     return OK;
9931 }
9932 
9933     char_u *
9934 typval_tostring(typval_T *arg)
9935 {
9936     char_u	*tofree;
9937     char_u	numbuf[NUMBUFLEN];
9938     char_u	*ret = NULL;
9939 
9940     if (arg == NULL)
9941 	return vim_strsave((char_u *)"(does not exist)");
9942     ret = tv2string(arg, &tofree, numbuf, 0);
9943     /* Make a copy if we have a value but it's not in allocated memory. */
9944     if (ret != NULL && tofree == NULL)
9945 	ret = vim_strsave(ret);
9946     return ret;
9947 }
9948 
9949     int
9950 var_exists(char_u *var)
9951 {
9952     char_u	*name;
9953     char_u	*tofree;
9954     typval_T    tv;
9955     int		len = 0;
9956     int		n = FALSE;
9957 
9958     /* get_name_len() takes care of expanding curly braces */
9959     name = var;
9960     len = get_name_len(&var, &tofree, TRUE, FALSE);
9961     if (len > 0)
9962     {
9963 	if (tofree != NULL)
9964 	    name = tofree;
9965 	n = (get_var_tv(name, len, &tv, NULL, FALSE, TRUE) == OK);
9966 	if (n)
9967 	{
9968 	    /* handle d.key, l[idx], f(expr) */
9969 	    n = (handle_subscript(&var, &tv, TRUE, FALSE) == OK);
9970 	    if (n)
9971 		clear_tv(&tv);
9972 	}
9973     }
9974     if (*var != NUL)
9975 	n = FALSE;
9976 
9977     vim_free(tofree);
9978     return n;
9979 }
9980 
9981 #endif /* FEAT_EVAL */
9982 
9983 
9984 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
9985 
9986 #ifdef MSWIN
9987 /*
9988  * Functions for ":8" filename modifier: get 8.3 version of a filename.
9989  */
9990 
9991 /*
9992  * Get the short path (8.3) for the filename in "fnamep".
9993  * Only works for a valid file name.
9994  * When the path gets longer "fnamep" is changed and the allocated buffer
9995  * is put in "bufp".
9996  * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
9997  * Returns OK on success, FAIL on failure.
9998  */
9999     static int
10000 get_short_pathname(char_u **fnamep, char_u **bufp, int *fnamelen)
10001 {
10002     int		l, len;
10003     char_u	*newbuf;
10004 
10005     len = *fnamelen;
10006     l = GetShortPathName((LPSTR)*fnamep, (LPSTR)*fnamep, len);
10007     if (l > len - 1)
10008     {
10009 	/* If that doesn't work (not enough space), then save the string
10010 	 * and try again with a new buffer big enough. */
10011 	newbuf = vim_strnsave(*fnamep, l);
10012 	if (newbuf == NULL)
10013 	    return FAIL;
10014 
10015 	vim_free(*bufp);
10016 	*fnamep = *bufp = newbuf;
10017 
10018 	/* Really should always succeed, as the buffer is big enough. */
10019 	l = GetShortPathName((LPSTR)*fnamep, (LPSTR)*fnamep, l+1);
10020     }
10021 
10022     *fnamelen = l;
10023     return OK;
10024 }
10025 
10026 /*
10027  * Get the short path (8.3) for the filename in "fname". The converted
10028  * path is returned in "bufp".
10029  *
10030  * Some of the directories specified in "fname" may not exist. This function
10031  * will shorten the existing directories at the beginning of the path and then
10032  * append the remaining non-existing path.
10033  *
10034  * fname - Pointer to the filename to shorten.  On return, contains the
10035  *	   pointer to the shortened pathname
10036  * bufp -  Pointer to an allocated buffer for the filename.
10037  * fnamelen - Length of the filename pointed to by fname
10038  *
10039  * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
10040  */
10041     static int
10042 shortpath_for_invalid_fname(
10043     char_u	**fname,
10044     char_u	**bufp,
10045     int		*fnamelen)
10046 {
10047     char_u	*short_fname, *save_fname, *pbuf_unused;
10048     char_u	*endp, *save_endp;
10049     char_u	ch;
10050     int		old_len, len;
10051     int		new_len, sfx_len;
10052     int		retval = OK;
10053 
10054     /* Make a copy */
10055     old_len = *fnamelen;
10056     save_fname = vim_strnsave(*fname, old_len);
10057     pbuf_unused = NULL;
10058     short_fname = NULL;
10059 
10060     endp = save_fname + old_len - 1; /* Find the end of the copy */
10061     save_endp = endp;
10062 
10063     /*
10064      * Try shortening the supplied path till it succeeds by removing one
10065      * directory at a time from the tail of the path.
10066      */
10067     len = 0;
10068     for (;;)
10069     {
10070 	/* go back one path-separator */
10071 	while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
10072 	    --endp;
10073 	if (endp <= save_fname)
10074 	    break;		/* processed the complete path */
10075 
10076 	/*
10077 	 * Replace the path separator with a NUL and try to shorten the
10078 	 * resulting path.
10079 	 */
10080 	ch = *endp;
10081 	*endp = 0;
10082 	short_fname = save_fname;
10083 	len = (int)STRLEN(short_fname) + 1;
10084 	if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
10085 	{
10086 	    retval = FAIL;
10087 	    goto theend;
10088 	}
10089 	*endp = ch;	/* preserve the string */
10090 
10091 	if (len > 0)
10092 	    break;	/* successfully shortened the path */
10093 
10094 	/* failed to shorten the path. Skip the path separator */
10095 	--endp;
10096     }
10097 
10098     if (len > 0)
10099     {
10100 	/*
10101 	 * Succeeded in shortening the path. Now concatenate the shortened
10102 	 * path with the remaining path at the tail.
10103 	 */
10104 
10105 	/* Compute the length of the new path. */
10106 	sfx_len = (int)(save_endp - endp) + 1;
10107 	new_len = len + sfx_len;
10108 
10109 	*fnamelen = new_len;
10110 	vim_free(*bufp);
10111 	if (new_len > old_len)
10112 	{
10113 	    /* There is not enough space in the currently allocated string,
10114 	     * copy it to a buffer big enough. */
10115 	    *fname = *bufp = vim_strnsave(short_fname, new_len);
10116 	    if (*fname == NULL)
10117 	    {
10118 		retval = FAIL;
10119 		goto theend;
10120 	    }
10121 	}
10122 	else
10123 	{
10124 	    /* Transfer short_fname to the main buffer (it's big enough),
10125 	     * unless get_short_pathname() did its work in-place. */
10126 	    *fname = *bufp = save_fname;
10127 	    if (short_fname != save_fname)
10128 		vim_strncpy(save_fname, short_fname, len);
10129 	    save_fname = NULL;
10130 	}
10131 
10132 	/* concat the not-shortened part of the path */
10133 	vim_strncpy(*fname + len, endp, sfx_len);
10134 	(*fname)[new_len] = NUL;
10135     }
10136 
10137 theend:
10138     vim_free(pbuf_unused);
10139     vim_free(save_fname);
10140 
10141     return retval;
10142 }
10143 
10144 /*
10145  * Get a pathname for a partial path.
10146  * Returns OK for success, FAIL for failure.
10147  */
10148     static int
10149 shortpath_for_partial(
10150     char_u	**fnamep,
10151     char_u	**bufp,
10152     int		*fnamelen)
10153 {
10154     int		sepcount, len, tflen;
10155     char_u	*p;
10156     char_u	*pbuf, *tfname;
10157     int		hasTilde;
10158 
10159     /* Count up the path separators from the RHS.. so we know which part
10160      * of the path to return. */
10161     sepcount = 0;
10162     for (p = *fnamep; p < *fnamep + *fnamelen; MB_PTR_ADV(p))
10163 	if (vim_ispathsep(*p))
10164 	    ++sepcount;
10165 
10166     /* Need full path first (use expand_env() to remove a "~/") */
10167     hasTilde = (**fnamep == '~');
10168     if (hasTilde)
10169 	pbuf = tfname = expand_env_save(*fnamep);
10170     else
10171 	pbuf = tfname = FullName_save(*fnamep, FALSE);
10172 
10173     len = tflen = (int)STRLEN(tfname);
10174 
10175     if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
10176 	return FAIL;
10177 
10178     if (len == 0)
10179     {
10180 	/* Don't have a valid filename, so shorten the rest of the
10181 	 * path if we can. This CAN give us invalid 8.3 filenames, but
10182 	 * there's not a lot of point in guessing what it might be.
10183 	 */
10184 	len = tflen;
10185 	if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
10186 	    return FAIL;
10187     }
10188 
10189     /* Count the paths backward to find the beginning of the desired string. */
10190     for (p = tfname + len - 1; p >= tfname; --p)
10191     {
10192 	if (has_mbyte)
10193 	    p -= mb_head_off(tfname, p);
10194 	if (vim_ispathsep(*p))
10195 	{
10196 	    if (sepcount == 0 || (hasTilde && sepcount == 1))
10197 		break;
10198 	    else
10199 		sepcount --;
10200 	}
10201     }
10202     if (hasTilde)
10203     {
10204 	--p;
10205 	if (p >= tfname)
10206 	    *p = '~';
10207 	else
10208 	    return FAIL;
10209     }
10210     else
10211 	++p;
10212 
10213     /* Copy in the string - p indexes into tfname - allocated at pbuf */
10214     vim_free(*bufp);
10215     *fnamelen = (int)STRLEN(p);
10216     *bufp = pbuf;
10217     *fnamep = p;
10218 
10219     return OK;
10220 }
10221 #endif // MSWIN
10222 
10223 /*
10224  * Adjust a filename, according to a string of modifiers.
10225  * *fnamep must be NUL terminated when called.  When returning, the length is
10226  * determined by *fnamelen.
10227  * Returns VALID_ flags or -1 for failure.
10228  * When there is an error, *fnamep is set to NULL.
10229  */
10230     int
10231 modify_fname(
10232     char_u	*src,		// string with modifiers
10233     int		tilde_file,	// "~" is a file name, not $HOME
10234     int		*usedlen,	// characters after src that are used
10235     char_u	**fnamep,	// file name so far
10236     char_u	**bufp,		// buffer for allocated file name or NULL
10237     int		*fnamelen)	// length of fnamep
10238 {
10239     int		valid = 0;
10240     char_u	*tail;
10241     char_u	*s, *p, *pbuf;
10242     char_u	dirname[MAXPATHL];
10243     int		c;
10244     int		has_fullname = 0;
10245 #ifdef MSWIN
10246     char_u	*fname_start = *fnamep;
10247     int		has_shortname = 0;
10248 #endif
10249 
10250 repeat:
10251     /* ":p" - full path/file_name */
10252     if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
10253     {
10254 	has_fullname = 1;
10255 
10256 	valid |= VALID_PATH;
10257 	*usedlen += 2;
10258 
10259 	/* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
10260 	if ((*fnamep)[0] == '~'
10261 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
10262 		&& ((*fnamep)[1] == '/'
10263 # ifdef BACKSLASH_IN_FILENAME
10264 		    || (*fnamep)[1] == '\\'
10265 # endif
10266 		    || (*fnamep)[1] == NUL)
10267 #endif
10268 		&& !(tilde_file && (*fnamep)[1] == NUL)
10269 	   )
10270 	{
10271 	    *fnamep = expand_env_save(*fnamep);
10272 	    vim_free(*bufp);	/* free any allocated file name */
10273 	    *bufp = *fnamep;
10274 	    if (*fnamep == NULL)
10275 		return -1;
10276 	}
10277 
10278 	/* When "/." or "/.." is used: force expansion to get rid of it. */
10279 	for (p = *fnamep; *p != NUL; MB_PTR_ADV(p))
10280 	{
10281 	    if (vim_ispathsep(*p)
10282 		    && p[1] == '.'
10283 		    && (p[2] == NUL
10284 			|| vim_ispathsep(p[2])
10285 			|| (p[2] == '.'
10286 			    && (p[3] == NUL || vim_ispathsep(p[3])))))
10287 		break;
10288 	}
10289 
10290 	/* FullName_save() is slow, don't use it when not needed. */
10291 	if (*p != NUL || !vim_isAbsName(*fnamep))
10292 	{
10293 	    *fnamep = FullName_save(*fnamep, *p != NUL);
10294 	    vim_free(*bufp);	/* free any allocated file name */
10295 	    *bufp = *fnamep;
10296 	    if (*fnamep == NULL)
10297 		return -1;
10298 	}
10299 
10300 #ifdef MSWIN
10301 # if _WIN32_WINNT >= 0x0500
10302 	if (vim_strchr(*fnamep, '~') != NULL)
10303 	{
10304 	    /* Expand 8.3 filename to full path.  Needed to make sure the same
10305 	     * file does not have two different names.
10306 	     * Note: problem does not occur if _WIN32_WINNT < 0x0500. */
10307 	    p = alloc(_MAX_PATH + 1);
10308 	    if (p != NULL)
10309 	    {
10310 		if (GetLongPathName((LPSTR)*fnamep, (LPSTR)p, _MAX_PATH))
10311 		{
10312 		    vim_free(*bufp);
10313 		    *bufp = *fnamep = p;
10314 		}
10315 		else
10316 		    vim_free(p);
10317 	    }
10318 	}
10319 # endif
10320 #endif
10321 	/* Append a path separator to a directory. */
10322 	if (mch_isdir(*fnamep))
10323 	{
10324 	    /* Make room for one or two extra characters. */
10325 	    *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
10326 	    vim_free(*bufp);	/* free any allocated file name */
10327 	    *bufp = *fnamep;
10328 	    if (*fnamep == NULL)
10329 		return -1;
10330 	    add_pathsep(*fnamep);
10331 	}
10332     }
10333 
10334     /* ":." - path relative to the current directory */
10335     /* ":~" - path relative to the home directory */
10336     /* ":8" - shortname path - postponed till after */
10337     while (src[*usedlen] == ':'
10338 		  && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
10339     {
10340 	*usedlen += 2;
10341 	if (c == '8')
10342 	{
10343 #ifdef MSWIN
10344 	    has_shortname = 1; /* Postpone this. */
10345 #endif
10346 	    continue;
10347 	}
10348 	pbuf = NULL;
10349 	/* Need full path first (use expand_env() to remove a "~/") */
10350 	if (!has_fullname)
10351 	{
10352 	    if (c == '.' && **fnamep == '~')
10353 		p = pbuf = expand_env_save(*fnamep);
10354 	    else
10355 		p = pbuf = FullName_save(*fnamep, FALSE);
10356 	}
10357 	else
10358 	    p = *fnamep;
10359 
10360 	has_fullname = 0;
10361 
10362 	if (p != NULL)
10363 	{
10364 	    if (c == '.')
10365 	    {
10366 		mch_dirname(dirname, MAXPATHL);
10367 		s = shorten_fname(p, dirname);
10368 		if (s != NULL)
10369 		{
10370 		    *fnamep = s;
10371 		    if (pbuf != NULL)
10372 		    {
10373 			vim_free(*bufp);   /* free any allocated file name */
10374 			*bufp = pbuf;
10375 			pbuf = NULL;
10376 		    }
10377 		}
10378 	    }
10379 	    else
10380 	    {
10381 		home_replace(NULL, p, dirname, MAXPATHL, TRUE);
10382 		/* Only replace it when it starts with '~' */
10383 		if (*dirname == '~')
10384 		{
10385 		    s = vim_strsave(dirname);
10386 		    if (s != NULL)
10387 		    {
10388 			*fnamep = s;
10389 			vim_free(*bufp);
10390 			*bufp = s;
10391 		    }
10392 		}
10393 	    }
10394 	    vim_free(pbuf);
10395 	}
10396     }
10397 
10398     tail = gettail(*fnamep);
10399     *fnamelen = (int)STRLEN(*fnamep);
10400 
10401     /* ":h" - head, remove "/file_name", can be repeated  */
10402     /* Don't remove the first "/" or "c:\" */
10403     while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
10404     {
10405 	valid |= VALID_HEAD;
10406 	*usedlen += 2;
10407 	s = get_past_head(*fnamep);
10408 	while (tail > s && after_pathsep(s, tail))
10409 	    MB_PTR_BACK(*fnamep, tail);
10410 	*fnamelen = (int)(tail - *fnamep);
10411 #ifdef VMS
10412 	if (*fnamelen > 0)
10413 	    *fnamelen += 1; /* the path separator is part of the path */
10414 #endif
10415 	if (*fnamelen == 0)
10416 	{
10417 	    /* Result is empty.  Turn it into "." to make ":cd %:h" work. */
10418 	    p = vim_strsave((char_u *)".");
10419 	    if (p == NULL)
10420 		return -1;
10421 	    vim_free(*bufp);
10422 	    *bufp = *fnamep = tail = p;
10423 	    *fnamelen = 1;
10424 	}
10425 	else
10426 	{
10427 	    while (tail > s && !after_pathsep(s, tail))
10428 		MB_PTR_BACK(*fnamep, tail);
10429 	}
10430     }
10431 
10432     /* ":8" - shortname  */
10433     if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
10434     {
10435 	*usedlen += 2;
10436 #ifdef MSWIN
10437 	has_shortname = 1;
10438 #endif
10439     }
10440 
10441 #ifdef MSWIN
10442     /*
10443      * Handle ":8" after we have done 'heads' and before we do 'tails'.
10444      */
10445     if (has_shortname)
10446     {
10447 	/* Copy the string if it is shortened by :h and when it wasn't copied
10448 	 * yet, because we are going to change it in place.  Avoids changing
10449 	 * the buffer name for "%:8". */
10450 	if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start)
10451 	{
10452 	    p = vim_strnsave(*fnamep, *fnamelen);
10453 	    if (p == NULL)
10454 		return -1;
10455 	    vim_free(*bufp);
10456 	    *bufp = *fnamep = p;
10457 	}
10458 
10459 	/* Split into two implementations - makes it easier.  First is where
10460 	 * there isn't a full name already, second is where there is. */
10461 	if (!has_fullname && !vim_isAbsName(*fnamep))
10462 	{
10463 	    if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
10464 		return -1;
10465 	}
10466 	else
10467 	{
10468 	    int		l = *fnamelen;
10469 
10470 	    /* Simple case, already have the full-name.
10471 	     * Nearly always shorter, so try first time. */
10472 	    if (get_short_pathname(fnamep, bufp, &l) == FAIL)
10473 		return -1;
10474 
10475 	    if (l == 0)
10476 	    {
10477 		/* Couldn't find the filename, search the paths. */
10478 		l = *fnamelen;
10479 		if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
10480 		    return -1;
10481 	    }
10482 	    *fnamelen = l;
10483 	}
10484     }
10485 #endif // MSWIN
10486 
10487     /* ":t" - tail, just the basename */
10488     if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
10489     {
10490 	*usedlen += 2;
10491 	*fnamelen -= (int)(tail - *fnamep);
10492 	*fnamep = tail;
10493     }
10494 
10495     /* ":e" - extension, can be repeated */
10496     /* ":r" - root, without extension, can be repeated */
10497     while (src[*usedlen] == ':'
10498 	    && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
10499     {
10500 	/* find a '.' in the tail:
10501 	 * - for second :e: before the current fname
10502 	 * - otherwise: The last '.'
10503 	 */
10504 	if (src[*usedlen + 1] == 'e' && *fnamep > tail)
10505 	    s = *fnamep - 2;
10506 	else
10507 	    s = *fnamep + *fnamelen - 1;
10508 	for ( ; s > tail; --s)
10509 	    if (s[0] == '.')
10510 		break;
10511 	if (src[*usedlen + 1] == 'e')		/* :e */
10512 	{
10513 	    if (s > tail)
10514 	    {
10515 		*fnamelen += (int)(*fnamep - (s + 1));
10516 		*fnamep = s + 1;
10517 #ifdef VMS
10518 		/* cut version from the extension */
10519 		s = *fnamep + *fnamelen - 1;
10520 		for ( ; s > *fnamep; --s)
10521 		    if (s[0] == ';')
10522 			break;
10523 		if (s > *fnamep)
10524 		    *fnamelen = s - *fnamep;
10525 #endif
10526 	    }
10527 	    else if (*fnamep <= tail)
10528 		*fnamelen = 0;
10529 	}
10530 	else				/* :r */
10531 	{
10532 	    if (s > tail)	/* remove one extension */
10533 		*fnamelen = (int)(s - *fnamep);
10534 	}
10535 	*usedlen += 2;
10536     }
10537 
10538     /* ":s?pat?foo?" - substitute */
10539     /* ":gs?pat?foo?" - global substitute */
10540     if (src[*usedlen] == ':'
10541 	    && (src[*usedlen + 1] == 's'
10542 		|| (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
10543     {
10544 	char_u	    *str;
10545 	char_u	    *pat;
10546 	char_u	    *sub;
10547 	int	    sep;
10548 	char_u	    *flags;
10549 	int	    didit = FALSE;
10550 
10551 	flags = (char_u *)"";
10552 	s = src + *usedlen + 2;
10553 	if (src[*usedlen + 1] == 'g')
10554 	{
10555 	    flags = (char_u *)"g";
10556 	    ++s;
10557 	}
10558 
10559 	sep = *s++;
10560 	if (sep)
10561 	{
10562 	    /* find end of pattern */
10563 	    p = vim_strchr(s, sep);
10564 	    if (p != NULL)
10565 	    {
10566 		pat = vim_strnsave(s, (int)(p - s));
10567 		if (pat != NULL)
10568 		{
10569 		    s = p + 1;
10570 		    /* find end of substitution */
10571 		    p = vim_strchr(s, sep);
10572 		    if (p != NULL)
10573 		    {
10574 			sub = vim_strnsave(s, (int)(p - s));
10575 			str = vim_strnsave(*fnamep, *fnamelen);
10576 			if (sub != NULL && str != NULL)
10577 			{
10578 			    *usedlen = (int)(p + 1 - src);
10579 			    s = do_string_sub(str, pat, sub, NULL, flags);
10580 			    if (s != NULL)
10581 			    {
10582 				*fnamep = s;
10583 				*fnamelen = (int)STRLEN(s);
10584 				vim_free(*bufp);
10585 				*bufp = s;
10586 				didit = TRUE;
10587 			    }
10588 			}
10589 			vim_free(sub);
10590 			vim_free(str);
10591 		    }
10592 		    vim_free(pat);
10593 		}
10594 	    }
10595 	    /* after using ":s", repeat all the modifiers */
10596 	    if (didit)
10597 		goto repeat;
10598 	}
10599     }
10600 
10601     if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S')
10602     {
10603 	/* vim_strsave_shellescape() needs a NUL terminated string. */
10604 	c = (*fnamep)[*fnamelen];
10605 	if (c != NUL)
10606 	    (*fnamep)[*fnamelen] = NUL;
10607 	p = vim_strsave_shellescape(*fnamep, FALSE, FALSE);
10608 	if (c != NUL)
10609 	    (*fnamep)[*fnamelen] = c;
10610 	if (p == NULL)
10611 	    return -1;
10612 	vim_free(*bufp);
10613 	*bufp = *fnamep = p;
10614 	*fnamelen = (int)STRLEN(p);
10615 	*usedlen += 2;
10616     }
10617 
10618     return valid;
10619 }
10620 
10621 /*
10622  * Perform a substitution on "str" with pattern "pat" and substitute "sub".
10623  * When "sub" is NULL "expr" is used, must be a VAR_FUNC or VAR_PARTIAL.
10624  * "flags" can be "g" to do a global substitute.
10625  * Returns an allocated string, NULL for error.
10626  */
10627     char_u *
10628 do_string_sub(
10629     char_u	*str,
10630     char_u	*pat,
10631     char_u	*sub,
10632     typval_T	*expr,
10633     char_u	*flags)
10634 {
10635     int		sublen;
10636     regmatch_T	regmatch;
10637     int		i;
10638     int		do_all;
10639     char_u	*tail;
10640     char_u	*end;
10641     garray_T	ga;
10642     char_u	*ret;
10643     char_u	*save_cpo;
10644     char_u	*zero_width = NULL;
10645 
10646     /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
10647     save_cpo = p_cpo;
10648     p_cpo = empty_option;
10649 
10650     ga_init2(&ga, 1, 200);
10651 
10652     do_all = (flags[0] == 'g');
10653 
10654     regmatch.rm_ic = p_ic;
10655     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10656     if (regmatch.regprog != NULL)
10657     {
10658 	tail = str;
10659 	end = str + STRLEN(str);
10660 	while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
10661 	{
10662 	    /* Skip empty match except for first match. */
10663 	    if (regmatch.startp[0] == regmatch.endp[0])
10664 	    {
10665 		if (zero_width == regmatch.startp[0])
10666 		{
10667 		    /* avoid getting stuck on a match with an empty string */
10668 		    i = MB_PTR2LEN(tail);
10669 		    mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail,
10670 								   (size_t)i);
10671 		    ga.ga_len += i;
10672 		    tail += i;
10673 		    continue;
10674 		}
10675 		zero_width = regmatch.startp[0];
10676 	    }
10677 
10678 	    /*
10679 	     * Get some space for a temporary buffer to do the substitution
10680 	     * into.  It will contain:
10681 	     * - The text up to where the match is.
10682 	     * - The substituted text.
10683 	     * - The text after the match.
10684 	     */
10685 	    sublen = vim_regsub(&regmatch, sub, expr, tail, FALSE, TRUE, FALSE);
10686 	    if (ga_grow(&ga, (int)((end - tail) + sublen -
10687 			    (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
10688 	    {
10689 		ga_clear(&ga);
10690 		break;
10691 	    }
10692 
10693 	    /* copy the text up to where the match is */
10694 	    i = (int)(regmatch.startp[0] - tail);
10695 	    mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
10696 	    /* add the substituted text */
10697 	    (void)vim_regsub(&regmatch, sub, expr, (char_u *)ga.ga_data
10698 					  + ga.ga_len + i, TRUE, TRUE, FALSE);
10699 	    ga.ga_len += i + sublen - 1;
10700 	    tail = regmatch.endp[0];
10701 	    if (*tail == NUL)
10702 		break;
10703 	    if (!do_all)
10704 		break;
10705 	}
10706 
10707 	if (ga.ga_data != NULL)
10708 	    STRCPY((char *)ga.ga_data + ga.ga_len, tail);
10709 
10710 	vim_regfree(regmatch.regprog);
10711     }
10712 
10713     ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
10714     ga_clear(&ga);
10715     if (p_cpo == empty_option)
10716 	p_cpo = save_cpo;
10717     else
10718 	/* Darn, evaluating {sub} expression or {expr} changed the value. */
10719 	free_string_option(save_cpo);
10720 
10721     return ret;
10722 }
10723 
10724     static int
10725 filter_map_one(typval_T *tv, typval_T *expr, int map, int *remp)
10726 {
10727     typval_T	rettv;
10728     typval_T	argv[3];
10729     int		retval = FAIL;
10730 
10731     copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10732     argv[0] = vimvars[VV_KEY].vv_tv;
10733     argv[1] = vimvars[VV_VAL].vv_tv;
10734     if (eval_expr_typval(expr, argv, 2, &rettv) == FAIL)
10735 	goto theend;
10736     if (map)
10737     {
10738 	/* map(): replace the list item value */
10739 	clear_tv(tv);
10740 	rettv.v_lock = 0;
10741 	*tv = rettv;
10742     }
10743     else
10744     {
10745 	int	    error = FALSE;
10746 
10747 	/* filter(): when expr is zero remove the item */
10748 	*remp = (tv_get_number_chk(&rettv, &error) == 0);
10749 	clear_tv(&rettv);
10750 	/* On type error, nothing has been removed; return FAIL to stop the
10751 	 * loop.  The error message was given by tv_get_number_chk(). */
10752 	if (error)
10753 	    goto theend;
10754     }
10755     retval = OK;
10756 theend:
10757     clear_tv(&vimvars[VV_VAL].vv_tv);
10758     return retval;
10759 }
10760 
10761 
10762 /*
10763  * Implementation of map() and filter().
10764  */
10765     void
10766 filter_map(typval_T *argvars, typval_T *rettv, int map)
10767 {
10768     typval_T	*expr;
10769     listitem_T	*li, *nli;
10770     list_T	*l = NULL;
10771     dictitem_T	*di;
10772     hashtab_T	*ht;
10773     hashitem_T	*hi;
10774     dict_T	*d = NULL;
10775     typval_T	save_val;
10776     typval_T	save_key;
10777     blob_T	*b = NULL;
10778     int		rem;
10779     int		todo;
10780     char_u	*ermsg = (char_u *)(map ? "map()" : "filter()");
10781     char_u	*arg_errmsg = (char_u *)(map ? N_("map() argument")
10782 				   : N_("filter() argument"));
10783     int		save_did_emsg;
10784     int		idx = 0;
10785 
10786     if (argvars[0].v_type == VAR_BLOB)
10787     {
10788 	if ((b = argvars[0].vval.v_blob) == NULL)
10789 	    return;
10790     }
10791     else if (argvars[0].v_type == VAR_LIST)
10792     {
10793 	if ((l = argvars[0].vval.v_list) == NULL
10794 	      || (!map && var_check_lock(l->lv_lock, arg_errmsg, TRUE)))
10795 	    return;
10796     }
10797     else if (argvars[0].v_type == VAR_DICT)
10798     {
10799 	if ((d = argvars[0].vval.v_dict) == NULL
10800 	      || (!map && var_check_lock(d->dv_lock, arg_errmsg, TRUE)))
10801 	    return;
10802     }
10803     else
10804     {
10805 	semsg(_(e_listdictarg), ermsg);
10806 	return;
10807     }
10808 
10809     expr = &argvars[1];
10810     /* On type errors, the preceding call has already displayed an error
10811      * message.  Avoid a misleading error message for an empty string that
10812      * was not passed as argument. */
10813     if (expr->v_type != VAR_UNKNOWN)
10814     {
10815 	prepare_vimvar(VV_VAL, &save_val);
10816 
10817 	/* We reset "did_emsg" to be able to detect whether an error
10818 	 * occurred during evaluation of the expression. */
10819 	save_did_emsg = did_emsg;
10820 	did_emsg = FALSE;
10821 
10822 	prepare_vimvar(VV_KEY, &save_key);
10823 	if (argvars[0].v_type == VAR_DICT)
10824 	{
10825 	    vimvars[VV_KEY].vv_type = VAR_STRING;
10826 
10827 	    ht = &d->dv_hashtab;
10828 	    hash_lock(ht);
10829 	    todo = (int)ht->ht_used;
10830 	    for (hi = ht->ht_array; todo > 0; ++hi)
10831 	    {
10832 		if (!HASHITEM_EMPTY(hi))
10833 		{
10834 		    int r;
10835 
10836 		    --todo;
10837 		    di = HI2DI(hi);
10838 		    if (map && (var_check_lock(di->di_tv.v_lock,
10839 							   arg_errmsg, TRUE)
10840 				|| var_check_ro(di->di_flags,
10841 							   arg_errmsg, TRUE)))
10842 			break;
10843 		    vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
10844 		    r = filter_map_one(&di->di_tv, expr, map, &rem);
10845 		    clear_tv(&vimvars[VV_KEY].vv_tv);
10846 		    if (r == FAIL || did_emsg)
10847 			break;
10848 		    if (!map && rem)
10849 		    {
10850 			if (var_check_fixed(di->di_flags, arg_errmsg, TRUE)
10851 			    || var_check_ro(di->di_flags, arg_errmsg, TRUE))
10852 			    break;
10853 			dictitem_remove(d, di);
10854 		    }
10855 		}
10856 	    }
10857 	    hash_unlock(ht);
10858 	}
10859 	else if (argvars[0].v_type == VAR_BLOB)
10860 	{
10861 	    int		i;
10862 	    typval_T	tv;
10863 
10864 	    vimvars[VV_KEY].vv_type = VAR_NUMBER;
10865 	    for (i = 0; i < b->bv_ga.ga_len; i++)
10866 	    {
10867 		tv.v_type = VAR_NUMBER;
10868 		tv.vval.v_number = blob_get(b, i);
10869 		vimvars[VV_KEY].vv_nr = idx;
10870 		if (filter_map_one(&tv, expr, map, &rem) == FAIL || did_emsg)
10871 		    break;
10872 		if (tv.v_type != VAR_NUMBER)
10873 		{
10874 		    emsg(_(e_invalblob));
10875 		    return;
10876 		}
10877 		tv.v_type = VAR_NUMBER;
10878 		blob_set(b, i, tv.vval.v_number);
10879 		if (!map && rem)
10880 		{
10881 		    char_u *p = (char_u *)argvars[0].vval.v_blob->bv_ga.ga_data;
10882 
10883 		    mch_memmove(p + idx, p + i + 1,
10884 					      (size_t)b->bv_ga.ga_len - i - 1);
10885 		    --b->bv_ga.ga_len;
10886 		    --i;
10887 		}
10888 	    }
10889 	}
10890 	else
10891 	{
10892 	    // argvars[0].v_type == VAR_LIST
10893 	    vimvars[VV_KEY].vv_type = VAR_NUMBER;
10894 
10895 	    for (li = l->lv_first; li != NULL; li = nli)
10896 	    {
10897 		if (map && var_check_lock(li->li_tv.v_lock, arg_errmsg, TRUE))
10898 		    break;
10899 		nli = li->li_next;
10900 		vimvars[VV_KEY].vv_nr = idx;
10901 		if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10902 								  || did_emsg)
10903 		    break;
10904 		if (!map && rem)
10905 		    listitem_remove(l, li);
10906 		++idx;
10907 	    }
10908 	}
10909 
10910 	restore_vimvar(VV_KEY, &save_key);
10911 	restore_vimvar(VV_VAL, &save_val);
10912 
10913 	did_emsg |= save_did_emsg;
10914     }
10915 
10916     copy_tv(&argvars[0], rettv);
10917 }
10918 
10919 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */
10920