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