xref: /vim-8.2.3635/src/eval.c (revision 06fe74ae)
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 static char *e_missbrac = N_("E111: Missing ']'");
24 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
25 #ifdef FEAT_FLOAT
26 static char *e_float_as_string = N_("E806: using Float as a String");
27 #endif
28 static char *e_nowhitespace = N_("E274: No white space allowed before parenthesis");
29 
30 #define NAMESPACE_CHAR	(char_u *)"abglstvw"
31 
32 /*
33  * When recursively copying lists and dicts we need to remember which ones we
34  * have done to avoid endless recursiveness.  This unique ID is used for that.
35  * The last bit is used for previous_funccal, ignored when comparing.
36  */
37 static int current_copyID = 0;
38 
39 static int echo_attr = 0;   /* attributes used for ":echo" */
40 
41 /* The names of packages that once were loaded are remembered. */
42 static garray_T		ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
43 
44 /*
45  * Info used by a ":for" loop.
46  */
47 typedef struct
48 {
49     int		fi_semicolon;	/* TRUE if ending in '; var]' */
50     int		fi_varcount;	/* nr of variables in the list */
51     listwatch_T	fi_lw;		/* keep an eye on the item used. */
52     list_T	*fi_list;	/* list being used */
53     int		fi_bi;		/* index of blob */
54     blob_T	*fi_blob;	/* blob being used */
55 } forinfo_T;
56 
57 static int tv_op(typval_T *tv1, typval_T *tv2, char_u  *op);
58 static int eval2(char_u **arg, typval_T *rettv, int evaluate);
59 static int eval3(char_u **arg, typval_T *rettv, int evaluate);
60 static int eval4(char_u **arg, typval_T *rettv, int evaluate);
61 static int eval5(char_u **arg, typval_T *rettv, int evaluate);
62 static int eval6(char_u **arg, typval_T *rettv, int evaluate, int want_string);
63 static int eval7(char_u **arg, typval_T *rettv, int evaluate, int want_string);
64 static int eval7_leader(typval_T *rettv, char_u *start_leader, char_u **end_leaderp);
65 
66 static int get_string_tv(char_u **arg, typval_T *rettv, int evaluate);
67 static int get_lit_string_tv(char_u **arg, typval_T *rettv, int evaluate);
68 static int free_unref_items(int copyID);
69 static int get_env_tv(char_u **arg, typval_T *rettv, int evaluate);
70 static char_u *make_expanded_name(char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end);
71 static int tv_check_lock(typval_T *tv, char_u *name, int use_gettext);
72 
73 /*
74  * Return "n1" divided by "n2", taking care of dividing by zero.
75  */
76 	varnumber_T
77 num_divide(varnumber_T n1, varnumber_T n2)
78 {
79     varnumber_T	result;
80 
81     if (n2 == 0)	// give an error message?
82     {
83 	if (n1 == 0)
84 	    result = VARNUM_MIN; // similar to NaN
85 	else if (n1 < 0)
86 	    result = -VARNUM_MAX;
87 	else
88 	    result = VARNUM_MAX;
89     }
90     else
91 	result = n1 / n2;
92 
93     return result;
94 }
95 
96 /*
97  * Return "n1" modulus "n2", taking care of dividing by zero.
98  */
99 	varnumber_T
100 num_modulus(varnumber_T n1, varnumber_T n2)
101 {
102     // Give an error when n2 is 0?
103     return (n2 == 0) ? 0 : (n1 % n2);
104 }
105 
106 #if defined(EBCDIC) || defined(PROTO)
107 /*
108  * Compare struct fst by function name.
109  */
110     static int
111 compare_func_name(const void *s1, const void *s2)
112 {
113     struct fst *p1 = (struct fst *)s1;
114     struct fst *p2 = (struct fst *)s2;
115 
116     return STRCMP(p1->f_name, p2->f_name);
117 }
118 
119 /*
120  * Sort the function table by function name.
121  * The sorting of the table above is ASCII dependent.
122  * On machines using EBCDIC we have to sort it.
123  */
124     static void
125 sortFunctions(void)
126 {
127     int		funcCnt = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
128 
129     qsort(functions, (size_t)funcCnt, sizeof(struct fst), compare_func_name);
130 }
131 #endif
132 
133 /*
134  * Initialize the global and v: variables.
135  */
136     void
137 eval_init(void)
138 {
139     evalvars_init();
140     func_init();
141 
142 #ifdef EBCDIC
143     /*
144      * Sort the function table, to enable binary search.
145      */
146     sortFunctions();
147 #endif
148 }
149 
150 #if defined(EXITFREE) || defined(PROTO)
151     void
152 eval_clear(void)
153 {
154     evalvars_clear();
155 
156     free_scriptnames();
157     free_locales();
158 
159     /* autoloaded script names */
160     ga_clear_strings(&ga_loaded);
161 
162     // unreferenced lists and dicts
163     (void)garbage_collect(FALSE);
164 
165     // functions not garbage collected
166     free_all_functions();
167 }
168 #endif
169 
170 static lval_T	*redir_lval = NULL;
171 #define EVALCMD_BUSY (redir_lval == (lval_T *)&redir_lval)
172 static garray_T redir_ga;	/* only valid when redir_lval is not NULL */
173 static char_u	*redir_endp = NULL;
174 static char_u	*redir_varname = NULL;
175 
176 /*
177  * Start recording command output to a variable
178  * When "append" is TRUE append to an existing variable.
179  * Returns OK if successfully completed the setup.  FAIL otherwise.
180  */
181     int
182 var_redir_start(char_u *name, int append)
183 {
184     int		save_emsg;
185     int		err;
186     typval_T	tv;
187 
188     /* Catch a bad name early. */
189     if (!eval_isnamec1(*name))
190     {
191 	emsg(_(e_invarg));
192 	return FAIL;
193     }
194 
195     /* Make a copy of the name, it is used in redir_lval until redir ends. */
196     redir_varname = vim_strsave(name);
197     if (redir_varname == NULL)
198 	return FAIL;
199 
200     redir_lval = ALLOC_CLEAR_ONE(lval_T);
201     if (redir_lval == NULL)
202     {
203 	var_redir_stop();
204 	return FAIL;
205     }
206 
207     /* The output is stored in growarray "redir_ga" until redirection ends. */
208     ga_init2(&redir_ga, (int)sizeof(char), 500);
209 
210     /* Parse the variable name (can be a dict or list entry). */
211     redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, 0,
212 							     FNE_CHECK_START);
213     if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
214     {
215 	clear_lval(redir_lval);
216 	if (redir_endp != NULL && *redir_endp != NUL)
217 	    /* Trailing characters are present after the variable name */
218 	    emsg(_(e_trailing));
219 	else
220 	    emsg(_(e_invarg));
221 	redir_endp = NULL;  /* don't store a value, only cleanup */
222 	var_redir_stop();
223 	return FAIL;
224     }
225 
226     /* check if we can write to the variable: set it to or append an empty
227      * string */
228     save_emsg = did_emsg;
229     did_emsg = FALSE;
230     tv.v_type = VAR_STRING;
231     tv.vval.v_string = (char_u *)"";
232     if (append)
233 	set_var_lval(redir_lval, redir_endp, &tv, TRUE, FALSE, (char_u *)".");
234     else
235 	set_var_lval(redir_lval, redir_endp, &tv, TRUE, FALSE, (char_u *)"=");
236     clear_lval(redir_lval);
237     err = did_emsg;
238     did_emsg |= save_emsg;
239     if (err)
240     {
241 	redir_endp = NULL;  /* don't store a value, only cleanup */
242 	var_redir_stop();
243 	return FAIL;
244     }
245 
246     return OK;
247 }
248 
249 /*
250  * Append "value[value_len]" to the variable set by var_redir_start().
251  * The actual appending is postponed until redirection ends, because the value
252  * appended may in fact be the string we write to, changing it may cause freed
253  * memory to be used:
254  *   :redir => foo
255  *   :let foo
256  *   :redir END
257  */
258     void
259 var_redir_str(char_u *value, int value_len)
260 {
261     int		len;
262 
263     if (redir_lval == NULL)
264 	return;
265 
266     if (value_len == -1)
267 	len = (int)STRLEN(value);	/* Append the entire string */
268     else
269 	len = value_len;		/* Append only "value_len" characters */
270 
271     if (ga_grow(&redir_ga, len) == OK)
272     {
273 	mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
274 	redir_ga.ga_len += len;
275     }
276     else
277 	var_redir_stop();
278 }
279 
280 /*
281  * Stop redirecting command output to a variable.
282  * Frees the allocated memory.
283  */
284     void
285 var_redir_stop(void)
286 {
287     typval_T	tv;
288 
289     if (EVALCMD_BUSY)
290     {
291 	redir_lval = NULL;
292 	return;
293     }
294 
295     if (redir_lval != NULL)
296     {
297 	/* If there was no error: assign the text to the variable. */
298 	if (redir_endp != NULL)
299 	{
300 	    ga_append(&redir_ga, NUL);  /* Append the trailing NUL. */
301 	    tv.v_type = VAR_STRING;
302 	    tv.vval.v_string = redir_ga.ga_data;
303 	    /* Call get_lval() again, if it's inside a Dict or List it may
304 	     * have changed. */
305 	    redir_endp = get_lval(redir_varname, NULL, redir_lval,
306 					FALSE, FALSE, 0, FNE_CHECK_START);
307 	    if (redir_endp != NULL && redir_lval->ll_name != NULL)
308 		set_var_lval(redir_lval, redir_endp, &tv, FALSE, FALSE,
309 								(char_u *)".");
310 	    clear_lval(redir_lval);
311 	}
312 
313 	/* free the collected output */
314 	VIM_CLEAR(redir_ga.ga_data);
315 
316 	VIM_CLEAR(redir_lval);
317     }
318     VIM_CLEAR(redir_varname);
319 }
320 
321     int
322 eval_charconvert(
323     char_u	*enc_from,
324     char_u	*enc_to,
325     char_u	*fname_from,
326     char_u	*fname_to)
327 {
328     int		err = FALSE;
329 
330     set_vim_var_string(VV_CC_FROM, enc_from, -1);
331     set_vim_var_string(VV_CC_TO, enc_to, -1);
332     set_vim_var_string(VV_FNAME_IN, fname_from, -1);
333     set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
334     if (eval_to_bool(p_ccv, &err, NULL, FALSE))
335 	err = TRUE;
336     set_vim_var_string(VV_CC_FROM, NULL, -1);
337     set_vim_var_string(VV_CC_TO, NULL, -1);
338     set_vim_var_string(VV_FNAME_IN, NULL, -1);
339     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
340 
341     if (err)
342 	return FAIL;
343     return OK;
344 }
345 
346 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
347     int
348 eval_printexpr(char_u *fname, char_u *args)
349 {
350     int		err = FALSE;
351 
352     set_vim_var_string(VV_FNAME_IN, fname, -1);
353     set_vim_var_string(VV_CMDARG, args, -1);
354     if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
355 	err = TRUE;
356     set_vim_var_string(VV_FNAME_IN, NULL, -1);
357     set_vim_var_string(VV_CMDARG, NULL, -1);
358 
359     if (err)
360     {
361 	mch_remove(fname);
362 	return FAIL;
363     }
364     return OK;
365 }
366 # endif
367 
368 # if defined(FEAT_DIFF) || defined(PROTO)
369     void
370 eval_diff(
371     char_u	*origfile,
372     char_u	*newfile,
373     char_u	*outfile)
374 {
375     int		err = FALSE;
376 
377     set_vim_var_string(VV_FNAME_IN, origfile, -1);
378     set_vim_var_string(VV_FNAME_NEW, newfile, -1);
379     set_vim_var_string(VV_FNAME_OUT, outfile, -1);
380     (void)eval_to_bool(p_dex, &err, NULL, FALSE);
381     set_vim_var_string(VV_FNAME_IN, NULL, -1);
382     set_vim_var_string(VV_FNAME_NEW, NULL, -1);
383     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
384 }
385 
386     void
387 eval_patch(
388     char_u	*origfile,
389     char_u	*difffile,
390     char_u	*outfile)
391 {
392     int		err;
393 
394     set_vim_var_string(VV_FNAME_IN, origfile, -1);
395     set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
396     set_vim_var_string(VV_FNAME_OUT, outfile, -1);
397     (void)eval_to_bool(p_pex, &err, NULL, FALSE);
398     set_vim_var_string(VV_FNAME_IN, NULL, -1);
399     set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
400     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
401 }
402 # endif
403 
404 /*
405  * Top level evaluation function, returning a boolean.
406  * Sets "error" to TRUE if there was an error.
407  * Return TRUE or FALSE.
408  */
409     int
410 eval_to_bool(
411     char_u	*arg,
412     int		*error,
413     char_u	**nextcmd,
414     int		skip)	    /* only parse, don't execute */
415 {
416     typval_T	tv;
417     varnumber_T	retval = FALSE;
418 
419     if (skip)
420 	++emsg_skip;
421     if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
422 	*error = TRUE;
423     else
424     {
425 	*error = FALSE;
426 	if (!skip)
427 	{
428 	    retval = (tv_get_number_chk(&tv, error) != 0);
429 	    clear_tv(&tv);
430 	}
431     }
432     if (skip)
433 	--emsg_skip;
434 
435     return (int)retval;
436 }
437 
438 /*
439  * Call eval1() and give an error message if not done at a lower level.
440  */
441     static int
442 eval1_emsg(char_u **arg, typval_T *rettv, int evaluate)
443 {
444     char_u	*start = *arg;
445     int		ret;
446     int		did_emsg_before = did_emsg;
447     int		called_emsg_before = called_emsg;
448 
449     ret = eval1(arg, rettv, evaluate);
450     if (ret == FAIL)
451     {
452 	// Report the invalid expression unless the expression evaluation has
453 	// been cancelled due to an aborting error, an interrupt, or an
454 	// exception, or we already gave a more specific error.
455 	// Also check called_emsg for when using assert_fails().
456 	if (!aborting() && did_emsg == did_emsg_before
457 					  && called_emsg == called_emsg_before)
458 	    semsg(_(e_invexpr2), start);
459     }
460     return ret;
461 }
462 
463     int
464 eval_expr_typval(typval_T *expr, typval_T *argv, int argc, typval_T *rettv)
465 {
466     char_u	*s;
467     char_u	buf[NUMBUFLEN];
468     funcexe_T	funcexe;
469 
470     if (expr->v_type == VAR_FUNC)
471     {
472 	s = expr->vval.v_string;
473 	if (s == NULL || *s == NUL)
474 	    return FAIL;
475 	vim_memset(&funcexe, 0, sizeof(funcexe));
476 	funcexe.evaluate = TRUE;
477 	if (call_func(s, -1, rettv, argc, argv, &funcexe) == FAIL)
478 	    return FAIL;
479     }
480     else if (expr->v_type == VAR_PARTIAL)
481     {
482 	partial_T   *partial = expr->vval.v_partial;
483 
484 	s = partial_name(partial);
485 	if (s == NULL || *s == NUL)
486 	    return FAIL;
487 	vim_memset(&funcexe, 0, sizeof(funcexe));
488 	funcexe.evaluate = TRUE;
489 	funcexe.partial = partial;
490 	if (call_func(s, -1, rettv, argc, argv, &funcexe) == FAIL)
491 	    return FAIL;
492     }
493     else
494     {
495 	s = tv_get_string_buf_chk(expr, buf);
496 	if (s == NULL)
497 	    return FAIL;
498 	s = skipwhite(s);
499 	if (eval1_emsg(&s, rettv, TRUE) == FAIL)
500 	    return FAIL;
501 	if (*s != NUL)  /* check for trailing chars after expr */
502 	{
503 	    clear_tv(rettv);
504 	    semsg(_(e_invexpr2), s);
505 	    return FAIL;
506 	}
507     }
508     return OK;
509 }
510 
511 /*
512  * Like eval_to_bool() but using a typval_T instead of a string.
513  * Works for string, funcref and partial.
514  */
515     int
516 eval_expr_to_bool(typval_T *expr, int *error)
517 {
518     typval_T	rettv;
519     int		res;
520 
521     if (eval_expr_typval(expr, NULL, 0, &rettv) == FAIL)
522     {
523 	*error = TRUE;
524 	return FALSE;
525     }
526     res = (tv_get_number_chk(&rettv, error) != 0);
527     clear_tv(&rettv);
528     return res;
529 }
530 
531 /*
532  * Top level evaluation function, returning a string.  If "skip" is TRUE,
533  * only parsing to "nextcmd" is done, without reporting errors.  Return
534  * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
535  */
536     char_u *
537 eval_to_string_skip(
538     char_u	*arg,
539     char_u	**nextcmd,
540     int		skip)	    /* only parse, don't execute */
541 {
542     typval_T	tv;
543     char_u	*retval;
544 
545     if (skip)
546 	++emsg_skip;
547     if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
548 	retval = NULL;
549     else
550     {
551 	retval = vim_strsave(tv_get_string(&tv));
552 	clear_tv(&tv);
553     }
554     if (skip)
555 	--emsg_skip;
556 
557     return retval;
558 }
559 
560 /*
561  * Skip over an expression at "*pp".
562  * Return FAIL for an error, OK otherwise.
563  */
564     int
565 skip_expr(char_u **pp)
566 {
567     typval_T	rettv;
568 
569     *pp = skipwhite(*pp);
570     return eval1(pp, &rettv, FALSE);
571 }
572 
573 /*
574  * Top level evaluation function, returning a string.
575  * When "convert" is TRUE convert a List into a sequence of lines and convert
576  * a Float to a String.
577  * Return pointer to allocated memory, or NULL for failure.
578  */
579     char_u *
580 eval_to_string(
581     char_u	*arg,
582     char_u	**nextcmd,
583     int		convert)
584 {
585     typval_T	tv;
586     char_u	*retval;
587     garray_T	ga;
588 #ifdef FEAT_FLOAT
589     char_u	numbuf[NUMBUFLEN];
590 #endif
591 
592     if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
593 	retval = NULL;
594     else
595     {
596 	if (convert && tv.v_type == VAR_LIST)
597 	{
598 	    ga_init2(&ga, (int)sizeof(char), 80);
599 	    if (tv.vval.v_list != NULL)
600 	    {
601 		list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, FALSE, 0);
602 		if (tv.vval.v_list->lv_len > 0)
603 		    ga_append(&ga, NL);
604 	    }
605 	    ga_append(&ga, NUL);
606 	    retval = (char_u *)ga.ga_data;
607 	}
608 #ifdef FEAT_FLOAT
609 	else if (convert && tv.v_type == VAR_FLOAT)
610 	{
611 	    vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
612 	    retval = vim_strsave(numbuf);
613 	}
614 #endif
615 	else
616 	    retval = vim_strsave(tv_get_string(&tv));
617 	clear_tv(&tv);
618     }
619 
620     return retval;
621 }
622 
623 /*
624  * Call eval_to_string() without using current local variables and using
625  * textlock.  When "use_sandbox" is TRUE use the sandbox.
626  */
627     char_u *
628 eval_to_string_safe(
629     char_u	*arg,
630     char_u	**nextcmd,
631     int		use_sandbox)
632 {
633     char_u	*retval;
634     funccal_entry_T funccal_entry;
635 
636     save_funccal(&funccal_entry);
637     if (use_sandbox)
638 	++sandbox;
639     ++textlock;
640     retval = eval_to_string(arg, nextcmd, FALSE);
641     if (use_sandbox)
642 	--sandbox;
643     --textlock;
644     restore_funccal();
645     return retval;
646 }
647 
648 /*
649  * Top level evaluation function, returning a number.
650  * Evaluates "expr" silently.
651  * Returns -1 for an error.
652  */
653     varnumber_T
654 eval_to_number(char_u *expr)
655 {
656     typval_T	rettv;
657     varnumber_T	retval;
658     char_u	*p = skipwhite(expr);
659 
660     ++emsg_off;
661 
662     if (eval1(&p, &rettv, TRUE) == FAIL)
663 	retval = -1;
664     else
665     {
666 	retval = tv_get_number_chk(&rettv, NULL);
667 	clear_tv(&rettv);
668     }
669     --emsg_off;
670 
671     return retval;
672 }
673 
674 #if defined(FEAT_SPELL) || defined(PROTO)
675 /*
676  * Evaluate an expression to a list with suggestions.
677  * For the "expr:" part of 'spellsuggest'.
678  * Returns NULL when there is an error.
679  */
680     list_T *
681 eval_spell_expr(char_u *badword, char_u *expr)
682 {
683     typval_T	save_val;
684     typval_T	rettv;
685     list_T	*list = NULL;
686     char_u	*p = skipwhite(expr);
687 
688     /* Set "v:val" to the bad word. */
689     prepare_vimvar(VV_VAL, &save_val);
690     set_vim_var_string(VV_VAL, badword, -1);
691     if (p_verbose == 0)
692 	++emsg_off;
693 
694     if (eval1(&p, &rettv, TRUE) == OK)
695     {
696 	if (rettv.v_type != VAR_LIST)
697 	    clear_tv(&rettv);
698 	else
699 	    list = rettv.vval.v_list;
700     }
701 
702     if (p_verbose == 0)
703 	--emsg_off;
704     clear_tv(get_vim_var_tv(VV_VAL));
705     restore_vimvar(VV_VAL, &save_val);
706 
707     return list;
708 }
709 
710 /*
711  * "list" is supposed to contain two items: a word and a number.  Return the
712  * word in "pp" and the number as the return value.
713  * Return -1 if anything isn't right.
714  * Used to get the good word and score from the eval_spell_expr() result.
715  */
716     int
717 get_spellword(list_T *list, char_u **pp)
718 {
719     listitem_T	*li;
720 
721     li = list->lv_first;
722     if (li == NULL)
723 	return -1;
724     *pp = tv_get_string(&li->li_tv);
725 
726     li = li->li_next;
727     if (li == NULL)
728 	return -1;
729     return (int)tv_get_number(&li->li_tv);
730 }
731 #endif
732 
733 /*
734  * Top level evaluation function.
735  * Returns an allocated typval_T with the result.
736  * Returns NULL when there is an error.
737  */
738     typval_T *
739 eval_expr(char_u *arg, char_u **nextcmd)
740 {
741     typval_T	*tv;
742 
743     tv = ALLOC_ONE(typval_T);
744     if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
745 	VIM_CLEAR(tv);
746 
747     return tv;
748 }
749 
750 /*
751  * Call some Vim script function and return the result in "*rettv".
752  * Uses argv[0] to argv[argc - 1] for the function arguments.  argv[argc]
753  * should have type VAR_UNKNOWN.
754  * Returns OK or FAIL.
755  */
756     int
757 call_vim_function(
758     char_u      *func,
759     int		argc,
760     typval_T	*argv,
761     typval_T	*rettv)
762 {
763     int		ret;
764     funcexe_T	funcexe;
765 
766     rettv->v_type = VAR_UNKNOWN;		/* clear_tv() uses this */
767     vim_memset(&funcexe, 0, sizeof(funcexe));
768     funcexe.firstline = curwin->w_cursor.lnum;
769     funcexe.lastline = curwin->w_cursor.lnum;
770     funcexe.evaluate = TRUE;
771     ret = call_func(func, -1, rettv, argc, argv, &funcexe);
772     if (ret == FAIL)
773 	clear_tv(rettv);
774 
775     return ret;
776 }
777 
778 /*
779  * Call Vim script function "func" and return the result as a number.
780  * Returns -1 when calling the function fails.
781  * Uses argv[0] to argv[argc - 1] for the function arguments. argv[argc] should
782  * have type VAR_UNKNOWN.
783  */
784     varnumber_T
785 call_func_retnr(
786     char_u      *func,
787     int		argc,
788     typval_T	*argv)
789 {
790     typval_T	rettv;
791     varnumber_T	retval;
792 
793     if (call_vim_function(func, argc, argv, &rettv) == FAIL)
794 	return -1;
795 
796     retval = tv_get_number_chk(&rettv, NULL);
797     clear_tv(&rettv);
798     return retval;
799 }
800 
801 /*
802  * Call Vim script function "func" and return the result as a string.
803  * Returns NULL when calling the function fails.
804  * Uses argv[0] to argv[argc - 1] for the function arguments. argv[argc] should
805  * have type VAR_UNKNOWN.
806  */
807     void *
808 call_func_retstr(
809     char_u      *func,
810     int		argc,
811     typval_T	*argv)
812 {
813     typval_T	rettv;
814     char_u	*retval;
815 
816     if (call_vim_function(func, argc, argv, &rettv) == FAIL)
817 	return NULL;
818 
819     retval = vim_strsave(tv_get_string(&rettv));
820     clear_tv(&rettv);
821     return retval;
822 }
823 
824 /*
825  * Call Vim script function "func" and return the result as a List.
826  * Uses argv[0] to argv[argc - 1] for the function arguments. argv[argc] should
827  * have type VAR_UNKNOWN.
828  * Returns NULL when there is something wrong.
829  */
830     void *
831 call_func_retlist(
832     char_u      *func,
833     int		argc,
834     typval_T	*argv)
835 {
836     typval_T	rettv;
837 
838     if (call_vim_function(func, argc, argv, &rettv) == FAIL)
839 	return NULL;
840 
841     if (rettv.v_type != VAR_LIST)
842     {
843 	clear_tv(&rettv);
844 	return NULL;
845     }
846 
847     return rettv.vval.v_list;
848 }
849 
850 #ifdef FEAT_FOLDING
851 /*
852  * Evaluate 'foldexpr'.  Returns the foldlevel, and any character preceding
853  * it in "*cp".  Doesn't give error messages.
854  */
855     int
856 eval_foldexpr(char_u *arg, int *cp)
857 {
858     typval_T	tv;
859     varnumber_T	retval;
860     char_u	*s;
861     int		use_sandbox = was_set_insecurely((char_u *)"foldexpr",
862 								   OPT_LOCAL);
863 
864     ++emsg_off;
865     if (use_sandbox)
866 	++sandbox;
867     ++textlock;
868     *cp = NUL;
869     if (eval0(arg, &tv, NULL, TRUE) == FAIL)
870 	retval = 0;
871     else
872     {
873 	/* If the result is a number, just return the number. */
874 	if (tv.v_type == VAR_NUMBER)
875 	    retval = tv.vval.v_number;
876 	else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
877 	    retval = 0;
878 	else
879 	{
880 	    /* If the result is a string, check if there is a non-digit before
881 	     * the number. */
882 	    s = tv.vval.v_string;
883 	    if (!VIM_ISDIGIT(*s) && *s != '-')
884 		*cp = *s++;
885 	    retval = atol((char *)s);
886 	}
887 	clear_tv(&tv);
888     }
889     --emsg_off;
890     if (use_sandbox)
891 	--sandbox;
892     --textlock;
893 
894     return (int)retval;
895 }
896 #endif
897 
898 /*
899  * Get an lval: variable, Dict item or List item that can be assigned a value
900  * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
901  * "name.key", "name.key[expr]" etc.
902  * Indexing only works if "name" is an existing List or Dictionary.
903  * "name" points to the start of the name.
904  * If "rettv" is not NULL it points to the value to be assigned.
905  * "unlet" is TRUE for ":unlet": slightly different behavior when something is
906  * wrong; must end in space or cmd separator.
907  *
908  * flags:
909  *  GLV_QUIET:       do not give error messages
910  *  GLV_READ_ONLY:   will not change the variable
911  *  GLV_NO_AUTOLOAD: do not use script autoloading
912  *
913  * Returns a pointer to just after the name, including indexes.
914  * When an evaluation error occurs "lp->ll_name" is NULL;
915  * Returns NULL for a parsing error.  Still need to free items in "lp"!
916  */
917     char_u *
918 get_lval(
919     char_u	*name,
920     typval_T	*rettv,
921     lval_T	*lp,
922     int		unlet,
923     int		skip,
924     int		flags,	    /* GLV_ values */
925     int		fne_flags)  /* flags for find_name_end() */
926 {
927     char_u	*p;
928     char_u	*expr_start, *expr_end;
929     int		cc;
930     dictitem_T	*v;
931     typval_T	var1;
932     typval_T	var2;
933     int		empty1 = FALSE;
934     listitem_T	*ni;
935     char_u	*key = NULL;
936     int		len;
937     hashtab_T	*ht;
938     int		quiet = flags & GLV_QUIET;
939 
940     /* Clear everything in "lp". */
941     vim_memset(lp, 0, sizeof(lval_T));
942 
943     if (skip)
944     {
945 	/* When skipping just find the end of the name. */
946 	lp->ll_name = name;
947 	return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
948     }
949 
950     /* Find the end of the name. */
951     p = find_name_end(name, &expr_start, &expr_end, fne_flags);
952     if (expr_start != NULL)
953     {
954 	/* Don't expand the name when we already know there is an error. */
955 	if (unlet && !VIM_ISWHITE(*p) && !ends_excmd(*p)
956 						    && *p != '[' && *p != '.')
957 	{
958 	    emsg(_(e_trailing));
959 	    return NULL;
960 	}
961 
962 	lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
963 	if (lp->ll_exp_name == NULL)
964 	{
965 	    /* Report an invalid expression in braces, unless the
966 	     * expression evaluation has been cancelled due to an
967 	     * aborting error, an interrupt, or an exception. */
968 	    if (!aborting() && !quiet)
969 	    {
970 		emsg_severe = TRUE;
971 		semsg(_(e_invarg2), name);
972 		return NULL;
973 	    }
974 	}
975 	lp->ll_name = lp->ll_exp_name;
976     }
977     else
978 	lp->ll_name = name;
979 
980     /* Without [idx] or .key we are done. */
981     if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
982 	return p;
983 
984     cc = *p;
985     *p = NUL;
986     /* Only pass &ht when we would write to the variable, it prevents autoload
987      * as well. */
988     v = find_var(lp->ll_name, (flags & GLV_READ_ONLY) ? NULL : &ht,
989 						      flags & GLV_NO_AUTOLOAD);
990     if (v == NULL && !quiet)
991 	semsg(_(e_undefvar), lp->ll_name);
992     *p = cc;
993     if (v == NULL)
994 	return NULL;
995 
996     /*
997      * Loop until no more [idx] or .key is following.
998      */
999     lp->ll_tv = &v->di_tv;
1000     var1.v_type = VAR_UNKNOWN;
1001     var2.v_type = VAR_UNKNOWN;
1002     while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
1003     {
1004 	if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
1005 		&& !(lp->ll_tv->v_type == VAR_DICT
1006 					   && lp->ll_tv->vval.v_dict != NULL)
1007 		&& !(lp->ll_tv->v_type == VAR_BLOB
1008 					   && lp->ll_tv->vval.v_blob != NULL))
1009 	{
1010 	    if (!quiet)
1011 		emsg(_("E689: Can only index a List, Dictionary or Blob"));
1012 	    return NULL;
1013 	}
1014 	if (lp->ll_range)
1015 	{
1016 	    if (!quiet)
1017 		emsg(_("E708: [:] must come last"));
1018 	    return NULL;
1019 	}
1020 
1021 	len = -1;
1022 	if (*p == '.')
1023 	{
1024 	    key = p + 1;
1025 	    for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
1026 		;
1027 	    if (len == 0)
1028 	    {
1029 		if (!quiet)
1030 		    emsg(_(e_emptykey));
1031 		return NULL;
1032 	    }
1033 	    p = key + len;
1034 	}
1035 	else
1036 	{
1037 	    /* Get the index [expr] or the first index [expr: ]. */
1038 	    p = skipwhite(p + 1);
1039 	    if (*p == ':')
1040 		empty1 = TRUE;
1041 	    else
1042 	    {
1043 		empty1 = FALSE;
1044 		if (eval1(&p, &var1, TRUE) == FAIL)	/* recursive! */
1045 		    return NULL;
1046 		if (tv_get_string_chk(&var1) == NULL)
1047 		{
1048 		    /* not a number or string */
1049 		    clear_tv(&var1);
1050 		    return NULL;
1051 		}
1052 	    }
1053 
1054 	    /* Optionally get the second index [ :expr]. */
1055 	    if (*p == ':')
1056 	    {
1057 		if (lp->ll_tv->v_type == VAR_DICT)
1058 		{
1059 		    if (!quiet)
1060 			emsg(_(e_dictrange));
1061 		    clear_tv(&var1);
1062 		    return NULL;
1063 		}
1064 		if (rettv != NULL
1065 			&& !(rettv->v_type == VAR_LIST
1066 						 && rettv->vval.v_list != NULL)
1067 			&& !(rettv->v_type == VAR_BLOB
1068 						&& rettv->vval.v_blob != NULL))
1069 		{
1070 		    if (!quiet)
1071 			emsg(_("E709: [:] requires a List or Blob value"));
1072 		    clear_tv(&var1);
1073 		    return NULL;
1074 		}
1075 		p = skipwhite(p + 1);
1076 		if (*p == ']')
1077 		    lp->ll_empty2 = TRUE;
1078 		else
1079 		{
1080 		    lp->ll_empty2 = FALSE;
1081 		    if (eval1(&p, &var2, TRUE) == FAIL)	/* recursive! */
1082 		    {
1083 			clear_tv(&var1);
1084 			return NULL;
1085 		    }
1086 		    if (tv_get_string_chk(&var2) == NULL)
1087 		    {
1088 			/* not a number or string */
1089 			clear_tv(&var1);
1090 			clear_tv(&var2);
1091 			return NULL;
1092 		    }
1093 		}
1094 		lp->ll_range = TRUE;
1095 	    }
1096 	    else
1097 		lp->ll_range = FALSE;
1098 
1099 	    if (*p != ']')
1100 	    {
1101 		if (!quiet)
1102 		    emsg(_(e_missbrac));
1103 		clear_tv(&var1);
1104 		clear_tv(&var2);
1105 		return NULL;
1106 	    }
1107 
1108 	    /* Skip to past ']'. */
1109 	    ++p;
1110 	}
1111 
1112 	if (lp->ll_tv->v_type == VAR_DICT)
1113 	{
1114 	    if (len == -1)
1115 	    {
1116 		/* "[key]": get key from "var1" */
1117 		key = tv_get_string_chk(&var1);	/* is number or string */
1118 		if (key == NULL)
1119 		{
1120 		    clear_tv(&var1);
1121 		    return NULL;
1122 		}
1123 	    }
1124 	    lp->ll_list = NULL;
1125 	    lp->ll_dict = lp->ll_tv->vval.v_dict;
1126 	    lp->ll_di = dict_find(lp->ll_dict, key, len);
1127 
1128 	    /* When assigning to a scope dictionary check that a function and
1129 	     * variable name is valid (only variable name unless it is l: or
1130 	     * g: dictionary). Disallow overwriting a builtin function. */
1131 	    if (rettv != NULL && lp->ll_dict->dv_scope != 0)
1132 	    {
1133 		int prevval;
1134 		int wrong;
1135 
1136 		if (len != -1)
1137 		{
1138 		    prevval = key[len];
1139 		    key[len] = NUL;
1140 		}
1141 		else
1142 		    prevval = 0; /* avoid compiler warning */
1143 		wrong = (lp->ll_dict->dv_scope == VAR_DEF_SCOPE
1144 			       && rettv->v_type == VAR_FUNC
1145 			       && var_check_func_name(key, lp->ll_di == NULL))
1146 			|| !valid_varname(key);
1147 		if (len != -1)
1148 		    key[len] = prevval;
1149 		if (wrong)
1150 		    return NULL;
1151 	    }
1152 
1153 	    if (lp->ll_di == NULL)
1154 	    {
1155 		// Can't add "v:" or "a:" variable.
1156 		if (lp->ll_dict == &vimvardict
1157 			 || &lp->ll_dict->dv_hashtab == get_funccal_args_ht())
1158 		{
1159 		    semsg(_(e_illvar), name);
1160 		    clear_tv(&var1);
1161 		    return NULL;
1162 		}
1163 
1164 		// Key does not exist in dict: may need to add it.
1165 		if (*p == '[' || *p == '.' || unlet)
1166 		{
1167 		    if (!quiet)
1168 			semsg(_(e_dictkey), key);
1169 		    clear_tv(&var1);
1170 		    return NULL;
1171 		}
1172 		if (len == -1)
1173 		    lp->ll_newkey = vim_strsave(key);
1174 		else
1175 		    lp->ll_newkey = vim_strnsave(key, len);
1176 		clear_tv(&var1);
1177 		if (lp->ll_newkey == NULL)
1178 		    p = NULL;
1179 		break;
1180 	    }
1181 	    /* existing variable, need to check if it can be changed */
1182 	    else if ((flags & GLV_READ_ONLY) == 0
1183 			     && var_check_ro(lp->ll_di->di_flags, name, FALSE))
1184 	    {
1185 		clear_tv(&var1);
1186 		return NULL;
1187 	    }
1188 
1189 	    clear_tv(&var1);
1190 	    lp->ll_tv = &lp->ll_di->di_tv;
1191 	}
1192 	else if (lp->ll_tv->v_type == VAR_BLOB)
1193 	{
1194 	    long bloblen = blob_len(lp->ll_tv->vval.v_blob);
1195 
1196 	    /*
1197 	     * Get the number and item for the only or first index of the List.
1198 	     */
1199 	    if (empty1)
1200 		lp->ll_n1 = 0;
1201 	    else
1202 		// is number or string
1203 		lp->ll_n1 = (long)tv_get_number(&var1);
1204 	    clear_tv(&var1);
1205 
1206 	    if (lp->ll_n1 < 0
1207 		    || lp->ll_n1 > bloblen
1208 		    || (lp->ll_range && lp->ll_n1 == bloblen))
1209 	    {
1210 		if (!quiet)
1211 		    semsg(_(e_blobidx), lp->ll_n1);
1212 		clear_tv(&var2);
1213 		return NULL;
1214 	    }
1215 	    if (lp->ll_range && !lp->ll_empty2)
1216 	    {
1217 		lp->ll_n2 = (long)tv_get_number(&var2);
1218 		clear_tv(&var2);
1219 		if (lp->ll_n2 < 0
1220 			|| lp->ll_n2 >= bloblen
1221 			|| lp->ll_n2 < lp->ll_n1)
1222 		{
1223 		    if (!quiet)
1224 			semsg(_(e_blobidx), lp->ll_n2);
1225 		    return NULL;
1226 		}
1227 	    }
1228 	    lp->ll_blob = lp->ll_tv->vval.v_blob;
1229 	    lp->ll_tv = NULL;
1230 	    break;
1231 	}
1232 	else
1233 	{
1234 	    /*
1235 	     * Get the number and item for the only or first index of the List.
1236 	     */
1237 	    if (empty1)
1238 		lp->ll_n1 = 0;
1239 	    else
1240 		/* is number or string */
1241 		lp->ll_n1 = (long)tv_get_number(&var1);
1242 	    clear_tv(&var1);
1243 
1244 	    lp->ll_dict = NULL;
1245 	    lp->ll_list = lp->ll_tv->vval.v_list;
1246 	    lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
1247 	    if (lp->ll_li == NULL)
1248 	    {
1249 		if (lp->ll_n1 < 0)
1250 		{
1251 		    lp->ll_n1 = 0;
1252 		    lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
1253 		}
1254 	    }
1255 	    if (lp->ll_li == NULL)
1256 	    {
1257 		clear_tv(&var2);
1258 		if (!quiet)
1259 		    semsg(_(e_listidx), lp->ll_n1);
1260 		return NULL;
1261 	    }
1262 
1263 	    /*
1264 	     * May need to find the item or absolute index for the second
1265 	     * index of a range.
1266 	     * When no index given: "lp->ll_empty2" is TRUE.
1267 	     * Otherwise "lp->ll_n2" is set to the second index.
1268 	     */
1269 	    if (lp->ll_range && !lp->ll_empty2)
1270 	    {
1271 		lp->ll_n2 = (long)tv_get_number(&var2);
1272 						    /* is number or string */
1273 		clear_tv(&var2);
1274 		if (lp->ll_n2 < 0)
1275 		{
1276 		    ni = list_find(lp->ll_list, lp->ll_n2);
1277 		    if (ni == NULL)
1278 		    {
1279 			if (!quiet)
1280 			    semsg(_(e_listidx), lp->ll_n2);
1281 			return NULL;
1282 		    }
1283 		    lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
1284 		}
1285 
1286 		/* Check that lp->ll_n2 isn't before lp->ll_n1. */
1287 		if (lp->ll_n1 < 0)
1288 		    lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
1289 		if (lp->ll_n2 < lp->ll_n1)
1290 		{
1291 		    if (!quiet)
1292 			semsg(_(e_listidx), lp->ll_n2);
1293 		    return NULL;
1294 		}
1295 	    }
1296 
1297 	    lp->ll_tv = &lp->ll_li->li_tv;
1298 	}
1299     }
1300 
1301     clear_tv(&var1);
1302     return p;
1303 }
1304 
1305 /*
1306  * Clear lval "lp" that was filled by get_lval().
1307  */
1308     void
1309 clear_lval(lval_T *lp)
1310 {
1311     vim_free(lp->ll_exp_name);
1312     vim_free(lp->ll_newkey);
1313 }
1314 
1315 /*
1316  * Set a variable that was parsed by get_lval() to "rettv".
1317  * "endp" points to just after the parsed name.
1318  * "op" is NULL, "+" for "+=", "-" for "-=", "*" for "*=", "/" for "/=",
1319  * "%" for "%=", "." for ".=" or "=" for "=".
1320  */
1321     void
1322 set_var_lval(
1323     lval_T	*lp,
1324     char_u	*endp,
1325     typval_T	*rettv,
1326     int		copy,
1327     int		is_const,    // Disallow to modify existing variable for :const
1328     char_u	*op)
1329 {
1330     int		cc;
1331     listitem_T	*ri;
1332     dictitem_T	*di;
1333 
1334     if (lp->ll_tv == NULL)
1335     {
1336 	cc = *endp;
1337 	*endp = NUL;
1338 	if (lp->ll_blob != NULL)
1339 	{
1340 	    int	    error = FALSE, val;
1341 
1342 	    if (op != NULL && *op != '=')
1343 	    {
1344 		semsg(_(e_letwrong), op);
1345 		return;
1346 	    }
1347 
1348 	    if (lp->ll_range && rettv->v_type == VAR_BLOB)
1349 	    {
1350 		int	il, ir;
1351 
1352 		if (lp->ll_empty2)
1353 		    lp->ll_n2 = blob_len(lp->ll_blob) - 1;
1354 
1355 		if (lp->ll_n2 - lp->ll_n1 + 1 != blob_len(rettv->vval.v_blob))
1356 		{
1357 		    emsg(_("E972: Blob value does not have the right number of bytes"));
1358 		    return;
1359 		}
1360 		if (lp->ll_empty2)
1361 		    lp->ll_n2 = blob_len(lp->ll_blob);
1362 
1363 		ir = 0;
1364 		for (il = lp->ll_n1; il <= lp->ll_n2; il++)
1365 		    blob_set(lp->ll_blob, il,
1366 			    blob_get(rettv->vval.v_blob, ir++));
1367 	    }
1368 	    else
1369 	    {
1370 		val = (int)tv_get_number_chk(rettv, &error);
1371 		if (!error)
1372 		{
1373 		    garray_T *gap = &lp->ll_blob->bv_ga;
1374 
1375 		    // Allow for appending a byte.  Setting a byte beyond
1376 		    // the end is an error otherwise.
1377 		    if (lp->ll_n1 < gap->ga_len
1378 			    || (lp->ll_n1 == gap->ga_len
1379 				&& ga_grow(&lp->ll_blob->bv_ga, 1) == OK))
1380 		    {
1381 			blob_set(lp->ll_blob, lp->ll_n1, val);
1382 			if (lp->ll_n1 == gap->ga_len)
1383 			    ++gap->ga_len;
1384 		    }
1385 		    // error for invalid range was already given in get_lval()
1386 		}
1387 	    }
1388 	}
1389 	else if (op != NULL && *op != '=')
1390 	{
1391 	    typval_T tv;
1392 
1393 	    if (is_const)
1394 	    {
1395 		emsg(_(e_cannot_mod));
1396 		*endp = cc;
1397 		return;
1398 	    }
1399 
1400 	    // handle +=, -=, *=, /=, %= and .=
1401 	    di = NULL;
1402 	    if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
1403 					     &tv, &di, TRUE, FALSE) == OK)
1404 	    {
1405 		if ((di == NULL
1406 			 || (!var_check_ro(di->di_flags, lp->ll_name, FALSE)
1407 			   && !tv_check_lock(&di->di_tv, lp->ll_name, FALSE)))
1408 			&& tv_op(&tv, rettv, op) == OK)
1409 		    set_var(lp->ll_name, &tv, FALSE);
1410 		clear_tv(&tv);
1411 	    }
1412 	}
1413 	else
1414 	    set_var_const(lp->ll_name, rettv, copy, is_const);
1415 	*endp = cc;
1416     }
1417     else if (var_check_lock(lp->ll_newkey == NULL
1418 		? lp->ll_tv->v_lock
1419 		: lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name, FALSE))
1420 	;
1421     else if (lp->ll_range)
1422     {
1423 	listitem_T *ll_li = lp->ll_li;
1424 	int	    ll_n1 = lp->ll_n1;
1425 
1426 	if (is_const)
1427 	{
1428 	    emsg(_("E996: Cannot lock a range"));
1429 	    return;
1430 	}
1431 
1432 	/*
1433 	 * Check whether any of the list items is locked
1434 	 */
1435 	for (ri = rettv->vval.v_list->lv_first; ri != NULL && ll_li != NULL; )
1436 	{
1437 	    if (var_check_lock(ll_li->li_tv.v_lock, lp->ll_name, FALSE))
1438 		return;
1439 	    ri = ri->li_next;
1440 	    if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == ll_n1))
1441 		break;
1442 	    ll_li = ll_li->li_next;
1443 	    ++ll_n1;
1444 	}
1445 
1446 	/*
1447 	 * Assign the List values to the list items.
1448 	 */
1449 	for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
1450 	{
1451 	    if (op != NULL && *op != '=')
1452 		tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
1453 	    else
1454 	    {
1455 		clear_tv(&lp->ll_li->li_tv);
1456 		copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
1457 	    }
1458 	    ri = ri->li_next;
1459 	    if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
1460 		break;
1461 	    if (lp->ll_li->li_next == NULL)
1462 	    {
1463 		/* Need to add an empty item. */
1464 		if (list_append_number(lp->ll_list, 0) == FAIL)
1465 		{
1466 		    ri = NULL;
1467 		    break;
1468 		}
1469 	    }
1470 	    lp->ll_li = lp->ll_li->li_next;
1471 	    ++lp->ll_n1;
1472 	}
1473 	if (ri != NULL)
1474 	    emsg(_("E710: List value has more items than target"));
1475 	else if (lp->ll_empty2
1476 		? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
1477 		: lp->ll_n1 != lp->ll_n2)
1478 	    emsg(_("E711: List value has not enough items"));
1479     }
1480     else
1481     {
1482 	/*
1483 	 * Assign to a List or Dictionary item.
1484 	 */
1485 	if (is_const)
1486 	{
1487 	    emsg(_("E996: Cannot lock a list or dict"));
1488 	    return;
1489 	}
1490 	if (lp->ll_newkey != NULL)
1491 	{
1492 	    if (op != NULL && *op != '=')
1493 	    {
1494 		semsg(_(e_letwrong), op);
1495 		return;
1496 	    }
1497 
1498 	    /* Need to add an item to the Dictionary. */
1499 	    di = dictitem_alloc(lp->ll_newkey);
1500 	    if (di == NULL)
1501 		return;
1502 	    if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
1503 	    {
1504 		vim_free(di);
1505 		return;
1506 	    }
1507 	    lp->ll_tv = &di->di_tv;
1508 	}
1509 	else if (op != NULL && *op != '=')
1510 	{
1511 	    tv_op(lp->ll_tv, rettv, op);
1512 	    return;
1513 	}
1514 	else
1515 	    clear_tv(lp->ll_tv);
1516 
1517 	/*
1518 	 * Assign the value to the variable or list item.
1519 	 */
1520 	if (copy)
1521 	    copy_tv(rettv, lp->ll_tv);
1522 	else
1523 	{
1524 	    *lp->ll_tv = *rettv;
1525 	    lp->ll_tv->v_lock = 0;
1526 	    init_tv(rettv);
1527 	}
1528     }
1529 }
1530 
1531 /*
1532  * Handle "tv1 += tv2", "tv1 -= tv2", "tv1 *= tv2", "tv1 /= tv2", "tv1 %= tv2"
1533  * and "tv1 .= tv2"
1534  * Returns OK or FAIL.
1535  */
1536     static int
1537 tv_op(typval_T *tv1, typval_T *tv2, char_u *op)
1538 {
1539     varnumber_T	n;
1540     char_u	numbuf[NUMBUFLEN];
1541     char_u	*s;
1542 
1543     /* Can't do anything with a Funcref, Dict, v:true on the right. */
1544     if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT
1545 						&& tv2->v_type != VAR_SPECIAL)
1546     {
1547 	switch (tv1->v_type)
1548 	{
1549 	    case VAR_UNKNOWN:
1550 	    case VAR_DICT:
1551 	    case VAR_FUNC:
1552 	    case VAR_PARTIAL:
1553 	    case VAR_SPECIAL:
1554 	    case VAR_JOB:
1555 	    case VAR_CHANNEL:
1556 		break;
1557 
1558 	    case VAR_BLOB:
1559 		if (*op != '+' || tv2->v_type != VAR_BLOB)
1560 		    break;
1561 		// BLOB += BLOB
1562 		if (tv1->vval.v_blob != NULL && tv2->vval.v_blob != NULL)
1563 		{
1564 		    blob_T  *b1 = tv1->vval.v_blob;
1565 		    blob_T  *b2 = tv2->vval.v_blob;
1566 		    int	i, len = blob_len(b2);
1567 		    for (i = 0; i < len; i++)
1568 			ga_append(&b1->bv_ga, blob_get(b2, i));
1569 		}
1570 		return OK;
1571 
1572 	    case VAR_LIST:
1573 		if (*op != '+' || tv2->v_type != VAR_LIST)
1574 		    break;
1575 		// List += List
1576 		if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
1577 		    list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
1578 		return OK;
1579 
1580 	    case VAR_NUMBER:
1581 	    case VAR_STRING:
1582 		if (tv2->v_type == VAR_LIST)
1583 		    break;
1584 		if (vim_strchr((char_u *)"+-*/%", *op) != NULL)
1585 		{
1586 		    // nr += nr , nr -= nr , nr *=nr , nr /= nr , nr %= nr
1587 		    n = tv_get_number(tv1);
1588 #ifdef FEAT_FLOAT
1589 		    if (tv2->v_type == VAR_FLOAT)
1590 		    {
1591 			float_T f = n;
1592 
1593 			if (*op == '%')
1594 			    break;
1595 			switch (*op)
1596 			{
1597 			    case '+': f += tv2->vval.v_float; break;
1598 			    case '-': f -= tv2->vval.v_float; break;
1599 			    case '*': f *= tv2->vval.v_float; break;
1600 			    case '/': f /= tv2->vval.v_float; break;
1601 			}
1602 			clear_tv(tv1);
1603 			tv1->v_type = VAR_FLOAT;
1604 			tv1->vval.v_float = f;
1605 		    }
1606 		    else
1607 #endif
1608 		    {
1609 			switch (*op)
1610 			{
1611 			    case '+': n += tv_get_number(tv2); break;
1612 			    case '-': n -= tv_get_number(tv2); break;
1613 			    case '*': n *= tv_get_number(tv2); break;
1614 			    case '/': n = num_divide(n, tv_get_number(tv2)); break;
1615 			    case '%': n = num_modulus(n, tv_get_number(tv2)); break;
1616 			}
1617 			clear_tv(tv1);
1618 			tv1->v_type = VAR_NUMBER;
1619 			tv1->vval.v_number = n;
1620 		    }
1621 		}
1622 		else
1623 		{
1624 		    if (tv2->v_type == VAR_FLOAT)
1625 			break;
1626 
1627 		    // str .= str
1628 		    s = tv_get_string(tv1);
1629 		    s = concat_str(s, tv_get_string_buf(tv2, numbuf));
1630 		    clear_tv(tv1);
1631 		    tv1->v_type = VAR_STRING;
1632 		    tv1->vval.v_string = s;
1633 		}
1634 		return OK;
1635 
1636 	    case VAR_FLOAT:
1637 #ifdef FEAT_FLOAT
1638 		{
1639 		    float_T f;
1640 
1641 		    if (*op == '%' || *op == '.'
1642 				   || (tv2->v_type != VAR_FLOAT
1643 				    && tv2->v_type != VAR_NUMBER
1644 				    && tv2->v_type != VAR_STRING))
1645 			break;
1646 		    if (tv2->v_type == VAR_FLOAT)
1647 			f = tv2->vval.v_float;
1648 		    else
1649 			f = tv_get_number(tv2);
1650 		    switch (*op)
1651 		    {
1652 			case '+': tv1->vval.v_float += f; break;
1653 			case '-': tv1->vval.v_float -= f; break;
1654 			case '*': tv1->vval.v_float *= f; break;
1655 			case '/': tv1->vval.v_float /= f; break;
1656 		    }
1657 		}
1658 #endif
1659 		return OK;
1660 	}
1661     }
1662 
1663     semsg(_(e_letwrong), op);
1664     return FAIL;
1665 }
1666 
1667 /*
1668  * Evaluate the expression used in a ":for var in expr" command.
1669  * "arg" points to "var".
1670  * Set "*errp" to TRUE for an error, FALSE otherwise;
1671  * Return a pointer that holds the info.  Null when there is an error.
1672  */
1673     void *
1674 eval_for_line(
1675     char_u	*arg,
1676     int		*errp,
1677     char_u	**nextcmdp,
1678     int		skip)
1679 {
1680     forinfo_T	*fi;
1681     char_u	*expr;
1682     typval_T	tv;
1683     list_T	*l;
1684 
1685     *errp = TRUE;	/* default: there is an error */
1686 
1687     fi = ALLOC_CLEAR_ONE(forinfo_T);
1688     if (fi == NULL)
1689 	return NULL;
1690 
1691     expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
1692     if (expr == NULL)
1693 	return fi;
1694 
1695     expr = skipwhite(expr);
1696     if (expr[0] != 'i' || expr[1] != 'n' || !VIM_ISWHITE(expr[2]))
1697     {
1698 	emsg(_("E690: Missing \"in\" after :for"));
1699 	return fi;
1700     }
1701 
1702     if (skip)
1703 	++emsg_skip;
1704     if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
1705     {
1706 	*errp = FALSE;
1707 	if (!skip)
1708 	{
1709 	    if (tv.v_type == VAR_LIST)
1710 	    {
1711 		l = tv.vval.v_list;
1712 		if (l == NULL)
1713 		{
1714 		    // a null list is like an empty list: do nothing
1715 		    clear_tv(&tv);
1716 		}
1717 		else
1718 		{
1719 		    // No need to increment the refcount, it's already set for
1720 		    // the list being used in "tv".
1721 		    fi->fi_list = l;
1722 		    list_add_watch(l, &fi->fi_lw);
1723 		    fi->fi_lw.lw_item = l->lv_first;
1724 		}
1725 	    }
1726 	    else if (tv.v_type == VAR_BLOB)
1727 	    {
1728 		fi->fi_bi = 0;
1729 		if (tv.vval.v_blob != NULL)
1730 		{
1731 		    typval_T btv;
1732 
1733 		    // Make a copy, so that the iteration still works when the
1734 		    // blob is changed.
1735 		    blob_copy(&tv, &btv);
1736 		    fi->fi_blob = btv.vval.v_blob;
1737 		}
1738 		clear_tv(&tv);
1739 	    }
1740 	    else
1741 	    {
1742 		emsg(_(e_listreq));
1743 		clear_tv(&tv);
1744 	    }
1745 	}
1746     }
1747     if (skip)
1748 	--emsg_skip;
1749 
1750     return fi;
1751 }
1752 
1753 /*
1754  * Use the first item in a ":for" list.  Advance to the next.
1755  * Assign the values to the variable (list).  "arg" points to the first one.
1756  * Return TRUE when a valid item was found, FALSE when at end of list or
1757  * something wrong.
1758  */
1759     int
1760 next_for_item(void *fi_void, char_u *arg)
1761 {
1762     forinfo_T	*fi = (forinfo_T *)fi_void;
1763     int		result;
1764     listitem_T	*item;
1765 
1766     if (fi->fi_blob != NULL)
1767     {
1768 	typval_T	tv;
1769 
1770 	if (fi->fi_bi >= blob_len(fi->fi_blob))
1771 	    return FALSE;
1772 	tv.v_type = VAR_NUMBER;
1773 	tv.v_lock = VAR_FIXED;
1774 	tv.vval.v_number = blob_get(fi->fi_blob, fi->fi_bi);
1775 	++fi->fi_bi;
1776 	return ex_let_vars(arg, &tv, TRUE, fi->fi_semicolon,
1777 					   fi->fi_varcount, FALSE, NULL) == OK;
1778     }
1779 
1780     item = fi->fi_lw.lw_item;
1781     if (item == NULL)
1782 	result = FALSE;
1783     else
1784     {
1785 	fi->fi_lw.lw_item = item->li_next;
1786 	result = (ex_let_vars(arg, &item->li_tv, TRUE, fi->fi_semicolon,
1787 					  fi->fi_varcount, FALSE, NULL) == OK);
1788     }
1789     return result;
1790 }
1791 
1792 /*
1793  * Free the structure used to store info used by ":for".
1794  */
1795     void
1796 free_for_info(void *fi_void)
1797 {
1798     forinfo_T    *fi = (forinfo_T *)fi_void;
1799 
1800     if (fi != NULL && fi->fi_list != NULL)
1801     {
1802 	list_rem_watch(fi->fi_list, &fi->fi_lw);
1803 	list_unref(fi->fi_list);
1804     }
1805     if (fi != NULL && fi->fi_blob != NULL)
1806 	blob_unref(fi->fi_blob);
1807     vim_free(fi);
1808 }
1809 
1810     void
1811 set_context_for_expression(
1812     expand_T	*xp,
1813     char_u	*arg,
1814     cmdidx_T	cmdidx)
1815 {
1816     int		got_eq = FALSE;
1817     int		c;
1818     char_u	*p;
1819 
1820     if (cmdidx == CMD_let)
1821     {
1822 	xp->xp_context = EXPAND_USER_VARS;
1823 	if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
1824 	{
1825 	    /* ":let var1 var2 ...": find last space. */
1826 	    for (p = arg + STRLEN(arg); p >= arg; )
1827 	    {
1828 		xp->xp_pattern = p;
1829 		MB_PTR_BACK(arg, p);
1830 		if (VIM_ISWHITE(*p))
1831 		    break;
1832 	    }
1833 	    return;
1834 	}
1835     }
1836     else
1837 	xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
1838 							  : EXPAND_EXPRESSION;
1839     while ((xp->xp_pattern = vim_strpbrk(arg,
1840 				  (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
1841     {
1842 	c = *xp->xp_pattern;
1843 	if (c == '&')
1844 	{
1845 	    c = xp->xp_pattern[1];
1846 	    if (c == '&')
1847 	    {
1848 		++xp->xp_pattern;
1849 		xp->xp_context = cmdidx != CMD_let || got_eq
1850 					 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
1851 	    }
1852 	    else if (c != ' ')
1853 	    {
1854 		xp->xp_context = EXPAND_SETTINGS;
1855 		if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
1856 		    xp->xp_pattern += 2;
1857 
1858 	    }
1859 	}
1860 	else if (c == '$')
1861 	{
1862 	    /* environment variable */
1863 	    xp->xp_context = EXPAND_ENV_VARS;
1864 	}
1865 	else if (c == '=')
1866 	{
1867 	    got_eq = TRUE;
1868 	    xp->xp_context = EXPAND_EXPRESSION;
1869 	}
1870 	else if (c == '#'
1871 		&& xp->xp_context == EXPAND_EXPRESSION)
1872 	{
1873 	    /* Autoload function/variable contains '#'. */
1874 	    break;
1875 	}
1876 	else if ((c == '<' || c == '#')
1877 		&& xp->xp_context == EXPAND_FUNCTIONS
1878 		&& vim_strchr(xp->xp_pattern, '(') == NULL)
1879 	{
1880 	    /* Function name can start with "<SNR>" and contain '#'. */
1881 	    break;
1882 	}
1883 	else if (cmdidx != CMD_let || got_eq)
1884 	{
1885 	    if (c == '"')	    /* string */
1886 	    {
1887 		while ((c = *++xp->xp_pattern) != NUL && c != '"')
1888 		    if (c == '\\' && xp->xp_pattern[1] != NUL)
1889 			++xp->xp_pattern;
1890 		xp->xp_context = EXPAND_NOTHING;
1891 	    }
1892 	    else if (c == '\'')	    /* literal string */
1893 	    {
1894 		/* Trick: '' is like stopping and starting a literal string. */
1895 		while ((c = *++xp->xp_pattern) != NUL && c != '\'')
1896 		    /* skip */ ;
1897 		xp->xp_context = EXPAND_NOTHING;
1898 	    }
1899 	    else if (c == '|')
1900 	    {
1901 		if (xp->xp_pattern[1] == '|')
1902 		{
1903 		    ++xp->xp_pattern;
1904 		    xp->xp_context = EXPAND_EXPRESSION;
1905 		}
1906 		else
1907 		    xp->xp_context = EXPAND_COMMANDS;
1908 	    }
1909 	    else
1910 		xp->xp_context = EXPAND_EXPRESSION;
1911 	}
1912 	else
1913 	    /* Doesn't look like something valid, expand as an expression
1914 	     * anyway. */
1915 	    xp->xp_context = EXPAND_EXPRESSION;
1916 	arg = xp->xp_pattern;
1917 	if (*arg != NUL)
1918 	    while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
1919 		/* skip */ ;
1920     }
1921     xp->xp_pattern = arg;
1922 }
1923 
1924 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
1925 /*
1926  * Delete all "menutrans_" variables.
1927  */
1928     void
1929 del_menutrans_vars(void)
1930 {
1931     hashitem_T	*hi;
1932     int		todo;
1933 
1934     hash_lock(&globvarht);
1935     todo = (int)globvarht.ht_used;
1936     for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
1937     {
1938 	if (!HASHITEM_EMPTY(hi))
1939 	{
1940 	    --todo;
1941 	    if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
1942 		delete_var(&globvarht, hi);
1943 	}
1944     }
1945     hash_unlock(&globvarht);
1946 }
1947 #endif
1948 
1949 /*
1950  * Return TRUE if "pat" matches "text".
1951  * Does not use 'cpo' and always uses 'magic'.
1952  */
1953     int
1954 pattern_match(char_u *pat, char_u *text, int ic)
1955 {
1956     int		matches = FALSE;
1957     char_u	*save_cpo;
1958     regmatch_T	regmatch;
1959 
1960     /* avoid 'l' flag in 'cpoptions' */
1961     save_cpo = p_cpo;
1962     p_cpo = (char_u *)"";
1963     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
1964     if (regmatch.regprog != NULL)
1965     {
1966 	regmatch.rm_ic = ic;
1967 	matches = vim_regexec_nl(&regmatch, text, (colnr_T)0);
1968 	vim_regfree(regmatch.regprog);
1969     }
1970     p_cpo = save_cpo;
1971     return matches;
1972 }
1973 
1974 /*
1975  * Handle a name followed by "(".  Both for just "name(arg)" and for
1976  * "expr->name(arg)".
1977  * Returns OK or FAIL.
1978  */
1979     static int
1980 eval_func(
1981 	char_u	    **arg,	// points to "(", will be advanced
1982 	char_u	    *name,
1983 	int	    name_len,
1984 	typval_T    *rettv,
1985 	int	    evaluate,
1986 	typval_T    *basetv)	// "expr" for "expr->name(arg)"
1987 {
1988     char_u	*s = name;
1989     int		len = name_len;
1990     partial_T	*partial;
1991     int		ret = OK;
1992 
1993     if (!evaluate)
1994 	check_vars(s, len);
1995 
1996     /* If "s" is the name of a variable of type VAR_FUNC
1997      * use its contents. */
1998     s = deref_func_name(s, &len, &partial, !evaluate);
1999 
2000     /* Need to make a copy, in case evaluating the arguments makes
2001      * the name invalid. */
2002     s = vim_strsave(s);
2003     if (s == NULL)
2004 	ret = FAIL;
2005     else
2006     {
2007 	funcexe_T funcexe;
2008 
2009 	// Invoke the function.
2010 	vim_memset(&funcexe, 0, sizeof(funcexe));
2011 	funcexe.firstline = curwin->w_cursor.lnum;
2012 	funcexe.lastline = curwin->w_cursor.lnum;
2013 	funcexe.evaluate = evaluate;
2014 	funcexe.partial = partial;
2015 	funcexe.basetv = basetv;
2016 	ret = get_func_tv(s, len, rettv, arg, &funcexe);
2017     }
2018     vim_free(s);
2019 
2020     /* If evaluate is FALSE rettv->v_type was not set in
2021      * get_func_tv, but it's needed in handle_subscript() to parse
2022      * what follows. So set it here. */
2023     if (rettv->v_type == VAR_UNKNOWN && !evaluate && **arg == '(')
2024     {
2025 	rettv->vval.v_string = NULL;
2026 	rettv->v_type = VAR_FUNC;
2027     }
2028 
2029     /* Stop the expression evaluation when immediately
2030      * aborting on error, or when an interrupt occurred or
2031      * an exception was thrown but not caught. */
2032     if (evaluate && aborting())
2033     {
2034 	if (ret == OK)
2035 	    clear_tv(rettv);
2036 	ret = FAIL;
2037     }
2038     return ret;
2039 }
2040 
2041 /*
2042  * The "evaluate" argument: When FALSE, the argument is only parsed but not
2043  * executed.  The function may return OK, but the rettv will be of type
2044  * VAR_UNKNOWN.  The function still returns FAIL for a syntax error.
2045  */
2046 
2047 /*
2048  * Handle zero level expression.
2049  * This calls eval1() and handles error message and nextcmd.
2050  * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
2051  * Note: "rettv.v_lock" is not set.
2052  * Return OK or FAIL.
2053  */
2054     int
2055 eval0(
2056     char_u	*arg,
2057     typval_T	*rettv,
2058     char_u	**nextcmd,
2059     int		evaluate)
2060 {
2061     int		ret;
2062     char_u	*p;
2063     int		did_emsg_before = did_emsg;
2064     int		called_emsg_before = called_emsg;
2065 
2066     p = skipwhite(arg);
2067     ret = eval1(&p, rettv, evaluate);
2068     if (ret == FAIL || !ends_excmd(*p))
2069     {
2070 	if (ret != FAIL)
2071 	    clear_tv(rettv);
2072 	/*
2073 	 * Report the invalid expression unless the expression evaluation has
2074 	 * been cancelled due to an aborting error, an interrupt, or an
2075 	 * exception, or we already gave a more specific error.
2076 	 * Also check called_emsg for when using assert_fails().
2077 	 */
2078 	if (!aborting() && did_emsg == did_emsg_before
2079 					  && called_emsg == called_emsg_before)
2080 	    semsg(_(e_invexpr2), arg);
2081 	ret = FAIL;
2082     }
2083     if (nextcmd != NULL)
2084 	*nextcmd = check_nextcmd(p);
2085 
2086     return ret;
2087 }
2088 
2089 /*
2090  * Handle top level expression:
2091  *	expr2 ? expr1 : expr1
2092  *
2093  * "arg" must point to the first non-white of the expression.
2094  * "arg" is advanced to the next non-white after the recognized expression.
2095  *
2096  * Note: "rettv.v_lock" is not set.
2097  *
2098  * Return OK or FAIL.
2099  */
2100     int
2101 eval1(char_u **arg, typval_T *rettv, int evaluate)
2102 {
2103     int		result;
2104     typval_T	var2;
2105 
2106     /*
2107      * Get the first variable.
2108      */
2109     if (eval2(arg, rettv, evaluate) == FAIL)
2110 	return FAIL;
2111 
2112     if ((*arg)[0] == '?')
2113     {
2114 	result = FALSE;
2115 	if (evaluate)
2116 	{
2117 	    int		error = FALSE;
2118 
2119 	    if (tv_get_number_chk(rettv, &error) != 0)
2120 		result = TRUE;
2121 	    clear_tv(rettv);
2122 	    if (error)
2123 		return FAIL;
2124 	}
2125 
2126 	/*
2127 	 * Get the second variable.
2128 	 */
2129 	*arg = skipwhite(*arg + 1);
2130 	if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
2131 	    return FAIL;
2132 
2133 	/*
2134 	 * Check for the ":".
2135 	 */
2136 	if ((*arg)[0] != ':')
2137 	{
2138 	    emsg(_("E109: Missing ':' after '?'"));
2139 	    if (evaluate && result)
2140 		clear_tv(rettv);
2141 	    return FAIL;
2142 	}
2143 
2144 	/*
2145 	 * Get the third variable.
2146 	 */
2147 	*arg = skipwhite(*arg + 1);
2148 	if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
2149 	{
2150 	    if (evaluate && result)
2151 		clear_tv(rettv);
2152 	    return FAIL;
2153 	}
2154 	if (evaluate && !result)
2155 	    *rettv = var2;
2156     }
2157 
2158     return OK;
2159 }
2160 
2161 /*
2162  * Handle first level expression:
2163  *	expr2 || expr2 || expr2	    logical OR
2164  *
2165  * "arg" must point to the first non-white of the expression.
2166  * "arg" is advanced to the next non-white after the recognized expression.
2167  *
2168  * Return OK or FAIL.
2169  */
2170     static int
2171 eval2(char_u **arg, typval_T *rettv, int evaluate)
2172 {
2173     typval_T	var2;
2174     long	result;
2175     int		first;
2176     int		error = FALSE;
2177 
2178     /*
2179      * Get the first variable.
2180      */
2181     if (eval3(arg, rettv, evaluate) == FAIL)
2182 	return FAIL;
2183 
2184     /*
2185      * Repeat until there is no following "||".
2186      */
2187     first = TRUE;
2188     result = FALSE;
2189     while ((*arg)[0] == '|' && (*arg)[1] == '|')
2190     {
2191 	if (evaluate && first)
2192 	{
2193 	    if (tv_get_number_chk(rettv, &error) != 0)
2194 		result = TRUE;
2195 	    clear_tv(rettv);
2196 	    if (error)
2197 		return FAIL;
2198 	    first = FALSE;
2199 	}
2200 
2201 	/*
2202 	 * Get the second variable.
2203 	 */
2204 	*arg = skipwhite(*arg + 2);
2205 	if (eval3(arg, &var2, evaluate && !result) == FAIL)
2206 	    return FAIL;
2207 
2208 	/*
2209 	 * Compute the result.
2210 	 */
2211 	if (evaluate && !result)
2212 	{
2213 	    if (tv_get_number_chk(&var2, &error) != 0)
2214 		result = TRUE;
2215 	    clear_tv(&var2);
2216 	    if (error)
2217 		return FAIL;
2218 	}
2219 	if (evaluate)
2220 	{
2221 	    rettv->v_type = VAR_NUMBER;
2222 	    rettv->vval.v_number = result;
2223 	}
2224     }
2225 
2226     return OK;
2227 }
2228 
2229 /*
2230  * Handle second level expression:
2231  *	expr3 && expr3 && expr3	    logical AND
2232  *
2233  * "arg" must point to the first non-white of the expression.
2234  * "arg" is advanced to the next non-white after the recognized expression.
2235  *
2236  * Return OK or FAIL.
2237  */
2238     static int
2239 eval3(char_u **arg, typval_T *rettv, int evaluate)
2240 {
2241     typval_T	var2;
2242     long	result;
2243     int		first;
2244     int		error = FALSE;
2245 
2246     /*
2247      * Get the first variable.
2248      */
2249     if (eval4(arg, rettv, evaluate) == FAIL)
2250 	return FAIL;
2251 
2252     /*
2253      * Repeat until there is no following "&&".
2254      */
2255     first = TRUE;
2256     result = TRUE;
2257     while ((*arg)[0] == '&' && (*arg)[1] == '&')
2258     {
2259 	if (evaluate && first)
2260 	{
2261 	    if (tv_get_number_chk(rettv, &error) == 0)
2262 		result = FALSE;
2263 	    clear_tv(rettv);
2264 	    if (error)
2265 		return FAIL;
2266 	    first = FALSE;
2267 	}
2268 
2269 	/*
2270 	 * Get the second variable.
2271 	 */
2272 	*arg = skipwhite(*arg + 2);
2273 	if (eval4(arg, &var2, evaluate && result) == FAIL)
2274 	    return FAIL;
2275 
2276 	/*
2277 	 * Compute the result.
2278 	 */
2279 	if (evaluate && result)
2280 	{
2281 	    if (tv_get_number_chk(&var2, &error) == 0)
2282 		result = FALSE;
2283 	    clear_tv(&var2);
2284 	    if (error)
2285 		return FAIL;
2286 	}
2287 	if (evaluate)
2288 	{
2289 	    rettv->v_type = VAR_NUMBER;
2290 	    rettv->vval.v_number = result;
2291 	}
2292     }
2293 
2294     return OK;
2295 }
2296 
2297 /*
2298  * Handle third level expression:
2299  *	var1 == var2
2300  *	var1 =~ var2
2301  *	var1 != var2
2302  *	var1 !~ var2
2303  *	var1 > var2
2304  *	var1 >= var2
2305  *	var1 < var2
2306  *	var1 <= var2
2307  *	var1 is var2
2308  *	var1 isnot var2
2309  *
2310  * "arg" must point to the first non-white of the expression.
2311  * "arg" is advanced to the next non-white after the recognized expression.
2312  *
2313  * Return OK or FAIL.
2314  */
2315     static int
2316 eval4(char_u **arg, typval_T *rettv, int evaluate)
2317 {
2318     typval_T	var2;
2319     char_u	*p;
2320     int		i;
2321     exptype_T	type = TYPE_UNKNOWN;
2322     int		type_is = FALSE;    /* TRUE for "is" and "isnot" */
2323     int		len = 2;
2324     int		ic;
2325 
2326     /*
2327      * Get the first variable.
2328      */
2329     if (eval5(arg, rettv, evaluate) == FAIL)
2330 	return FAIL;
2331 
2332     p = *arg;
2333     switch (p[0])
2334     {
2335 	case '=':   if (p[1] == '=')
2336 			type = TYPE_EQUAL;
2337 		    else if (p[1] == '~')
2338 			type = TYPE_MATCH;
2339 		    break;
2340 	case '!':   if (p[1] == '=')
2341 			type = TYPE_NEQUAL;
2342 		    else if (p[1] == '~')
2343 			type = TYPE_NOMATCH;
2344 		    break;
2345 	case '>':   if (p[1] != '=')
2346 		    {
2347 			type = TYPE_GREATER;
2348 			len = 1;
2349 		    }
2350 		    else
2351 			type = TYPE_GEQUAL;
2352 		    break;
2353 	case '<':   if (p[1] != '=')
2354 		    {
2355 			type = TYPE_SMALLER;
2356 			len = 1;
2357 		    }
2358 		    else
2359 			type = TYPE_SEQUAL;
2360 		    break;
2361 	case 'i':   if (p[1] == 's')
2362 		    {
2363 			if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
2364 			    len = 5;
2365 			i = p[len];
2366 			if (!isalnum(i) && i != '_')
2367 			{
2368 			    type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
2369 			    type_is = TRUE;
2370 			}
2371 		    }
2372 		    break;
2373     }
2374 
2375     /*
2376      * If there is a comparative operator, use it.
2377      */
2378     if (type != TYPE_UNKNOWN)
2379     {
2380 	/* extra question mark appended: ignore case */
2381 	if (p[len] == '?')
2382 	{
2383 	    ic = TRUE;
2384 	    ++len;
2385 	}
2386 	/* extra '#' appended: match case */
2387 	else if (p[len] == '#')
2388 	{
2389 	    ic = FALSE;
2390 	    ++len;
2391 	}
2392 	/* nothing appended: use 'ignorecase' */
2393 	else
2394 	    ic = p_ic;
2395 
2396 	/*
2397 	 * Get the second variable.
2398 	 */
2399 	*arg = skipwhite(p + len);
2400 	if (eval5(arg, &var2, evaluate) == FAIL)
2401 	{
2402 	    clear_tv(rettv);
2403 	    return FAIL;
2404 	}
2405 	if (evaluate)
2406 	{
2407 	    int ret = typval_compare(rettv, &var2, type, type_is, ic);
2408 
2409 	    clear_tv(&var2);
2410 	    return ret;
2411 	}
2412     }
2413 
2414     return OK;
2415 }
2416 
2417 /*
2418  * Handle fourth level expression:
2419  *	+	number addition
2420  *	-	number subtraction
2421  *	.	string concatenation (if script version is 1)
2422  *	..	string concatenation
2423  *
2424  * "arg" must point to the first non-white of the expression.
2425  * "arg" is advanced to the next non-white after the recognized expression.
2426  *
2427  * Return OK or FAIL.
2428  */
2429     static int
2430 eval5(char_u **arg, typval_T *rettv, int evaluate)
2431 {
2432     typval_T	var2;
2433     typval_T	var3;
2434     int		op;
2435     varnumber_T	n1, n2;
2436 #ifdef FEAT_FLOAT
2437     float_T	f1 = 0, f2 = 0;
2438 #endif
2439     char_u	*s1, *s2;
2440     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
2441     char_u	*p;
2442     int		concat;
2443 
2444     /*
2445      * Get the first variable.
2446      */
2447     if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
2448 	return FAIL;
2449 
2450     /*
2451      * Repeat computing, until no '+', '-' or '.' is following.
2452      */
2453     for (;;)
2454     {
2455 	// "." is only string concatenation when scriptversion is 1
2456 	op = **arg;
2457 	concat = op == '.'
2458 			&& (*(*arg + 1) == '.' || current_sctx.sc_version < 2);
2459 	if (op != '+' && op != '-' && !concat)
2460 	    break;
2461 
2462 	if ((op != '+' || (rettv->v_type != VAR_LIST
2463 						 && rettv->v_type != VAR_BLOB))
2464 #ifdef FEAT_FLOAT
2465 		&& (op == '.' || rettv->v_type != VAR_FLOAT)
2466 #endif
2467 		)
2468 	{
2469 	    /* For "list + ...", an illegal use of the first operand as
2470 	     * a number cannot be determined before evaluating the 2nd
2471 	     * operand: if this is also a list, all is ok.
2472 	     * For "something . ...", "something - ..." or "non-list + ...",
2473 	     * we know that the first operand needs to be a string or number
2474 	     * without evaluating the 2nd operand.  So check before to avoid
2475 	     * side effects after an error. */
2476 	    if (evaluate && tv_get_string_chk(rettv) == NULL)
2477 	    {
2478 		clear_tv(rettv);
2479 		return FAIL;
2480 	    }
2481 	}
2482 
2483 	/*
2484 	 * Get the second variable.
2485 	 */
2486 	if (op == '.' && *(*arg + 1) == '.')  // .. string concatenation
2487 	    ++*arg;
2488 	*arg = skipwhite(*arg + 1);
2489 	if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
2490 	{
2491 	    clear_tv(rettv);
2492 	    return FAIL;
2493 	}
2494 
2495 	if (evaluate)
2496 	{
2497 	    /*
2498 	     * Compute the result.
2499 	     */
2500 	    if (op == '.')
2501 	    {
2502 		s1 = tv_get_string_buf(rettv, buf1);	/* already checked */
2503 		s2 = tv_get_string_buf_chk(&var2, buf2);
2504 		if (s2 == NULL)		/* type error ? */
2505 		{
2506 		    clear_tv(rettv);
2507 		    clear_tv(&var2);
2508 		    return FAIL;
2509 		}
2510 		p = concat_str(s1, s2);
2511 		clear_tv(rettv);
2512 		rettv->v_type = VAR_STRING;
2513 		rettv->vval.v_string = p;
2514 	    }
2515 	    else if (op == '+' && rettv->v_type == VAR_BLOB
2516 						   && var2.v_type == VAR_BLOB)
2517 	    {
2518 		blob_T  *b1 = rettv->vval.v_blob;
2519 		blob_T  *b2 = var2.vval.v_blob;
2520 		blob_T	*b = blob_alloc();
2521 		int	i;
2522 
2523 		if (b != NULL)
2524 		{
2525 		    for (i = 0; i < blob_len(b1); i++)
2526 			ga_append(&b->bv_ga, blob_get(b1, i));
2527 		    for (i = 0; i < blob_len(b2); i++)
2528 			ga_append(&b->bv_ga, blob_get(b2, i));
2529 
2530 		    clear_tv(rettv);
2531 		    rettv_blob_set(rettv, b);
2532 		}
2533 	    }
2534 	    else if (op == '+' && rettv->v_type == VAR_LIST
2535 						   && var2.v_type == VAR_LIST)
2536 	    {
2537 		/* concatenate Lists */
2538 		if (list_concat(rettv->vval.v_list, var2.vval.v_list,
2539 							       &var3) == FAIL)
2540 		{
2541 		    clear_tv(rettv);
2542 		    clear_tv(&var2);
2543 		    return FAIL;
2544 		}
2545 		clear_tv(rettv);
2546 		*rettv = var3;
2547 	    }
2548 	    else
2549 	    {
2550 		int	    error = FALSE;
2551 
2552 #ifdef FEAT_FLOAT
2553 		if (rettv->v_type == VAR_FLOAT)
2554 		{
2555 		    f1 = rettv->vval.v_float;
2556 		    n1 = 0;
2557 		}
2558 		else
2559 #endif
2560 		{
2561 		    n1 = tv_get_number_chk(rettv, &error);
2562 		    if (error)
2563 		    {
2564 			/* This can only happen for "list + non-list".  For
2565 			 * "non-list + ..." or "something - ...", we returned
2566 			 * before evaluating the 2nd operand. */
2567 			clear_tv(rettv);
2568 			return FAIL;
2569 		    }
2570 #ifdef FEAT_FLOAT
2571 		    if (var2.v_type == VAR_FLOAT)
2572 			f1 = n1;
2573 #endif
2574 		}
2575 #ifdef FEAT_FLOAT
2576 		if (var2.v_type == VAR_FLOAT)
2577 		{
2578 		    f2 = var2.vval.v_float;
2579 		    n2 = 0;
2580 		}
2581 		else
2582 #endif
2583 		{
2584 		    n2 = tv_get_number_chk(&var2, &error);
2585 		    if (error)
2586 		    {
2587 			clear_tv(rettv);
2588 			clear_tv(&var2);
2589 			return FAIL;
2590 		    }
2591 #ifdef FEAT_FLOAT
2592 		    if (rettv->v_type == VAR_FLOAT)
2593 			f2 = n2;
2594 #endif
2595 		}
2596 		clear_tv(rettv);
2597 
2598 #ifdef FEAT_FLOAT
2599 		/* If there is a float on either side the result is a float. */
2600 		if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
2601 		{
2602 		    if (op == '+')
2603 			f1 = f1 + f2;
2604 		    else
2605 			f1 = f1 - f2;
2606 		    rettv->v_type = VAR_FLOAT;
2607 		    rettv->vval.v_float = f1;
2608 		}
2609 		else
2610 #endif
2611 		{
2612 		    if (op == '+')
2613 			n1 = n1 + n2;
2614 		    else
2615 			n1 = n1 - n2;
2616 		    rettv->v_type = VAR_NUMBER;
2617 		    rettv->vval.v_number = n1;
2618 		}
2619 	    }
2620 	    clear_tv(&var2);
2621 	}
2622     }
2623     return OK;
2624 }
2625 
2626 /*
2627  * Handle fifth level expression:
2628  *	*	number multiplication
2629  *	/	number division
2630  *	%	number modulo
2631  *
2632  * "arg" must point to the first non-white of the expression.
2633  * "arg" is advanced to the next non-white after the recognized expression.
2634  *
2635  * Return OK or FAIL.
2636  */
2637     static int
2638 eval6(
2639     char_u	**arg,
2640     typval_T	*rettv,
2641     int		evaluate,
2642     int		want_string)  /* after "." operator */
2643 {
2644     typval_T	var2;
2645     int		op;
2646     varnumber_T	n1, n2;
2647 #ifdef FEAT_FLOAT
2648     int		use_float = FALSE;
2649     float_T	f1 = 0, f2 = 0;
2650 #endif
2651     int		error = FALSE;
2652 
2653     /*
2654      * Get the first variable.
2655      */
2656     if (eval7(arg, rettv, evaluate, want_string) == FAIL)
2657 	return FAIL;
2658 
2659     /*
2660      * Repeat computing, until no '*', '/' or '%' is following.
2661      */
2662     for (;;)
2663     {
2664 	op = **arg;
2665 	if (op != '*' && op != '/' && op != '%')
2666 	    break;
2667 
2668 	if (evaluate)
2669 	{
2670 #ifdef FEAT_FLOAT
2671 	    if (rettv->v_type == VAR_FLOAT)
2672 	    {
2673 		f1 = rettv->vval.v_float;
2674 		use_float = TRUE;
2675 		n1 = 0;
2676 	    }
2677 	    else
2678 #endif
2679 		n1 = tv_get_number_chk(rettv, &error);
2680 	    clear_tv(rettv);
2681 	    if (error)
2682 		return FAIL;
2683 	}
2684 	else
2685 	    n1 = 0;
2686 
2687 	/*
2688 	 * Get the second variable.
2689 	 */
2690 	*arg = skipwhite(*arg + 1);
2691 	if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
2692 	    return FAIL;
2693 
2694 	if (evaluate)
2695 	{
2696 #ifdef FEAT_FLOAT
2697 	    if (var2.v_type == VAR_FLOAT)
2698 	    {
2699 		if (!use_float)
2700 		{
2701 		    f1 = n1;
2702 		    use_float = TRUE;
2703 		}
2704 		f2 = var2.vval.v_float;
2705 		n2 = 0;
2706 	    }
2707 	    else
2708 #endif
2709 	    {
2710 		n2 = tv_get_number_chk(&var2, &error);
2711 		clear_tv(&var2);
2712 		if (error)
2713 		    return FAIL;
2714 #ifdef FEAT_FLOAT
2715 		if (use_float)
2716 		    f2 = n2;
2717 #endif
2718 	    }
2719 
2720 	    /*
2721 	     * Compute the result.
2722 	     * When either side is a float the result is a float.
2723 	     */
2724 #ifdef FEAT_FLOAT
2725 	    if (use_float)
2726 	    {
2727 		if (op == '*')
2728 		    f1 = f1 * f2;
2729 		else if (op == '/')
2730 		{
2731 # ifdef VMS
2732 		    /* VMS crashes on divide by zero, work around it */
2733 		    if (f2 == 0.0)
2734 		    {
2735 			if (f1 == 0)
2736 			    f1 = -1 * __F_FLT_MAX - 1L;   /* similar to NaN */
2737 			else if (f1 < 0)
2738 			    f1 = -1 * __F_FLT_MAX;
2739 			else
2740 			    f1 = __F_FLT_MAX;
2741 		    }
2742 		    else
2743 			f1 = f1 / f2;
2744 # else
2745 		    /* We rely on the floating point library to handle divide
2746 		     * by zero to result in "inf" and not a crash. */
2747 		    f1 = f1 / f2;
2748 # endif
2749 		}
2750 		else
2751 		{
2752 		    emsg(_("E804: Cannot use '%' with Float"));
2753 		    return FAIL;
2754 		}
2755 		rettv->v_type = VAR_FLOAT;
2756 		rettv->vval.v_float = f1;
2757 	    }
2758 	    else
2759 #endif
2760 	    {
2761 		if (op == '*')
2762 		    n1 = n1 * n2;
2763 		else if (op == '/')
2764 		    n1 = num_divide(n1, n2);
2765 		else
2766 		    n1 = num_modulus(n1, n2);
2767 
2768 		rettv->v_type = VAR_NUMBER;
2769 		rettv->vval.v_number = n1;
2770 	    }
2771 	}
2772     }
2773 
2774     return OK;
2775 }
2776 
2777 /*
2778  * Handle sixth level expression:
2779  *  number		number constant
2780  *  0zFFFFFFFF		Blob constant
2781  *  "string"		string constant
2782  *  'string'		literal string constant
2783  *  &option-name	option value
2784  *  @r			register contents
2785  *  identifier		variable value
2786  *  function()		function call
2787  *  $VAR		environment variable
2788  *  (expression)	nested expression
2789  *  [expr, expr]	List
2790  *  {key: val, key: val}   Dictionary
2791  *  #{key: val, key: val}  Dictionary with literal keys
2792  *
2793  *  Also handle:
2794  *  ! in front		logical NOT
2795  *  - in front		unary minus
2796  *  + in front		unary plus (ignored)
2797  *  trailing []		subscript in String or List
2798  *  trailing .name	entry in Dictionary
2799  *  trailing ->name()	method call
2800  *
2801  * "arg" must point to the first non-white of the expression.
2802  * "arg" is advanced to the next non-white after the recognized expression.
2803  *
2804  * Return OK or FAIL.
2805  */
2806     static int
2807 eval7(
2808     char_u	**arg,
2809     typval_T	*rettv,
2810     int		evaluate,
2811     int		want_string UNUSED)	/* after "." operator */
2812 {
2813     varnumber_T	n;
2814     int		len;
2815     char_u	*s;
2816     char_u	*start_leader, *end_leader;
2817     int		ret = OK;
2818     char_u	*alias;
2819 
2820     /*
2821      * Initialise variable so that clear_tv() can't mistake this for a
2822      * string and free a string that isn't there.
2823      */
2824     rettv->v_type = VAR_UNKNOWN;
2825 
2826     /*
2827      * Skip '!', '-' and '+' characters.  They are handled later.
2828      */
2829     start_leader = *arg;
2830     while (**arg == '!' || **arg == '-' || **arg == '+')
2831 	*arg = skipwhite(*arg + 1);
2832     end_leader = *arg;
2833 
2834     if (**arg == '.' && (!isdigit(*(*arg + 1))
2835 #ifdef FEAT_FLOAT
2836 	    || current_sctx.sc_version < 2
2837 #endif
2838 	    ))
2839     {
2840 	semsg(_(e_invexpr2), *arg);
2841 	++*arg;
2842 	return FAIL;
2843     }
2844 
2845     switch (**arg)
2846     {
2847     /*
2848      * Number constant.
2849      */
2850     case '0':
2851     case '1':
2852     case '2':
2853     case '3':
2854     case '4':
2855     case '5':
2856     case '6':
2857     case '7':
2858     case '8':
2859     case '9':
2860     case '.':
2861 	{
2862 #ifdef FEAT_FLOAT
2863 		char_u *p;
2864 		int    get_float = FALSE;
2865 
2866 		/* We accept a float when the format matches
2867 		 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?".  This is very
2868 		 * strict to avoid backwards compatibility problems.
2869 		 * With script version 2 and later the leading digit can be
2870 		 * omitted.
2871 		 * Don't look for a float after the "." operator, so that
2872 		 * ":let vers = 1.2.3" doesn't fail. */
2873 		if (**arg == '.')
2874 		    p = *arg;
2875 		else
2876 		    p = skipdigits(*arg + 1);
2877 		if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
2878 		{
2879 		    get_float = TRUE;
2880 		    p = skipdigits(p + 2);
2881 		    if (*p == 'e' || *p == 'E')
2882 		    {
2883 			++p;
2884 			if (*p == '-' || *p == '+')
2885 			    ++p;
2886 			if (!vim_isdigit(*p))
2887 			    get_float = FALSE;
2888 			else
2889 			    p = skipdigits(p + 1);
2890 		    }
2891 		    if (ASCII_ISALPHA(*p) || *p == '.')
2892 			get_float = FALSE;
2893 		}
2894 		if (get_float)
2895 		{
2896 		    float_T	f;
2897 
2898 		    *arg += string2float(*arg, &f);
2899 		    if (evaluate)
2900 		    {
2901 			rettv->v_type = VAR_FLOAT;
2902 			rettv->vval.v_float = f;
2903 		    }
2904 		}
2905 		else
2906 #endif
2907 		if (**arg == '0' && ((*arg)[1] == 'z' || (*arg)[1] == 'Z'))
2908 		{
2909 		    char_u  *bp;
2910 		    blob_T  *blob = NULL;  // init for gcc
2911 
2912 		    // Blob constant: 0z0123456789abcdef
2913 		    if (evaluate)
2914 			blob = blob_alloc();
2915 		    for (bp = *arg + 2; vim_isxdigit(bp[0]); bp += 2)
2916 		    {
2917 			if (!vim_isxdigit(bp[1]))
2918 			{
2919 			    if (blob != NULL)
2920 			    {
2921 				emsg(_("E973: Blob literal should have an even number of hex characters"));
2922 				ga_clear(&blob->bv_ga);
2923 				VIM_CLEAR(blob);
2924 			    }
2925 			    ret = FAIL;
2926 			    break;
2927 			}
2928 			if (blob != NULL)
2929 			    ga_append(&blob->bv_ga,
2930 					 (hex2nr(*bp) << 4) + hex2nr(*(bp+1)));
2931 			if (bp[2] == '.' && vim_isxdigit(bp[3]))
2932 			    ++bp;
2933 		    }
2934 		    if (blob != NULL)
2935 			rettv_blob_set(rettv, blob);
2936 		    *arg = bp;
2937 		}
2938 		else
2939 		{
2940 		    // decimal, hex or octal number
2941 		    vim_str2nr(*arg, NULL, &len, STR2NR_ALL, &n, NULL, 0, TRUE);
2942 		    if (len == 0)
2943 		    {
2944 			semsg(_(e_invexpr2), *arg);
2945 			ret = FAIL;
2946 			break;
2947 		    }
2948 		    *arg += len;
2949 		    if (evaluate)
2950 		    {
2951 			rettv->v_type = VAR_NUMBER;
2952 			rettv->vval.v_number = n;
2953 		    }
2954 		}
2955 		break;
2956 	}
2957 
2958     /*
2959      * String constant: "string".
2960      */
2961     case '"':	ret = get_string_tv(arg, rettv, evaluate);
2962 		break;
2963 
2964     /*
2965      * Literal string constant: 'str''ing'.
2966      */
2967     case '\'':	ret = get_lit_string_tv(arg, rettv, evaluate);
2968 		break;
2969 
2970     /*
2971      * List: [expr, expr]
2972      */
2973     case '[':	ret = get_list_tv(arg, rettv, evaluate);
2974 		break;
2975 
2976     /*
2977      * Dictionary: #{key: val, key: val}
2978      */
2979     case '#':	if ((*arg)[1] == '{')
2980 		{
2981 		    ++*arg;
2982 		    ret = dict_get_tv(arg, rettv, evaluate, TRUE);
2983 		}
2984 		else
2985 		    ret = NOTDONE;
2986 		break;
2987 
2988     /*
2989      * Lambda: {arg, arg -> expr}
2990      * Dictionary: {'key': val, 'key': val}
2991      */
2992     case '{':	ret = get_lambda_tv(arg, rettv, evaluate);
2993 		if (ret == NOTDONE)
2994 		    ret = dict_get_tv(arg, rettv, evaluate, FALSE);
2995 		break;
2996 
2997     /*
2998      * Option value: &name
2999      */
3000     case '&':	ret = get_option_tv(arg, rettv, evaluate);
3001 		break;
3002 
3003     /*
3004      * Environment variable: $VAR.
3005      */
3006     case '$':	ret = get_env_tv(arg, rettv, evaluate);
3007 		break;
3008 
3009     /*
3010      * Register contents: @r.
3011      */
3012     case '@':	++*arg;
3013 		if (evaluate)
3014 		{
3015 		    rettv->v_type = VAR_STRING;
3016 		    rettv->vval.v_string = get_reg_contents(**arg,
3017 							    GREG_EXPR_SRC);
3018 		}
3019 		if (**arg != NUL)
3020 		    ++*arg;
3021 		break;
3022 
3023     /*
3024      * nested expression: (expression).
3025      */
3026     case '(':	*arg = skipwhite(*arg + 1);
3027 		ret = eval1(arg, rettv, evaluate);	/* recursive! */
3028 		if (**arg == ')')
3029 		    ++*arg;
3030 		else if (ret == OK)
3031 		{
3032 		    emsg(_("E110: Missing ')'"));
3033 		    clear_tv(rettv);
3034 		    ret = FAIL;
3035 		}
3036 		break;
3037 
3038     default:	ret = NOTDONE;
3039 		break;
3040     }
3041 
3042     if (ret == NOTDONE)
3043     {
3044 	/*
3045 	 * Must be a variable or function name.
3046 	 * Can also be a curly-braces kind of name: {expr}.
3047 	 */
3048 	s = *arg;
3049 	len = get_name_len(arg, &alias, evaluate, TRUE);
3050 	if (alias != NULL)
3051 	    s = alias;
3052 
3053 	if (len <= 0)
3054 	    ret = FAIL;
3055 	else
3056 	{
3057 	    if (**arg == '(')		/* recursive! */
3058 		ret = eval_func(arg, s, len, rettv, evaluate, NULL);
3059 	    else if (evaluate)
3060 		ret = get_var_tv(s, len, rettv, NULL, TRUE, FALSE);
3061 	    else
3062 	    {
3063 		check_vars(s, len);
3064 		ret = OK;
3065 	    }
3066 	}
3067 	vim_free(alias);
3068     }
3069 
3070     *arg = skipwhite(*arg);
3071 
3072     /* Handle following '[', '(' and '.' for expr[expr], expr.name,
3073      * expr(expr), expr->name(expr) */
3074     if (ret == OK)
3075 	ret = handle_subscript(arg, rettv, evaluate, TRUE,
3076 						    start_leader, &end_leader);
3077 
3078     /*
3079      * Apply logical NOT and unary '-', from right to left, ignore '+'.
3080      */
3081     if (ret == OK && evaluate && end_leader > start_leader)
3082 	ret = eval7_leader(rettv, start_leader, &end_leader);
3083     return ret;
3084 }
3085 
3086 /*
3087  * Apply the leading "!" and "-" before an eval7 expression to "rettv".
3088  * Adjusts "end_leaderp" until it is at "start_leader".
3089  */
3090     static int
3091 eval7_leader(typval_T *rettv, char_u *start_leader, char_u **end_leaderp)
3092 {
3093     char_u	*end_leader = *end_leaderp;
3094     int		ret = OK;
3095     int		error = FALSE;
3096     varnumber_T val = 0;
3097 #ifdef FEAT_FLOAT
3098     float_T	    f = 0.0;
3099 
3100     if (rettv->v_type == VAR_FLOAT)
3101 	f = rettv->vval.v_float;
3102     else
3103 #endif
3104 	val = tv_get_number_chk(rettv, &error);
3105     if (error)
3106     {
3107 	clear_tv(rettv);
3108 	ret = FAIL;
3109     }
3110     else
3111     {
3112 	while (end_leader > start_leader)
3113 	{
3114 	    --end_leader;
3115 	    if (*end_leader == '!')
3116 	    {
3117 #ifdef FEAT_FLOAT
3118 		if (rettv->v_type == VAR_FLOAT)
3119 		    f = !f;
3120 		else
3121 #endif
3122 		    val = !val;
3123 	    }
3124 	    else if (*end_leader == '-')
3125 	    {
3126 #ifdef FEAT_FLOAT
3127 		if (rettv->v_type == VAR_FLOAT)
3128 		    f = -f;
3129 		else
3130 #endif
3131 		    val = -val;
3132 	    }
3133 	}
3134 #ifdef FEAT_FLOAT
3135 	if (rettv->v_type == VAR_FLOAT)
3136 	{
3137 	    clear_tv(rettv);
3138 	    rettv->vval.v_float = f;
3139 	}
3140 	else
3141 #endif
3142 	{
3143 	    clear_tv(rettv);
3144 	    rettv->v_type = VAR_NUMBER;
3145 	    rettv->vval.v_number = val;
3146 	}
3147     }
3148     *end_leaderp = end_leader;
3149     return ret;
3150 }
3151 
3152 /*
3153  * Call the function referred to in "rettv".
3154  */
3155     static int
3156 call_func_rettv(
3157 	char_u	    **arg,
3158 	typval_T    *rettv,
3159 	int	    evaluate,
3160 	dict_T	    *selfdict,
3161 	typval_T    *basetv)
3162 {
3163     partial_T	*pt = NULL;
3164     funcexe_T	funcexe;
3165     typval_T	functv;
3166     char_u	*s;
3167     int		ret;
3168 
3169     // need to copy the funcref so that we can clear rettv
3170     if (evaluate)
3171     {
3172 	functv = *rettv;
3173 	rettv->v_type = VAR_UNKNOWN;
3174 
3175 	/* Invoke the function.  Recursive! */
3176 	if (functv.v_type == VAR_PARTIAL)
3177 	{
3178 	    pt = functv.vval.v_partial;
3179 	    s = partial_name(pt);
3180 	}
3181 	else
3182 	    s = functv.vval.v_string;
3183     }
3184     else
3185 	s = (char_u *)"";
3186 
3187     vim_memset(&funcexe, 0, sizeof(funcexe));
3188     funcexe.firstline = curwin->w_cursor.lnum;
3189     funcexe.lastline = curwin->w_cursor.lnum;
3190     funcexe.evaluate = evaluate;
3191     funcexe.partial = pt;
3192     funcexe.selfdict = selfdict;
3193     funcexe.basetv = basetv;
3194     ret = get_func_tv(s, -1, rettv, arg, &funcexe);
3195 
3196     /* Clear the funcref afterwards, so that deleting it while
3197      * evaluating the arguments is possible (see test55). */
3198     if (evaluate)
3199 	clear_tv(&functv);
3200 
3201     return ret;
3202 }
3203 
3204 /*
3205  * Evaluate "->method()".
3206  * "*arg" points to the '-'.
3207  * Returns FAIL or OK. "*arg" is advanced to after the ')'.
3208  */
3209     static int
3210 eval_lambda(
3211     char_u	**arg,
3212     typval_T	*rettv,
3213     int		evaluate,
3214     int		verbose)	/* give error messages */
3215 {
3216     typval_T	base = *rettv;
3217     int		ret;
3218 
3219     // Skip over the ->.
3220     *arg += 2;
3221     rettv->v_type = VAR_UNKNOWN;
3222 
3223     ret = get_lambda_tv(arg, rettv, evaluate);
3224     if (ret == NOTDONE)
3225 	return FAIL;
3226     else if (**arg != '(')
3227     {
3228 	if (verbose)
3229 	{
3230 	    if (*skipwhite(*arg) == '(')
3231 		semsg(_(e_nowhitespace));
3232 	    else
3233 		semsg(_(e_missingparen), "lambda");
3234 	}
3235 	clear_tv(rettv);
3236 	return FAIL;
3237     }
3238     return call_func_rettv(arg, rettv, evaluate, NULL, &base);
3239 }
3240 
3241 /*
3242  * Evaluate "->method()".
3243  * "*arg" points to the '-'.
3244  * Returns FAIL or OK. "*arg" is advanced to after the ')'.
3245  */
3246     static int
3247 eval_method(
3248     char_u	**arg,
3249     typval_T	*rettv,
3250     int		evaluate,
3251     int		verbose)	/* give error messages */
3252 {
3253     char_u	*name;
3254     long	len;
3255     char_u	*alias;
3256     typval_T	base = *rettv;
3257     int		ret;
3258 
3259     // Skip over the ->.
3260     *arg += 2;
3261     rettv->v_type = VAR_UNKNOWN;
3262 
3263     name = *arg;
3264     len = get_name_len(arg, &alias, evaluate, TRUE);
3265     if (alias != NULL)
3266 	name = alias;
3267 
3268     if (len <= 0)
3269     {
3270 	if (verbose)
3271 	    emsg(_("E260: Missing name after ->"));
3272 	ret = FAIL;
3273     }
3274     else
3275     {
3276 	if (**arg != '(')
3277 	{
3278 	    if (verbose)
3279 		semsg(_(e_missingparen), name);
3280 	    ret = FAIL;
3281 	}
3282 	else if (VIM_ISWHITE((*arg)[-1]))
3283 	{
3284 	    if (verbose)
3285 		semsg(_(e_nowhitespace));
3286 	    ret = FAIL;
3287 	}
3288 	else
3289 	    ret = eval_func(arg, name, len, rettv, evaluate, &base);
3290     }
3291 
3292     // Clear the funcref afterwards, so that deleting it while
3293     // evaluating the arguments is possible (see test55).
3294     if (evaluate)
3295 	clear_tv(&base);
3296 
3297     return ret;
3298 }
3299 
3300 /*
3301  * Evaluate an "[expr]" or "[expr:expr]" index.  Also "dict.key".
3302  * "*arg" points to the '[' or '.'.
3303  * Returns FAIL or OK. "*arg" is advanced to after the ']'.
3304  */
3305     static int
3306 eval_index(
3307     char_u	**arg,
3308     typval_T	*rettv,
3309     int		evaluate,
3310     int		verbose)	/* give error messages */
3311 {
3312     int		empty1 = FALSE, empty2 = FALSE;
3313     typval_T	var1, var2;
3314     long	i;
3315     long	n1, n2 = 0;
3316     long	len = -1;
3317     int		range = FALSE;
3318     char_u	*s;
3319     char_u	*key = NULL;
3320 
3321     switch (rettv->v_type)
3322     {
3323 	case VAR_FUNC:
3324 	case VAR_PARTIAL:
3325 	    if (verbose)
3326 		emsg(_("E695: Cannot index a Funcref"));
3327 	    return FAIL;
3328 	case VAR_FLOAT:
3329 #ifdef FEAT_FLOAT
3330 	    if (verbose)
3331 		emsg(_(e_float_as_string));
3332 	    return FAIL;
3333 #endif
3334 	case VAR_SPECIAL:
3335 	case VAR_JOB:
3336 	case VAR_CHANNEL:
3337 	    if (verbose)
3338 		emsg(_("E909: Cannot index a special variable"));
3339 	    return FAIL;
3340 	case VAR_UNKNOWN:
3341 	    if (evaluate)
3342 		return FAIL;
3343 	    /* FALLTHROUGH */
3344 
3345 	case VAR_STRING:
3346 	case VAR_NUMBER:
3347 	case VAR_LIST:
3348 	case VAR_DICT:
3349 	case VAR_BLOB:
3350 	    break;
3351     }
3352 
3353     init_tv(&var1);
3354     init_tv(&var2);
3355     if (**arg == '.')
3356     {
3357 	/*
3358 	 * dict.name
3359 	 */
3360 	key = *arg + 1;
3361 	for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
3362 	    ;
3363 	if (len == 0)
3364 	    return FAIL;
3365 	*arg = skipwhite(key + len);
3366     }
3367     else
3368     {
3369 	/*
3370 	 * something[idx]
3371 	 *
3372 	 * Get the (first) variable from inside the [].
3373 	 */
3374 	*arg = skipwhite(*arg + 1);
3375 	if (**arg == ':')
3376 	    empty1 = TRUE;
3377 	else if (eval1(arg, &var1, evaluate) == FAIL)	/* recursive! */
3378 	    return FAIL;
3379 	else if (evaluate && tv_get_string_chk(&var1) == NULL)
3380 	{
3381 	    /* not a number or string */
3382 	    clear_tv(&var1);
3383 	    return FAIL;
3384 	}
3385 
3386 	/*
3387 	 * Get the second variable from inside the [:].
3388 	 */
3389 	if (**arg == ':')
3390 	{
3391 	    range = TRUE;
3392 	    *arg = skipwhite(*arg + 1);
3393 	    if (**arg == ']')
3394 		empty2 = TRUE;
3395 	    else if (eval1(arg, &var2, evaluate) == FAIL)	/* recursive! */
3396 	    {
3397 		if (!empty1)
3398 		    clear_tv(&var1);
3399 		return FAIL;
3400 	    }
3401 	    else if (evaluate && tv_get_string_chk(&var2) == NULL)
3402 	    {
3403 		/* not a number or string */
3404 		if (!empty1)
3405 		    clear_tv(&var1);
3406 		clear_tv(&var2);
3407 		return FAIL;
3408 	    }
3409 	}
3410 
3411 	/* Check for the ']'. */
3412 	if (**arg != ']')
3413 	{
3414 	    if (verbose)
3415 		emsg(_(e_missbrac));
3416 	    clear_tv(&var1);
3417 	    if (range)
3418 		clear_tv(&var2);
3419 	    return FAIL;
3420 	}
3421 	*arg = skipwhite(*arg + 1);	/* skip the ']' */
3422     }
3423 
3424     if (evaluate)
3425     {
3426 	n1 = 0;
3427 	if (!empty1 && rettv->v_type != VAR_DICT)
3428 	{
3429 	    n1 = tv_get_number(&var1);
3430 	    clear_tv(&var1);
3431 	}
3432 	if (range)
3433 	{
3434 	    if (empty2)
3435 		n2 = -1;
3436 	    else
3437 	    {
3438 		n2 = tv_get_number(&var2);
3439 		clear_tv(&var2);
3440 	    }
3441 	}
3442 
3443 	switch (rettv->v_type)
3444 	{
3445 	    case VAR_UNKNOWN:
3446 	    case VAR_FUNC:
3447 	    case VAR_PARTIAL:
3448 	    case VAR_FLOAT:
3449 	    case VAR_SPECIAL:
3450 	    case VAR_JOB:
3451 	    case VAR_CHANNEL:
3452 		break; /* not evaluating, skipping over subscript */
3453 
3454 	    case VAR_NUMBER:
3455 	    case VAR_STRING:
3456 		s = tv_get_string(rettv);
3457 		len = (long)STRLEN(s);
3458 		if (range)
3459 		{
3460 		    /* The resulting variable is a substring.  If the indexes
3461 		     * are out of range the result is empty. */
3462 		    if (n1 < 0)
3463 		    {
3464 			n1 = len + n1;
3465 			if (n1 < 0)
3466 			    n1 = 0;
3467 		    }
3468 		    if (n2 < 0)
3469 			n2 = len + n2;
3470 		    else if (n2 >= len)
3471 			n2 = len;
3472 		    if (n1 >= len || n2 < 0 || n1 > n2)
3473 			s = NULL;
3474 		    else
3475 			s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
3476 		}
3477 		else
3478 		{
3479 		    /* The resulting variable is a string of a single
3480 		     * character.  If the index is too big or negative the
3481 		     * result is empty. */
3482 		    if (n1 >= len || n1 < 0)
3483 			s = NULL;
3484 		    else
3485 			s = vim_strnsave(s + n1, 1);
3486 		}
3487 		clear_tv(rettv);
3488 		rettv->v_type = VAR_STRING;
3489 		rettv->vval.v_string = s;
3490 		break;
3491 
3492 	    case VAR_BLOB:
3493 		len = blob_len(rettv->vval.v_blob);
3494 		if (range)
3495 		{
3496 		    // The resulting variable is a sub-blob.  If the indexes
3497 		    // are out of range the result is empty.
3498 		    if (n1 < 0)
3499 		    {
3500 			n1 = len + n1;
3501 			if (n1 < 0)
3502 			    n1 = 0;
3503 		    }
3504 		    if (n2 < 0)
3505 			n2 = len + n2;
3506 		    else if (n2 >= len)
3507 			n2 = len - 1;
3508 		    if (n1 >= len || n2 < 0 || n1 > n2)
3509 		    {
3510 			clear_tv(rettv);
3511 			rettv->v_type = VAR_BLOB;
3512 			rettv->vval.v_blob = NULL;
3513 		    }
3514 		    else
3515 		    {
3516 			blob_T  *blob = blob_alloc();
3517 
3518 			if (blob != NULL)
3519 			{
3520 			    if (ga_grow(&blob->bv_ga, n2 - n1 + 1) == FAIL)
3521 			    {
3522 				blob_free(blob);
3523 				return FAIL;
3524 			    }
3525 			    blob->bv_ga.ga_len = n2 - n1 + 1;
3526 			    for (i = n1; i <= n2; i++)
3527 				blob_set(blob, i - n1,
3528 					      blob_get(rettv->vval.v_blob, i));
3529 
3530 			    clear_tv(rettv);
3531 			    rettv_blob_set(rettv, blob);
3532 			}
3533 		    }
3534 		}
3535 		else
3536 		{
3537 		    // The resulting variable is a byte value.
3538 		    // If the index is too big or negative that is an error.
3539 		    if (n1 < 0)
3540 			n1 = len + n1;
3541 		    if (n1 < len && n1 >= 0)
3542 		    {
3543 			int v = blob_get(rettv->vval.v_blob, n1);
3544 
3545 			clear_tv(rettv);
3546 			rettv->v_type = VAR_NUMBER;
3547 			rettv->vval.v_number = v;
3548 		    }
3549 		    else
3550 			semsg(_(e_blobidx), n1);
3551 		}
3552 		break;
3553 
3554 	    case VAR_LIST:
3555 		len = list_len(rettv->vval.v_list);
3556 		if (n1 < 0)
3557 		    n1 = len + n1;
3558 		if (!empty1 && (n1 < 0 || n1 >= len))
3559 		{
3560 		    /* For a range we allow invalid values and return an empty
3561 		     * list.  A list index out of range is an error. */
3562 		    if (!range)
3563 		    {
3564 			if (verbose)
3565 			    semsg(_(e_listidx), n1);
3566 			return FAIL;
3567 		    }
3568 		    n1 = len;
3569 		}
3570 		if (range)
3571 		{
3572 		    list_T	*l;
3573 		    listitem_T	*item;
3574 
3575 		    if (n2 < 0)
3576 			n2 = len + n2;
3577 		    else if (n2 >= len)
3578 			n2 = len - 1;
3579 		    if (!empty2 && (n2 < 0 || n2 + 1 < n1))
3580 			n2 = -1;
3581 		    l = list_alloc();
3582 		    if (l == NULL)
3583 			return FAIL;
3584 		    for (item = list_find(rettv->vval.v_list, n1);
3585 							       n1 <= n2; ++n1)
3586 		    {
3587 			if (list_append_tv(l, &item->li_tv) == FAIL)
3588 			{
3589 			    list_free(l);
3590 			    return FAIL;
3591 			}
3592 			item = item->li_next;
3593 		    }
3594 		    clear_tv(rettv);
3595 		    rettv_list_set(rettv, l);
3596 		}
3597 		else
3598 		{
3599 		    copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
3600 		    clear_tv(rettv);
3601 		    *rettv = var1;
3602 		}
3603 		break;
3604 
3605 	    case VAR_DICT:
3606 		if (range)
3607 		{
3608 		    if (verbose)
3609 			emsg(_(e_dictrange));
3610 		    if (len == -1)
3611 			clear_tv(&var1);
3612 		    return FAIL;
3613 		}
3614 		{
3615 		    dictitem_T	*item;
3616 
3617 		    if (len == -1)
3618 		    {
3619 			key = tv_get_string_chk(&var1);
3620 			if (key == NULL)
3621 			{
3622 			    clear_tv(&var1);
3623 			    return FAIL;
3624 			}
3625 		    }
3626 
3627 		    item = dict_find(rettv->vval.v_dict, key, (int)len);
3628 
3629 		    if (item == NULL && verbose)
3630 			semsg(_(e_dictkey), key);
3631 		    if (len == -1)
3632 			clear_tv(&var1);
3633 		    if (item == NULL)
3634 			return FAIL;
3635 
3636 		    copy_tv(&item->di_tv, &var1);
3637 		    clear_tv(rettv);
3638 		    *rettv = var1;
3639 		}
3640 		break;
3641 	}
3642     }
3643 
3644     return OK;
3645 }
3646 
3647 /*
3648  * Get an option value.
3649  * "arg" points to the '&' or '+' before the option name.
3650  * "arg" is advanced to character after the option name.
3651  * Return OK or FAIL.
3652  */
3653     int
3654 get_option_tv(
3655     char_u	**arg,
3656     typval_T	*rettv,	/* when NULL, only check if option exists */
3657     int		evaluate)
3658 {
3659     char_u	*option_end;
3660     long	numval;
3661     char_u	*stringval;
3662     int		opt_type;
3663     int		c;
3664     int		working = (**arg == '+');    /* has("+option") */
3665     int		ret = OK;
3666     int		opt_flags;
3667 
3668     /*
3669      * Isolate the option name and find its value.
3670      */
3671     option_end = find_option_end(arg, &opt_flags);
3672     if (option_end == NULL)
3673     {
3674 	if (rettv != NULL)
3675 	    semsg(_("E112: Option name missing: %s"), *arg);
3676 	return FAIL;
3677     }
3678 
3679     if (!evaluate)
3680     {
3681 	*arg = option_end;
3682 	return OK;
3683     }
3684 
3685     c = *option_end;
3686     *option_end = NUL;
3687     opt_type = get_option_value(*arg, &numval,
3688 			       rettv == NULL ? NULL : &stringval, opt_flags);
3689 
3690     if (opt_type == -3)			/* invalid name */
3691     {
3692 	if (rettv != NULL)
3693 	    semsg(_("E113: Unknown option: %s"), *arg);
3694 	ret = FAIL;
3695     }
3696     else if (rettv != NULL)
3697     {
3698 	if (opt_type == -2)		/* hidden string option */
3699 	{
3700 	    rettv->v_type = VAR_STRING;
3701 	    rettv->vval.v_string = NULL;
3702 	}
3703 	else if (opt_type == -1)	/* hidden number option */
3704 	{
3705 	    rettv->v_type = VAR_NUMBER;
3706 	    rettv->vval.v_number = 0;
3707 	}
3708 	else if (opt_type == 1)		/* number option */
3709 	{
3710 	    rettv->v_type = VAR_NUMBER;
3711 	    rettv->vval.v_number = numval;
3712 	}
3713 	else				/* string option */
3714 	{
3715 	    rettv->v_type = VAR_STRING;
3716 	    rettv->vval.v_string = stringval;
3717 	}
3718     }
3719     else if (working && (opt_type == -2 || opt_type == -1))
3720 	ret = FAIL;
3721 
3722     *option_end = c;		    /* put back for error messages */
3723     *arg = option_end;
3724 
3725     return ret;
3726 }
3727 
3728 /*
3729  * Allocate a variable for a string constant.
3730  * Return OK or FAIL.
3731  */
3732     static int
3733 get_string_tv(char_u **arg, typval_T *rettv, int evaluate)
3734 {
3735     char_u	*p;
3736     char_u	*name;
3737     int		extra = 0;
3738 
3739     /*
3740      * Find the end of the string, skipping backslashed characters.
3741      */
3742     for (p = *arg + 1; *p != NUL && *p != '"'; MB_PTR_ADV(p))
3743     {
3744 	if (*p == '\\' && p[1] != NUL)
3745 	{
3746 	    ++p;
3747 	    /* A "\<x>" form occupies at least 4 characters, and produces up
3748 	     * to 6 characters: reserve space for 2 extra */
3749 	    if (*p == '<')
3750 		extra += 2;
3751 	}
3752     }
3753 
3754     if (*p != '"')
3755     {
3756 	semsg(_("E114: Missing quote: %s"), *arg);
3757 	return FAIL;
3758     }
3759 
3760     /* If only parsing, set *arg and return here */
3761     if (!evaluate)
3762     {
3763 	*arg = p + 1;
3764 	return OK;
3765     }
3766 
3767     /*
3768      * Copy the string into allocated memory, handling backslashed
3769      * characters.
3770      */
3771     name = alloc(p - *arg + extra);
3772     if (name == NULL)
3773 	return FAIL;
3774     rettv->v_type = VAR_STRING;
3775     rettv->vval.v_string = name;
3776 
3777     for (p = *arg + 1; *p != NUL && *p != '"'; )
3778     {
3779 	if (*p == '\\')
3780 	{
3781 	    switch (*++p)
3782 	    {
3783 		case 'b': *name++ = BS; ++p; break;
3784 		case 'e': *name++ = ESC; ++p; break;
3785 		case 'f': *name++ = FF; ++p; break;
3786 		case 'n': *name++ = NL; ++p; break;
3787 		case 'r': *name++ = CAR; ++p; break;
3788 		case 't': *name++ = TAB; ++p; break;
3789 
3790 		case 'X': /* hex: "\x1", "\x12" */
3791 		case 'x':
3792 		case 'u': /* Unicode: "\u0023" */
3793 		case 'U':
3794 			  if (vim_isxdigit(p[1]))
3795 			  {
3796 			      int	n, nr;
3797 			      int	c = toupper(*p);
3798 
3799 			      if (c == 'X')
3800 				  n = 2;
3801 			      else if (*p == 'u')
3802 				  n = 4;
3803 			      else
3804 				  n = 8;
3805 			      nr = 0;
3806 			      while (--n >= 0 && vim_isxdigit(p[1]))
3807 			      {
3808 				  ++p;
3809 				  nr = (nr << 4) + hex2nr(*p);
3810 			      }
3811 			      ++p;
3812 			      /* For "\u" store the number according to
3813 			       * 'encoding'. */
3814 			      if (c != 'X')
3815 				  name += (*mb_char2bytes)(nr, name);
3816 			      else
3817 				  *name++ = nr;
3818 			  }
3819 			  break;
3820 
3821 			  /* octal: "\1", "\12", "\123" */
3822 		case '0':
3823 		case '1':
3824 		case '2':
3825 		case '3':
3826 		case '4':
3827 		case '5':
3828 		case '6':
3829 		case '7': *name = *p++ - '0';
3830 			  if (*p >= '0' && *p <= '7')
3831 			  {
3832 			      *name = (*name << 3) + *p++ - '0';
3833 			      if (*p >= '0' && *p <= '7')
3834 				  *name = (*name << 3) + *p++ - '0';
3835 			  }
3836 			  ++name;
3837 			  break;
3838 
3839 			    /* Special key, e.g.: "\<C-W>" */
3840 		case '<': extra = trans_special(&p, name, TRUE, TRUE);
3841 			  if (extra != 0)
3842 			  {
3843 			      name += extra;
3844 			      break;
3845 			  }
3846 			  /* FALLTHROUGH */
3847 
3848 		default:  MB_COPY_CHAR(p, name);
3849 			  break;
3850 	    }
3851 	}
3852 	else
3853 	    MB_COPY_CHAR(p, name);
3854 
3855     }
3856     *name = NUL;
3857     if (*p != NUL) /* just in case */
3858 	++p;
3859     *arg = p;
3860 
3861     return OK;
3862 }
3863 
3864 /*
3865  * Allocate a variable for a 'str''ing' constant.
3866  * Return OK or FAIL.
3867  */
3868     static int
3869 get_lit_string_tv(char_u **arg, typval_T *rettv, int evaluate)
3870 {
3871     char_u	*p;
3872     char_u	*str;
3873     int		reduce = 0;
3874 
3875     /*
3876      * Find the end of the string, skipping ''.
3877      */
3878     for (p = *arg + 1; *p != NUL; MB_PTR_ADV(p))
3879     {
3880 	if (*p == '\'')
3881 	{
3882 	    if (p[1] != '\'')
3883 		break;
3884 	    ++reduce;
3885 	    ++p;
3886 	}
3887     }
3888 
3889     if (*p != '\'')
3890     {
3891 	semsg(_("E115: Missing quote: %s"), *arg);
3892 	return FAIL;
3893     }
3894 
3895     /* If only parsing return after setting "*arg" */
3896     if (!evaluate)
3897     {
3898 	*arg = p + 1;
3899 	return OK;
3900     }
3901 
3902     /*
3903      * Copy the string into allocated memory, handling '' to ' reduction.
3904      */
3905     str = alloc((p - *arg) - reduce);
3906     if (str == NULL)
3907 	return FAIL;
3908     rettv->v_type = VAR_STRING;
3909     rettv->vval.v_string = str;
3910 
3911     for (p = *arg + 1; *p != NUL; )
3912     {
3913 	if (*p == '\'')
3914 	{
3915 	    if (p[1] != '\'')
3916 		break;
3917 	    ++p;
3918 	}
3919 	MB_COPY_CHAR(p, str);
3920     }
3921     *str = NUL;
3922     *arg = p + 1;
3923 
3924     return OK;
3925 }
3926 
3927 /*
3928  * Return the function name of the partial.
3929  */
3930     char_u *
3931 partial_name(partial_T *pt)
3932 {
3933     if (pt->pt_name != NULL)
3934 	return pt->pt_name;
3935     return pt->pt_func->uf_name;
3936 }
3937 
3938     static void
3939 partial_free(partial_T *pt)
3940 {
3941     int i;
3942 
3943     for (i = 0; i < pt->pt_argc; ++i)
3944 	clear_tv(&pt->pt_argv[i]);
3945     vim_free(pt->pt_argv);
3946     dict_unref(pt->pt_dict);
3947     if (pt->pt_name != NULL)
3948     {
3949 	func_unref(pt->pt_name);
3950 	vim_free(pt->pt_name);
3951     }
3952     else
3953 	func_ptr_unref(pt->pt_func);
3954     vim_free(pt);
3955 }
3956 
3957 /*
3958  * Unreference a closure: decrement the reference count and free it when it
3959  * becomes zero.
3960  */
3961     void
3962 partial_unref(partial_T *pt)
3963 {
3964     if (pt != NULL && --pt->pt_refcount <= 0)
3965 	partial_free(pt);
3966 }
3967 
3968 static int tv_equal_recurse_limit;
3969 
3970     static int
3971 func_equal(
3972     typval_T *tv1,
3973     typval_T *tv2,
3974     int	     ic)	    /* ignore case */
3975 {
3976     char_u	*s1, *s2;
3977     dict_T	*d1, *d2;
3978     int		a1, a2;
3979     int		i;
3980 
3981     /* empty and NULL function name considered the same */
3982     s1 = tv1->v_type == VAR_FUNC ? tv1->vval.v_string
3983 					   : partial_name(tv1->vval.v_partial);
3984     if (s1 != NULL && *s1 == NUL)
3985 	s1 = NULL;
3986     s2 = tv2->v_type == VAR_FUNC ? tv2->vval.v_string
3987 					   : partial_name(tv2->vval.v_partial);
3988     if (s2 != NULL && *s2 == NUL)
3989 	s2 = NULL;
3990     if (s1 == NULL || s2 == NULL)
3991     {
3992 	if (s1 != s2)
3993 	    return FALSE;
3994     }
3995     else if (STRCMP(s1, s2) != 0)
3996 	return FALSE;
3997 
3998     /* empty dict and NULL dict is different */
3999     d1 = tv1->v_type == VAR_FUNC ? NULL : tv1->vval.v_partial->pt_dict;
4000     d2 = tv2->v_type == VAR_FUNC ? NULL : tv2->vval.v_partial->pt_dict;
4001     if (d1 == NULL || d2 == NULL)
4002     {
4003 	if (d1 != d2)
4004 	    return FALSE;
4005     }
4006     else if (!dict_equal(d1, d2, ic, TRUE))
4007 	return FALSE;
4008 
4009     /* empty list and no list considered the same */
4010     a1 = tv1->v_type == VAR_FUNC ? 0 : tv1->vval.v_partial->pt_argc;
4011     a2 = tv2->v_type == VAR_FUNC ? 0 : tv2->vval.v_partial->pt_argc;
4012     if (a1 != a2)
4013 	return FALSE;
4014     for (i = 0; i < a1; ++i)
4015 	if (!tv_equal(tv1->vval.v_partial->pt_argv + i,
4016 		      tv2->vval.v_partial->pt_argv + i, ic, TRUE))
4017 	    return FALSE;
4018 
4019     return TRUE;
4020 }
4021 
4022 /*
4023  * Return TRUE if "tv1" and "tv2" have the same value.
4024  * Compares the items just like "==" would compare them, but strings and
4025  * numbers are different.  Floats and numbers are also different.
4026  */
4027     int
4028 tv_equal(
4029     typval_T *tv1,
4030     typval_T *tv2,
4031     int	     ic,	    /* ignore case */
4032     int	     recursive)	    /* TRUE when used recursively */
4033 {
4034     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4035     char_u	*s1, *s2;
4036     static int  recursive_cnt = 0;	    /* catch recursive loops */
4037     int		r;
4038 
4039     /* Catch lists and dicts that have an endless loop by limiting
4040      * recursiveness to a limit.  We guess they are equal then.
4041      * A fixed limit has the problem of still taking an awful long time.
4042      * Reduce the limit every time running into it. That should work fine for
4043      * deeply linked structures that are not recursively linked and catch
4044      * recursiveness quickly. */
4045     if (!recursive)
4046 	tv_equal_recurse_limit = 1000;
4047     if (recursive_cnt >= tv_equal_recurse_limit)
4048     {
4049 	--tv_equal_recurse_limit;
4050 	return TRUE;
4051     }
4052 
4053     /* For VAR_FUNC and VAR_PARTIAL compare the function name, bound dict and
4054      * arguments. */
4055     if ((tv1->v_type == VAR_FUNC
4056 		|| (tv1->v_type == VAR_PARTIAL && tv1->vval.v_partial != NULL))
4057 	    && (tv2->v_type == VAR_FUNC
4058 		|| (tv2->v_type == VAR_PARTIAL && tv2->vval.v_partial != NULL)))
4059     {
4060 	++recursive_cnt;
4061 	r = func_equal(tv1, tv2, ic);
4062 	--recursive_cnt;
4063 	return r;
4064     }
4065 
4066     if (tv1->v_type != tv2->v_type)
4067 	return FALSE;
4068 
4069     switch (tv1->v_type)
4070     {
4071 	case VAR_LIST:
4072 	    ++recursive_cnt;
4073 	    r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic, TRUE);
4074 	    --recursive_cnt;
4075 	    return r;
4076 
4077 	case VAR_DICT:
4078 	    ++recursive_cnt;
4079 	    r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic, TRUE);
4080 	    --recursive_cnt;
4081 	    return r;
4082 
4083 	case VAR_BLOB:
4084 	    return blob_equal(tv1->vval.v_blob, tv2->vval.v_blob);
4085 
4086 	case VAR_NUMBER:
4087 	    return tv1->vval.v_number == tv2->vval.v_number;
4088 
4089 	case VAR_STRING:
4090 	    s1 = tv_get_string_buf(tv1, buf1);
4091 	    s2 = tv_get_string_buf(tv2, buf2);
4092 	    return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
4093 
4094 	case VAR_SPECIAL:
4095 	    return tv1->vval.v_number == tv2->vval.v_number;
4096 
4097 	case VAR_FLOAT:
4098 #ifdef FEAT_FLOAT
4099 	    return tv1->vval.v_float == tv2->vval.v_float;
4100 #endif
4101 	case VAR_JOB:
4102 #ifdef FEAT_JOB_CHANNEL
4103 	    return tv1->vval.v_job == tv2->vval.v_job;
4104 #endif
4105 	case VAR_CHANNEL:
4106 #ifdef FEAT_JOB_CHANNEL
4107 	    return tv1->vval.v_channel == tv2->vval.v_channel;
4108 #endif
4109 	case VAR_FUNC:
4110 	case VAR_PARTIAL:
4111 	case VAR_UNKNOWN:
4112 	    break;
4113     }
4114 
4115     /* VAR_UNKNOWN can be the result of a invalid expression, let's say it
4116      * does not equal anything, not even itself. */
4117     return FALSE;
4118 }
4119 
4120 /*
4121  * Return the next (unique) copy ID.
4122  * Used for serializing nested structures.
4123  */
4124     int
4125 get_copyID(void)
4126 {
4127     current_copyID += COPYID_INC;
4128     return current_copyID;
4129 }
4130 
4131 /*
4132  * Garbage collection for lists and dictionaries.
4133  *
4134  * We use reference counts to be able to free most items right away when they
4135  * are no longer used.  But for composite items it's possible that it becomes
4136  * unused while the reference count is > 0: When there is a recursive
4137  * reference.  Example:
4138  *	:let l = [1, 2, 3]
4139  *	:let d = {9: l}
4140  *	:let l[1] = d
4141  *
4142  * Since this is quite unusual we handle this with garbage collection: every
4143  * once in a while find out which lists and dicts are not referenced from any
4144  * variable.
4145  *
4146  * Here is a good reference text about garbage collection (refers to Python
4147  * but it applies to all reference-counting mechanisms):
4148  *	http://python.ca/nas/python/gc/
4149  */
4150 
4151 /*
4152  * Do garbage collection for lists and dicts.
4153  * When "testing" is TRUE this is called from test_garbagecollect_now().
4154  * Return TRUE if some memory was freed.
4155  */
4156     int
4157 garbage_collect(int testing)
4158 {
4159     int		copyID;
4160     int		abort = FALSE;
4161     buf_T	*buf;
4162     win_T	*wp;
4163     int		did_free = FALSE;
4164     tabpage_T	*tp;
4165 
4166     if (!testing)
4167     {
4168 	/* Only do this once. */
4169 	want_garbage_collect = FALSE;
4170 	may_garbage_collect = FALSE;
4171 	garbage_collect_at_exit = FALSE;
4172     }
4173 
4174     /* We advance by two because we add one for items referenced through
4175      * previous_funccal. */
4176     copyID = get_copyID();
4177 
4178     /*
4179      * 1. Go through all accessible variables and mark all lists and dicts
4180      *    with copyID.
4181      */
4182 
4183     /* Don't free variables in the previous_funccal list unless they are only
4184      * referenced through previous_funccal.  This must be first, because if
4185      * the item is referenced elsewhere the funccal must not be freed. */
4186     abort = abort || set_ref_in_previous_funccal(copyID);
4187 
4188     /* script-local variables */
4189     abort = abort || garbage_collect_scriptvars(copyID);
4190 
4191     /* buffer-local variables */
4192     FOR_ALL_BUFFERS(buf)
4193 	abort = abort || set_ref_in_item(&buf->b_bufvar.di_tv, copyID,
4194 								  NULL, NULL);
4195 
4196     /* window-local variables */
4197     FOR_ALL_TAB_WINDOWS(tp, wp)
4198 	abort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,
4199 								  NULL, NULL);
4200     if (aucmd_win != NULL)
4201 	abort = abort || set_ref_in_item(&aucmd_win->w_winvar.di_tv, copyID,
4202 								  NULL, NULL);
4203 #ifdef FEAT_TEXT_PROP
4204     for (wp = first_popupwin; wp != NULL; wp = wp->w_next)
4205 	abort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,
4206 								  NULL, NULL);
4207     FOR_ALL_TABPAGES(tp)
4208 	for (wp = tp->tp_first_popupwin; wp != NULL; wp = wp->w_next)
4209 		abort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,
4210 								  NULL, NULL);
4211 #endif
4212 
4213     /* tabpage-local variables */
4214     FOR_ALL_TABPAGES(tp)
4215 	abort = abort || set_ref_in_item(&tp->tp_winvar.di_tv, copyID,
4216 								  NULL, NULL);
4217     /* global variables */
4218     abort = abort || set_ref_in_ht(&globvarht, copyID, NULL);
4219 
4220     /* function-local variables */
4221     abort = abort || set_ref_in_call_stack(copyID);
4222 
4223     /* named functions (matters for closures) */
4224     abort = abort || set_ref_in_functions(copyID);
4225 
4226     /* function call arguments, if v:testing is set. */
4227     abort = abort || set_ref_in_func_args(copyID);
4228 
4229     /* v: vars */
4230     abort = abort || garbage_collect_vimvars(copyID);
4231 
4232     // callbacks in buffers
4233     abort = abort || set_ref_in_buffers(copyID);
4234 
4235 #ifdef FEAT_LUA
4236     abort = abort || set_ref_in_lua(copyID);
4237 #endif
4238 
4239 #ifdef FEAT_PYTHON
4240     abort = abort || set_ref_in_python(copyID);
4241 #endif
4242 
4243 #ifdef FEAT_PYTHON3
4244     abort = abort || set_ref_in_python3(copyID);
4245 #endif
4246 
4247 #ifdef FEAT_JOB_CHANNEL
4248     abort = abort || set_ref_in_channel(copyID);
4249     abort = abort || set_ref_in_job(copyID);
4250 #endif
4251 #ifdef FEAT_NETBEANS_INTG
4252     abort = abort || set_ref_in_nb_channel(copyID);
4253 #endif
4254 
4255 #ifdef FEAT_TIMERS
4256     abort = abort || set_ref_in_timer(copyID);
4257 #endif
4258 
4259 #ifdef FEAT_QUICKFIX
4260     abort = abort || set_ref_in_quickfix(copyID);
4261 #endif
4262 
4263 #ifdef FEAT_TERMINAL
4264     abort = abort || set_ref_in_term(copyID);
4265 #endif
4266 
4267 #ifdef FEAT_TEXT_PROP
4268     abort = abort || set_ref_in_popups(copyID);
4269 #endif
4270 
4271     if (!abort)
4272     {
4273 	/*
4274 	 * 2. Free lists and dictionaries that are not referenced.
4275 	 */
4276 	did_free = free_unref_items(copyID);
4277 
4278 	/*
4279 	 * 3. Check if any funccal can be freed now.
4280 	 *    This may call us back recursively.
4281 	 */
4282 	free_unref_funccal(copyID, testing);
4283     }
4284     else if (p_verbose > 0)
4285     {
4286 	verb_msg(_("Not enough memory to set references, garbage collection aborted!"));
4287     }
4288 
4289     return did_free;
4290 }
4291 
4292 /*
4293  * Free lists, dictionaries, channels and jobs that are no longer referenced.
4294  */
4295     static int
4296 free_unref_items(int copyID)
4297 {
4298     int		did_free = FALSE;
4299 
4300     /* Let all "free" functions know that we are here.  This means no
4301      * dictionaries, lists, channels or jobs are to be freed, because we will
4302      * do that here. */
4303     in_free_unref_items = TRUE;
4304 
4305     /*
4306      * PASS 1: free the contents of the items.  We don't free the items
4307      * themselves yet, so that it is possible to decrement refcount counters
4308      */
4309 
4310     /* Go through the list of dicts and free items without the copyID. */
4311     did_free |= dict_free_nonref(copyID);
4312 
4313     /* Go through the list of lists and free items without the copyID. */
4314     did_free |= list_free_nonref(copyID);
4315 
4316 #ifdef FEAT_JOB_CHANNEL
4317     /* Go through the list of jobs and free items without the copyID. This
4318      * must happen before doing channels, because jobs refer to channels, but
4319      * the reference from the channel to the job isn't tracked. */
4320     did_free |= free_unused_jobs_contents(copyID, COPYID_MASK);
4321 
4322     /* Go through the list of channels and free items without the copyID.  */
4323     did_free |= free_unused_channels_contents(copyID, COPYID_MASK);
4324 #endif
4325 
4326     /*
4327      * PASS 2: free the items themselves.
4328      */
4329     dict_free_items(copyID);
4330     list_free_items(copyID);
4331 
4332 #ifdef FEAT_JOB_CHANNEL
4333     /* Go through the list of jobs and free items without the copyID. This
4334      * must happen before doing channels, because jobs refer to channels, but
4335      * the reference from the channel to the job isn't tracked. */
4336     free_unused_jobs(copyID, COPYID_MASK);
4337 
4338     /* Go through the list of channels and free items without the copyID.  */
4339     free_unused_channels(copyID, COPYID_MASK);
4340 #endif
4341 
4342     in_free_unref_items = FALSE;
4343 
4344     return did_free;
4345 }
4346 
4347 /*
4348  * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
4349  * "list_stack" is used to add lists to be marked.  Can be NULL.
4350  *
4351  * Returns TRUE if setting references failed somehow.
4352  */
4353     int
4354 set_ref_in_ht(hashtab_T *ht, int copyID, list_stack_T **list_stack)
4355 {
4356     int		todo;
4357     int		abort = FALSE;
4358     hashitem_T	*hi;
4359     hashtab_T	*cur_ht;
4360     ht_stack_T	*ht_stack = NULL;
4361     ht_stack_T	*tempitem;
4362 
4363     cur_ht = ht;
4364     for (;;)
4365     {
4366 	if (!abort)
4367 	{
4368 	    /* Mark each item in the hashtab.  If the item contains a hashtab
4369 	     * it is added to ht_stack, if it contains a list it is added to
4370 	     * list_stack. */
4371 	    todo = (int)cur_ht->ht_used;
4372 	    for (hi = cur_ht->ht_array; todo > 0; ++hi)
4373 		if (!HASHITEM_EMPTY(hi))
4374 		{
4375 		    --todo;
4376 		    abort = abort || set_ref_in_item(&HI2DI(hi)->di_tv, copyID,
4377 						       &ht_stack, list_stack);
4378 		}
4379 	}
4380 
4381 	if (ht_stack == NULL)
4382 	    break;
4383 
4384 	/* take an item from the stack */
4385 	cur_ht = ht_stack->ht;
4386 	tempitem = ht_stack;
4387 	ht_stack = ht_stack->prev;
4388 	free(tempitem);
4389     }
4390 
4391     return abort;
4392 }
4393 
4394 /*
4395  * Mark a dict and its items with "copyID".
4396  * Returns TRUE if setting references failed somehow.
4397  */
4398     int
4399 set_ref_in_dict(dict_T *d, int copyID)
4400 {
4401     if (d != NULL && d->dv_copyID != copyID)
4402     {
4403 	d->dv_copyID = copyID;
4404 	return set_ref_in_ht(&d->dv_hashtab, copyID, NULL);
4405     }
4406     return FALSE;
4407 }
4408 
4409 /*
4410  * Mark a list and its items with "copyID".
4411  * Returns TRUE if setting references failed somehow.
4412  */
4413     int
4414 set_ref_in_list(list_T *ll, int copyID)
4415 {
4416     if (ll != NULL && ll->lv_copyID != copyID)
4417     {
4418 	ll->lv_copyID = copyID;
4419 	return set_ref_in_list_items(ll, copyID, NULL);
4420     }
4421     return FALSE;
4422 }
4423 
4424 /*
4425  * Mark all lists and dicts referenced through list "l" with "copyID".
4426  * "ht_stack" is used to add hashtabs to be marked.  Can be NULL.
4427  *
4428  * Returns TRUE if setting references failed somehow.
4429  */
4430     int
4431 set_ref_in_list_items(list_T *l, int copyID, ht_stack_T **ht_stack)
4432 {
4433     listitem_T	 *li;
4434     int		 abort = FALSE;
4435     list_T	 *cur_l;
4436     list_stack_T *list_stack = NULL;
4437     list_stack_T *tempitem;
4438 
4439     cur_l = l;
4440     for (;;)
4441     {
4442 	if (!abort)
4443 	    /* Mark each item in the list.  If the item contains a hashtab
4444 	     * it is added to ht_stack, if it contains a list it is added to
4445 	     * list_stack. */
4446 	    for (li = cur_l->lv_first; !abort && li != NULL; li = li->li_next)
4447 		abort = abort || set_ref_in_item(&li->li_tv, copyID,
4448 						       ht_stack, &list_stack);
4449 	if (list_stack == NULL)
4450 	    break;
4451 
4452 	/* take an item from the stack */
4453 	cur_l = list_stack->list;
4454 	tempitem = list_stack;
4455 	list_stack = list_stack->prev;
4456 	free(tempitem);
4457     }
4458 
4459     return abort;
4460 }
4461 
4462 /*
4463  * Mark all lists and dicts referenced through typval "tv" with "copyID".
4464  * "list_stack" is used to add lists to be marked.  Can be NULL.
4465  * "ht_stack" is used to add hashtabs to be marked.  Can be NULL.
4466  *
4467  * Returns TRUE if setting references failed somehow.
4468  */
4469     int
4470 set_ref_in_item(
4471     typval_T	    *tv,
4472     int		    copyID,
4473     ht_stack_T	    **ht_stack,
4474     list_stack_T    **list_stack)
4475 {
4476     int		abort = FALSE;
4477 
4478     if (tv->v_type == VAR_DICT)
4479     {
4480 	dict_T	*dd = tv->vval.v_dict;
4481 
4482 	if (dd != NULL && dd->dv_copyID != copyID)
4483 	{
4484 	    /* Didn't see this dict yet. */
4485 	    dd->dv_copyID = copyID;
4486 	    if (ht_stack == NULL)
4487 	    {
4488 		abort = set_ref_in_ht(&dd->dv_hashtab, copyID, list_stack);
4489 	    }
4490 	    else
4491 	    {
4492 		ht_stack_T *newitem = (ht_stack_T*)malloc(sizeof(ht_stack_T));
4493 		if (newitem == NULL)
4494 		    abort = TRUE;
4495 		else
4496 		{
4497 		    newitem->ht = &dd->dv_hashtab;
4498 		    newitem->prev = *ht_stack;
4499 		    *ht_stack = newitem;
4500 		}
4501 	    }
4502 	}
4503     }
4504     else if (tv->v_type == VAR_LIST)
4505     {
4506 	list_T	*ll = tv->vval.v_list;
4507 
4508 	if (ll != NULL && ll->lv_copyID != copyID)
4509 	{
4510 	    /* Didn't see this list yet. */
4511 	    ll->lv_copyID = copyID;
4512 	    if (list_stack == NULL)
4513 	    {
4514 		abort = set_ref_in_list_items(ll, copyID, ht_stack);
4515 	    }
4516 	    else
4517 	    {
4518 		list_stack_T *newitem = (list_stack_T*)malloc(
4519 							sizeof(list_stack_T));
4520 		if (newitem == NULL)
4521 		    abort = TRUE;
4522 		else
4523 		{
4524 		    newitem->list = ll;
4525 		    newitem->prev = *list_stack;
4526 		    *list_stack = newitem;
4527 		}
4528 	    }
4529 	}
4530     }
4531     else if (tv->v_type == VAR_FUNC)
4532     {
4533 	abort = set_ref_in_func(tv->vval.v_string, NULL, copyID);
4534     }
4535     else if (tv->v_type == VAR_PARTIAL)
4536     {
4537 	partial_T	*pt = tv->vval.v_partial;
4538 	int		i;
4539 
4540 	/* A partial does not have a copyID, because it cannot contain itself.
4541 	 */
4542 	if (pt != NULL)
4543 	{
4544 	    abort = set_ref_in_func(pt->pt_name, pt->pt_func, copyID);
4545 
4546 	    if (pt->pt_dict != NULL)
4547 	    {
4548 		typval_T dtv;
4549 
4550 		dtv.v_type = VAR_DICT;
4551 		dtv.vval.v_dict = pt->pt_dict;
4552 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4553 	    }
4554 
4555 	    for (i = 0; i < pt->pt_argc; ++i)
4556 		abort = abort || set_ref_in_item(&pt->pt_argv[i], copyID,
4557 							ht_stack, list_stack);
4558 	}
4559     }
4560 #ifdef FEAT_JOB_CHANNEL
4561     else if (tv->v_type == VAR_JOB)
4562     {
4563 	job_T	    *job = tv->vval.v_job;
4564 	typval_T    dtv;
4565 
4566 	if (job != NULL && job->jv_copyID != copyID)
4567 	{
4568 	    job->jv_copyID = copyID;
4569 	    if (job->jv_channel != NULL)
4570 	    {
4571 		dtv.v_type = VAR_CHANNEL;
4572 		dtv.vval.v_channel = job->jv_channel;
4573 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4574 	    }
4575 	    if (job->jv_exit_cb.cb_partial != NULL)
4576 	    {
4577 		dtv.v_type = VAR_PARTIAL;
4578 		dtv.vval.v_partial = job->jv_exit_cb.cb_partial;
4579 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4580 	    }
4581 	}
4582     }
4583     else if (tv->v_type == VAR_CHANNEL)
4584     {
4585 	channel_T   *ch =tv->vval.v_channel;
4586 	ch_part_T   part;
4587 	typval_T    dtv;
4588 	jsonq_T	    *jq;
4589 	cbq_T	    *cq;
4590 
4591 	if (ch != NULL && ch->ch_copyID != copyID)
4592 	{
4593 	    ch->ch_copyID = copyID;
4594 	    for (part = PART_SOCK; part < PART_COUNT; ++part)
4595 	    {
4596 		for (jq = ch->ch_part[part].ch_json_head.jq_next; jq != NULL;
4597 							     jq = jq->jq_next)
4598 		    set_ref_in_item(jq->jq_value, copyID, ht_stack, list_stack);
4599 		for (cq = ch->ch_part[part].ch_cb_head.cq_next; cq != NULL;
4600 							     cq = cq->cq_next)
4601 		    if (cq->cq_callback.cb_partial != NULL)
4602 		    {
4603 			dtv.v_type = VAR_PARTIAL;
4604 			dtv.vval.v_partial = cq->cq_callback.cb_partial;
4605 			set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4606 		    }
4607 		if (ch->ch_part[part].ch_callback.cb_partial != NULL)
4608 		{
4609 		    dtv.v_type = VAR_PARTIAL;
4610 		    dtv.vval.v_partial =
4611 				      ch->ch_part[part].ch_callback.cb_partial;
4612 		    set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4613 		}
4614 	    }
4615 	    if (ch->ch_callback.cb_partial != NULL)
4616 	    {
4617 		dtv.v_type = VAR_PARTIAL;
4618 		dtv.vval.v_partial = ch->ch_callback.cb_partial;
4619 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4620 	    }
4621 	    if (ch->ch_close_cb.cb_partial != NULL)
4622 	    {
4623 		dtv.v_type = VAR_PARTIAL;
4624 		dtv.vval.v_partial = ch->ch_close_cb.cb_partial;
4625 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4626 	    }
4627 	}
4628     }
4629 #endif
4630     return abort;
4631 }
4632 
4633     static char *
4634 get_var_special_name(int nr)
4635 {
4636     switch (nr)
4637     {
4638 	case VVAL_FALSE: return "v:false";
4639 	case VVAL_TRUE:  return "v:true";
4640 	case VVAL_NONE:  return "v:none";
4641 	case VVAL_NULL:  return "v:null";
4642     }
4643     internal_error("get_var_special_name()");
4644     return "42";
4645 }
4646 
4647 /*
4648  * Return a string with the string representation of a variable.
4649  * If the memory is allocated "tofree" is set to it, otherwise NULL.
4650  * "numbuf" is used for a number.
4651  * When "copyID" is not NULL replace recursive lists and dicts with "...".
4652  * When both "echo_style" and "composite_val" are FALSE, put quotes around
4653  * stings as "string()", otherwise does not put quotes around strings, as
4654  * ":echo" displays values.
4655  * When "restore_copyID" is FALSE, repeated items in dictionaries and lists
4656  * are replaced with "...".
4657  * May return NULL.
4658  */
4659     char_u *
4660 echo_string_core(
4661     typval_T	*tv,
4662     char_u	**tofree,
4663     char_u	*numbuf,
4664     int		copyID,
4665     int		echo_style,
4666     int		restore_copyID,
4667     int		composite_val)
4668 {
4669     static int	recurse = 0;
4670     char_u	*r = NULL;
4671 
4672     if (recurse >= DICT_MAXNEST)
4673     {
4674 	if (!did_echo_string_emsg)
4675 	{
4676 	    /* Only give this message once for a recursive call to avoid
4677 	     * flooding the user with errors.  And stop iterating over lists
4678 	     * and dicts. */
4679 	    did_echo_string_emsg = TRUE;
4680 	    emsg(_("E724: variable nested too deep for displaying"));
4681 	}
4682 	*tofree = NULL;
4683 	return (char_u *)"{E724}";
4684     }
4685     ++recurse;
4686 
4687     switch (tv->v_type)
4688     {
4689 	case VAR_STRING:
4690 	    if (echo_style && !composite_val)
4691 	    {
4692 		*tofree = NULL;
4693 		r = tv->vval.v_string;
4694 		if (r == NULL)
4695 		    r = (char_u *)"";
4696 	    }
4697 	    else
4698 	    {
4699 		*tofree = string_quote(tv->vval.v_string, FALSE);
4700 		r = *tofree;
4701 	    }
4702 	    break;
4703 
4704 	case VAR_FUNC:
4705 	    if (echo_style)
4706 	    {
4707 		*tofree = NULL;
4708 		r = tv->vval.v_string;
4709 	    }
4710 	    else
4711 	    {
4712 		*tofree = string_quote(tv->vval.v_string, TRUE);
4713 		r = *tofree;
4714 	    }
4715 	    break;
4716 
4717 	case VAR_PARTIAL:
4718 	    {
4719 		partial_T   *pt = tv->vval.v_partial;
4720 		char_u	    *fname = string_quote(pt == NULL ? NULL
4721 						    : partial_name(pt), FALSE);
4722 		garray_T    ga;
4723 		int	    i;
4724 		char_u	    *tf;
4725 
4726 		ga_init2(&ga, 1, 100);
4727 		ga_concat(&ga, (char_u *)"function(");
4728 		if (fname != NULL)
4729 		{
4730 		    ga_concat(&ga, fname);
4731 		    vim_free(fname);
4732 		}
4733 		if (pt != NULL && pt->pt_argc > 0)
4734 		{
4735 		    ga_concat(&ga, (char_u *)", [");
4736 		    for (i = 0; i < pt->pt_argc; ++i)
4737 		    {
4738 			if (i > 0)
4739 			    ga_concat(&ga, (char_u *)", ");
4740 			ga_concat(&ga,
4741 			     tv2string(&pt->pt_argv[i], &tf, numbuf, copyID));
4742 			vim_free(tf);
4743 		    }
4744 		    ga_concat(&ga, (char_u *)"]");
4745 		}
4746 		if (pt != NULL && pt->pt_dict != NULL)
4747 		{
4748 		    typval_T dtv;
4749 
4750 		    ga_concat(&ga, (char_u *)", ");
4751 		    dtv.v_type = VAR_DICT;
4752 		    dtv.vval.v_dict = pt->pt_dict;
4753 		    ga_concat(&ga, tv2string(&dtv, &tf, numbuf, copyID));
4754 		    vim_free(tf);
4755 		}
4756 		ga_concat(&ga, (char_u *)")");
4757 
4758 		*tofree = ga.ga_data;
4759 		r = *tofree;
4760 		break;
4761 	    }
4762 
4763 	case VAR_BLOB:
4764 	    r = blob2string(tv->vval.v_blob, tofree, numbuf);
4765 	    break;
4766 
4767 	case VAR_LIST:
4768 	    if (tv->vval.v_list == NULL)
4769 	    {
4770 		*tofree = NULL;
4771 		r = NULL;
4772 	    }
4773 	    else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID
4774 		    && tv->vval.v_list->lv_len > 0)
4775 	    {
4776 		*tofree = NULL;
4777 		r = (char_u *)"[...]";
4778 	    }
4779 	    else
4780 	    {
4781 		int old_copyID = tv->vval.v_list->lv_copyID;
4782 
4783 		tv->vval.v_list->lv_copyID = copyID;
4784 		*tofree = list2string(tv, copyID, restore_copyID);
4785 		if (restore_copyID)
4786 		    tv->vval.v_list->lv_copyID = old_copyID;
4787 		r = *tofree;
4788 	    }
4789 	    break;
4790 
4791 	case VAR_DICT:
4792 	    if (tv->vval.v_dict == NULL)
4793 	    {
4794 		*tofree = NULL;
4795 		r = NULL;
4796 	    }
4797 	    else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID
4798 		    && tv->vval.v_dict->dv_hashtab.ht_used != 0)
4799 	    {
4800 		*tofree = NULL;
4801 		r = (char_u *)"{...}";
4802 	    }
4803 	    else
4804 	    {
4805 		int old_copyID = tv->vval.v_dict->dv_copyID;
4806 		tv->vval.v_dict->dv_copyID = copyID;
4807 		*tofree = dict2string(tv, copyID, restore_copyID);
4808 		if (restore_copyID)
4809 		    tv->vval.v_dict->dv_copyID = old_copyID;
4810 		r = *tofree;
4811 	    }
4812 	    break;
4813 
4814 	case VAR_NUMBER:
4815 	case VAR_UNKNOWN:
4816 	    *tofree = NULL;
4817 	    r = tv_get_string_buf(tv, numbuf);
4818 	    break;
4819 
4820 	case VAR_JOB:
4821 	case VAR_CHANNEL:
4822 	    *tofree = NULL;
4823 	    r = tv_get_string_buf(tv, numbuf);
4824 	    if (composite_val)
4825 	    {
4826 		*tofree = string_quote(r, FALSE);
4827 		r = *tofree;
4828 	    }
4829 	    break;
4830 
4831 	case VAR_FLOAT:
4832 #ifdef FEAT_FLOAT
4833 	    *tofree = NULL;
4834 	    vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
4835 	    r = numbuf;
4836 	    break;
4837 #endif
4838 
4839 	case VAR_SPECIAL:
4840 	    *tofree = NULL;
4841 	    r = (char_u *)get_var_special_name(tv->vval.v_number);
4842 	    break;
4843     }
4844 
4845     if (--recurse == 0)
4846 	did_echo_string_emsg = FALSE;
4847     return r;
4848 }
4849 
4850 /*
4851  * Return a string with the string representation of a variable.
4852  * If the memory is allocated "tofree" is set to it, otherwise NULL.
4853  * "numbuf" is used for a number.
4854  * Does not put quotes around strings, as ":echo" displays values.
4855  * When "copyID" is not NULL replace recursive lists and dicts with "...".
4856  * May return NULL.
4857  */
4858     char_u *
4859 echo_string(
4860     typval_T	*tv,
4861     char_u	**tofree,
4862     char_u	*numbuf,
4863     int		copyID)
4864 {
4865     return echo_string_core(tv, tofree, numbuf, copyID, TRUE, FALSE, FALSE);
4866 }
4867 
4868 /*
4869  * Return a string with the string representation of a variable.
4870  * If the memory is allocated "tofree" is set to it, otherwise NULL.
4871  * "numbuf" is used for a number.
4872  * Puts quotes around strings, so that they can be parsed back by eval().
4873  * May return NULL.
4874  */
4875     char_u *
4876 tv2string(
4877     typval_T	*tv,
4878     char_u	**tofree,
4879     char_u	*numbuf,
4880     int		copyID)
4881 {
4882     return echo_string_core(tv, tofree, numbuf, copyID, FALSE, TRUE, FALSE);
4883 }
4884 
4885 /*
4886  * Return string "str" in ' quotes, doubling ' characters.
4887  * If "str" is NULL an empty string is assumed.
4888  * If "function" is TRUE make it function('string').
4889  */
4890     char_u *
4891 string_quote(char_u *str, int function)
4892 {
4893     unsigned	len;
4894     char_u	*p, *r, *s;
4895 
4896     len = (function ? 13 : 3);
4897     if (str != NULL)
4898     {
4899 	len += (unsigned)STRLEN(str);
4900 	for (p = str; *p != NUL; MB_PTR_ADV(p))
4901 	    if (*p == '\'')
4902 		++len;
4903     }
4904     s = r = alloc(len);
4905     if (r != NULL)
4906     {
4907 	if (function)
4908 	{
4909 	    STRCPY(r, "function('");
4910 	    r += 10;
4911 	}
4912 	else
4913 	    *r++ = '\'';
4914 	if (str != NULL)
4915 	    for (p = str; *p != NUL; )
4916 	    {
4917 		if (*p == '\'')
4918 		    *r++ = '\'';
4919 		MB_COPY_CHAR(p, r);
4920 	    }
4921 	*r++ = '\'';
4922 	if (function)
4923 	    *r++ = ')';
4924 	*r++ = NUL;
4925     }
4926     return s;
4927 }
4928 
4929 #if defined(FEAT_FLOAT) || defined(PROTO)
4930 /*
4931  * Convert the string "text" to a floating point number.
4932  * This uses strtod().  setlocale(LC_NUMERIC, "C") has been used to make sure
4933  * this always uses a decimal point.
4934  * Returns the length of the text that was consumed.
4935  */
4936     int
4937 string2float(
4938     char_u	*text,
4939     float_T	*value)	    /* result stored here */
4940 {
4941     char	*s = (char *)text;
4942     float_T	f;
4943 
4944     /* MS-Windows does not deal with "inf" and "nan" properly. */
4945     if (STRNICMP(text, "inf", 3) == 0)
4946     {
4947 	*value = INFINITY;
4948 	return 3;
4949     }
4950     if (STRNICMP(text, "-inf", 3) == 0)
4951     {
4952 	*value = -INFINITY;
4953 	return 4;
4954     }
4955     if (STRNICMP(text, "nan", 3) == 0)
4956     {
4957 	*value = NAN;
4958 	return 3;
4959     }
4960     f = strtod(s, &s);
4961     *value = f;
4962     return (int)((char_u *)s - text);
4963 }
4964 #endif
4965 
4966 /*
4967  * Get the value of an environment variable.
4968  * "arg" is pointing to the '$'.  It is advanced to after the name.
4969  * If the environment variable was not set, silently assume it is empty.
4970  * Return FAIL if the name is invalid.
4971  */
4972     static int
4973 get_env_tv(char_u **arg, typval_T *rettv, int evaluate)
4974 {
4975     char_u	*string = NULL;
4976     int		len;
4977     int		cc;
4978     char_u	*name;
4979     int		mustfree = FALSE;
4980 
4981     ++*arg;
4982     name = *arg;
4983     len = get_env_len(arg);
4984     if (evaluate)
4985     {
4986 	if (len == 0)
4987 	    return FAIL; /* invalid empty name */
4988 
4989 	cc = name[len];
4990 	name[len] = NUL;
4991 	/* first try vim_getenv(), fast for normal environment vars */
4992 	string = vim_getenv(name, &mustfree);
4993 	if (string != NULL && *string != NUL)
4994 	{
4995 	    if (!mustfree)
4996 		string = vim_strsave(string);
4997 	}
4998 	else
4999 	{
5000 	    if (mustfree)
5001 		vim_free(string);
5002 
5003 	    /* next try expanding things like $VIM and ${HOME} */
5004 	    string = expand_env_save(name - 1);
5005 	    if (string != NULL && *string == '$')
5006 		VIM_CLEAR(string);
5007 	}
5008 	name[len] = cc;
5009 
5010 	rettv->v_type = VAR_STRING;
5011 	rettv->vval.v_string = string;
5012     }
5013 
5014     return OK;
5015 }
5016 
5017 /*
5018  * Translate a String variable into a position.
5019  * Returns NULL when there is an error.
5020  */
5021     pos_T *
5022 var2fpos(
5023     typval_T	*varp,
5024     int		dollar_lnum,	/* TRUE when $ is last line */
5025     int		*fnum)		/* set to fnum for '0, 'A, etc. */
5026 {
5027     char_u		*name;
5028     static pos_T	pos;
5029     pos_T		*pp;
5030 
5031     /* Argument can be [lnum, col, coladd]. */
5032     if (varp->v_type == VAR_LIST)
5033     {
5034 	list_T		*l;
5035 	int		len;
5036 	int		error = FALSE;
5037 	listitem_T	*li;
5038 
5039 	l = varp->vval.v_list;
5040 	if (l == NULL)
5041 	    return NULL;
5042 
5043 	/* Get the line number */
5044 	pos.lnum = list_find_nr(l, 0L, &error);
5045 	if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
5046 	    return NULL;	/* invalid line number */
5047 
5048 	/* Get the column number */
5049 	pos.col = list_find_nr(l, 1L, &error);
5050 	if (error)
5051 	    return NULL;
5052 	len = (long)STRLEN(ml_get(pos.lnum));
5053 
5054 	/* We accept "$" for the column number: last column. */
5055 	li = list_find(l, 1L);
5056 	if (li != NULL && li->li_tv.v_type == VAR_STRING
5057 		&& li->li_tv.vval.v_string != NULL
5058 		&& STRCMP(li->li_tv.vval.v_string, "$") == 0)
5059 	    pos.col = len + 1;
5060 
5061 	/* Accept a position up to the NUL after the line. */
5062 	if (pos.col == 0 || (int)pos.col > len + 1)
5063 	    return NULL;	/* invalid column number */
5064 	--pos.col;
5065 
5066 	/* Get the virtual offset.  Defaults to zero. */
5067 	pos.coladd = list_find_nr(l, 2L, &error);
5068 	if (error)
5069 	    pos.coladd = 0;
5070 
5071 	return &pos;
5072     }
5073 
5074     name = tv_get_string_chk(varp);
5075     if (name == NULL)
5076 	return NULL;
5077     if (name[0] == '.')				/* cursor */
5078 	return &curwin->w_cursor;
5079     if (name[0] == 'v' && name[1] == NUL)	/* Visual start */
5080     {
5081 	if (VIsual_active)
5082 	    return &VIsual;
5083 	return &curwin->w_cursor;
5084     }
5085     if (name[0] == '\'')			/* mark */
5086     {
5087 	pp = getmark_buf_fnum(curbuf, name[1], FALSE, fnum);
5088 	if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
5089 	    return NULL;
5090 	return pp;
5091     }
5092 
5093     pos.coladd = 0;
5094 
5095     if (name[0] == 'w' && dollar_lnum)
5096     {
5097 	pos.col = 0;
5098 	if (name[1] == '0')		/* "w0": first visible line */
5099 	{
5100 	    update_topline();
5101 	    /* In silent Ex mode topline is zero, but that's not a valid line
5102 	     * number; use one instead. */
5103 	    pos.lnum = curwin->w_topline > 0 ? curwin->w_topline : 1;
5104 	    return &pos;
5105 	}
5106 	else if (name[1] == '$')	/* "w$": last visible line */
5107 	{
5108 	    validate_botline();
5109 	    /* In silent Ex mode botline is zero, return zero then. */
5110 	    pos.lnum = curwin->w_botline > 0 ? curwin->w_botline - 1 : 0;
5111 	    return &pos;
5112 	}
5113     }
5114     else if (name[0] == '$')		/* last column or line */
5115     {
5116 	if (dollar_lnum)
5117 	{
5118 	    pos.lnum = curbuf->b_ml.ml_line_count;
5119 	    pos.col = 0;
5120 	}
5121 	else
5122 	{
5123 	    pos.lnum = curwin->w_cursor.lnum;
5124 	    pos.col = (colnr_T)STRLEN(ml_get_curline());
5125 	}
5126 	return &pos;
5127     }
5128     return NULL;
5129 }
5130 
5131 /*
5132  * Convert list in "arg" into a position and optional file number.
5133  * When "fnump" is NULL there is no file number, only 3 items.
5134  * Note that the column is passed on as-is, the caller may want to decrement
5135  * it to use 1 for the first column.
5136  * Return FAIL when conversion is not possible, doesn't check the position for
5137  * validity.
5138  */
5139     int
5140 list2fpos(
5141     typval_T	*arg,
5142     pos_T	*posp,
5143     int		*fnump,
5144     colnr_T	*curswantp)
5145 {
5146     list_T	*l = arg->vval.v_list;
5147     long	i = 0;
5148     long	n;
5149 
5150     /* List must be: [fnum, lnum, col, coladd, curswant], where "fnum" is only
5151      * there when "fnump" isn't NULL; "coladd" and "curswant" are optional. */
5152     if (arg->v_type != VAR_LIST
5153 	    || l == NULL
5154 	    || l->lv_len < (fnump == NULL ? 2 : 3)
5155 	    || l->lv_len > (fnump == NULL ? 4 : 5))
5156 	return FAIL;
5157 
5158     if (fnump != NULL)
5159     {
5160 	n = list_find_nr(l, i++, NULL);	/* fnum */
5161 	if (n < 0)
5162 	    return FAIL;
5163 	if (n == 0)
5164 	    n = curbuf->b_fnum;		/* current buffer */
5165 	*fnump = n;
5166     }
5167 
5168     n = list_find_nr(l, i++, NULL);	/* lnum */
5169     if (n < 0)
5170 	return FAIL;
5171     posp->lnum = n;
5172 
5173     n = list_find_nr(l, i++, NULL);	/* col */
5174     if (n < 0)
5175 	return FAIL;
5176     posp->col = n;
5177 
5178     n = list_find_nr(l, i, NULL);	/* off */
5179     if (n < 0)
5180 	posp->coladd = 0;
5181     else
5182 	posp->coladd = n;
5183 
5184     if (curswantp != NULL)
5185 	*curswantp = list_find_nr(l, i + 1, NULL);  /* curswant */
5186 
5187     return OK;
5188 }
5189 
5190 /*
5191  * Get the length of an environment variable name.
5192  * Advance "arg" to the first character after the name.
5193  * Return 0 for error.
5194  */
5195     int
5196 get_env_len(char_u **arg)
5197 {
5198     char_u	*p;
5199     int		len;
5200 
5201     for (p = *arg; vim_isIDc(*p); ++p)
5202 	;
5203     if (p == *arg)	    /* no name found */
5204 	return 0;
5205 
5206     len = (int)(p - *arg);
5207     *arg = p;
5208     return len;
5209 }
5210 
5211 /*
5212  * Get the length of the name of a function or internal variable.
5213  * "arg" is advanced to the first non-white character after the name.
5214  * Return 0 if something is wrong.
5215  */
5216     int
5217 get_id_len(char_u **arg)
5218 {
5219     char_u	*p;
5220     int		len;
5221 
5222     /* Find the end of the name. */
5223     for (p = *arg; eval_isnamec(*p); ++p)
5224     {
5225 	if (*p == ':')
5226 	{
5227 	    /* "s:" is start of "s:var", but "n:" is not and can be used in
5228 	     * slice "[n:]".  Also "xx:" is not a namespace. */
5229 	    len = (int)(p - *arg);
5230 	    if ((len == 1 && vim_strchr(NAMESPACE_CHAR, **arg) == NULL)
5231 		    || len > 1)
5232 		break;
5233 	}
5234     }
5235     if (p == *arg)	    /* no name found */
5236 	return 0;
5237 
5238     len = (int)(p - *arg);
5239     *arg = skipwhite(p);
5240 
5241     return len;
5242 }
5243 
5244 /*
5245  * Get the length of the name of a variable or function.
5246  * Only the name is recognized, does not handle ".key" or "[idx]".
5247  * "arg" is advanced to the first non-white character after the name.
5248  * Return -1 if curly braces expansion failed.
5249  * Return 0 if something else is wrong.
5250  * If the name contains 'magic' {}'s, expand them and return the
5251  * expanded name in an allocated string via 'alias' - caller must free.
5252  */
5253     int
5254 get_name_len(
5255     char_u	**arg,
5256     char_u	**alias,
5257     int		evaluate,
5258     int		verbose)
5259 {
5260     int		len;
5261     char_u	*p;
5262     char_u	*expr_start;
5263     char_u	*expr_end;
5264 
5265     *alias = NULL;  /* default to no alias */
5266 
5267     if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
5268 						  && (*arg)[2] == (int)KE_SNR)
5269     {
5270 	/* hard coded <SNR>, already translated */
5271 	*arg += 3;
5272 	return get_id_len(arg) + 3;
5273     }
5274     len = eval_fname_script(*arg);
5275     if (len > 0)
5276     {
5277 	/* literal "<SID>", "s:" or "<SNR>" */
5278 	*arg += len;
5279     }
5280 
5281     /*
5282      * Find the end of the name; check for {} construction.
5283      */
5284     p = find_name_end(*arg, &expr_start, &expr_end,
5285 					       len > 0 ? 0 : FNE_CHECK_START);
5286     if (expr_start != NULL)
5287     {
5288 	char_u	*temp_string;
5289 
5290 	if (!evaluate)
5291 	{
5292 	    len += (int)(p - *arg);
5293 	    *arg = skipwhite(p);
5294 	    return len;
5295 	}
5296 
5297 	/*
5298 	 * Include any <SID> etc in the expanded string:
5299 	 * Thus the -len here.
5300 	 */
5301 	temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
5302 	if (temp_string == NULL)
5303 	    return -1;
5304 	*alias = temp_string;
5305 	*arg = skipwhite(p);
5306 	return (int)STRLEN(temp_string);
5307     }
5308 
5309     len += get_id_len(arg);
5310     // Only give an error when there is something, otherwise it will be
5311     // reported at a higher level.
5312     if (len == 0 && verbose && **arg != NUL)
5313 	semsg(_(e_invexpr2), *arg);
5314 
5315     return len;
5316 }
5317 
5318 /*
5319  * Find the end of a variable or function name, taking care of magic braces.
5320  * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
5321  * start and end of the first magic braces item.
5322  * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
5323  * Return a pointer to just after the name.  Equal to "arg" if there is no
5324  * valid name.
5325  */
5326     char_u *
5327 find_name_end(
5328     char_u	*arg,
5329     char_u	**expr_start,
5330     char_u	**expr_end,
5331     int		flags)
5332 {
5333     int		mb_nest = 0;
5334     int		br_nest = 0;
5335     char_u	*p;
5336     int		len;
5337 
5338     if (expr_start != NULL)
5339     {
5340 	*expr_start = NULL;
5341 	*expr_end = NULL;
5342     }
5343 
5344     /* Quick check for valid starting character. */
5345     if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
5346 	return arg;
5347 
5348     for (p = arg; *p != NUL
5349 		    && (eval_isnamec(*p)
5350 			|| *p == '{'
5351 			|| ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
5352 			|| mb_nest != 0
5353 			|| br_nest != 0); MB_PTR_ADV(p))
5354     {
5355 	if (*p == '\'')
5356 	{
5357 	    /* skip over 'string' to avoid counting [ and ] inside it. */
5358 	    for (p = p + 1; *p != NUL && *p != '\''; MB_PTR_ADV(p))
5359 		;
5360 	    if (*p == NUL)
5361 		break;
5362 	}
5363 	else if (*p == '"')
5364 	{
5365 	    /* skip over "str\"ing" to avoid counting [ and ] inside it. */
5366 	    for (p = p + 1; *p != NUL && *p != '"'; MB_PTR_ADV(p))
5367 		if (*p == '\\' && p[1] != NUL)
5368 		    ++p;
5369 	    if (*p == NUL)
5370 		break;
5371 	}
5372 	else if (br_nest == 0 && mb_nest == 0 && *p == ':')
5373 	{
5374 	    /* "s:" is start of "s:var", but "n:" is not and can be used in
5375 	     * slice "[n:]".  Also "xx:" is not a namespace. But {ns}: is. */
5376 	    len = (int)(p - arg);
5377 	    if ((len == 1 && vim_strchr(NAMESPACE_CHAR, *arg) == NULL)
5378 		    || (len > 1 && p[-1] != '}'))
5379 		break;
5380 	}
5381 
5382 	if (mb_nest == 0)
5383 	{
5384 	    if (*p == '[')
5385 		++br_nest;
5386 	    else if (*p == ']')
5387 		--br_nest;
5388 	}
5389 
5390 	if (br_nest == 0)
5391 	{
5392 	    if (*p == '{')
5393 	    {
5394 		mb_nest++;
5395 		if (expr_start != NULL && *expr_start == NULL)
5396 		    *expr_start = p;
5397 	    }
5398 	    else if (*p == '}')
5399 	    {
5400 		mb_nest--;
5401 		if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
5402 		    *expr_end = p;
5403 	    }
5404 	}
5405     }
5406 
5407     return p;
5408 }
5409 
5410 /*
5411  * Expands out the 'magic' {}'s in a variable/function name.
5412  * Note that this can call itself recursively, to deal with
5413  * constructs like foo{bar}{baz}{bam}
5414  * The four pointer arguments point to "foo{expre}ss{ion}bar"
5415  *			"in_start"      ^
5416  *			"expr_start"	   ^
5417  *			"expr_end"		 ^
5418  *			"in_end"			    ^
5419  *
5420  * Returns a new allocated string, which the caller must free.
5421  * Returns NULL for failure.
5422  */
5423     static char_u *
5424 make_expanded_name(
5425     char_u	*in_start,
5426     char_u	*expr_start,
5427     char_u	*expr_end,
5428     char_u	*in_end)
5429 {
5430     char_u	c1;
5431     char_u	*retval = NULL;
5432     char_u	*temp_result;
5433     char_u	*nextcmd = NULL;
5434 
5435     if (expr_end == NULL || in_end == NULL)
5436 	return NULL;
5437     *expr_start	= NUL;
5438     *expr_end = NUL;
5439     c1 = *in_end;
5440     *in_end = NUL;
5441 
5442     temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
5443     if (temp_result != NULL && nextcmd == NULL)
5444     {
5445 	retval = alloc(STRLEN(temp_result) + (expr_start - in_start)
5446 						   + (in_end - expr_end) + 1);
5447 	if (retval != NULL)
5448 	{
5449 	    STRCPY(retval, in_start);
5450 	    STRCAT(retval, temp_result);
5451 	    STRCAT(retval, expr_end + 1);
5452 	}
5453     }
5454     vim_free(temp_result);
5455 
5456     *in_end = c1;		/* put char back for error messages */
5457     *expr_start = '{';
5458     *expr_end = '}';
5459 
5460     if (retval != NULL)
5461     {
5462 	temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
5463 	if (expr_start != NULL)
5464 	{
5465 	    /* Further expansion! */
5466 	    temp_result = make_expanded_name(retval, expr_start,
5467 						       expr_end, temp_result);
5468 	    vim_free(retval);
5469 	    retval = temp_result;
5470 	}
5471     }
5472 
5473     return retval;
5474 }
5475 
5476 /*
5477  * Return TRUE if character "c" can be used in a variable or function name.
5478  * Does not include '{' or '}' for magic braces.
5479  */
5480     int
5481 eval_isnamec(int c)
5482 {
5483     return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
5484 }
5485 
5486 /*
5487  * Return TRUE if character "c" can be used as the first character in a
5488  * variable or function name (excluding '{' and '}').
5489  */
5490     int
5491 eval_isnamec1(int c)
5492 {
5493     return (ASCII_ISALPHA(c) || c == '_');
5494 }
5495 
5496 /*
5497  * Handle:
5498  * - expr[expr], expr[expr:expr] subscript
5499  * - ".name" lookup
5500  * - function call with Funcref variable: func(expr)
5501  * - method call: var->method()
5502  *
5503  * Can all be combined in any order: dict.func(expr)[idx]['func'](expr)->len()
5504  */
5505     int
5506 handle_subscript(
5507     char_u	**arg,
5508     typval_T	*rettv,
5509     int		evaluate,	// do more than finding the end
5510     int		verbose,	// give error messages
5511     char_u	*start_leader,	// start of '!' and '-' prefixes
5512     char_u	**end_leaderp)  // end of '!' and '-' prefixes
5513 {
5514     int		ret = OK;
5515     dict_T	*selfdict = NULL;
5516 
5517     // "." is ".name" lookup when we found a dict or when evaluating and
5518     // scriptversion is at least 2, where string concatenation is "..".
5519     while (ret == OK
5520 	    && (((**arg == '['
5521 		    || (**arg == '.' && (rettv->v_type == VAR_DICT
5522 			|| (!evaluate
5523 			    && (*arg)[1] != '.'
5524 			    && current_sctx.sc_version >= 2)))
5525 		    || (**arg == '(' && (!evaluate || rettv->v_type == VAR_FUNC
5526 					    || rettv->v_type == VAR_PARTIAL)))
5527 		&& !VIM_ISWHITE(*(*arg - 1)))
5528 	    || (**arg == '-' && (*arg)[1] == '>')))
5529     {
5530 	if (**arg == '(')
5531 	{
5532 	    ret = call_func_rettv(arg, rettv, evaluate, selfdict, NULL);
5533 
5534 	    // Stop the expression evaluation when immediately aborting on
5535 	    // error, or when an interrupt occurred or an exception was thrown
5536 	    // but not caught.
5537 	    if (aborting())
5538 	    {
5539 		if (ret == OK)
5540 		    clear_tv(rettv);
5541 		ret = FAIL;
5542 	    }
5543 	    dict_unref(selfdict);
5544 	    selfdict = NULL;
5545 	}
5546 	else if (**arg == '-')
5547 	{
5548 	    // Expression "-1.0->method()" applies the leader "-" before
5549 	    // applying ->.
5550 	    if (evaluate && *end_leaderp > start_leader)
5551 		ret = eval7_leader(rettv, start_leader, end_leaderp);
5552 	    if (ret == OK)
5553 	    {
5554 		if ((*arg)[2] == '{')
5555 		    // expr->{lambda}()
5556 		    ret = eval_lambda(arg, rettv, evaluate, verbose);
5557 		else
5558 		    // expr->name()
5559 		    ret = eval_method(arg, rettv, evaluate, verbose);
5560 	    }
5561 	}
5562 	else /* **arg == '[' || **arg == '.' */
5563 	{
5564 	    dict_unref(selfdict);
5565 	    if (rettv->v_type == VAR_DICT)
5566 	    {
5567 		selfdict = rettv->vval.v_dict;
5568 		if (selfdict != NULL)
5569 		    ++selfdict->dv_refcount;
5570 	    }
5571 	    else
5572 		selfdict = NULL;
5573 	    if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
5574 	    {
5575 		clear_tv(rettv);
5576 		ret = FAIL;
5577 	    }
5578 	}
5579     }
5580 
5581     /* Turn "dict.Func" into a partial for "Func" bound to "dict".
5582      * Don't do this when "Func" is already a partial that was bound
5583      * explicitly (pt_auto is FALSE). */
5584     if (selfdict != NULL
5585 	    && (rettv->v_type == VAR_FUNC
5586 		|| (rettv->v_type == VAR_PARTIAL
5587 		    && (rettv->vval.v_partial->pt_auto
5588 			|| rettv->vval.v_partial->pt_dict == NULL))))
5589 	selfdict = make_partial(selfdict, rettv);
5590 
5591     dict_unref(selfdict);
5592     return ret;
5593 }
5594 
5595 /*
5596  * Allocate memory for a variable type-value, and make it empty (0 or NULL
5597  * value).
5598  */
5599     typval_T *
5600 alloc_tv(void)
5601 {
5602     return ALLOC_CLEAR_ONE(typval_T);
5603 }
5604 
5605 /*
5606  * Allocate memory for a variable type-value, and assign a string to it.
5607  * The string "s" must have been allocated, it is consumed.
5608  * Return NULL for out of memory, the variable otherwise.
5609  */
5610     typval_T *
5611 alloc_string_tv(char_u *s)
5612 {
5613     typval_T	*rettv;
5614 
5615     rettv = alloc_tv();
5616     if (rettv != NULL)
5617     {
5618 	rettv->v_type = VAR_STRING;
5619 	rettv->vval.v_string = s;
5620     }
5621     else
5622 	vim_free(s);
5623     return rettv;
5624 }
5625 
5626 /*
5627  * Free the memory for a variable type-value.
5628  */
5629     void
5630 free_tv(typval_T *varp)
5631 {
5632     if (varp != NULL)
5633     {
5634 	switch (varp->v_type)
5635 	{
5636 	    case VAR_FUNC:
5637 		func_unref(varp->vval.v_string);
5638 		/* FALLTHROUGH */
5639 	    case VAR_STRING:
5640 		vim_free(varp->vval.v_string);
5641 		break;
5642 	    case VAR_PARTIAL:
5643 		partial_unref(varp->vval.v_partial);
5644 		break;
5645 	    case VAR_BLOB:
5646 		blob_unref(varp->vval.v_blob);
5647 		break;
5648 	    case VAR_LIST:
5649 		list_unref(varp->vval.v_list);
5650 		break;
5651 	    case VAR_DICT:
5652 		dict_unref(varp->vval.v_dict);
5653 		break;
5654 	    case VAR_JOB:
5655 #ifdef FEAT_JOB_CHANNEL
5656 		job_unref(varp->vval.v_job);
5657 		break;
5658 #endif
5659 	    case VAR_CHANNEL:
5660 #ifdef FEAT_JOB_CHANNEL
5661 		channel_unref(varp->vval.v_channel);
5662 		break;
5663 #endif
5664 	    case VAR_NUMBER:
5665 	    case VAR_FLOAT:
5666 	    case VAR_UNKNOWN:
5667 	    case VAR_SPECIAL:
5668 		break;
5669 	}
5670 	vim_free(varp);
5671     }
5672 }
5673 
5674 /*
5675  * Free the memory for a variable value and set the value to NULL or 0.
5676  */
5677     void
5678 clear_tv(typval_T *varp)
5679 {
5680     if (varp != NULL)
5681     {
5682 	switch (varp->v_type)
5683 	{
5684 	    case VAR_FUNC:
5685 		func_unref(varp->vval.v_string);
5686 		/* FALLTHROUGH */
5687 	    case VAR_STRING:
5688 		VIM_CLEAR(varp->vval.v_string);
5689 		break;
5690 	    case VAR_PARTIAL:
5691 		partial_unref(varp->vval.v_partial);
5692 		varp->vval.v_partial = NULL;
5693 		break;
5694 	    case VAR_BLOB:
5695 		blob_unref(varp->vval.v_blob);
5696 		varp->vval.v_blob = NULL;
5697 		break;
5698 	    case VAR_LIST:
5699 		list_unref(varp->vval.v_list);
5700 		varp->vval.v_list = NULL;
5701 		break;
5702 	    case VAR_DICT:
5703 		dict_unref(varp->vval.v_dict);
5704 		varp->vval.v_dict = NULL;
5705 		break;
5706 	    case VAR_NUMBER:
5707 	    case VAR_SPECIAL:
5708 		varp->vval.v_number = 0;
5709 		break;
5710 	    case VAR_FLOAT:
5711 #ifdef FEAT_FLOAT
5712 		varp->vval.v_float = 0.0;
5713 		break;
5714 #endif
5715 	    case VAR_JOB:
5716 #ifdef FEAT_JOB_CHANNEL
5717 		job_unref(varp->vval.v_job);
5718 		varp->vval.v_job = NULL;
5719 #endif
5720 		break;
5721 	    case VAR_CHANNEL:
5722 #ifdef FEAT_JOB_CHANNEL
5723 		channel_unref(varp->vval.v_channel);
5724 		varp->vval.v_channel = NULL;
5725 #endif
5726 	    case VAR_UNKNOWN:
5727 		break;
5728 	}
5729 	varp->v_lock = 0;
5730     }
5731 }
5732 
5733 /*
5734  * Set the value of a variable to NULL without freeing items.
5735  */
5736     void
5737 init_tv(typval_T *varp)
5738 {
5739     if (varp != NULL)
5740 	vim_memset(varp, 0, sizeof(typval_T));
5741 }
5742 
5743 /*
5744  * Get the number value of a variable.
5745  * If it is a String variable, uses vim_str2nr().
5746  * For incompatible types, return 0.
5747  * tv_get_number_chk() is similar to tv_get_number(), but informs the
5748  * caller of incompatible types: it sets *denote to TRUE if "denote"
5749  * is not NULL or returns -1 otherwise.
5750  */
5751     varnumber_T
5752 tv_get_number(typval_T *varp)
5753 {
5754     int		error = FALSE;
5755 
5756     return tv_get_number_chk(varp, &error);	/* return 0L on error */
5757 }
5758 
5759     varnumber_T
5760 tv_get_number_chk(typval_T *varp, int *denote)
5761 {
5762     varnumber_T	n = 0L;
5763 
5764     switch (varp->v_type)
5765     {
5766 	case VAR_NUMBER:
5767 	    return varp->vval.v_number;
5768 	case VAR_FLOAT:
5769 #ifdef FEAT_FLOAT
5770 	    emsg(_("E805: Using a Float as a Number"));
5771 	    break;
5772 #endif
5773 	case VAR_FUNC:
5774 	case VAR_PARTIAL:
5775 	    emsg(_("E703: Using a Funcref as a Number"));
5776 	    break;
5777 	case VAR_STRING:
5778 	    if (varp->vval.v_string != NULL)
5779 		vim_str2nr(varp->vval.v_string, NULL, NULL,
5780 					    STR2NR_ALL, &n, NULL, 0, FALSE);
5781 	    return n;
5782 	case VAR_LIST:
5783 	    emsg(_("E745: Using a List as a Number"));
5784 	    break;
5785 	case VAR_DICT:
5786 	    emsg(_("E728: Using a Dictionary as a Number"));
5787 	    break;
5788 	case VAR_SPECIAL:
5789 	    return varp->vval.v_number == VVAL_TRUE ? 1 : 0;
5790 	    break;
5791 	case VAR_JOB:
5792 #ifdef FEAT_JOB_CHANNEL
5793 	    emsg(_("E910: Using a Job as a Number"));
5794 	    break;
5795 #endif
5796 	case VAR_CHANNEL:
5797 #ifdef FEAT_JOB_CHANNEL
5798 	    emsg(_("E913: Using a Channel as a Number"));
5799 	    break;
5800 #endif
5801 	case VAR_BLOB:
5802 	    emsg(_("E974: Using a Blob as a Number"));
5803 	    break;
5804 	case VAR_UNKNOWN:
5805 	    internal_error("tv_get_number(UNKNOWN)");
5806 	    break;
5807     }
5808     if (denote == NULL)		/* useful for values that must be unsigned */
5809 	n = -1;
5810     else
5811 	*denote = TRUE;
5812     return n;
5813 }
5814 
5815 #ifdef FEAT_FLOAT
5816     float_T
5817 tv_get_float(typval_T *varp)
5818 {
5819     switch (varp->v_type)
5820     {
5821 	case VAR_NUMBER:
5822 	    return (float_T)(varp->vval.v_number);
5823 	case VAR_FLOAT:
5824 	    return varp->vval.v_float;
5825 	case VAR_FUNC:
5826 	case VAR_PARTIAL:
5827 	    emsg(_("E891: Using a Funcref as a Float"));
5828 	    break;
5829 	case VAR_STRING:
5830 	    emsg(_("E892: Using a String as a Float"));
5831 	    break;
5832 	case VAR_LIST:
5833 	    emsg(_("E893: Using a List as a Float"));
5834 	    break;
5835 	case VAR_DICT:
5836 	    emsg(_("E894: Using a Dictionary as a Float"));
5837 	    break;
5838 	case VAR_SPECIAL:
5839 	    emsg(_("E907: Using a special value as a Float"));
5840 	    break;
5841 	case VAR_JOB:
5842 # ifdef FEAT_JOB_CHANNEL
5843 	    emsg(_("E911: Using a Job as a Float"));
5844 	    break;
5845 # endif
5846 	case VAR_CHANNEL:
5847 # ifdef FEAT_JOB_CHANNEL
5848 	    emsg(_("E914: Using a Channel as a Float"));
5849 	    break;
5850 # endif
5851 	case VAR_BLOB:
5852 	    emsg(_("E975: Using a Blob as a Float"));
5853 	    break;
5854 	case VAR_UNKNOWN:
5855 	    internal_error("tv_get_float(UNKNOWN)");
5856 	    break;
5857     }
5858     return 0;
5859 }
5860 #endif
5861 
5862 /*
5863  * Get the string value of a variable.
5864  * If it is a Number variable, the number is converted into a string.
5865  * tv_get_string() uses a single, static buffer.  YOU CAN ONLY USE IT ONCE!
5866  * tv_get_string_buf() uses a given buffer.
5867  * If the String variable has never been set, return an empty string.
5868  * Never returns NULL;
5869  * tv_get_string_chk() and tv_get_string_buf_chk() are similar, but return
5870  * NULL on error.
5871  */
5872     char_u *
5873 tv_get_string(typval_T *varp)
5874 {
5875     static char_u   mybuf[NUMBUFLEN];
5876 
5877     return tv_get_string_buf(varp, mybuf);
5878 }
5879 
5880     char_u *
5881 tv_get_string_buf(typval_T *varp, char_u *buf)
5882 {
5883     char_u	*res =  tv_get_string_buf_chk(varp, buf);
5884 
5885     return res != NULL ? res : (char_u *)"";
5886 }
5887 
5888 /*
5889  * Careful: This uses a single, static buffer.  YOU CAN ONLY USE IT ONCE!
5890  */
5891     char_u *
5892 tv_get_string_chk(typval_T *varp)
5893 {
5894     static char_u   mybuf[NUMBUFLEN];
5895 
5896     return tv_get_string_buf_chk(varp, mybuf);
5897 }
5898 
5899     char_u *
5900 tv_get_string_buf_chk(typval_T *varp, char_u *buf)
5901 {
5902     switch (varp->v_type)
5903     {
5904 	case VAR_NUMBER:
5905 	    vim_snprintf((char *)buf, NUMBUFLEN, "%lld",
5906 					    (long_long_T)varp->vval.v_number);
5907 	    return buf;
5908 	case VAR_FUNC:
5909 	case VAR_PARTIAL:
5910 	    emsg(_("E729: using Funcref as a String"));
5911 	    break;
5912 	case VAR_LIST:
5913 	    emsg(_("E730: using List as a String"));
5914 	    break;
5915 	case VAR_DICT:
5916 	    emsg(_("E731: using Dictionary as a String"));
5917 	    break;
5918 	case VAR_FLOAT:
5919 #ifdef FEAT_FLOAT
5920 	    emsg(_(e_float_as_string));
5921 	    break;
5922 #endif
5923 	case VAR_STRING:
5924 	    if (varp->vval.v_string != NULL)
5925 		return varp->vval.v_string;
5926 	    return (char_u *)"";
5927 	case VAR_SPECIAL:
5928 	    STRCPY(buf, get_var_special_name(varp->vval.v_number));
5929 	    return buf;
5930         case VAR_BLOB:
5931 	    emsg(_("E976: using Blob as a String"));
5932 	    break;
5933 	case VAR_JOB:
5934 #ifdef FEAT_JOB_CHANNEL
5935 	    {
5936 		job_T *job = varp->vval.v_job;
5937 		char  *status;
5938 
5939 		if (job == NULL)
5940 		    return (char_u *)"no process";
5941 		status = job->jv_status == JOB_FAILED ? "fail"
5942 				: job->jv_status >= JOB_ENDED ? "dead"
5943 				: "run";
5944 # ifdef UNIX
5945 		vim_snprintf((char *)buf, NUMBUFLEN,
5946 			    "process %ld %s", (long)job->jv_pid, status);
5947 # elif defined(MSWIN)
5948 		vim_snprintf((char *)buf, NUMBUFLEN,
5949 			    "process %ld %s",
5950 			    (long)job->jv_proc_info.dwProcessId,
5951 			    status);
5952 # else
5953 		/* fall-back */
5954 		vim_snprintf((char *)buf, NUMBUFLEN, "process ? %s", status);
5955 # endif
5956 		return buf;
5957 	    }
5958 #endif
5959 	    break;
5960 	case VAR_CHANNEL:
5961 #ifdef FEAT_JOB_CHANNEL
5962 	    {
5963 		channel_T *channel = varp->vval.v_channel;
5964 		char      *status = channel_status(channel, -1);
5965 
5966 		if (channel == NULL)
5967 		    vim_snprintf((char *)buf, NUMBUFLEN, "channel %s", status);
5968 		else
5969 		    vim_snprintf((char *)buf, NUMBUFLEN,
5970 				     "channel %d %s", channel->ch_id, status);
5971 		return buf;
5972 	    }
5973 #endif
5974 	    break;
5975 	case VAR_UNKNOWN:
5976 	    emsg(_("E908: using an invalid value as a String"));
5977 	    break;
5978     }
5979     return NULL;
5980 }
5981 
5982 /*
5983  * Turn a typeval into a string.  Similar to tv_get_string_buf() but uses
5984  * string() on Dict, List, etc.
5985  */
5986     static char_u *
5987 tv_stringify(typval_T *varp, char_u *buf)
5988 {
5989     if (varp->v_type == VAR_LIST
5990 	    || varp->v_type == VAR_DICT
5991 	    || varp->v_type == VAR_FUNC
5992 	    || varp->v_type == VAR_PARTIAL
5993 	    || varp->v_type == VAR_FLOAT)
5994     {
5995 	typval_T tmp;
5996 
5997 	f_string(varp, &tmp);
5998 	tv_get_string_buf(&tmp, buf);
5999 	clear_tv(varp);
6000 	*varp = tmp;
6001 	return tmp.vval.v_string;
6002     }
6003     return tv_get_string_buf(varp, buf);
6004 }
6005 
6006 /*
6007  * Return TRUE if typeval "tv" and its value are set to be locked (immutable).
6008  * Also give an error message, using "name" or _("name") when use_gettext is
6009  * TRUE.
6010  */
6011     static int
6012 tv_check_lock(typval_T *tv, char_u *name, int use_gettext)
6013 {
6014     int	lock = 0;
6015 
6016     switch (tv->v_type)
6017     {
6018 	case VAR_BLOB:
6019 	    if (tv->vval.v_blob != NULL)
6020 		lock = tv->vval.v_blob->bv_lock;
6021 	    break;
6022 	case VAR_LIST:
6023 	    if (tv->vval.v_list != NULL)
6024 		lock = tv->vval.v_list->lv_lock;
6025 	    break;
6026 	case VAR_DICT:
6027 	    if (tv->vval.v_dict != NULL)
6028 		lock = tv->vval.v_dict->dv_lock;
6029 	    break;
6030 	default:
6031 	    break;
6032     }
6033     return var_check_lock(tv->v_lock, name, use_gettext)
6034 		    || (lock != 0 && var_check_lock(lock, name, use_gettext));
6035 }
6036 
6037 /*
6038  * Copy the values from typval_T "from" to typval_T "to".
6039  * When needed allocates string or increases reference count.
6040  * Does not make a copy of a list, blob or dict but copies the reference!
6041  * It is OK for "from" and "to" to point to the same item.  This is used to
6042  * make a copy later.
6043  */
6044     void
6045 copy_tv(typval_T *from, typval_T *to)
6046 {
6047     to->v_type = from->v_type;
6048     to->v_lock = 0;
6049     switch (from->v_type)
6050     {
6051 	case VAR_NUMBER:
6052 	case VAR_SPECIAL:
6053 	    to->vval.v_number = from->vval.v_number;
6054 	    break;
6055 	case VAR_FLOAT:
6056 #ifdef FEAT_FLOAT
6057 	    to->vval.v_float = from->vval.v_float;
6058 	    break;
6059 #endif
6060 	case VAR_JOB:
6061 #ifdef FEAT_JOB_CHANNEL
6062 	    to->vval.v_job = from->vval.v_job;
6063 	    if (to->vval.v_job != NULL)
6064 		++to->vval.v_job->jv_refcount;
6065 	    break;
6066 #endif
6067 	case VAR_CHANNEL:
6068 #ifdef FEAT_JOB_CHANNEL
6069 	    to->vval.v_channel = from->vval.v_channel;
6070 	    if (to->vval.v_channel != NULL)
6071 		++to->vval.v_channel->ch_refcount;
6072 	    break;
6073 #endif
6074 	case VAR_STRING:
6075 	case VAR_FUNC:
6076 	    if (from->vval.v_string == NULL)
6077 		to->vval.v_string = NULL;
6078 	    else
6079 	    {
6080 		to->vval.v_string = vim_strsave(from->vval.v_string);
6081 		if (from->v_type == VAR_FUNC)
6082 		    func_ref(to->vval.v_string);
6083 	    }
6084 	    break;
6085 	case VAR_PARTIAL:
6086 	    if (from->vval.v_partial == NULL)
6087 		to->vval.v_partial = NULL;
6088 	    else
6089 	    {
6090 		to->vval.v_partial = from->vval.v_partial;
6091 		++to->vval.v_partial->pt_refcount;
6092 	    }
6093 	    break;
6094 	case VAR_BLOB:
6095 	    if (from->vval.v_blob == NULL)
6096 		to->vval.v_blob = NULL;
6097 	    else
6098 	    {
6099 		to->vval.v_blob = from->vval.v_blob;
6100 		++to->vval.v_blob->bv_refcount;
6101 	    }
6102 	    break;
6103 	case VAR_LIST:
6104 	    if (from->vval.v_list == NULL)
6105 		to->vval.v_list = NULL;
6106 	    else
6107 	    {
6108 		to->vval.v_list = from->vval.v_list;
6109 		++to->vval.v_list->lv_refcount;
6110 	    }
6111 	    break;
6112 	case VAR_DICT:
6113 	    if (from->vval.v_dict == NULL)
6114 		to->vval.v_dict = NULL;
6115 	    else
6116 	    {
6117 		to->vval.v_dict = from->vval.v_dict;
6118 		++to->vval.v_dict->dv_refcount;
6119 	    }
6120 	    break;
6121 	case VAR_UNKNOWN:
6122 	    internal_error("copy_tv(UNKNOWN)");
6123 	    break;
6124     }
6125 }
6126 
6127 /*
6128  * Make a copy of an item.
6129  * Lists and Dictionaries are also copied.  A deep copy if "deep" is set.
6130  * For deepcopy() "copyID" is zero for a full copy or the ID for when a
6131  * reference to an already copied list/dict can be used.
6132  * Returns FAIL or OK.
6133  */
6134     int
6135 item_copy(
6136     typval_T	*from,
6137     typval_T	*to,
6138     int		deep,
6139     int		copyID)
6140 {
6141     static int	recurse = 0;
6142     int		ret = OK;
6143 
6144     if (recurse >= DICT_MAXNEST)
6145     {
6146 	emsg(_("E698: variable nested too deep for making a copy"));
6147 	return FAIL;
6148     }
6149     ++recurse;
6150 
6151     switch (from->v_type)
6152     {
6153 	case VAR_NUMBER:
6154 	case VAR_FLOAT:
6155 	case VAR_STRING:
6156 	case VAR_FUNC:
6157 	case VAR_PARTIAL:
6158 	case VAR_SPECIAL:
6159 	case VAR_JOB:
6160 	case VAR_CHANNEL:
6161 	    copy_tv(from, to);
6162 	    break;
6163 	case VAR_LIST:
6164 	    to->v_type = VAR_LIST;
6165 	    to->v_lock = 0;
6166 	    if (from->vval.v_list == NULL)
6167 		to->vval.v_list = NULL;
6168 	    else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
6169 	    {
6170 		/* use the copy made earlier */
6171 		to->vval.v_list = from->vval.v_list->lv_copylist;
6172 		++to->vval.v_list->lv_refcount;
6173 	    }
6174 	    else
6175 		to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
6176 	    if (to->vval.v_list == NULL)
6177 		ret = FAIL;
6178 	    break;
6179 	case VAR_BLOB:
6180 	    ret = blob_copy(from, to);
6181 	    break;
6182 	case VAR_DICT:
6183 	    to->v_type = VAR_DICT;
6184 	    to->v_lock = 0;
6185 	    if (from->vval.v_dict == NULL)
6186 		to->vval.v_dict = NULL;
6187 	    else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
6188 	    {
6189 		/* use the copy made earlier */
6190 		to->vval.v_dict = from->vval.v_dict->dv_copydict;
6191 		++to->vval.v_dict->dv_refcount;
6192 	    }
6193 	    else
6194 		to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
6195 	    if (to->vval.v_dict == NULL)
6196 		ret = FAIL;
6197 	    break;
6198 	case VAR_UNKNOWN:
6199 	    internal_error("item_copy(UNKNOWN)");
6200 	    ret = FAIL;
6201     }
6202     --recurse;
6203     return ret;
6204 }
6205 
6206 /*
6207  * This function is used by f_input() and f_inputdialog() functions. The third
6208  * argument to f_input() specifies the type of completion to use at the
6209  * prompt. The third argument to f_inputdialog() specifies the value to return
6210  * when the user cancels the prompt.
6211  */
6212     void
6213 get_user_input(
6214     typval_T	*argvars,
6215     typval_T	*rettv,
6216     int		inputdialog,
6217     int		secret)
6218 {
6219     char_u	*prompt = tv_get_string_chk(&argvars[0]);
6220     char_u	*p = NULL;
6221     int		c;
6222     char_u	buf[NUMBUFLEN];
6223     int		cmd_silent_save = cmd_silent;
6224     char_u	*defstr = (char_u *)"";
6225     int		xp_type = EXPAND_NOTHING;
6226     char_u	*xp_arg = NULL;
6227 
6228     rettv->v_type = VAR_STRING;
6229     rettv->vval.v_string = NULL;
6230 
6231 #ifdef NO_CONSOLE_INPUT
6232     /* While starting up, there is no place to enter text. When running tests
6233      * with --not-a-term we assume feedkeys() will be used. */
6234     if (no_console_input() && !is_not_a_term())
6235 	return;
6236 #endif
6237 
6238     cmd_silent = FALSE;		/* Want to see the prompt. */
6239     if (prompt != NULL)
6240     {
6241 	/* Only the part of the message after the last NL is considered as
6242 	 * prompt for the command line */
6243 	p = vim_strrchr(prompt, '\n');
6244 	if (p == NULL)
6245 	    p = prompt;
6246 	else
6247 	{
6248 	    ++p;
6249 	    c = *p;
6250 	    *p = NUL;
6251 	    msg_start();
6252 	    msg_clr_eos();
6253 	    msg_puts_attr((char *)prompt, echo_attr);
6254 	    msg_didout = FALSE;
6255 	    msg_starthere();
6256 	    *p = c;
6257 	}
6258 	cmdline_row = msg_row;
6259 
6260 	if (argvars[1].v_type != VAR_UNKNOWN)
6261 	{
6262 	    defstr = tv_get_string_buf_chk(&argvars[1], buf);
6263 	    if (defstr != NULL)
6264 		stuffReadbuffSpec(defstr);
6265 
6266 	    if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
6267 	    {
6268 		char_u	*xp_name;
6269 		int	xp_namelen;
6270 		long	argt;
6271 
6272 		/* input() with a third argument: completion */
6273 		rettv->vval.v_string = NULL;
6274 
6275 		xp_name = tv_get_string_buf_chk(&argvars[2], buf);
6276 		if (xp_name == NULL)
6277 		    return;
6278 
6279 		xp_namelen = (int)STRLEN(xp_name);
6280 
6281 		if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
6282 							     &xp_arg) == FAIL)
6283 		    return;
6284 	    }
6285 	}
6286 
6287 	if (defstr != NULL)
6288 	{
6289 	    int save_ex_normal_busy = ex_normal_busy;
6290 
6291 	    ex_normal_busy = 0;
6292 	    rettv->vval.v_string =
6293 		getcmdline_prompt(secret ? NUL : '@', p, echo_attr,
6294 							      xp_type, xp_arg);
6295 	    ex_normal_busy = save_ex_normal_busy;
6296 	}
6297 	if (inputdialog && rettv->vval.v_string == NULL
6298 		&& argvars[1].v_type != VAR_UNKNOWN
6299 		&& argvars[2].v_type != VAR_UNKNOWN)
6300 	    rettv->vval.v_string = vim_strsave(tv_get_string_buf(
6301 							   &argvars[2], buf));
6302 
6303 	vim_free(xp_arg);
6304 
6305 	/* since the user typed this, no need to wait for return */
6306 	need_wait_return = FALSE;
6307 	msg_didout = FALSE;
6308     }
6309     cmd_silent = cmd_silent_save;
6310 }
6311 
6312 /*
6313  * ":echo expr1 ..."	print each argument separated with a space, add a
6314  *			newline at the end.
6315  * ":echon expr1 ..."	print each argument plain.
6316  */
6317     void
6318 ex_echo(exarg_T *eap)
6319 {
6320     char_u	*arg = eap->arg;
6321     typval_T	rettv;
6322     char_u	*tofree;
6323     char_u	*p;
6324     int		needclr = TRUE;
6325     int		atstart = TRUE;
6326     char_u	numbuf[NUMBUFLEN];
6327     int		did_emsg_before = did_emsg;
6328     int		called_emsg_before = called_emsg;
6329 
6330     if (eap->skip)
6331 	++emsg_skip;
6332     while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
6333     {
6334 	/* If eval1() causes an error message the text from the command may
6335 	 * still need to be cleared. E.g., "echo 22,44". */
6336 	need_clr_eos = needclr;
6337 
6338 	p = arg;
6339 	if (eval1(&arg, &rettv, !eap->skip) == FAIL)
6340 	{
6341 	    /*
6342 	     * Report the invalid expression unless the expression evaluation
6343 	     * has been cancelled due to an aborting error, an interrupt, or an
6344 	     * exception.
6345 	     */
6346 	    if (!aborting() && did_emsg == did_emsg_before
6347 					  && called_emsg == called_emsg_before)
6348 		semsg(_(e_invexpr2), p);
6349 	    need_clr_eos = FALSE;
6350 	    break;
6351 	}
6352 	need_clr_eos = FALSE;
6353 
6354 	if (!eap->skip)
6355 	{
6356 	    if (atstart)
6357 	    {
6358 		atstart = FALSE;
6359 		/* Call msg_start() after eval1(), evaluating the expression
6360 		 * may cause a message to appear. */
6361 		if (eap->cmdidx == CMD_echo)
6362 		{
6363 		    /* Mark the saved text as finishing the line, so that what
6364 		     * follows is displayed on a new line when scrolling back
6365 		     * at the more prompt. */
6366 		    msg_sb_eol();
6367 		    msg_start();
6368 		}
6369 	    }
6370 	    else if (eap->cmdidx == CMD_echo)
6371 		msg_puts_attr(" ", echo_attr);
6372 	    p = echo_string(&rettv, &tofree, numbuf, get_copyID());
6373 	    if (p != NULL)
6374 		for ( ; *p != NUL && !got_int; ++p)
6375 		{
6376 		    if (*p == '\n' || *p == '\r' || *p == TAB)
6377 		    {
6378 			if (*p != TAB && needclr)
6379 			{
6380 			    /* remove any text still there from the command */
6381 			    msg_clr_eos();
6382 			    needclr = FALSE;
6383 			}
6384 			msg_putchar_attr(*p, echo_attr);
6385 		    }
6386 		    else
6387 		    {
6388 			if (has_mbyte)
6389 			{
6390 			    int i = (*mb_ptr2len)(p);
6391 
6392 			    (void)msg_outtrans_len_attr(p, i, echo_attr);
6393 			    p += i - 1;
6394 			}
6395 			else
6396 			    (void)msg_outtrans_len_attr(p, 1, echo_attr);
6397 		    }
6398 		}
6399 	    vim_free(tofree);
6400 	}
6401 	clear_tv(&rettv);
6402 	arg = skipwhite(arg);
6403     }
6404     eap->nextcmd = check_nextcmd(arg);
6405 
6406     if (eap->skip)
6407 	--emsg_skip;
6408     else
6409     {
6410 	/* remove text that may still be there from the command */
6411 	if (needclr)
6412 	    msg_clr_eos();
6413 	if (eap->cmdidx == CMD_echo)
6414 	    msg_end();
6415     }
6416 }
6417 
6418 /*
6419  * ":echohl {name}".
6420  */
6421     void
6422 ex_echohl(exarg_T *eap)
6423 {
6424     echo_attr = syn_name2attr(eap->arg);
6425 }
6426 
6427 /*
6428  * ":execute expr1 ..."	execute the result of an expression.
6429  * ":echomsg expr1 ..."	Print a message
6430  * ":echoerr expr1 ..."	Print an error
6431  * Each gets spaces around each argument and a newline at the end for
6432  * echo commands
6433  */
6434     void
6435 ex_execute(exarg_T *eap)
6436 {
6437     char_u	*arg = eap->arg;
6438     typval_T	rettv;
6439     int		ret = OK;
6440     char_u	*p;
6441     garray_T	ga;
6442     int		len;
6443     int		save_did_emsg;
6444 
6445     ga_init2(&ga, 1, 80);
6446 
6447     if (eap->skip)
6448 	++emsg_skip;
6449     while (*arg != NUL && *arg != '|' && *arg != '\n')
6450     {
6451 	ret = eval1_emsg(&arg, &rettv, !eap->skip);
6452 	if (ret == FAIL)
6453 	    break;
6454 
6455 	if (!eap->skip)
6456 	{
6457 	    char_u   buf[NUMBUFLEN];
6458 
6459 	    if (eap->cmdidx == CMD_execute)
6460 		p = tv_get_string_buf(&rettv, buf);
6461 	    else
6462 		p = tv_stringify(&rettv, buf);
6463 	    len = (int)STRLEN(p);
6464 	    if (ga_grow(&ga, len + 2) == FAIL)
6465 	    {
6466 		clear_tv(&rettv);
6467 		ret = FAIL;
6468 		break;
6469 	    }
6470 	    if (ga.ga_len)
6471 		((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
6472 	    STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
6473 	    ga.ga_len += len;
6474 	}
6475 
6476 	clear_tv(&rettv);
6477 	arg = skipwhite(arg);
6478     }
6479 
6480     if (ret != FAIL && ga.ga_data != NULL)
6481     {
6482 	if (eap->cmdidx == CMD_echomsg || eap->cmdidx == CMD_echoerr)
6483 	{
6484 	    /* Mark the already saved text as finishing the line, so that what
6485 	     * follows is displayed on a new line when scrolling back at the
6486 	     * more prompt. */
6487 	    msg_sb_eol();
6488 	}
6489 
6490 	if (eap->cmdidx == CMD_echomsg)
6491 	{
6492 	    msg_attr(ga.ga_data, echo_attr);
6493 	    out_flush();
6494 	}
6495 	else if (eap->cmdidx == CMD_echoerr)
6496 	{
6497 	    /* We don't want to abort following commands, restore did_emsg. */
6498 	    save_did_emsg = did_emsg;
6499 	    emsg(ga.ga_data);
6500 	    if (!force_abort)
6501 		did_emsg = save_did_emsg;
6502 	}
6503 	else if (eap->cmdidx == CMD_execute)
6504 	    do_cmdline((char_u *)ga.ga_data,
6505 		       eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
6506     }
6507 
6508     ga_clear(&ga);
6509 
6510     if (eap->skip)
6511 	--emsg_skip;
6512 
6513     eap->nextcmd = check_nextcmd(arg);
6514 }
6515 
6516 /*
6517  * Skip over the name of an option: "&option", "&g:option" or "&l:option".
6518  * "arg" points to the "&" or '+' when called, to "option" when returning.
6519  * Returns NULL when no option name found.  Otherwise pointer to the char
6520  * after the option name.
6521  */
6522     char_u *
6523 find_option_end(char_u **arg, int *opt_flags)
6524 {
6525     char_u	*p = *arg;
6526 
6527     ++p;
6528     if (*p == 'g' && p[1] == ':')
6529     {
6530 	*opt_flags = OPT_GLOBAL;
6531 	p += 2;
6532     }
6533     else if (*p == 'l' && p[1] == ':')
6534     {
6535 	*opt_flags = OPT_LOCAL;
6536 	p += 2;
6537     }
6538     else
6539 	*opt_flags = 0;
6540 
6541     if (!ASCII_ISALPHA(*p))
6542 	return NULL;
6543     *arg = p;
6544 
6545     if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
6546 	p += 4;	    /* termcap option */
6547     else
6548 	while (ASCII_ISALPHA(*p))
6549 	    ++p;
6550     return p;
6551 }
6552 
6553 /*
6554  * Return the autoload script name for a function or variable name.
6555  * Returns NULL when out of memory.
6556  * Caller must make sure that "name" contains AUTOLOAD_CHAR.
6557  */
6558     char_u *
6559 autoload_name(char_u *name)
6560 {
6561     char_u	*p, *q = NULL;
6562     char_u	*scriptname;
6563 
6564     // Get the script file name: replace '#' with '/', append ".vim".
6565     scriptname = alloc(STRLEN(name) + 14);
6566     if (scriptname == NULL)
6567 	return NULL;
6568     STRCPY(scriptname, "autoload/");
6569     STRCAT(scriptname, name);
6570     for (p = scriptname + 9; (p = vim_strchr(p, AUTOLOAD_CHAR)) != NULL;
6571 								    q = p, ++p)
6572 	*p = '/';
6573     STRCPY(q, ".vim");
6574     return scriptname;
6575 }
6576 
6577 /*
6578  * If "name" has a package name try autoloading the script for it.
6579  * Return TRUE if a package was loaded.
6580  */
6581     int
6582 script_autoload(
6583     char_u	*name,
6584     int		reload)	    /* load script again when already loaded */
6585 {
6586     char_u	*p;
6587     char_u	*scriptname, *tofree;
6588     int		ret = FALSE;
6589     int		i;
6590 
6591     /* If there is no '#' after name[0] there is no package name. */
6592     p = vim_strchr(name, AUTOLOAD_CHAR);
6593     if (p == NULL || p == name)
6594 	return FALSE;
6595 
6596     tofree = scriptname = autoload_name(name);
6597     if (scriptname == NULL)
6598 	return FALSE;
6599 
6600     /* Find the name in the list of previously loaded package names.  Skip
6601      * "autoload/", it's always the same. */
6602     for (i = 0; i < ga_loaded.ga_len; ++i)
6603 	if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
6604 	    break;
6605     if (!reload && i < ga_loaded.ga_len)
6606 	ret = FALSE;	    /* was loaded already */
6607     else
6608     {
6609 	/* Remember the name if it wasn't loaded already. */
6610 	if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
6611 	{
6612 	    ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
6613 	    tofree = NULL;
6614 	}
6615 
6616 	/* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
6617 	if (source_runtime(scriptname, 0) == OK)
6618 	    ret = TRUE;
6619     }
6620 
6621     vim_free(tofree);
6622     return ret;
6623 }
6624 
6625 /*
6626  * Display script name where an item was last set.
6627  * Should only be invoked when 'verbose' is non-zero.
6628  */
6629     void
6630 last_set_msg(sctx_T script_ctx)
6631 {
6632     char_u *p;
6633 
6634     if (script_ctx.sc_sid != 0)
6635     {
6636 	p = home_replace_save(NULL, get_scriptname(script_ctx.sc_sid));
6637 	if (p != NULL)
6638 	{
6639 	    verbose_enter();
6640 	    msg_puts(_("\n\tLast set from "));
6641 	    msg_puts((char *)p);
6642 	    if (script_ctx.sc_lnum > 0)
6643 	    {
6644 		msg_puts(_(" line "));
6645 		msg_outnum((long)script_ctx.sc_lnum);
6646 	    }
6647 	    verbose_leave();
6648 	    vim_free(p);
6649 	}
6650     }
6651 }
6652 
6653 /*
6654  * Compare "typ1" and "typ2".  Put the result in "typ1".
6655  */
6656     int
6657 typval_compare(
6658     typval_T	*typ1,   /* first operand */
6659     typval_T	*typ2,   /* second operand */
6660     exptype_T	type,    /* operator */
6661     int		type_is, /* TRUE for "is" and "isnot" */
6662     int		ic)      /* ignore case */
6663 {
6664     int		i;
6665     varnumber_T	n1, n2;
6666     char_u	*s1, *s2;
6667     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
6668 
6669     if (type_is && typ1->v_type != typ2->v_type)
6670     {
6671 	/* For "is" a different type always means FALSE, for "notis"
6672 	    * it means TRUE. */
6673 	n1 = (type == TYPE_NEQUAL);
6674     }
6675     else if (typ1->v_type == VAR_BLOB || typ2->v_type == VAR_BLOB)
6676     {
6677 	if (type_is)
6678 	{
6679 	    n1 = (typ1->v_type == typ2->v_type
6680 			    && typ1->vval.v_blob == typ2->vval.v_blob);
6681 	    if (type == TYPE_NEQUAL)
6682 		n1 = !n1;
6683 	}
6684 	else if (typ1->v_type != typ2->v_type
6685 		|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
6686 	{
6687 	    if (typ1->v_type != typ2->v_type)
6688 		emsg(_("E977: Can only compare Blob with Blob"));
6689 	    else
6690 		emsg(_(e_invalblob));
6691 	    clear_tv(typ1);
6692 	    return FAIL;
6693 	}
6694 	else
6695 	{
6696 	    // Compare two Blobs for being equal or unequal.
6697 	    n1 = blob_equal(typ1->vval.v_blob, typ2->vval.v_blob);
6698 	    if (type == TYPE_NEQUAL)
6699 		n1 = !n1;
6700 	}
6701     }
6702     else if (typ1->v_type == VAR_LIST || typ2->v_type == VAR_LIST)
6703     {
6704 	if (type_is)
6705 	{
6706 	    n1 = (typ1->v_type == typ2->v_type
6707 			    && typ1->vval.v_list == typ2->vval.v_list);
6708 	    if (type == TYPE_NEQUAL)
6709 		n1 = !n1;
6710 	}
6711 	else if (typ1->v_type != typ2->v_type
6712 		|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
6713 	{
6714 	    if (typ1->v_type != typ2->v_type)
6715 		emsg(_("E691: Can only compare List with List"));
6716 	    else
6717 		emsg(_("E692: Invalid operation for List"));
6718 	    clear_tv(typ1);
6719 	    return FAIL;
6720 	}
6721 	else
6722 	{
6723 	    /* Compare two Lists for being equal or unequal. */
6724 	    n1 = list_equal(typ1->vval.v_list, typ2->vval.v_list,
6725 							    ic, FALSE);
6726 	    if (type == TYPE_NEQUAL)
6727 		n1 = !n1;
6728 	}
6729     }
6730 
6731     else if (typ1->v_type == VAR_DICT || typ2->v_type == VAR_DICT)
6732     {
6733 	if (type_is)
6734 	{
6735 	    n1 = (typ1->v_type == typ2->v_type
6736 			    && typ1->vval.v_dict == typ2->vval.v_dict);
6737 	    if (type == TYPE_NEQUAL)
6738 		n1 = !n1;
6739 	}
6740 	else if (typ1->v_type != typ2->v_type
6741 		|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
6742 	{
6743 	    if (typ1->v_type != typ2->v_type)
6744 		emsg(_("E735: Can only compare Dictionary with Dictionary"));
6745 	    else
6746 		emsg(_("E736: Invalid operation for Dictionary"));
6747 	    clear_tv(typ1);
6748 	    return FAIL;
6749 	}
6750 	else
6751 	{
6752 	    /* Compare two Dictionaries for being equal or unequal. */
6753 	    n1 = dict_equal(typ1->vval.v_dict, typ2->vval.v_dict,
6754 							    ic, FALSE);
6755 	    if (type == TYPE_NEQUAL)
6756 		n1 = !n1;
6757 	}
6758     }
6759 
6760     else if (typ1->v_type == VAR_FUNC || typ2->v_type == VAR_FUNC
6761 	|| typ1->v_type == VAR_PARTIAL || typ2->v_type == VAR_PARTIAL)
6762     {
6763 	if (type != TYPE_EQUAL && type != TYPE_NEQUAL)
6764 	{
6765 	    emsg(_("E694: Invalid operation for Funcrefs"));
6766 	    clear_tv(typ1);
6767 	    return FAIL;
6768 	}
6769 	if ((typ1->v_type == VAR_PARTIAL
6770 					&& typ1->vval.v_partial == NULL)
6771 		|| (typ2->v_type == VAR_PARTIAL
6772 					&& typ2->vval.v_partial == NULL))
6773 	    /* when a partial is NULL assume not equal */
6774 	    n1 = FALSE;
6775 	else if (type_is)
6776 	{
6777 	    if (typ1->v_type == VAR_FUNC && typ2->v_type == VAR_FUNC)
6778 		/* strings are considered the same if their value is
6779 		    * the same */
6780 		n1 = tv_equal(typ1, typ2, ic, FALSE);
6781 	    else if (typ1->v_type == VAR_PARTIAL
6782 					&& typ2->v_type == VAR_PARTIAL)
6783 		n1 = (typ1->vval.v_partial == typ2->vval.v_partial);
6784 	    else
6785 		n1 = FALSE;
6786 	}
6787 	else
6788 	    n1 = tv_equal(typ1, typ2, ic, FALSE);
6789 	if (type == TYPE_NEQUAL)
6790 	    n1 = !n1;
6791     }
6792 
6793 #ifdef FEAT_FLOAT
6794     /*
6795 	* If one of the two variables is a float, compare as a float.
6796 	* When using "=~" or "!~", always compare as string.
6797 	*/
6798     else if ((typ1->v_type == VAR_FLOAT || typ2->v_type == VAR_FLOAT)
6799 	    && type != TYPE_MATCH && type != TYPE_NOMATCH)
6800     {
6801 	float_T f1, f2;
6802 
6803 	f1 = tv_get_float(typ1);
6804 	f2 = tv_get_float(typ2);
6805 	n1 = FALSE;
6806 	switch (type)
6807 	{
6808 	    case TYPE_EQUAL:    n1 = (f1 == f2); break;
6809 	    case TYPE_NEQUAL:   n1 = (f1 != f2); break;
6810 	    case TYPE_GREATER:  n1 = (f1 > f2); break;
6811 	    case TYPE_GEQUAL:   n1 = (f1 >= f2); break;
6812 	    case TYPE_SMALLER:  n1 = (f1 < f2); break;
6813 	    case TYPE_SEQUAL:   n1 = (f1 <= f2); break;
6814 	    case TYPE_UNKNOWN:
6815 	    case TYPE_MATCH:
6816 	    case TYPE_NOMATCH:  break;  /* avoid gcc warning */
6817 	}
6818     }
6819 #endif
6820 
6821     /*
6822 	* If one of the two variables is a number, compare as a number.
6823 	* When using "=~" or "!~", always compare as string.
6824 	*/
6825     else if ((typ1->v_type == VAR_NUMBER || typ2->v_type == VAR_NUMBER)
6826 	    && type != TYPE_MATCH && type != TYPE_NOMATCH)
6827     {
6828 	n1 = tv_get_number(typ1);
6829 	n2 = tv_get_number(typ2);
6830 	switch (type)
6831 	{
6832 	    case TYPE_EQUAL:    n1 = (n1 == n2); break;
6833 	    case TYPE_NEQUAL:   n1 = (n1 != n2); break;
6834 	    case TYPE_GREATER:  n1 = (n1 > n2); break;
6835 	    case TYPE_GEQUAL:   n1 = (n1 >= n2); break;
6836 	    case TYPE_SMALLER:  n1 = (n1 < n2); break;
6837 	    case TYPE_SEQUAL:   n1 = (n1 <= n2); break;
6838 	    case TYPE_UNKNOWN:
6839 	    case TYPE_MATCH:
6840 	    case TYPE_NOMATCH:  break;  /* avoid gcc warning */
6841 	}
6842     }
6843     else
6844     {
6845 	s1 = tv_get_string_buf(typ1, buf1);
6846 	s2 = tv_get_string_buf(typ2, buf2);
6847 	if (type != TYPE_MATCH && type != TYPE_NOMATCH)
6848 	    i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
6849 	else
6850 	    i = 0;
6851 	n1 = FALSE;
6852 	switch (type)
6853 	{
6854 	    case TYPE_EQUAL:    n1 = (i == 0); break;
6855 	    case TYPE_NEQUAL:   n1 = (i != 0); break;
6856 	    case TYPE_GREATER:  n1 = (i > 0); break;
6857 	    case TYPE_GEQUAL:   n1 = (i >= 0); break;
6858 	    case TYPE_SMALLER:  n1 = (i < 0); break;
6859 	    case TYPE_SEQUAL:   n1 = (i <= 0); break;
6860 
6861 	    case TYPE_MATCH:
6862 	    case TYPE_NOMATCH:
6863 		    n1 = pattern_match(s2, s1, ic);
6864 		    if (type == TYPE_NOMATCH)
6865 			n1 = !n1;
6866 		    break;
6867 
6868 	    case TYPE_UNKNOWN:  break;  /* avoid gcc warning */
6869 	}
6870     }
6871     clear_tv(typ1);
6872     typ1->v_type = VAR_NUMBER;
6873     typ1->vval.v_number = n1;
6874 
6875     return OK;
6876 }
6877 
6878     char_u *
6879 typval_tostring(typval_T *arg)
6880 {
6881     char_u	*tofree;
6882     char_u	numbuf[NUMBUFLEN];
6883     char_u	*ret = NULL;
6884 
6885     if (arg == NULL)
6886 	return vim_strsave((char_u *)"(does not exist)");
6887     ret = tv2string(arg, &tofree, numbuf, 0);
6888     /* Make a copy if we have a value but it's not in allocated memory. */
6889     if (ret != NULL && tofree == NULL)
6890 	ret = vim_strsave(ret);
6891     return ret;
6892 }
6893 
6894 #endif /* FEAT_EVAL */
6895 
6896 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
6897 
6898 #ifdef MSWIN
6899 /*
6900  * Functions for ":8" filename modifier: get 8.3 version of a filename.
6901  */
6902 
6903 /*
6904  * Get the short path (8.3) for the filename in "fnamep".
6905  * Only works for a valid file name.
6906  * When the path gets longer "fnamep" is changed and the allocated buffer
6907  * is put in "bufp".
6908  * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
6909  * Returns OK on success, FAIL on failure.
6910  */
6911     static int
6912 get_short_pathname(char_u **fnamep, char_u **bufp, int *fnamelen)
6913 {
6914     int		l, len;
6915     char_u	*newbuf;
6916 
6917     len = *fnamelen;
6918     l = GetShortPathName((LPSTR)*fnamep, (LPSTR)*fnamep, len);
6919     if (l > len - 1)
6920     {
6921 	/* If that doesn't work (not enough space), then save the string
6922 	 * and try again with a new buffer big enough. */
6923 	newbuf = vim_strnsave(*fnamep, l);
6924 	if (newbuf == NULL)
6925 	    return FAIL;
6926 
6927 	vim_free(*bufp);
6928 	*fnamep = *bufp = newbuf;
6929 
6930 	/* Really should always succeed, as the buffer is big enough. */
6931 	l = GetShortPathName((LPSTR)*fnamep, (LPSTR)*fnamep, l+1);
6932     }
6933 
6934     *fnamelen = l;
6935     return OK;
6936 }
6937 
6938 /*
6939  * Get the short path (8.3) for the filename in "fname". The converted
6940  * path is returned in "bufp".
6941  *
6942  * Some of the directories specified in "fname" may not exist. This function
6943  * will shorten the existing directories at the beginning of the path and then
6944  * append the remaining non-existing path.
6945  *
6946  * fname - Pointer to the filename to shorten.  On return, contains the
6947  *	   pointer to the shortened pathname
6948  * bufp -  Pointer to an allocated buffer for the filename.
6949  * fnamelen - Length of the filename pointed to by fname
6950  *
6951  * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
6952  */
6953     static int
6954 shortpath_for_invalid_fname(
6955     char_u	**fname,
6956     char_u	**bufp,
6957     int		*fnamelen)
6958 {
6959     char_u	*short_fname, *save_fname, *pbuf_unused;
6960     char_u	*endp, *save_endp;
6961     char_u	ch;
6962     int		old_len, len;
6963     int		new_len, sfx_len;
6964     int		retval = OK;
6965 
6966     /* Make a copy */
6967     old_len = *fnamelen;
6968     save_fname = vim_strnsave(*fname, old_len);
6969     pbuf_unused = NULL;
6970     short_fname = NULL;
6971 
6972     endp = save_fname + old_len - 1; /* Find the end of the copy */
6973     save_endp = endp;
6974 
6975     /*
6976      * Try shortening the supplied path till it succeeds by removing one
6977      * directory at a time from the tail of the path.
6978      */
6979     len = 0;
6980     for (;;)
6981     {
6982 	/* go back one path-separator */
6983 	while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
6984 	    --endp;
6985 	if (endp <= save_fname)
6986 	    break;		/* processed the complete path */
6987 
6988 	/*
6989 	 * Replace the path separator with a NUL and try to shorten the
6990 	 * resulting path.
6991 	 */
6992 	ch = *endp;
6993 	*endp = 0;
6994 	short_fname = save_fname;
6995 	len = (int)STRLEN(short_fname) + 1;
6996 	if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
6997 	{
6998 	    retval = FAIL;
6999 	    goto theend;
7000 	}
7001 	*endp = ch;	/* preserve the string */
7002 
7003 	if (len > 0)
7004 	    break;	/* successfully shortened the path */
7005 
7006 	/* failed to shorten the path. Skip the path separator */
7007 	--endp;
7008     }
7009 
7010     if (len > 0)
7011     {
7012 	/*
7013 	 * Succeeded in shortening the path. Now concatenate the shortened
7014 	 * path with the remaining path at the tail.
7015 	 */
7016 
7017 	/* Compute the length of the new path. */
7018 	sfx_len = (int)(save_endp - endp) + 1;
7019 	new_len = len + sfx_len;
7020 
7021 	*fnamelen = new_len;
7022 	vim_free(*bufp);
7023 	if (new_len > old_len)
7024 	{
7025 	    /* There is not enough space in the currently allocated string,
7026 	     * copy it to a buffer big enough. */
7027 	    *fname = *bufp = vim_strnsave(short_fname, new_len);
7028 	    if (*fname == NULL)
7029 	    {
7030 		retval = FAIL;
7031 		goto theend;
7032 	    }
7033 	}
7034 	else
7035 	{
7036 	    /* Transfer short_fname to the main buffer (it's big enough),
7037 	     * unless get_short_pathname() did its work in-place. */
7038 	    *fname = *bufp = save_fname;
7039 	    if (short_fname != save_fname)
7040 		vim_strncpy(save_fname, short_fname, len);
7041 	    save_fname = NULL;
7042 	}
7043 
7044 	/* concat the not-shortened part of the path */
7045 	vim_strncpy(*fname + len, endp, sfx_len);
7046 	(*fname)[new_len] = NUL;
7047     }
7048 
7049 theend:
7050     vim_free(pbuf_unused);
7051     vim_free(save_fname);
7052 
7053     return retval;
7054 }
7055 
7056 /*
7057  * Get a pathname for a partial path.
7058  * Returns OK for success, FAIL for failure.
7059  */
7060     static int
7061 shortpath_for_partial(
7062     char_u	**fnamep,
7063     char_u	**bufp,
7064     int		*fnamelen)
7065 {
7066     int		sepcount, len, tflen;
7067     char_u	*p;
7068     char_u	*pbuf, *tfname;
7069     int		hasTilde;
7070 
7071     /* Count up the path separators from the RHS.. so we know which part
7072      * of the path to return. */
7073     sepcount = 0;
7074     for (p = *fnamep; p < *fnamep + *fnamelen; MB_PTR_ADV(p))
7075 	if (vim_ispathsep(*p))
7076 	    ++sepcount;
7077 
7078     /* Need full path first (use expand_env() to remove a "~/") */
7079     hasTilde = (**fnamep == '~');
7080     if (hasTilde)
7081 	pbuf = tfname = expand_env_save(*fnamep);
7082     else
7083 	pbuf = tfname = FullName_save(*fnamep, FALSE);
7084 
7085     len = tflen = (int)STRLEN(tfname);
7086 
7087     if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
7088 	return FAIL;
7089 
7090     if (len == 0)
7091     {
7092 	/* Don't have a valid filename, so shorten the rest of the
7093 	 * path if we can. This CAN give us invalid 8.3 filenames, but
7094 	 * there's not a lot of point in guessing what it might be.
7095 	 */
7096 	len = tflen;
7097 	if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
7098 	    return FAIL;
7099     }
7100 
7101     /* Count the paths backward to find the beginning of the desired string. */
7102     for (p = tfname + len - 1; p >= tfname; --p)
7103     {
7104 	if (has_mbyte)
7105 	    p -= mb_head_off(tfname, p);
7106 	if (vim_ispathsep(*p))
7107 	{
7108 	    if (sepcount == 0 || (hasTilde && sepcount == 1))
7109 		break;
7110 	    else
7111 		sepcount --;
7112 	}
7113     }
7114     if (hasTilde)
7115     {
7116 	--p;
7117 	if (p >= tfname)
7118 	    *p = '~';
7119 	else
7120 	    return FAIL;
7121     }
7122     else
7123 	++p;
7124 
7125     /* Copy in the string - p indexes into tfname - allocated at pbuf */
7126     vim_free(*bufp);
7127     *fnamelen = (int)STRLEN(p);
7128     *bufp = pbuf;
7129     *fnamep = p;
7130 
7131     return OK;
7132 }
7133 #endif // MSWIN
7134 
7135 /*
7136  * Adjust a filename, according to a string of modifiers.
7137  * *fnamep must be NUL terminated when called.  When returning, the length is
7138  * determined by *fnamelen.
7139  * Returns VALID_ flags or -1 for failure.
7140  * When there is an error, *fnamep is set to NULL.
7141  */
7142     int
7143 modify_fname(
7144     char_u	*src,		// string with modifiers
7145     int		tilde_file,	// "~" is a file name, not $HOME
7146     int		*usedlen,	// characters after src that are used
7147     char_u	**fnamep,	// file name so far
7148     char_u	**bufp,		// buffer for allocated file name or NULL
7149     int		*fnamelen)	// length of fnamep
7150 {
7151     int		valid = 0;
7152     char_u	*tail;
7153     char_u	*s, *p, *pbuf;
7154     char_u	dirname[MAXPATHL];
7155     int		c;
7156     int		has_fullname = 0;
7157 #ifdef MSWIN
7158     char_u	*fname_start = *fnamep;
7159     int		has_shortname = 0;
7160 #endif
7161 
7162 repeat:
7163     /* ":p" - full path/file_name */
7164     if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
7165     {
7166 	has_fullname = 1;
7167 
7168 	valid |= VALID_PATH;
7169 	*usedlen += 2;
7170 
7171 	/* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
7172 	if ((*fnamep)[0] == '~'
7173 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
7174 		&& ((*fnamep)[1] == '/'
7175 # ifdef BACKSLASH_IN_FILENAME
7176 		    || (*fnamep)[1] == '\\'
7177 # endif
7178 		    || (*fnamep)[1] == NUL)
7179 #endif
7180 		&& !(tilde_file && (*fnamep)[1] == NUL)
7181 	   )
7182 	{
7183 	    *fnamep = expand_env_save(*fnamep);
7184 	    vim_free(*bufp);	/* free any allocated file name */
7185 	    *bufp = *fnamep;
7186 	    if (*fnamep == NULL)
7187 		return -1;
7188 	}
7189 
7190 	/* When "/." or "/.." is used: force expansion to get rid of it. */
7191 	for (p = *fnamep; *p != NUL; MB_PTR_ADV(p))
7192 	{
7193 	    if (vim_ispathsep(*p)
7194 		    && p[1] == '.'
7195 		    && (p[2] == NUL
7196 			|| vim_ispathsep(p[2])
7197 			|| (p[2] == '.'
7198 			    && (p[3] == NUL || vim_ispathsep(p[3])))))
7199 		break;
7200 	}
7201 
7202 	/* FullName_save() is slow, don't use it when not needed. */
7203 	if (*p != NUL || !vim_isAbsName(*fnamep))
7204 	{
7205 	    *fnamep = FullName_save(*fnamep, *p != NUL);
7206 	    vim_free(*bufp);	/* free any allocated file name */
7207 	    *bufp = *fnamep;
7208 	    if (*fnamep == NULL)
7209 		return -1;
7210 	}
7211 
7212 #ifdef MSWIN
7213 # if _WIN32_WINNT >= 0x0500
7214 	if (vim_strchr(*fnamep, '~') != NULL)
7215 	{
7216 	    // Expand 8.3 filename to full path.  Needed to make sure the same
7217 	    // file does not have two different names.
7218 	    // Note: problem does not occur if _WIN32_WINNT < 0x0500.
7219 	    WCHAR *wfname = enc_to_utf16(*fnamep, NULL);
7220 	    WCHAR buf[_MAX_PATH];
7221 
7222 	    if (wfname != NULL)
7223 	    {
7224 		if (GetLongPathNameW(wfname, buf, _MAX_PATH))
7225 		{
7226 		    char_u *p = utf16_to_enc(buf, NULL);
7227 
7228 		    if (p != NULL)
7229 		    {
7230 			vim_free(*bufp);    // free any allocated file name
7231 			*bufp = *fnamep = p;
7232 		    }
7233 		}
7234 		vim_free(wfname);
7235 	    }
7236 	}
7237 # endif
7238 #endif
7239 	/* Append a path separator to a directory. */
7240 	if (mch_isdir(*fnamep))
7241 	{
7242 	    /* Make room for one or two extra characters. */
7243 	    *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
7244 	    vim_free(*bufp);	/* free any allocated file name */
7245 	    *bufp = *fnamep;
7246 	    if (*fnamep == NULL)
7247 		return -1;
7248 	    add_pathsep(*fnamep);
7249 	}
7250     }
7251 
7252     /* ":." - path relative to the current directory */
7253     /* ":~" - path relative to the home directory */
7254     /* ":8" - shortname path - postponed till after */
7255     while (src[*usedlen] == ':'
7256 		  && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
7257     {
7258 	*usedlen += 2;
7259 	if (c == '8')
7260 	{
7261 #ifdef MSWIN
7262 	    has_shortname = 1; /* Postpone this. */
7263 #endif
7264 	    continue;
7265 	}
7266 	pbuf = NULL;
7267 	/* Need full path first (use expand_env() to remove a "~/") */
7268 	if (!has_fullname)
7269 	{
7270 	    if (c == '.' && **fnamep == '~')
7271 		p = pbuf = expand_env_save(*fnamep);
7272 	    else
7273 		p = pbuf = FullName_save(*fnamep, FALSE);
7274 	}
7275 	else
7276 	    p = *fnamep;
7277 
7278 	has_fullname = 0;
7279 
7280 	if (p != NULL)
7281 	{
7282 	    if (c == '.')
7283 	    {
7284 		mch_dirname(dirname, MAXPATHL);
7285 		s = shorten_fname(p, dirname);
7286 		if (s != NULL)
7287 		{
7288 		    *fnamep = s;
7289 		    if (pbuf != NULL)
7290 		    {
7291 			vim_free(*bufp);   /* free any allocated file name */
7292 			*bufp = pbuf;
7293 			pbuf = NULL;
7294 		    }
7295 		}
7296 	    }
7297 	    else
7298 	    {
7299 		home_replace(NULL, p, dirname, MAXPATHL, TRUE);
7300 		/* Only replace it when it starts with '~' */
7301 		if (*dirname == '~')
7302 		{
7303 		    s = vim_strsave(dirname);
7304 		    if (s != NULL)
7305 		    {
7306 			*fnamep = s;
7307 			vim_free(*bufp);
7308 			*bufp = s;
7309 		    }
7310 		}
7311 	    }
7312 	    vim_free(pbuf);
7313 	}
7314     }
7315 
7316     tail = gettail(*fnamep);
7317     *fnamelen = (int)STRLEN(*fnamep);
7318 
7319     /* ":h" - head, remove "/file_name", can be repeated  */
7320     /* Don't remove the first "/" or "c:\" */
7321     while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
7322     {
7323 	valid |= VALID_HEAD;
7324 	*usedlen += 2;
7325 	s = get_past_head(*fnamep);
7326 	while (tail > s && after_pathsep(s, tail))
7327 	    MB_PTR_BACK(*fnamep, tail);
7328 	*fnamelen = (int)(tail - *fnamep);
7329 #ifdef VMS
7330 	if (*fnamelen > 0)
7331 	    *fnamelen += 1; /* the path separator is part of the path */
7332 #endif
7333 	if (*fnamelen == 0)
7334 	{
7335 	    /* Result is empty.  Turn it into "." to make ":cd %:h" work. */
7336 	    p = vim_strsave((char_u *)".");
7337 	    if (p == NULL)
7338 		return -1;
7339 	    vim_free(*bufp);
7340 	    *bufp = *fnamep = tail = p;
7341 	    *fnamelen = 1;
7342 	}
7343 	else
7344 	{
7345 	    while (tail > s && !after_pathsep(s, tail))
7346 		MB_PTR_BACK(*fnamep, tail);
7347 	}
7348     }
7349 
7350     /* ":8" - shortname  */
7351     if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
7352     {
7353 	*usedlen += 2;
7354 #ifdef MSWIN
7355 	has_shortname = 1;
7356 #endif
7357     }
7358 
7359 #ifdef MSWIN
7360     /*
7361      * Handle ":8" after we have done 'heads' and before we do 'tails'.
7362      */
7363     if (has_shortname)
7364     {
7365 	/* Copy the string if it is shortened by :h and when it wasn't copied
7366 	 * yet, because we are going to change it in place.  Avoids changing
7367 	 * the buffer name for "%:8". */
7368 	if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start)
7369 	{
7370 	    p = vim_strnsave(*fnamep, *fnamelen);
7371 	    if (p == NULL)
7372 		return -1;
7373 	    vim_free(*bufp);
7374 	    *bufp = *fnamep = p;
7375 	}
7376 
7377 	/* Split into two implementations - makes it easier.  First is where
7378 	 * there isn't a full name already, second is where there is. */
7379 	if (!has_fullname && !vim_isAbsName(*fnamep))
7380 	{
7381 	    if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
7382 		return -1;
7383 	}
7384 	else
7385 	{
7386 	    int		l = *fnamelen;
7387 
7388 	    /* Simple case, already have the full-name.
7389 	     * Nearly always shorter, so try first time. */
7390 	    if (get_short_pathname(fnamep, bufp, &l) == FAIL)
7391 		return -1;
7392 
7393 	    if (l == 0)
7394 	    {
7395 		/* Couldn't find the filename, search the paths. */
7396 		l = *fnamelen;
7397 		if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
7398 		    return -1;
7399 	    }
7400 	    *fnamelen = l;
7401 	}
7402     }
7403 #endif // MSWIN
7404 
7405     /* ":t" - tail, just the basename */
7406     if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
7407     {
7408 	*usedlen += 2;
7409 	*fnamelen -= (int)(tail - *fnamep);
7410 	*fnamep = tail;
7411     }
7412 
7413     /* ":e" - extension, can be repeated */
7414     /* ":r" - root, without extension, can be repeated */
7415     while (src[*usedlen] == ':'
7416 	    && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
7417     {
7418 	/* find a '.' in the tail:
7419 	 * - for second :e: before the current fname
7420 	 * - otherwise: The last '.'
7421 	 */
7422 	if (src[*usedlen + 1] == 'e' && *fnamep > tail)
7423 	    s = *fnamep - 2;
7424 	else
7425 	    s = *fnamep + *fnamelen - 1;
7426 	for ( ; s > tail; --s)
7427 	    if (s[0] == '.')
7428 		break;
7429 	if (src[*usedlen + 1] == 'e')		/* :e */
7430 	{
7431 	    if (s > tail)
7432 	    {
7433 		*fnamelen += (int)(*fnamep - (s + 1));
7434 		*fnamep = s + 1;
7435 #ifdef VMS
7436 		/* cut version from the extension */
7437 		s = *fnamep + *fnamelen - 1;
7438 		for ( ; s > *fnamep; --s)
7439 		    if (s[0] == ';')
7440 			break;
7441 		if (s > *fnamep)
7442 		    *fnamelen = s - *fnamep;
7443 #endif
7444 	    }
7445 	    else if (*fnamep <= tail)
7446 		*fnamelen = 0;
7447 	}
7448 	else				/* :r */
7449 	{
7450 	    if (s > tail)	/* remove one extension */
7451 		*fnamelen = (int)(s - *fnamep);
7452 	}
7453 	*usedlen += 2;
7454     }
7455 
7456     /* ":s?pat?foo?" - substitute */
7457     /* ":gs?pat?foo?" - global substitute */
7458     if (src[*usedlen] == ':'
7459 	    && (src[*usedlen + 1] == 's'
7460 		|| (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
7461     {
7462 	char_u	    *str;
7463 	char_u	    *pat;
7464 	char_u	    *sub;
7465 	int	    sep;
7466 	char_u	    *flags;
7467 	int	    didit = FALSE;
7468 
7469 	flags = (char_u *)"";
7470 	s = src + *usedlen + 2;
7471 	if (src[*usedlen + 1] == 'g')
7472 	{
7473 	    flags = (char_u *)"g";
7474 	    ++s;
7475 	}
7476 
7477 	sep = *s++;
7478 	if (sep)
7479 	{
7480 	    /* find end of pattern */
7481 	    p = vim_strchr(s, sep);
7482 	    if (p != NULL)
7483 	    {
7484 		pat = vim_strnsave(s, (int)(p - s));
7485 		if (pat != NULL)
7486 		{
7487 		    s = p + 1;
7488 		    /* find end of substitution */
7489 		    p = vim_strchr(s, sep);
7490 		    if (p != NULL)
7491 		    {
7492 			sub = vim_strnsave(s, (int)(p - s));
7493 			str = vim_strnsave(*fnamep, *fnamelen);
7494 			if (sub != NULL && str != NULL)
7495 			{
7496 			    *usedlen = (int)(p + 1 - src);
7497 			    s = do_string_sub(str, pat, sub, NULL, flags);
7498 			    if (s != NULL)
7499 			    {
7500 				*fnamep = s;
7501 				*fnamelen = (int)STRLEN(s);
7502 				vim_free(*bufp);
7503 				*bufp = s;
7504 				didit = TRUE;
7505 			    }
7506 			}
7507 			vim_free(sub);
7508 			vim_free(str);
7509 		    }
7510 		    vim_free(pat);
7511 		}
7512 	    }
7513 	    /* after using ":s", repeat all the modifiers */
7514 	    if (didit)
7515 		goto repeat;
7516 	}
7517     }
7518 
7519     if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S')
7520     {
7521 	/* vim_strsave_shellescape() needs a NUL terminated string. */
7522 	c = (*fnamep)[*fnamelen];
7523 	if (c != NUL)
7524 	    (*fnamep)[*fnamelen] = NUL;
7525 	p = vim_strsave_shellescape(*fnamep, FALSE, FALSE);
7526 	if (c != NUL)
7527 	    (*fnamep)[*fnamelen] = c;
7528 	if (p == NULL)
7529 	    return -1;
7530 	vim_free(*bufp);
7531 	*bufp = *fnamep = p;
7532 	*fnamelen = (int)STRLEN(p);
7533 	*usedlen += 2;
7534     }
7535 
7536     return valid;
7537 }
7538 
7539 /*
7540  * Perform a substitution on "str" with pattern "pat" and substitute "sub".
7541  * When "sub" is NULL "expr" is used, must be a VAR_FUNC or VAR_PARTIAL.
7542  * "flags" can be "g" to do a global substitute.
7543  * Returns an allocated string, NULL for error.
7544  */
7545     char_u *
7546 do_string_sub(
7547     char_u	*str,
7548     char_u	*pat,
7549     char_u	*sub,
7550     typval_T	*expr,
7551     char_u	*flags)
7552 {
7553     int		sublen;
7554     regmatch_T	regmatch;
7555     int		i;
7556     int		do_all;
7557     char_u	*tail;
7558     char_u	*end;
7559     garray_T	ga;
7560     char_u	*ret;
7561     char_u	*save_cpo;
7562     char_u	*zero_width = NULL;
7563 
7564     /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
7565     save_cpo = p_cpo;
7566     p_cpo = empty_option;
7567 
7568     ga_init2(&ga, 1, 200);
7569 
7570     do_all = (flags[0] == 'g');
7571 
7572     regmatch.rm_ic = p_ic;
7573     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
7574     if (regmatch.regprog != NULL)
7575     {
7576 	tail = str;
7577 	end = str + STRLEN(str);
7578 	while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
7579 	{
7580 	    /* Skip empty match except for first match. */
7581 	    if (regmatch.startp[0] == regmatch.endp[0])
7582 	    {
7583 		if (zero_width == regmatch.startp[0])
7584 		{
7585 		    /* avoid getting stuck on a match with an empty string */
7586 		    i = MB_PTR2LEN(tail);
7587 		    mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail,
7588 								   (size_t)i);
7589 		    ga.ga_len += i;
7590 		    tail += i;
7591 		    continue;
7592 		}
7593 		zero_width = regmatch.startp[0];
7594 	    }
7595 
7596 	    /*
7597 	     * Get some space for a temporary buffer to do the substitution
7598 	     * into.  It will contain:
7599 	     * - The text up to where the match is.
7600 	     * - The substituted text.
7601 	     * - The text after the match.
7602 	     */
7603 	    sublen = vim_regsub(&regmatch, sub, expr, tail, FALSE, TRUE, FALSE);
7604 	    if (ga_grow(&ga, (int)((end - tail) + sublen -
7605 			    (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
7606 	    {
7607 		ga_clear(&ga);
7608 		break;
7609 	    }
7610 
7611 	    /* copy the text up to where the match is */
7612 	    i = (int)(regmatch.startp[0] - tail);
7613 	    mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
7614 	    /* add the substituted text */
7615 	    (void)vim_regsub(&regmatch, sub, expr, (char_u *)ga.ga_data
7616 					  + ga.ga_len + i, TRUE, TRUE, FALSE);
7617 	    ga.ga_len += i + sublen - 1;
7618 	    tail = regmatch.endp[0];
7619 	    if (*tail == NUL)
7620 		break;
7621 	    if (!do_all)
7622 		break;
7623 	}
7624 
7625 	if (ga.ga_data != NULL)
7626 	    STRCPY((char *)ga.ga_data + ga.ga_len, tail);
7627 
7628 	vim_regfree(regmatch.regprog);
7629     }
7630 
7631     ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
7632     ga_clear(&ga);
7633     if (p_cpo == empty_option)
7634 	p_cpo = save_cpo;
7635     else
7636 	/* Darn, evaluating {sub} expression or {expr} changed the value. */
7637 	free_string_option(save_cpo);
7638 
7639     return ret;
7640 }
7641 
7642     static int
7643 filter_map_one(typval_T *tv, typval_T *expr, int map, int *remp)
7644 {
7645     typval_T	rettv;
7646     typval_T	argv[3];
7647     int		retval = FAIL;
7648 
7649     copy_tv(tv, get_vim_var_tv(VV_VAL));
7650     argv[0] = *get_vim_var_tv(VV_KEY);
7651     argv[1] = *get_vim_var_tv(VV_VAL);
7652     if (eval_expr_typval(expr, argv, 2, &rettv) == FAIL)
7653 	goto theend;
7654     if (map)
7655     {
7656 	/* map(): replace the list item value */
7657 	clear_tv(tv);
7658 	rettv.v_lock = 0;
7659 	*tv = rettv;
7660     }
7661     else
7662     {
7663 	int	    error = FALSE;
7664 
7665 	/* filter(): when expr is zero remove the item */
7666 	*remp = (tv_get_number_chk(&rettv, &error) == 0);
7667 	clear_tv(&rettv);
7668 	/* On type error, nothing has been removed; return FAIL to stop the
7669 	 * loop.  The error message was given by tv_get_number_chk(). */
7670 	if (error)
7671 	    goto theend;
7672     }
7673     retval = OK;
7674 theend:
7675     clear_tv(get_vim_var_tv(VV_VAL));
7676     return retval;
7677 }
7678 
7679 /*
7680  * Implementation of map() and filter().
7681  */
7682     void
7683 filter_map(typval_T *argvars, typval_T *rettv, int map)
7684 {
7685     typval_T	*expr;
7686     listitem_T	*li, *nli;
7687     list_T	*l = NULL;
7688     dictitem_T	*di;
7689     hashtab_T	*ht;
7690     hashitem_T	*hi;
7691     dict_T	*d = NULL;
7692     typval_T	save_val;
7693     typval_T	save_key;
7694     blob_T	*b = NULL;
7695     int		rem;
7696     int		todo;
7697     char_u	*ermsg = (char_u *)(map ? "map()" : "filter()");
7698     char_u	*arg_errmsg = (char_u *)(map ? N_("map() argument")
7699 				   : N_("filter() argument"));
7700     int		save_did_emsg;
7701     int		idx = 0;
7702 
7703     if (argvars[0].v_type == VAR_BLOB)
7704     {
7705 	if ((b = argvars[0].vval.v_blob) == NULL)
7706 	    return;
7707     }
7708     else if (argvars[0].v_type == VAR_LIST)
7709     {
7710 	if ((l = argvars[0].vval.v_list) == NULL
7711 	      || (!map && var_check_lock(l->lv_lock, arg_errmsg, TRUE)))
7712 	    return;
7713     }
7714     else if (argvars[0].v_type == VAR_DICT)
7715     {
7716 	if ((d = argvars[0].vval.v_dict) == NULL
7717 	      || (!map && var_check_lock(d->dv_lock, arg_errmsg, TRUE)))
7718 	    return;
7719     }
7720     else
7721     {
7722 	semsg(_(e_listdictarg), ermsg);
7723 	return;
7724     }
7725 
7726     expr = &argvars[1];
7727     /* On type errors, the preceding call has already displayed an error
7728      * message.  Avoid a misleading error message for an empty string that
7729      * was not passed as argument. */
7730     if (expr->v_type != VAR_UNKNOWN)
7731     {
7732 	prepare_vimvar(VV_VAL, &save_val);
7733 
7734 	/* We reset "did_emsg" to be able to detect whether an error
7735 	 * occurred during evaluation of the expression. */
7736 	save_did_emsg = did_emsg;
7737 	did_emsg = FALSE;
7738 
7739 	prepare_vimvar(VV_KEY, &save_key);
7740 	if (argvars[0].v_type == VAR_DICT)
7741 	{
7742 	    ht = &d->dv_hashtab;
7743 	    hash_lock(ht);
7744 	    todo = (int)ht->ht_used;
7745 	    for (hi = ht->ht_array; todo > 0; ++hi)
7746 	    {
7747 		if (!HASHITEM_EMPTY(hi))
7748 		{
7749 		    int r;
7750 
7751 		    --todo;
7752 		    di = HI2DI(hi);
7753 		    if (map && (var_check_lock(di->di_tv.v_lock,
7754 							   arg_errmsg, TRUE)
7755 				|| var_check_ro(di->di_flags,
7756 							   arg_errmsg, TRUE)))
7757 			break;
7758 		    set_vim_var_string(VV_KEY, di->di_key, -1);
7759 		    r = filter_map_one(&di->di_tv, expr, map, &rem);
7760 		    clear_tv(get_vim_var_tv(VV_KEY));
7761 		    if (r == FAIL || did_emsg)
7762 			break;
7763 		    if (!map && rem)
7764 		    {
7765 			if (var_check_fixed(di->di_flags, arg_errmsg, TRUE)
7766 			    || var_check_ro(di->di_flags, arg_errmsg, TRUE))
7767 			    break;
7768 			dictitem_remove(d, di);
7769 		    }
7770 		}
7771 	    }
7772 	    hash_unlock(ht);
7773 	}
7774 	else if (argvars[0].v_type == VAR_BLOB)
7775 	{
7776 	    int		i;
7777 	    typval_T	tv;
7778 
7779 	    set_vim_var_type(VV_KEY, VAR_NUMBER);
7780 	    for (i = 0; i < b->bv_ga.ga_len; i++)
7781 	    {
7782 		tv.v_type = VAR_NUMBER;
7783 		tv.vval.v_number = blob_get(b, i);
7784 		set_vim_var_nr(VV_KEY, idx);
7785 		if (filter_map_one(&tv, expr, map, &rem) == FAIL || did_emsg)
7786 		    break;
7787 		if (tv.v_type != VAR_NUMBER)
7788 		{
7789 		    emsg(_(e_invalblob));
7790 		    return;
7791 		}
7792 		tv.v_type = VAR_NUMBER;
7793 		blob_set(b, i, tv.vval.v_number);
7794 		if (!map && rem)
7795 		{
7796 		    char_u *p = (char_u *)argvars[0].vval.v_blob->bv_ga.ga_data;
7797 
7798 		    mch_memmove(p + idx, p + i + 1,
7799 					      (size_t)b->bv_ga.ga_len - i - 1);
7800 		    --b->bv_ga.ga_len;
7801 		    --i;
7802 		}
7803 	    }
7804 	}
7805 	else
7806 	{
7807 	    // argvars[0].v_type == VAR_LIST
7808 	    set_vim_var_type(VV_KEY, VAR_NUMBER);
7809 
7810 	    for (li = l->lv_first; li != NULL; li = nli)
7811 	    {
7812 		if (map && var_check_lock(li->li_tv.v_lock, arg_errmsg, TRUE))
7813 		    break;
7814 		nli = li->li_next;
7815 		set_vim_var_nr(VV_KEY, idx);
7816 		if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
7817 								  || did_emsg)
7818 		    break;
7819 		if (!map && rem)
7820 		    listitem_remove(l, li);
7821 		++idx;
7822 	    }
7823 	}
7824 
7825 	restore_vimvar(VV_KEY, &save_key);
7826 	restore_vimvar(VV_VAL, &save_val);
7827 
7828 	did_emsg |= save_did_emsg;
7829     }
7830 
7831     copy_tv(&argvars[0], rettv);
7832 }
7833 
7834 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */
7835