xref: /vim-8.2.3635/src/eval.c (revision 6e65d594)
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 };
196 
197 /* shorthand */
198 #define vv_type		vv_di.di_tv.v_type
199 #define vv_nr		vv_di.di_tv.vval.v_number
200 #define vv_float	vv_di.di_tv.vval.v_float
201 #define vv_str		vv_di.di_tv.vval.v_string
202 #define vv_list		vv_di.di_tv.vval.v_list
203 #define vv_dict		vv_di.di_tv.vval.v_dict
204 #define vv_tv		vv_di.di_tv
205 
206 static dictitem_T	vimvars_var;		/* variable used for v: */
207 #define vimvarht  vimvardict.dv_hashtab
208 
209 static int ex_let_vars(char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars);
210 static char_u *skip_var_list(char_u *arg, int *var_count, int *semicolon);
211 static char_u *skip_var_one(char_u *arg);
212 static void list_glob_vars(int *first);
213 static void list_buf_vars(int *first);
214 static void list_win_vars(int *first);
215 static void list_tab_vars(int *first);
216 static void list_vim_vars(int *first);
217 static void list_script_vars(int *first);
218 static char_u *list_arg_vars(exarg_T *eap, char_u *arg, int *first);
219 static char_u *ex_let_one(char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op);
220 static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op);
221 static int tv_op(typval_T *tv1, typval_T *tv2, char_u  *op);
222 static void ex_unletlock(exarg_T *eap, char_u *argstart, int deep);
223 static int do_unlet_var(lval_T *lp, char_u *name_end, int forceit);
224 static int do_lock_var(lval_T *lp, char_u *name_end, int deep, int lock);
225 static void item_lock(typval_T *tv, int deep, int lock);
226 
227 static int eval2(char_u **arg, typval_T *rettv, int evaluate);
228 static int eval3(char_u **arg, typval_T *rettv, int evaluate);
229 static int eval4(char_u **arg, typval_T *rettv, int evaluate);
230 static int eval5(char_u **arg, typval_T *rettv, int evaluate);
231 static int eval6(char_u **arg, typval_T *rettv, int evaluate, int want_string);
232 static int eval7(char_u **arg, typval_T *rettv, int evaluate, int want_string);
233 
234 static int eval_index(char_u **arg, typval_T *rettv, int evaluate, int verbose);
235 static int get_string_tv(char_u **arg, typval_T *rettv, int evaluate);
236 static int get_lit_string_tv(char_u **arg, typval_T *rettv, int evaluate);
237 static int free_unref_items(int copyID);
238 static int get_env_tv(char_u **arg, typval_T *rettv, int evaluate);
239 static int get_env_len(char_u **arg);
240 static char_u * make_expanded_name(char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end);
241 static void check_vars(char_u *name, int len);
242 static typval_T *alloc_string_tv(char_u *string);
243 static void delete_var(hashtab_T *ht, hashitem_T *hi);
244 static void list_one_var(dictitem_T *v, char_u *prefix, int *first);
245 static void list_one_var_a(char_u *prefix, char_u *name, int type, char_u *string, int *first);
246 static char_u *find_option_end(char_u **arg, int *opt_flags);
247 
248 /* for VIM_VERSION_ defines */
249 #include "version.h"
250 
251 
252 #if defined(EBCDIC) || defined(PROTO)
253 /*
254  * Compare struct fst by function name.
255  */
256     static int
257 compare_func_name(const void *s1, const void *s2)
258 {
259     struct fst *p1 = (struct fst *)s1;
260     struct fst *p2 = (struct fst *)s2;
261 
262     return STRCMP(p1->f_name, p2->f_name);
263 }
264 
265 /*
266  * Sort the function table by function name.
267  * The sorting of the table above is ASCII dependant.
268  * On machines using EBCDIC we have to sort it.
269  */
270     static void
271 sortFunctions(void)
272 {
273     int		funcCnt = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
274 
275     qsort(functions, (size_t)funcCnt, sizeof(struct fst), compare_func_name);
276 }
277 #endif
278 
279 
280 /*
281  * Initialize the global and v: variables.
282  */
283     void
284 eval_init(void)
285 {
286     int		    i;
287     struct vimvar   *p;
288 
289     init_var_dict(&globvardict, &globvars_var, VAR_DEF_SCOPE);
290     init_var_dict(&vimvardict, &vimvars_var, VAR_SCOPE);
291     vimvardict.dv_lock = VAR_FIXED;
292     hash_init(&compat_hashtab);
293     func_init();
294 
295     for (i = 0; i < VV_LEN; ++i)
296     {
297 	p = &vimvars[i];
298 	if (STRLEN(p->vv_name) > 16)
299 	{
300 	    IEMSG("INTERNAL: name too long, increase size of dictitem16_T");
301 	    getout(1);
302 	}
303 	STRCPY(p->vv_di.di_key, p->vv_name);
304 	if (p->vv_flags & VV_RO)
305 	    p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
306 	else if (p->vv_flags & VV_RO_SBX)
307 	    p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
308 	else
309 	    p->vv_di.di_flags = DI_FLAGS_FIX;
310 
311 	/* add to v: scope dict, unless the value is not always available */
312 	if (p->vv_type != VAR_UNKNOWN)
313 	    hash_add(&vimvarht, p->vv_di.di_key);
314 	if (p->vv_flags & VV_COMPAT)
315 	    /* add to compat scope dict */
316 	    hash_add(&compat_hashtab, p->vv_di.di_key);
317     }
318     vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
319 
320     set_vim_var_nr(VV_SEARCHFORWARD, 1L);
321     set_vim_var_nr(VV_HLSEARCH, 1L);
322     set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc());
323     set_vim_var_list(VV_ERRORS, list_alloc());
324 
325     set_vim_var_nr(VV_FALSE, VVAL_FALSE);
326     set_vim_var_nr(VV_TRUE, VVAL_TRUE);
327     set_vim_var_nr(VV_NONE, VVAL_NONE);
328     set_vim_var_nr(VV_NULL, VVAL_NULL);
329 
330     set_vim_var_nr(VV_TYPE_NUMBER,  VAR_TYPE_NUMBER);
331     set_vim_var_nr(VV_TYPE_STRING,  VAR_TYPE_STRING);
332     set_vim_var_nr(VV_TYPE_FUNC,    VAR_TYPE_FUNC);
333     set_vim_var_nr(VV_TYPE_LIST,    VAR_TYPE_LIST);
334     set_vim_var_nr(VV_TYPE_DICT,    VAR_TYPE_DICT);
335     set_vim_var_nr(VV_TYPE_FLOAT,   VAR_TYPE_FLOAT);
336     set_vim_var_nr(VV_TYPE_BOOL,    VAR_TYPE_BOOL);
337     set_vim_var_nr(VV_TYPE_NONE,    VAR_TYPE_NONE);
338     set_vim_var_nr(VV_TYPE_JOB,     VAR_TYPE_JOB);
339     set_vim_var_nr(VV_TYPE_CHANNEL, VAR_TYPE_CHANNEL);
340 
341     set_reg_var(0);  /* default for v:register is not 0 but '"' */
342 
343 #ifdef EBCDIC
344     /*
345      * Sort the function table, to enable binary search.
346      */
347     sortFunctions();
348 #endif
349 }
350 
351 #if defined(EXITFREE) || defined(PROTO)
352     void
353 eval_clear(void)
354 {
355     int		    i;
356     struct vimvar   *p;
357 
358     for (i = 0; i < VV_LEN; ++i)
359     {
360 	p = &vimvars[i];
361 	if (p->vv_di.di_tv.v_type == VAR_STRING)
362 	{
363 	    vim_free(p->vv_str);
364 	    p->vv_str = NULL;
365 	}
366 	else if (p->vv_di.di_tv.v_type == VAR_LIST)
367 	{
368 	    list_unref(p->vv_list);
369 	    p->vv_list = NULL;
370 	}
371     }
372     hash_clear(&vimvarht);
373     hash_init(&vimvarht);  /* garbage_collect() will access it */
374     hash_clear(&compat_hashtab);
375 
376     free_scriptnames();
377 # if defined(FEAT_CMDL_COMPL)
378     free_locales();
379 # endif
380 
381     /* global variables */
382     vars_clear(&globvarht);
383 
384     /* autoloaded script names */
385     ga_clear_strings(&ga_loaded);
386 
387     /* Script-local variables. First clear all the variables and in a second
388      * loop free the scriptvar_T, because a variable in one script might hold
389      * a reference to the whole scope of another script. */
390     for (i = 1; i <= ga_scripts.ga_len; ++i)
391 	vars_clear(&SCRIPT_VARS(i));
392     for (i = 1; i <= ga_scripts.ga_len; ++i)
393 	vim_free(SCRIPT_SV(i));
394     ga_clear(&ga_scripts);
395 
396     /* unreferenced lists and dicts */
397     (void)garbage_collect(FALSE);
398 
399     /* functions */
400     free_all_functions();
401 }
402 #endif
403 
404 
405 /*
406  * Set an internal variable to a string value. Creates the variable if it does
407  * not already exist.
408  */
409     void
410 set_internal_string_var(char_u *name, char_u *value)
411 {
412     char_u	*val;
413     typval_T	*tvp;
414 
415     val = vim_strsave(value);
416     if (val != NULL)
417     {
418 	tvp = alloc_string_tv(val);
419 	if (tvp != NULL)
420 	{
421 	    set_var(name, tvp, FALSE);
422 	    free_tv(tvp);
423 	}
424     }
425 }
426 
427 static lval_T	*redir_lval = NULL;
428 #define EVALCMD_BUSY (redir_lval == (lval_T *)&redir_lval)
429 static garray_T redir_ga;	/* only valid when redir_lval is not NULL */
430 static char_u	*redir_endp = NULL;
431 static char_u	*redir_varname = NULL;
432 
433 /*
434  * Start recording command output to a variable
435  * When "append" is TRUE append to an existing variable.
436  * Returns OK if successfully completed the setup.  FAIL otherwise.
437  */
438     int
439 var_redir_start(char_u *name, int append)
440 {
441     int		save_emsg;
442     int		err;
443     typval_T	tv;
444 
445     /* Catch a bad name early. */
446     if (!eval_isnamec1(*name))
447     {
448 	EMSG(_(e_invarg));
449 	return FAIL;
450     }
451 
452     /* Make a copy of the name, it is used in redir_lval until redir ends. */
453     redir_varname = vim_strsave(name);
454     if (redir_varname == NULL)
455 	return FAIL;
456 
457     redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
458     if (redir_lval == NULL)
459     {
460 	var_redir_stop();
461 	return FAIL;
462     }
463 
464     /* The output is stored in growarray "redir_ga" until redirection ends. */
465     ga_init2(&redir_ga, (int)sizeof(char), 500);
466 
467     /* Parse the variable name (can be a dict or list entry). */
468     redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, 0,
469 							     FNE_CHECK_START);
470     if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
471     {
472 	clear_lval(redir_lval);
473 	if (redir_endp != NULL && *redir_endp != NUL)
474 	    /* Trailing characters are present after the variable name */
475 	    EMSG(_(e_trailing));
476 	else
477 	    EMSG(_(e_invarg));
478 	redir_endp = NULL;  /* don't store a value, only cleanup */
479 	var_redir_stop();
480 	return FAIL;
481     }
482 
483     /* check if we can write to the variable: set it to or append an empty
484      * string */
485     save_emsg = did_emsg;
486     did_emsg = FALSE;
487     tv.v_type = VAR_STRING;
488     tv.vval.v_string = (char_u *)"";
489     if (append)
490 	set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
491     else
492 	set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
493     clear_lval(redir_lval);
494     err = did_emsg;
495     did_emsg |= save_emsg;
496     if (err)
497     {
498 	redir_endp = NULL;  /* don't store a value, only cleanup */
499 	var_redir_stop();
500 	return FAIL;
501     }
502 
503     return OK;
504 }
505 
506 /*
507  * Append "value[value_len]" to the variable set by var_redir_start().
508  * The actual appending is postponed until redirection ends, because the value
509  * appended may in fact be the string we write to, changing it may cause freed
510  * memory to be used:
511  *   :redir => foo
512  *   :let foo
513  *   :redir END
514  */
515     void
516 var_redir_str(char_u *value, int value_len)
517 {
518     int		len;
519 
520     if (redir_lval == NULL)
521 	return;
522 
523     if (value_len == -1)
524 	len = (int)STRLEN(value);	/* Append the entire string */
525     else
526 	len = value_len;		/* Append only "value_len" characters */
527 
528     if (ga_grow(&redir_ga, len) == OK)
529     {
530 	mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
531 	redir_ga.ga_len += len;
532     }
533     else
534 	var_redir_stop();
535 }
536 
537 /*
538  * Stop redirecting command output to a variable.
539  * Frees the allocated memory.
540  */
541     void
542 var_redir_stop(void)
543 {
544     typval_T	tv;
545 
546     if (EVALCMD_BUSY)
547     {
548 	redir_lval = NULL;
549 	return;
550     }
551 
552     if (redir_lval != NULL)
553     {
554 	/* If there was no error: assign the text to the variable. */
555 	if (redir_endp != NULL)
556 	{
557 	    ga_append(&redir_ga, NUL);  /* Append the trailing NUL. */
558 	    tv.v_type = VAR_STRING;
559 	    tv.vval.v_string = redir_ga.ga_data;
560 	    /* Call get_lval() again, if it's inside a Dict or List it may
561 	     * have changed. */
562 	    redir_endp = get_lval(redir_varname, NULL, redir_lval,
563 					FALSE, FALSE, 0, FNE_CHECK_START);
564 	    if (redir_endp != NULL && redir_lval->ll_name != NULL)
565 		set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
566 	    clear_lval(redir_lval);
567 	}
568 
569 	/* free the collected output */
570 	vim_free(redir_ga.ga_data);
571 	redir_ga.ga_data = NULL;
572 
573 	vim_free(redir_lval);
574 	redir_lval = NULL;
575     }
576     vim_free(redir_varname);
577     redir_varname = NULL;
578 }
579 
580 # if defined(FEAT_MBYTE) || defined(PROTO)
581     int
582 eval_charconvert(
583     char_u	*enc_from,
584     char_u	*enc_to,
585     char_u	*fname_from,
586     char_u	*fname_to)
587 {
588     int		err = FALSE;
589 
590     set_vim_var_string(VV_CC_FROM, enc_from, -1);
591     set_vim_var_string(VV_CC_TO, enc_to, -1);
592     set_vim_var_string(VV_FNAME_IN, fname_from, -1);
593     set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
594     if (eval_to_bool(p_ccv, &err, NULL, FALSE))
595 	err = TRUE;
596     set_vim_var_string(VV_CC_FROM, NULL, -1);
597     set_vim_var_string(VV_CC_TO, NULL, -1);
598     set_vim_var_string(VV_FNAME_IN, NULL, -1);
599     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
600 
601     if (err)
602 	return FAIL;
603     return OK;
604 }
605 # endif
606 
607 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
608     int
609 eval_printexpr(char_u *fname, char_u *args)
610 {
611     int		err = FALSE;
612 
613     set_vim_var_string(VV_FNAME_IN, fname, -1);
614     set_vim_var_string(VV_CMDARG, args, -1);
615     if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
616 	err = TRUE;
617     set_vim_var_string(VV_FNAME_IN, NULL, -1);
618     set_vim_var_string(VV_CMDARG, NULL, -1);
619 
620     if (err)
621     {
622 	mch_remove(fname);
623 	return FAIL;
624     }
625     return OK;
626 }
627 # endif
628 
629 # if defined(FEAT_DIFF) || defined(PROTO)
630     void
631 eval_diff(
632     char_u	*origfile,
633     char_u	*newfile,
634     char_u	*outfile)
635 {
636     int		err = FALSE;
637 
638     set_vim_var_string(VV_FNAME_IN, origfile, -1);
639     set_vim_var_string(VV_FNAME_NEW, newfile, -1);
640     set_vim_var_string(VV_FNAME_OUT, outfile, -1);
641     (void)eval_to_bool(p_dex, &err, NULL, FALSE);
642     set_vim_var_string(VV_FNAME_IN, NULL, -1);
643     set_vim_var_string(VV_FNAME_NEW, NULL, -1);
644     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
645 }
646 
647     void
648 eval_patch(
649     char_u	*origfile,
650     char_u	*difffile,
651     char_u	*outfile)
652 {
653     int		err;
654 
655     set_vim_var_string(VV_FNAME_IN, origfile, -1);
656     set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
657     set_vim_var_string(VV_FNAME_OUT, outfile, -1);
658     (void)eval_to_bool(p_pex, &err, NULL, FALSE);
659     set_vim_var_string(VV_FNAME_IN, NULL, -1);
660     set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
661     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
662 }
663 # endif
664 
665 /*
666  * Top level evaluation function, returning a boolean.
667  * Sets "error" to TRUE if there was an error.
668  * Return TRUE or FALSE.
669  */
670     int
671 eval_to_bool(
672     char_u	*arg,
673     int		*error,
674     char_u	**nextcmd,
675     int		skip)	    /* only parse, don't execute */
676 {
677     typval_T	tv;
678     varnumber_T	retval = FALSE;
679 
680     if (skip)
681 	++emsg_skip;
682     if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
683 	*error = TRUE;
684     else
685     {
686 	*error = FALSE;
687 	if (!skip)
688 	{
689 	    retval = (get_tv_number_chk(&tv, error) != 0);
690 	    clear_tv(&tv);
691 	}
692     }
693     if (skip)
694 	--emsg_skip;
695 
696     return (int)retval;
697 }
698 
699     static int
700 eval_expr_typval(typval_T *expr, typval_T *argv, int argc, typval_T *rettv)
701 {
702     char_u	*s;
703     int		dummy;
704     char_u	buf[NUMBUFLEN];
705 
706     if (expr->v_type == VAR_FUNC)
707     {
708 	s = expr->vval.v_string;
709 	if (s == NULL || *s == NUL)
710 	    return FAIL;
711 	if (call_func(s, (int)STRLEN(s), rettv, argc, argv, NULL,
712 				     0L, 0L, &dummy, TRUE, NULL, NULL) == FAIL)
713 	    return FAIL;
714     }
715     else if (expr->v_type == VAR_PARTIAL)
716     {
717 	partial_T   *partial = expr->vval.v_partial;
718 
719 	s = partial_name(partial);
720 	if (s == NULL || *s == NUL)
721 	    return FAIL;
722 	if (call_func(s, (int)STRLEN(s), rettv, argc, argv, NULL,
723 				  0L, 0L, &dummy, TRUE, partial, NULL) == FAIL)
724 	    return FAIL;
725     }
726     else
727     {
728 	s = get_tv_string_buf_chk(expr, buf);
729 	if (s == NULL)
730 	    return FAIL;
731 	s = skipwhite(s);
732 	if (eval1(&s, rettv, TRUE) == FAIL)
733 	    return FAIL;
734 	if (*s != NUL)  /* check for trailing chars after expr */
735 	{
736 	    EMSG2(_(e_invexpr2), s);
737 	    return FAIL;
738 	}
739     }
740     return OK;
741 }
742 
743 /*
744  * Like eval_to_bool() but using a typval_T instead of a string.
745  * Works for string, funcref and partial.
746  */
747     int
748 eval_expr_to_bool(typval_T *expr, int *error)
749 {
750     typval_T	rettv;
751     int		res;
752 
753     if (eval_expr_typval(expr, NULL, 0, &rettv) == FAIL)
754     {
755 	*error = TRUE;
756 	return FALSE;
757     }
758     res = (get_tv_number_chk(&rettv, error) != 0);
759     clear_tv(&rettv);
760     return res;
761 }
762 
763 /*
764  * Top level evaluation function, returning a string.  If "skip" is TRUE,
765  * only parsing to "nextcmd" is done, without reporting errors.  Return
766  * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
767  */
768     char_u *
769 eval_to_string_skip(
770     char_u	*arg,
771     char_u	**nextcmd,
772     int		skip)	    /* only parse, don't execute */
773 {
774     typval_T	tv;
775     char_u	*retval;
776 
777     if (skip)
778 	++emsg_skip;
779     if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
780 	retval = NULL;
781     else
782     {
783 	retval = vim_strsave(get_tv_string(&tv));
784 	clear_tv(&tv);
785     }
786     if (skip)
787 	--emsg_skip;
788 
789     return retval;
790 }
791 
792 /*
793  * Skip over an expression at "*pp".
794  * Return FAIL for an error, OK otherwise.
795  */
796     int
797 skip_expr(char_u **pp)
798 {
799     typval_T	rettv;
800 
801     *pp = skipwhite(*pp);
802     return eval1(pp, &rettv, FALSE);
803 }
804 
805 /*
806  * Top level evaluation function, returning a string.
807  * When "convert" is TRUE convert a List into a sequence of lines and convert
808  * a Float to a String.
809  * Return pointer to allocated memory, or NULL for failure.
810  */
811     char_u *
812 eval_to_string(
813     char_u	*arg,
814     char_u	**nextcmd,
815     int		convert)
816 {
817     typval_T	tv;
818     char_u	*retval;
819     garray_T	ga;
820 #ifdef FEAT_FLOAT
821     char_u	numbuf[NUMBUFLEN];
822 #endif
823 
824     if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
825 	retval = NULL;
826     else
827     {
828 	if (convert && tv.v_type == VAR_LIST)
829 	{
830 	    ga_init2(&ga, (int)sizeof(char), 80);
831 	    if (tv.vval.v_list != NULL)
832 	    {
833 		list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, FALSE, 0);
834 		if (tv.vval.v_list->lv_len > 0)
835 		    ga_append(&ga, NL);
836 	    }
837 	    ga_append(&ga, NUL);
838 	    retval = (char_u *)ga.ga_data;
839 	}
840 #ifdef FEAT_FLOAT
841 	else if (convert && tv.v_type == VAR_FLOAT)
842 	{
843 	    vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
844 	    retval = vim_strsave(numbuf);
845 	}
846 #endif
847 	else
848 	    retval = vim_strsave(get_tv_string(&tv));
849 	clear_tv(&tv);
850     }
851 
852     return retval;
853 }
854 
855 /*
856  * Call eval_to_string() without using current local variables and using
857  * textlock.  When "use_sandbox" is TRUE use the sandbox.
858  */
859     char_u *
860 eval_to_string_safe(
861     char_u	*arg,
862     char_u	**nextcmd,
863     int		use_sandbox)
864 {
865     char_u	*retval;
866     void	*save_funccalp;
867 
868     save_funccalp = save_funccal();
869     if (use_sandbox)
870 	++sandbox;
871     ++textlock;
872     retval = eval_to_string(arg, nextcmd, FALSE);
873     if (use_sandbox)
874 	--sandbox;
875     --textlock;
876     restore_funccal(save_funccalp);
877     return retval;
878 }
879 
880 /*
881  * Top level evaluation function, returning a number.
882  * Evaluates "expr" silently.
883  * Returns -1 for an error.
884  */
885     varnumber_T
886 eval_to_number(char_u *expr)
887 {
888     typval_T	rettv;
889     varnumber_T	retval;
890     char_u	*p = skipwhite(expr);
891 
892     ++emsg_off;
893 
894     if (eval1(&p, &rettv, TRUE) == FAIL)
895 	retval = -1;
896     else
897     {
898 	retval = get_tv_number_chk(&rettv, NULL);
899 	clear_tv(&rettv);
900     }
901     --emsg_off;
902 
903     return retval;
904 }
905 
906 /*
907  * Prepare v: variable "idx" to be used.
908  * Save the current typeval in "save_tv".
909  * When not used yet add the variable to the v: hashtable.
910  */
911     static void
912 prepare_vimvar(int idx, typval_T *save_tv)
913 {
914     *save_tv = vimvars[idx].vv_tv;
915     if (vimvars[idx].vv_type == VAR_UNKNOWN)
916 	hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
917 }
918 
919 /*
920  * Restore v: variable "idx" to typeval "save_tv".
921  * When no longer defined, remove the variable from the v: hashtable.
922  */
923     static void
924 restore_vimvar(int idx, typval_T *save_tv)
925 {
926     hashitem_T	*hi;
927 
928     vimvars[idx].vv_tv = *save_tv;
929     if (vimvars[idx].vv_type == VAR_UNKNOWN)
930     {
931 	hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
932 	if (HASHITEM_EMPTY(hi))
933 	    internal_error("restore_vimvar()");
934 	else
935 	    hash_remove(&vimvarht, hi);
936     }
937 }
938 
939 #if defined(FEAT_SPELL) || defined(PROTO)
940 /*
941  * Evaluate an expression to a list with suggestions.
942  * For the "expr:" part of 'spellsuggest'.
943  * Returns NULL when there is an error.
944  */
945     list_T *
946 eval_spell_expr(char_u *badword, char_u *expr)
947 {
948     typval_T	save_val;
949     typval_T	rettv;
950     list_T	*list = NULL;
951     char_u	*p = skipwhite(expr);
952 
953     /* Set "v:val" to the bad word. */
954     prepare_vimvar(VV_VAL, &save_val);
955     vimvars[VV_VAL].vv_type = VAR_STRING;
956     vimvars[VV_VAL].vv_str = badword;
957     if (p_verbose == 0)
958 	++emsg_off;
959 
960     if (eval1(&p, &rettv, TRUE) == OK)
961     {
962 	if (rettv.v_type != VAR_LIST)
963 	    clear_tv(&rettv);
964 	else
965 	    list = rettv.vval.v_list;
966     }
967 
968     if (p_verbose == 0)
969 	--emsg_off;
970     restore_vimvar(VV_VAL, &save_val);
971 
972     return list;
973 }
974 
975 /*
976  * "list" is supposed to contain two items: a word and a number.  Return the
977  * word in "pp" and the number as the return value.
978  * Return -1 if anything isn't right.
979  * Used to get the good word and score from the eval_spell_expr() result.
980  */
981     int
982 get_spellword(list_T *list, char_u **pp)
983 {
984     listitem_T	*li;
985 
986     li = list->lv_first;
987     if (li == NULL)
988 	return -1;
989     *pp = get_tv_string(&li->li_tv);
990 
991     li = li->li_next;
992     if (li == NULL)
993 	return -1;
994     return (int)get_tv_number(&li->li_tv);
995 }
996 #endif
997 
998 /*
999  * Top level evaluation function.
1000  * Returns an allocated typval_T with the result.
1001  * Returns NULL when there is an error.
1002  */
1003     typval_T *
1004 eval_expr(char_u *arg, char_u **nextcmd)
1005 {
1006     typval_T	*tv;
1007 
1008     tv = (typval_T *)alloc(sizeof(typval_T));
1009     if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1010     {
1011 	vim_free(tv);
1012 	tv = NULL;
1013     }
1014 
1015     return tv;
1016 }
1017 
1018 
1019 /*
1020  * Call some Vim script function and return the result in "*rettv".
1021  * Uses argv[argc] for the function arguments.  Only Number and String
1022  * arguments are currently supported.
1023  * Returns OK or FAIL.
1024  */
1025     int
1026 call_vim_function(
1027     char_u      *func,
1028     int		argc,
1029     char_u      **argv,
1030     int		safe,		/* use the sandbox */
1031     int		str_arg_only,	/* all arguments are strings */
1032     typval_T	*rettv)
1033 {
1034     typval_T	*argvars;
1035     varnumber_T	n;
1036     int		len;
1037     int		i;
1038     int		doesrange;
1039     void	*save_funccalp = NULL;
1040     int		ret;
1041 
1042     argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1043     if (argvars == NULL)
1044 	return FAIL;
1045 
1046     for (i = 0; i < argc; i++)
1047     {
1048 	/* Pass a NULL or empty argument as an empty string */
1049 	if (argv[i] == NULL || *argv[i] == NUL)
1050 	{
1051 	    argvars[i].v_type = VAR_STRING;
1052 	    argvars[i].vval.v_string = (char_u *)"";
1053 	    continue;
1054 	}
1055 
1056 	if (str_arg_only)
1057 	    len = 0;
1058 	else
1059 	{
1060 	    /* Recognize a number argument, the others must be strings. A dash
1061 	     * is a string too. */
1062 	    vim_str2nr(argv[i], NULL, &len, STR2NR_ALL, &n, NULL, 0);
1063 	    if (len == 1 && *argv[i] == '-')
1064 		len = 0;
1065 	}
1066 	if (len != 0 && len == (int)STRLEN(argv[i]))
1067 	{
1068 	    argvars[i].v_type = VAR_NUMBER;
1069 	    argvars[i].vval.v_number = n;
1070 	}
1071 	else
1072 	{
1073 	    argvars[i].v_type = VAR_STRING;
1074 	    argvars[i].vval.v_string = argv[i];
1075 	}
1076     }
1077 
1078     if (safe)
1079     {
1080 	save_funccalp = save_funccal();
1081 	++sandbox;
1082     }
1083 
1084     rettv->v_type = VAR_UNKNOWN;		/* clear_tv() uses this */
1085     ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars, NULL,
1086 		    curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1087 		    &doesrange, TRUE, NULL, NULL);
1088     if (safe)
1089     {
1090 	--sandbox;
1091 	restore_funccal(save_funccalp);
1092     }
1093     vim_free(argvars);
1094 
1095     if (ret == FAIL)
1096 	clear_tv(rettv);
1097 
1098     return ret;
1099 }
1100 
1101 /*
1102  * Call Vim script function "func" and return the result as a number.
1103  * Returns -1 when calling the function fails.
1104  * Uses argv[argc] for the function arguments.
1105  */
1106     varnumber_T
1107 call_func_retnr(
1108     char_u      *func,
1109     int		argc,
1110     char_u      **argv,
1111     int		safe)		/* use the sandbox */
1112 {
1113     typval_T	rettv;
1114     varnumber_T	retval;
1115 
1116     /* All arguments are passed as strings, no conversion to number. */
1117     if (call_vim_function(func, argc, argv, safe, TRUE, &rettv) == FAIL)
1118 	return -1;
1119 
1120     retval = get_tv_number_chk(&rettv, NULL);
1121     clear_tv(&rettv);
1122     return retval;
1123 }
1124 
1125 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1126 	|| defined(FEAT_COMPL_FUNC) || defined(PROTO)
1127 
1128 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1129 /*
1130  * Call Vim script function "func" and return the result as a string.
1131  * Returns NULL when calling the function fails.
1132  * Uses argv[argc] for the function arguments.
1133  */
1134     void *
1135 call_func_retstr(
1136     char_u      *func,
1137     int		argc,
1138     char_u      **argv,
1139     int		safe)		/* use the sandbox */
1140 {
1141     typval_T	rettv;
1142     char_u	*retval;
1143 
1144     /* All arguments are passed as strings, no conversion to number. */
1145     if (call_vim_function(func, argc, argv, safe, TRUE, &rettv) == FAIL)
1146 	return NULL;
1147 
1148     retval = vim_strsave(get_tv_string(&rettv));
1149     clear_tv(&rettv);
1150     return retval;
1151 }
1152 # endif
1153 
1154 /*
1155  * Call Vim script function "func" and return the result as a List.
1156  * Uses argv[argc] for the function arguments.
1157  * Returns NULL when there is something wrong.
1158  */
1159     void *
1160 call_func_retlist(
1161     char_u      *func,
1162     int		argc,
1163     char_u      **argv,
1164     int		safe)		/* use the sandbox */
1165 {
1166     typval_T	rettv;
1167 
1168     /* All arguments are passed as strings, no conversion to number. */
1169     if (call_vim_function(func, argc, argv, safe, TRUE, &rettv) == FAIL)
1170 	return NULL;
1171 
1172     if (rettv.v_type != VAR_LIST)
1173     {
1174 	clear_tv(&rettv);
1175 	return NULL;
1176     }
1177 
1178     return rettv.vval.v_list;
1179 }
1180 #endif
1181 
1182 
1183 #ifdef FEAT_FOLDING
1184 /*
1185  * Evaluate 'foldexpr'.  Returns the foldlevel, and any character preceding
1186  * it in "*cp".  Doesn't give error messages.
1187  */
1188     int
1189 eval_foldexpr(char_u *arg, int *cp)
1190 {
1191     typval_T	tv;
1192     varnumber_T	retval;
1193     char_u	*s;
1194     int		use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1195 								   OPT_LOCAL);
1196 
1197     ++emsg_off;
1198     if (use_sandbox)
1199 	++sandbox;
1200     ++textlock;
1201     *cp = NUL;
1202     if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1203 	retval = 0;
1204     else
1205     {
1206 	/* If the result is a number, just return the number. */
1207 	if (tv.v_type == VAR_NUMBER)
1208 	    retval = tv.vval.v_number;
1209 	else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1210 	    retval = 0;
1211 	else
1212 	{
1213 	    /* If the result is a string, check if there is a non-digit before
1214 	     * the number. */
1215 	    s = tv.vval.v_string;
1216 	    if (!VIM_ISDIGIT(*s) && *s != '-')
1217 		*cp = *s++;
1218 	    retval = atol((char *)s);
1219 	}
1220 	clear_tv(&tv);
1221     }
1222     --emsg_off;
1223     if (use_sandbox)
1224 	--sandbox;
1225     --textlock;
1226 
1227     return (int)retval;
1228 }
1229 #endif
1230 
1231 /*
1232  * ":let"			list all variable values
1233  * ":let var1 var2"		list variable values
1234  * ":let var = expr"		assignment command.
1235  * ":let var += expr"		assignment command.
1236  * ":let var -= expr"		assignment command.
1237  * ":let var .= expr"		assignment command.
1238  * ":let [var1, var2] = expr"	unpack list.
1239  */
1240     void
1241 ex_let(exarg_T *eap)
1242 {
1243     char_u	*arg = eap->arg;
1244     char_u	*expr = NULL;
1245     typval_T	rettv;
1246     int		i;
1247     int		var_count = 0;
1248     int		semicolon = 0;
1249     char_u	op[2];
1250     char_u	*argend;
1251     int		first = TRUE;
1252 
1253     argend = skip_var_list(arg, &var_count, &semicolon);
1254     if (argend == NULL)
1255 	return;
1256     if (argend > arg && argend[-1] == '.')  /* for var.='str' */
1257 	--argend;
1258     expr = skipwhite(argend);
1259     if (*expr != '=' && !(vim_strchr((char_u *)"+-.", *expr) != NULL
1260 			  && expr[1] == '='))
1261     {
1262 	/*
1263 	 * ":let" without "=": list variables
1264 	 */
1265 	if (*arg == '[')
1266 	    EMSG(_(e_invarg));
1267 	else if (!ends_excmd(*arg))
1268 	    /* ":let var1 var2" */
1269 	    arg = list_arg_vars(eap, arg, &first);
1270 	else if (!eap->skip)
1271 	{
1272 	    /* ":let" */
1273 	    list_glob_vars(&first);
1274 	    list_buf_vars(&first);
1275 	    list_win_vars(&first);
1276 	    list_tab_vars(&first);
1277 	    list_script_vars(&first);
1278 	    list_func_vars(&first);
1279 	    list_vim_vars(&first);
1280 	}
1281 	eap->nextcmd = check_nextcmd(arg);
1282     }
1283     else
1284     {
1285 	op[0] = '=';
1286 	op[1] = NUL;
1287 	if (*expr != '=')
1288 	{
1289 	    if (vim_strchr((char_u *)"+-.", *expr) != NULL)
1290 		op[0] = *expr;   /* +=, -= or .= */
1291 	    expr = skipwhite(expr + 2);
1292 	}
1293 	else
1294 	    expr = skipwhite(expr + 1);
1295 
1296 	if (eap->skip)
1297 	    ++emsg_skip;
1298 	i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1299 	if (eap->skip)
1300 	{
1301 	    if (i != FAIL)
1302 		clear_tv(&rettv);
1303 	    --emsg_skip;
1304 	}
1305 	else if (i != FAIL)
1306 	{
1307 	    (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1308 									  op);
1309 	    clear_tv(&rettv);
1310 	}
1311     }
1312 }
1313 
1314 /*
1315  * Assign the typevalue "tv" to the variable or variables at "arg_start".
1316  * Handles both "var" with any type and "[var, var; var]" with a list type.
1317  * When "nextchars" is not NULL it points to a string with characters that
1318  * must appear after the variable(s).  Use "+", "-" or "." for add, subtract
1319  * or concatenate.
1320  * Returns OK or FAIL;
1321  */
1322     static int
1323 ex_let_vars(
1324     char_u	*arg_start,
1325     typval_T	*tv,
1326     int		copy,		/* copy values from "tv", don't move */
1327     int		semicolon,	/* from skip_var_list() */
1328     int		var_count,	/* from skip_var_list() */
1329     char_u	*nextchars)
1330 {
1331     char_u	*arg = arg_start;
1332     list_T	*l;
1333     int		i;
1334     listitem_T	*item;
1335     typval_T	ltv;
1336 
1337     if (*arg != '[')
1338     {
1339 	/*
1340 	 * ":let var = expr" or ":for var in list"
1341 	 */
1342 	if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1343 	    return FAIL;
1344 	return OK;
1345     }
1346 
1347     /*
1348      * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1349      */
1350     if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1351     {
1352 	EMSG(_(e_listreq));
1353 	return FAIL;
1354     }
1355 
1356     i = list_len(l);
1357     if (semicolon == 0 && var_count < i)
1358     {
1359 	EMSG(_("E687: Less targets than List items"));
1360 	return FAIL;
1361     }
1362     if (var_count - semicolon > i)
1363     {
1364 	EMSG(_("E688: More targets than List items"));
1365 	return FAIL;
1366     }
1367 
1368     item = l->lv_first;
1369     while (*arg != ']')
1370     {
1371 	arg = skipwhite(arg + 1);
1372 	arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1373 	item = item->li_next;
1374 	if (arg == NULL)
1375 	    return FAIL;
1376 
1377 	arg = skipwhite(arg);
1378 	if (*arg == ';')
1379 	{
1380 	    /* Put the rest of the list (may be empty) in the var after ';'.
1381 	     * Create a new list for this. */
1382 	    l = list_alloc();
1383 	    if (l == NULL)
1384 		return FAIL;
1385 	    while (item != NULL)
1386 	    {
1387 		list_append_tv(l, &item->li_tv);
1388 		item = item->li_next;
1389 	    }
1390 
1391 	    ltv.v_type = VAR_LIST;
1392 	    ltv.v_lock = 0;
1393 	    ltv.vval.v_list = l;
1394 	    l->lv_refcount = 1;
1395 
1396 	    arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1397 						    (char_u *)"]", nextchars);
1398 	    clear_tv(&ltv);
1399 	    if (arg == NULL)
1400 		return FAIL;
1401 	    break;
1402 	}
1403 	else if (*arg != ',' && *arg != ']')
1404 	{
1405 	    internal_error("ex_let_vars()");
1406 	    return FAIL;
1407 	}
1408     }
1409 
1410     return OK;
1411 }
1412 
1413 /*
1414  * Skip over assignable variable "var" or list of variables "[var, var]".
1415  * Used for ":let varvar = expr" and ":for varvar in expr".
1416  * For "[var, var]" increment "*var_count" for each variable.
1417  * for "[var, var; var]" set "semicolon".
1418  * Return NULL for an error.
1419  */
1420     static char_u *
1421 skip_var_list(
1422     char_u	*arg,
1423     int		*var_count,
1424     int		*semicolon)
1425 {
1426     char_u	*p, *s;
1427 
1428     if (*arg == '[')
1429     {
1430 	/* "[var, var]": find the matching ']'. */
1431 	p = arg;
1432 	for (;;)
1433 	{
1434 	    p = skipwhite(p + 1);	/* skip whites after '[', ';' or ',' */
1435 	    s = skip_var_one(p);
1436 	    if (s == p)
1437 	    {
1438 		EMSG2(_(e_invarg2), p);
1439 		return NULL;
1440 	    }
1441 	    ++*var_count;
1442 
1443 	    p = skipwhite(s);
1444 	    if (*p == ']')
1445 		break;
1446 	    else if (*p == ';')
1447 	    {
1448 		if (*semicolon == 1)
1449 		{
1450 		    EMSG(_("Double ; in list of variables"));
1451 		    return NULL;
1452 		}
1453 		*semicolon = 1;
1454 	    }
1455 	    else if (*p != ',')
1456 	    {
1457 		EMSG2(_(e_invarg2), p);
1458 		return NULL;
1459 	    }
1460 	}
1461 	return p + 1;
1462     }
1463     else
1464 	return skip_var_one(arg);
1465 }
1466 
1467 /*
1468  * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1469  * l[idx].
1470  */
1471     static char_u *
1472 skip_var_one(char_u *arg)
1473 {
1474     if (*arg == '@' && arg[1] != NUL)
1475 	return arg + 2;
1476     return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1477 				   NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1478 }
1479 
1480 /*
1481  * List variables for hashtab "ht" with prefix "prefix".
1482  * If "empty" is TRUE also list NULL strings as empty strings.
1483  */
1484     void
1485 list_hashtable_vars(
1486     hashtab_T	*ht,
1487     char_u	*prefix,
1488     int		empty,
1489     int		*first)
1490 {
1491     hashitem_T	*hi;
1492     dictitem_T	*di;
1493     int		todo;
1494 
1495     todo = (int)ht->ht_used;
1496     for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
1497     {
1498 	if (!HASHITEM_EMPTY(hi))
1499 	{
1500 	    --todo;
1501 	    di = HI2DI(hi);
1502 	    if (empty || di->di_tv.v_type != VAR_STRING
1503 					   || di->di_tv.vval.v_string != NULL)
1504 		list_one_var(di, prefix, first);
1505 	}
1506     }
1507 }
1508 
1509 /*
1510  * List global variables.
1511  */
1512     static void
1513 list_glob_vars(int *first)
1514 {
1515     list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
1516 }
1517 
1518 /*
1519  * List buffer variables.
1520  */
1521     static void
1522 list_buf_vars(int *first)
1523 {
1524     list_hashtable_vars(&curbuf->b_vars->dv_hashtab, (char_u *)"b:",
1525 								 TRUE, first);
1526 }
1527 
1528 /*
1529  * List window variables.
1530  */
1531     static void
1532 list_win_vars(int *first)
1533 {
1534     list_hashtable_vars(&curwin->w_vars->dv_hashtab,
1535 						 (char_u *)"w:", TRUE, first);
1536 }
1537 
1538 /*
1539  * List tab page variables.
1540  */
1541     static void
1542 list_tab_vars(int *first)
1543 {
1544     list_hashtable_vars(&curtab->tp_vars->dv_hashtab,
1545 						 (char_u *)"t:", TRUE, first);
1546 }
1547 
1548 /*
1549  * List Vim variables.
1550  */
1551     static void
1552 list_vim_vars(int *first)
1553 {
1554     list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
1555 }
1556 
1557 /*
1558  * List script-local variables, if there is a script.
1559  */
1560     static void
1561 list_script_vars(int *first)
1562 {
1563     if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
1564 	list_hashtable_vars(&SCRIPT_VARS(current_SID),
1565 						(char_u *)"s:", FALSE, first);
1566 }
1567 
1568 /*
1569  * List variables in "arg".
1570  */
1571     static char_u *
1572 list_arg_vars(exarg_T *eap, char_u *arg, int *first)
1573 {
1574     int		error = FALSE;
1575     int		len;
1576     char_u	*name;
1577     char_u	*name_start;
1578     char_u	*arg_subsc;
1579     char_u	*tofree;
1580     typval_T    tv;
1581 
1582     while (!ends_excmd(*arg) && !got_int)
1583     {
1584 	if (error || eap->skip)
1585 	{
1586 	    arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1587 	    if (!VIM_ISWHITE(*arg) && !ends_excmd(*arg))
1588 	    {
1589 		emsg_severe = TRUE;
1590 		EMSG(_(e_trailing));
1591 		break;
1592 	    }
1593 	}
1594 	else
1595 	{
1596 	    /* get_name_len() takes care of expanding curly braces */
1597 	    name_start = name = arg;
1598 	    len = get_name_len(&arg, &tofree, TRUE, TRUE);
1599 	    if (len <= 0)
1600 	    {
1601 		/* This is mainly to keep test 49 working: when expanding
1602 		 * curly braces fails overrule the exception error message. */
1603 		if (len < 0 && !aborting())
1604 		{
1605 		    emsg_severe = TRUE;
1606 		    EMSG2(_(e_invarg2), arg);
1607 		    break;
1608 		}
1609 		error = TRUE;
1610 	    }
1611 	    else
1612 	    {
1613 		if (tofree != NULL)
1614 		    name = tofree;
1615 		if (get_var_tv(name, len, &tv, NULL, TRUE, FALSE) == FAIL)
1616 		    error = TRUE;
1617 		else
1618 		{
1619 		    /* handle d.key, l[idx], f(expr) */
1620 		    arg_subsc = arg;
1621 		    if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
1622 			error = TRUE;
1623 		    else
1624 		    {
1625 			if (arg == arg_subsc && len == 2 && name[1] == ':')
1626 			{
1627 			    switch (*name)
1628 			    {
1629 				case 'g': list_glob_vars(first); break;
1630 				case 'b': list_buf_vars(first); break;
1631 				case 'w': list_win_vars(first); break;
1632 				case 't': list_tab_vars(first); break;
1633 				case 'v': list_vim_vars(first); break;
1634 				case 's': list_script_vars(first); break;
1635 				case 'l': list_func_vars(first); break;
1636 				default:
1637 					  EMSG2(_("E738: Can't list variables for %s"), name);
1638 			    }
1639 			}
1640 			else
1641 			{
1642 			    char_u	numbuf[NUMBUFLEN];
1643 			    char_u	*tf;
1644 			    int		c;
1645 			    char_u	*s;
1646 
1647 			    s = echo_string(&tv, &tf, numbuf, 0);
1648 			    c = *arg;
1649 			    *arg = NUL;
1650 			    list_one_var_a((char_u *)"",
1651 				    arg == arg_subsc ? name : name_start,
1652 				    tv.v_type,
1653 				    s == NULL ? (char_u *)"" : s,
1654 				    first);
1655 			    *arg = c;
1656 			    vim_free(tf);
1657 			}
1658 			clear_tv(&tv);
1659 		    }
1660 		}
1661 	    }
1662 
1663 	    vim_free(tofree);
1664 	}
1665 
1666 	arg = skipwhite(arg);
1667     }
1668 
1669     return arg;
1670 }
1671 
1672 /*
1673  * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
1674  * Returns a pointer to the char just after the var name.
1675  * Returns NULL if there is an error.
1676  */
1677     static char_u *
1678 ex_let_one(
1679     char_u	*arg,		/* points to variable name */
1680     typval_T	*tv,		/* value to assign to variable */
1681     int		copy,		/* copy value from "tv" */
1682     char_u	*endchars,	/* valid chars after variable name  or NULL */
1683     char_u	*op)		/* "+", "-", "."  or NULL*/
1684 {
1685     int		c1;
1686     char_u	*name;
1687     char_u	*p;
1688     char_u	*arg_end = NULL;
1689     int		len;
1690     int		opt_flags;
1691     char_u	*tofree = NULL;
1692 
1693     /*
1694      * ":let $VAR = expr": Set environment variable.
1695      */
1696     if (*arg == '$')
1697     {
1698 	/* Find the end of the name. */
1699 	++arg;
1700 	name = arg;
1701 	len = get_env_len(&arg);
1702 	if (len == 0)
1703 	    EMSG2(_(e_invarg2), name - 1);
1704 	else
1705 	{
1706 	    if (op != NULL && (*op == '+' || *op == '-'))
1707 		EMSG2(_(e_letwrong), op);
1708 	    else if (endchars != NULL
1709 			     && vim_strchr(endchars, *skipwhite(arg)) == NULL)
1710 		EMSG(_(e_letunexp));
1711 	    else if (!check_secure())
1712 	    {
1713 		c1 = name[len];
1714 		name[len] = NUL;
1715 		p = get_tv_string_chk(tv);
1716 		if (p != NULL && op != NULL && *op == '.')
1717 		{
1718 		    int	    mustfree = FALSE;
1719 		    char_u  *s = vim_getenv(name, &mustfree);
1720 
1721 		    if (s != NULL)
1722 		    {
1723 			p = tofree = concat_str(s, p);
1724 			if (mustfree)
1725 			    vim_free(s);
1726 		    }
1727 		}
1728 		if (p != NULL)
1729 		{
1730 		    vim_setenv(name, p);
1731 		    if (STRICMP(name, "HOME") == 0)
1732 			init_homedir();
1733 		    else if (didset_vim && STRICMP(name, "VIM") == 0)
1734 			didset_vim = FALSE;
1735 		    else if (didset_vimruntime
1736 					&& STRICMP(name, "VIMRUNTIME") == 0)
1737 			didset_vimruntime = FALSE;
1738 		    arg_end = arg;
1739 		}
1740 		name[len] = c1;
1741 		vim_free(tofree);
1742 	    }
1743 	}
1744     }
1745 
1746     /*
1747      * ":let &option = expr": Set option value.
1748      * ":let &l:option = expr": Set local option value.
1749      * ":let &g:option = expr": Set global option value.
1750      */
1751     else if (*arg == '&')
1752     {
1753 	/* Find the end of the name. */
1754 	p = find_option_end(&arg, &opt_flags);
1755 	if (p == NULL || (endchars != NULL
1756 			      && vim_strchr(endchars, *skipwhite(p)) == NULL))
1757 	    EMSG(_(e_letunexp));
1758 	else
1759 	{
1760 	    long	n;
1761 	    int		opt_type;
1762 	    long	numval;
1763 	    char_u	*stringval = NULL;
1764 	    char_u	*s;
1765 
1766 	    c1 = *p;
1767 	    *p = NUL;
1768 
1769 	    n = (long)get_tv_number(tv);
1770 	    s = get_tv_string_chk(tv);	    /* != NULL if number or string */
1771 	    if (s != NULL && op != NULL && *op != '=')
1772 	    {
1773 		opt_type = get_option_value(arg, &numval,
1774 						       &stringval, opt_flags);
1775 		if ((opt_type == 1 && *op == '.')
1776 			|| (opt_type == 0 && *op != '.'))
1777 		{
1778 		    EMSG2(_(e_letwrong), op);
1779 		    s = NULL;  /* don't set the value */
1780 		}
1781 		else
1782 		{
1783 		    if (opt_type == 1)  /* number */
1784 		    {
1785 			if (*op == '+')
1786 			    n = numval + n;
1787 			else
1788 			    n = numval - n;
1789 		    }
1790 		    else if (opt_type == 0 && stringval != NULL) /* string */
1791 		    {
1792 			s = concat_str(stringval, s);
1793 			vim_free(stringval);
1794 			stringval = s;
1795 		    }
1796 		}
1797 	    }
1798 	    if (s != NULL)
1799 	    {
1800 		set_option_value(arg, n, s, opt_flags);
1801 		arg_end = p;
1802 	    }
1803 	    *p = c1;
1804 	    vim_free(stringval);
1805 	}
1806     }
1807 
1808     /*
1809      * ":let @r = expr": Set register contents.
1810      */
1811     else if (*arg == '@')
1812     {
1813 	++arg;
1814 	if (op != NULL && (*op == '+' || *op == '-'))
1815 	    EMSG2(_(e_letwrong), op);
1816 	else if (endchars != NULL
1817 			 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
1818 	    EMSG(_(e_letunexp));
1819 	else
1820 	{
1821 	    char_u	*ptofree = NULL;
1822 	    char_u	*s;
1823 
1824 	    p = get_tv_string_chk(tv);
1825 	    if (p != NULL && op != NULL && *op == '.')
1826 	    {
1827 		s = get_reg_contents(*arg == '@' ? '"' : *arg, GREG_EXPR_SRC);
1828 		if (s != NULL)
1829 		{
1830 		    p = ptofree = concat_str(s, p);
1831 		    vim_free(s);
1832 		}
1833 	    }
1834 	    if (p != NULL)
1835 	    {
1836 		write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
1837 		arg_end = arg + 1;
1838 	    }
1839 	    vim_free(ptofree);
1840 	}
1841     }
1842 
1843     /*
1844      * ":let var = expr": Set internal variable.
1845      * ":let {expr} = expr": Idem, name made with curly braces
1846      */
1847     else if (eval_isnamec1(*arg) || *arg == '{')
1848     {
1849 	lval_T	lv;
1850 
1851 	p = get_lval(arg, tv, &lv, FALSE, FALSE, 0, FNE_CHECK_START);
1852 	if (p != NULL && lv.ll_name != NULL)
1853 	{
1854 	    if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
1855 		EMSG(_(e_letunexp));
1856 	    else
1857 	    {
1858 		set_var_lval(&lv, p, tv, copy, op);
1859 		arg_end = p;
1860 	    }
1861 	}
1862 	clear_lval(&lv);
1863     }
1864 
1865     else
1866 	EMSG2(_(e_invarg2), arg);
1867 
1868     return arg_end;
1869 }
1870 
1871 /*
1872  * Get an lval: variable, Dict item or List item that can be assigned a value
1873  * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
1874  * "name.key", "name.key[expr]" etc.
1875  * Indexing only works if "name" is an existing List or Dictionary.
1876  * "name" points to the start of the name.
1877  * If "rettv" is not NULL it points to the value to be assigned.
1878  * "unlet" is TRUE for ":unlet": slightly different behavior when something is
1879  * wrong; must end in space or cmd separator.
1880  *
1881  * flags:
1882  *  GLV_QUIET:       do not give error messages
1883  *  GLV_READ_ONLY:   will not change the variable
1884  *  GLV_NO_AUTOLOAD: do not use script autoloading
1885  *
1886  * Returns a pointer to just after the name, including indexes.
1887  * When an evaluation error occurs "lp->ll_name" is NULL;
1888  * Returns NULL for a parsing error.  Still need to free items in "lp"!
1889  */
1890     char_u *
1891 get_lval(
1892     char_u	*name,
1893     typval_T	*rettv,
1894     lval_T	*lp,
1895     int		unlet,
1896     int		skip,
1897     int		flags,	    /* GLV_ values */
1898     int		fne_flags)  /* flags for find_name_end() */
1899 {
1900     char_u	*p;
1901     char_u	*expr_start, *expr_end;
1902     int		cc;
1903     dictitem_T	*v;
1904     typval_T	var1;
1905     typval_T	var2;
1906     int		empty1 = FALSE;
1907     listitem_T	*ni;
1908     char_u	*key = NULL;
1909     int		len;
1910     hashtab_T	*ht;
1911     int		quiet = flags & GLV_QUIET;
1912 
1913     /* Clear everything in "lp". */
1914     vim_memset(lp, 0, sizeof(lval_T));
1915 
1916     if (skip)
1917     {
1918 	/* When skipping just find the end of the name. */
1919 	lp->ll_name = name;
1920 	return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
1921     }
1922 
1923     /* Find the end of the name. */
1924     p = find_name_end(name, &expr_start, &expr_end, fne_flags);
1925     if (expr_start != NULL)
1926     {
1927 	/* Don't expand the name when we already know there is an error. */
1928 	if (unlet && !VIM_ISWHITE(*p) && !ends_excmd(*p)
1929 						    && *p != '[' && *p != '.')
1930 	{
1931 	    EMSG(_(e_trailing));
1932 	    return NULL;
1933 	}
1934 
1935 	lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
1936 	if (lp->ll_exp_name == NULL)
1937 	{
1938 	    /* Report an invalid expression in braces, unless the
1939 	     * expression evaluation has been cancelled due to an
1940 	     * aborting error, an interrupt, or an exception. */
1941 	    if (!aborting() && !quiet)
1942 	    {
1943 		emsg_severe = TRUE;
1944 		EMSG2(_(e_invarg2), name);
1945 		return NULL;
1946 	    }
1947 	}
1948 	lp->ll_name = lp->ll_exp_name;
1949     }
1950     else
1951 	lp->ll_name = name;
1952 
1953     /* Without [idx] or .key we are done. */
1954     if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
1955 	return p;
1956 
1957     cc = *p;
1958     *p = NUL;
1959     /* Only pass &ht when we would write to the variable, it prevents autoload
1960      * as well. */
1961     v = find_var(lp->ll_name, (flags & GLV_READ_ONLY) ? NULL : &ht,
1962 						      flags & GLV_NO_AUTOLOAD);
1963     if (v == NULL && !quiet)
1964 	EMSG2(_(e_undefvar), lp->ll_name);
1965     *p = cc;
1966     if (v == NULL)
1967 	return NULL;
1968 
1969     /*
1970      * Loop until no more [idx] or .key is following.
1971      */
1972     lp->ll_tv = &v->di_tv;
1973     var1.v_type = VAR_UNKNOWN;
1974     var2.v_type = VAR_UNKNOWN;
1975     while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
1976     {
1977 	if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
1978 		&& !(lp->ll_tv->v_type == VAR_DICT
1979 					   && lp->ll_tv->vval.v_dict != NULL))
1980 	{
1981 	    if (!quiet)
1982 		EMSG(_("E689: Can only index a List or Dictionary"));
1983 	    return NULL;
1984 	}
1985 	if (lp->ll_range)
1986 	{
1987 	    if (!quiet)
1988 		EMSG(_("E708: [:] must come last"));
1989 	    return NULL;
1990 	}
1991 
1992 	len = -1;
1993 	if (*p == '.')
1994 	{
1995 	    key = p + 1;
1996 	    for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
1997 		;
1998 	    if (len == 0)
1999 	    {
2000 		if (!quiet)
2001 		    EMSG(_(e_emptykey));
2002 		return NULL;
2003 	    }
2004 	    p = key + len;
2005 	}
2006 	else
2007 	{
2008 	    /* Get the index [expr] or the first index [expr: ]. */
2009 	    p = skipwhite(p + 1);
2010 	    if (*p == ':')
2011 		empty1 = TRUE;
2012 	    else
2013 	    {
2014 		empty1 = FALSE;
2015 		if (eval1(&p, &var1, TRUE) == FAIL)	/* recursive! */
2016 		    return NULL;
2017 		if (get_tv_string_chk(&var1) == NULL)
2018 		{
2019 		    /* not a number or string */
2020 		    clear_tv(&var1);
2021 		    return NULL;
2022 		}
2023 	    }
2024 
2025 	    /* Optionally get the second index [ :expr]. */
2026 	    if (*p == ':')
2027 	    {
2028 		if (lp->ll_tv->v_type == VAR_DICT)
2029 		{
2030 		    if (!quiet)
2031 			EMSG(_(e_dictrange));
2032 		    clear_tv(&var1);
2033 		    return NULL;
2034 		}
2035 		if (rettv != NULL && (rettv->v_type != VAR_LIST
2036 					       || rettv->vval.v_list == NULL))
2037 		{
2038 		    if (!quiet)
2039 			EMSG(_("E709: [:] requires a List value"));
2040 		    clear_tv(&var1);
2041 		    return NULL;
2042 		}
2043 		p = skipwhite(p + 1);
2044 		if (*p == ']')
2045 		    lp->ll_empty2 = TRUE;
2046 		else
2047 		{
2048 		    lp->ll_empty2 = FALSE;
2049 		    if (eval1(&p, &var2, TRUE) == FAIL)	/* recursive! */
2050 		    {
2051 			clear_tv(&var1);
2052 			return NULL;
2053 		    }
2054 		    if (get_tv_string_chk(&var2) == NULL)
2055 		    {
2056 			/* not a number or string */
2057 			clear_tv(&var1);
2058 			clear_tv(&var2);
2059 			return NULL;
2060 		    }
2061 		}
2062 		lp->ll_range = TRUE;
2063 	    }
2064 	    else
2065 		lp->ll_range = FALSE;
2066 
2067 	    if (*p != ']')
2068 	    {
2069 		if (!quiet)
2070 		    EMSG(_(e_missbrac));
2071 		clear_tv(&var1);
2072 		clear_tv(&var2);
2073 		return NULL;
2074 	    }
2075 
2076 	    /* Skip to past ']'. */
2077 	    ++p;
2078 	}
2079 
2080 	if (lp->ll_tv->v_type == VAR_DICT)
2081 	{
2082 	    if (len == -1)
2083 	    {
2084 		/* "[key]": get key from "var1" */
2085 		key = get_tv_string_chk(&var1);	/* is number or string */
2086 		if (key == NULL)
2087 		{
2088 		    clear_tv(&var1);
2089 		    return NULL;
2090 		}
2091 	    }
2092 	    lp->ll_list = NULL;
2093 	    lp->ll_dict = lp->ll_tv->vval.v_dict;
2094 	    lp->ll_di = dict_find(lp->ll_dict, key, len);
2095 
2096 	    /* When assigning to a scope dictionary check that a function and
2097 	     * variable name is valid (only variable name unless it is l: or
2098 	     * g: dictionary). Disallow overwriting a builtin function. */
2099 	    if (rettv != NULL && lp->ll_dict->dv_scope != 0)
2100 	    {
2101 		int prevval;
2102 		int wrong;
2103 
2104 		if (len != -1)
2105 		{
2106 		    prevval = key[len];
2107 		    key[len] = NUL;
2108 		}
2109 		else
2110 		    prevval = 0; /* avoid compiler warning */
2111 		wrong = (lp->ll_dict->dv_scope == VAR_DEF_SCOPE
2112 			       && rettv->v_type == VAR_FUNC
2113 			       && var_check_func_name(key, lp->ll_di == NULL))
2114 			|| !valid_varname(key);
2115 		if (len != -1)
2116 		    key[len] = prevval;
2117 		if (wrong)
2118 		    return NULL;
2119 	    }
2120 
2121 	    if (lp->ll_di == NULL)
2122 	    {
2123 		/* Can't add "v:" variable. */
2124 		if (lp->ll_dict == &vimvardict)
2125 		{
2126 		    EMSG2(_(e_illvar), name);
2127 		    return NULL;
2128 		}
2129 
2130 		/* Key does not exist in dict: may need to add it. */
2131 		if (*p == '[' || *p == '.' || unlet)
2132 		{
2133 		    if (!quiet)
2134 			EMSG2(_(e_dictkey), key);
2135 		    clear_tv(&var1);
2136 		    return NULL;
2137 		}
2138 		if (len == -1)
2139 		    lp->ll_newkey = vim_strsave(key);
2140 		else
2141 		    lp->ll_newkey = vim_strnsave(key, len);
2142 		clear_tv(&var1);
2143 		if (lp->ll_newkey == NULL)
2144 		    p = NULL;
2145 		break;
2146 	    }
2147 	    /* existing variable, need to check if it can be changed */
2148 	    else if ((flags & GLV_READ_ONLY) == 0
2149 			     && var_check_ro(lp->ll_di->di_flags, name, FALSE))
2150 	    {
2151 		clear_tv(&var1);
2152 		return NULL;
2153 	    }
2154 
2155 	    clear_tv(&var1);
2156 	    lp->ll_tv = &lp->ll_di->di_tv;
2157 	}
2158 	else
2159 	{
2160 	    /*
2161 	     * Get the number and item for the only or first index of the List.
2162 	     */
2163 	    if (empty1)
2164 		lp->ll_n1 = 0;
2165 	    else
2166 		/* is number or string */
2167 		lp->ll_n1 = (long)get_tv_number(&var1);
2168 	    clear_tv(&var1);
2169 
2170 	    lp->ll_dict = NULL;
2171 	    lp->ll_list = lp->ll_tv->vval.v_list;
2172 	    lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2173 	    if (lp->ll_li == NULL)
2174 	    {
2175 		if (lp->ll_n1 < 0)
2176 		{
2177 		    lp->ll_n1 = 0;
2178 		    lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2179 		}
2180 	    }
2181 	    if (lp->ll_li == NULL)
2182 	    {
2183 		clear_tv(&var2);
2184 		if (!quiet)
2185 		    EMSGN(_(e_listidx), lp->ll_n1);
2186 		return NULL;
2187 	    }
2188 
2189 	    /*
2190 	     * May need to find the item or absolute index for the second
2191 	     * index of a range.
2192 	     * When no index given: "lp->ll_empty2" is TRUE.
2193 	     * Otherwise "lp->ll_n2" is set to the second index.
2194 	     */
2195 	    if (lp->ll_range && !lp->ll_empty2)
2196 	    {
2197 		lp->ll_n2 = (long)get_tv_number(&var2);
2198 						    /* is number or string */
2199 		clear_tv(&var2);
2200 		if (lp->ll_n2 < 0)
2201 		{
2202 		    ni = list_find(lp->ll_list, lp->ll_n2);
2203 		    if (ni == NULL)
2204 		    {
2205 			if (!quiet)
2206 			    EMSGN(_(e_listidx), lp->ll_n2);
2207 			return NULL;
2208 		    }
2209 		    lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2210 		}
2211 
2212 		/* Check that lp->ll_n2 isn't before lp->ll_n1. */
2213 		if (lp->ll_n1 < 0)
2214 		    lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2215 		if (lp->ll_n2 < lp->ll_n1)
2216 		{
2217 		    if (!quiet)
2218 			EMSGN(_(e_listidx), lp->ll_n2);
2219 		    return NULL;
2220 		}
2221 	    }
2222 
2223 	    lp->ll_tv = &lp->ll_li->li_tv;
2224 	}
2225     }
2226 
2227     clear_tv(&var1);
2228     return p;
2229 }
2230 
2231 /*
2232  * Clear lval "lp" that was filled by get_lval().
2233  */
2234     void
2235 clear_lval(lval_T *lp)
2236 {
2237     vim_free(lp->ll_exp_name);
2238     vim_free(lp->ll_newkey);
2239 }
2240 
2241 /*
2242  * Set a variable that was parsed by get_lval() to "rettv".
2243  * "endp" points to just after the parsed name.
2244  * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2245  */
2246     static void
2247 set_var_lval(
2248     lval_T	*lp,
2249     char_u	*endp,
2250     typval_T	*rettv,
2251     int		copy,
2252     char_u	*op)
2253 {
2254     int		cc;
2255     listitem_T	*ri;
2256     dictitem_T	*di;
2257 
2258     if (lp->ll_tv == NULL)
2259     {
2260 	cc = *endp;
2261 	*endp = NUL;
2262 	if (op != NULL && *op != '=')
2263 	{
2264 	    typval_T tv;
2265 
2266 	    /* handle +=, -= and .= */
2267 	    di = NULL;
2268 	    if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2269 					     &tv, &di, TRUE, FALSE) == OK)
2270 	    {
2271 		if ((di == NULL
2272 		       || (!var_check_ro(di->di_flags, lp->ll_name, FALSE)
2273 			  && !tv_check_lock(di->di_tv.v_lock, lp->ll_name,
2274 								  FALSE)))
2275 			&& tv_op(&tv, rettv, op) == OK)
2276 		    set_var(lp->ll_name, &tv, FALSE);
2277 		clear_tv(&tv);
2278 	    }
2279 	}
2280 	else
2281 	    set_var(lp->ll_name, rettv, copy);
2282 	*endp = cc;
2283     }
2284     else if (tv_check_lock(lp->ll_newkey == NULL
2285 		? lp->ll_tv->v_lock
2286 		: lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name, FALSE))
2287 	;
2288     else if (lp->ll_range)
2289     {
2290 	listitem_T *ll_li = lp->ll_li;
2291 	int ll_n1 = lp->ll_n1;
2292 
2293 	/*
2294 	 * Check whether any of the list items is locked
2295 	 */
2296 	for (ri = rettv->vval.v_list->lv_first; ri != NULL && ll_li != NULL; )
2297 	{
2298 	    if (tv_check_lock(ll_li->li_tv.v_lock, lp->ll_name, FALSE))
2299 		return;
2300 	    ri = ri->li_next;
2301 	    if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == ll_n1))
2302 		break;
2303 	    ll_li = ll_li->li_next;
2304 	    ++ll_n1;
2305 	}
2306 
2307 	/*
2308 	 * Assign the List values to the list items.
2309 	 */
2310 	for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2311 	{
2312 	    if (op != NULL && *op != '=')
2313 		tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2314 	    else
2315 	    {
2316 		clear_tv(&lp->ll_li->li_tv);
2317 		copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2318 	    }
2319 	    ri = ri->li_next;
2320 	    if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2321 		break;
2322 	    if (lp->ll_li->li_next == NULL)
2323 	    {
2324 		/* Need to add an empty item. */
2325 		if (list_append_number(lp->ll_list, 0) == FAIL)
2326 		{
2327 		    ri = NULL;
2328 		    break;
2329 		}
2330 	    }
2331 	    lp->ll_li = lp->ll_li->li_next;
2332 	    ++lp->ll_n1;
2333 	}
2334 	if (ri != NULL)
2335 	    EMSG(_("E710: List value has more items than target"));
2336 	else if (lp->ll_empty2
2337 		? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2338 		: lp->ll_n1 != lp->ll_n2)
2339 	    EMSG(_("E711: List value has not enough items"));
2340     }
2341     else
2342     {
2343 	/*
2344 	 * Assign to a List or Dictionary item.
2345 	 */
2346 	if (lp->ll_newkey != NULL)
2347 	{
2348 	    if (op != NULL && *op != '=')
2349 	    {
2350 		EMSG2(_(e_letwrong), op);
2351 		return;
2352 	    }
2353 
2354 	    /* Need to add an item to the Dictionary. */
2355 	    di = dictitem_alloc(lp->ll_newkey);
2356 	    if (di == NULL)
2357 		return;
2358 	    if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2359 	    {
2360 		vim_free(di);
2361 		return;
2362 	    }
2363 	    lp->ll_tv = &di->di_tv;
2364 	}
2365 	else if (op != NULL && *op != '=')
2366 	{
2367 	    tv_op(lp->ll_tv, rettv, op);
2368 	    return;
2369 	}
2370 	else
2371 	    clear_tv(lp->ll_tv);
2372 
2373 	/*
2374 	 * Assign the value to the variable or list item.
2375 	 */
2376 	if (copy)
2377 	    copy_tv(rettv, lp->ll_tv);
2378 	else
2379 	{
2380 	    *lp->ll_tv = *rettv;
2381 	    lp->ll_tv->v_lock = 0;
2382 	    init_tv(rettv);
2383 	}
2384     }
2385 }
2386 
2387 /*
2388  * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2389  * Returns OK or FAIL.
2390  */
2391     static int
2392 tv_op(typval_T *tv1, typval_T *tv2, char_u *op)
2393 {
2394     varnumber_T	n;
2395     char_u	numbuf[NUMBUFLEN];
2396     char_u	*s;
2397 
2398     /* Can't do anything with a Funcref, Dict, v:true on the right. */
2399     if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT
2400 						&& tv2->v_type != VAR_SPECIAL)
2401     {
2402 	switch (tv1->v_type)
2403 	{
2404 	    case VAR_UNKNOWN:
2405 	    case VAR_DICT:
2406 	    case VAR_FUNC:
2407 	    case VAR_PARTIAL:
2408 	    case VAR_SPECIAL:
2409 	    case VAR_JOB:
2410 	    case VAR_CHANNEL:
2411 		break;
2412 
2413 	    case VAR_LIST:
2414 		if (*op != '+' || tv2->v_type != VAR_LIST)
2415 		    break;
2416 		/* List += List */
2417 		if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2418 		    list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2419 		return OK;
2420 
2421 	    case VAR_NUMBER:
2422 	    case VAR_STRING:
2423 		if (tv2->v_type == VAR_LIST)
2424 		    break;
2425 		if (*op == '+' || *op == '-')
2426 		{
2427 		    /* nr += nr  or  nr -= nr*/
2428 		    n = get_tv_number(tv1);
2429 #ifdef FEAT_FLOAT
2430 		    if (tv2->v_type == VAR_FLOAT)
2431 		    {
2432 			float_T f = n;
2433 
2434 			if (*op == '+')
2435 			    f += tv2->vval.v_float;
2436 			else
2437 			    f -= tv2->vval.v_float;
2438 			clear_tv(tv1);
2439 			tv1->v_type = VAR_FLOAT;
2440 			tv1->vval.v_float = f;
2441 		    }
2442 		    else
2443 #endif
2444 		    {
2445 			if (*op == '+')
2446 			    n += get_tv_number(tv2);
2447 			else
2448 			    n -= get_tv_number(tv2);
2449 			clear_tv(tv1);
2450 			tv1->v_type = VAR_NUMBER;
2451 			tv1->vval.v_number = n;
2452 		    }
2453 		}
2454 		else
2455 		{
2456 		    if (tv2->v_type == VAR_FLOAT)
2457 			break;
2458 
2459 		    /* str .= str */
2460 		    s = get_tv_string(tv1);
2461 		    s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2462 		    clear_tv(tv1);
2463 		    tv1->v_type = VAR_STRING;
2464 		    tv1->vval.v_string = s;
2465 		}
2466 		return OK;
2467 
2468 	    case VAR_FLOAT:
2469 #ifdef FEAT_FLOAT
2470 		{
2471 		    float_T f;
2472 
2473 		    if (*op == '.' || (tv2->v_type != VAR_FLOAT
2474 				    && tv2->v_type != VAR_NUMBER
2475 				    && tv2->v_type != VAR_STRING))
2476 			break;
2477 		    if (tv2->v_type == VAR_FLOAT)
2478 			f = tv2->vval.v_float;
2479 		    else
2480 			f = get_tv_number(tv2);
2481 		    if (*op == '+')
2482 			tv1->vval.v_float += f;
2483 		    else
2484 			tv1->vval.v_float -= f;
2485 		}
2486 #endif
2487 		return OK;
2488 	}
2489     }
2490 
2491     EMSG2(_(e_letwrong), op);
2492     return FAIL;
2493 }
2494 
2495 /*
2496  * Evaluate the expression used in a ":for var in expr" command.
2497  * "arg" points to "var".
2498  * Set "*errp" to TRUE for an error, FALSE otherwise;
2499  * Return a pointer that holds the info.  Null when there is an error.
2500  */
2501     void *
2502 eval_for_line(
2503     char_u	*arg,
2504     int		*errp,
2505     char_u	**nextcmdp,
2506     int		skip)
2507 {
2508     forinfo_T	*fi;
2509     char_u	*expr;
2510     typval_T	tv;
2511     list_T	*l;
2512 
2513     *errp = TRUE;	/* default: there is an error */
2514 
2515     fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
2516     if (fi == NULL)
2517 	return NULL;
2518 
2519     expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
2520     if (expr == NULL)
2521 	return fi;
2522 
2523     expr = skipwhite(expr);
2524     if (expr[0] != 'i' || expr[1] != 'n' || !VIM_ISWHITE(expr[2]))
2525     {
2526 	EMSG(_("E690: Missing \"in\" after :for"));
2527 	return fi;
2528     }
2529 
2530     if (skip)
2531 	++emsg_skip;
2532     if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
2533     {
2534 	*errp = FALSE;
2535 	if (!skip)
2536 	{
2537 	    l = tv.vval.v_list;
2538 	    if (tv.v_type != VAR_LIST)
2539 	    {
2540 		EMSG(_(e_listreq));
2541 		clear_tv(&tv);
2542 	    }
2543 	    else if (l == NULL)
2544 	    {
2545 		/* a null list is like an empty list: do nothing */
2546 		clear_tv(&tv);
2547 	    }
2548 	    else
2549 	    {
2550 		/* No need to increment the refcount, it's already set for the
2551 		 * list being used in "tv". */
2552 		fi->fi_list = l;
2553 		list_add_watch(l, &fi->fi_lw);
2554 		fi->fi_lw.lw_item = l->lv_first;
2555 	    }
2556 	}
2557     }
2558     if (skip)
2559 	--emsg_skip;
2560 
2561     return fi;
2562 }
2563 
2564 /*
2565  * Use the first item in a ":for" list.  Advance to the next.
2566  * Assign the values to the variable (list).  "arg" points to the first one.
2567  * Return TRUE when a valid item was found, FALSE when at end of list or
2568  * something wrong.
2569  */
2570     int
2571 next_for_item(void *fi_void, char_u *arg)
2572 {
2573     forinfo_T	*fi = (forinfo_T *)fi_void;
2574     int		result;
2575     listitem_T	*item;
2576 
2577     item = fi->fi_lw.lw_item;
2578     if (item == NULL)
2579 	result = FALSE;
2580     else
2581     {
2582 	fi->fi_lw.lw_item = item->li_next;
2583 	result = (ex_let_vars(arg, &item->li_tv, TRUE,
2584 			      fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
2585     }
2586     return result;
2587 }
2588 
2589 /*
2590  * Free the structure used to store info used by ":for".
2591  */
2592     void
2593 free_for_info(void *fi_void)
2594 {
2595     forinfo_T    *fi = (forinfo_T *)fi_void;
2596 
2597     if (fi != NULL && fi->fi_list != NULL)
2598     {
2599 	list_rem_watch(fi->fi_list, &fi->fi_lw);
2600 	list_unref(fi->fi_list);
2601     }
2602     vim_free(fi);
2603 }
2604 
2605 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2606 
2607     void
2608 set_context_for_expression(
2609     expand_T	*xp,
2610     char_u	*arg,
2611     cmdidx_T	cmdidx)
2612 {
2613     int		got_eq = FALSE;
2614     int		c;
2615     char_u	*p;
2616 
2617     if (cmdidx == CMD_let)
2618     {
2619 	xp->xp_context = EXPAND_USER_VARS;
2620 	if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
2621 	{
2622 	    /* ":let var1 var2 ...": find last space. */
2623 	    for (p = arg + STRLEN(arg); p >= arg; )
2624 	    {
2625 		xp->xp_pattern = p;
2626 		MB_PTR_BACK(arg, p);
2627 		if (VIM_ISWHITE(*p))
2628 		    break;
2629 	    }
2630 	    return;
2631 	}
2632     }
2633     else
2634 	xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
2635 							  : EXPAND_EXPRESSION;
2636     while ((xp->xp_pattern = vim_strpbrk(arg,
2637 				  (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
2638     {
2639 	c = *xp->xp_pattern;
2640 	if (c == '&')
2641 	{
2642 	    c = xp->xp_pattern[1];
2643 	    if (c == '&')
2644 	    {
2645 		++xp->xp_pattern;
2646 		xp->xp_context = cmdidx != CMD_let || got_eq
2647 					 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
2648 	    }
2649 	    else if (c != ' ')
2650 	    {
2651 		xp->xp_context = EXPAND_SETTINGS;
2652 		if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
2653 		    xp->xp_pattern += 2;
2654 
2655 	    }
2656 	}
2657 	else if (c == '$')
2658 	{
2659 	    /* environment variable */
2660 	    xp->xp_context = EXPAND_ENV_VARS;
2661 	}
2662 	else if (c == '=')
2663 	{
2664 	    got_eq = TRUE;
2665 	    xp->xp_context = EXPAND_EXPRESSION;
2666 	}
2667 	else if (c == '#'
2668 		&& xp->xp_context == EXPAND_EXPRESSION)
2669 	{
2670 	    /* Autoload function/variable contains '#'. */
2671 	    break;
2672 	}
2673 	else if ((c == '<' || c == '#')
2674 		&& xp->xp_context == EXPAND_FUNCTIONS
2675 		&& vim_strchr(xp->xp_pattern, '(') == NULL)
2676 	{
2677 	    /* Function name can start with "<SNR>" and contain '#'. */
2678 	    break;
2679 	}
2680 	else if (cmdidx != CMD_let || got_eq)
2681 	{
2682 	    if (c == '"')	    /* string */
2683 	    {
2684 		while ((c = *++xp->xp_pattern) != NUL && c != '"')
2685 		    if (c == '\\' && xp->xp_pattern[1] != NUL)
2686 			++xp->xp_pattern;
2687 		xp->xp_context = EXPAND_NOTHING;
2688 	    }
2689 	    else if (c == '\'')	    /* literal string */
2690 	    {
2691 		/* Trick: '' is like stopping and starting a literal string. */
2692 		while ((c = *++xp->xp_pattern) != NUL && c != '\'')
2693 		    /* skip */ ;
2694 		xp->xp_context = EXPAND_NOTHING;
2695 	    }
2696 	    else if (c == '|')
2697 	    {
2698 		if (xp->xp_pattern[1] == '|')
2699 		{
2700 		    ++xp->xp_pattern;
2701 		    xp->xp_context = EXPAND_EXPRESSION;
2702 		}
2703 		else
2704 		    xp->xp_context = EXPAND_COMMANDS;
2705 	    }
2706 	    else
2707 		xp->xp_context = EXPAND_EXPRESSION;
2708 	}
2709 	else
2710 	    /* Doesn't look like something valid, expand as an expression
2711 	     * anyway. */
2712 	    xp->xp_context = EXPAND_EXPRESSION;
2713 	arg = xp->xp_pattern;
2714 	if (*arg != NUL)
2715 	    while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
2716 		/* skip */ ;
2717     }
2718     xp->xp_pattern = arg;
2719 }
2720 
2721 #endif /* FEAT_CMDL_COMPL */
2722 
2723 /*
2724  * ":unlet[!] var1 ... " command.
2725  */
2726     void
2727 ex_unlet(exarg_T *eap)
2728 {
2729     ex_unletlock(eap, eap->arg, 0);
2730 }
2731 
2732 /*
2733  * ":lockvar" and ":unlockvar" commands
2734  */
2735     void
2736 ex_lockvar(exarg_T *eap)
2737 {
2738     char_u	*arg = eap->arg;
2739     int		deep = 2;
2740 
2741     if (eap->forceit)
2742 	deep = -1;
2743     else if (vim_isdigit(*arg))
2744     {
2745 	deep = getdigits(&arg);
2746 	arg = skipwhite(arg);
2747     }
2748 
2749     ex_unletlock(eap, arg, deep);
2750 }
2751 
2752 /*
2753  * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
2754  */
2755     static void
2756 ex_unletlock(
2757     exarg_T	*eap,
2758     char_u	*argstart,
2759     int		deep)
2760 {
2761     char_u	*arg = argstart;
2762     char_u	*name_end;
2763     int		error = FALSE;
2764     lval_T	lv;
2765 
2766     do
2767     {
2768 	/* Parse the name and find the end. */
2769 	name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, 0,
2770 							     FNE_CHECK_START);
2771 	if (lv.ll_name == NULL)
2772 	    error = TRUE;	    /* error but continue parsing */
2773 	if (name_end == NULL || (!VIM_ISWHITE(*name_end)
2774 						   && !ends_excmd(*name_end)))
2775 	{
2776 	    if (name_end != NULL)
2777 	    {
2778 		emsg_severe = TRUE;
2779 		EMSG(_(e_trailing));
2780 	    }
2781 	    if (!(eap->skip || error))
2782 		clear_lval(&lv);
2783 	    break;
2784 	}
2785 
2786 	if (!error && !eap->skip)
2787 	{
2788 	    if (eap->cmdidx == CMD_unlet)
2789 	    {
2790 		if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
2791 		    error = TRUE;
2792 	    }
2793 	    else
2794 	    {
2795 		if (do_lock_var(&lv, name_end, deep,
2796 					  eap->cmdidx == CMD_lockvar) == FAIL)
2797 		    error = TRUE;
2798 	    }
2799 	}
2800 
2801 	if (!eap->skip)
2802 	    clear_lval(&lv);
2803 
2804 	arg = skipwhite(name_end);
2805     } while (!ends_excmd(*arg));
2806 
2807     eap->nextcmd = check_nextcmd(arg);
2808 }
2809 
2810     static int
2811 do_unlet_var(
2812     lval_T	*lp,
2813     char_u	*name_end,
2814     int		forceit)
2815 {
2816     int		ret = OK;
2817     int		cc;
2818 
2819     if (lp->ll_tv == NULL)
2820     {
2821 	cc = *name_end;
2822 	*name_end = NUL;
2823 
2824 	/* Normal name or expanded name. */
2825 	if (do_unlet(lp->ll_name, forceit) == FAIL)
2826 	    ret = FAIL;
2827 	*name_end = cc;
2828     }
2829     else if ((lp->ll_list != NULL
2830 		   && tv_check_lock(lp->ll_list->lv_lock, lp->ll_name, FALSE))
2831 	    || (lp->ll_dict != NULL
2832 		  && tv_check_lock(lp->ll_dict->dv_lock, lp->ll_name, FALSE)))
2833 	return FAIL;
2834     else if (lp->ll_range)
2835     {
2836 	listitem_T    *li;
2837 	listitem_T    *ll_li = lp->ll_li;
2838 	int	      ll_n1 = lp->ll_n1;
2839 
2840 	while (ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= ll_n1))
2841 	{
2842 	    li = ll_li->li_next;
2843 	    if (tv_check_lock(ll_li->li_tv.v_lock, lp->ll_name, FALSE))
2844 		return FAIL;
2845 	    ll_li = li;
2846 	    ++ll_n1;
2847 	}
2848 
2849 	/* Delete a range of List items. */
2850 	while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
2851 	{
2852 	    li = lp->ll_li->li_next;
2853 	    listitem_remove(lp->ll_list, lp->ll_li);
2854 	    lp->ll_li = li;
2855 	    ++lp->ll_n1;
2856 	}
2857     }
2858     else
2859     {
2860 	if (lp->ll_list != NULL)
2861 	    /* unlet a List item. */
2862 	    listitem_remove(lp->ll_list, lp->ll_li);
2863 	else
2864 	    /* unlet a Dictionary item. */
2865 	    dictitem_remove(lp->ll_dict, lp->ll_di);
2866     }
2867 
2868     return ret;
2869 }
2870 
2871 /*
2872  * "unlet" a variable.  Return OK if it existed, FAIL if not.
2873  * When "forceit" is TRUE don't complain if the variable doesn't exist.
2874  */
2875     int
2876 do_unlet(char_u *name, int forceit)
2877 {
2878     hashtab_T	*ht;
2879     hashitem_T	*hi;
2880     char_u	*varname;
2881     dict_T	*d;
2882     dictitem_T	*di;
2883 
2884     ht = find_var_ht(name, &varname);
2885     if (ht != NULL && *varname != NUL)
2886     {
2887 	d = get_current_funccal_dict(ht);
2888 	if (d == NULL)
2889 	{
2890 	    if (ht == &globvarht)
2891 		d = &globvardict;
2892 	    else if (ht == &compat_hashtab)
2893 		d = &vimvardict;
2894 	    else
2895 	    {
2896 		di = find_var_in_ht(ht, *name, (char_u *)"", FALSE);
2897 		d = di == NULL ? NULL : di->di_tv.vval.v_dict;
2898 	    }
2899 	    if (d == NULL)
2900 	    {
2901 		internal_error("do_unlet()");
2902 		return FAIL;
2903 	    }
2904 	}
2905 	hi = hash_find(ht, varname);
2906 	if (HASHITEM_EMPTY(hi))
2907 	    hi = find_hi_in_scoped_ht(name, &ht);
2908 	if (hi != NULL && !HASHITEM_EMPTY(hi))
2909 	{
2910 	    di = HI2DI(hi);
2911 	    if (var_check_fixed(di->di_flags, name, FALSE)
2912 		    || var_check_ro(di->di_flags, name, FALSE)
2913 		    || tv_check_lock(d->dv_lock, name, FALSE))
2914 		return FAIL;
2915 
2916 	    delete_var(ht, hi);
2917 	    return OK;
2918 	}
2919     }
2920     if (forceit)
2921 	return OK;
2922     EMSG2(_("E108: No such variable: \"%s\""), name);
2923     return FAIL;
2924 }
2925 
2926 /*
2927  * Lock or unlock variable indicated by "lp".
2928  * "deep" is the levels to go (-1 for unlimited);
2929  * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
2930  */
2931     static int
2932 do_lock_var(
2933     lval_T	*lp,
2934     char_u	*name_end,
2935     int		deep,
2936     int		lock)
2937 {
2938     int		ret = OK;
2939     int		cc;
2940     dictitem_T	*di;
2941 
2942     if (deep == 0)	/* nothing to do */
2943 	return OK;
2944 
2945     if (lp->ll_tv == NULL)
2946     {
2947 	cc = *name_end;
2948 	*name_end = NUL;
2949 
2950 	/* Normal name or expanded name. */
2951 	di = find_var(lp->ll_name, NULL, TRUE);
2952 	if (di == NULL)
2953 	    ret = FAIL;
2954 	else if ((di->di_flags & DI_FLAGS_FIX)
2955 			&& di->di_tv.v_type != VAR_DICT
2956 			&& di->di_tv.v_type != VAR_LIST)
2957 	    /* For historic reasons this error is not given for a list or dict.
2958 	     * E.g., the b: dict could be locked/unlocked. */
2959 	    EMSG2(_("E940: Cannot lock or unlock variable %s"), lp->ll_name);
2960 	else
2961 	{
2962 	    if (lock)
2963 		di->di_flags |= DI_FLAGS_LOCK;
2964 	    else
2965 		di->di_flags &= ~DI_FLAGS_LOCK;
2966 	    item_lock(&di->di_tv, deep, lock);
2967 	}
2968 	*name_end = cc;
2969     }
2970     else if (lp->ll_range)
2971     {
2972 	listitem_T    *li = lp->ll_li;
2973 
2974 	/* (un)lock a range of List items. */
2975 	while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
2976 	{
2977 	    item_lock(&li->li_tv, deep, lock);
2978 	    li = li->li_next;
2979 	    ++lp->ll_n1;
2980 	}
2981     }
2982     else if (lp->ll_list != NULL)
2983 	/* (un)lock a List item. */
2984 	item_lock(&lp->ll_li->li_tv, deep, lock);
2985     else
2986 	/* (un)lock a Dictionary item. */
2987 	item_lock(&lp->ll_di->di_tv, deep, lock);
2988 
2989     return ret;
2990 }
2991 
2992 /*
2993  * Lock or unlock an item.  "deep" is nr of levels to go.
2994  */
2995     static void
2996 item_lock(typval_T *tv, int deep, int lock)
2997 {
2998     static int	recurse = 0;
2999     list_T	*l;
3000     listitem_T	*li;
3001     dict_T	*d;
3002     hashitem_T	*hi;
3003     int		todo;
3004 
3005     if (recurse >= DICT_MAXNEST)
3006     {
3007 	EMSG(_("E743: variable nested too deep for (un)lock"));
3008 	return;
3009     }
3010     if (deep == 0)
3011 	return;
3012     ++recurse;
3013 
3014     /* lock/unlock the item itself */
3015     if (lock)
3016 	tv->v_lock |= VAR_LOCKED;
3017     else
3018 	tv->v_lock &= ~VAR_LOCKED;
3019 
3020     switch (tv->v_type)
3021     {
3022 	case VAR_UNKNOWN:
3023 	case VAR_NUMBER:
3024 	case VAR_STRING:
3025 	case VAR_FUNC:
3026 	case VAR_PARTIAL:
3027 	case VAR_FLOAT:
3028 	case VAR_SPECIAL:
3029 	case VAR_JOB:
3030 	case VAR_CHANNEL:
3031 	    break;
3032 
3033 	case VAR_LIST:
3034 	    if ((l = tv->vval.v_list) != NULL)
3035 	    {
3036 		if (lock)
3037 		    l->lv_lock |= VAR_LOCKED;
3038 		else
3039 		    l->lv_lock &= ~VAR_LOCKED;
3040 		if (deep < 0 || deep > 1)
3041 		    /* recursive: lock/unlock the items the List contains */
3042 		    for (li = l->lv_first; li != NULL; li = li->li_next)
3043 			item_lock(&li->li_tv, deep - 1, lock);
3044 	    }
3045 	    break;
3046 	case VAR_DICT:
3047 	    if ((d = tv->vval.v_dict) != NULL)
3048 	    {
3049 		if (lock)
3050 		    d->dv_lock |= VAR_LOCKED;
3051 		else
3052 		    d->dv_lock &= ~VAR_LOCKED;
3053 		if (deep < 0 || deep > 1)
3054 		{
3055 		    /* recursive: lock/unlock the items the List contains */
3056 		    todo = (int)d->dv_hashtab.ht_used;
3057 		    for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3058 		    {
3059 			if (!HASHITEM_EMPTY(hi))
3060 			{
3061 			    --todo;
3062 			    item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3063 			}
3064 		    }
3065 		}
3066 	    }
3067     }
3068     --recurse;
3069 }
3070 
3071 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3072 /*
3073  * Delete all "menutrans_" variables.
3074  */
3075     void
3076 del_menutrans_vars(void)
3077 {
3078     hashitem_T	*hi;
3079     int		todo;
3080 
3081     hash_lock(&globvarht);
3082     todo = (int)globvarht.ht_used;
3083     for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3084     {
3085 	if (!HASHITEM_EMPTY(hi))
3086 	{
3087 	    --todo;
3088 	    if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3089 		delete_var(&globvarht, hi);
3090 	}
3091     }
3092     hash_unlock(&globvarht);
3093 }
3094 #endif
3095 
3096 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3097 
3098 /*
3099  * Local string buffer for the next two functions to store a variable name
3100  * with its prefix. Allocated in cat_prefix_varname(), freed later in
3101  * get_user_var_name().
3102  */
3103 
3104 static char_u *cat_prefix_varname(int prefix, char_u *name);
3105 
3106 static char_u	*varnamebuf = NULL;
3107 static int	varnamebuflen = 0;
3108 
3109 /*
3110  * Function to concatenate a prefix and a variable name.
3111  */
3112     static char_u *
3113 cat_prefix_varname(int prefix, char_u *name)
3114 {
3115     int		len;
3116 
3117     len = (int)STRLEN(name) + 3;
3118     if (len > varnamebuflen)
3119     {
3120 	vim_free(varnamebuf);
3121 	len += 10;			/* some additional space */
3122 	varnamebuf = alloc(len);
3123 	if (varnamebuf == NULL)
3124 	{
3125 	    varnamebuflen = 0;
3126 	    return NULL;
3127 	}
3128 	varnamebuflen = len;
3129     }
3130     *varnamebuf = prefix;
3131     varnamebuf[1] = ':';
3132     STRCPY(varnamebuf + 2, name);
3133     return varnamebuf;
3134 }
3135 
3136 /*
3137  * Function given to ExpandGeneric() to obtain the list of user defined
3138  * (global/buffer/window/built-in) variable names.
3139  */
3140     char_u *
3141 get_user_var_name(expand_T *xp, int idx)
3142 {
3143     static long_u	gdone;
3144     static long_u	bdone;
3145     static long_u	wdone;
3146     static long_u	tdone;
3147     static int		vidx;
3148     static hashitem_T	*hi;
3149     hashtab_T		*ht;
3150 
3151     if (idx == 0)
3152     {
3153 	gdone = bdone = wdone = vidx = 0;
3154 	tdone = 0;
3155     }
3156 
3157     /* Global variables */
3158     if (gdone < globvarht.ht_used)
3159     {
3160 	if (gdone++ == 0)
3161 	    hi = globvarht.ht_array;
3162 	else
3163 	    ++hi;
3164 	while (HASHITEM_EMPTY(hi))
3165 	    ++hi;
3166 	if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3167 	    return cat_prefix_varname('g', hi->hi_key);
3168 	return hi->hi_key;
3169     }
3170 
3171     /* b: variables */
3172     ht = &curbuf->b_vars->dv_hashtab;
3173     if (bdone < ht->ht_used)
3174     {
3175 	if (bdone++ == 0)
3176 	    hi = ht->ht_array;
3177 	else
3178 	    ++hi;
3179 	while (HASHITEM_EMPTY(hi))
3180 	    ++hi;
3181 	return cat_prefix_varname('b', hi->hi_key);
3182     }
3183 
3184     /* w: variables */
3185     ht = &curwin->w_vars->dv_hashtab;
3186     if (wdone < ht->ht_used)
3187     {
3188 	if (wdone++ == 0)
3189 	    hi = ht->ht_array;
3190 	else
3191 	    ++hi;
3192 	while (HASHITEM_EMPTY(hi))
3193 	    ++hi;
3194 	return cat_prefix_varname('w', hi->hi_key);
3195     }
3196 
3197     /* t: variables */
3198     ht = &curtab->tp_vars->dv_hashtab;
3199     if (tdone < ht->ht_used)
3200     {
3201 	if (tdone++ == 0)
3202 	    hi = ht->ht_array;
3203 	else
3204 	    ++hi;
3205 	while (HASHITEM_EMPTY(hi))
3206 	    ++hi;
3207 	return cat_prefix_varname('t', hi->hi_key);
3208     }
3209 
3210     /* v: variables */
3211     if (vidx < VV_LEN)
3212 	return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3213 
3214     vim_free(varnamebuf);
3215     varnamebuf = NULL;
3216     varnamebuflen = 0;
3217     return NULL;
3218 }
3219 
3220 #endif /* FEAT_CMDL_COMPL */
3221 
3222 /*
3223  * Return TRUE if "pat" matches "text".
3224  * Does not use 'cpo' and always uses 'magic'.
3225  */
3226     static int
3227 pattern_match(char_u *pat, char_u *text, int ic)
3228 {
3229     int		matches = FALSE;
3230     char_u	*save_cpo;
3231     regmatch_T	regmatch;
3232 
3233     /* avoid 'l' flag in 'cpoptions' */
3234     save_cpo = p_cpo;
3235     p_cpo = (char_u *)"";
3236     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
3237     if (regmatch.regprog != NULL)
3238     {
3239 	regmatch.rm_ic = ic;
3240 	matches = vim_regexec_nl(&regmatch, text, (colnr_T)0);
3241 	vim_regfree(regmatch.regprog);
3242     }
3243     p_cpo = save_cpo;
3244     return matches;
3245 }
3246 
3247 /*
3248  * types for expressions.
3249  */
3250 typedef enum
3251 {
3252     TYPE_UNKNOWN = 0
3253     , TYPE_EQUAL	/* == */
3254     , TYPE_NEQUAL	/* != */
3255     , TYPE_GREATER	/* >  */
3256     , TYPE_GEQUAL	/* >= */
3257     , TYPE_SMALLER	/* <  */
3258     , TYPE_SEQUAL	/* <= */
3259     , TYPE_MATCH	/* =~ */
3260     , TYPE_NOMATCH	/* !~ */
3261 } exptype_T;
3262 
3263 /*
3264  * The "evaluate" argument: When FALSE, the argument is only parsed but not
3265  * executed.  The function may return OK, but the rettv will be of type
3266  * VAR_UNKNOWN.  The function still returns FAIL for a syntax error.
3267  */
3268 
3269 /*
3270  * Handle zero level expression.
3271  * This calls eval1() and handles error message and nextcmd.
3272  * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3273  * Note: "rettv.v_lock" is not set.
3274  * Return OK or FAIL.
3275  */
3276     int
3277 eval0(
3278     char_u	*arg,
3279     typval_T	*rettv,
3280     char_u	**nextcmd,
3281     int		evaluate)
3282 {
3283     int		ret;
3284     char_u	*p;
3285 
3286     p = skipwhite(arg);
3287     ret = eval1(&p, rettv, evaluate);
3288     if (ret == FAIL || !ends_excmd(*p))
3289     {
3290 	if (ret != FAIL)
3291 	    clear_tv(rettv);
3292 	/*
3293 	 * Report the invalid expression unless the expression evaluation has
3294 	 * been cancelled due to an aborting error, an interrupt, or an
3295 	 * exception.
3296 	 */
3297 	if (!aborting())
3298 	    EMSG2(_(e_invexpr2), arg);
3299 	ret = FAIL;
3300     }
3301     if (nextcmd != NULL)
3302 	*nextcmd = check_nextcmd(p);
3303 
3304     return ret;
3305 }
3306 
3307 /*
3308  * Handle top level expression:
3309  *	expr2 ? expr1 : expr1
3310  *
3311  * "arg" must point to the first non-white of the expression.
3312  * "arg" is advanced to the next non-white after the recognized expression.
3313  *
3314  * Note: "rettv.v_lock" is not set.
3315  *
3316  * Return OK or FAIL.
3317  */
3318     int
3319 eval1(char_u **arg, typval_T *rettv, int evaluate)
3320 {
3321     int		result;
3322     typval_T	var2;
3323 
3324     /*
3325      * Get the first variable.
3326      */
3327     if (eval2(arg, rettv, evaluate) == FAIL)
3328 	return FAIL;
3329 
3330     if ((*arg)[0] == '?')
3331     {
3332 	result = FALSE;
3333 	if (evaluate)
3334 	{
3335 	    int		error = FALSE;
3336 
3337 	    if (get_tv_number_chk(rettv, &error) != 0)
3338 		result = TRUE;
3339 	    clear_tv(rettv);
3340 	    if (error)
3341 		return FAIL;
3342 	}
3343 
3344 	/*
3345 	 * Get the second variable.
3346 	 */
3347 	*arg = skipwhite(*arg + 1);
3348 	if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3349 	    return FAIL;
3350 
3351 	/*
3352 	 * Check for the ":".
3353 	 */
3354 	if ((*arg)[0] != ':')
3355 	{
3356 	    EMSG(_("E109: Missing ':' after '?'"));
3357 	    if (evaluate && result)
3358 		clear_tv(rettv);
3359 	    return FAIL;
3360 	}
3361 
3362 	/*
3363 	 * Get the third variable.
3364 	 */
3365 	*arg = skipwhite(*arg + 1);
3366 	if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3367 	{
3368 	    if (evaluate && result)
3369 		clear_tv(rettv);
3370 	    return FAIL;
3371 	}
3372 	if (evaluate && !result)
3373 	    *rettv = var2;
3374     }
3375 
3376     return OK;
3377 }
3378 
3379 /*
3380  * Handle first level expression:
3381  *	expr2 || expr2 || expr2	    logical OR
3382  *
3383  * "arg" must point to the first non-white of the expression.
3384  * "arg" is advanced to the next non-white after the recognized expression.
3385  *
3386  * Return OK or FAIL.
3387  */
3388     static int
3389 eval2(char_u **arg, typval_T *rettv, int evaluate)
3390 {
3391     typval_T	var2;
3392     long	result;
3393     int		first;
3394     int		error = FALSE;
3395 
3396     /*
3397      * Get the first variable.
3398      */
3399     if (eval3(arg, rettv, evaluate) == FAIL)
3400 	return FAIL;
3401 
3402     /*
3403      * Repeat until there is no following "||".
3404      */
3405     first = TRUE;
3406     result = FALSE;
3407     while ((*arg)[0] == '|' && (*arg)[1] == '|')
3408     {
3409 	if (evaluate && first)
3410 	{
3411 	    if (get_tv_number_chk(rettv, &error) != 0)
3412 		result = TRUE;
3413 	    clear_tv(rettv);
3414 	    if (error)
3415 		return FAIL;
3416 	    first = FALSE;
3417 	}
3418 
3419 	/*
3420 	 * Get the second variable.
3421 	 */
3422 	*arg = skipwhite(*arg + 2);
3423 	if (eval3(arg, &var2, evaluate && !result) == FAIL)
3424 	    return FAIL;
3425 
3426 	/*
3427 	 * Compute the result.
3428 	 */
3429 	if (evaluate && !result)
3430 	{
3431 	    if (get_tv_number_chk(&var2, &error) != 0)
3432 		result = TRUE;
3433 	    clear_tv(&var2);
3434 	    if (error)
3435 		return FAIL;
3436 	}
3437 	if (evaluate)
3438 	{
3439 	    rettv->v_type = VAR_NUMBER;
3440 	    rettv->vval.v_number = result;
3441 	}
3442     }
3443 
3444     return OK;
3445 }
3446 
3447 /*
3448  * Handle second level expression:
3449  *	expr3 && expr3 && expr3	    logical AND
3450  *
3451  * "arg" must point to the first non-white of the expression.
3452  * "arg" is advanced to the next non-white after the recognized expression.
3453  *
3454  * Return OK or FAIL.
3455  */
3456     static int
3457 eval3(char_u **arg, typval_T *rettv, int evaluate)
3458 {
3459     typval_T	var2;
3460     long	result;
3461     int		first;
3462     int		error = FALSE;
3463 
3464     /*
3465      * Get the first variable.
3466      */
3467     if (eval4(arg, rettv, evaluate) == FAIL)
3468 	return FAIL;
3469 
3470     /*
3471      * Repeat until there is no following "&&".
3472      */
3473     first = TRUE;
3474     result = TRUE;
3475     while ((*arg)[0] == '&' && (*arg)[1] == '&')
3476     {
3477 	if (evaluate && first)
3478 	{
3479 	    if (get_tv_number_chk(rettv, &error) == 0)
3480 		result = FALSE;
3481 	    clear_tv(rettv);
3482 	    if (error)
3483 		return FAIL;
3484 	    first = FALSE;
3485 	}
3486 
3487 	/*
3488 	 * Get the second variable.
3489 	 */
3490 	*arg = skipwhite(*arg + 2);
3491 	if (eval4(arg, &var2, evaluate && result) == FAIL)
3492 	    return FAIL;
3493 
3494 	/*
3495 	 * Compute the result.
3496 	 */
3497 	if (evaluate && result)
3498 	{
3499 	    if (get_tv_number_chk(&var2, &error) == 0)
3500 		result = FALSE;
3501 	    clear_tv(&var2);
3502 	    if (error)
3503 		return FAIL;
3504 	}
3505 	if (evaluate)
3506 	{
3507 	    rettv->v_type = VAR_NUMBER;
3508 	    rettv->vval.v_number = result;
3509 	}
3510     }
3511 
3512     return OK;
3513 }
3514 
3515 /*
3516  * Handle third level expression:
3517  *	var1 == var2
3518  *	var1 =~ var2
3519  *	var1 != var2
3520  *	var1 !~ var2
3521  *	var1 > var2
3522  *	var1 >= var2
3523  *	var1 < var2
3524  *	var1 <= var2
3525  *	var1 is var2
3526  *	var1 isnot var2
3527  *
3528  * "arg" must point to the first non-white of the expression.
3529  * "arg" is advanced to the next non-white after the recognized expression.
3530  *
3531  * Return OK or FAIL.
3532  */
3533     static int
3534 eval4(char_u **arg, typval_T *rettv, int evaluate)
3535 {
3536     typval_T	var2;
3537     char_u	*p;
3538     int		i;
3539     exptype_T	type = TYPE_UNKNOWN;
3540     int		type_is = FALSE;    /* TRUE for "is" and "isnot" */
3541     int		len = 2;
3542     varnumber_T	n1, n2;
3543     char_u	*s1, *s2;
3544     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
3545     int		ic;
3546 
3547     /*
3548      * Get the first variable.
3549      */
3550     if (eval5(arg, rettv, evaluate) == FAIL)
3551 	return FAIL;
3552 
3553     p = *arg;
3554     switch (p[0])
3555     {
3556 	case '=':   if (p[1] == '=')
3557 			type = TYPE_EQUAL;
3558 		    else if (p[1] == '~')
3559 			type = TYPE_MATCH;
3560 		    break;
3561 	case '!':   if (p[1] == '=')
3562 			type = TYPE_NEQUAL;
3563 		    else if (p[1] == '~')
3564 			type = TYPE_NOMATCH;
3565 		    break;
3566 	case '>':   if (p[1] != '=')
3567 		    {
3568 			type = TYPE_GREATER;
3569 			len = 1;
3570 		    }
3571 		    else
3572 			type = TYPE_GEQUAL;
3573 		    break;
3574 	case '<':   if (p[1] != '=')
3575 		    {
3576 			type = TYPE_SMALLER;
3577 			len = 1;
3578 		    }
3579 		    else
3580 			type = TYPE_SEQUAL;
3581 		    break;
3582 	case 'i':   if (p[1] == 's')
3583 		    {
3584 			if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
3585 			    len = 5;
3586 			i = p[len];
3587 			if (!isalnum(i) && i != '_')
3588 			{
3589 			    type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
3590 			    type_is = TRUE;
3591 			}
3592 		    }
3593 		    break;
3594     }
3595 
3596     /*
3597      * If there is a comparative operator, use it.
3598      */
3599     if (type != TYPE_UNKNOWN)
3600     {
3601 	/* extra question mark appended: ignore case */
3602 	if (p[len] == '?')
3603 	{
3604 	    ic = TRUE;
3605 	    ++len;
3606 	}
3607 	/* extra '#' appended: match case */
3608 	else if (p[len] == '#')
3609 	{
3610 	    ic = FALSE;
3611 	    ++len;
3612 	}
3613 	/* nothing appended: use 'ignorecase' */
3614 	else
3615 	    ic = p_ic;
3616 
3617 	/*
3618 	 * Get the second variable.
3619 	 */
3620 	*arg = skipwhite(p + len);
3621 	if (eval5(arg, &var2, evaluate) == FAIL)
3622 	{
3623 	    clear_tv(rettv);
3624 	    return FAIL;
3625 	}
3626 
3627 	if (evaluate)
3628 	{
3629 	    if (type_is && rettv->v_type != var2.v_type)
3630 	    {
3631 		/* For "is" a different type always means FALSE, for "notis"
3632 		 * it means TRUE. */
3633 		n1 = (type == TYPE_NEQUAL);
3634 	    }
3635 	    else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
3636 	    {
3637 		if (type_is)
3638 		{
3639 		    n1 = (rettv->v_type == var2.v_type
3640 				   && rettv->vval.v_list == var2.vval.v_list);
3641 		    if (type == TYPE_NEQUAL)
3642 			n1 = !n1;
3643 		}
3644 		else if (rettv->v_type != var2.v_type
3645 			|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
3646 		{
3647 		    if (rettv->v_type != var2.v_type)
3648 			EMSG(_("E691: Can only compare List with List"));
3649 		    else
3650 			EMSG(_("E692: Invalid operation for List"));
3651 		    clear_tv(rettv);
3652 		    clear_tv(&var2);
3653 		    return FAIL;
3654 		}
3655 		else
3656 		{
3657 		    /* Compare two Lists for being equal or unequal. */
3658 		    n1 = list_equal(rettv->vval.v_list, var2.vval.v_list,
3659 								   ic, FALSE);
3660 		    if (type == TYPE_NEQUAL)
3661 			n1 = !n1;
3662 		}
3663 	    }
3664 
3665 	    else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
3666 	    {
3667 		if (type_is)
3668 		{
3669 		    n1 = (rettv->v_type == var2.v_type
3670 				   && rettv->vval.v_dict == var2.vval.v_dict);
3671 		    if (type == TYPE_NEQUAL)
3672 			n1 = !n1;
3673 		}
3674 		else if (rettv->v_type != var2.v_type
3675 			|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
3676 		{
3677 		    if (rettv->v_type != var2.v_type)
3678 			EMSG(_("E735: Can only compare Dictionary with Dictionary"));
3679 		    else
3680 			EMSG(_("E736: Invalid operation for Dictionary"));
3681 		    clear_tv(rettv);
3682 		    clear_tv(&var2);
3683 		    return FAIL;
3684 		}
3685 		else
3686 		{
3687 		    /* Compare two Dictionaries for being equal or unequal. */
3688 		    n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict,
3689 								   ic, FALSE);
3690 		    if (type == TYPE_NEQUAL)
3691 			n1 = !n1;
3692 		}
3693 	    }
3694 
3695 	    else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC
3696 		|| rettv->v_type == VAR_PARTIAL || var2.v_type == VAR_PARTIAL)
3697 	    {
3698 		if (type != TYPE_EQUAL && type != TYPE_NEQUAL)
3699 		{
3700 		    EMSG(_("E694: Invalid operation for Funcrefs"));
3701 		    clear_tv(rettv);
3702 		    clear_tv(&var2);
3703 		    return FAIL;
3704 		}
3705 		if ((rettv->v_type == VAR_PARTIAL
3706 					     && rettv->vval.v_partial == NULL)
3707 			|| (var2.v_type == VAR_PARTIAL
3708 					      && var2.vval.v_partial == NULL))
3709 		    /* when a partial is NULL assume not equal */
3710 		    n1 = FALSE;
3711 		else if (type_is)
3712 		{
3713 		    if (rettv->v_type == VAR_FUNC && var2.v_type == VAR_FUNC)
3714 			/* strings are considered the same if their value is
3715 			 * the same */
3716 			n1 = tv_equal(rettv, &var2, ic, FALSE);
3717 		    else if (rettv->v_type == VAR_PARTIAL
3718 						&& var2.v_type == VAR_PARTIAL)
3719 			n1 = (rettv->vval.v_partial == var2.vval.v_partial);
3720 		    else
3721 			n1 = FALSE;
3722 		}
3723 		else
3724 		    n1 = tv_equal(rettv, &var2, ic, FALSE);
3725 		if (type == TYPE_NEQUAL)
3726 		    n1 = !n1;
3727 	    }
3728 
3729 #ifdef FEAT_FLOAT
3730 	    /*
3731 	     * If one of the two variables is a float, compare as a float.
3732 	     * When using "=~" or "!~", always compare as string.
3733 	     */
3734 	    else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
3735 		    && type != TYPE_MATCH && type != TYPE_NOMATCH)
3736 	    {
3737 		float_T f1, f2;
3738 
3739 		if (rettv->v_type == VAR_FLOAT)
3740 		    f1 = rettv->vval.v_float;
3741 		else
3742 		    f1 = get_tv_number(rettv);
3743 		if (var2.v_type == VAR_FLOAT)
3744 		    f2 = var2.vval.v_float;
3745 		else
3746 		    f2 = get_tv_number(&var2);
3747 		n1 = FALSE;
3748 		switch (type)
3749 		{
3750 		    case TYPE_EQUAL:    n1 = (f1 == f2); break;
3751 		    case TYPE_NEQUAL:   n1 = (f1 != f2); break;
3752 		    case TYPE_GREATER:  n1 = (f1 > f2); break;
3753 		    case TYPE_GEQUAL:   n1 = (f1 >= f2); break;
3754 		    case TYPE_SMALLER:  n1 = (f1 < f2); break;
3755 		    case TYPE_SEQUAL:   n1 = (f1 <= f2); break;
3756 		    case TYPE_UNKNOWN:
3757 		    case TYPE_MATCH:
3758 		    case TYPE_NOMATCH:  break;  /* avoid gcc warning */
3759 		}
3760 	    }
3761 #endif
3762 
3763 	    /*
3764 	     * If one of the two variables is a number, compare as a number.
3765 	     * When using "=~" or "!~", always compare as string.
3766 	     */
3767 	    else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
3768 		    && type != TYPE_MATCH && type != TYPE_NOMATCH)
3769 	    {
3770 		n1 = get_tv_number(rettv);
3771 		n2 = get_tv_number(&var2);
3772 		switch (type)
3773 		{
3774 		    case TYPE_EQUAL:    n1 = (n1 == n2); break;
3775 		    case TYPE_NEQUAL:   n1 = (n1 != n2); break;
3776 		    case TYPE_GREATER:  n1 = (n1 > n2); break;
3777 		    case TYPE_GEQUAL:   n1 = (n1 >= n2); break;
3778 		    case TYPE_SMALLER:  n1 = (n1 < n2); break;
3779 		    case TYPE_SEQUAL:   n1 = (n1 <= n2); break;
3780 		    case TYPE_UNKNOWN:
3781 		    case TYPE_MATCH:
3782 		    case TYPE_NOMATCH:  break;  /* avoid gcc warning */
3783 		}
3784 	    }
3785 	    else
3786 	    {
3787 		s1 = get_tv_string_buf(rettv, buf1);
3788 		s2 = get_tv_string_buf(&var2, buf2);
3789 		if (type != TYPE_MATCH && type != TYPE_NOMATCH)
3790 		    i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
3791 		else
3792 		    i = 0;
3793 		n1 = FALSE;
3794 		switch (type)
3795 		{
3796 		    case TYPE_EQUAL:    n1 = (i == 0); break;
3797 		    case TYPE_NEQUAL:   n1 = (i != 0); break;
3798 		    case TYPE_GREATER:  n1 = (i > 0); break;
3799 		    case TYPE_GEQUAL:   n1 = (i >= 0); break;
3800 		    case TYPE_SMALLER:  n1 = (i < 0); break;
3801 		    case TYPE_SEQUAL:   n1 = (i <= 0); break;
3802 
3803 		    case TYPE_MATCH:
3804 		    case TYPE_NOMATCH:
3805 			    n1 = pattern_match(s2, s1, ic);
3806 			    if (type == TYPE_NOMATCH)
3807 				n1 = !n1;
3808 			    break;
3809 
3810 		    case TYPE_UNKNOWN:  break;  /* avoid gcc warning */
3811 		}
3812 	    }
3813 	    clear_tv(rettv);
3814 	    clear_tv(&var2);
3815 	    rettv->v_type = VAR_NUMBER;
3816 	    rettv->vval.v_number = n1;
3817 	}
3818     }
3819 
3820     return OK;
3821 }
3822 
3823 /*
3824  * Handle fourth level expression:
3825  *	+	number addition
3826  *	-	number subtraction
3827  *	.	string concatenation
3828  *
3829  * "arg" must point to the first non-white of the expression.
3830  * "arg" is advanced to the next non-white after the recognized expression.
3831  *
3832  * Return OK or FAIL.
3833  */
3834     static int
3835 eval5(char_u **arg, typval_T *rettv, int evaluate)
3836 {
3837     typval_T	var2;
3838     typval_T	var3;
3839     int		op;
3840     varnumber_T	n1, n2;
3841 #ifdef FEAT_FLOAT
3842     float_T	f1 = 0, f2 = 0;
3843 #endif
3844     char_u	*s1, *s2;
3845     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
3846     char_u	*p;
3847 
3848     /*
3849      * Get the first variable.
3850      */
3851     if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
3852 	return FAIL;
3853 
3854     /*
3855      * Repeat computing, until no '+', '-' or '.' is following.
3856      */
3857     for (;;)
3858     {
3859 	op = **arg;
3860 	if (op != '+' && op != '-' && op != '.')
3861 	    break;
3862 
3863 	if ((op != '+' || rettv->v_type != VAR_LIST)
3864 #ifdef FEAT_FLOAT
3865 		&& (op == '.' || rettv->v_type != VAR_FLOAT)
3866 #endif
3867 		)
3868 	{
3869 	    /* For "list + ...", an illegal use of the first operand as
3870 	     * a number cannot be determined before evaluating the 2nd
3871 	     * operand: if this is also a list, all is ok.
3872 	     * For "something . ...", "something - ..." or "non-list + ...",
3873 	     * we know that the first operand needs to be a string or number
3874 	     * without evaluating the 2nd operand.  So check before to avoid
3875 	     * side effects after an error. */
3876 	    if (evaluate && get_tv_string_chk(rettv) == NULL)
3877 	    {
3878 		clear_tv(rettv);
3879 		return FAIL;
3880 	    }
3881 	}
3882 
3883 	/*
3884 	 * Get the second variable.
3885 	 */
3886 	*arg = skipwhite(*arg + 1);
3887 	if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
3888 	{
3889 	    clear_tv(rettv);
3890 	    return FAIL;
3891 	}
3892 
3893 	if (evaluate)
3894 	{
3895 	    /*
3896 	     * Compute the result.
3897 	     */
3898 	    if (op == '.')
3899 	    {
3900 		s1 = get_tv_string_buf(rettv, buf1);	/* already checked */
3901 		s2 = get_tv_string_buf_chk(&var2, buf2);
3902 		if (s2 == NULL)		/* type error ? */
3903 		{
3904 		    clear_tv(rettv);
3905 		    clear_tv(&var2);
3906 		    return FAIL;
3907 		}
3908 		p = concat_str(s1, s2);
3909 		clear_tv(rettv);
3910 		rettv->v_type = VAR_STRING;
3911 		rettv->vval.v_string = p;
3912 	    }
3913 	    else if (op == '+' && rettv->v_type == VAR_LIST
3914 						   && var2.v_type == VAR_LIST)
3915 	    {
3916 		/* concatenate Lists */
3917 		if (list_concat(rettv->vval.v_list, var2.vval.v_list,
3918 							       &var3) == FAIL)
3919 		{
3920 		    clear_tv(rettv);
3921 		    clear_tv(&var2);
3922 		    return FAIL;
3923 		}
3924 		clear_tv(rettv);
3925 		*rettv = var3;
3926 	    }
3927 	    else
3928 	    {
3929 		int	    error = FALSE;
3930 
3931 #ifdef FEAT_FLOAT
3932 		if (rettv->v_type == VAR_FLOAT)
3933 		{
3934 		    f1 = rettv->vval.v_float;
3935 		    n1 = 0;
3936 		}
3937 		else
3938 #endif
3939 		{
3940 		    n1 = get_tv_number_chk(rettv, &error);
3941 		    if (error)
3942 		    {
3943 			/* This can only happen for "list + non-list".  For
3944 			 * "non-list + ..." or "something - ...", we returned
3945 			 * before evaluating the 2nd operand. */
3946 			clear_tv(rettv);
3947 			return FAIL;
3948 		    }
3949 #ifdef FEAT_FLOAT
3950 		    if (var2.v_type == VAR_FLOAT)
3951 			f1 = n1;
3952 #endif
3953 		}
3954 #ifdef FEAT_FLOAT
3955 		if (var2.v_type == VAR_FLOAT)
3956 		{
3957 		    f2 = var2.vval.v_float;
3958 		    n2 = 0;
3959 		}
3960 		else
3961 #endif
3962 		{
3963 		    n2 = get_tv_number_chk(&var2, &error);
3964 		    if (error)
3965 		    {
3966 			clear_tv(rettv);
3967 			clear_tv(&var2);
3968 			return FAIL;
3969 		    }
3970 #ifdef FEAT_FLOAT
3971 		    if (rettv->v_type == VAR_FLOAT)
3972 			f2 = n2;
3973 #endif
3974 		}
3975 		clear_tv(rettv);
3976 
3977 #ifdef FEAT_FLOAT
3978 		/* If there is a float on either side the result is a float. */
3979 		if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
3980 		{
3981 		    if (op == '+')
3982 			f1 = f1 + f2;
3983 		    else
3984 			f1 = f1 - f2;
3985 		    rettv->v_type = VAR_FLOAT;
3986 		    rettv->vval.v_float = f1;
3987 		}
3988 		else
3989 #endif
3990 		{
3991 		    if (op == '+')
3992 			n1 = n1 + n2;
3993 		    else
3994 			n1 = n1 - n2;
3995 		    rettv->v_type = VAR_NUMBER;
3996 		    rettv->vval.v_number = n1;
3997 		}
3998 	    }
3999 	    clear_tv(&var2);
4000 	}
4001     }
4002     return OK;
4003 }
4004 
4005 /*
4006  * Handle fifth level expression:
4007  *	*	number multiplication
4008  *	/	number division
4009  *	%	number modulo
4010  *
4011  * "arg" must point to the first non-white of the expression.
4012  * "arg" is advanced to the next non-white after the recognized expression.
4013  *
4014  * Return OK or FAIL.
4015  */
4016     static int
4017 eval6(
4018     char_u	**arg,
4019     typval_T	*rettv,
4020     int		evaluate,
4021     int		want_string)  /* after "." operator */
4022 {
4023     typval_T	var2;
4024     int		op;
4025     varnumber_T	n1, n2;
4026 #ifdef FEAT_FLOAT
4027     int		use_float = FALSE;
4028     float_T	f1 = 0, f2;
4029 #endif
4030     int		error = FALSE;
4031 
4032     /*
4033      * Get the first variable.
4034      */
4035     if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4036 	return FAIL;
4037 
4038     /*
4039      * Repeat computing, until no '*', '/' or '%' is following.
4040      */
4041     for (;;)
4042     {
4043 	op = **arg;
4044 	if (op != '*' && op != '/' && op != '%')
4045 	    break;
4046 
4047 	if (evaluate)
4048 	{
4049 #ifdef FEAT_FLOAT
4050 	    if (rettv->v_type == VAR_FLOAT)
4051 	    {
4052 		f1 = rettv->vval.v_float;
4053 		use_float = TRUE;
4054 		n1 = 0;
4055 	    }
4056 	    else
4057 #endif
4058 		n1 = get_tv_number_chk(rettv, &error);
4059 	    clear_tv(rettv);
4060 	    if (error)
4061 		return FAIL;
4062 	}
4063 	else
4064 	    n1 = 0;
4065 
4066 	/*
4067 	 * Get the second variable.
4068 	 */
4069 	*arg = skipwhite(*arg + 1);
4070 	if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4071 	    return FAIL;
4072 
4073 	if (evaluate)
4074 	{
4075 #ifdef FEAT_FLOAT
4076 	    if (var2.v_type == VAR_FLOAT)
4077 	    {
4078 		if (!use_float)
4079 		{
4080 		    f1 = n1;
4081 		    use_float = TRUE;
4082 		}
4083 		f2 = var2.vval.v_float;
4084 		n2 = 0;
4085 	    }
4086 	    else
4087 #endif
4088 	    {
4089 		n2 = get_tv_number_chk(&var2, &error);
4090 		clear_tv(&var2);
4091 		if (error)
4092 		    return FAIL;
4093 #ifdef FEAT_FLOAT
4094 		if (use_float)
4095 		    f2 = n2;
4096 #endif
4097 	    }
4098 
4099 	    /*
4100 	     * Compute the result.
4101 	     * When either side is a float the result is a float.
4102 	     */
4103 #ifdef FEAT_FLOAT
4104 	    if (use_float)
4105 	    {
4106 		if (op == '*')
4107 		    f1 = f1 * f2;
4108 		else if (op == '/')
4109 		{
4110 # ifdef VMS
4111 		    /* VMS crashes on divide by zero, work around it */
4112 		    if (f2 == 0.0)
4113 		    {
4114 			if (f1 == 0)
4115 			    f1 = -1 * __F_FLT_MAX - 1L;   /* similar to NaN */
4116 			else if (f1 < 0)
4117 			    f1 = -1 * __F_FLT_MAX;
4118 			else
4119 			    f1 = __F_FLT_MAX;
4120 		    }
4121 		    else
4122 			f1 = f1 / f2;
4123 # else
4124 		    /* We rely on the floating point library to handle divide
4125 		     * by zero to result in "inf" and not a crash. */
4126 		    f1 = f1 / f2;
4127 # endif
4128 		}
4129 		else
4130 		{
4131 		    EMSG(_("E804: Cannot use '%' with Float"));
4132 		    return FAIL;
4133 		}
4134 		rettv->v_type = VAR_FLOAT;
4135 		rettv->vval.v_float = f1;
4136 	    }
4137 	    else
4138 #endif
4139 	    {
4140 		if (op == '*')
4141 		    n1 = n1 * n2;
4142 		else if (op == '/')
4143 		{
4144 		    if (n2 == 0)	/* give an error message? */
4145 		    {
4146 			if (n1 == 0)
4147 			    n1 = VARNUM_MIN; /* similar to NaN */
4148 			else if (n1 < 0)
4149 			    n1 = -VARNUM_MAX;
4150 			else
4151 			    n1 = VARNUM_MAX;
4152 		    }
4153 		    else
4154 			n1 = n1 / n2;
4155 		}
4156 		else
4157 		{
4158 		    if (n2 == 0)	/* give an error message? */
4159 			n1 = 0;
4160 		    else
4161 			n1 = n1 % n2;
4162 		}
4163 		rettv->v_type = VAR_NUMBER;
4164 		rettv->vval.v_number = n1;
4165 	    }
4166 	}
4167     }
4168 
4169     return OK;
4170 }
4171 
4172 /*
4173  * Handle sixth level expression:
4174  *  number		number constant
4175  *  "string"		string constant
4176  *  'string'		literal string constant
4177  *  &option-name	option value
4178  *  @r			register contents
4179  *  identifier		variable value
4180  *  function()		function call
4181  *  $VAR		environment variable
4182  *  (expression)	nested expression
4183  *  [expr, expr]	List
4184  *  {key: val, key: val}  Dictionary
4185  *
4186  *  Also handle:
4187  *  ! in front		logical NOT
4188  *  - in front		unary minus
4189  *  + in front		unary plus (ignored)
4190  *  trailing []		subscript in String or List
4191  *  trailing .name	entry in Dictionary
4192  *
4193  * "arg" must point to the first non-white of the expression.
4194  * "arg" is advanced to the next non-white after the recognized expression.
4195  *
4196  * Return OK or FAIL.
4197  */
4198     static int
4199 eval7(
4200     char_u	**arg,
4201     typval_T	*rettv,
4202     int		evaluate,
4203     int		want_string UNUSED)	/* after "." operator */
4204 {
4205     varnumber_T	n;
4206     int		len;
4207     char_u	*s;
4208     char_u	*start_leader, *end_leader;
4209     int		ret = OK;
4210     char_u	*alias;
4211 
4212     /*
4213      * Initialise variable so that clear_tv() can't mistake this for a
4214      * string and free a string that isn't there.
4215      */
4216     rettv->v_type = VAR_UNKNOWN;
4217 
4218     /*
4219      * Skip '!', '-' and '+' characters.  They are handled later.
4220      */
4221     start_leader = *arg;
4222     while (**arg == '!' || **arg == '-' || **arg == '+')
4223 	*arg = skipwhite(*arg + 1);
4224     end_leader = *arg;
4225 
4226     switch (**arg)
4227     {
4228     /*
4229      * Number constant.
4230      */
4231     case '0':
4232     case '1':
4233     case '2':
4234     case '3':
4235     case '4':
4236     case '5':
4237     case '6':
4238     case '7':
4239     case '8':
4240     case '9':
4241 	{
4242 #ifdef FEAT_FLOAT
4243 		char_u *p = skipdigits(*arg + 1);
4244 		int    get_float = FALSE;
4245 
4246 		/* We accept a float when the format matches
4247 		 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?".  This is very
4248 		 * strict to avoid backwards compatibility problems.
4249 		 * Don't look for a float after the "." operator, so that
4250 		 * ":let vers = 1.2.3" doesn't fail. */
4251 		if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
4252 		{
4253 		    get_float = TRUE;
4254 		    p = skipdigits(p + 2);
4255 		    if (*p == 'e' || *p == 'E')
4256 		    {
4257 			++p;
4258 			if (*p == '-' || *p == '+')
4259 			    ++p;
4260 			if (!vim_isdigit(*p))
4261 			    get_float = FALSE;
4262 			else
4263 			    p = skipdigits(p + 1);
4264 		    }
4265 		    if (ASCII_ISALPHA(*p) || *p == '.')
4266 			get_float = FALSE;
4267 		}
4268 		if (get_float)
4269 		{
4270 		    float_T	f;
4271 
4272 		    *arg += string2float(*arg, &f);
4273 		    if (evaluate)
4274 		    {
4275 			rettv->v_type = VAR_FLOAT;
4276 			rettv->vval.v_float = f;
4277 		    }
4278 		}
4279 		else
4280 #endif
4281 		{
4282 		    vim_str2nr(*arg, NULL, &len, STR2NR_ALL, &n, NULL, 0);
4283 		    *arg += len;
4284 		    if (evaluate)
4285 		    {
4286 			rettv->v_type = VAR_NUMBER;
4287 			rettv->vval.v_number = n;
4288 		    }
4289 		}
4290 		break;
4291 	}
4292 
4293     /*
4294      * String constant: "string".
4295      */
4296     case '"':	ret = get_string_tv(arg, rettv, evaluate);
4297 		break;
4298 
4299     /*
4300      * Literal string constant: 'str''ing'.
4301      */
4302     case '\'':	ret = get_lit_string_tv(arg, rettv, evaluate);
4303 		break;
4304 
4305     /*
4306      * List: [expr, expr]
4307      */
4308     case '[':	ret = get_list_tv(arg, rettv, evaluate);
4309 		break;
4310 
4311     /*
4312      * Lambda: {arg, arg -> expr}
4313      * Dictionary: {key: val, key: val}
4314      */
4315     case '{':	ret = get_lambda_tv(arg, rettv, evaluate);
4316 		if (ret == NOTDONE)
4317 		    ret = get_dict_tv(arg, rettv, evaluate);
4318 		break;
4319 
4320     /*
4321      * Option value: &name
4322      */
4323     case '&':	ret = get_option_tv(arg, rettv, evaluate);
4324 		break;
4325 
4326     /*
4327      * Environment variable: $VAR.
4328      */
4329     case '$':	ret = get_env_tv(arg, rettv, evaluate);
4330 		break;
4331 
4332     /*
4333      * Register contents: @r.
4334      */
4335     case '@':	++*arg;
4336 		if (evaluate)
4337 		{
4338 		    rettv->v_type = VAR_STRING;
4339 		    rettv->vval.v_string = get_reg_contents(**arg,
4340 							    GREG_EXPR_SRC);
4341 		}
4342 		if (**arg != NUL)
4343 		    ++*arg;
4344 		break;
4345 
4346     /*
4347      * nested expression: (expression).
4348      */
4349     case '(':	*arg = skipwhite(*arg + 1);
4350 		ret = eval1(arg, rettv, evaluate);	/* recursive! */
4351 		if (**arg == ')')
4352 		    ++*arg;
4353 		else if (ret == OK)
4354 		{
4355 		    EMSG(_("E110: Missing ')'"));
4356 		    clear_tv(rettv);
4357 		    ret = FAIL;
4358 		}
4359 		break;
4360 
4361     default:	ret = NOTDONE;
4362 		break;
4363     }
4364 
4365     if (ret == NOTDONE)
4366     {
4367 	/*
4368 	 * Must be a variable or function name.
4369 	 * Can also be a curly-braces kind of name: {expr}.
4370 	 */
4371 	s = *arg;
4372 	len = get_name_len(arg, &alias, evaluate, TRUE);
4373 	if (alias != NULL)
4374 	    s = alias;
4375 
4376 	if (len <= 0)
4377 	    ret = FAIL;
4378 	else
4379 	{
4380 	    if (**arg == '(')		/* recursive! */
4381 	    {
4382 		partial_T *partial;
4383 
4384 		if (!evaluate)
4385 		    check_vars(s, len);
4386 
4387 		/* If "s" is the name of a variable of type VAR_FUNC
4388 		 * use its contents. */
4389 		s = deref_func_name(s, &len, &partial, !evaluate);
4390 
4391 		/* Need to make a copy, in case evaluating the arguments makes
4392 		 * the name invalid. */
4393 		s = vim_strsave(s);
4394 		if (s == NULL)
4395 		    ret = FAIL;
4396 		else
4397 		    /* Invoke the function. */
4398 		    ret = get_func_tv(s, len, rettv, arg,
4399 			      curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4400 			      &len, evaluate, partial, NULL);
4401 		vim_free(s);
4402 
4403 		/* If evaluate is FALSE rettv->v_type was not set in
4404 		 * get_func_tv, but it's needed in handle_subscript() to parse
4405 		 * what follows. So set it here. */
4406 		if (rettv->v_type == VAR_UNKNOWN && !evaluate && **arg == '(')
4407 		{
4408 		    rettv->vval.v_string = NULL;
4409 		    rettv->v_type = VAR_FUNC;
4410 		}
4411 
4412 		/* Stop the expression evaluation when immediately
4413 		 * aborting on error, or when an interrupt occurred or
4414 		 * an exception was thrown but not caught. */
4415 		if (aborting())
4416 		{
4417 		    if (ret == OK)
4418 			clear_tv(rettv);
4419 		    ret = FAIL;
4420 		}
4421 	    }
4422 	    else if (evaluate)
4423 		ret = get_var_tv(s, len, rettv, NULL, TRUE, FALSE);
4424 	    else
4425 	    {
4426 		check_vars(s, len);
4427 		ret = OK;
4428 	    }
4429 	}
4430 	vim_free(alias);
4431     }
4432 
4433     *arg = skipwhite(*arg);
4434 
4435     /* Handle following '[', '(' and '.' for expr[expr], expr.name,
4436      * expr(expr). */
4437     if (ret == OK)
4438 	ret = handle_subscript(arg, rettv, evaluate, TRUE);
4439 
4440     /*
4441      * Apply logical NOT and unary '-', from right to left, ignore '+'.
4442      */
4443     if (ret == OK && evaluate && end_leader > start_leader)
4444     {
4445 	int	    error = FALSE;
4446 	varnumber_T val = 0;
4447 #ifdef FEAT_FLOAT
4448 	float_T	    f = 0.0;
4449 
4450 	if (rettv->v_type == VAR_FLOAT)
4451 	    f = rettv->vval.v_float;
4452 	else
4453 #endif
4454 	    val = get_tv_number_chk(rettv, &error);
4455 	if (error)
4456 	{
4457 	    clear_tv(rettv);
4458 	    ret = FAIL;
4459 	}
4460 	else
4461 	{
4462 	    while (end_leader > start_leader)
4463 	    {
4464 		--end_leader;
4465 		if (*end_leader == '!')
4466 		{
4467 #ifdef FEAT_FLOAT
4468 		    if (rettv->v_type == VAR_FLOAT)
4469 			f = !f;
4470 		    else
4471 #endif
4472 			val = !val;
4473 		}
4474 		else if (*end_leader == '-')
4475 		{
4476 #ifdef FEAT_FLOAT
4477 		    if (rettv->v_type == VAR_FLOAT)
4478 			f = -f;
4479 		    else
4480 #endif
4481 			val = -val;
4482 		}
4483 	    }
4484 #ifdef FEAT_FLOAT
4485 	    if (rettv->v_type == VAR_FLOAT)
4486 	    {
4487 		clear_tv(rettv);
4488 		rettv->vval.v_float = f;
4489 	    }
4490 	    else
4491 #endif
4492 	    {
4493 		clear_tv(rettv);
4494 		rettv->v_type = VAR_NUMBER;
4495 		rettv->vval.v_number = val;
4496 	    }
4497 	}
4498     }
4499 
4500     return ret;
4501 }
4502 
4503 /*
4504  * Evaluate an "[expr]" or "[expr:expr]" index.  Also "dict.key".
4505  * "*arg" points to the '[' or '.'.
4506  * Returns FAIL or OK. "*arg" is advanced to after the ']'.
4507  */
4508     static int
4509 eval_index(
4510     char_u	**arg,
4511     typval_T	*rettv,
4512     int		evaluate,
4513     int		verbose)	/* give error messages */
4514 {
4515     int		empty1 = FALSE, empty2 = FALSE;
4516     typval_T	var1, var2;
4517     long	n1, n2 = 0;
4518     long	len = -1;
4519     int		range = FALSE;
4520     char_u	*s;
4521     char_u	*key = NULL;
4522 
4523     switch (rettv->v_type)
4524     {
4525 	case VAR_FUNC:
4526 	case VAR_PARTIAL:
4527 	    if (verbose)
4528 		EMSG(_("E695: Cannot index a Funcref"));
4529 	    return FAIL;
4530 	case VAR_FLOAT:
4531 #ifdef FEAT_FLOAT
4532 	    if (verbose)
4533 		EMSG(_(e_float_as_string));
4534 	    return FAIL;
4535 #endif
4536 	case VAR_SPECIAL:
4537 	case VAR_JOB:
4538 	case VAR_CHANNEL:
4539 	    if (verbose)
4540 		EMSG(_("E909: Cannot index a special variable"));
4541 	    return FAIL;
4542 	case VAR_UNKNOWN:
4543 	    if (evaluate)
4544 		return FAIL;
4545 	    /* FALLTHROUGH */
4546 
4547 	case VAR_STRING:
4548 	case VAR_NUMBER:
4549 	case VAR_LIST:
4550 	case VAR_DICT:
4551 	    break;
4552     }
4553 
4554     init_tv(&var1);
4555     init_tv(&var2);
4556     if (**arg == '.')
4557     {
4558 	/*
4559 	 * dict.name
4560 	 */
4561 	key = *arg + 1;
4562 	for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
4563 	    ;
4564 	if (len == 0)
4565 	    return FAIL;
4566 	*arg = skipwhite(key + len);
4567     }
4568     else
4569     {
4570 	/*
4571 	 * something[idx]
4572 	 *
4573 	 * Get the (first) variable from inside the [].
4574 	 */
4575 	*arg = skipwhite(*arg + 1);
4576 	if (**arg == ':')
4577 	    empty1 = TRUE;
4578 	else if (eval1(arg, &var1, evaluate) == FAIL)	/* recursive! */
4579 	    return FAIL;
4580 	else if (evaluate && get_tv_string_chk(&var1) == NULL)
4581 	{
4582 	    /* not a number or string */
4583 	    clear_tv(&var1);
4584 	    return FAIL;
4585 	}
4586 
4587 	/*
4588 	 * Get the second variable from inside the [:].
4589 	 */
4590 	if (**arg == ':')
4591 	{
4592 	    range = TRUE;
4593 	    *arg = skipwhite(*arg + 1);
4594 	    if (**arg == ']')
4595 		empty2 = TRUE;
4596 	    else if (eval1(arg, &var2, evaluate) == FAIL)	/* recursive! */
4597 	    {
4598 		if (!empty1)
4599 		    clear_tv(&var1);
4600 		return FAIL;
4601 	    }
4602 	    else if (evaluate && get_tv_string_chk(&var2) == NULL)
4603 	    {
4604 		/* not a number or string */
4605 		if (!empty1)
4606 		    clear_tv(&var1);
4607 		clear_tv(&var2);
4608 		return FAIL;
4609 	    }
4610 	}
4611 
4612 	/* Check for the ']'. */
4613 	if (**arg != ']')
4614 	{
4615 	    if (verbose)
4616 		EMSG(_(e_missbrac));
4617 	    clear_tv(&var1);
4618 	    if (range)
4619 		clear_tv(&var2);
4620 	    return FAIL;
4621 	}
4622 	*arg = skipwhite(*arg + 1);	/* skip the ']' */
4623     }
4624 
4625     if (evaluate)
4626     {
4627 	n1 = 0;
4628 	if (!empty1 && rettv->v_type != VAR_DICT)
4629 	{
4630 	    n1 = get_tv_number(&var1);
4631 	    clear_tv(&var1);
4632 	}
4633 	if (range)
4634 	{
4635 	    if (empty2)
4636 		n2 = -1;
4637 	    else
4638 	    {
4639 		n2 = get_tv_number(&var2);
4640 		clear_tv(&var2);
4641 	    }
4642 	}
4643 
4644 	switch (rettv->v_type)
4645 	{
4646 	    case VAR_UNKNOWN:
4647 	    case VAR_FUNC:
4648 	    case VAR_PARTIAL:
4649 	    case VAR_FLOAT:
4650 	    case VAR_SPECIAL:
4651 	    case VAR_JOB:
4652 	    case VAR_CHANNEL:
4653 		break; /* not evaluating, skipping over subscript */
4654 
4655 	    case VAR_NUMBER:
4656 	    case VAR_STRING:
4657 		s = get_tv_string(rettv);
4658 		len = (long)STRLEN(s);
4659 		if (range)
4660 		{
4661 		    /* The resulting variable is a substring.  If the indexes
4662 		     * are out of range the result is empty. */
4663 		    if (n1 < 0)
4664 		    {
4665 			n1 = len + n1;
4666 			if (n1 < 0)
4667 			    n1 = 0;
4668 		    }
4669 		    if (n2 < 0)
4670 			n2 = len + n2;
4671 		    else if (n2 >= len)
4672 			n2 = len;
4673 		    if (n1 >= len || n2 < 0 || n1 > n2)
4674 			s = NULL;
4675 		    else
4676 			s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
4677 		}
4678 		else
4679 		{
4680 		    /* The resulting variable is a string of a single
4681 		     * character.  If the index is too big or negative the
4682 		     * result is empty. */
4683 		    if (n1 >= len || n1 < 0)
4684 			s = NULL;
4685 		    else
4686 			s = vim_strnsave(s + n1, 1);
4687 		}
4688 		clear_tv(rettv);
4689 		rettv->v_type = VAR_STRING;
4690 		rettv->vval.v_string = s;
4691 		break;
4692 
4693 	    case VAR_LIST:
4694 		len = list_len(rettv->vval.v_list);
4695 		if (n1 < 0)
4696 		    n1 = len + n1;
4697 		if (!empty1 && (n1 < 0 || n1 >= len))
4698 		{
4699 		    /* For a range we allow invalid values and return an empty
4700 		     * list.  A list index out of range is an error. */
4701 		    if (!range)
4702 		    {
4703 			if (verbose)
4704 			    EMSGN(_(e_listidx), n1);
4705 			return FAIL;
4706 		    }
4707 		    n1 = len;
4708 		}
4709 		if (range)
4710 		{
4711 		    list_T	*l;
4712 		    listitem_T	*item;
4713 
4714 		    if (n2 < 0)
4715 			n2 = len + n2;
4716 		    else if (n2 >= len)
4717 			n2 = len - 1;
4718 		    if (!empty2 && (n2 < 0 || n2 + 1 < n1))
4719 			n2 = -1;
4720 		    l = list_alloc();
4721 		    if (l == NULL)
4722 			return FAIL;
4723 		    for (item = list_find(rettv->vval.v_list, n1);
4724 							       n1 <= n2; ++n1)
4725 		    {
4726 			if (list_append_tv(l, &item->li_tv) == FAIL)
4727 			{
4728 			    list_free(l);
4729 			    return FAIL;
4730 			}
4731 			item = item->li_next;
4732 		    }
4733 		    clear_tv(rettv);
4734 		    rettv_list_set(rettv, l);
4735 		}
4736 		else
4737 		{
4738 		    copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
4739 		    clear_tv(rettv);
4740 		    *rettv = var1;
4741 		}
4742 		break;
4743 
4744 	    case VAR_DICT:
4745 		if (range)
4746 		{
4747 		    if (verbose)
4748 			EMSG(_(e_dictrange));
4749 		    if (len == -1)
4750 			clear_tv(&var1);
4751 		    return FAIL;
4752 		}
4753 		{
4754 		    dictitem_T	*item;
4755 
4756 		    if (len == -1)
4757 		    {
4758 			key = get_tv_string_chk(&var1);
4759 			if (key == NULL)
4760 			{
4761 			    clear_tv(&var1);
4762 			    return FAIL;
4763 			}
4764 		    }
4765 
4766 		    item = dict_find(rettv->vval.v_dict, key, (int)len);
4767 
4768 		    if (item == NULL && verbose)
4769 			EMSG2(_(e_dictkey), key);
4770 		    if (len == -1)
4771 			clear_tv(&var1);
4772 		    if (item == NULL)
4773 			return FAIL;
4774 
4775 		    copy_tv(&item->di_tv, &var1);
4776 		    clear_tv(rettv);
4777 		    *rettv = var1;
4778 		}
4779 		break;
4780 	}
4781     }
4782 
4783     return OK;
4784 }
4785 
4786 /*
4787  * Get an option value.
4788  * "arg" points to the '&' or '+' before the option name.
4789  * "arg" is advanced to character after the option name.
4790  * Return OK or FAIL.
4791  */
4792     int
4793 get_option_tv(
4794     char_u	**arg,
4795     typval_T	*rettv,	/* when NULL, only check if option exists */
4796     int		evaluate)
4797 {
4798     char_u	*option_end;
4799     long	numval;
4800     char_u	*stringval;
4801     int		opt_type;
4802     int		c;
4803     int		working = (**arg == '+');    /* has("+option") */
4804     int		ret = OK;
4805     int		opt_flags;
4806 
4807     /*
4808      * Isolate the option name and find its value.
4809      */
4810     option_end = find_option_end(arg, &opt_flags);
4811     if (option_end == NULL)
4812     {
4813 	if (rettv != NULL)
4814 	    EMSG2(_("E112: Option name missing: %s"), *arg);
4815 	return FAIL;
4816     }
4817 
4818     if (!evaluate)
4819     {
4820 	*arg = option_end;
4821 	return OK;
4822     }
4823 
4824     c = *option_end;
4825     *option_end = NUL;
4826     opt_type = get_option_value(*arg, &numval,
4827 			       rettv == NULL ? NULL : &stringval, opt_flags);
4828 
4829     if (opt_type == -3)			/* invalid name */
4830     {
4831 	if (rettv != NULL)
4832 	    EMSG2(_("E113: Unknown option: %s"), *arg);
4833 	ret = FAIL;
4834     }
4835     else if (rettv != NULL)
4836     {
4837 	if (opt_type == -2)		/* hidden string option */
4838 	{
4839 	    rettv->v_type = VAR_STRING;
4840 	    rettv->vval.v_string = NULL;
4841 	}
4842 	else if (opt_type == -1)	/* hidden number option */
4843 	{
4844 	    rettv->v_type = VAR_NUMBER;
4845 	    rettv->vval.v_number = 0;
4846 	}
4847 	else if (opt_type == 1)		/* number option */
4848 	{
4849 	    rettv->v_type = VAR_NUMBER;
4850 	    rettv->vval.v_number = numval;
4851 	}
4852 	else				/* string option */
4853 	{
4854 	    rettv->v_type = VAR_STRING;
4855 	    rettv->vval.v_string = stringval;
4856 	}
4857     }
4858     else if (working && (opt_type == -2 || opt_type == -1))
4859 	ret = FAIL;
4860 
4861     *option_end = c;		    /* put back for error messages */
4862     *arg = option_end;
4863 
4864     return ret;
4865 }
4866 
4867 /*
4868  * Allocate a variable for a string constant.
4869  * Return OK or FAIL.
4870  */
4871     static int
4872 get_string_tv(char_u **arg, typval_T *rettv, int evaluate)
4873 {
4874     char_u	*p;
4875     char_u	*name;
4876     int		extra = 0;
4877 
4878     /*
4879      * Find the end of the string, skipping backslashed characters.
4880      */
4881     for (p = *arg + 1; *p != NUL && *p != '"'; MB_PTR_ADV(p))
4882     {
4883 	if (*p == '\\' && p[1] != NUL)
4884 	{
4885 	    ++p;
4886 	    /* A "\<x>" form occupies at least 4 characters, and produces up
4887 	     * to 6 characters: reserve space for 2 extra */
4888 	    if (*p == '<')
4889 		extra += 2;
4890 	}
4891     }
4892 
4893     if (*p != '"')
4894     {
4895 	EMSG2(_("E114: Missing quote: %s"), *arg);
4896 	return FAIL;
4897     }
4898 
4899     /* If only parsing, set *arg and return here */
4900     if (!evaluate)
4901     {
4902 	*arg = p + 1;
4903 	return OK;
4904     }
4905 
4906     /*
4907      * Copy the string into allocated memory, handling backslashed
4908      * characters.
4909      */
4910     name = alloc((unsigned)(p - *arg + extra));
4911     if (name == NULL)
4912 	return FAIL;
4913     rettv->v_type = VAR_STRING;
4914     rettv->vval.v_string = name;
4915 
4916     for (p = *arg + 1; *p != NUL && *p != '"'; )
4917     {
4918 	if (*p == '\\')
4919 	{
4920 	    switch (*++p)
4921 	    {
4922 		case 'b': *name++ = BS; ++p; break;
4923 		case 'e': *name++ = ESC; ++p; break;
4924 		case 'f': *name++ = FF; ++p; break;
4925 		case 'n': *name++ = NL; ++p; break;
4926 		case 'r': *name++ = CAR; ++p; break;
4927 		case 't': *name++ = TAB; ++p; break;
4928 
4929 		case 'X': /* hex: "\x1", "\x12" */
4930 		case 'x':
4931 		case 'u': /* Unicode: "\u0023" */
4932 		case 'U':
4933 			  if (vim_isxdigit(p[1]))
4934 			  {
4935 			      int	n, nr;
4936 			      int	c = toupper(*p);
4937 
4938 			      if (c == 'X')
4939 				  n = 2;
4940 			      else if (*p == 'u')
4941 				  n = 4;
4942 			      else
4943 				  n = 8;
4944 			      nr = 0;
4945 			      while (--n >= 0 && vim_isxdigit(p[1]))
4946 			      {
4947 				  ++p;
4948 				  nr = (nr << 4) + hex2nr(*p);
4949 			      }
4950 			      ++p;
4951 #ifdef FEAT_MBYTE
4952 			      /* For "\u" store the number according to
4953 			       * 'encoding'. */
4954 			      if (c != 'X')
4955 				  name += (*mb_char2bytes)(nr, name);
4956 			      else
4957 #endif
4958 				  *name++ = nr;
4959 			  }
4960 			  break;
4961 
4962 			  /* octal: "\1", "\12", "\123" */
4963 		case '0':
4964 		case '1':
4965 		case '2':
4966 		case '3':
4967 		case '4':
4968 		case '5':
4969 		case '6':
4970 		case '7': *name = *p++ - '0';
4971 			  if (*p >= '0' && *p <= '7')
4972 			  {
4973 			      *name = (*name << 3) + *p++ - '0';
4974 			      if (*p >= '0' && *p <= '7')
4975 				  *name = (*name << 3) + *p++ - '0';
4976 			  }
4977 			  ++name;
4978 			  break;
4979 
4980 			    /* Special key, e.g.: "\<C-W>" */
4981 		case '<': extra = trans_special(&p, name, TRUE, TRUE);
4982 			  if (extra != 0)
4983 			  {
4984 			      name += extra;
4985 			      break;
4986 			  }
4987 			  /* FALLTHROUGH */
4988 
4989 		default:  MB_COPY_CHAR(p, name);
4990 			  break;
4991 	    }
4992 	}
4993 	else
4994 	    MB_COPY_CHAR(p, name);
4995 
4996     }
4997     *name = NUL;
4998     if (*p != NUL) /* just in case */
4999 	++p;
5000     *arg = p;
5001 
5002     return OK;
5003 }
5004 
5005 /*
5006  * Allocate a variable for a 'str''ing' constant.
5007  * Return OK or FAIL.
5008  */
5009     static int
5010 get_lit_string_tv(char_u **arg, typval_T *rettv, int evaluate)
5011 {
5012     char_u	*p;
5013     char_u	*str;
5014     int		reduce = 0;
5015 
5016     /*
5017      * Find the end of the string, skipping ''.
5018      */
5019     for (p = *arg + 1; *p != NUL; MB_PTR_ADV(p))
5020     {
5021 	if (*p == '\'')
5022 	{
5023 	    if (p[1] != '\'')
5024 		break;
5025 	    ++reduce;
5026 	    ++p;
5027 	}
5028     }
5029 
5030     if (*p != '\'')
5031     {
5032 	EMSG2(_("E115: Missing quote: %s"), *arg);
5033 	return FAIL;
5034     }
5035 
5036     /* If only parsing return after setting "*arg" */
5037     if (!evaluate)
5038     {
5039 	*arg = p + 1;
5040 	return OK;
5041     }
5042 
5043     /*
5044      * Copy the string into allocated memory, handling '' to ' reduction.
5045      */
5046     str = alloc((unsigned)((p - *arg) - reduce));
5047     if (str == NULL)
5048 	return FAIL;
5049     rettv->v_type = VAR_STRING;
5050     rettv->vval.v_string = str;
5051 
5052     for (p = *arg + 1; *p != NUL; )
5053     {
5054 	if (*p == '\'')
5055 	{
5056 	    if (p[1] != '\'')
5057 		break;
5058 	    ++p;
5059 	}
5060 	MB_COPY_CHAR(p, str);
5061     }
5062     *str = NUL;
5063     *arg = p + 1;
5064 
5065     return OK;
5066 }
5067 
5068 /*
5069  * Return the function name of the partial.
5070  */
5071     char_u *
5072 partial_name(partial_T *pt)
5073 {
5074     if (pt->pt_name != NULL)
5075 	return pt->pt_name;
5076     return pt->pt_func->uf_name;
5077 }
5078 
5079     static void
5080 partial_free(partial_T *pt)
5081 {
5082     int i;
5083 
5084     for (i = 0; i < pt->pt_argc; ++i)
5085 	clear_tv(&pt->pt_argv[i]);
5086     vim_free(pt->pt_argv);
5087     dict_unref(pt->pt_dict);
5088     if (pt->pt_name != NULL)
5089     {
5090 	func_unref(pt->pt_name);
5091 	vim_free(pt->pt_name);
5092     }
5093     else
5094 	func_ptr_unref(pt->pt_func);
5095     vim_free(pt);
5096 }
5097 
5098 /*
5099  * Unreference a closure: decrement the reference count and free it when it
5100  * becomes zero.
5101  */
5102     void
5103 partial_unref(partial_T *pt)
5104 {
5105     if (pt != NULL && --pt->pt_refcount <= 0)
5106 	partial_free(pt);
5107 }
5108 
5109 static int tv_equal_recurse_limit;
5110 
5111     static int
5112 func_equal(
5113     typval_T *tv1,
5114     typval_T *tv2,
5115     int	     ic)	    /* ignore case */
5116 {
5117     char_u	*s1, *s2;
5118     dict_T	*d1, *d2;
5119     int		a1, a2;
5120     int		i;
5121 
5122     /* empty and NULL function name considered the same */
5123     s1 = tv1->v_type == VAR_FUNC ? tv1->vval.v_string
5124 					   : partial_name(tv1->vval.v_partial);
5125     if (s1 != NULL && *s1 == NUL)
5126 	s1 = NULL;
5127     s2 = tv2->v_type == VAR_FUNC ? tv2->vval.v_string
5128 					   : partial_name(tv2->vval.v_partial);
5129     if (s2 != NULL && *s2 == NUL)
5130 	s2 = NULL;
5131     if (s1 == NULL || s2 == NULL)
5132     {
5133 	if (s1 != s2)
5134 	    return FALSE;
5135     }
5136     else if (STRCMP(s1, s2) != 0)
5137 	return FALSE;
5138 
5139     /* empty dict and NULL dict is different */
5140     d1 = tv1->v_type == VAR_FUNC ? NULL : tv1->vval.v_partial->pt_dict;
5141     d2 = tv2->v_type == VAR_FUNC ? NULL : tv2->vval.v_partial->pt_dict;
5142     if (d1 == NULL || d2 == NULL)
5143     {
5144 	if (d1 != d2)
5145 	    return FALSE;
5146     }
5147     else if (!dict_equal(d1, d2, ic, TRUE))
5148 	return FALSE;
5149 
5150     /* empty list and no list considered the same */
5151     a1 = tv1->v_type == VAR_FUNC ? 0 : tv1->vval.v_partial->pt_argc;
5152     a2 = tv2->v_type == VAR_FUNC ? 0 : tv2->vval.v_partial->pt_argc;
5153     if (a1 != a2)
5154 	return FALSE;
5155     for (i = 0; i < a1; ++i)
5156 	if (!tv_equal(tv1->vval.v_partial->pt_argv + i,
5157 		      tv2->vval.v_partial->pt_argv + i, ic, TRUE))
5158 	    return FALSE;
5159 
5160     return TRUE;
5161 }
5162 
5163 /*
5164  * Return TRUE if "tv1" and "tv2" have the same value.
5165  * Compares the items just like "==" would compare them, but strings and
5166  * numbers are different.  Floats and numbers are also different.
5167  */
5168     int
5169 tv_equal(
5170     typval_T *tv1,
5171     typval_T *tv2,
5172     int	     ic,	    /* ignore case */
5173     int	     recursive)	    /* TRUE when used recursively */
5174 {
5175     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5176     char_u	*s1, *s2;
5177     static int  recursive_cnt = 0;	    /* catch recursive loops */
5178     int		r;
5179 
5180     /* Catch lists and dicts that have an endless loop by limiting
5181      * recursiveness to a limit.  We guess they are equal then.
5182      * A fixed limit has the problem of still taking an awful long time.
5183      * Reduce the limit every time running into it. That should work fine for
5184      * deeply linked structures that are not recursively linked and catch
5185      * recursiveness quickly. */
5186     if (!recursive)
5187 	tv_equal_recurse_limit = 1000;
5188     if (recursive_cnt >= tv_equal_recurse_limit)
5189     {
5190 	--tv_equal_recurse_limit;
5191 	return TRUE;
5192     }
5193 
5194     /* For VAR_FUNC and VAR_PARTIAL compare the function name, bound dict and
5195      * arguments. */
5196     if ((tv1->v_type == VAR_FUNC
5197 		|| (tv1->v_type == VAR_PARTIAL && tv1->vval.v_partial != NULL))
5198 	    && (tv2->v_type == VAR_FUNC
5199 		|| (tv2->v_type == VAR_PARTIAL && tv2->vval.v_partial != NULL)))
5200     {
5201 	++recursive_cnt;
5202 	r = func_equal(tv1, tv2, ic);
5203 	--recursive_cnt;
5204 	return r;
5205     }
5206 
5207     if (tv1->v_type != tv2->v_type)
5208 	return FALSE;
5209 
5210     switch (tv1->v_type)
5211     {
5212 	case VAR_LIST:
5213 	    ++recursive_cnt;
5214 	    r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic, TRUE);
5215 	    --recursive_cnt;
5216 	    return r;
5217 
5218 	case VAR_DICT:
5219 	    ++recursive_cnt;
5220 	    r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic, TRUE);
5221 	    --recursive_cnt;
5222 	    return r;
5223 
5224 	case VAR_NUMBER:
5225 	    return tv1->vval.v_number == tv2->vval.v_number;
5226 
5227 	case VAR_STRING:
5228 	    s1 = get_tv_string_buf(tv1, buf1);
5229 	    s2 = get_tv_string_buf(tv2, buf2);
5230 	    return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5231 
5232 	case VAR_SPECIAL:
5233 	    return tv1->vval.v_number == tv2->vval.v_number;
5234 
5235 	case VAR_FLOAT:
5236 #ifdef FEAT_FLOAT
5237 	    return tv1->vval.v_float == tv2->vval.v_float;
5238 #endif
5239 	case VAR_JOB:
5240 #ifdef FEAT_JOB_CHANNEL
5241 	    return tv1->vval.v_job == tv2->vval.v_job;
5242 #endif
5243 	case VAR_CHANNEL:
5244 #ifdef FEAT_JOB_CHANNEL
5245 	    return tv1->vval.v_channel == tv2->vval.v_channel;
5246 #endif
5247 	case VAR_FUNC:
5248 	case VAR_PARTIAL:
5249 	case VAR_UNKNOWN:
5250 	    break;
5251     }
5252 
5253     /* VAR_UNKNOWN can be the result of a invalid expression, let's say it
5254      * does not equal anything, not even itself. */
5255     return FALSE;
5256 }
5257 
5258 /*
5259  * Return the next (unique) copy ID.
5260  * Used for serializing nested structures.
5261  */
5262     int
5263 get_copyID(void)
5264 {
5265     current_copyID += COPYID_INC;
5266     return current_copyID;
5267 }
5268 
5269 /*
5270  * Garbage collection for lists and dictionaries.
5271  *
5272  * We use reference counts to be able to free most items right away when they
5273  * are no longer used.  But for composite items it's possible that it becomes
5274  * unused while the reference count is > 0: When there is a recursive
5275  * reference.  Example:
5276  *	:let l = [1, 2, 3]
5277  *	:let d = {9: l}
5278  *	:let l[1] = d
5279  *
5280  * Since this is quite unusual we handle this with garbage collection: every
5281  * once in a while find out which lists and dicts are not referenced from any
5282  * variable.
5283  *
5284  * Here is a good reference text about garbage collection (refers to Python
5285  * but it applies to all reference-counting mechanisms):
5286  *	http://python.ca/nas/python/gc/
5287  */
5288 
5289 /*
5290  * Do garbage collection for lists and dicts.
5291  * When "testing" is TRUE this is called from test_garbagecollect_now().
5292  * Return TRUE if some memory was freed.
5293  */
5294     int
5295 garbage_collect(int testing)
5296 {
5297     int		copyID;
5298     int		abort = FALSE;
5299     buf_T	*buf;
5300     win_T	*wp;
5301     int		i;
5302     int		did_free = FALSE;
5303     tabpage_T	*tp;
5304 
5305     if (!testing)
5306     {
5307 	/* Only do this once. */
5308 	want_garbage_collect = FALSE;
5309 	may_garbage_collect = FALSE;
5310 	garbage_collect_at_exit = FALSE;
5311     }
5312 
5313     /* We advance by two because we add one for items referenced through
5314      * previous_funccal. */
5315     copyID = get_copyID();
5316 
5317     /*
5318      * 1. Go through all accessible variables and mark all lists and dicts
5319      *    with copyID.
5320      */
5321 
5322     /* Don't free variables in the previous_funccal list unless they are only
5323      * referenced through previous_funccal.  This must be first, because if
5324      * the item is referenced elsewhere the funccal must not be freed. */
5325     abort = abort || set_ref_in_previous_funccal(copyID);
5326 
5327     /* script-local variables */
5328     for (i = 1; i <= ga_scripts.ga_len; ++i)
5329 	abort = abort || set_ref_in_ht(&SCRIPT_VARS(i), copyID, NULL);
5330 
5331     /* buffer-local variables */
5332     FOR_ALL_BUFFERS(buf)
5333 	abort = abort || set_ref_in_item(&buf->b_bufvar.di_tv, copyID,
5334 								  NULL, NULL);
5335 
5336     /* window-local variables */
5337     FOR_ALL_TAB_WINDOWS(tp, wp)
5338 	abort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,
5339 								  NULL, NULL);
5340 #ifdef FEAT_AUTOCMD
5341     if (aucmd_win != NULL)
5342 	abort = abort || set_ref_in_item(&aucmd_win->w_winvar.di_tv, copyID,
5343 								  NULL, NULL);
5344 #endif
5345 
5346     /* tabpage-local variables */
5347     FOR_ALL_TABPAGES(tp)
5348 	abort = abort || set_ref_in_item(&tp->tp_winvar.di_tv, copyID,
5349 								  NULL, NULL);
5350     /* global variables */
5351     abort = abort || set_ref_in_ht(&globvarht, copyID, NULL);
5352 
5353     /* function-local variables */
5354     abort = abort || set_ref_in_call_stack(copyID);
5355 
5356     /* named functions (matters for closures) */
5357     abort = abort || set_ref_in_functions(copyID);
5358 
5359     /* function call arguments, if v:testing is set. */
5360     abort = abort || set_ref_in_func_args(copyID);
5361 
5362     /* v: vars */
5363     abort = abort || set_ref_in_ht(&vimvarht, copyID, NULL);
5364 
5365 #ifdef FEAT_LUA
5366     abort = abort || set_ref_in_lua(copyID);
5367 #endif
5368 
5369 #ifdef FEAT_PYTHON
5370     abort = abort || set_ref_in_python(copyID);
5371 #endif
5372 
5373 #ifdef FEAT_PYTHON3
5374     abort = abort || set_ref_in_python3(copyID);
5375 #endif
5376 
5377 #ifdef FEAT_JOB_CHANNEL
5378     abort = abort || set_ref_in_channel(copyID);
5379     abort = abort || set_ref_in_job(copyID);
5380 #endif
5381 #ifdef FEAT_NETBEANS_INTG
5382     abort = abort || set_ref_in_nb_channel(copyID);
5383 #endif
5384 
5385 #ifdef FEAT_TIMERS
5386     abort = abort || set_ref_in_timer(copyID);
5387 #endif
5388 
5389 #ifdef FEAT_QUICKFIX
5390     abort = abort || set_ref_in_quickfix(copyID);
5391 #endif
5392 
5393 #ifdef FEAT_TERMINAL
5394     abort = abort || set_ref_in_term(copyID);
5395 #endif
5396 
5397     if (!abort)
5398     {
5399 	/*
5400 	 * 2. Free lists and dictionaries that are not referenced.
5401 	 */
5402 	did_free = free_unref_items(copyID);
5403 
5404 	/*
5405 	 * 3. Check if any funccal can be freed now.
5406 	 *    This may call us back recursively.
5407 	 */
5408 	free_unref_funccal(copyID, testing);
5409     }
5410     else if (p_verbose > 0)
5411     {
5412 	verb_msg((char_u *)_("Not enough memory to set references, garbage collection aborted!"));
5413     }
5414 
5415     return did_free;
5416 }
5417 
5418 /*
5419  * Free lists, dictionaries, channels and jobs that are no longer referenced.
5420  */
5421     static int
5422 free_unref_items(int copyID)
5423 {
5424     int		did_free = FALSE;
5425 
5426     /* Let all "free" functions know that we are here.  This means no
5427      * dictionaries, lists, channels or jobs are to be freed, because we will
5428      * do that here. */
5429     in_free_unref_items = TRUE;
5430 
5431     /*
5432      * PASS 1: free the contents of the items.  We don't free the items
5433      * themselves yet, so that it is possible to decrement refcount counters
5434      */
5435 
5436     /* Go through the list of dicts and free items without the copyID. */
5437     did_free |= dict_free_nonref(copyID);
5438 
5439     /* Go through the list of lists and free items without the copyID. */
5440     did_free |= list_free_nonref(copyID);
5441 
5442 #ifdef FEAT_JOB_CHANNEL
5443     /* Go through the list of jobs and free items without the copyID. This
5444      * must happen before doing channels, because jobs refer to channels, but
5445      * the reference from the channel to the job isn't tracked. */
5446     did_free |= free_unused_jobs_contents(copyID, COPYID_MASK);
5447 
5448     /* Go through the list of channels and free items without the copyID.  */
5449     did_free |= free_unused_channels_contents(copyID, COPYID_MASK);
5450 #endif
5451 
5452     /*
5453      * PASS 2: free the items themselves.
5454      */
5455     dict_free_items(copyID);
5456     list_free_items(copyID);
5457 
5458 #ifdef FEAT_JOB_CHANNEL
5459     /* Go through the list of jobs and free items without the copyID. This
5460      * must happen before doing channels, because jobs refer to channels, but
5461      * the reference from the channel to the job isn't tracked. */
5462     free_unused_jobs(copyID, COPYID_MASK);
5463 
5464     /* Go through the list of channels and free items without the copyID.  */
5465     free_unused_channels(copyID, COPYID_MASK);
5466 #endif
5467 
5468     in_free_unref_items = FALSE;
5469 
5470     return did_free;
5471 }
5472 
5473 /*
5474  * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
5475  * "list_stack" is used to add lists to be marked.  Can be NULL.
5476  *
5477  * Returns TRUE if setting references failed somehow.
5478  */
5479     int
5480 set_ref_in_ht(hashtab_T *ht, int copyID, list_stack_T **list_stack)
5481 {
5482     int		todo;
5483     int		abort = FALSE;
5484     hashitem_T	*hi;
5485     hashtab_T	*cur_ht;
5486     ht_stack_T	*ht_stack = NULL;
5487     ht_stack_T	*tempitem;
5488 
5489     cur_ht = ht;
5490     for (;;)
5491     {
5492 	if (!abort)
5493 	{
5494 	    /* Mark each item in the hashtab.  If the item contains a hashtab
5495 	     * it is added to ht_stack, if it contains a list it is added to
5496 	     * list_stack. */
5497 	    todo = (int)cur_ht->ht_used;
5498 	    for (hi = cur_ht->ht_array; todo > 0; ++hi)
5499 		if (!HASHITEM_EMPTY(hi))
5500 		{
5501 		    --todo;
5502 		    abort = abort || set_ref_in_item(&HI2DI(hi)->di_tv, copyID,
5503 						       &ht_stack, list_stack);
5504 		}
5505 	}
5506 
5507 	if (ht_stack == NULL)
5508 	    break;
5509 
5510 	/* take an item from the stack */
5511 	cur_ht = ht_stack->ht;
5512 	tempitem = ht_stack;
5513 	ht_stack = ht_stack->prev;
5514 	free(tempitem);
5515     }
5516 
5517     return abort;
5518 }
5519 
5520 /*
5521  * Mark all lists and dicts referenced through list "l" with "copyID".
5522  * "ht_stack" is used to add hashtabs to be marked.  Can be NULL.
5523  *
5524  * Returns TRUE if setting references failed somehow.
5525  */
5526     int
5527 set_ref_in_list(list_T *l, int copyID, ht_stack_T **ht_stack)
5528 {
5529     listitem_T	 *li;
5530     int		 abort = FALSE;
5531     list_T	 *cur_l;
5532     list_stack_T *list_stack = NULL;
5533     list_stack_T *tempitem;
5534 
5535     cur_l = l;
5536     for (;;)
5537     {
5538 	if (!abort)
5539 	    /* Mark each item in the list.  If the item contains a hashtab
5540 	     * it is added to ht_stack, if it contains a list it is added to
5541 	     * list_stack. */
5542 	    for (li = cur_l->lv_first; !abort && li != NULL; li = li->li_next)
5543 		abort = abort || set_ref_in_item(&li->li_tv, copyID,
5544 						       ht_stack, &list_stack);
5545 	if (list_stack == NULL)
5546 	    break;
5547 
5548 	/* take an item from the stack */
5549 	cur_l = list_stack->list;
5550 	tempitem = list_stack;
5551 	list_stack = list_stack->prev;
5552 	free(tempitem);
5553     }
5554 
5555     return abort;
5556 }
5557 
5558 /*
5559  * Mark all lists and dicts referenced through typval "tv" with "copyID".
5560  * "list_stack" is used to add lists to be marked.  Can be NULL.
5561  * "ht_stack" is used to add hashtabs to be marked.  Can be NULL.
5562  *
5563  * Returns TRUE if setting references failed somehow.
5564  */
5565     int
5566 set_ref_in_item(
5567     typval_T	    *tv,
5568     int		    copyID,
5569     ht_stack_T	    **ht_stack,
5570     list_stack_T    **list_stack)
5571 {
5572     int		abort = FALSE;
5573 
5574     if (tv->v_type == VAR_DICT)
5575     {
5576 	dict_T	*dd = tv->vval.v_dict;
5577 
5578 	if (dd != NULL && dd->dv_copyID != copyID)
5579 	{
5580 	    /* Didn't see this dict yet. */
5581 	    dd->dv_copyID = copyID;
5582 	    if (ht_stack == NULL)
5583 	    {
5584 		abort = set_ref_in_ht(&dd->dv_hashtab, copyID, list_stack);
5585 	    }
5586 	    else
5587 	    {
5588 		ht_stack_T *newitem = (ht_stack_T*)malloc(sizeof(ht_stack_T));
5589 		if (newitem == NULL)
5590 		    abort = TRUE;
5591 		else
5592 		{
5593 		    newitem->ht = &dd->dv_hashtab;
5594 		    newitem->prev = *ht_stack;
5595 		    *ht_stack = newitem;
5596 		}
5597 	    }
5598 	}
5599     }
5600     else if (tv->v_type == VAR_LIST)
5601     {
5602 	list_T	*ll = tv->vval.v_list;
5603 
5604 	if (ll != NULL && ll->lv_copyID != copyID)
5605 	{
5606 	    /* Didn't see this list yet. */
5607 	    ll->lv_copyID = copyID;
5608 	    if (list_stack == NULL)
5609 	    {
5610 		abort = set_ref_in_list(ll, copyID, ht_stack);
5611 	    }
5612 	    else
5613 	    {
5614 		list_stack_T *newitem = (list_stack_T*)malloc(
5615 							sizeof(list_stack_T));
5616 		if (newitem == NULL)
5617 		    abort = TRUE;
5618 		else
5619 		{
5620 		    newitem->list = ll;
5621 		    newitem->prev = *list_stack;
5622 		    *list_stack = newitem;
5623 		}
5624 	    }
5625 	}
5626     }
5627     else if (tv->v_type == VAR_FUNC)
5628     {
5629 	abort = set_ref_in_func(tv->vval.v_string, NULL, copyID);
5630     }
5631     else if (tv->v_type == VAR_PARTIAL)
5632     {
5633 	partial_T	*pt = tv->vval.v_partial;
5634 	int		i;
5635 
5636 	/* A partial does not have a copyID, because it cannot contain itself.
5637 	 */
5638 	if (pt != NULL)
5639 	{
5640 	    abort = set_ref_in_func(pt->pt_name, pt->pt_func, copyID);
5641 
5642 	    if (pt->pt_dict != NULL)
5643 	    {
5644 		typval_T dtv;
5645 
5646 		dtv.v_type = VAR_DICT;
5647 		dtv.vval.v_dict = pt->pt_dict;
5648 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5649 	    }
5650 
5651 	    for (i = 0; i < pt->pt_argc; ++i)
5652 		abort = abort || set_ref_in_item(&pt->pt_argv[i], copyID,
5653 							ht_stack, list_stack);
5654 	}
5655     }
5656 #ifdef FEAT_JOB_CHANNEL
5657     else if (tv->v_type == VAR_JOB)
5658     {
5659 	job_T	    *job = tv->vval.v_job;
5660 	typval_T    dtv;
5661 
5662 	if (job != NULL && job->jv_copyID != copyID)
5663 	{
5664 	    job->jv_copyID = copyID;
5665 	    if (job->jv_channel != NULL)
5666 	    {
5667 		dtv.v_type = VAR_CHANNEL;
5668 		dtv.vval.v_channel = job->jv_channel;
5669 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5670 	    }
5671 	    if (job->jv_exit_partial != NULL)
5672 	    {
5673 		dtv.v_type = VAR_PARTIAL;
5674 		dtv.vval.v_partial = job->jv_exit_partial;
5675 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5676 	    }
5677 	}
5678     }
5679     else if (tv->v_type == VAR_CHANNEL)
5680     {
5681 	channel_T   *ch =tv->vval.v_channel;
5682 	ch_part_T   part;
5683 	typval_T    dtv;
5684 	jsonq_T	    *jq;
5685 	cbq_T	    *cq;
5686 
5687 	if (ch != NULL && ch->ch_copyID != copyID)
5688 	{
5689 	    ch->ch_copyID = copyID;
5690 	    for (part = PART_SOCK; part < PART_COUNT; ++part)
5691 	    {
5692 		for (jq = ch->ch_part[part].ch_json_head.jq_next; jq != NULL;
5693 							     jq = jq->jq_next)
5694 		    set_ref_in_item(jq->jq_value, copyID, ht_stack, list_stack);
5695 		for (cq = ch->ch_part[part].ch_cb_head.cq_next; cq != NULL;
5696 							     cq = cq->cq_next)
5697 		    if (cq->cq_partial != NULL)
5698 		    {
5699 			dtv.v_type = VAR_PARTIAL;
5700 			dtv.vval.v_partial = cq->cq_partial;
5701 			set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5702 		    }
5703 		if (ch->ch_part[part].ch_partial != NULL)
5704 		{
5705 		    dtv.v_type = VAR_PARTIAL;
5706 		    dtv.vval.v_partial = ch->ch_part[part].ch_partial;
5707 		    set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5708 		}
5709 	    }
5710 	    if (ch->ch_partial != NULL)
5711 	    {
5712 		dtv.v_type = VAR_PARTIAL;
5713 		dtv.vval.v_partial = ch->ch_partial;
5714 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5715 	    }
5716 	    if (ch->ch_close_partial != NULL)
5717 	    {
5718 		dtv.v_type = VAR_PARTIAL;
5719 		dtv.vval.v_partial = ch->ch_close_partial;
5720 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
5721 	    }
5722 	}
5723     }
5724 #endif
5725     return abort;
5726 }
5727 
5728     static char *
5729 get_var_special_name(int nr)
5730 {
5731     switch (nr)
5732     {
5733 	case VVAL_FALSE: return "v:false";
5734 	case VVAL_TRUE:  return "v:true";
5735 	case VVAL_NONE:  return "v:none";
5736 	case VVAL_NULL:  return "v:null";
5737     }
5738     internal_error("get_var_special_name()");
5739     return "42";
5740 }
5741 
5742 /*
5743  * Return a string with the string representation of a variable.
5744  * If the memory is allocated "tofree" is set to it, otherwise NULL.
5745  * "numbuf" is used for a number.
5746  * When "copyID" is not NULL replace recursive lists and dicts with "...".
5747  * When both "echo_style" and "composite_val" are FALSE, put quotes around
5748  * stings as "string()", otherwise does not put quotes around strings, as
5749  * ":echo" displays values.
5750  * When "restore_copyID" is FALSE, repeated items in dictionaries and lists
5751  * are replaced with "...".
5752  * May return NULL.
5753  */
5754     char_u *
5755 echo_string_core(
5756     typval_T	*tv,
5757     char_u	**tofree,
5758     char_u	*numbuf,
5759     int		copyID,
5760     int		echo_style,
5761     int		restore_copyID,
5762     int		composite_val)
5763 {
5764     static int	recurse = 0;
5765     char_u	*r = NULL;
5766 
5767     if (recurse >= DICT_MAXNEST)
5768     {
5769 	if (!did_echo_string_emsg)
5770 	{
5771 	    /* Only give this message once for a recursive call to avoid
5772 	     * flooding the user with errors.  And stop iterating over lists
5773 	     * and dicts. */
5774 	    did_echo_string_emsg = TRUE;
5775 	    EMSG(_("E724: variable nested too deep for displaying"));
5776 	}
5777 	*tofree = NULL;
5778 	return (char_u *)"{E724}";
5779     }
5780     ++recurse;
5781 
5782     switch (tv->v_type)
5783     {
5784 	case VAR_STRING:
5785 	    if (echo_style && !composite_val)
5786 	    {
5787 		*tofree = NULL;
5788 		r = tv->vval.v_string;
5789 		if (r == NULL)
5790 		    r = (char_u *)"";
5791 	    }
5792 	    else
5793 	    {
5794 		*tofree = string_quote(tv->vval.v_string, FALSE);
5795 		r = *tofree;
5796 	    }
5797 	    break;
5798 
5799 	case VAR_FUNC:
5800 	    if (echo_style)
5801 	    {
5802 		*tofree = NULL;
5803 		r = tv->vval.v_string;
5804 	    }
5805 	    else
5806 	    {
5807 		*tofree = string_quote(tv->vval.v_string, TRUE);
5808 		r = *tofree;
5809 	    }
5810 	    break;
5811 
5812 	case VAR_PARTIAL:
5813 	    {
5814 		partial_T   *pt = tv->vval.v_partial;
5815 		char_u	    *fname = string_quote(pt == NULL ? NULL
5816 						    : partial_name(pt), FALSE);
5817 		garray_T    ga;
5818 		int	    i;
5819 		char_u	    *tf;
5820 
5821 		ga_init2(&ga, 1, 100);
5822 		ga_concat(&ga, (char_u *)"function(");
5823 		if (fname != NULL)
5824 		{
5825 		    ga_concat(&ga, fname);
5826 		    vim_free(fname);
5827 		}
5828 		if (pt != NULL && pt->pt_argc > 0)
5829 		{
5830 		    ga_concat(&ga, (char_u *)", [");
5831 		    for (i = 0; i < pt->pt_argc; ++i)
5832 		    {
5833 			if (i > 0)
5834 			    ga_concat(&ga, (char_u *)", ");
5835 			ga_concat(&ga,
5836 			     tv2string(&pt->pt_argv[i], &tf, numbuf, copyID));
5837 			vim_free(tf);
5838 		    }
5839 		    ga_concat(&ga, (char_u *)"]");
5840 		}
5841 		if (pt != NULL && pt->pt_dict != NULL)
5842 		{
5843 		    typval_T dtv;
5844 
5845 		    ga_concat(&ga, (char_u *)", ");
5846 		    dtv.v_type = VAR_DICT;
5847 		    dtv.vval.v_dict = pt->pt_dict;
5848 		    ga_concat(&ga, tv2string(&dtv, &tf, numbuf, copyID));
5849 		    vim_free(tf);
5850 		}
5851 		ga_concat(&ga, (char_u *)")");
5852 
5853 		*tofree = ga.ga_data;
5854 		r = *tofree;
5855 		break;
5856 	    }
5857 
5858 	case VAR_LIST:
5859 	    if (tv->vval.v_list == NULL)
5860 	    {
5861 		*tofree = NULL;
5862 		r = NULL;
5863 	    }
5864 	    else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID
5865 		    && tv->vval.v_list->lv_len > 0)
5866 	    {
5867 		*tofree = NULL;
5868 		r = (char_u *)"[...]";
5869 	    }
5870 	    else
5871 	    {
5872 		int old_copyID = tv->vval.v_list->lv_copyID;
5873 
5874 		tv->vval.v_list->lv_copyID = copyID;
5875 		*tofree = list2string(tv, copyID, restore_copyID);
5876 		if (restore_copyID)
5877 		    tv->vval.v_list->lv_copyID = old_copyID;
5878 		r = *tofree;
5879 	    }
5880 	    break;
5881 
5882 	case VAR_DICT:
5883 	    if (tv->vval.v_dict == NULL)
5884 	    {
5885 		*tofree = NULL;
5886 		r = NULL;
5887 	    }
5888 	    else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID
5889 		    && tv->vval.v_dict->dv_hashtab.ht_used != 0)
5890 	    {
5891 		*tofree = NULL;
5892 		r = (char_u *)"{...}";
5893 	    }
5894 	    else
5895 	    {
5896 		int old_copyID = tv->vval.v_dict->dv_copyID;
5897 		tv->vval.v_dict->dv_copyID = copyID;
5898 		*tofree = dict2string(tv, copyID, restore_copyID);
5899 		if (restore_copyID)
5900 		    tv->vval.v_dict->dv_copyID = old_copyID;
5901 		r = *tofree;
5902 	    }
5903 	    break;
5904 
5905 	case VAR_NUMBER:
5906 	case VAR_UNKNOWN:
5907 	    *tofree = NULL;
5908 	    r = get_tv_string_buf(tv, numbuf);
5909 	    break;
5910 
5911 	case VAR_JOB:
5912 	case VAR_CHANNEL:
5913 	    *tofree = NULL;
5914 	    r = get_tv_string_buf(tv, numbuf);
5915 	    if (composite_val)
5916 	    {
5917 		*tofree = string_quote(r, FALSE);
5918 		r = *tofree;
5919 	    }
5920 	    break;
5921 
5922 	case VAR_FLOAT:
5923 #ifdef FEAT_FLOAT
5924 	    *tofree = NULL;
5925 	    vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
5926 	    r = numbuf;
5927 	    break;
5928 #endif
5929 
5930 	case VAR_SPECIAL:
5931 	    *tofree = NULL;
5932 	    r = (char_u *)get_var_special_name(tv->vval.v_number);
5933 	    break;
5934     }
5935 
5936     if (--recurse == 0)
5937 	did_echo_string_emsg = FALSE;
5938     return r;
5939 }
5940 
5941 /*
5942  * Return a string with the string representation of a variable.
5943  * If the memory is allocated "tofree" is set to it, otherwise NULL.
5944  * "numbuf" is used for a number.
5945  * Does not put quotes around strings, as ":echo" displays values.
5946  * When "copyID" is not NULL replace recursive lists and dicts with "...".
5947  * May return NULL.
5948  */
5949     char_u *
5950 echo_string(
5951     typval_T	*tv,
5952     char_u	**tofree,
5953     char_u	*numbuf,
5954     int		copyID)
5955 {
5956     return echo_string_core(tv, tofree, numbuf, copyID, TRUE, FALSE, FALSE);
5957 }
5958 
5959 /*
5960  * Return a string with the string representation of a variable.
5961  * If the memory is allocated "tofree" is set to it, otherwise NULL.
5962  * "numbuf" is used for a number.
5963  * Puts quotes around strings, so that they can be parsed back by eval().
5964  * May return NULL.
5965  */
5966     char_u *
5967 tv2string(
5968     typval_T	*tv,
5969     char_u	**tofree,
5970     char_u	*numbuf,
5971     int		copyID)
5972 {
5973     return echo_string_core(tv, tofree, numbuf, copyID, FALSE, TRUE, FALSE);
5974 }
5975 
5976 /*
5977  * Return string "str" in ' quotes, doubling ' characters.
5978  * If "str" is NULL an empty string is assumed.
5979  * If "function" is TRUE make it function('string').
5980  */
5981     char_u *
5982 string_quote(char_u *str, int function)
5983 {
5984     unsigned	len;
5985     char_u	*p, *r, *s;
5986 
5987     len = (function ? 13 : 3);
5988     if (str != NULL)
5989     {
5990 	len += (unsigned)STRLEN(str);
5991 	for (p = str; *p != NUL; MB_PTR_ADV(p))
5992 	    if (*p == '\'')
5993 		++len;
5994     }
5995     s = r = alloc(len);
5996     if (r != NULL)
5997     {
5998 	if (function)
5999 	{
6000 	    STRCPY(r, "function('");
6001 	    r += 10;
6002 	}
6003 	else
6004 	    *r++ = '\'';
6005 	if (str != NULL)
6006 	    for (p = str; *p != NUL; )
6007 	    {
6008 		if (*p == '\'')
6009 		    *r++ = '\'';
6010 		MB_COPY_CHAR(p, r);
6011 	    }
6012 	*r++ = '\'';
6013 	if (function)
6014 	    *r++ = ')';
6015 	*r++ = NUL;
6016     }
6017     return s;
6018 }
6019 
6020 #if defined(FEAT_FLOAT) || defined(PROTO)
6021 /*
6022  * Convert the string "text" to a floating point number.
6023  * This uses strtod().  setlocale(LC_NUMERIC, "C") has been used to make sure
6024  * this always uses a decimal point.
6025  * Returns the length of the text that was consumed.
6026  */
6027     int
6028 string2float(
6029     char_u	*text,
6030     float_T	*value)	    /* result stored here */
6031 {
6032     char	*s = (char *)text;
6033     float_T	f;
6034 
6035     /* MS-Windows does not deal with "inf" and "nan" properly. */
6036     if (STRNICMP(text, "inf", 3) == 0)
6037     {
6038 	*value = INFINITY;
6039 	return 3;
6040     }
6041     if (STRNICMP(text, "-inf", 3) == 0)
6042     {
6043 	*value = -INFINITY;
6044 	return 4;
6045     }
6046     if (STRNICMP(text, "nan", 3) == 0)
6047     {
6048 	*value = NAN;
6049 	return 3;
6050     }
6051     f = strtod(s, &s);
6052     *value = f;
6053     return (int)((char_u *)s - text);
6054 }
6055 #endif
6056 
6057 /*
6058  * Get the value of an environment variable.
6059  * "arg" is pointing to the '$'.  It is advanced to after the name.
6060  * If the environment variable was not set, silently assume it is empty.
6061  * Return FAIL if the name is invalid.
6062  */
6063     static int
6064 get_env_tv(char_u **arg, typval_T *rettv, int evaluate)
6065 {
6066     char_u	*string = NULL;
6067     int		len;
6068     int		cc;
6069     char_u	*name;
6070     int		mustfree = FALSE;
6071 
6072     ++*arg;
6073     name = *arg;
6074     len = get_env_len(arg);
6075     if (evaluate)
6076     {
6077 	if (len == 0)
6078 	    return FAIL; /* invalid empty name */
6079 
6080 	cc = name[len];
6081 	name[len] = NUL;
6082 	/* first try vim_getenv(), fast for normal environment vars */
6083 	string = vim_getenv(name, &mustfree);
6084 	if (string != NULL && *string != NUL)
6085 	{
6086 	    if (!mustfree)
6087 		string = vim_strsave(string);
6088 	}
6089 	else
6090 	{
6091 	    if (mustfree)
6092 		vim_free(string);
6093 
6094 	    /* next try expanding things like $VIM and ${HOME} */
6095 	    string = expand_env_save(name - 1);
6096 	    if (string != NULL && *string == '$')
6097 	    {
6098 		vim_free(string);
6099 		string = NULL;
6100 	    }
6101 	}
6102 	name[len] = cc;
6103 
6104 	rettv->v_type = VAR_STRING;
6105 	rettv->vval.v_string = string;
6106     }
6107 
6108     return OK;
6109 }
6110 
6111 
6112 
6113 /*
6114  * Translate a String variable into a position.
6115  * Returns NULL when there is an error.
6116  */
6117     pos_T *
6118 var2fpos(
6119     typval_T	*varp,
6120     int		dollar_lnum,	/* TRUE when $ is last line */
6121     int		*fnum)		/* set to fnum for '0, 'A, etc. */
6122 {
6123     char_u		*name;
6124     static pos_T	pos;
6125     pos_T		*pp;
6126 
6127     /* Argument can be [lnum, col, coladd]. */
6128     if (varp->v_type == VAR_LIST)
6129     {
6130 	list_T		*l;
6131 	int		len;
6132 	int		error = FALSE;
6133 	listitem_T	*li;
6134 
6135 	l = varp->vval.v_list;
6136 	if (l == NULL)
6137 	    return NULL;
6138 
6139 	/* Get the line number */
6140 	pos.lnum = list_find_nr(l, 0L, &error);
6141 	if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
6142 	    return NULL;	/* invalid line number */
6143 
6144 	/* Get the column number */
6145 	pos.col = list_find_nr(l, 1L, &error);
6146 	if (error)
6147 	    return NULL;
6148 	len = (long)STRLEN(ml_get(pos.lnum));
6149 
6150 	/* We accept "$" for the column number: last column. */
6151 	li = list_find(l, 1L);
6152 	if (li != NULL && li->li_tv.v_type == VAR_STRING
6153 		&& li->li_tv.vval.v_string != NULL
6154 		&& STRCMP(li->li_tv.vval.v_string, "$") == 0)
6155 	    pos.col = len + 1;
6156 
6157 	/* Accept a position up to the NUL after the line. */
6158 	if (pos.col == 0 || (int)pos.col > len + 1)
6159 	    return NULL;	/* invalid column number */
6160 	--pos.col;
6161 
6162 #ifdef FEAT_VIRTUALEDIT
6163 	/* Get the virtual offset.  Defaults to zero. */
6164 	pos.coladd = list_find_nr(l, 2L, &error);
6165 	if (error)
6166 	    pos.coladd = 0;
6167 #endif
6168 
6169 	return &pos;
6170     }
6171 
6172     name = get_tv_string_chk(varp);
6173     if (name == NULL)
6174 	return NULL;
6175     if (name[0] == '.')				/* cursor */
6176 	return &curwin->w_cursor;
6177     if (name[0] == 'v' && name[1] == NUL)	/* Visual start */
6178     {
6179 	if (VIsual_active)
6180 	    return &VIsual;
6181 	return &curwin->w_cursor;
6182     }
6183     if (name[0] == '\'')			/* mark */
6184     {
6185 	pp = getmark_buf_fnum(curbuf, name[1], FALSE, fnum);
6186 	if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
6187 	    return NULL;
6188 	return pp;
6189     }
6190 
6191 #ifdef FEAT_VIRTUALEDIT
6192     pos.coladd = 0;
6193 #endif
6194 
6195     if (name[0] == 'w' && dollar_lnum)
6196     {
6197 	pos.col = 0;
6198 	if (name[1] == '0')		/* "w0": first visible line */
6199 	{
6200 	    update_topline();
6201 	    /* In silent Ex mode topline is zero, but that's not a valid line
6202 	     * number; use one instead. */
6203 	    pos.lnum = curwin->w_topline > 0 ? curwin->w_topline : 1;
6204 	    return &pos;
6205 	}
6206 	else if (name[1] == '$')	/* "w$": last visible line */
6207 	{
6208 	    validate_botline();
6209 	    /* In silent Ex mode botline is zero, return zero then. */
6210 	    pos.lnum = curwin->w_botline > 0 ? curwin->w_botline - 1 : 0;
6211 	    return &pos;
6212 	}
6213     }
6214     else if (name[0] == '$')		/* last column or line */
6215     {
6216 	if (dollar_lnum)
6217 	{
6218 	    pos.lnum = curbuf->b_ml.ml_line_count;
6219 	    pos.col = 0;
6220 	}
6221 	else
6222 	{
6223 	    pos.lnum = curwin->w_cursor.lnum;
6224 	    pos.col = (colnr_T)STRLEN(ml_get_curline());
6225 	}
6226 	return &pos;
6227     }
6228     return NULL;
6229 }
6230 
6231 /*
6232  * Convert list in "arg" into a position and optional file number.
6233  * When "fnump" is NULL there is no file number, only 3 items.
6234  * Note that the column is passed on as-is, the caller may want to decrement
6235  * it to use 1 for the first column.
6236  * Return FAIL when conversion is not possible, doesn't check the position for
6237  * validity.
6238  */
6239     int
6240 list2fpos(
6241     typval_T	*arg,
6242     pos_T	*posp,
6243     int		*fnump,
6244     colnr_T	*curswantp)
6245 {
6246     list_T	*l = arg->vval.v_list;
6247     long	i = 0;
6248     long	n;
6249 
6250     /* List must be: [fnum, lnum, col, coladd, curswant], where "fnum" is only
6251      * there when "fnump" isn't NULL; "coladd" and "curswant" are optional. */
6252     if (arg->v_type != VAR_LIST
6253 	    || l == NULL
6254 	    || l->lv_len < (fnump == NULL ? 2 : 3)
6255 	    || l->lv_len > (fnump == NULL ? 4 : 5))
6256 	return FAIL;
6257 
6258     if (fnump != NULL)
6259     {
6260 	n = list_find_nr(l, i++, NULL);	/* fnum */
6261 	if (n < 0)
6262 	    return FAIL;
6263 	if (n == 0)
6264 	    n = curbuf->b_fnum;		/* current buffer */
6265 	*fnump = n;
6266     }
6267 
6268     n = list_find_nr(l, i++, NULL);	/* lnum */
6269     if (n < 0)
6270 	return FAIL;
6271     posp->lnum = n;
6272 
6273     n = list_find_nr(l, i++, NULL);	/* col */
6274     if (n < 0)
6275 	return FAIL;
6276     posp->col = n;
6277 
6278 #ifdef FEAT_VIRTUALEDIT
6279     n = list_find_nr(l, i, NULL);	/* off */
6280     if (n < 0)
6281 	posp->coladd = 0;
6282     else
6283 	posp->coladd = n;
6284 #endif
6285 
6286     if (curswantp != NULL)
6287 	*curswantp = list_find_nr(l, i + 1, NULL);  /* curswant */
6288 
6289     return OK;
6290 }
6291 
6292 /*
6293  * Get the length of an environment variable name.
6294  * Advance "arg" to the first character after the name.
6295  * Return 0 for error.
6296  */
6297     static int
6298 get_env_len(char_u **arg)
6299 {
6300     char_u	*p;
6301     int		len;
6302 
6303     for (p = *arg; vim_isIDc(*p); ++p)
6304 	;
6305     if (p == *arg)	    /* no name found */
6306 	return 0;
6307 
6308     len = (int)(p - *arg);
6309     *arg = p;
6310     return len;
6311 }
6312 
6313 /*
6314  * Get the length of the name of a function or internal variable.
6315  * "arg" is advanced to the first non-white character after the name.
6316  * Return 0 if something is wrong.
6317  */
6318     int
6319 get_id_len(char_u **arg)
6320 {
6321     char_u	*p;
6322     int		len;
6323 
6324     /* Find the end of the name. */
6325     for (p = *arg; eval_isnamec(*p); ++p)
6326     {
6327 	if (*p == ':')
6328 	{
6329 	    /* "s:" is start of "s:var", but "n:" is not and can be used in
6330 	     * slice "[n:]".  Also "xx:" is not a namespace. */
6331 	    len = (int)(p - *arg);
6332 	    if ((len == 1 && vim_strchr(NAMESPACE_CHAR, **arg) == NULL)
6333 		    || len > 1)
6334 		break;
6335 	}
6336     }
6337     if (p == *arg)	    /* no name found */
6338 	return 0;
6339 
6340     len = (int)(p - *arg);
6341     *arg = skipwhite(p);
6342 
6343     return len;
6344 }
6345 
6346 /*
6347  * Get the length of the name of a variable or function.
6348  * Only the name is recognized, does not handle ".key" or "[idx]".
6349  * "arg" is advanced to the first non-white character after the name.
6350  * Return -1 if curly braces expansion failed.
6351  * Return 0 if something else is wrong.
6352  * If the name contains 'magic' {}'s, expand them and return the
6353  * expanded name in an allocated string via 'alias' - caller must free.
6354  */
6355     int
6356 get_name_len(
6357     char_u	**arg,
6358     char_u	**alias,
6359     int		evaluate,
6360     int		verbose)
6361 {
6362     int		len;
6363     char_u	*p;
6364     char_u	*expr_start;
6365     char_u	*expr_end;
6366 
6367     *alias = NULL;  /* default to no alias */
6368 
6369     if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
6370 						  && (*arg)[2] == (int)KE_SNR)
6371     {
6372 	/* hard coded <SNR>, already translated */
6373 	*arg += 3;
6374 	return get_id_len(arg) + 3;
6375     }
6376     len = eval_fname_script(*arg);
6377     if (len > 0)
6378     {
6379 	/* literal "<SID>", "s:" or "<SNR>" */
6380 	*arg += len;
6381     }
6382 
6383     /*
6384      * Find the end of the name; check for {} construction.
6385      */
6386     p = find_name_end(*arg, &expr_start, &expr_end,
6387 					       len > 0 ? 0 : FNE_CHECK_START);
6388     if (expr_start != NULL)
6389     {
6390 	char_u	*temp_string;
6391 
6392 	if (!evaluate)
6393 	{
6394 	    len += (int)(p - *arg);
6395 	    *arg = skipwhite(p);
6396 	    return len;
6397 	}
6398 
6399 	/*
6400 	 * Include any <SID> etc in the expanded string:
6401 	 * Thus the -len here.
6402 	 */
6403 	temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
6404 	if (temp_string == NULL)
6405 	    return -1;
6406 	*alias = temp_string;
6407 	*arg = skipwhite(p);
6408 	return (int)STRLEN(temp_string);
6409     }
6410 
6411     len += get_id_len(arg);
6412     if (len == 0 && verbose)
6413 	EMSG2(_(e_invexpr2), *arg);
6414 
6415     return len;
6416 }
6417 
6418 /*
6419  * Find the end of a variable or function name, taking care of magic braces.
6420  * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
6421  * start and end of the first magic braces item.
6422  * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
6423  * Return a pointer to just after the name.  Equal to "arg" if there is no
6424  * valid name.
6425  */
6426     char_u *
6427 find_name_end(
6428     char_u	*arg,
6429     char_u	**expr_start,
6430     char_u	**expr_end,
6431     int		flags)
6432 {
6433     int		mb_nest = 0;
6434     int		br_nest = 0;
6435     char_u	*p;
6436     int		len;
6437 
6438     if (expr_start != NULL)
6439     {
6440 	*expr_start = NULL;
6441 	*expr_end = NULL;
6442     }
6443 
6444     /* Quick check for valid starting character. */
6445     if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
6446 	return arg;
6447 
6448     for (p = arg; *p != NUL
6449 		    && (eval_isnamec(*p)
6450 			|| *p == '{'
6451 			|| ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
6452 			|| mb_nest != 0
6453 			|| br_nest != 0); MB_PTR_ADV(p))
6454     {
6455 	if (*p == '\'')
6456 	{
6457 	    /* skip over 'string' to avoid counting [ and ] inside it. */
6458 	    for (p = p + 1; *p != NUL && *p != '\''; MB_PTR_ADV(p))
6459 		;
6460 	    if (*p == NUL)
6461 		break;
6462 	}
6463 	else if (*p == '"')
6464 	{
6465 	    /* skip over "str\"ing" to avoid counting [ and ] inside it. */
6466 	    for (p = p + 1; *p != NUL && *p != '"'; MB_PTR_ADV(p))
6467 		if (*p == '\\' && p[1] != NUL)
6468 		    ++p;
6469 	    if (*p == NUL)
6470 		break;
6471 	}
6472 	else if (br_nest == 0 && mb_nest == 0 && *p == ':')
6473 	{
6474 	    /* "s:" is start of "s:var", but "n:" is not and can be used in
6475 	     * slice "[n:]".  Also "xx:" is not a namespace. But {ns}: is. */
6476 	    len = (int)(p - arg);
6477 	    if ((len == 1 && vim_strchr(NAMESPACE_CHAR, *arg) == NULL)
6478 		    || (len > 1 && p[-1] != '}'))
6479 		break;
6480 	}
6481 
6482 	if (mb_nest == 0)
6483 	{
6484 	    if (*p == '[')
6485 		++br_nest;
6486 	    else if (*p == ']')
6487 		--br_nest;
6488 	}
6489 
6490 	if (br_nest == 0)
6491 	{
6492 	    if (*p == '{')
6493 	    {
6494 		mb_nest++;
6495 		if (expr_start != NULL && *expr_start == NULL)
6496 		    *expr_start = p;
6497 	    }
6498 	    else if (*p == '}')
6499 	    {
6500 		mb_nest--;
6501 		if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
6502 		    *expr_end = p;
6503 	    }
6504 	}
6505     }
6506 
6507     return p;
6508 }
6509 
6510 /*
6511  * Expands out the 'magic' {}'s in a variable/function name.
6512  * Note that this can call itself recursively, to deal with
6513  * constructs like foo{bar}{baz}{bam}
6514  * The four pointer arguments point to "foo{expre}ss{ion}bar"
6515  *			"in_start"      ^
6516  *			"expr_start"	   ^
6517  *			"expr_end"		 ^
6518  *			"in_end"			    ^
6519  *
6520  * Returns a new allocated string, which the caller must free.
6521  * Returns NULL for failure.
6522  */
6523     static char_u *
6524 make_expanded_name(
6525     char_u	*in_start,
6526     char_u	*expr_start,
6527     char_u	*expr_end,
6528     char_u	*in_end)
6529 {
6530     char_u	c1;
6531     char_u	*retval = NULL;
6532     char_u	*temp_result;
6533     char_u	*nextcmd = NULL;
6534 
6535     if (expr_end == NULL || in_end == NULL)
6536 	return NULL;
6537     *expr_start	= NUL;
6538     *expr_end = NUL;
6539     c1 = *in_end;
6540     *in_end = NUL;
6541 
6542     temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
6543     if (temp_result != NULL && nextcmd == NULL)
6544     {
6545 	retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
6546 						   + (in_end - expr_end) + 1));
6547 	if (retval != NULL)
6548 	{
6549 	    STRCPY(retval, in_start);
6550 	    STRCAT(retval, temp_result);
6551 	    STRCAT(retval, expr_end + 1);
6552 	}
6553     }
6554     vim_free(temp_result);
6555 
6556     *in_end = c1;		/* put char back for error messages */
6557     *expr_start = '{';
6558     *expr_end = '}';
6559 
6560     if (retval != NULL)
6561     {
6562 	temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
6563 	if (expr_start != NULL)
6564 	{
6565 	    /* Further expansion! */
6566 	    temp_result = make_expanded_name(retval, expr_start,
6567 						       expr_end, temp_result);
6568 	    vim_free(retval);
6569 	    retval = temp_result;
6570 	}
6571     }
6572 
6573     return retval;
6574 }
6575 
6576 /*
6577  * Return TRUE if character "c" can be used in a variable or function name.
6578  * Does not include '{' or '}' for magic braces.
6579  */
6580     int
6581 eval_isnamec(int c)
6582 {
6583     return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
6584 }
6585 
6586 /*
6587  * Return TRUE if character "c" can be used as the first character in a
6588  * variable or function name (excluding '{' and '}').
6589  */
6590     int
6591 eval_isnamec1(int c)
6592 {
6593     return (ASCII_ISALPHA(c) || c == '_');
6594 }
6595 
6596 /*
6597  * Set number v: variable to "val".
6598  */
6599     void
6600 set_vim_var_nr(int idx, varnumber_T val)
6601 {
6602     vimvars[idx].vv_nr = val;
6603 }
6604 
6605 /*
6606  * Get number v: variable value.
6607  */
6608     varnumber_T
6609 get_vim_var_nr(int idx)
6610 {
6611     return vimvars[idx].vv_nr;
6612 }
6613 
6614 /*
6615  * Get string v: variable value.  Uses a static buffer, can only be used once.
6616  * If the String variable has never been set, return an empty string.
6617  * Never returns NULL;
6618  */
6619     char_u *
6620 get_vim_var_str(int idx)
6621 {
6622     return get_tv_string(&vimvars[idx].vv_tv);
6623 }
6624 
6625 /*
6626  * Get List v: variable value.  Caller must take care of reference count when
6627  * needed.
6628  */
6629     list_T *
6630 get_vim_var_list(int idx)
6631 {
6632     return vimvars[idx].vv_list;
6633 }
6634 
6635 /*
6636  * Set v:char to character "c".
6637  */
6638     void
6639 set_vim_var_char(int c)
6640 {
6641     char_u	buf[MB_MAXBYTES + 1];
6642 
6643 #ifdef FEAT_MBYTE
6644     if (has_mbyte)
6645 	buf[(*mb_char2bytes)(c, buf)] = NUL;
6646     else
6647 #endif
6648     {
6649 	buf[0] = c;
6650 	buf[1] = NUL;
6651     }
6652     set_vim_var_string(VV_CHAR, buf, -1);
6653 }
6654 
6655 /*
6656  * Set v:count to "count" and v:count1 to "count1".
6657  * When "set_prevcount" is TRUE first set v:prevcount from v:count.
6658  */
6659     void
6660 set_vcount(
6661     long	count,
6662     long	count1,
6663     int		set_prevcount)
6664 {
6665     if (set_prevcount)
6666 	vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
6667     vimvars[VV_COUNT].vv_nr = count;
6668     vimvars[VV_COUNT1].vv_nr = count1;
6669 }
6670 
6671 /*
6672  * Set string v: variable to a copy of "val".
6673  */
6674     void
6675 set_vim_var_string(
6676     int		idx,
6677     char_u	*val,
6678     int		len)	    /* length of "val" to use or -1 (whole string) */
6679 {
6680     clear_tv(&vimvars[idx].vv_di.di_tv);
6681     vimvars[idx].vv_type = VAR_STRING;
6682     if (val == NULL)
6683 	vimvars[idx].vv_str = NULL;
6684     else if (len == -1)
6685 	vimvars[idx].vv_str = vim_strsave(val);
6686     else
6687 	vimvars[idx].vv_str = vim_strnsave(val, len);
6688 }
6689 
6690 /*
6691  * Set List v: variable to "val".
6692  */
6693     void
6694 set_vim_var_list(int idx, list_T *val)
6695 {
6696     clear_tv(&vimvars[idx].vv_di.di_tv);
6697     vimvars[idx].vv_type = VAR_LIST;
6698     vimvars[idx].vv_list = val;
6699     if (val != NULL)
6700 	++val->lv_refcount;
6701 }
6702 
6703 /*
6704  * Set Dictionary v: variable to "val".
6705  */
6706     void
6707 set_vim_var_dict(int idx, dict_T *val)
6708 {
6709     int		todo;
6710     hashitem_T	*hi;
6711 
6712     clear_tv(&vimvars[idx].vv_di.di_tv);
6713     vimvars[idx].vv_type = VAR_DICT;
6714     vimvars[idx].vv_dict = val;
6715     if (val != NULL)
6716     {
6717 	++val->dv_refcount;
6718 
6719 	/* Set readonly */
6720 	todo = (int)val->dv_hashtab.ht_used;
6721 	for (hi = val->dv_hashtab.ht_array; todo > 0 ; ++hi)
6722 	{
6723 	    if (HASHITEM_EMPTY(hi))
6724 		continue;
6725 	    --todo;
6726 	    HI2DI(hi)->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX;
6727 	}
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