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