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