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