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