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