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