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