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