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