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