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