xref: /vim-8.2.3635/src/eval.c (revision fda3729a)
1 /* vi:set ts=8 sts=4 sw=4:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * eval.c: Expression evaluation.
12  */
13 
14 #include "vim.h"
15 
16 #if defined(FEAT_EVAL) || defined(PROTO)
17 
18 #ifdef AMIGA
19 # include <time.h>	/* for strftime() */
20 #endif
21 
22 #ifdef VMS
23 # include <float.h>
24 #endif
25 
26 #ifdef MACOS
27 # include <time.h>	/* for time_t */
28 #endif
29 
30 #if defined(FEAT_FLOAT) && defined(HAVE_MATH_H)
31 # include <math.h>
32 #endif
33 
34 #define DICT_MAXNEST 100	/* maximum nesting of lists and dicts */
35 
36 #define DO_NOT_FREE_CNT 99999	/* refcount for dict or list that should not
37 				   be freed. */
38 
39 /*
40  * In a hashtab item "hi_key" points to "di_key" in a dictitem.
41  * This avoids adding a pointer to the hashtab item.
42  * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
43  * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
44  * HI2DI() converts a hashitem pointer to a dictitem pointer.
45  */
46 static dictitem_T dumdi;
47 #define DI2HIKEY(di) ((di)->di_key)
48 #define HIKEY2DI(p)  ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
49 #define HI2DI(hi)     HIKEY2DI((hi)->hi_key)
50 
51 /*
52  * Structure returned by get_lval() and used by set_var_lval().
53  * For a plain name:
54  *	"name"	    points to the variable name.
55  *	"exp_name"  is NULL.
56  *	"tv"	    is NULL
57  * For a magic braces name:
58  *	"name"	    points to the expanded variable name.
59  *	"exp_name"  is non-NULL, to be freed later.
60  *	"tv"	    is NULL
61  * For an index in a list:
62  *	"name"	    points to the (expanded) variable name.
63  *	"exp_name"  NULL or non-NULL, to be freed later.
64  *	"tv"	    points to the (first) list item value
65  *	"li"	    points to the (first) list item
66  *	"range", "n1", "n2" and "empty2" indicate what items are used.
67  * For an existing Dict item:
68  *	"name"	    points to the (expanded) variable name.
69  *	"exp_name"  NULL or non-NULL, to be freed later.
70  *	"tv"	    points to the dict item value
71  *	"newkey"    is NULL
72  * For a non-existing Dict item:
73  *	"name"	    points to the (expanded) variable name.
74  *	"exp_name"  NULL or non-NULL, to be freed later.
75  *	"tv"	    points to the Dictionary typval_T
76  *	"newkey"    is the key for the new item.
77  */
78 typedef struct lval_S
79 {
80     char_u	*ll_name;	/* start of variable name (can be NULL) */
81     char_u	*ll_exp_name;	/* NULL or expanded name in allocated memory. */
82     typval_T	*ll_tv;		/* Typeval of item being used.  If "newkey"
83 				   isn't NULL it's the Dict to which to add
84 				   the item. */
85     listitem_T	*ll_li;		/* The list item or NULL. */
86     list_T	*ll_list;	/* The list or NULL. */
87     int		ll_range;	/* TRUE when a [i:j] range was used */
88     long	ll_n1;		/* First index for list */
89     long	ll_n2;		/* Second index for list range */
90     int		ll_empty2;	/* Second index is empty: [i:] */
91     dict_T	*ll_dict;	/* The Dictionary or NULL */
92     dictitem_T	*ll_di;		/* The dictitem or NULL */
93     char_u	*ll_newkey;	/* New key for Dict in alloc. mem or NULL. */
94 } lval_T;
95 
96 
97 static char *e_letunexp	= N_("E18: Unexpected characters in :let");
98 static char *e_listidx = N_("E684: list index out of range: %ld");
99 static char *e_undefvar = N_("E121: Undefined variable: %s");
100 static char *e_missbrac = N_("E111: Missing ']'");
101 static char *e_listarg = N_("E686: Argument of %s must be a List");
102 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
103 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
104 static char *e_listreq = N_("E714: List required");
105 static char *e_dictreq = N_("E715: Dictionary required");
106 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
107 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
108 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
109 static char *e_funcdict = N_("E717: Dictionary entry already exists");
110 static char *e_funcref = N_("E718: Funcref required");
111 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
112 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
113 static char *e_nofunc = N_("E130: Unknown function: %s");
114 static char *e_illvar = N_("E461: Illegal variable name: %s");
115 #ifdef FEAT_FLOAT
116 static char *e_float_as_string = N_("E806: using Float as a String");
117 #endif
118 
119 static dictitem_T	globvars_var;		/* variable used for g: */
120 #define globvarht globvardict.dv_hashtab
121 
122 /*
123  * Old Vim variables such as "v:version" are also available without the "v:".
124  * Also in functions.  We need a special hashtable for them.
125  */
126 static hashtab_T	compat_hashtab;
127 
128 /*
129  * When recursively copying lists and dicts we need to remember which ones we
130  * have done to avoid endless recursiveness.  This unique ID is used for that.
131  * The last bit is used for previous_funccal, ignored when comparing.
132  */
133 static int current_copyID = 0;
134 #define COPYID_INC 2
135 #define COPYID_MASK (~0x1)
136 
137 /* Abort conversion to string after a recursion error. */
138 static int  did_echo_string_emsg = FALSE;
139 
140 /*
141  * Array to hold the hashtab with variables local to each sourced script.
142  * Each item holds a variable (nameless) that points to the dict_T.
143  */
144 typedef struct
145 {
146     dictitem_T	sv_var;
147     dict_T	sv_dict;
148 } scriptvar_T;
149 
150 static garray_T	    ga_scripts = {0, 0, sizeof(scriptvar_T *), 4, NULL};
151 #define SCRIPT_SV(id) (((scriptvar_T **)ga_scripts.ga_data)[(id) - 1])
152 #define SCRIPT_VARS(id) (SCRIPT_SV(id)->sv_dict.dv_hashtab)
153 
154 static int echo_attr = 0;   /* attributes used for ":echo" */
155 
156 /* Values for trans_function_name() argument: */
157 #define TFN_INT		1	/* internal function name OK */
158 #define TFN_QUIET	2	/* no error messages */
159 #define TFN_NO_AUTOLOAD	4	/* do not use script autoloading */
160 
161 /* Values for get_lval() flags argument: */
162 #define GLV_QUIET	TFN_QUIET	/* no error messages */
163 #define GLV_NO_AUTOLOAD	TFN_NO_AUTOLOAD	/* do not use script autoloading */
164 
165 /*
166  * Structure to hold info for a user function.
167  */
168 typedef struct ufunc ufunc_T;
169 
170 struct ufunc
171 {
172     int		uf_varargs;	/* variable nr of arguments */
173     int		uf_flags;
174     int		uf_calls;	/* nr of active calls */
175     garray_T	uf_args;	/* arguments */
176     garray_T	uf_lines;	/* function lines */
177 #ifdef FEAT_PROFILE
178     int		uf_profiling;	/* TRUE when func is being profiled */
179     /* profiling the function as a whole */
180     int		uf_tm_count;	/* nr of calls */
181     proftime_T	uf_tm_total;	/* time spent in function + children */
182     proftime_T	uf_tm_self;	/* time spent in function itself */
183     proftime_T	uf_tm_children;	/* time spent in children this call */
184     /* profiling the function per line */
185     int		*uf_tml_count;	/* nr of times line was executed */
186     proftime_T	*uf_tml_total;	/* time spent in a line + children */
187     proftime_T	*uf_tml_self;	/* time spent in a line itself */
188     proftime_T	uf_tml_start;	/* start time for current line */
189     proftime_T	uf_tml_children; /* time spent in children for this line */
190     proftime_T	uf_tml_wait;	/* start wait time for current line */
191     int		uf_tml_idx;	/* index of line being timed; -1 if none */
192     int		uf_tml_execed;	/* line being timed was executed */
193 #endif
194     scid_T	uf_script_ID;	/* ID of script where function was defined,
195 				   used for s: variables */
196     int		uf_refcount;	/* for numbered function: reference count */
197     char_u	uf_name[1];	/* name of function (actually longer); can
198 				   start with <SNR>123_ (<SNR> is K_SPECIAL
199 				   KS_EXTRA KE_SNR) */
200 };
201 
202 /* function flags */
203 #define FC_ABORT    1		/* abort function on error */
204 #define FC_RANGE    2		/* function accepts range */
205 #define FC_DICT	    4		/* Dict function, uses "self" */
206 
207 /*
208  * All user-defined functions are found in this hashtable.
209  */
210 static hashtab_T	func_hashtab;
211 
212 /* The names of packages that once were loaded are remembered. */
213 static garray_T		ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
214 
215 /* list heads for garbage collection */
216 static dict_T		*first_dict = NULL;	/* list of all dicts */
217 static list_T		*first_list = NULL;	/* list of all lists */
218 
219 /* From user function to hashitem and back. */
220 static ufunc_T dumuf;
221 #define UF2HIKEY(fp) ((fp)->uf_name)
222 #define HIKEY2UF(p)  ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
223 #define HI2UF(hi)     HIKEY2UF((hi)->hi_key)
224 
225 #define FUNCARG(fp, j)	((char_u **)(fp->uf_args.ga_data))[j]
226 #define FUNCLINE(fp, j)	((char_u **)(fp->uf_lines.ga_data))[j]
227 
228 #define MAX_FUNC_ARGS	20	/* maximum number of function arguments */
229 #define VAR_SHORT_LEN	20	/* short variable name length */
230 #define FIXVAR_CNT	12	/* number of fixed variables */
231 
232 /* structure to hold info for a function that is currently being executed. */
233 typedef struct funccall_S funccall_T;
234 
235 struct funccall_S
236 {
237     ufunc_T	*func;		/* function being called */
238     int		linenr;		/* next line to be executed */
239     int		returned;	/* ":return" used */
240     struct			/* fixed variables for arguments */
241     {
242 	dictitem_T	var;		/* variable (without room for name) */
243 	char_u	room[VAR_SHORT_LEN];	/* room for the name */
244     } fixvar[FIXVAR_CNT];
245     dict_T	l_vars;		/* l: local function variables */
246     dictitem_T	l_vars_var;	/* variable for l: scope */
247     dict_T	l_avars;	/* a: argument variables */
248     dictitem_T	l_avars_var;	/* variable for a: scope */
249     list_T	l_varlist;	/* list for a:000 */
250     listitem_T	l_listitems[MAX_FUNC_ARGS];	/* listitems for a:000 */
251     typval_T	*rettv;		/* return value */
252     linenr_T	breakpoint;	/* next line with breakpoint or zero */
253     int		dbg_tick;	/* debug_tick when breakpoint was set */
254     int		level;		/* top nesting level of executed function */
255 #ifdef FEAT_PROFILE
256     proftime_T	prof_child;	/* time spent in a child */
257 #endif
258     funccall_T	*caller;	/* calling function or NULL */
259 };
260 
261 /*
262  * Info used by a ":for" loop.
263  */
264 typedef struct
265 {
266     int		fi_semicolon;	/* TRUE if ending in '; var]' */
267     int		fi_varcount;	/* nr of variables in the list */
268     listwatch_T	fi_lw;		/* keep an eye on the item used. */
269     list_T	*fi_list;	/* list being used */
270 } forinfo_T;
271 
272 /*
273  * Struct used by trans_function_name()
274  */
275 typedef struct
276 {
277     dict_T	*fd_dict;	/* Dictionary used */
278     char_u	*fd_newkey;	/* new key in "dict" in allocated memory */
279     dictitem_T	*fd_di;		/* Dictionary item used */
280 } funcdict_T;
281 
282 
283 /*
284  * Array to hold the value of v: variables.
285  * The value is in a dictitem, so that it can also be used in the v: scope.
286  * The reason to use this table anyway is for very quick access to the
287  * variables with the VV_ defines.
288  */
289 #include "version.h"
290 
291 /* values for vv_flags: */
292 #define VV_COMPAT	1	/* compatible, also used without "v:" */
293 #define VV_RO		2	/* read-only */
294 #define VV_RO_SBX	4	/* read-only in the sandbox */
295 
296 #define VV_NAME(s, t)	s, {{t, 0, {0}}, 0, {0}}, {0}
297 
298 static struct vimvar
299 {
300     char	*vv_name;	/* name of variable, without v: */
301     dictitem_T	vv_di;		/* value and name for key */
302     char	vv_filler[16];	/* space for LONGEST name below!!! */
303     char	vv_flags;	/* VV_COMPAT, VV_RO, VV_RO_SBX */
304 } vimvars[VV_LEN] =
305 {
306     /*
307      * The order here must match the VV_ defines in vim.h!
308      * Initializing a union does not work, leave tv.vval empty to get zero's.
309      */
310     {VV_NAME("count",		 VAR_NUMBER), VV_COMPAT+VV_RO},
311     {VV_NAME("count1",		 VAR_NUMBER), VV_RO},
312     {VV_NAME("prevcount",	 VAR_NUMBER), VV_RO},
313     {VV_NAME("errmsg",		 VAR_STRING), VV_COMPAT},
314     {VV_NAME("warningmsg",	 VAR_STRING), 0},
315     {VV_NAME("statusmsg",	 VAR_STRING), 0},
316     {VV_NAME("shell_error",	 VAR_NUMBER), VV_COMPAT+VV_RO},
317     {VV_NAME("this_session",	 VAR_STRING), VV_COMPAT},
318     {VV_NAME("version",		 VAR_NUMBER), VV_COMPAT+VV_RO},
319     {VV_NAME("lnum",		 VAR_NUMBER), VV_RO_SBX},
320     {VV_NAME("termresponse",	 VAR_STRING), VV_RO},
321     {VV_NAME("fname",		 VAR_STRING), VV_RO},
322     {VV_NAME("lang",		 VAR_STRING), VV_RO},
323     {VV_NAME("lc_time",		 VAR_STRING), VV_RO},
324     {VV_NAME("ctype",		 VAR_STRING), VV_RO},
325     {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
326     {VV_NAME("charconvert_to",	 VAR_STRING), VV_RO},
327     {VV_NAME("fname_in",	 VAR_STRING), VV_RO},
328     {VV_NAME("fname_out",	 VAR_STRING), VV_RO},
329     {VV_NAME("fname_new",	 VAR_STRING), VV_RO},
330     {VV_NAME("fname_diff",	 VAR_STRING), VV_RO},
331     {VV_NAME("cmdarg",		 VAR_STRING), VV_RO},
332     {VV_NAME("foldstart",	 VAR_NUMBER), VV_RO_SBX},
333     {VV_NAME("foldend",		 VAR_NUMBER), VV_RO_SBX},
334     {VV_NAME("folddashes",	 VAR_STRING), VV_RO_SBX},
335     {VV_NAME("foldlevel",	 VAR_NUMBER), VV_RO_SBX},
336     {VV_NAME("progname",	 VAR_STRING), VV_RO},
337     {VV_NAME("servername",	 VAR_STRING), VV_RO},
338     {VV_NAME("dying",		 VAR_NUMBER), VV_RO},
339     {VV_NAME("exception",	 VAR_STRING), VV_RO},
340     {VV_NAME("throwpoint",	 VAR_STRING), VV_RO},
341     {VV_NAME("register",	 VAR_STRING), VV_RO},
342     {VV_NAME("cmdbang",		 VAR_NUMBER), VV_RO},
343     {VV_NAME("insertmode",	 VAR_STRING), VV_RO},
344     {VV_NAME("val",		 VAR_UNKNOWN), VV_RO},
345     {VV_NAME("key",		 VAR_UNKNOWN), VV_RO},
346     {VV_NAME("profiling",	 VAR_NUMBER), VV_RO},
347     {VV_NAME("fcs_reason",	 VAR_STRING), VV_RO},
348     {VV_NAME("fcs_choice",	 VAR_STRING), 0},
349     {VV_NAME("beval_bufnr",	 VAR_NUMBER), VV_RO},
350     {VV_NAME("beval_winnr",	 VAR_NUMBER), VV_RO},
351     {VV_NAME("beval_lnum",	 VAR_NUMBER), VV_RO},
352     {VV_NAME("beval_col",	 VAR_NUMBER), VV_RO},
353     {VV_NAME("beval_text",	 VAR_STRING), VV_RO},
354     {VV_NAME("scrollstart",	 VAR_STRING), 0},
355     {VV_NAME("swapname",	 VAR_STRING), VV_RO},
356     {VV_NAME("swapchoice",	 VAR_STRING), 0},
357     {VV_NAME("swapcommand",	 VAR_STRING), VV_RO},
358     {VV_NAME("char",		 VAR_STRING), 0},
359     {VV_NAME("mouse_win",	 VAR_NUMBER), 0},
360     {VV_NAME("mouse_lnum",	 VAR_NUMBER), 0},
361     {VV_NAME("mouse_col",	 VAR_NUMBER), 0},
362     {VV_NAME("operator",	 VAR_STRING), VV_RO},
363     {VV_NAME("searchforward",	 VAR_NUMBER), 0},
364     {VV_NAME("hlsearch",	 VAR_NUMBER), 0},
365     {VV_NAME("oldfiles",	 VAR_LIST), 0},
366     {VV_NAME("windowid",	 VAR_NUMBER), VV_RO},
367     {VV_NAME("progpath",	 VAR_STRING), VV_RO},
368 };
369 
370 /* shorthand */
371 #define vv_type		vv_di.di_tv.v_type
372 #define vv_nr		vv_di.di_tv.vval.v_number
373 #define vv_float	vv_di.di_tv.vval.v_float
374 #define vv_str		vv_di.di_tv.vval.v_string
375 #define vv_list		vv_di.di_tv.vval.v_list
376 #define vv_tv		vv_di.di_tv
377 
378 static dictitem_T	vimvars_var;		/* variable used for v: */
379 #define vimvarht  vimvardict.dv_hashtab
380 
381 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
382 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
383 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
384 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
385 static char_u *skip_var_one __ARGS((char_u *arg));
386 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
387 static void list_glob_vars __ARGS((int *first));
388 static void list_buf_vars __ARGS((int *first));
389 static void list_win_vars __ARGS((int *first));
390 #ifdef FEAT_WINDOWS
391 static void list_tab_vars __ARGS((int *first));
392 #endif
393 static void list_vim_vars __ARGS((int *first));
394 static void list_script_vars __ARGS((int *first));
395 static void list_func_vars __ARGS((int *first));
396 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
397 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
398 static int check_changedtick __ARGS((char_u *arg));
399 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int flags, int fne_flags));
400 static void clear_lval __ARGS((lval_T *lp));
401 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
402 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u  *op));
403 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
404 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
405 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
406 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
407 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
408 static int tv_islocked __ARGS((typval_T *tv));
409 
410 static int eval0 __ARGS((char_u *arg,  typval_T *rettv, char_u **nextcmd, int evaluate));
411 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
412 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
413 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
414 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
415 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
416 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
417 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
418 
419 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
420 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
421 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
422 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
423 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
424 static int rettv_list_alloc __ARGS((typval_T *rettv));
425 static long list_len __ARGS((list_T *l));
426 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic, int recursive));
427 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic, int recursive));
428 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic, int recursive));
429 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
430 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
431 static int list_append_number __ARGS((list_T *l, varnumber_T n));
432 static int list_extend __ARGS((list_T	*l1, list_T *l2, listitem_T *bef));
433 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
434 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
435 static char_u *list2string __ARGS((typval_T *tv, int copyID));
436 static int list_join_inner __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo_style, int copyID, garray_T *join_gap));
437 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
438 static int free_unref_items __ARGS((int copyID));
439 static int rettv_dict_alloc __ARGS((typval_T *rettv));
440 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
441 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
442 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
443 static long dict_len __ARGS((dict_T *d));
444 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
445 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
446 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
447 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
448 static char_u *string_quote __ARGS((char_u *str, int function));
449 #ifdef FEAT_FLOAT
450 static int string2float __ARGS((char_u *text, float_T *value));
451 #endif
452 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
453 static int find_internal_func __ARGS((char_u *name));
454 static char_u *deref_func_name __ARGS((char_u *name, int *lenp, int no_autoload));
455 static int get_func_tv __ARGS((char_u *name, int len, typval_T *rettv, char_u **arg, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
456 static int call_func __ARGS((char_u *funcname, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
457 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
458 static int non_zero_arg __ARGS((typval_T *argvars));
459 
460 #ifdef FEAT_FLOAT
461 static void f_abs __ARGS((typval_T *argvars, typval_T *rettv));
462 static void f_acos __ARGS((typval_T *argvars, typval_T *rettv));
463 #endif
464 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
465 static void f_and __ARGS((typval_T *argvars, typval_T *rettv));
466 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
467 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
468 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
469 static void f_arglistid __ARGS((typval_T *argvars, typval_T *rettv));
470 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
471 #ifdef FEAT_FLOAT
472 static void f_asin __ARGS((typval_T *argvars, typval_T *rettv));
473 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
474 static void f_atan2 __ARGS((typval_T *argvars, typval_T *rettv));
475 #endif
476 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
480 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
481 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
482 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
485 static void byteidx __ARGS((typval_T *argvars, typval_T *rettv, int comp));
486 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_byteidxcomp __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
489 #ifdef FEAT_FLOAT
490 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
491 #endif
492 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
494 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
495 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
496 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
497 #if defined(FEAT_INS_EXPAND)
498 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
501 #endif
502 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
504 #ifdef FEAT_FLOAT
505 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
506 static void f_cosh __ARGS((typval_T *argvars, typval_T *rettv));
507 #endif
508 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
509 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
510 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
511 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_exepath __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
523 #ifdef FEAT_FLOAT
524 static void f_exp __ARGS((typval_T *argvars, typval_T *rettv));
525 #endif
526 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
534 #ifdef FEAT_FLOAT
535 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_fmod __ARGS((typval_T *argvars, typval_T *rettv));
538 #endif
539 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_getcmdwintype __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_getcurpos __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_gettabvar __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_invert __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
614 #ifdef FEAT_FLOAT
615 static void f_log __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
617 #endif
618 #ifdef FEAT_LUA
619 static void f_luaeval __ARGS((typval_T *argvars, typval_T *rettv));
620 #endif
621 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
623 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
625 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_matchaddpos __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
634 #ifdef vim_mkdir
635 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
636 #endif
637 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
638 #ifdef FEAT_MZSCHEME
639 static void f_mzeval __ARGS((typval_T *argvars, typval_T *rettv));
640 #endif
641 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
642 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_or __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
645 #ifdef FEAT_FLOAT
646 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
647 #endif
648 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
651 #ifdef FEAT_PYTHON3
652 static void f_py3eval __ARGS((typval_T *argvars, typval_T *rettv));
653 #endif
654 #ifdef FEAT_PYTHON
655 static void f_pyeval __ARGS((typval_T *argvars, typval_T *rettv));
656 #endif
657 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
671 #ifdef FEAT_FLOAT
672 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
673 #endif
674 static void f_screenattr __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_screenchar __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_screencol __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_screenrow __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
680 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
681 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
682 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
683 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
684 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
685 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
686 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
687 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
688 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
689 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
690 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
691 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
692 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
693 static void f_settabvar __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
696 #ifdef FEAT_CRYPT
697 static void f_sha256 __ARGS((typval_T *argvars, typval_T *rettv));
698 #endif /* FEAT_CRYPT */
699 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
700 static void f_shiftwidth __ARGS((typval_T *argvars, typval_T *rettv));
701 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
702 #ifdef FEAT_FLOAT
703 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
704 static void f_sinh __ARGS((typval_T *argvars, typval_T *rettv));
705 #endif
706 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
707 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
708 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
709 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
711 #ifdef FEAT_FLOAT
712 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
713 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
714 #endif
715 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
716 static void f_strchars __ARGS((typval_T *argvars, typval_T *rettv));
717 #ifdef HAVE_STRFTIME
718 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
719 #endif
720 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
723 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
724 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
725 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
726 static void f_strdisplaywidth __ARGS((typval_T *argvars, typval_T *rettv));
727 static void f_strwidth __ARGS((typval_T *argvars, typval_T *rettv));
728 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
729 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
730 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
731 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
732 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
733 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
734 static void f_synconcealed __ARGS((typval_T *argvars, typval_T *rettv));
735 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
736 static void f_systemlist __ARGS((typval_T *argvars, typval_T *rettv));
737 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
738 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
739 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
740 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
741 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
742 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
743 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
744 #ifdef FEAT_FLOAT
745 static void f_tan __ARGS((typval_T *argvars, typval_T *rettv));
746 static void f_tanh __ARGS((typval_T *argvars, typval_T *rettv));
747 #endif
748 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
749 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
750 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
751 #ifdef FEAT_FLOAT
752 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
753 #endif
754 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
755 static void f_undofile __ARGS((typval_T *argvars, typval_T *rettv));
756 static void f_undotree __ARGS((typval_T *argvars, typval_T *rettv));
757 static void f_uniq __ARGS((typval_T *argvars, typval_T *rettv));
758 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
759 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
760 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
761 static void f_wildmenumode __ARGS((typval_T *argvars, typval_T *rettv));
762 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
763 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
764 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
765 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
766 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
767 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
768 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
769 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
770 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
771 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
772 static void f_xor __ARGS((typval_T *argvars, typval_T *rettv));
773 
774 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump, colnr_T *curswantp));
775 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
776 static int get_env_len __ARGS((char_u **arg));
777 static int get_id_len __ARGS((char_u **arg));
778 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
779 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
780 #define FNE_INCL_BR	1	/* find_name_end(): include [] in name */
781 #define FNE_CHECK_START	2	/* find_name_end(): check name starts with
782 				   valid character */
783 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
784 static int eval_isnamec __ARGS((int c));
785 static int eval_isnamec1 __ARGS((int c));
786 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose, int no_autoload));
787 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
788 static typval_T *alloc_tv __ARGS((void));
789 static typval_T *alloc_string_tv __ARGS((char_u *string));
790 static void init_tv __ARGS((typval_T *varp));
791 static long get_tv_number __ARGS((typval_T *varp));
792 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
793 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
794 static char_u *get_tv_string __ARGS((typval_T *varp));
795 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
796 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
797 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp, int no_autoload));
798 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, int htname, char_u *varname, int no_autoload));
799 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
800 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
801 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
802 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
803 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
804 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
805 static int var_check_ro __ARGS((int flags, char_u *name));
806 static int var_check_fixed __ARGS((int flags, char_u *name));
807 static int var_check_func_name __ARGS((char_u *name, int new_var));
808 static int valid_varname __ARGS((char_u *varname));
809 static int tv_check_lock __ARGS((int lock, char_u *name));
810 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
811 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
812 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
813 static int eval_fname_script __ARGS((char_u *p));
814 static int eval_fname_sid __ARGS((char_u *p));
815 static void list_func_head __ARGS((ufunc_T *fp, int indent));
816 static ufunc_T *find_func __ARGS((char_u *name));
817 static int function_exists __ARGS((char_u *name));
818 static int builtin_function __ARGS((char_u *name, int len));
819 #ifdef FEAT_PROFILE
820 static void func_do_profile __ARGS((ufunc_T *fp));
821 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
822 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
823 static int
824 # ifdef __BORLANDC__
825     _RTLENTRYF
826 # endif
827 	prof_total_cmp __ARGS((const void *s1, const void *s2));
828 static int
829 # ifdef __BORLANDC__
830     _RTLENTRYF
831 # endif
832 	prof_self_cmp __ARGS((const void *s1, const void *s2));
833 #endif
834 static int script_autoload __ARGS((char_u *name, int reload));
835 static char_u *autoload_name __ARGS((char_u *name));
836 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
837 static void func_free __ARGS((ufunc_T *fp));
838 static void call_user_func __ARGS((ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, linenr_T firstline, linenr_T lastline, dict_T *selfdict));
839 static int can_free_funccal __ARGS((funccall_T *fc, int copyID)) ;
840 static void free_funccal __ARGS((funccall_T *fc, int free_val));
841 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
842 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
843 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
844 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
845 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
846 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
847 static int write_list __ARGS((FILE *fd, list_T *list, int binary));
848 static void get_cmd_output_as_rettv __ARGS((typval_T *argvars, typval_T *rettv, int retlist));
849 
850 
851 #ifdef EBCDIC
852 static int compare_func_name __ARGS((const void *s1, const void *s2));
853 static void sortFunctions __ARGS(());
854 #endif
855 
856 /*
857  * Initialize the global and v: variables.
858  */
859     void
860 eval_init()
861 {
862     int		    i;
863     struct vimvar   *p;
864 
865     init_var_dict(&globvardict, &globvars_var, VAR_DEF_SCOPE);
866     init_var_dict(&vimvardict, &vimvars_var, VAR_SCOPE);
867     vimvardict.dv_lock = VAR_FIXED;
868     hash_init(&compat_hashtab);
869     hash_init(&func_hashtab);
870 
871     for (i = 0; i < VV_LEN; ++i)
872     {
873 	p = &vimvars[i];
874 	STRCPY(p->vv_di.di_key, p->vv_name);
875 	if (p->vv_flags & VV_RO)
876 	    p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
877 	else if (p->vv_flags & VV_RO_SBX)
878 	    p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
879 	else
880 	    p->vv_di.di_flags = DI_FLAGS_FIX;
881 
882 	/* add to v: scope dict, unless the value is not always available */
883 	if (p->vv_type != VAR_UNKNOWN)
884 	    hash_add(&vimvarht, p->vv_di.di_key);
885 	if (p->vv_flags & VV_COMPAT)
886 	    /* add to compat scope dict */
887 	    hash_add(&compat_hashtab, p->vv_di.di_key);
888     }
889     set_vim_var_nr(VV_SEARCHFORWARD, 1L);
890     set_vim_var_nr(VV_HLSEARCH, 1L);
891     set_reg_var(0);  /* default for v:register is not 0 but '"' */
892 
893 #ifdef EBCDIC
894     /*
895      * Sort the function table, to enable binary search.
896      */
897     sortFunctions();
898 #endif
899 }
900 
901 #if defined(EXITFREE) || defined(PROTO)
902     void
903 eval_clear()
904 {
905     int		    i;
906     struct vimvar   *p;
907 
908     for (i = 0; i < VV_LEN; ++i)
909     {
910 	p = &vimvars[i];
911 	if (p->vv_di.di_tv.v_type == VAR_STRING)
912 	{
913 	    vim_free(p->vv_str);
914 	    p->vv_str = NULL;
915 	}
916 	else if (p->vv_di.di_tv.v_type == VAR_LIST)
917 	{
918 	    list_unref(p->vv_list);
919 	    p->vv_list = NULL;
920 	}
921     }
922     hash_clear(&vimvarht);
923     hash_init(&vimvarht);  /* garbage_collect() will access it */
924     hash_clear(&compat_hashtab);
925 
926     free_scriptnames();
927 # if defined(FEAT_CMDL_COMPL)
928     free_locales();
929 # endif
930 
931     /* global variables */
932     vars_clear(&globvarht);
933 
934     /* autoloaded script names */
935     ga_clear_strings(&ga_loaded);
936 
937     /* Script-local variables. First clear all the variables and in a second
938      * loop free the scriptvar_T, because a variable in one script might hold
939      * a reference to the whole scope of another script. */
940     for (i = 1; i <= ga_scripts.ga_len; ++i)
941 	vars_clear(&SCRIPT_VARS(i));
942     for (i = 1; i <= ga_scripts.ga_len; ++i)
943 	vim_free(SCRIPT_SV(i));
944     ga_clear(&ga_scripts);
945 
946     /* unreferenced lists and dicts */
947     (void)garbage_collect();
948 
949     /* functions */
950     free_all_functions();
951     hash_clear(&func_hashtab);
952 }
953 #endif
954 
955 /*
956  * Return the name of the executed function.
957  */
958     char_u *
959 func_name(cookie)
960     void *cookie;
961 {
962     return ((funccall_T *)cookie)->func->uf_name;
963 }
964 
965 /*
966  * Return the address holding the next breakpoint line for a funccall cookie.
967  */
968     linenr_T *
969 func_breakpoint(cookie)
970     void *cookie;
971 {
972     return &((funccall_T *)cookie)->breakpoint;
973 }
974 
975 /*
976  * Return the address holding the debug tick for a funccall cookie.
977  */
978     int *
979 func_dbg_tick(cookie)
980     void *cookie;
981 {
982     return &((funccall_T *)cookie)->dbg_tick;
983 }
984 
985 /*
986  * Return the nesting level for a funccall cookie.
987  */
988     int
989 func_level(cookie)
990     void *cookie;
991 {
992     return ((funccall_T *)cookie)->level;
993 }
994 
995 /* pointer to funccal for currently active function */
996 funccall_T *current_funccal = NULL;
997 
998 /* pointer to list of previously used funccal, still around because some
999  * item in it is still being used. */
1000 funccall_T *previous_funccal = NULL;
1001 
1002 /*
1003  * Return TRUE when a function was ended by a ":return" command.
1004  */
1005     int
1006 current_func_returned()
1007 {
1008     return current_funccal->returned;
1009 }
1010 
1011 
1012 /*
1013  * Set an internal variable to a string value. Creates the variable if it does
1014  * not already exist.
1015  */
1016     void
1017 set_internal_string_var(name, value)
1018     char_u	*name;
1019     char_u	*value;
1020 {
1021     char_u	*val;
1022     typval_T	*tvp;
1023 
1024     val = vim_strsave(value);
1025     if (val != NULL)
1026     {
1027 	tvp = alloc_string_tv(val);
1028 	if (tvp != NULL)
1029 	{
1030 	    set_var(name, tvp, FALSE);
1031 	    free_tv(tvp);
1032 	}
1033     }
1034 }
1035 
1036 static lval_T	*redir_lval = NULL;
1037 static garray_T redir_ga;	/* only valid when redir_lval is not NULL */
1038 static char_u	*redir_endp = NULL;
1039 static char_u	*redir_varname = NULL;
1040 
1041 /*
1042  * Start recording command output to a variable
1043  * Returns OK if successfully completed the setup.  FAIL otherwise.
1044  */
1045     int
1046 var_redir_start(name, append)
1047     char_u	*name;
1048     int		append;		/* append to an existing variable */
1049 {
1050     int		save_emsg;
1051     int		err;
1052     typval_T	tv;
1053 
1054     /* Catch a bad name early. */
1055     if (!eval_isnamec1(*name))
1056     {
1057 	EMSG(_(e_invarg));
1058 	return FAIL;
1059     }
1060 
1061     /* Make a copy of the name, it is used in redir_lval until redir ends. */
1062     redir_varname = vim_strsave(name);
1063     if (redir_varname == NULL)
1064 	return FAIL;
1065 
1066     redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
1067     if (redir_lval == NULL)
1068     {
1069 	var_redir_stop();
1070 	return FAIL;
1071     }
1072 
1073     /* The output is stored in growarray "redir_ga" until redirection ends. */
1074     ga_init2(&redir_ga, (int)sizeof(char), 500);
1075 
1076     /* Parse the variable name (can be a dict or list entry). */
1077     redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, 0,
1078 							     FNE_CHECK_START);
1079     if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
1080     {
1081 	clear_lval(redir_lval);
1082 	if (redir_endp != NULL && *redir_endp != NUL)
1083 	    /* Trailing characters are present after the variable name */
1084 	    EMSG(_(e_trailing));
1085 	else
1086 	    EMSG(_(e_invarg));
1087 	redir_endp = NULL;  /* don't store a value, only cleanup */
1088 	var_redir_stop();
1089 	return FAIL;
1090     }
1091 
1092     /* check if we can write to the variable: set it to or append an empty
1093      * string */
1094     save_emsg = did_emsg;
1095     did_emsg = FALSE;
1096     tv.v_type = VAR_STRING;
1097     tv.vval.v_string = (char_u *)"";
1098     if (append)
1099 	set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1100     else
1101 	set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1102     clear_lval(redir_lval);
1103     err = did_emsg;
1104     did_emsg |= save_emsg;
1105     if (err)
1106     {
1107 	redir_endp = NULL;  /* don't store a value, only cleanup */
1108 	var_redir_stop();
1109 	return FAIL;
1110     }
1111 
1112     return OK;
1113 }
1114 
1115 /*
1116  * Append "value[value_len]" to the variable set by var_redir_start().
1117  * The actual appending is postponed until redirection ends, because the value
1118  * appended may in fact be the string we write to, changing it may cause freed
1119  * memory to be used:
1120  *   :redir => foo
1121  *   :let foo
1122  *   :redir END
1123  */
1124     void
1125 var_redir_str(value, value_len)
1126     char_u	*value;
1127     int		value_len;
1128 {
1129     int		len;
1130 
1131     if (redir_lval == NULL)
1132 	return;
1133 
1134     if (value_len == -1)
1135 	len = (int)STRLEN(value);	/* Append the entire string */
1136     else
1137 	len = value_len;		/* Append only "value_len" characters */
1138 
1139     if (ga_grow(&redir_ga, len) == OK)
1140     {
1141 	mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1142 	redir_ga.ga_len += len;
1143     }
1144     else
1145 	var_redir_stop();
1146 }
1147 
1148 /*
1149  * Stop redirecting command output to a variable.
1150  * Frees the allocated memory.
1151  */
1152     void
1153 var_redir_stop()
1154 {
1155     typval_T	tv;
1156 
1157     if (redir_lval != NULL)
1158     {
1159 	/* If there was no error: assign the text to the variable. */
1160 	if (redir_endp != NULL)
1161 	{
1162 	    ga_append(&redir_ga, NUL);  /* Append the trailing NUL. */
1163 	    tv.v_type = VAR_STRING;
1164 	    tv.vval.v_string = redir_ga.ga_data;
1165 	    /* Call get_lval() again, if it's inside a Dict or List it may
1166 	     * have changed. */
1167 	    redir_endp = get_lval(redir_varname, NULL, redir_lval,
1168 					FALSE, FALSE, 0, FNE_CHECK_START);
1169 	    if (redir_endp != NULL && redir_lval->ll_name != NULL)
1170 		set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1171 	    clear_lval(redir_lval);
1172 	}
1173 
1174 	/* free the collected output */
1175 	vim_free(redir_ga.ga_data);
1176 	redir_ga.ga_data = NULL;
1177 
1178 	vim_free(redir_lval);
1179 	redir_lval = NULL;
1180     }
1181     vim_free(redir_varname);
1182     redir_varname = NULL;
1183 }
1184 
1185 # if defined(FEAT_MBYTE) || defined(PROTO)
1186     int
1187 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1188     char_u	*enc_from;
1189     char_u	*enc_to;
1190     char_u	*fname_from;
1191     char_u	*fname_to;
1192 {
1193     int		err = FALSE;
1194 
1195     set_vim_var_string(VV_CC_FROM, enc_from, -1);
1196     set_vim_var_string(VV_CC_TO, enc_to, -1);
1197     set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1198     set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1199     if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1200 	err = TRUE;
1201     set_vim_var_string(VV_CC_FROM, NULL, -1);
1202     set_vim_var_string(VV_CC_TO, NULL, -1);
1203     set_vim_var_string(VV_FNAME_IN, NULL, -1);
1204     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1205 
1206     if (err)
1207 	return FAIL;
1208     return OK;
1209 }
1210 # endif
1211 
1212 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1213     int
1214 eval_printexpr(fname, args)
1215     char_u	*fname;
1216     char_u	*args;
1217 {
1218     int		err = FALSE;
1219 
1220     set_vim_var_string(VV_FNAME_IN, fname, -1);
1221     set_vim_var_string(VV_CMDARG, args, -1);
1222     if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1223 	err = TRUE;
1224     set_vim_var_string(VV_FNAME_IN, NULL, -1);
1225     set_vim_var_string(VV_CMDARG, NULL, -1);
1226 
1227     if (err)
1228     {
1229 	mch_remove(fname);
1230 	return FAIL;
1231     }
1232     return OK;
1233 }
1234 # endif
1235 
1236 # if defined(FEAT_DIFF) || defined(PROTO)
1237     void
1238 eval_diff(origfile, newfile, outfile)
1239     char_u	*origfile;
1240     char_u	*newfile;
1241     char_u	*outfile;
1242 {
1243     int		err = FALSE;
1244 
1245     set_vim_var_string(VV_FNAME_IN, origfile, -1);
1246     set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1247     set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1248     (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1249     set_vim_var_string(VV_FNAME_IN, NULL, -1);
1250     set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1251     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1252 }
1253 
1254     void
1255 eval_patch(origfile, difffile, outfile)
1256     char_u	*origfile;
1257     char_u	*difffile;
1258     char_u	*outfile;
1259 {
1260     int		err;
1261 
1262     set_vim_var_string(VV_FNAME_IN, origfile, -1);
1263     set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1264     set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1265     (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1266     set_vim_var_string(VV_FNAME_IN, NULL, -1);
1267     set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1268     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1269 }
1270 # endif
1271 
1272 /*
1273  * Top level evaluation function, returning a boolean.
1274  * Sets "error" to TRUE if there was an error.
1275  * Return TRUE or FALSE.
1276  */
1277     int
1278 eval_to_bool(arg, error, nextcmd, skip)
1279     char_u	*arg;
1280     int		*error;
1281     char_u	**nextcmd;
1282     int		skip;	    /* only parse, don't execute */
1283 {
1284     typval_T	tv;
1285     int		retval = FALSE;
1286 
1287     if (skip)
1288 	++emsg_skip;
1289     if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1290 	*error = TRUE;
1291     else
1292     {
1293 	*error = FALSE;
1294 	if (!skip)
1295 	{
1296 	    retval = (get_tv_number_chk(&tv, error) != 0);
1297 	    clear_tv(&tv);
1298 	}
1299     }
1300     if (skip)
1301 	--emsg_skip;
1302 
1303     return retval;
1304 }
1305 
1306 /*
1307  * Top level evaluation function, returning a string.  If "skip" is TRUE,
1308  * only parsing to "nextcmd" is done, without reporting errors.  Return
1309  * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1310  */
1311     char_u *
1312 eval_to_string_skip(arg, nextcmd, skip)
1313     char_u	*arg;
1314     char_u	**nextcmd;
1315     int		skip;	    /* only parse, don't execute */
1316 {
1317     typval_T	tv;
1318     char_u	*retval;
1319 
1320     if (skip)
1321 	++emsg_skip;
1322     if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1323 	retval = NULL;
1324     else
1325     {
1326 	retval = vim_strsave(get_tv_string(&tv));
1327 	clear_tv(&tv);
1328     }
1329     if (skip)
1330 	--emsg_skip;
1331 
1332     return retval;
1333 }
1334 
1335 /*
1336  * Skip over an expression at "*pp".
1337  * Return FAIL for an error, OK otherwise.
1338  */
1339     int
1340 skip_expr(pp)
1341     char_u	**pp;
1342 {
1343     typval_T	rettv;
1344 
1345     *pp = skipwhite(*pp);
1346     return eval1(pp, &rettv, FALSE);
1347 }
1348 
1349 /*
1350  * Top level evaluation function, returning a string.
1351  * When "convert" is TRUE convert a List into a sequence of lines and convert
1352  * a Float to a String.
1353  * Return pointer to allocated memory, or NULL for failure.
1354  */
1355     char_u *
1356 eval_to_string(arg, nextcmd, convert)
1357     char_u	*arg;
1358     char_u	**nextcmd;
1359     int		convert;
1360 {
1361     typval_T	tv;
1362     char_u	*retval;
1363     garray_T	ga;
1364 #ifdef FEAT_FLOAT
1365     char_u	numbuf[NUMBUFLEN];
1366 #endif
1367 
1368     if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1369 	retval = NULL;
1370     else
1371     {
1372 	if (convert && tv.v_type == VAR_LIST)
1373 	{
1374 	    ga_init2(&ga, (int)sizeof(char), 80);
1375 	    if (tv.vval.v_list != NULL)
1376 	    {
1377 		list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1378 		if (tv.vval.v_list->lv_len > 0)
1379 		    ga_append(&ga, NL);
1380 	    }
1381 	    ga_append(&ga, NUL);
1382 	    retval = (char_u *)ga.ga_data;
1383 	}
1384 #ifdef FEAT_FLOAT
1385 	else if (convert && tv.v_type == VAR_FLOAT)
1386 	{
1387 	    vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
1388 	    retval = vim_strsave(numbuf);
1389 	}
1390 #endif
1391 	else
1392 	    retval = vim_strsave(get_tv_string(&tv));
1393 	clear_tv(&tv);
1394     }
1395 
1396     return retval;
1397 }
1398 
1399 /*
1400  * Call eval_to_string() without using current local variables and using
1401  * textlock.  When "use_sandbox" is TRUE use the sandbox.
1402  */
1403     char_u *
1404 eval_to_string_safe(arg, nextcmd, use_sandbox)
1405     char_u	*arg;
1406     char_u	**nextcmd;
1407     int		use_sandbox;
1408 {
1409     char_u	*retval;
1410     void	*save_funccalp;
1411 
1412     save_funccalp = save_funccal();
1413     if (use_sandbox)
1414 	++sandbox;
1415     ++textlock;
1416     retval = eval_to_string(arg, nextcmd, FALSE);
1417     if (use_sandbox)
1418 	--sandbox;
1419     --textlock;
1420     restore_funccal(save_funccalp);
1421     return retval;
1422 }
1423 
1424 /*
1425  * Top level evaluation function, returning a number.
1426  * Evaluates "expr" silently.
1427  * Returns -1 for an error.
1428  */
1429     int
1430 eval_to_number(expr)
1431     char_u	*expr;
1432 {
1433     typval_T	rettv;
1434     int		retval;
1435     char_u	*p = skipwhite(expr);
1436 
1437     ++emsg_off;
1438 
1439     if (eval1(&p, &rettv, TRUE) == FAIL)
1440 	retval = -1;
1441     else
1442     {
1443 	retval = get_tv_number_chk(&rettv, NULL);
1444 	clear_tv(&rettv);
1445     }
1446     --emsg_off;
1447 
1448     return retval;
1449 }
1450 
1451 /*
1452  * Prepare v: variable "idx" to be used.
1453  * Save the current typeval in "save_tv".
1454  * When not used yet add the variable to the v: hashtable.
1455  */
1456     static void
1457 prepare_vimvar(idx, save_tv)
1458     int		idx;
1459     typval_T	*save_tv;
1460 {
1461     *save_tv = vimvars[idx].vv_tv;
1462     if (vimvars[idx].vv_type == VAR_UNKNOWN)
1463 	hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1464 }
1465 
1466 /*
1467  * Restore v: variable "idx" to typeval "save_tv".
1468  * When no longer defined, remove the variable from the v: hashtable.
1469  */
1470     static void
1471 restore_vimvar(idx, save_tv)
1472     int		idx;
1473     typval_T	*save_tv;
1474 {
1475     hashitem_T	*hi;
1476 
1477     vimvars[idx].vv_tv = *save_tv;
1478     if (vimvars[idx].vv_type == VAR_UNKNOWN)
1479     {
1480 	hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1481 	if (HASHITEM_EMPTY(hi))
1482 	    EMSG2(_(e_intern2), "restore_vimvar()");
1483 	else
1484 	    hash_remove(&vimvarht, hi);
1485     }
1486 }
1487 
1488 #if defined(FEAT_SPELL) || defined(PROTO)
1489 /*
1490  * Evaluate an expression to a list with suggestions.
1491  * For the "expr:" part of 'spellsuggest'.
1492  * Returns NULL when there is an error.
1493  */
1494     list_T *
1495 eval_spell_expr(badword, expr)
1496     char_u	*badword;
1497     char_u	*expr;
1498 {
1499     typval_T	save_val;
1500     typval_T	rettv;
1501     list_T	*list = NULL;
1502     char_u	*p = skipwhite(expr);
1503 
1504     /* Set "v:val" to the bad word. */
1505     prepare_vimvar(VV_VAL, &save_val);
1506     vimvars[VV_VAL].vv_type = VAR_STRING;
1507     vimvars[VV_VAL].vv_str = badword;
1508     if (p_verbose == 0)
1509 	++emsg_off;
1510 
1511     if (eval1(&p, &rettv, TRUE) == OK)
1512     {
1513 	if (rettv.v_type != VAR_LIST)
1514 	    clear_tv(&rettv);
1515 	else
1516 	    list = rettv.vval.v_list;
1517     }
1518 
1519     if (p_verbose == 0)
1520 	--emsg_off;
1521     restore_vimvar(VV_VAL, &save_val);
1522 
1523     return list;
1524 }
1525 
1526 /*
1527  * "list" is supposed to contain two items: a word and a number.  Return the
1528  * word in "pp" and the number as the return value.
1529  * Return -1 if anything isn't right.
1530  * Used to get the good word and score from the eval_spell_expr() result.
1531  */
1532     int
1533 get_spellword(list, pp)
1534     list_T	*list;
1535     char_u	**pp;
1536 {
1537     listitem_T	*li;
1538 
1539     li = list->lv_first;
1540     if (li == NULL)
1541 	return -1;
1542     *pp = get_tv_string(&li->li_tv);
1543 
1544     li = li->li_next;
1545     if (li == NULL)
1546 	return -1;
1547     return get_tv_number(&li->li_tv);
1548 }
1549 #endif
1550 
1551 /*
1552  * Top level evaluation function.
1553  * Returns an allocated typval_T with the result.
1554  * Returns NULL when there is an error.
1555  */
1556     typval_T *
1557 eval_expr(arg, nextcmd)
1558     char_u	*arg;
1559     char_u	**nextcmd;
1560 {
1561     typval_T	*tv;
1562 
1563     tv = (typval_T *)alloc(sizeof(typval_T));
1564     if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1565     {
1566 	vim_free(tv);
1567 	tv = NULL;
1568     }
1569 
1570     return tv;
1571 }
1572 
1573 
1574 /*
1575  * Call some vimL function and return the result in "*rettv".
1576  * Uses argv[argc] for the function arguments.  Only Number and String
1577  * arguments are currently supported.
1578  * Returns OK or FAIL.
1579  */
1580     int
1581 call_vim_function(func, argc, argv, safe, str_arg_only, rettv)
1582     char_u      *func;
1583     int		argc;
1584     char_u      **argv;
1585     int		safe;		/* use the sandbox */
1586     int		str_arg_only;	/* all arguments are strings */
1587     typval_T	*rettv;
1588 {
1589     typval_T	*argvars;
1590     long	n;
1591     int		len;
1592     int		i;
1593     int		doesrange;
1594     void	*save_funccalp = NULL;
1595     int		ret;
1596 
1597     argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1598     if (argvars == NULL)
1599 	return FAIL;
1600 
1601     for (i = 0; i < argc; i++)
1602     {
1603 	/* Pass a NULL or empty argument as an empty string */
1604 	if (argv[i] == NULL || *argv[i] == NUL)
1605 	{
1606 	    argvars[i].v_type = VAR_STRING;
1607 	    argvars[i].vval.v_string = (char_u *)"";
1608 	    continue;
1609 	}
1610 
1611 	if (str_arg_only)
1612 	    len = 0;
1613 	else
1614 	    /* Recognize a number argument, the others must be strings. */
1615 	    vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1616 	if (len != 0 && len == (int)STRLEN(argv[i]))
1617 	{
1618 	    argvars[i].v_type = VAR_NUMBER;
1619 	    argvars[i].vval.v_number = n;
1620 	}
1621 	else
1622 	{
1623 	    argvars[i].v_type = VAR_STRING;
1624 	    argvars[i].vval.v_string = argv[i];
1625 	}
1626     }
1627 
1628     if (safe)
1629     {
1630 	save_funccalp = save_funccal();
1631 	++sandbox;
1632     }
1633 
1634     rettv->v_type = VAR_UNKNOWN;		/* clear_tv() uses this */
1635     ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1636 		    curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1637 		    &doesrange, TRUE, NULL);
1638     if (safe)
1639     {
1640 	--sandbox;
1641 	restore_funccal(save_funccalp);
1642     }
1643     vim_free(argvars);
1644 
1645     if (ret == FAIL)
1646 	clear_tv(rettv);
1647 
1648     return ret;
1649 }
1650 
1651 /*
1652  * Call vimL function "func" and return the result as a number.
1653  * Returns -1 when calling the function fails.
1654  * Uses argv[argc] for the function arguments.
1655  */
1656     long
1657 call_func_retnr(func, argc, argv, safe)
1658     char_u      *func;
1659     int		argc;
1660     char_u      **argv;
1661     int		safe;		/* use the sandbox */
1662 {
1663     typval_T	rettv;
1664     long	retval;
1665 
1666     /* All arguments are passed as strings, no conversion to number. */
1667     if (call_vim_function(func, argc, argv, safe, TRUE, &rettv) == FAIL)
1668 	return -1;
1669 
1670     retval = get_tv_number_chk(&rettv, NULL);
1671     clear_tv(&rettv);
1672     return retval;
1673 }
1674 
1675 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1676 	|| defined(FEAT_COMPL_FUNC) || defined(PROTO)
1677 
1678 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1679 /*
1680  * Call vimL function "func" and return the result as a string.
1681  * Returns NULL when calling the function fails.
1682  * Uses argv[argc] for the function arguments.
1683  */
1684     void *
1685 call_func_retstr(func, argc, argv, safe)
1686     char_u      *func;
1687     int		argc;
1688     char_u      **argv;
1689     int		safe;		/* use the sandbox */
1690 {
1691     typval_T	rettv;
1692     char_u	*retval;
1693 
1694     /* All arguments are passed as strings, no conversion to number. */
1695     if (call_vim_function(func, argc, argv, safe, TRUE, &rettv) == FAIL)
1696 	return NULL;
1697 
1698     retval = vim_strsave(get_tv_string(&rettv));
1699     clear_tv(&rettv);
1700     return retval;
1701 }
1702 # endif
1703 
1704 /*
1705  * Call vimL function "func" and return the result as a List.
1706  * Uses argv[argc] for the function arguments.
1707  * Returns NULL when there is something wrong.
1708  */
1709     void *
1710 call_func_retlist(func, argc, argv, safe)
1711     char_u      *func;
1712     int		argc;
1713     char_u      **argv;
1714     int		safe;		/* use the sandbox */
1715 {
1716     typval_T	rettv;
1717 
1718     /* All arguments are passed as strings, no conversion to number. */
1719     if (call_vim_function(func, argc, argv, safe, TRUE, &rettv) == FAIL)
1720 	return NULL;
1721 
1722     if (rettv.v_type != VAR_LIST)
1723     {
1724 	clear_tv(&rettv);
1725 	return NULL;
1726     }
1727 
1728     return rettv.vval.v_list;
1729 }
1730 #endif
1731 
1732 /*
1733  * Save the current function call pointer, and set it to NULL.
1734  * Used when executing autocommands and for ":source".
1735  */
1736     void *
1737 save_funccal()
1738 {
1739     funccall_T *fc = current_funccal;
1740 
1741     current_funccal = NULL;
1742     return (void *)fc;
1743 }
1744 
1745     void
1746 restore_funccal(vfc)
1747     void *vfc;
1748 {
1749     funccall_T *fc = (funccall_T *)vfc;
1750 
1751     current_funccal = fc;
1752 }
1753 
1754 #if defined(FEAT_PROFILE) || defined(PROTO)
1755 /*
1756  * Prepare profiling for entering a child or something else that is not
1757  * counted for the script/function itself.
1758  * Should always be called in pair with prof_child_exit().
1759  */
1760     void
1761 prof_child_enter(tm)
1762     proftime_T *tm;	/* place to store waittime */
1763 {
1764     funccall_T *fc = current_funccal;
1765 
1766     if (fc != NULL && fc->func->uf_profiling)
1767 	profile_start(&fc->prof_child);
1768     script_prof_save(tm);
1769 }
1770 
1771 /*
1772  * Take care of time spent in a child.
1773  * Should always be called after prof_child_enter().
1774  */
1775     void
1776 prof_child_exit(tm)
1777     proftime_T *tm;	/* where waittime was stored */
1778 {
1779     funccall_T *fc = current_funccal;
1780 
1781     if (fc != NULL && fc->func->uf_profiling)
1782     {
1783 	profile_end(&fc->prof_child);
1784 	profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1785 	profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1786 	profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1787     }
1788     script_prof_restore(tm);
1789 }
1790 #endif
1791 
1792 
1793 #ifdef FEAT_FOLDING
1794 /*
1795  * Evaluate 'foldexpr'.  Returns the foldlevel, and any character preceding
1796  * it in "*cp".  Doesn't give error messages.
1797  */
1798     int
1799 eval_foldexpr(arg, cp)
1800     char_u	*arg;
1801     int		*cp;
1802 {
1803     typval_T	tv;
1804     int		retval;
1805     char_u	*s;
1806     int		use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1807 								   OPT_LOCAL);
1808 
1809     ++emsg_off;
1810     if (use_sandbox)
1811 	++sandbox;
1812     ++textlock;
1813     *cp = NUL;
1814     if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1815 	retval = 0;
1816     else
1817     {
1818 	/* If the result is a number, just return the number. */
1819 	if (tv.v_type == VAR_NUMBER)
1820 	    retval = tv.vval.v_number;
1821 	else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1822 	    retval = 0;
1823 	else
1824 	{
1825 	    /* If the result is a string, check if there is a non-digit before
1826 	     * the number. */
1827 	    s = tv.vval.v_string;
1828 	    if (!VIM_ISDIGIT(*s) && *s != '-')
1829 		*cp = *s++;
1830 	    retval = atol((char *)s);
1831 	}
1832 	clear_tv(&tv);
1833     }
1834     --emsg_off;
1835     if (use_sandbox)
1836 	--sandbox;
1837     --textlock;
1838 
1839     return retval;
1840 }
1841 #endif
1842 
1843 /*
1844  * ":let"			list all variable values
1845  * ":let var1 var2"		list variable values
1846  * ":let var = expr"		assignment command.
1847  * ":let var += expr"		assignment command.
1848  * ":let var -= expr"		assignment command.
1849  * ":let var .= expr"		assignment command.
1850  * ":let [var1, var2] = expr"	unpack list.
1851  */
1852     void
1853 ex_let(eap)
1854     exarg_T	*eap;
1855 {
1856     char_u	*arg = eap->arg;
1857     char_u	*expr = NULL;
1858     typval_T	rettv;
1859     int		i;
1860     int		var_count = 0;
1861     int		semicolon = 0;
1862     char_u	op[2];
1863     char_u	*argend;
1864     int		first = TRUE;
1865 
1866     argend = skip_var_list(arg, &var_count, &semicolon);
1867     if (argend == NULL)
1868 	return;
1869     if (argend > arg && argend[-1] == '.')  /* for var.='str' */
1870 	--argend;
1871     expr = skipwhite(argend);
1872     if (*expr != '=' && !(vim_strchr((char_u *)"+-.", *expr) != NULL
1873 			  && expr[1] == '='))
1874     {
1875 	/*
1876 	 * ":let" without "=": list variables
1877 	 */
1878 	if (*arg == '[')
1879 	    EMSG(_(e_invarg));
1880 	else if (!ends_excmd(*arg))
1881 	    /* ":let var1 var2" */
1882 	    arg = list_arg_vars(eap, arg, &first);
1883 	else if (!eap->skip)
1884 	{
1885 	    /* ":let" */
1886 	    list_glob_vars(&first);
1887 	    list_buf_vars(&first);
1888 	    list_win_vars(&first);
1889 #ifdef FEAT_WINDOWS
1890 	    list_tab_vars(&first);
1891 #endif
1892 	    list_script_vars(&first);
1893 	    list_func_vars(&first);
1894 	    list_vim_vars(&first);
1895 	}
1896 	eap->nextcmd = check_nextcmd(arg);
1897     }
1898     else
1899     {
1900 	op[0] = '=';
1901 	op[1] = NUL;
1902 	if (*expr != '=')
1903 	{
1904 	    if (vim_strchr((char_u *)"+-.", *expr) != NULL)
1905 		op[0] = *expr;   /* +=, -= or .= */
1906 	    expr = skipwhite(expr + 2);
1907 	}
1908 	else
1909 	    expr = skipwhite(expr + 1);
1910 
1911 	if (eap->skip)
1912 	    ++emsg_skip;
1913 	i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1914 	if (eap->skip)
1915 	{
1916 	    if (i != FAIL)
1917 		clear_tv(&rettv);
1918 	    --emsg_skip;
1919 	}
1920 	else if (i != FAIL)
1921 	{
1922 	    (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1923 									  op);
1924 	    clear_tv(&rettv);
1925 	}
1926     }
1927 }
1928 
1929 /*
1930  * Assign the typevalue "tv" to the variable or variables at "arg_start".
1931  * Handles both "var" with any type and "[var, var; var]" with a list type.
1932  * When "nextchars" is not NULL it points to a string with characters that
1933  * must appear after the variable(s).  Use "+", "-" or "." for add, subtract
1934  * or concatenate.
1935  * Returns OK or FAIL;
1936  */
1937     static int
1938 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1939     char_u	*arg_start;
1940     typval_T	*tv;
1941     int		copy;		/* copy values from "tv", don't move */
1942     int		semicolon;	/* from skip_var_list() */
1943     int		var_count;	/* from skip_var_list() */
1944     char_u	*nextchars;
1945 {
1946     char_u	*arg = arg_start;
1947     list_T	*l;
1948     int		i;
1949     listitem_T	*item;
1950     typval_T	ltv;
1951 
1952     if (*arg != '[')
1953     {
1954 	/*
1955 	 * ":let var = expr" or ":for var in list"
1956 	 */
1957 	if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1958 	    return FAIL;
1959 	return OK;
1960     }
1961 
1962     /*
1963      * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1964      */
1965     if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1966     {
1967 	EMSG(_(e_listreq));
1968 	return FAIL;
1969     }
1970 
1971     i = list_len(l);
1972     if (semicolon == 0 && var_count < i)
1973     {
1974 	EMSG(_("E687: Less targets than List items"));
1975 	return FAIL;
1976     }
1977     if (var_count - semicolon > i)
1978     {
1979 	EMSG(_("E688: More targets than List items"));
1980 	return FAIL;
1981     }
1982 
1983     item = l->lv_first;
1984     while (*arg != ']')
1985     {
1986 	arg = skipwhite(arg + 1);
1987 	arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1988 	item = item->li_next;
1989 	if (arg == NULL)
1990 	    return FAIL;
1991 
1992 	arg = skipwhite(arg);
1993 	if (*arg == ';')
1994 	{
1995 	    /* Put the rest of the list (may be empty) in the var after ';'.
1996 	     * Create a new list for this. */
1997 	    l = list_alloc();
1998 	    if (l == NULL)
1999 		return FAIL;
2000 	    while (item != NULL)
2001 	    {
2002 		list_append_tv(l, &item->li_tv);
2003 		item = item->li_next;
2004 	    }
2005 
2006 	    ltv.v_type = VAR_LIST;
2007 	    ltv.v_lock = 0;
2008 	    ltv.vval.v_list = l;
2009 	    l->lv_refcount = 1;
2010 
2011 	    arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
2012 						    (char_u *)"]", nextchars);
2013 	    clear_tv(&ltv);
2014 	    if (arg == NULL)
2015 		return FAIL;
2016 	    break;
2017 	}
2018 	else if (*arg != ',' && *arg != ']')
2019 	{
2020 	    EMSG2(_(e_intern2), "ex_let_vars()");
2021 	    return FAIL;
2022 	}
2023     }
2024 
2025     return OK;
2026 }
2027 
2028 /*
2029  * Skip over assignable variable "var" or list of variables "[var, var]".
2030  * Used for ":let varvar = expr" and ":for varvar in expr".
2031  * For "[var, var]" increment "*var_count" for each variable.
2032  * for "[var, var; var]" set "semicolon".
2033  * Return NULL for an error.
2034  */
2035     static char_u *
2036 skip_var_list(arg, var_count, semicolon)
2037     char_u	*arg;
2038     int		*var_count;
2039     int		*semicolon;
2040 {
2041     char_u	*p, *s;
2042 
2043     if (*arg == '[')
2044     {
2045 	/* "[var, var]": find the matching ']'. */
2046 	p = arg;
2047 	for (;;)
2048 	{
2049 	    p = skipwhite(p + 1);	/* skip whites after '[', ';' or ',' */
2050 	    s = skip_var_one(p);
2051 	    if (s == p)
2052 	    {
2053 		EMSG2(_(e_invarg2), p);
2054 		return NULL;
2055 	    }
2056 	    ++*var_count;
2057 
2058 	    p = skipwhite(s);
2059 	    if (*p == ']')
2060 		break;
2061 	    else if (*p == ';')
2062 	    {
2063 		if (*semicolon == 1)
2064 		{
2065 		    EMSG(_("Double ; in list of variables"));
2066 		    return NULL;
2067 		}
2068 		*semicolon = 1;
2069 	    }
2070 	    else if (*p != ',')
2071 	    {
2072 		EMSG2(_(e_invarg2), p);
2073 		return NULL;
2074 	    }
2075 	}
2076 	return p + 1;
2077     }
2078     else
2079 	return skip_var_one(arg);
2080 }
2081 
2082 /*
2083  * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
2084  * l[idx].
2085  */
2086     static char_u *
2087 skip_var_one(arg)
2088     char_u	*arg;
2089 {
2090     if (*arg == '@' && arg[1] != NUL)
2091 	return arg + 2;
2092     return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
2093 				   NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2094 }
2095 
2096 /*
2097  * List variables for hashtab "ht" with prefix "prefix".
2098  * If "empty" is TRUE also list NULL strings as empty strings.
2099  */
2100     static void
2101 list_hashtable_vars(ht, prefix, empty, first)
2102     hashtab_T	*ht;
2103     char_u	*prefix;
2104     int		empty;
2105     int		*first;
2106 {
2107     hashitem_T	*hi;
2108     dictitem_T	*di;
2109     int		todo;
2110 
2111     todo = (int)ht->ht_used;
2112     for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
2113     {
2114 	if (!HASHITEM_EMPTY(hi))
2115 	{
2116 	    --todo;
2117 	    di = HI2DI(hi);
2118 	    if (empty || di->di_tv.v_type != VAR_STRING
2119 					   || di->di_tv.vval.v_string != NULL)
2120 		list_one_var(di, prefix, first);
2121 	}
2122     }
2123 }
2124 
2125 /*
2126  * List global variables.
2127  */
2128     static void
2129 list_glob_vars(first)
2130     int *first;
2131 {
2132     list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2133 }
2134 
2135 /*
2136  * List buffer variables.
2137  */
2138     static void
2139 list_buf_vars(first)
2140     int *first;
2141 {
2142     char_u	numbuf[NUMBUFLEN];
2143 
2144     list_hashtable_vars(&curbuf->b_vars->dv_hashtab, (char_u *)"b:",
2145 								 TRUE, first);
2146 
2147     sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2148     list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2149 							       numbuf, first);
2150 }
2151 
2152 /*
2153  * List window variables.
2154  */
2155     static void
2156 list_win_vars(first)
2157     int *first;
2158 {
2159     list_hashtable_vars(&curwin->w_vars->dv_hashtab,
2160 						 (char_u *)"w:", TRUE, first);
2161 }
2162 
2163 #ifdef FEAT_WINDOWS
2164 /*
2165  * List tab page variables.
2166  */
2167     static void
2168 list_tab_vars(first)
2169     int *first;
2170 {
2171     list_hashtable_vars(&curtab->tp_vars->dv_hashtab,
2172 						 (char_u *)"t:", TRUE, first);
2173 }
2174 #endif
2175 
2176 /*
2177  * List Vim variables.
2178  */
2179     static void
2180 list_vim_vars(first)
2181     int *first;
2182 {
2183     list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2184 }
2185 
2186 /*
2187  * List script-local variables, if there is a script.
2188  */
2189     static void
2190 list_script_vars(first)
2191     int *first;
2192 {
2193     if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2194 	list_hashtable_vars(&SCRIPT_VARS(current_SID),
2195 						(char_u *)"s:", FALSE, first);
2196 }
2197 
2198 /*
2199  * List function variables, if there is a function.
2200  */
2201     static void
2202 list_func_vars(first)
2203     int *first;
2204 {
2205     if (current_funccal != NULL)
2206 	list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2207 						(char_u *)"l:", FALSE, first);
2208 }
2209 
2210 /*
2211  * List variables in "arg".
2212  */
2213     static char_u *
2214 list_arg_vars(eap, arg, first)
2215     exarg_T	*eap;
2216     char_u	*arg;
2217     int		*first;
2218 {
2219     int		error = FALSE;
2220     int		len;
2221     char_u	*name;
2222     char_u	*name_start;
2223     char_u	*arg_subsc;
2224     char_u	*tofree;
2225     typval_T    tv;
2226 
2227     while (!ends_excmd(*arg) && !got_int)
2228     {
2229 	if (error || eap->skip)
2230 	{
2231 	    arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2232 	    if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2233 	    {
2234 		emsg_severe = TRUE;
2235 		EMSG(_(e_trailing));
2236 		break;
2237 	    }
2238 	}
2239 	else
2240 	{
2241 	    /* get_name_len() takes care of expanding curly braces */
2242 	    name_start = name = arg;
2243 	    len = get_name_len(&arg, &tofree, TRUE, TRUE);
2244 	    if (len <= 0)
2245 	    {
2246 		/* This is mainly to keep test 49 working: when expanding
2247 		 * curly braces fails overrule the exception error message. */
2248 		if (len < 0 && !aborting())
2249 		{
2250 		    emsg_severe = TRUE;
2251 		    EMSG2(_(e_invarg2), arg);
2252 		    break;
2253 		}
2254 		error = TRUE;
2255 	    }
2256 	    else
2257 	    {
2258 		if (tofree != NULL)
2259 		    name = tofree;
2260 		if (get_var_tv(name, len, &tv, TRUE, FALSE) == FAIL)
2261 		    error = TRUE;
2262 		else
2263 		{
2264 		    /* handle d.key, l[idx], f(expr) */
2265 		    arg_subsc = arg;
2266 		    if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2267 			error = TRUE;
2268 		    else
2269 		    {
2270 			if (arg == arg_subsc && len == 2 && name[1] == ':')
2271 			{
2272 			    switch (*name)
2273 			    {
2274 				case 'g': list_glob_vars(first); break;
2275 				case 'b': list_buf_vars(first); break;
2276 				case 'w': list_win_vars(first); break;
2277 #ifdef FEAT_WINDOWS
2278 				case 't': list_tab_vars(first); break;
2279 #endif
2280 				case 'v': list_vim_vars(first); break;
2281 				case 's': list_script_vars(first); break;
2282 				case 'l': list_func_vars(first); break;
2283 				default:
2284 					  EMSG2(_("E738: Can't list variables for %s"), name);
2285 			    }
2286 			}
2287 			else
2288 			{
2289 			    char_u	numbuf[NUMBUFLEN];
2290 			    char_u	*tf;
2291 			    int		c;
2292 			    char_u	*s;
2293 
2294 			    s = echo_string(&tv, &tf, numbuf, 0);
2295 			    c = *arg;
2296 			    *arg = NUL;
2297 			    list_one_var_a((char_u *)"",
2298 				    arg == arg_subsc ? name : name_start,
2299 				    tv.v_type,
2300 				    s == NULL ? (char_u *)"" : s,
2301 				    first);
2302 			    *arg = c;
2303 			    vim_free(tf);
2304 			}
2305 			clear_tv(&tv);
2306 		    }
2307 		}
2308 	    }
2309 
2310 	    vim_free(tofree);
2311 	}
2312 
2313 	arg = skipwhite(arg);
2314     }
2315 
2316     return arg;
2317 }
2318 
2319 /*
2320  * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2321  * Returns a pointer to the char just after the var name.
2322  * Returns NULL if there is an error.
2323  */
2324     static char_u *
2325 ex_let_one(arg, tv, copy, endchars, op)
2326     char_u	*arg;		/* points to variable name */
2327     typval_T	*tv;		/* value to assign to variable */
2328     int		copy;		/* copy value from "tv" */
2329     char_u	*endchars;	/* valid chars after variable name  or NULL */
2330     char_u	*op;		/* "+", "-", "."  or NULL*/
2331 {
2332     int		c1;
2333     char_u	*name;
2334     char_u	*p;
2335     char_u	*arg_end = NULL;
2336     int		len;
2337     int		opt_flags;
2338     char_u	*tofree = NULL;
2339 
2340     /*
2341      * ":let $VAR = expr": Set environment variable.
2342      */
2343     if (*arg == '$')
2344     {
2345 	/* Find the end of the name. */
2346 	++arg;
2347 	name = arg;
2348 	len = get_env_len(&arg);
2349 	if (len == 0)
2350 	    EMSG2(_(e_invarg2), name - 1);
2351 	else
2352 	{
2353 	    if (op != NULL && (*op == '+' || *op == '-'))
2354 		EMSG2(_(e_letwrong), op);
2355 	    else if (endchars != NULL
2356 			     && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2357 		EMSG(_(e_letunexp));
2358 	    else if (!check_secure())
2359 	    {
2360 		c1 = name[len];
2361 		name[len] = NUL;
2362 		p = get_tv_string_chk(tv);
2363 		if (p != NULL && op != NULL && *op == '.')
2364 		{
2365 		    int	    mustfree = FALSE;
2366 		    char_u  *s = vim_getenv(name, &mustfree);
2367 
2368 		    if (s != NULL)
2369 		    {
2370 			p = tofree = concat_str(s, p);
2371 			if (mustfree)
2372 			    vim_free(s);
2373 		    }
2374 		}
2375 		if (p != NULL)
2376 		{
2377 		    vim_setenv(name, p);
2378 		    if (STRICMP(name, "HOME") == 0)
2379 			init_homedir();
2380 		    else if (didset_vim && STRICMP(name, "VIM") == 0)
2381 			didset_vim = FALSE;
2382 		    else if (didset_vimruntime
2383 					&& STRICMP(name, "VIMRUNTIME") == 0)
2384 			didset_vimruntime = FALSE;
2385 		    arg_end = arg;
2386 		}
2387 		name[len] = c1;
2388 		vim_free(tofree);
2389 	    }
2390 	}
2391     }
2392 
2393     /*
2394      * ":let &option = expr": Set option value.
2395      * ":let &l:option = expr": Set local option value.
2396      * ":let &g:option = expr": Set global option value.
2397      */
2398     else if (*arg == '&')
2399     {
2400 	/* Find the end of the name. */
2401 	p = find_option_end(&arg, &opt_flags);
2402 	if (p == NULL || (endchars != NULL
2403 			      && vim_strchr(endchars, *skipwhite(p)) == NULL))
2404 	    EMSG(_(e_letunexp));
2405 	else
2406 	{
2407 	    long	n;
2408 	    int		opt_type;
2409 	    long	numval;
2410 	    char_u	*stringval = NULL;
2411 	    char_u	*s;
2412 
2413 	    c1 = *p;
2414 	    *p = NUL;
2415 
2416 	    n = get_tv_number(tv);
2417 	    s = get_tv_string_chk(tv);	    /* != NULL if number or string */
2418 	    if (s != NULL && op != NULL && *op != '=')
2419 	    {
2420 		opt_type = get_option_value(arg, &numval,
2421 						       &stringval, opt_flags);
2422 		if ((opt_type == 1 && *op == '.')
2423 			|| (opt_type == 0 && *op != '.'))
2424 		    EMSG2(_(e_letwrong), op);
2425 		else
2426 		{
2427 		    if (opt_type == 1)  /* number */
2428 		    {
2429 			if (*op == '+')
2430 			    n = numval + n;
2431 			else
2432 			    n = numval - n;
2433 		    }
2434 		    else if (opt_type == 0 && stringval != NULL) /* string */
2435 		    {
2436 			s = concat_str(stringval, s);
2437 			vim_free(stringval);
2438 			stringval = s;
2439 		    }
2440 		}
2441 	    }
2442 	    if (s != NULL)
2443 	    {
2444 		set_option_value(arg, n, s, opt_flags);
2445 		arg_end = p;
2446 	    }
2447 	    *p = c1;
2448 	    vim_free(stringval);
2449 	}
2450     }
2451 
2452     /*
2453      * ":let @r = expr": Set register contents.
2454      */
2455     else if (*arg == '@')
2456     {
2457 	++arg;
2458 	if (op != NULL && (*op == '+' || *op == '-'))
2459 	    EMSG2(_(e_letwrong), op);
2460 	else if (endchars != NULL
2461 			 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2462 	    EMSG(_(e_letunexp));
2463 	else
2464 	{
2465 	    char_u	*ptofree = NULL;
2466 	    char_u	*s;
2467 
2468 	    p = get_tv_string_chk(tv);
2469 	    if (p != NULL && op != NULL && *op == '.')
2470 	    {
2471 		s = get_reg_contents(*arg == '@' ? '"' : *arg, GREG_EXPR_SRC);
2472 		if (s != NULL)
2473 		{
2474 		    p = ptofree = concat_str(s, p);
2475 		    vim_free(s);
2476 		}
2477 	    }
2478 	    if (p != NULL)
2479 	    {
2480 		write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2481 		arg_end = arg + 1;
2482 	    }
2483 	    vim_free(ptofree);
2484 	}
2485     }
2486 
2487     /*
2488      * ":let var = expr": Set internal variable.
2489      * ":let {expr} = expr": Idem, name made with curly braces
2490      */
2491     else if (eval_isnamec1(*arg) || *arg == '{')
2492     {
2493 	lval_T	lv;
2494 
2495 	p = get_lval(arg, tv, &lv, FALSE, FALSE, 0, FNE_CHECK_START);
2496 	if (p != NULL && lv.ll_name != NULL)
2497 	{
2498 	    if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2499 		EMSG(_(e_letunexp));
2500 	    else
2501 	    {
2502 		set_var_lval(&lv, p, tv, copy, op);
2503 		arg_end = p;
2504 	    }
2505 	}
2506 	clear_lval(&lv);
2507     }
2508 
2509     else
2510 	EMSG2(_(e_invarg2), arg);
2511 
2512     return arg_end;
2513 }
2514 
2515 /*
2516  * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2517  */
2518     static int
2519 check_changedtick(arg)
2520     char_u	*arg;
2521 {
2522     if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2523     {
2524 	EMSG2(_(e_readonlyvar), arg);
2525 	return TRUE;
2526     }
2527     return FALSE;
2528 }
2529 
2530 /*
2531  * Get an lval: variable, Dict item or List item that can be assigned a value
2532  * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2533  * "name.key", "name.key[expr]" etc.
2534  * Indexing only works if "name" is an existing List or Dictionary.
2535  * "name" points to the start of the name.
2536  * If "rettv" is not NULL it points to the value to be assigned.
2537  * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2538  * wrong; must end in space or cmd separator.
2539  *
2540  * flags:
2541  *  GLV_QUIET:       do not give error messages
2542  *  GLV_NO_AUTOLOAD: do not use script autoloading
2543  *
2544  * Returns a pointer to just after the name, including indexes.
2545  * When an evaluation error occurs "lp->ll_name" is NULL;
2546  * Returns NULL for a parsing error.  Still need to free items in "lp"!
2547  */
2548     static char_u *
2549 get_lval(name, rettv, lp, unlet, skip, flags, fne_flags)
2550     char_u	*name;
2551     typval_T	*rettv;
2552     lval_T	*lp;
2553     int		unlet;
2554     int		skip;
2555     int		flags;	    /* GLV_ values */
2556     int		fne_flags;  /* flags for find_name_end() */
2557 {
2558     char_u	*p;
2559     char_u	*expr_start, *expr_end;
2560     int		cc;
2561     dictitem_T	*v;
2562     typval_T	var1;
2563     typval_T	var2;
2564     int		empty1 = FALSE;
2565     listitem_T	*ni;
2566     char_u	*key = NULL;
2567     int		len;
2568     hashtab_T	*ht;
2569     int		quiet = flags & GLV_QUIET;
2570 
2571     /* Clear everything in "lp". */
2572     vim_memset(lp, 0, sizeof(lval_T));
2573 
2574     if (skip)
2575     {
2576 	/* When skipping just find the end of the name. */
2577 	lp->ll_name = name;
2578 	return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2579     }
2580 
2581     /* Find the end of the name. */
2582     p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2583     if (expr_start != NULL)
2584     {
2585 	/* Don't expand the name when we already know there is an error. */
2586 	if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2587 						    && *p != '[' && *p != '.')
2588 	{
2589 	    EMSG(_(e_trailing));
2590 	    return NULL;
2591 	}
2592 
2593 	lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2594 	if (lp->ll_exp_name == NULL)
2595 	{
2596 	    /* Report an invalid expression in braces, unless the
2597 	     * expression evaluation has been cancelled due to an
2598 	     * aborting error, an interrupt, or an exception. */
2599 	    if (!aborting() && !quiet)
2600 	    {
2601 		emsg_severe = TRUE;
2602 		EMSG2(_(e_invarg2), name);
2603 		return NULL;
2604 	    }
2605 	}
2606 	lp->ll_name = lp->ll_exp_name;
2607     }
2608     else
2609 	lp->ll_name = name;
2610 
2611     /* Without [idx] or .key we are done. */
2612     if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2613 	return p;
2614 
2615     cc = *p;
2616     *p = NUL;
2617     v = find_var(lp->ll_name, &ht, flags & GLV_NO_AUTOLOAD);
2618     if (v == NULL && !quiet)
2619 	EMSG2(_(e_undefvar), lp->ll_name);
2620     *p = cc;
2621     if (v == NULL)
2622 	return NULL;
2623 
2624     /*
2625      * Loop until no more [idx] or .key is following.
2626      */
2627     lp->ll_tv = &v->di_tv;
2628     while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2629     {
2630 	if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2631 		&& !(lp->ll_tv->v_type == VAR_DICT
2632 					   && lp->ll_tv->vval.v_dict != NULL))
2633 	{
2634 	    if (!quiet)
2635 		EMSG(_("E689: Can only index a List or Dictionary"));
2636 	    return NULL;
2637 	}
2638 	if (lp->ll_range)
2639 	{
2640 	    if (!quiet)
2641 		EMSG(_("E708: [:] must come last"));
2642 	    return NULL;
2643 	}
2644 
2645 	len = -1;
2646 	if (*p == '.')
2647 	{
2648 	    key = p + 1;
2649 	    for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2650 		;
2651 	    if (len == 0)
2652 	    {
2653 		if (!quiet)
2654 		    EMSG(_(e_emptykey));
2655 		return NULL;
2656 	    }
2657 	    p = key + len;
2658 	}
2659 	else
2660 	{
2661 	    /* Get the index [expr] or the first index [expr: ]. */
2662 	    p = skipwhite(p + 1);
2663 	    if (*p == ':')
2664 		empty1 = TRUE;
2665 	    else
2666 	    {
2667 		empty1 = FALSE;
2668 		if (eval1(&p, &var1, TRUE) == FAIL)	/* recursive! */
2669 		    return NULL;
2670 		if (get_tv_string_chk(&var1) == NULL)
2671 		{
2672 		    /* not a number or string */
2673 		    clear_tv(&var1);
2674 		    return NULL;
2675 		}
2676 	    }
2677 
2678 	    /* Optionally get the second index [ :expr]. */
2679 	    if (*p == ':')
2680 	    {
2681 		if (lp->ll_tv->v_type == VAR_DICT)
2682 		{
2683 		    if (!quiet)
2684 			EMSG(_(e_dictrange));
2685 		    if (!empty1)
2686 			clear_tv(&var1);
2687 		    return NULL;
2688 		}
2689 		if (rettv != NULL && (rettv->v_type != VAR_LIST
2690 					       || rettv->vval.v_list == NULL))
2691 		{
2692 		    if (!quiet)
2693 			EMSG(_("E709: [:] requires a List value"));
2694 		    if (!empty1)
2695 			clear_tv(&var1);
2696 		    return NULL;
2697 		}
2698 		p = skipwhite(p + 1);
2699 		if (*p == ']')
2700 		    lp->ll_empty2 = TRUE;
2701 		else
2702 		{
2703 		    lp->ll_empty2 = FALSE;
2704 		    if (eval1(&p, &var2, TRUE) == FAIL)	/* recursive! */
2705 		    {
2706 			if (!empty1)
2707 			    clear_tv(&var1);
2708 			return NULL;
2709 		    }
2710 		    if (get_tv_string_chk(&var2) == NULL)
2711 		    {
2712 			/* not a number or string */
2713 			if (!empty1)
2714 			    clear_tv(&var1);
2715 			clear_tv(&var2);
2716 			return NULL;
2717 		    }
2718 		}
2719 		lp->ll_range = TRUE;
2720 	    }
2721 	    else
2722 		lp->ll_range = FALSE;
2723 
2724 	    if (*p != ']')
2725 	    {
2726 		if (!quiet)
2727 		    EMSG(_(e_missbrac));
2728 		if (!empty1)
2729 		    clear_tv(&var1);
2730 		if (lp->ll_range && !lp->ll_empty2)
2731 		    clear_tv(&var2);
2732 		return NULL;
2733 	    }
2734 
2735 	    /* Skip to past ']'. */
2736 	    ++p;
2737 	}
2738 
2739 	if (lp->ll_tv->v_type == VAR_DICT)
2740 	{
2741 	    if (len == -1)
2742 	    {
2743 		/* "[key]": get key from "var1" */
2744 		key = get_tv_string(&var1);	/* is number or string */
2745 		if (*key == NUL)
2746 		{
2747 		    if (!quiet)
2748 			EMSG(_(e_emptykey));
2749 		    clear_tv(&var1);
2750 		    return NULL;
2751 		}
2752 	    }
2753 	    lp->ll_list = NULL;
2754 	    lp->ll_dict = lp->ll_tv->vval.v_dict;
2755 	    lp->ll_di = dict_find(lp->ll_dict, key, len);
2756 
2757 	    /* When assigning to a scope dictionary check that a function and
2758 	     * variable name is valid (only variable name unless it is l: or
2759 	     * g: dictionary). Disallow overwriting a builtin function. */
2760 	    if (rettv != NULL && lp->ll_dict->dv_scope != 0)
2761 	    {
2762 		int prevval;
2763 		int wrong;
2764 
2765 		if (len != -1)
2766 		{
2767 		    prevval = key[len];
2768 		    key[len] = NUL;
2769 		}
2770 		else
2771 		    prevval = 0; /* avoid compiler warning */
2772 		wrong = (lp->ll_dict->dv_scope == VAR_DEF_SCOPE
2773 			       && rettv->v_type == VAR_FUNC
2774 			       && var_check_func_name(key, lp->ll_di == NULL))
2775 			|| !valid_varname(key);
2776 		if (len != -1)
2777 		    key[len] = prevval;
2778 		if (wrong)
2779 		    return NULL;
2780 	    }
2781 
2782 	    if (lp->ll_di == NULL)
2783 	    {
2784 		/* Can't add "v:" variable. */
2785 		if (lp->ll_dict == &vimvardict)
2786 		{
2787 		    EMSG2(_(e_illvar), name);
2788 		    return NULL;
2789 		}
2790 
2791 		/* Key does not exist in dict: may need to add it. */
2792 		if (*p == '[' || *p == '.' || unlet)
2793 		{
2794 		    if (!quiet)
2795 			EMSG2(_(e_dictkey), key);
2796 		    if (len == -1)
2797 			clear_tv(&var1);
2798 		    return NULL;
2799 		}
2800 		if (len == -1)
2801 		    lp->ll_newkey = vim_strsave(key);
2802 		else
2803 		    lp->ll_newkey = vim_strnsave(key, len);
2804 		if (len == -1)
2805 		    clear_tv(&var1);
2806 		if (lp->ll_newkey == NULL)
2807 		    p = NULL;
2808 		break;
2809 	    }
2810 	    /* existing variable, need to check if it can be changed */
2811 	    else if (var_check_ro(lp->ll_di->di_flags, name))
2812 		return NULL;
2813 
2814 	    if (len == -1)
2815 		clear_tv(&var1);
2816 	    lp->ll_tv = &lp->ll_di->di_tv;
2817 	}
2818 	else
2819 	{
2820 	    /*
2821 	     * Get the number and item for the only or first index of the List.
2822 	     */
2823 	    if (empty1)
2824 		lp->ll_n1 = 0;
2825 	    else
2826 	    {
2827 		lp->ll_n1 = get_tv_number(&var1);   /* is number or string */
2828 		clear_tv(&var1);
2829 	    }
2830 	    lp->ll_dict = NULL;
2831 	    lp->ll_list = lp->ll_tv->vval.v_list;
2832 	    lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2833 	    if (lp->ll_li == NULL)
2834 	    {
2835 		if (lp->ll_n1 < 0)
2836 		{
2837 		    lp->ll_n1 = 0;
2838 		    lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2839 		}
2840 	    }
2841 	    if (lp->ll_li == NULL)
2842 	    {
2843 		if (lp->ll_range && !lp->ll_empty2)
2844 		    clear_tv(&var2);
2845 		if (!quiet)
2846 		    EMSGN(_(e_listidx), lp->ll_n1);
2847 		return NULL;
2848 	    }
2849 
2850 	    /*
2851 	     * May need to find the item or absolute index for the second
2852 	     * index of a range.
2853 	     * When no index given: "lp->ll_empty2" is TRUE.
2854 	     * Otherwise "lp->ll_n2" is set to the second index.
2855 	     */
2856 	    if (lp->ll_range && !lp->ll_empty2)
2857 	    {
2858 		lp->ll_n2 = get_tv_number(&var2);   /* is number or string */
2859 		clear_tv(&var2);
2860 		if (lp->ll_n2 < 0)
2861 		{
2862 		    ni = list_find(lp->ll_list, lp->ll_n2);
2863 		    if (ni == NULL)
2864 		    {
2865 			if (!quiet)
2866 			    EMSGN(_(e_listidx), lp->ll_n2);
2867 			return NULL;
2868 		    }
2869 		    lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2870 		}
2871 
2872 		/* Check that lp->ll_n2 isn't before lp->ll_n1. */
2873 		if (lp->ll_n1 < 0)
2874 		    lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2875 		if (lp->ll_n2 < lp->ll_n1)
2876 		{
2877 		    if (!quiet)
2878 			EMSGN(_(e_listidx), lp->ll_n2);
2879 		    return NULL;
2880 		}
2881 	    }
2882 
2883 	    lp->ll_tv = &lp->ll_li->li_tv;
2884 	}
2885     }
2886 
2887     return p;
2888 }
2889 
2890 /*
2891  * Clear lval "lp" that was filled by get_lval().
2892  */
2893     static void
2894 clear_lval(lp)
2895     lval_T	*lp;
2896 {
2897     vim_free(lp->ll_exp_name);
2898     vim_free(lp->ll_newkey);
2899 }
2900 
2901 /*
2902  * Set a variable that was parsed by get_lval() to "rettv".
2903  * "endp" points to just after the parsed name.
2904  * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2905  */
2906     static void
2907 set_var_lval(lp, endp, rettv, copy, op)
2908     lval_T	*lp;
2909     char_u	*endp;
2910     typval_T	*rettv;
2911     int		copy;
2912     char_u	*op;
2913 {
2914     int		cc;
2915     listitem_T	*ri;
2916     dictitem_T	*di;
2917 
2918     if (lp->ll_tv == NULL)
2919     {
2920 	if (!check_changedtick(lp->ll_name))
2921 	{
2922 	    cc = *endp;
2923 	    *endp = NUL;
2924 	    if (op != NULL && *op != '=')
2925 	    {
2926 		typval_T tv;
2927 
2928 		/* handle +=, -= and .= */
2929 		if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2930 						      &tv, TRUE, FALSE) == OK)
2931 		{
2932 		    if (tv_op(&tv, rettv, op) == OK)
2933 			set_var(lp->ll_name, &tv, FALSE);
2934 		    clear_tv(&tv);
2935 		}
2936 	    }
2937 	    else
2938 		set_var(lp->ll_name, rettv, copy);
2939 	    *endp = cc;
2940 	}
2941     }
2942     else if (tv_check_lock(lp->ll_newkey == NULL
2943 		? lp->ll_tv->v_lock
2944 		: lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2945 	;
2946     else if (lp->ll_range)
2947     {
2948 	listitem_T *ll_li = lp->ll_li;
2949 	int ll_n1 = lp->ll_n1;
2950 
2951 	/*
2952 	 * Check whether any of the list items is locked
2953 	 */
2954 	for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2955 	{
2956 	    if (tv_check_lock(ll_li->li_tv.v_lock, lp->ll_name))
2957 		return;
2958 	    ri = ri->li_next;
2959 	    if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == ll_n1))
2960 		break;
2961 	    ll_li = ll_li->li_next;
2962 	    ++ll_n1;
2963 	}
2964 
2965 	/*
2966 	 * Assign the List values to the list items.
2967 	 */
2968 	for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2969 	{
2970 	    if (op != NULL && *op != '=')
2971 		tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2972 	    else
2973 	    {
2974 		clear_tv(&lp->ll_li->li_tv);
2975 		copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2976 	    }
2977 	    ri = ri->li_next;
2978 	    if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2979 		break;
2980 	    if (lp->ll_li->li_next == NULL)
2981 	    {
2982 		/* Need to add an empty item. */
2983 		if (list_append_number(lp->ll_list, 0) == FAIL)
2984 		{
2985 		    ri = NULL;
2986 		    break;
2987 		}
2988 	    }
2989 	    lp->ll_li = lp->ll_li->li_next;
2990 	    ++lp->ll_n1;
2991 	}
2992 	if (ri != NULL)
2993 	    EMSG(_("E710: List value has more items than target"));
2994 	else if (lp->ll_empty2
2995 		? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2996 		: lp->ll_n1 != lp->ll_n2)
2997 	    EMSG(_("E711: List value has not enough items"));
2998     }
2999     else
3000     {
3001 	/*
3002 	 * Assign to a List or Dictionary item.
3003 	 */
3004 	if (lp->ll_newkey != NULL)
3005 	{
3006 	    if (op != NULL && *op != '=')
3007 	    {
3008 		EMSG2(_(e_letwrong), op);
3009 		return;
3010 	    }
3011 
3012 	    /* Need to add an item to the Dictionary. */
3013 	    di = dictitem_alloc(lp->ll_newkey);
3014 	    if (di == NULL)
3015 		return;
3016 	    if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
3017 	    {
3018 		vim_free(di);
3019 		return;
3020 	    }
3021 	    lp->ll_tv = &di->di_tv;
3022 	}
3023 	else if (op != NULL && *op != '=')
3024 	{
3025 	    tv_op(lp->ll_tv, rettv, op);
3026 	    return;
3027 	}
3028 	else
3029 	    clear_tv(lp->ll_tv);
3030 
3031 	/*
3032 	 * Assign the value to the variable or list item.
3033 	 */
3034 	if (copy)
3035 	    copy_tv(rettv, lp->ll_tv);
3036 	else
3037 	{
3038 	    *lp->ll_tv = *rettv;
3039 	    lp->ll_tv->v_lock = 0;
3040 	    init_tv(rettv);
3041 	}
3042     }
3043 }
3044 
3045 /*
3046  * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
3047  * Returns OK or FAIL.
3048  */
3049     static int
3050 tv_op(tv1, tv2, op)
3051     typval_T *tv1;
3052     typval_T *tv2;
3053     char_u  *op;
3054 {
3055     long	n;
3056     char_u	numbuf[NUMBUFLEN];
3057     char_u	*s;
3058 
3059     /* Can't do anything with a Funcref or a Dict on the right. */
3060     if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
3061     {
3062 	switch (tv1->v_type)
3063 	{
3064 	    case VAR_DICT:
3065 	    case VAR_FUNC:
3066 		break;
3067 
3068 	    case VAR_LIST:
3069 		if (*op != '+' || tv2->v_type != VAR_LIST)
3070 		    break;
3071 		/* List += List */
3072 		if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
3073 		    list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
3074 		return OK;
3075 
3076 	    case VAR_NUMBER:
3077 	    case VAR_STRING:
3078 		if (tv2->v_type == VAR_LIST)
3079 		    break;
3080 		if (*op == '+' || *op == '-')
3081 		{
3082 		    /* nr += nr  or  nr -= nr*/
3083 		    n = get_tv_number(tv1);
3084 #ifdef FEAT_FLOAT
3085 		    if (tv2->v_type == VAR_FLOAT)
3086 		    {
3087 			float_T f = n;
3088 
3089 			if (*op == '+')
3090 			    f += tv2->vval.v_float;
3091 			else
3092 			    f -= tv2->vval.v_float;
3093 			clear_tv(tv1);
3094 			tv1->v_type = VAR_FLOAT;
3095 			tv1->vval.v_float = f;
3096 		    }
3097 		    else
3098 #endif
3099 		    {
3100 			if (*op == '+')
3101 			    n += get_tv_number(tv2);
3102 			else
3103 			    n -= get_tv_number(tv2);
3104 			clear_tv(tv1);
3105 			tv1->v_type = VAR_NUMBER;
3106 			tv1->vval.v_number = n;
3107 		    }
3108 		}
3109 		else
3110 		{
3111 		    if (tv2->v_type == VAR_FLOAT)
3112 			break;
3113 
3114 		    /* str .= str */
3115 		    s = get_tv_string(tv1);
3116 		    s = concat_str(s, get_tv_string_buf(tv2, numbuf));
3117 		    clear_tv(tv1);
3118 		    tv1->v_type = VAR_STRING;
3119 		    tv1->vval.v_string = s;
3120 		}
3121 		return OK;
3122 
3123 #ifdef FEAT_FLOAT
3124 	    case VAR_FLOAT:
3125 		{
3126 		    float_T f;
3127 
3128 		    if (*op == '.' || (tv2->v_type != VAR_FLOAT
3129 				    && tv2->v_type != VAR_NUMBER
3130 				    && tv2->v_type != VAR_STRING))
3131 			break;
3132 		    if (tv2->v_type == VAR_FLOAT)
3133 			f = tv2->vval.v_float;
3134 		    else
3135 			f = get_tv_number(tv2);
3136 		    if (*op == '+')
3137 			tv1->vval.v_float += f;
3138 		    else
3139 			tv1->vval.v_float -= f;
3140 		}
3141 		return OK;
3142 #endif
3143 	}
3144     }
3145 
3146     EMSG2(_(e_letwrong), op);
3147     return FAIL;
3148 }
3149 
3150 /*
3151  * Add a watcher to a list.
3152  */
3153     void
3154 list_add_watch(l, lw)
3155     list_T	*l;
3156     listwatch_T	*lw;
3157 {
3158     lw->lw_next = l->lv_watch;
3159     l->lv_watch = lw;
3160 }
3161 
3162 /*
3163  * Remove a watcher from a list.
3164  * No warning when it isn't found...
3165  */
3166     void
3167 list_rem_watch(l, lwrem)
3168     list_T	*l;
3169     listwatch_T	*lwrem;
3170 {
3171     listwatch_T	*lw, **lwp;
3172 
3173     lwp = &l->lv_watch;
3174     for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3175     {
3176 	if (lw == lwrem)
3177 	{
3178 	    *lwp = lw->lw_next;
3179 	    break;
3180 	}
3181 	lwp = &lw->lw_next;
3182     }
3183 }
3184 
3185 /*
3186  * Just before removing an item from a list: advance watchers to the next
3187  * item.
3188  */
3189     static void
3190 list_fix_watch(l, item)
3191     list_T	*l;
3192     listitem_T	*item;
3193 {
3194     listwatch_T	*lw;
3195 
3196     for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3197 	if (lw->lw_item == item)
3198 	    lw->lw_item = item->li_next;
3199 }
3200 
3201 /*
3202  * Evaluate the expression used in a ":for var in expr" command.
3203  * "arg" points to "var".
3204  * Set "*errp" to TRUE for an error, FALSE otherwise;
3205  * Return a pointer that holds the info.  Null when there is an error.
3206  */
3207     void *
3208 eval_for_line(arg, errp, nextcmdp, skip)
3209     char_u	*arg;
3210     int		*errp;
3211     char_u	**nextcmdp;
3212     int		skip;
3213 {
3214     forinfo_T	*fi;
3215     char_u	*expr;
3216     typval_T	tv;
3217     list_T	*l;
3218 
3219     *errp = TRUE;	/* default: there is an error */
3220 
3221     fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3222     if (fi == NULL)
3223 	return NULL;
3224 
3225     expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3226     if (expr == NULL)
3227 	return fi;
3228 
3229     expr = skipwhite(expr);
3230     if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3231     {
3232 	EMSG(_("E690: Missing \"in\" after :for"));
3233 	return fi;
3234     }
3235 
3236     if (skip)
3237 	++emsg_skip;
3238     if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3239     {
3240 	*errp = FALSE;
3241 	if (!skip)
3242 	{
3243 	    l = tv.vval.v_list;
3244 	    if (tv.v_type != VAR_LIST || l == NULL)
3245 	    {
3246 		EMSG(_(e_listreq));
3247 		clear_tv(&tv);
3248 	    }
3249 	    else
3250 	    {
3251 		/* No need to increment the refcount, it's already set for the
3252 		 * list being used in "tv". */
3253 		fi->fi_list = l;
3254 		list_add_watch(l, &fi->fi_lw);
3255 		fi->fi_lw.lw_item = l->lv_first;
3256 	    }
3257 	}
3258     }
3259     if (skip)
3260 	--emsg_skip;
3261 
3262     return fi;
3263 }
3264 
3265 /*
3266  * Use the first item in a ":for" list.  Advance to the next.
3267  * Assign the values to the variable (list).  "arg" points to the first one.
3268  * Return TRUE when a valid item was found, FALSE when at end of list or
3269  * something wrong.
3270  */
3271     int
3272 next_for_item(fi_void, arg)
3273     void	*fi_void;
3274     char_u	*arg;
3275 {
3276     forinfo_T	*fi = (forinfo_T *)fi_void;
3277     int		result;
3278     listitem_T	*item;
3279 
3280     item = fi->fi_lw.lw_item;
3281     if (item == NULL)
3282 	result = FALSE;
3283     else
3284     {
3285 	fi->fi_lw.lw_item = item->li_next;
3286 	result = (ex_let_vars(arg, &item->li_tv, TRUE,
3287 			      fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3288     }
3289     return result;
3290 }
3291 
3292 /*
3293  * Free the structure used to store info used by ":for".
3294  */
3295     void
3296 free_for_info(fi_void)
3297     void *fi_void;
3298 {
3299     forinfo_T    *fi = (forinfo_T *)fi_void;
3300 
3301     if (fi != NULL && fi->fi_list != NULL)
3302     {
3303 	list_rem_watch(fi->fi_list, &fi->fi_lw);
3304 	list_unref(fi->fi_list);
3305     }
3306     vim_free(fi);
3307 }
3308 
3309 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3310 
3311     void
3312 set_context_for_expression(xp, arg, cmdidx)
3313     expand_T	*xp;
3314     char_u	*arg;
3315     cmdidx_T	cmdidx;
3316 {
3317     int		got_eq = FALSE;
3318     int		c;
3319     char_u	*p;
3320 
3321     if (cmdidx == CMD_let)
3322     {
3323 	xp->xp_context = EXPAND_USER_VARS;
3324 	if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3325 	{
3326 	    /* ":let var1 var2 ...": find last space. */
3327 	    for (p = arg + STRLEN(arg); p >= arg; )
3328 	    {
3329 		xp->xp_pattern = p;
3330 		mb_ptr_back(arg, p);
3331 		if (vim_iswhite(*p))
3332 		    break;
3333 	    }
3334 	    return;
3335 	}
3336     }
3337     else
3338 	xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3339 							  : EXPAND_EXPRESSION;
3340     while ((xp->xp_pattern = vim_strpbrk(arg,
3341 				  (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3342     {
3343 	c = *xp->xp_pattern;
3344 	if (c == '&')
3345 	{
3346 	    c = xp->xp_pattern[1];
3347 	    if (c == '&')
3348 	    {
3349 		++xp->xp_pattern;
3350 		xp->xp_context = cmdidx != CMD_let || got_eq
3351 					 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3352 	    }
3353 	    else if (c != ' ')
3354 	    {
3355 		xp->xp_context = EXPAND_SETTINGS;
3356 		if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3357 		    xp->xp_pattern += 2;
3358 
3359 	    }
3360 	}
3361 	else if (c == '$')
3362 	{
3363 	    /* environment variable */
3364 	    xp->xp_context = EXPAND_ENV_VARS;
3365 	}
3366 	else if (c == '=')
3367 	{
3368 	    got_eq = TRUE;
3369 	    xp->xp_context = EXPAND_EXPRESSION;
3370 	}
3371 	else if (c == '<'
3372 		&& xp->xp_context == EXPAND_FUNCTIONS
3373 		&& vim_strchr(xp->xp_pattern, '(') == NULL)
3374 	{
3375 	    /* Function name can start with "<SNR>" */
3376 	    break;
3377 	}
3378 	else if (cmdidx != CMD_let || got_eq)
3379 	{
3380 	    if (c == '"')	    /* string */
3381 	    {
3382 		while ((c = *++xp->xp_pattern) != NUL && c != '"')
3383 		    if (c == '\\' && xp->xp_pattern[1] != NUL)
3384 			++xp->xp_pattern;
3385 		xp->xp_context = EXPAND_NOTHING;
3386 	    }
3387 	    else if (c == '\'')	    /* literal string */
3388 	    {
3389 		/* Trick: '' is like stopping and starting a literal string. */
3390 		while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3391 		    /* skip */ ;
3392 		xp->xp_context = EXPAND_NOTHING;
3393 	    }
3394 	    else if (c == '|')
3395 	    {
3396 		if (xp->xp_pattern[1] == '|')
3397 		{
3398 		    ++xp->xp_pattern;
3399 		    xp->xp_context = EXPAND_EXPRESSION;
3400 		}
3401 		else
3402 		    xp->xp_context = EXPAND_COMMANDS;
3403 	    }
3404 	    else
3405 		xp->xp_context = EXPAND_EXPRESSION;
3406 	}
3407 	else
3408 	    /* Doesn't look like something valid, expand as an expression
3409 	     * anyway. */
3410 	    xp->xp_context = EXPAND_EXPRESSION;
3411 	arg = xp->xp_pattern;
3412 	if (*arg != NUL)
3413 	    while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3414 		/* skip */ ;
3415     }
3416     xp->xp_pattern = arg;
3417 }
3418 
3419 #endif /* FEAT_CMDL_COMPL */
3420 
3421 /*
3422  * ":1,25call func(arg1, arg2)"	function call.
3423  */
3424     void
3425 ex_call(eap)
3426     exarg_T	*eap;
3427 {
3428     char_u	*arg = eap->arg;
3429     char_u	*startarg;
3430     char_u	*name;
3431     char_u	*tofree;
3432     int		len;
3433     typval_T	rettv;
3434     linenr_T	lnum;
3435     int		doesrange;
3436     int		failed = FALSE;
3437     funcdict_T	fudi;
3438 
3439     if (eap->skip)
3440     {
3441 	/* trans_function_name() doesn't work well when skipping, use eval0()
3442 	 * instead to skip to any following command, e.g. for:
3443 	 *   :if 0 | call dict.foo().bar() | endif  */
3444 	++emsg_skip;
3445 	if (eval0(eap->arg, &rettv, &eap->nextcmd, FALSE) != FAIL)
3446 	    clear_tv(&rettv);
3447 	--emsg_skip;
3448 	return;
3449     }
3450 
3451     tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3452     if (fudi.fd_newkey != NULL)
3453     {
3454 	/* Still need to give an error message for missing key. */
3455 	EMSG2(_(e_dictkey), fudi.fd_newkey);
3456 	vim_free(fudi.fd_newkey);
3457     }
3458     if (tofree == NULL)
3459 	return;
3460 
3461     /* Increase refcount on dictionary, it could get deleted when evaluating
3462      * the arguments. */
3463     if (fudi.fd_dict != NULL)
3464 	++fudi.fd_dict->dv_refcount;
3465 
3466     /* If it is the name of a variable of type VAR_FUNC use its contents. */
3467     len = (int)STRLEN(tofree);
3468     name = deref_func_name(tofree, &len, FALSE);
3469 
3470     /* Skip white space to allow ":call func ()".  Not good, but required for
3471      * backward compatibility. */
3472     startarg = skipwhite(arg);
3473     rettv.v_type = VAR_UNKNOWN;	/* clear_tv() uses this */
3474 
3475     if (*startarg != '(')
3476     {
3477 	EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3478 	goto end;
3479     }
3480 
3481     /*
3482      * When skipping, evaluate the function once, to find the end of the
3483      * arguments.
3484      * When the function takes a range, this is discovered after the first
3485      * call, and the loop is broken.
3486      */
3487     if (eap->skip)
3488     {
3489 	++emsg_skip;
3490 	lnum = eap->line2;	/* do it once, also with an invalid range */
3491     }
3492     else
3493 	lnum = eap->line1;
3494     for ( ; lnum <= eap->line2; ++lnum)
3495     {
3496 	if (!eap->skip && eap->addr_count > 0)
3497 	{
3498 	    curwin->w_cursor.lnum = lnum;
3499 	    curwin->w_cursor.col = 0;
3500 #ifdef FEAT_VIRTUALEDIT
3501 	    curwin->w_cursor.coladd = 0;
3502 #endif
3503 	}
3504 	arg = startarg;
3505 	if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3506 		    eap->line1, eap->line2, &doesrange,
3507 					    !eap->skip, fudi.fd_dict) == FAIL)
3508 	{
3509 	    failed = TRUE;
3510 	    break;
3511 	}
3512 
3513 	/* Handle a function returning a Funcref, Dictionary or List. */
3514 	if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3515 	{
3516 	    failed = TRUE;
3517 	    break;
3518 	}
3519 
3520 	clear_tv(&rettv);
3521 	if (doesrange || eap->skip)
3522 	    break;
3523 
3524 	/* Stop when immediately aborting on error, or when an interrupt
3525 	 * occurred or an exception was thrown but not caught.
3526 	 * get_func_tv() returned OK, so that the check for trailing
3527 	 * characters below is executed. */
3528 	if (aborting())
3529 	    break;
3530     }
3531     if (eap->skip)
3532 	--emsg_skip;
3533 
3534     if (!failed)
3535     {
3536 	/* Check for trailing illegal characters and a following command. */
3537 	if (!ends_excmd(*arg))
3538 	{
3539 	    emsg_severe = TRUE;
3540 	    EMSG(_(e_trailing));
3541 	}
3542 	else
3543 	    eap->nextcmd = check_nextcmd(arg);
3544     }
3545 
3546 end:
3547     dict_unref(fudi.fd_dict);
3548     vim_free(tofree);
3549 }
3550 
3551 /*
3552  * ":unlet[!] var1 ... " command.
3553  */
3554     void
3555 ex_unlet(eap)
3556     exarg_T	*eap;
3557 {
3558     ex_unletlock(eap, eap->arg, 0);
3559 }
3560 
3561 /*
3562  * ":lockvar" and ":unlockvar" commands
3563  */
3564     void
3565 ex_lockvar(eap)
3566     exarg_T	*eap;
3567 {
3568     char_u	*arg = eap->arg;
3569     int		deep = 2;
3570 
3571     if (eap->forceit)
3572 	deep = -1;
3573     else if (vim_isdigit(*arg))
3574     {
3575 	deep = getdigits(&arg);
3576 	arg = skipwhite(arg);
3577     }
3578 
3579     ex_unletlock(eap, arg, deep);
3580 }
3581 
3582 /*
3583  * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3584  */
3585     static void
3586 ex_unletlock(eap, argstart, deep)
3587     exarg_T	*eap;
3588     char_u	*argstart;
3589     int		deep;
3590 {
3591     char_u	*arg = argstart;
3592     char_u	*name_end;
3593     int		error = FALSE;
3594     lval_T	lv;
3595 
3596     do
3597     {
3598 	/* Parse the name and find the end. */
3599 	name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, 0,
3600 							     FNE_CHECK_START);
3601 	if (lv.ll_name == NULL)
3602 	    error = TRUE;	    /* error but continue parsing */
3603 	if (name_end == NULL || (!vim_iswhite(*name_end)
3604 						   && !ends_excmd(*name_end)))
3605 	{
3606 	    if (name_end != NULL)
3607 	    {
3608 		emsg_severe = TRUE;
3609 		EMSG(_(e_trailing));
3610 	    }
3611 	    if (!(eap->skip || error))
3612 		clear_lval(&lv);
3613 	    break;
3614 	}
3615 
3616 	if (!error && !eap->skip)
3617 	{
3618 	    if (eap->cmdidx == CMD_unlet)
3619 	    {
3620 		if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3621 		    error = TRUE;
3622 	    }
3623 	    else
3624 	    {
3625 		if (do_lock_var(&lv, name_end, deep,
3626 					  eap->cmdidx == CMD_lockvar) == FAIL)
3627 		    error = TRUE;
3628 	    }
3629 	}
3630 
3631 	if (!eap->skip)
3632 	    clear_lval(&lv);
3633 
3634 	arg = skipwhite(name_end);
3635     } while (!ends_excmd(*arg));
3636 
3637     eap->nextcmd = check_nextcmd(arg);
3638 }
3639 
3640     static int
3641 do_unlet_var(lp, name_end, forceit)
3642     lval_T	*lp;
3643     char_u	*name_end;
3644     int		forceit;
3645 {
3646     int		ret = OK;
3647     int		cc;
3648 
3649     if (lp->ll_tv == NULL)
3650     {
3651 	cc = *name_end;
3652 	*name_end = NUL;
3653 
3654 	/* Normal name or expanded name. */
3655 	if (check_changedtick(lp->ll_name))
3656 	    ret = FAIL;
3657 	else if (do_unlet(lp->ll_name, forceit) == FAIL)
3658 	    ret = FAIL;
3659 	*name_end = cc;
3660     }
3661     else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3662 	return FAIL;
3663     else if (lp->ll_range)
3664     {
3665 	listitem_T    *li;
3666 	listitem_T    *ll_li = lp->ll_li;
3667 	int           ll_n1 = lp->ll_n1;
3668 
3669 	while (ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= ll_n1))
3670 	{
3671 	    li = ll_li->li_next;
3672 	    if (tv_check_lock(ll_li->li_tv.v_lock, lp->ll_name))
3673 		return FAIL;
3674 	    ll_li = li;
3675 	    ++ll_n1;
3676 	}
3677 
3678 	/* Delete a range of List items. */
3679 	while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3680 	{
3681 	    li = lp->ll_li->li_next;
3682 	    listitem_remove(lp->ll_list, lp->ll_li);
3683 	    lp->ll_li = li;
3684 	    ++lp->ll_n1;
3685 	}
3686     }
3687     else
3688     {
3689 	if (lp->ll_list != NULL)
3690 	    /* unlet a List item. */
3691 	    listitem_remove(lp->ll_list, lp->ll_li);
3692 	else
3693 	    /* unlet a Dictionary item. */
3694 	    dictitem_remove(lp->ll_dict, lp->ll_di);
3695     }
3696 
3697     return ret;
3698 }
3699 
3700 /*
3701  * "unlet" a variable.  Return OK if it existed, FAIL if not.
3702  * When "forceit" is TRUE don't complain if the variable doesn't exist.
3703  */
3704     int
3705 do_unlet(name, forceit)
3706     char_u	*name;
3707     int		forceit;
3708 {
3709     hashtab_T	*ht;
3710     hashitem_T	*hi;
3711     char_u	*varname;
3712     dictitem_T	*di;
3713 
3714     ht = find_var_ht(name, &varname);
3715     if (ht != NULL && *varname != NUL)
3716     {
3717 	hi = hash_find(ht, varname);
3718 	if (!HASHITEM_EMPTY(hi))
3719 	{
3720 	    di = HI2DI(hi);
3721 	    if (var_check_fixed(di->di_flags, name)
3722 		    || var_check_ro(di->di_flags, name))
3723 		return FAIL;
3724 	    delete_var(ht, hi);
3725 	    return OK;
3726 	}
3727     }
3728     if (forceit)
3729 	return OK;
3730     EMSG2(_("E108: No such variable: \"%s\""), name);
3731     return FAIL;
3732 }
3733 
3734 /*
3735  * Lock or unlock variable indicated by "lp".
3736  * "deep" is the levels to go (-1 for unlimited);
3737  * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3738  */
3739     static int
3740 do_lock_var(lp, name_end, deep, lock)
3741     lval_T	*lp;
3742     char_u	*name_end;
3743     int		deep;
3744     int		lock;
3745 {
3746     int		ret = OK;
3747     int		cc;
3748     dictitem_T	*di;
3749 
3750     if (deep == 0)	/* nothing to do */
3751 	return OK;
3752 
3753     if (lp->ll_tv == NULL)
3754     {
3755 	cc = *name_end;
3756 	*name_end = NUL;
3757 
3758 	/* Normal name or expanded name. */
3759 	if (check_changedtick(lp->ll_name))
3760 	    ret = FAIL;
3761 	else
3762 	{
3763 	    di = find_var(lp->ll_name, NULL, TRUE);
3764 	    if (di == NULL)
3765 		ret = FAIL;
3766 	    else
3767 	    {
3768 		if (lock)
3769 		    di->di_flags |= DI_FLAGS_LOCK;
3770 		else
3771 		    di->di_flags &= ~DI_FLAGS_LOCK;
3772 		item_lock(&di->di_tv, deep, lock);
3773 	    }
3774 	}
3775 	*name_end = cc;
3776     }
3777     else if (lp->ll_range)
3778     {
3779 	listitem_T    *li = lp->ll_li;
3780 
3781 	/* (un)lock a range of List items. */
3782 	while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3783 	{
3784 	    item_lock(&li->li_tv, deep, lock);
3785 	    li = li->li_next;
3786 	    ++lp->ll_n1;
3787 	}
3788     }
3789     else if (lp->ll_list != NULL)
3790 	/* (un)lock a List item. */
3791 	item_lock(&lp->ll_li->li_tv, deep, lock);
3792     else
3793 	/* un(lock) a Dictionary item. */
3794 	item_lock(&lp->ll_di->di_tv, deep, lock);
3795 
3796     return ret;
3797 }
3798 
3799 /*
3800  * Lock or unlock an item.  "deep" is nr of levels to go.
3801  */
3802     static void
3803 item_lock(tv, deep, lock)
3804     typval_T	*tv;
3805     int		deep;
3806     int		lock;
3807 {
3808     static int	recurse = 0;
3809     list_T	*l;
3810     listitem_T	*li;
3811     dict_T	*d;
3812     hashitem_T	*hi;
3813     int		todo;
3814 
3815     if (recurse >= DICT_MAXNEST)
3816     {
3817 	EMSG(_("E743: variable nested too deep for (un)lock"));
3818 	return;
3819     }
3820     if (deep == 0)
3821 	return;
3822     ++recurse;
3823 
3824     /* lock/unlock the item itself */
3825     if (lock)
3826 	tv->v_lock |= VAR_LOCKED;
3827     else
3828 	tv->v_lock &= ~VAR_LOCKED;
3829 
3830     switch (tv->v_type)
3831     {
3832 	case VAR_LIST:
3833 	    if ((l = tv->vval.v_list) != NULL)
3834 	    {
3835 		if (lock)
3836 		    l->lv_lock |= VAR_LOCKED;
3837 		else
3838 		    l->lv_lock &= ~VAR_LOCKED;
3839 		if (deep < 0 || deep > 1)
3840 		    /* recursive: lock/unlock the items the List contains */
3841 		    for (li = l->lv_first; li != NULL; li = li->li_next)
3842 			item_lock(&li->li_tv, deep - 1, lock);
3843 	    }
3844 	    break;
3845 	case VAR_DICT:
3846 	    if ((d = tv->vval.v_dict) != NULL)
3847 	    {
3848 		if (lock)
3849 		    d->dv_lock |= VAR_LOCKED;
3850 		else
3851 		    d->dv_lock &= ~VAR_LOCKED;
3852 		if (deep < 0 || deep > 1)
3853 		{
3854 		    /* recursive: lock/unlock the items the List contains */
3855 		    todo = (int)d->dv_hashtab.ht_used;
3856 		    for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3857 		    {
3858 			if (!HASHITEM_EMPTY(hi))
3859 			{
3860 			    --todo;
3861 			    item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3862 			}
3863 		    }
3864 		}
3865 	    }
3866     }
3867     --recurse;
3868 }
3869 
3870 /*
3871  * Return TRUE if typeval "tv" is locked: Either that value is locked itself
3872  * or it refers to a List or Dictionary that is locked.
3873  */
3874     static int
3875 tv_islocked(tv)
3876     typval_T	*tv;
3877 {
3878     return (tv->v_lock & VAR_LOCKED)
3879 	|| (tv->v_type == VAR_LIST
3880 		&& tv->vval.v_list != NULL
3881 		&& (tv->vval.v_list->lv_lock & VAR_LOCKED))
3882 	|| (tv->v_type == VAR_DICT
3883 		&& tv->vval.v_dict != NULL
3884 		&& (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3885 }
3886 
3887 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3888 /*
3889  * Delete all "menutrans_" variables.
3890  */
3891     void
3892 del_menutrans_vars()
3893 {
3894     hashitem_T	*hi;
3895     int		todo;
3896 
3897     hash_lock(&globvarht);
3898     todo = (int)globvarht.ht_used;
3899     for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3900     {
3901 	if (!HASHITEM_EMPTY(hi))
3902 	{
3903 	    --todo;
3904 	    if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3905 		delete_var(&globvarht, hi);
3906 	}
3907     }
3908     hash_unlock(&globvarht);
3909 }
3910 #endif
3911 
3912 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3913 
3914 /*
3915  * Local string buffer for the next two functions to store a variable name
3916  * with its prefix. Allocated in cat_prefix_varname(), freed later in
3917  * get_user_var_name().
3918  */
3919 
3920 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3921 
3922 static char_u	*varnamebuf = NULL;
3923 static int	varnamebuflen = 0;
3924 
3925 /*
3926  * Function to concatenate a prefix and a variable name.
3927  */
3928     static char_u *
3929 cat_prefix_varname(prefix, name)
3930     int		prefix;
3931     char_u	*name;
3932 {
3933     int		len;
3934 
3935     len = (int)STRLEN(name) + 3;
3936     if (len > varnamebuflen)
3937     {
3938 	vim_free(varnamebuf);
3939 	len += 10;			/* some additional space */
3940 	varnamebuf = alloc(len);
3941 	if (varnamebuf == NULL)
3942 	{
3943 	    varnamebuflen = 0;
3944 	    return NULL;
3945 	}
3946 	varnamebuflen = len;
3947     }
3948     *varnamebuf = prefix;
3949     varnamebuf[1] = ':';
3950     STRCPY(varnamebuf + 2, name);
3951     return varnamebuf;
3952 }
3953 
3954 /*
3955  * Function given to ExpandGeneric() to obtain the list of user defined
3956  * (global/buffer/window/built-in) variable names.
3957  */
3958     char_u *
3959 get_user_var_name(xp, idx)
3960     expand_T	*xp;
3961     int		idx;
3962 {
3963     static long_u	gdone;
3964     static long_u	bdone;
3965     static long_u	wdone;
3966 #ifdef FEAT_WINDOWS
3967     static long_u	tdone;
3968 #endif
3969     static int		vidx;
3970     static hashitem_T	*hi;
3971     hashtab_T		*ht;
3972 
3973     if (idx == 0)
3974     {
3975 	gdone = bdone = wdone = vidx = 0;
3976 #ifdef FEAT_WINDOWS
3977 	tdone = 0;
3978 #endif
3979     }
3980 
3981     /* Global variables */
3982     if (gdone < globvarht.ht_used)
3983     {
3984 	if (gdone++ == 0)
3985 	    hi = globvarht.ht_array;
3986 	else
3987 	    ++hi;
3988 	while (HASHITEM_EMPTY(hi))
3989 	    ++hi;
3990 	if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3991 	    return cat_prefix_varname('g', hi->hi_key);
3992 	return hi->hi_key;
3993     }
3994 
3995     /* b: variables */
3996     ht = &curbuf->b_vars->dv_hashtab;
3997     if (bdone < ht->ht_used)
3998     {
3999 	if (bdone++ == 0)
4000 	    hi = ht->ht_array;
4001 	else
4002 	    ++hi;
4003 	while (HASHITEM_EMPTY(hi))
4004 	    ++hi;
4005 	return cat_prefix_varname('b', hi->hi_key);
4006     }
4007     if (bdone == ht->ht_used)
4008     {
4009 	++bdone;
4010 	return (char_u *)"b:changedtick";
4011     }
4012 
4013     /* w: variables */
4014     ht = &curwin->w_vars->dv_hashtab;
4015     if (wdone < ht->ht_used)
4016     {
4017 	if (wdone++ == 0)
4018 	    hi = ht->ht_array;
4019 	else
4020 	    ++hi;
4021 	while (HASHITEM_EMPTY(hi))
4022 	    ++hi;
4023 	return cat_prefix_varname('w', hi->hi_key);
4024     }
4025 
4026 #ifdef FEAT_WINDOWS
4027     /* t: variables */
4028     ht = &curtab->tp_vars->dv_hashtab;
4029     if (tdone < ht->ht_used)
4030     {
4031 	if (tdone++ == 0)
4032 	    hi = ht->ht_array;
4033 	else
4034 	    ++hi;
4035 	while (HASHITEM_EMPTY(hi))
4036 	    ++hi;
4037 	return cat_prefix_varname('t', hi->hi_key);
4038     }
4039 #endif
4040 
4041     /* v: variables */
4042     if (vidx < VV_LEN)
4043 	return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
4044 
4045     vim_free(varnamebuf);
4046     varnamebuf = NULL;
4047     varnamebuflen = 0;
4048     return NULL;
4049 }
4050 
4051 #endif /* FEAT_CMDL_COMPL */
4052 
4053 /*
4054  * types for expressions.
4055  */
4056 typedef enum
4057 {
4058     TYPE_UNKNOWN = 0
4059     , TYPE_EQUAL	/* == */
4060     , TYPE_NEQUAL	/* != */
4061     , TYPE_GREATER	/* >  */
4062     , TYPE_GEQUAL	/* >= */
4063     , TYPE_SMALLER	/* <  */
4064     , TYPE_SEQUAL	/* <= */
4065     , TYPE_MATCH	/* =~ */
4066     , TYPE_NOMATCH	/* !~ */
4067 } exptype_T;
4068 
4069 /*
4070  * The "evaluate" argument: When FALSE, the argument is only parsed but not
4071  * executed.  The function may return OK, but the rettv will be of type
4072  * VAR_UNKNOWN.  The function still returns FAIL for a syntax error.
4073  */
4074 
4075 /*
4076  * Handle zero level expression.
4077  * This calls eval1() and handles error message and nextcmd.
4078  * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
4079  * Note: "rettv.v_lock" is not set.
4080  * Return OK or FAIL.
4081  */
4082     static int
4083 eval0(arg, rettv, nextcmd, evaluate)
4084     char_u	*arg;
4085     typval_T	*rettv;
4086     char_u	**nextcmd;
4087     int		evaluate;
4088 {
4089     int		ret;
4090     char_u	*p;
4091 
4092     p = skipwhite(arg);
4093     ret = eval1(&p, rettv, evaluate);
4094     if (ret == FAIL || !ends_excmd(*p))
4095     {
4096 	if (ret != FAIL)
4097 	    clear_tv(rettv);
4098 	/*
4099 	 * Report the invalid expression unless the expression evaluation has
4100 	 * been cancelled due to an aborting error, an interrupt, or an
4101 	 * exception.
4102 	 */
4103 	if (!aborting())
4104 	    EMSG2(_(e_invexpr2), arg);
4105 	ret = FAIL;
4106     }
4107     if (nextcmd != NULL)
4108 	*nextcmd = check_nextcmd(p);
4109 
4110     return ret;
4111 }
4112 
4113 /*
4114  * Handle top level expression:
4115  *	expr2 ? expr1 : expr1
4116  *
4117  * "arg" must point to the first non-white of the expression.
4118  * "arg" is advanced to the next non-white after the recognized expression.
4119  *
4120  * Note: "rettv.v_lock" is not set.
4121  *
4122  * Return OK or FAIL.
4123  */
4124     static int
4125 eval1(arg, rettv, evaluate)
4126     char_u	**arg;
4127     typval_T	*rettv;
4128     int		evaluate;
4129 {
4130     int		result;
4131     typval_T	var2;
4132 
4133     /*
4134      * Get the first variable.
4135      */
4136     if (eval2(arg, rettv, evaluate) == FAIL)
4137 	return FAIL;
4138 
4139     if ((*arg)[0] == '?')
4140     {
4141 	result = FALSE;
4142 	if (evaluate)
4143 	{
4144 	    int		error = FALSE;
4145 
4146 	    if (get_tv_number_chk(rettv, &error) != 0)
4147 		result = TRUE;
4148 	    clear_tv(rettv);
4149 	    if (error)
4150 		return FAIL;
4151 	}
4152 
4153 	/*
4154 	 * Get the second variable.
4155 	 */
4156 	*arg = skipwhite(*arg + 1);
4157 	if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
4158 	    return FAIL;
4159 
4160 	/*
4161 	 * Check for the ":".
4162 	 */
4163 	if ((*arg)[0] != ':')
4164 	{
4165 	    EMSG(_("E109: Missing ':' after '?'"));
4166 	    if (evaluate && result)
4167 		clear_tv(rettv);
4168 	    return FAIL;
4169 	}
4170 
4171 	/*
4172 	 * Get the third variable.
4173 	 */
4174 	*arg = skipwhite(*arg + 1);
4175 	if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
4176 	{
4177 	    if (evaluate && result)
4178 		clear_tv(rettv);
4179 	    return FAIL;
4180 	}
4181 	if (evaluate && !result)
4182 	    *rettv = var2;
4183     }
4184 
4185     return OK;
4186 }
4187 
4188 /*
4189  * Handle first level expression:
4190  *	expr2 || expr2 || expr2	    logical OR
4191  *
4192  * "arg" must point to the first non-white of the expression.
4193  * "arg" is advanced to the next non-white after the recognized expression.
4194  *
4195  * Return OK or FAIL.
4196  */
4197     static int
4198 eval2(arg, rettv, evaluate)
4199     char_u	**arg;
4200     typval_T	*rettv;
4201     int		evaluate;
4202 {
4203     typval_T	var2;
4204     long	result;
4205     int		first;
4206     int		error = FALSE;
4207 
4208     /*
4209      * Get the first variable.
4210      */
4211     if (eval3(arg, rettv, evaluate) == FAIL)
4212 	return FAIL;
4213 
4214     /*
4215      * Repeat until there is no following "||".
4216      */
4217     first = TRUE;
4218     result = FALSE;
4219     while ((*arg)[0] == '|' && (*arg)[1] == '|')
4220     {
4221 	if (evaluate && first)
4222 	{
4223 	    if (get_tv_number_chk(rettv, &error) != 0)
4224 		result = TRUE;
4225 	    clear_tv(rettv);
4226 	    if (error)
4227 		return FAIL;
4228 	    first = FALSE;
4229 	}
4230 
4231 	/*
4232 	 * Get the second variable.
4233 	 */
4234 	*arg = skipwhite(*arg + 2);
4235 	if (eval3(arg, &var2, evaluate && !result) == FAIL)
4236 	    return FAIL;
4237 
4238 	/*
4239 	 * Compute the result.
4240 	 */
4241 	if (evaluate && !result)
4242 	{
4243 	    if (get_tv_number_chk(&var2, &error) != 0)
4244 		result = TRUE;
4245 	    clear_tv(&var2);
4246 	    if (error)
4247 		return FAIL;
4248 	}
4249 	if (evaluate)
4250 	{
4251 	    rettv->v_type = VAR_NUMBER;
4252 	    rettv->vval.v_number = result;
4253 	}
4254     }
4255 
4256     return OK;
4257 }
4258 
4259 /*
4260  * Handle second level expression:
4261  *	expr3 && expr3 && expr3	    logical AND
4262  *
4263  * "arg" must point to the first non-white of the expression.
4264  * "arg" is advanced to the next non-white after the recognized expression.
4265  *
4266  * Return OK or FAIL.
4267  */
4268     static int
4269 eval3(arg, rettv, evaluate)
4270     char_u	**arg;
4271     typval_T	*rettv;
4272     int		evaluate;
4273 {
4274     typval_T	var2;
4275     long	result;
4276     int		first;
4277     int		error = FALSE;
4278 
4279     /*
4280      * Get the first variable.
4281      */
4282     if (eval4(arg, rettv, evaluate) == FAIL)
4283 	return FAIL;
4284 
4285     /*
4286      * Repeat until there is no following "&&".
4287      */
4288     first = TRUE;
4289     result = TRUE;
4290     while ((*arg)[0] == '&' && (*arg)[1] == '&')
4291     {
4292 	if (evaluate && first)
4293 	{
4294 	    if (get_tv_number_chk(rettv, &error) == 0)
4295 		result = FALSE;
4296 	    clear_tv(rettv);
4297 	    if (error)
4298 		return FAIL;
4299 	    first = FALSE;
4300 	}
4301 
4302 	/*
4303 	 * Get the second variable.
4304 	 */
4305 	*arg = skipwhite(*arg + 2);
4306 	if (eval4(arg, &var2, evaluate && result) == FAIL)
4307 	    return FAIL;
4308 
4309 	/*
4310 	 * Compute the result.
4311 	 */
4312 	if (evaluate && result)
4313 	{
4314 	    if (get_tv_number_chk(&var2, &error) == 0)
4315 		result = FALSE;
4316 	    clear_tv(&var2);
4317 	    if (error)
4318 		return FAIL;
4319 	}
4320 	if (evaluate)
4321 	{
4322 	    rettv->v_type = VAR_NUMBER;
4323 	    rettv->vval.v_number = result;
4324 	}
4325     }
4326 
4327     return OK;
4328 }
4329 
4330 /*
4331  * Handle third level expression:
4332  *	var1 == var2
4333  *	var1 =~ var2
4334  *	var1 != var2
4335  *	var1 !~ var2
4336  *	var1 > var2
4337  *	var1 >= var2
4338  *	var1 < var2
4339  *	var1 <= var2
4340  *	var1 is var2
4341  *	var1 isnot var2
4342  *
4343  * "arg" must point to the first non-white of the expression.
4344  * "arg" is advanced to the next non-white after the recognized expression.
4345  *
4346  * Return OK or FAIL.
4347  */
4348     static int
4349 eval4(arg, rettv, evaluate)
4350     char_u	**arg;
4351     typval_T	*rettv;
4352     int		evaluate;
4353 {
4354     typval_T	var2;
4355     char_u	*p;
4356     int		i;
4357     exptype_T	type = TYPE_UNKNOWN;
4358     int		type_is = FALSE;    /* TRUE for "is" and "isnot" */
4359     int		len = 2;
4360     long	n1, n2;
4361     char_u	*s1, *s2;
4362     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4363     regmatch_T	regmatch;
4364     int		ic;
4365     char_u	*save_cpo;
4366 
4367     /*
4368      * Get the first variable.
4369      */
4370     if (eval5(arg, rettv, evaluate) == FAIL)
4371 	return FAIL;
4372 
4373     p = *arg;
4374     switch (p[0])
4375     {
4376 	case '=':   if (p[1] == '=')
4377 			type = TYPE_EQUAL;
4378 		    else if (p[1] == '~')
4379 			type = TYPE_MATCH;
4380 		    break;
4381 	case '!':   if (p[1] == '=')
4382 			type = TYPE_NEQUAL;
4383 		    else if (p[1] == '~')
4384 			type = TYPE_NOMATCH;
4385 		    break;
4386 	case '>':   if (p[1] != '=')
4387 		    {
4388 			type = TYPE_GREATER;
4389 			len = 1;
4390 		    }
4391 		    else
4392 			type = TYPE_GEQUAL;
4393 		    break;
4394 	case '<':   if (p[1] != '=')
4395 		    {
4396 			type = TYPE_SMALLER;
4397 			len = 1;
4398 		    }
4399 		    else
4400 			type = TYPE_SEQUAL;
4401 		    break;
4402 	case 'i':   if (p[1] == 's')
4403 		    {
4404 			if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4405 			    len = 5;
4406 			if (!vim_isIDc(p[len]))
4407 			{
4408 			    type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4409 			    type_is = TRUE;
4410 			}
4411 		    }
4412 		    break;
4413     }
4414 
4415     /*
4416      * If there is a comparative operator, use it.
4417      */
4418     if (type != TYPE_UNKNOWN)
4419     {
4420 	/* extra question mark appended: ignore case */
4421 	if (p[len] == '?')
4422 	{
4423 	    ic = TRUE;
4424 	    ++len;
4425 	}
4426 	/* extra '#' appended: match case */
4427 	else if (p[len] == '#')
4428 	{
4429 	    ic = FALSE;
4430 	    ++len;
4431 	}
4432 	/* nothing appended: use 'ignorecase' */
4433 	else
4434 	    ic = p_ic;
4435 
4436 	/*
4437 	 * Get the second variable.
4438 	 */
4439 	*arg = skipwhite(p + len);
4440 	if (eval5(arg, &var2, evaluate) == FAIL)
4441 	{
4442 	    clear_tv(rettv);
4443 	    return FAIL;
4444 	}
4445 
4446 	if (evaluate)
4447 	{
4448 	    if (type_is && rettv->v_type != var2.v_type)
4449 	    {
4450 		/* For "is" a different type always means FALSE, for "notis"
4451 		 * it means TRUE. */
4452 		n1 = (type == TYPE_NEQUAL);
4453 	    }
4454 	    else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4455 	    {
4456 		if (type_is)
4457 		{
4458 		    n1 = (rettv->v_type == var2.v_type
4459 				   && rettv->vval.v_list == var2.vval.v_list);
4460 		    if (type == TYPE_NEQUAL)
4461 			n1 = !n1;
4462 		}
4463 		else if (rettv->v_type != var2.v_type
4464 			|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4465 		{
4466 		    if (rettv->v_type != var2.v_type)
4467 			EMSG(_("E691: Can only compare List with List"));
4468 		    else
4469 			EMSG(_("E692: Invalid operation for List"));
4470 		    clear_tv(rettv);
4471 		    clear_tv(&var2);
4472 		    return FAIL;
4473 		}
4474 		else
4475 		{
4476 		    /* Compare two Lists for being equal or unequal. */
4477 		    n1 = list_equal(rettv->vval.v_list, var2.vval.v_list,
4478 								   ic, FALSE);
4479 		    if (type == TYPE_NEQUAL)
4480 			n1 = !n1;
4481 		}
4482 	    }
4483 
4484 	    else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4485 	    {
4486 		if (type_is)
4487 		{
4488 		    n1 = (rettv->v_type == var2.v_type
4489 				   && rettv->vval.v_dict == var2.vval.v_dict);
4490 		    if (type == TYPE_NEQUAL)
4491 			n1 = !n1;
4492 		}
4493 		else if (rettv->v_type != var2.v_type
4494 			|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4495 		{
4496 		    if (rettv->v_type != var2.v_type)
4497 			EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4498 		    else
4499 			EMSG(_("E736: Invalid operation for Dictionary"));
4500 		    clear_tv(rettv);
4501 		    clear_tv(&var2);
4502 		    return FAIL;
4503 		}
4504 		else
4505 		{
4506 		    /* Compare two Dictionaries for being equal or unequal. */
4507 		    n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict,
4508 								   ic, FALSE);
4509 		    if (type == TYPE_NEQUAL)
4510 			n1 = !n1;
4511 		}
4512 	    }
4513 
4514 	    else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4515 	    {
4516 		if (rettv->v_type != var2.v_type
4517 			|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4518 		{
4519 		    if (rettv->v_type != var2.v_type)
4520 			EMSG(_("E693: Can only compare Funcref with Funcref"));
4521 		    else
4522 			EMSG(_("E694: Invalid operation for Funcrefs"));
4523 		    clear_tv(rettv);
4524 		    clear_tv(&var2);
4525 		    return FAIL;
4526 		}
4527 		else
4528 		{
4529 		    /* Compare two Funcrefs for being equal or unequal. */
4530 		    if (rettv->vval.v_string == NULL
4531 						|| var2.vval.v_string == NULL)
4532 			n1 = FALSE;
4533 		    else
4534 			n1 = STRCMP(rettv->vval.v_string,
4535 						     var2.vval.v_string) == 0;
4536 		    if (type == TYPE_NEQUAL)
4537 			n1 = !n1;
4538 		}
4539 	    }
4540 
4541 #ifdef FEAT_FLOAT
4542 	    /*
4543 	     * If one of the two variables is a float, compare as a float.
4544 	     * When using "=~" or "!~", always compare as string.
4545 	     */
4546 	    else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4547 		    && type != TYPE_MATCH && type != TYPE_NOMATCH)
4548 	    {
4549 		float_T f1, f2;
4550 
4551 		if (rettv->v_type == VAR_FLOAT)
4552 		    f1 = rettv->vval.v_float;
4553 		else
4554 		    f1 = get_tv_number(rettv);
4555 		if (var2.v_type == VAR_FLOAT)
4556 		    f2 = var2.vval.v_float;
4557 		else
4558 		    f2 = get_tv_number(&var2);
4559 		n1 = FALSE;
4560 		switch (type)
4561 		{
4562 		    case TYPE_EQUAL:    n1 = (f1 == f2); break;
4563 		    case TYPE_NEQUAL:   n1 = (f1 != f2); break;
4564 		    case TYPE_GREATER:  n1 = (f1 > f2); break;
4565 		    case TYPE_GEQUAL:   n1 = (f1 >= f2); break;
4566 		    case TYPE_SMALLER:  n1 = (f1 < f2); break;
4567 		    case TYPE_SEQUAL:   n1 = (f1 <= f2); break;
4568 		    case TYPE_UNKNOWN:
4569 		    case TYPE_MATCH:
4570 		    case TYPE_NOMATCH:  break;  /* avoid gcc warning */
4571 		}
4572 	    }
4573 #endif
4574 
4575 	    /*
4576 	     * If one of the two variables is a number, compare as a number.
4577 	     * When using "=~" or "!~", always compare as string.
4578 	     */
4579 	    else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4580 		    && type != TYPE_MATCH && type != TYPE_NOMATCH)
4581 	    {
4582 		n1 = get_tv_number(rettv);
4583 		n2 = get_tv_number(&var2);
4584 		switch (type)
4585 		{
4586 		    case TYPE_EQUAL:    n1 = (n1 == n2); break;
4587 		    case TYPE_NEQUAL:   n1 = (n1 != n2); break;
4588 		    case TYPE_GREATER:  n1 = (n1 > n2); break;
4589 		    case TYPE_GEQUAL:   n1 = (n1 >= n2); break;
4590 		    case TYPE_SMALLER:  n1 = (n1 < n2); break;
4591 		    case TYPE_SEQUAL:   n1 = (n1 <= n2); break;
4592 		    case TYPE_UNKNOWN:
4593 		    case TYPE_MATCH:
4594 		    case TYPE_NOMATCH:  break;  /* avoid gcc warning */
4595 		}
4596 	    }
4597 	    else
4598 	    {
4599 		s1 = get_tv_string_buf(rettv, buf1);
4600 		s2 = get_tv_string_buf(&var2, buf2);
4601 		if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4602 		    i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4603 		else
4604 		    i = 0;
4605 		n1 = FALSE;
4606 		switch (type)
4607 		{
4608 		    case TYPE_EQUAL:    n1 = (i == 0); break;
4609 		    case TYPE_NEQUAL:   n1 = (i != 0); break;
4610 		    case TYPE_GREATER:  n1 = (i > 0); break;
4611 		    case TYPE_GEQUAL:   n1 = (i >= 0); break;
4612 		    case TYPE_SMALLER:  n1 = (i < 0); break;
4613 		    case TYPE_SEQUAL:   n1 = (i <= 0); break;
4614 
4615 		    case TYPE_MATCH:
4616 		    case TYPE_NOMATCH:
4617 			    /* avoid 'l' flag in 'cpoptions' */
4618 			    save_cpo = p_cpo;
4619 			    p_cpo = (char_u *)"";
4620 			    regmatch.regprog = vim_regcomp(s2,
4621 							RE_MAGIC + RE_STRING);
4622 			    regmatch.rm_ic = ic;
4623 			    if (regmatch.regprog != NULL)
4624 			    {
4625 				n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4626 				vim_regfree(regmatch.regprog);
4627 				if (type == TYPE_NOMATCH)
4628 				    n1 = !n1;
4629 			    }
4630 			    p_cpo = save_cpo;
4631 			    break;
4632 
4633 		    case TYPE_UNKNOWN:  break;  /* avoid gcc warning */
4634 		}
4635 	    }
4636 	    clear_tv(rettv);
4637 	    clear_tv(&var2);
4638 	    rettv->v_type = VAR_NUMBER;
4639 	    rettv->vval.v_number = n1;
4640 	}
4641     }
4642 
4643     return OK;
4644 }
4645 
4646 /*
4647  * Handle fourth level expression:
4648  *	+	number addition
4649  *	-	number subtraction
4650  *	.	string concatenation
4651  *
4652  * "arg" must point to the first non-white of the expression.
4653  * "arg" is advanced to the next non-white after the recognized expression.
4654  *
4655  * Return OK or FAIL.
4656  */
4657     static int
4658 eval5(arg, rettv, evaluate)
4659     char_u	**arg;
4660     typval_T	*rettv;
4661     int		evaluate;
4662 {
4663     typval_T	var2;
4664     typval_T	var3;
4665     int		op;
4666     long	n1, n2;
4667 #ifdef FEAT_FLOAT
4668     float_T	f1 = 0, f2 = 0;
4669 #endif
4670     char_u	*s1, *s2;
4671     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4672     char_u	*p;
4673 
4674     /*
4675      * Get the first variable.
4676      */
4677     if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4678 	return FAIL;
4679 
4680     /*
4681      * Repeat computing, until no '+', '-' or '.' is following.
4682      */
4683     for (;;)
4684     {
4685 	op = **arg;
4686 	if (op != '+' && op != '-' && op != '.')
4687 	    break;
4688 
4689 	if ((op != '+' || rettv->v_type != VAR_LIST)
4690 #ifdef FEAT_FLOAT
4691 		&& (op == '.' || rettv->v_type != VAR_FLOAT)
4692 #endif
4693 		)
4694 	{
4695 	    /* For "list + ...", an illegal use of the first operand as
4696 	     * a number cannot be determined before evaluating the 2nd
4697 	     * operand: if this is also a list, all is ok.
4698 	     * For "something . ...", "something - ..." or "non-list + ...",
4699 	     * we know that the first operand needs to be a string or number
4700 	     * without evaluating the 2nd operand.  So check before to avoid
4701 	     * side effects after an error. */
4702 	    if (evaluate && get_tv_string_chk(rettv) == NULL)
4703 	    {
4704 		clear_tv(rettv);
4705 		return FAIL;
4706 	    }
4707 	}
4708 
4709 	/*
4710 	 * Get the second variable.
4711 	 */
4712 	*arg = skipwhite(*arg + 1);
4713 	if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4714 	{
4715 	    clear_tv(rettv);
4716 	    return FAIL;
4717 	}
4718 
4719 	if (evaluate)
4720 	{
4721 	    /*
4722 	     * Compute the result.
4723 	     */
4724 	    if (op == '.')
4725 	    {
4726 		s1 = get_tv_string_buf(rettv, buf1);	/* already checked */
4727 		s2 = get_tv_string_buf_chk(&var2, buf2);
4728 		if (s2 == NULL)		/* type error ? */
4729 		{
4730 		    clear_tv(rettv);
4731 		    clear_tv(&var2);
4732 		    return FAIL;
4733 		}
4734 		p = concat_str(s1, s2);
4735 		clear_tv(rettv);
4736 		rettv->v_type = VAR_STRING;
4737 		rettv->vval.v_string = p;
4738 	    }
4739 	    else if (op == '+' && rettv->v_type == VAR_LIST
4740 						   && var2.v_type == VAR_LIST)
4741 	    {
4742 		/* concatenate Lists */
4743 		if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4744 							       &var3) == FAIL)
4745 		{
4746 		    clear_tv(rettv);
4747 		    clear_tv(&var2);
4748 		    return FAIL;
4749 		}
4750 		clear_tv(rettv);
4751 		*rettv = var3;
4752 	    }
4753 	    else
4754 	    {
4755 		int	    error = FALSE;
4756 
4757 #ifdef FEAT_FLOAT
4758 		if (rettv->v_type == VAR_FLOAT)
4759 		{
4760 		    f1 = rettv->vval.v_float;
4761 		    n1 = 0;
4762 		}
4763 		else
4764 #endif
4765 		{
4766 		    n1 = get_tv_number_chk(rettv, &error);
4767 		    if (error)
4768 		    {
4769 			/* This can only happen for "list + non-list".  For
4770 			 * "non-list + ..." or "something - ...", we returned
4771 			 * before evaluating the 2nd operand. */
4772 			clear_tv(rettv);
4773 			return FAIL;
4774 		    }
4775 #ifdef FEAT_FLOAT
4776 		    if (var2.v_type == VAR_FLOAT)
4777 			f1 = n1;
4778 #endif
4779 		}
4780 #ifdef FEAT_FLOAT
4781 		if (var2.v_type == VAR_FLOAT)
4782 		{
4783 		    f2 = var2.vval.v_float;
4784 		    n2 = 0;
4785 		}
4786 		else
4787 #endif
4788 		{
4789 		    n2 = get_tv_number_chk(&var2, &error);
4790 		    if (error)
4791 		    {
4792 			clear_tv(rettv);
4793 			clear_tv(&var2);
4794 			return FAIL;
4795 		    }
4796 #ifdef FEAT_FLOAT
4797 		    if (rettv->v_type == VAR_FLOAT)
4798 			f2 = n2;
4799 #endif
4800 		}
4801 		clear_tv(rettv);
4802 
4803 #ifdef FEAT_FLOAT
4804 		/* If there is a float on either side the result is a float. */
4805 		if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4806 		{
4807 		    if (op == '+')
4808 			f1 = f1 + f2;
4809 		    else
4810 			f1 = f1 - f2;
4811 		    rettv->v_type = VAR_FLOAT;
4812 		    rettv->vval.v_float = f1;
4813 		}
4814 		else
4815 #endif
4816 		{
4817 		    if (op == '+')
4818 			n1 = n1 + n2;
4819 		    else
4820 			n1 = n1 - n2;
4821 		    rettv->v_type = VAR_NUMBER;
4822 		    rettv->vval.v_number = n1;
4823 		}
4824 	    }
4825 	    clear_tv(&var2);
4826 	}
4827     }
4828     return OK;
4829 }
4830 
4831 /*
4832  * Handle fifth level expression:
4833  *	*	number multiplication
4834  *	/	number division
4835  *	%	number modulo
4836  *
4837  * "arg" must point to the first non-white of the expression.
4838  * "arg" is advanced to the next non-white after the recognized expression.
4839  *
4840  * Return OK or FAIL.
4841  */
4842     static int
4843 eval6(arg, rettv, evaluate, want_string)
4844     char_u	**arg;
4845     typval_T	*rettv;
4846     int		evaluate;
4847     int		want_string;  /* after "." operator */
4848 {
4849     typval_T	var2;
4850     int		op;
4851     long	n1, n2;
4852 #ifdef FEAT_FLOAT
4853     int		use_float = FALSE;
4854     float_T	f1 = 0, f2;
4855 #endif
4856     int		error = FALSE;
4857 
4858     /*
4859      * Get the first variable.
4860      */
4861     if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4862 	return FAIL;
4863 
4864     /*
4865      * Repeat computing, until no '*', '/' or '%' is following.
4866      */
4867     for (;;)
4868     {
4869 	op = **arg;
4870 	if (op != '*' && op != '/' && op != '%')
4871 	    break;
4872 
4873 	if (evaluate)
4874 	{
4875 #ifdef FEAT_FLOAT
4876 	    if (rettv->v_type == VAR_FLOAT)
4877 	    {
4878 		f1 = rettv->vval.v_float;
4879 		use_float = TRUE;
4880 		n1 = 0;
4881 	    }
4882 	    else
4883 #endif
4884 		n1 = get_tv_number_chk(rettv, &error);
4885 	    clear_tv(rettv);
4886 	    if (error)
4887 		return FAIL;
4888 	}
4889 	else
4890 	    n1 = 0;
4891 
4892 	/*
4893 	 * Get the second variable.
4894 	 */
4895 	*arg = skipwhite(*arg + 1);
4896 	if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4897 	    return FAIL;
4898 
4899 	if (evaluate)
4900 	{
4901 #ifdef FEAT_FLOAT
4902 	    if (var2.v_type == VAR_FLOAT)
4903 	    {
4904 		if (!use_float)
4905 		{
4906 		    f1 = n1;
4907 		    use_float = TRUE;
4908 		}
4909 		f2 = var2.vval.v_float;
4910 		n2 = 0;
4911 	    }
4912 	    else
4913 #endif
4914 	    {
4915 		n2 = get_tv_number_chk(&var2, &error);
4916 		clear_tv(&var2);
4917 		if (error)
4918 		    return FAIL;
4919 #ifdef FEAT_FLOAT
4920 		if (use_float)
4921 		    f2 = n2;
4922 #endif
4923 	    }
4924 
4925 	    /*
4926 	     * Compute the result.
4927 	     * When either side is a float the result is a float.
4928 	     */
4929 #ifdef FEAT_FLOAT
4930 	    if (use_float)
4931 	    {
4932 		if (op == '*')
4933 		    f1 = f1 * f2;
4934 		else if (op == '/')
4935 		{
4936 # ifdef VMS
4937 		    /* VMS crashes on divide by zero, work around it */
4938 		    if (f2 == 0.0)
4939 		    {
4940 			if (f1 == 0)
4941 			    f1 = -1 * __F_FLT_MAX - 1L;   /* similar to NaN */
4942 			else if (f1 < 0)
4943 			    f1 = -1 * __F_FLT_MAX;
4944 			else
4945 			    f1 = __F_FLT_MAX;
4946 		    }
4947 		    else
4948 			f1 = f1 / f2;
4949 # else
4950 		    /* We rely on the floating point library to handle divide
4951 		     * by zero to result in "inf" and not a crash. */
4952 		    f1 = f1 / f2;
4953 # endif
4954 		}
4955 		else
4956 		{
4957 		    EMSG(_("E804: Cannot use '%' with Float"));
4958 		    return FAIL;
4959 		}
4960 		rettv->v_type = VAR_FLOAT;
4961 		rettv->vval.v_float = f1;
4962 	    }
4963 	    else
4964 #endif
4965 	    {
4966 		if (op == '*')
4967 		    n1 = n1 * n2;
4968 		else if (op == '/')
4969 		{
4970 		    if (n2 == 0)	/* give an error message? */
4971 		    {
4972 			if (n1 == 0)
4973 			    n1 = -0x7fffffffL - 1L;	/* similar to NaN */
4974 			else if (n1 < 0)
4975 			    n1 = -0x7fffffffL;
4976 			else
4977 			    n1 = 0x7fffffffL;
4978 		    }
4979 		    else
4980 			n1 = n1 / n2;
4981 		}
4982 		else
4983 		{
4984 		    if (n2 == 0)	/* give an error message? */
4985 			n1 = 0;
4986 		    else
4987 			n1 = n1 % n2;
4988 		}
4989 		rettv->v_type = VAR_NUMBER;
4990 		rettv->vval.v_number = n1;
4991 	    }
4992 	}
4993     }
4994 
4995     return OK;
4996 }
4997 
4998 /*
4999  * Handle sixth level expression:
5000  *  number		number constant
5001  *  "string"		string constant
5002  *  'string'		literal string constant
5003  *  &option-name	option value
5004  *  @r			register contents
5005  *  identifier		variable value
5006  *  function()		function call
5007  *  $VAR		environment variable
5008  *  (expression)	nested expression
5009  *  [expr, expr]	List
5010  *  {key: val, key: val}  Dictionary
5011  *
5012  *  Also handle:
5013  *  ! in front		logical NOT
5014  *  - in front		unary minus
5015  *  + in front		unary plus (ignored)
5016  *  trailing []		subscript in String or List
5017  *  trailing .name	entry in Dictionary
5018  *
5019  * "arg" must point to the first non-white of the expression.
5020  * "arg" is advanced to the next non-white after the recognized expression.
5021  *
5022  * Return OK or FAIL.
5023  */
5024     static int
5025 eval7(arg, rettv, evaluate, want_string)
5026     char_u	**arg;
5027     typval_T	*rettv;
5028     int		evaluate;
5029     int		want_string UNUSED;	/* after "." operator */
5030 {
5031     long	n;
5032     int		len;
5033     char_u	*s;
5034     char_u	*start_leader, *end_leader;
5035     int		ret = OK;
5036     char_u	*alias;
5037 
5038     /*
5039      * Initialise variable so that clear_tv() can't mistake this for a
5040      * string and free a string that isn't there.
5041      */
5042     rettv->v_type = VAR_UNKNOWN;
5043 
5044     /*
5045      * Skip '!' and '-' characters.  They are handled later.
5046      */
5047     start_leader = *arg;
5048     while (**arg == '!' || **arg == '-' || **arg == '+')
5049 	*arg = skipwhite(*arg + 1);
5050     end_leader = *arg;
5051 
5052     switch (**arg)
5053     {
5054     /*
5055      * Number constant.
5056      */
5057     case '0':
5058     case '1':
5059     case '2':
5060     case '3':
5061     case '4':
5062     case '5':
5063     case '6':
5064     case '7':
5065     case '8':
5066     case '9':
5067 	{
5068 #ifdef FEAT_FLOAT
5069 		char_u *p = skipdigits(*arg + 1);
5070 		int    get_float = FALSE;
5071 
5072 		/* We accept a float when the format matches
5073 		 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?".  This is very
5074 		 * strict to avoid backwards compatibility problems.
5075 		 * Don't look for a float after the "." operator, so that
5076 		 * ":let vers = 1.2.3" doesn't fail. */
5077 		if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
5078 		{
5079 		    get_float = TRUE;
5080 		    p = skipdigits(p + 2);
5081 		    if (*p == 'e' || *p == 'E')
5082 		    {
5083 			++p;
5084 			if (*p == '-' || *p == '+')
5085 			    ++p;
5086 			if (!vim_isdigit(*p))
5087 			    get_float = FALSE;
5088 			else
5089 			    p = skipdigits(p + 1);
5090 		    }
5091 		    if (ASCII_ISALPHA(*p) || *p == '.')
5092 			get_float = FALSE;
5093 		}
5094 		if (get_float)
5095 		{
5096 		    float_T	f;
5097 
5098 		    *arg += string2float(*arg, &f);
5099 		    if (evaluate)
5100 		    {
5101 			rettv->v_type = VAR_FLOAT;
5102 			rettv->vval.v_float = f;
5103 		    }
5104 		}
5105 		else
5106 #endif
5107 		{
5108 		    vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
5109 		    *arg += len;
5110 		    if (evaluate)
5111 		    {
5112 			rettv->v_type = VAR_NUMBER;
5113 			rettv->vval.v_number = n;
5114 		    }
5115 		}
5116 		break;
5117 	}
5118 
5119     /*
5120      * String constant: "string".
5121      */
5122     case '"':	ret = get_string_tv(arg, rettv, evaluate);
5123 		break;
5124 
5125     /*
5126      * Literal string constant: 'str''ing'.
5127      */
5128     case '\'':	ret = get_lit_string_tv(arg, rettv, evaluate);
5129 		break;
5130 
5131     /*
5132      * List: [expr, expr]
5133      */
5134     case '[':	ret = get_list_tv(arg, rettv, evaluate);
5135 		break;
5136 
5137     /*
5138      * Dictionary: {key: val, key: val}
5139      */
5140     case '{':	ret = get_dict_tv(arg, rettv, evaluate);
5141 		break;
5142 
5143     /*
5144      * Option value: &name
5145      */
5146     case '&':	ret = get_option_tv(arg, rettv, evaluate);
5147 		break;
5148 
5149     /*
5150      * Environment variable: $VAR.
5151      */
5152     case '$':	ret = get_env_tv(arg, rettv, evaluate);
5153 		break;
5154 
5155     /*
5156      * Register contents: @r.
5157      */
5158     case '@':	++*arg;
5159 		if (evaluate)
5160 		{
5161 		    rettv->v_type = VAR_STRING;
5162 		    rettv->vval.v_string = get_reg_contents(**arg,
5163 							    GREG_EXPR_SRC);
5164 		}
5165 		if (**arg != NUL)
5166 		    ++*arg;
5167 		break;
5168 
5169     /*
5170      * nested expression: (expression).
5171      */
5172     case '(':	*arg = skipwhite(*arg + 1);
5173 		ret = eval1(arg, rettv, evaluate);	/* recursive! */
5174 		if (**arg == ')')
5175 		    ++*arg;
5176 		else if (ret == OK)
5177 		{
5178 		    EMSG(_("E110: Missing ')'"));
5179 		    clear_tv(rettv);
5180 		    ret = FAIL;
5181 		}
5182 		break;
5183 
5184     default:	ret = NOTDONE;
5185 		break;
5186     }
5187 
5188     if (ret == NOTDONE)
5189     {
5190 	/*
5191 	 * Must be a variable or function name.
5192 	 * Can also be a curly-braces kind of name: {expr}.
5193 	 */
5194 	s = *arg;
5195 	len = get_name_len(arg, &alias, evaluate, TRUE);
5196 	if (alias != NULL)
5197 	    s = alias;
5198 
5199 	if (len <= 0)
5200 	    ret = FAIL;
5201 	else
5202 	{
5203 	    if (**arg == '(')		/* recursive! */
5204 	    {
5205 		/* If "s" is the name of a variable of type VAR_FUNC
5206 		 * use its contents. */
5207 		s = deref_func_name(s, &len, !evaluate);
5208 
5209 		/* Invoke the function. */
5210 		ret = get_func_tv(s, len, rettv, arg,
5211 			  curwin->w_cursor.lnum, curwin->w_cursor.lnum,
5212 			  &len, evaluate, NULL);
5213 
5214 		/* If evaluate is FALSE rettv->v_type was not set in
5215 		 * get_func_tv, but it's needed in handle_subscript() to parse
5216 		 * what follows. So set it here. */
5217 		if (rettv->v_type == VAR_UNKNOWN && !evaluate && **arg == '(')
5218 		{
5219 		    rettv->vval.v_string = vim_strsave((char_u *)"");
5220 		    rettv->v_type = VAR_FUNC;
5221 		}
5222 
5223 		/* Stop the expression evaluation when immediately
5224 		 * aborting on error, or when an interrupt occurred or
5225 		 * an exception was thrown but not caught. */
5226 		if (aborting())
5227 		{
5228 		    if (ret == OK)
5229 			clear_tv(rettv);
5230 		    ret = FAIL;
5231 		}
5232 	    }
5233 	    else if (evaluate)
5234 		ret = get_var_tv(s, len, rettv, TRUE, FALSE);
5235 	    else
5236 		ret = OK;
5237 	}
5238 	vim_free(alias);
5239     }
5240 
5241     *arg = skipwhite(*arg);
5242 
5243     /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5244      * expr(expr). */
5245     if (ret == OK)
5246 	ret = handle_subscript(arg, rettv, evaluate, TRUE);
5247 
5248     /*
5249      * Apply logical NOT and unary '-', from right to left, ignore '+'.
5250      */
5251     if (ret == OK && evaluate && end_leader > start_leader)
5252     {
5253 	int	    error = FALSE;
5254 	int	    val = 0;
5255 #ifdef FEAT_FLOAT
5256 	float_T	    f = 0.0;
5257 
5258 	if (rettv->v_type == VAR_FLOAT)
5259 	    f = rettv->vval.v_float;
5260 	else
5261 #endif
5262 	    val = get_tv_number_chk(rettv, &error);
5263 	if (error)
5264 	{
5265 	    clear_tv(rettv);
5266 	    ret = FAIL;
5267 	}
5268 	else
5269 	{
5270 	    while (end_leader > start_leader)
5271 	    {
5272 		--end_leader;
5273 		if (*end_leader == '!')
5274 		{
5275 #ifdef FEAT_FLOAT
5276 		    if (rettv->v_type == VAR_FLOAT)
5277 			f = !f;
5278 		    else
5279 #endif
5280 			val = !val;
5281 		}
5282 		else if (*end_leader == '-')
5283 		{
5284 #ifdef FEAT_FLOAT
5285 		    if (rettv->v_type == VAR_FLOAT)
5286 			f = -f;
5287 		    else
5288 #endif
5289 			val = -val;
5290 		}
5291 	    }
5292 #ifdef FEAT_FLOAT
5293 	    if (rettv->v_type == VAR_FLOAT)
5294 	    {
5295 		clear_tv(rettv);
5296 		rettv->vval.v_float = f;
5297 	    }
5298 	    else
5299 #endif
5300 	    {
5301 		clear_tv(rettv);
5302 		rettv->v_type = VAR_NUMBER;
5303 		rettv->vval.v_number = val;
5304 	    }
5305 	}
5306     }
5307 
5308     return ret;
5309 }
5310 
5311 /*
5312  * Evaluate an "[expr]" or "[expr:expr]" index.  Also "dict.key".
5313  * "*arg" points to the '[' or '.'.
5314  * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5315  */
5316     static int
5317 eval_index(arg, rettv, evaluate, verbose)
5318     char_u	**arg;
5319     typval_T	*rettv;
5320     int		evaluate;
5321     int		verbose;	/* give error messages */
5322 {
5323     int		empty1 = FALSE, empty2 = FALSE;
5324     typval_T	var1, var2;
5325     long	n1, n2 = 0;
5326     long	len = -1;
5327     int		range = FALSE;
5328     char_u	*s;
5329     char_u	*key = NULL;
5330 
5331     if (rettv->v_type == VAR_FUNC)
5332     {
5333 	if (verbose)
5334 	    EMSG(_("E695: Cannot index a Funcref"));
5335 	return FAIL;
5336     }
5337 #ifdef FEAT_FLOAT
5338     else if (rettv->v_type == VAR_FLOAT)
5339     {
5340 	if (verbose)
5341 	    EMSG(_(e_float_as_string));
5342 	return FAIL;
5343     }
5344 #endif
5345 
5346     if (**arg == '.')
5347     {
5348 	/*
5349 	 * dict.name
5350 	 */
5351 	key = *arg + 1;
5352 	for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5353 	    ;
5354 	if (len == 0)
5355 	    return FAIL;
5356 	*arg = skipwhite(key + len);
5357     }
5358     else
5359     {
5360 	/*
5361 	 * something[idx]
5362 	 *
5363 	 * Get the (first) variable from inside the [].
5364 	 */
5365 	*arg = skipwhite(*arg + 1);
5366 	if (**arg == ':')
5367 	    empty1 = TRUE;
5368 	else if (eval1(arg, &var1, evaluate) == FAIL)	/* recursive! */
5369 	    return FAIL;
5370 	else if (evaluate && get_tv_string_chk(&var1) == NULL)
5371 	{
5372 	    /* not a number or string */
5373 	    clear_tv(&var1);
5374 	    return FAIL;
5375 	}
5376 
5377 	/*
5378 	 * Get the second variable from inside the [:].
5379 	 */
5380 	if (**arg == ':')
5381 	{
5382 	    range = TRUE;
5383 	    *arg = skipwhite(*arg + 1);
5384 	    if (**arg == ']')
5385 		empty2 = TRUE;
5386 	    else if (eval1(arg, &var2, evaluate) == FAIL)	/* recursive! */
5387 	    {
5388 		if (!empty1)
5389 		    clear_tv(&var1);
5390 		return FAIL;
5391 	    }
5392 	    else if (evaluate && get_tv_string_chk(&var2) == NULL)
5393 	    {
5394 		/* not a number or string */
5395 		if (!empty1)
5396 		    clear_tv(&var1);
5397 		clear_tv(&var2);
5398 		return FAIL;
5399 	    }
5400 	}
5401 
5402 	/* Check for the ']'. */
5403 	if (**arg != ']')
5404 	{
5405 	    if (verbose)
5406 		EMSG(_(e_missbrac));
5407 	    clear_tv(&var1);
5408 	    if (range)
5409 		clear_tv(&var2);
5410 	    return FAIL;
5411 	}
5412 	*arg = skipwhite(*arg + 1);	/* skip the ']' */
5413     }
5414 
5415     if (evaluate)
5416     {
5417 	n1 = 0;
5418 	if (!empty1 && rettv->v_type != VAR_DICT)
5419 	{
5420 	    n1 = get_tv_number(&var1);
5421 	    clear_tv(&var1);
5422 	}
5423 	if (range)
5424 	{
5425 	    if (empty2)
5426 		n2 = -1;
5427 	    else
5428 	    {
5429 		n2 = get_tv_number(&var2);
5430 		clear_tv(&var2);
5431 	    }
5432 	}
5433 
5434 	switch (rettv->v_type)
5435 	{
5436 	    case VAR_NUMBER:
5437 	    case VAR_STRING:
5438 		s = get_tv_string(rettv);
5439 		len = (long)STRLEN(s);
5440 		if (range)
5441 		{
5442 		    /* The resulting variable is a substring.  If the indexes
5443 		     * are out of range the result is empty. */
5444 		    if (n1 < 0)
5445 		    {
5446 			n1 = len + n1;
5447 			if (n1 < 0)
5448 			    n1 = 0;
5449 		    }
5450 		    if (n2 < 0)
5451 			n2 = len + n2;
5452 		    else if (n2 >= len)
5453 			n2 = len;
5454 		    if (n1 >= len || n2 < 0 || n1 > n2)
5455 			s = NULL;
5456 		    else
5457 			s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5458 		}
5459 		else
5460 		{
5461 		    /* The resulting variable is a string of a single
5462 		     * character.  If the index is too big or negative the
5463 		     * result is empty. */
5464 		    if (n1 >= len || n1 < 0)
5465 			s = NULL;
5466 		    else
5467 			s = vim_strnsave(s + n1, 1);
5468 		}
5469 		clear_tv(rettv);
5470 		rettv->v_type = VAR_STRING;
5471 		rettv->vval.v_string = s;
5472 		break;
5473 
5474 	    case VAR_LIST:
5475 		len = list_len(rettv->vval.v_list);
5476 		if (n1 < 0)
5477 		    n1 = len + n1;
5478 		if (!empty1 && (n1 < 0 || n1 >= len))
5479 		{
5480 		    /* For a range we allow invalid values and return an empty
5481 		     * list.  A list index out of range is an error. */
5482 		    if (!range)
5483 		    {
5484 			if (verbose)
5485 			    EMSGN(_(e_listidx), n1);
5486 			return FAIL;
5487 		    }
5488 		    n1 = len;
5489 		}
5490 		if (range)
5491 		{
5492 		    list_T	*l;
5493 		    listitem_T	*item;
5494 
5495 		    if (n2 < 0)
5496 			n2 = len + n2;
5497 		    else if (n2 >= len)
5498 			n2 = len - 1;
5499 		    if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5500 			n2 = -1;
5501 		    l = list_alloc();
5502 		    if (l == NULL)
5503 			return FAIL;
5504 		    for (item = list_find(rettv->vval.v_list, n1);
5505 							       n1 <= n2; ++n1)
5506 		    {
5507 			if (list_append_tv(l, &item->li_tv) == FAIL)
5508 			{
5509 			    list_free(l, TRUE);
5510 			    return FAIL;
5511 			}
5512 			item = item->li_next;
5513 		    }
5514 		    clear_tv(rettv);
5515 		    rettv->v_type = VAR_LIST;
5516 		    rettv->vval.v_list = l;
5517 		    ++l->lv_refcount;
5518 		}
5519 		else
5520 		{
5521 		    copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5522 		    clear_tv(rettv);
5523 		    *rettv = var1;
5524 		}
5525 		break;
5526 
5527 	    case VAR_DICT:
5528 		if (range)
5529 		{
5530 		    if (verbose)
5531 			EMSG(_(e_dictrange));
5532 		    if (len == -1)
5533 			clear_tv(&var1);
5534 		    return FAIL;
5535 		}
5536 		{
5537 		    dictitem_T	*item;
5538 
5539 		    if (len == -1)
5540 		    {
5541 			key = get_tv_string(&var1);
5542 			if (*key == NUL)
5543 			{
5544 			    if (verbose)
5545 				EMSG(_(e_emptykey));
5546 			    clear_tv(&var1);
5547 			    return FAIL;
5548 			}
5549 		    }
5550 
5551 		    item = dict_find(rettv->vval.v_dict, key, (int)len);
5552 
5553 		    if (item == NULL && verbose)
5554 			EMSG2(_(e_dictkey), key);
5555 		    if (len == -1)
5556 			clear_tv(&var1);
5557 		    if (item == NULL)
5558 			return FAIL;
5559 
5560 		    copy_tv(&item->di_tv, &var1);
5561 		    clear_tv(rettv);
5562 		    *rettv = var1;
5563 		}
5564 		break;
5565 	}
5566     }
5567 
5568     return OK;
5569 }
5570 
5571 /*
5572  * Get an option value.
5573  * "arg" points to the '&' or '+' before the option name.
5574  * "arg" is advanced to character after the option name.
5575  * Return OK or FAIL.
5576  */
5577     static int
5578 get_option_tv(arg, rettv, evaluate)
5579     char_u	**arg;
5580     typval_T	*rettv;	/* when NULL, only check if option exists */
5581     int		evaluate;
5582 {
5583     char_u	*option_end;
5584     long	numval;
5585     char_u	*stringval;
5586     int		opt_type;
5587     int		c;
5588     int		working = (**arg == '+');    /* has("+option") */
5589     int		ret = OK;
5590     int		opt_flags;
5591 
5592     /*
5593      * Isolate the option name and find its value.
5594      */
5595     option_end = find_option_end(arg, &opt_flags);
5596     if (option_end == NULL)
5597     {
5598 	if (rettv != NULL)
5599 	    EMSG2(_("E112: Option name missing: %s"), *arg);
5600 	return FAIL;
5601     }
5602 
5603     if (!evaluate)
5604     {
5605 	*arg = option_end;
5606 	return OK;
5607     }
5608 
5609     c = *option_end;
5610     *option_end = NUL;
5611     opt_type = get_option_value(*arg, &numval,
5612 			       rettv == NULL ? NULL : &stringval, opt_flags);
5613 
5614     if (opt_type == -3)			/* invalid name */
5615     {
5616 	if (rettv != NULL)
5617 	    EMSG2(_("E113: Unknown option: %s"), *arg);
5618 	ret = FAIL;
5619     }
5620     else if (rettv != NULL)
5621     {
5622 	if (opt_type == -2)		/* hidden string option */
5623 	{
5624 	    rettv->v_type = VAR_STRING;
5625 	    rettv->vval.v_string = NULL;
5626 	}
5627 	else if (opt_type == -1)	/* hidden number option */
5628 	{
5629 	    rettv->v_type = VAR_NUMBER;
5630 	    rettv->vval.v_number = 0;
5631 	}
5632 	else if (opt_type == 1)		/* number option */
5633 	{
5634 	    rettv->v_type = VAR_NUMBER;
5635 	    rettv->vval.v_number = numval;
5636 	}
5637 	else				/* string option */
5638 	{
5639 	    rettv->v_type = VAR_STRING;
5640 	    rettv->vval.v_string = stringval;
5641 	}
5642     }
5643     else if (working && (opt_type == -2 || opt_type == -1))
5644 	ret = FAIL;
5645 
5646     *option_end = c;		    /* put back for error messages */
5647     *arg = option_end;
5648 
5649     return ret;
5650 }
5651 
5652 /*
5653  * Allocate a variable for a string constant.
5654  * Return OK or FAIL.
5655  */
5656     static int
5657 get_string_tv(arg, rettv, evaluate)
5658     char_u	**arg;
5659     typval_T	*rettv;
5660     int		evaluate;
5661 {
5662     char_u	*p;
5663     char_u	*name;
5664     int		extra = 0;
5665 
5666     /*
5667      * Find the end of the string, skipping backslashed characters.
5668      */
5669     for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5670     {
5671 	if (*p == '\\' && p[1] != NUL)
5672 	{
5673 	    ++p;
5674 	    /* A "\<x>" form occupies at least 4 characters, and produces up
5675 	     * to 6 characters: reserve space for 2 extra */
5676 	    if (*p == '<')
5677 		extra += 2;
5678 	}
5679     }
5680 
5681     if (*p != '"')
5682     {
5683 	EMSG2(_("E114: Missing quote: %s"), *arg);
5684 	return FAIL;
5685     }
5686 
5687     /* If only parsing, set *arg and return here */
5688     if (!evaluate)
5689     {
5690 	*arg = p + 1;
5691 	return OK;
5692     }
5693 
5694     /*
5695      * Copy the string into allocated memory, handling backslashed
5696      * characters.
5697      */
5698     name = alloc((unsigned)(p - *arg + extra));
5699     if (name == NULL)
5700 	return FAIL;
5701     rettv->v_type = VAR_STRING;
5702     rettv->vval.v_string = name;
5703 
5704     for (p = *arg + 1; *p != NUL && *p != '"'; )
5705     {
5706 	if (*p == '\\')
5707 	{
5708 	    switch (*++p)
5709 	    {
5710 		case 'b': *name++ = BS; ++p; break;
5711 		case 'e': *name++ = ESC; ++p; break;
5712 		case 'f': *name++ = FF; ++p; break;
5713 		case 'n': *name++ = NL; ++p; break;
5714 		case 'r': *name++ = CAR; ++p; break;
5715 		case 't': *name++ = TAB; ++p; break;
5716 
5717 		case 'X': /* hex: "\x1", "\x12" */
5718 		case 'x':
5719 		case 'u': /* Unicode: "\u0023" */
5720 		case 'U':
5721 			  if (vim_isxdigit(p[1]))
5722 			  {
5723 			      int	n, nr;
5724 			      int	c = toupper(*p);
5725 
5726 			      if (c == 'X')
5727 				  n = 2;
5728 			      else
5729 				  n = 4;
5730 			      nr = 0;
5731 			      while (--n >= 0 && vim_isxdigit(p[1]))
5732 			      {
5733 				  ++p;
5734 				  nr = (nr << 4) + hex2nr(*p);
5735 			      }
5736 			      ++p;
5737 #ifdef FEAT_MBYTE
5738 			      /* For "\u" store the number according to
5739 			       * 'encoding'. */
5740 			      if (c != 'X')
5741 				  name += (*mb_char2bytes)(nr, name);
5742 			      else
5743 #endif
5744 				  *name++ = nr;
5745 			  }
5746 			  break;
5747 
5748 			  /* octal: "\1", "\12", "\123" */
5749 		case '0':
5750 		case '1':
5751 		case '2':
5752 		case '3':
5753 		case '4':
5754 		case '5':
5755 		case '6':
5756 		case '7': *name = *p++ - '0';
5757 			  if (*p >= '0' && *p <= '7')
5758 			  {
5759 			      *name = (*name << 3) + *p++ - '0';
5760 			      if (*p >= '0' && *p <= '7')
5761 				  *name = (*name << 3) + *p++ - '0';
5762 			  }
5763 			  ++name;
5764 			  break;
5765 
5766 			    /* Special key, e.g.: "\<C-W>" */
5767 		case '<': extra = trans_special(&p, name, TRUE);
5768 			  if (extra != 0)
5769 			  {
5770 			      name += extra;
5771 			      break;
5772 			  }
5773 			  /* FALLTHROUGH */
5774 
5775 		default:  MB_COPY_CHAR(p, name);
5776 			  break;
5777 	    }
5778 	}
5779 	else
5780 	    MB_COPY_CHAR(p, name);
5781 
5782     }
5783     *name = NUL;
5784     *arg = p + 1;
5785 
5786     return OK;
5787 }
5788 
5789 /*
5790  * Allocate a variable for a 'str''ing' constant.
5791  * Return OK or FAIL.
5792  */
5793     static int
5794 get_lit_string_tv(arg, rettv, evaluate)
5795     char_u	**arg;
5796     typval_T	*rettv;
5797     int		evaluate;
5798 {
5799     char_u	*p;
5800     char_u	*str;
5801     int		reduce = 0;
5802 
5803     /*
5804      * Find the end of the string, skipping ''.
5805      */
5806     for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5807     {
5808 	if (*p == '\'')
5809 	{
5810 	    if (p[1] != '\'')
5811 		break;
5812 	    ++reduce;
5813 	    ++p;
5814 	}
5815     }
5816 
5817     if (*p != '\'')
5818     {
5819 	EMSG2(_("E115: Missing quote: %s"), *arg);
5820 	return FAIL;
5821     }
5822 
5823     /* If only parsing return after setting "*arg" */
5824     if (!evaluate)
5825     {
5826 	*arg = p + 1;
5827 	return OK;
5828     }
5829 
5830     /*
5831      * Copy the string into allocated memory, handling '' to ' reduction.
5832      */
5833     str = alloc((unsigned)((p - *arg) - reduce));
5834     if (str == NULL)
5835 	return FAIL;
5836     rettv->v_type = VAR_STRING;
5837     rettv->vval.v_string = str;
5838 
5839     for (p = *arg + 1; *p != NUL; )
5840     {
5841 	if (*p == '\'')
5842 	{
5843 	    if (p[1] != '\'')
5844 		break;
5845 	    ++p;
5846 	}
5847 	MB_COPY_CHAR(p, str);
5848     }
5849     *str = NUL;
5850     *arg = p + 1;
5851 
5852     return OK;
5853 }
5854 
5855 /*
5856  * Allocate a variable for a List and fill it from "*arg".
5857  * Return OK or FAIL.
5858  */
5859     static int
5860 get_list_tv(arg, rettv, evaluate)
5861     char_u	**arg;
5862     typval_T	*rettv;
5863     int		evaluate;
5864 {
5865     list_T	*l = NULL;
5866     typval_T	tv;
5867     listitem_T	*item;
5868 
5869     if (evaluate)
5870     {
5871 	l = list_alloc();
5872 	if (l == NULL)
5873 	    return FAIL;
5874     }
5875 
5876     *arg = skipwhite(*arg + 1);
5877     while (**arg != ']' && **arg != NUL)
5878     {
5879 	if (eval1(arg, &tv, evaluate) == FAIL)	/* recursive! */
5880 	    goto failret;
5881 	if (evaluate)
5882 	{
5883 	    item = listitem_alloc();
5884 	    if (item != NULL)
5885 	    {
5886 		item->li_tv = tv;
5887 		item->li_tv.v_lock = 0;
5888 		list_append(l, item);
5889 	    }
5890 	    else
5891 		clear_tv(&tv);
5892 	}
5893 
5894 	if (**arg == ']')
5895 	    break;
5896 	if (**arg != ',')
5897 	{
5898 	    EMSG2(_("E696: Missing comma in List: %s"), *arg);
5899 	    goto failret;
5900 	}
5901 	*arg = skipwhite(*arg + 1);
5902     }
5903 
5904     if (**arg != ']')
5905     {
5906 	EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5907 failret:
5908 	if (evaluate)
5909 	    list_free(l, TRUE);
5910 	return FAIL;
5911     }
5912 
5913     *arg = skipwhite(*arg + 1);
5914     if (evaluate)
5915     {
5916 	rettv->v_type = VAR_LIST;
5917 	rettv->vval.v_list = l;
5918 	++l->lv_refcount;
5919     }
5920 
5921     return OK;
5922 }
5923 
5924 /*
5925  * Allocate an empty header for a list.
5926  * Caller should take care of the reference count.
5927  */
5928     list_T *
5929 list_alloc()
5930 {
5931     list_T  *l;
5932 
5933     l = (list_T *)alloc_clear(sizeof(list_T));
5934     if (l != NULL)
5935     {
5936 	/* Prepend the list to the list of lists for garbage collection. */
5937 	if (first_list != NULL)
5938 	    first_list->lv_used_prev = l;
5939 	l->lv_used_prev = NULL;
5940 	l->lv_used_next = first_list;
5941 	first_list = l;
5942     }
5943     return l;
5944 }
5945 
5946 /*
5947  * Allocate an empty list for a return value.
5948  * Returns OK or FAIL.
5949  */
5950     static int
5951 rettv_list_alloc(rettv)
5952     typval_T	*rettv;
5953 {
5954     list_T	*l = list_alloc();
5955 
5956     if (l == NULL)
5957 	return FAIL;
5958 
5959     rettv->vval.v_list = l;
5960     rettv->v_type = VAR_LIST;
5961     ++l->lv_refcount;
5962     return OK;
5963 }
5964 
5965 /*
5966  * Unreference a list: decrement the reference count and free it when it
5967  * becomes zero.
5968  */
5969     void
5970 list_unref(l)
5971     list_T *l;
5972 {
5973     if (l != NULL && --l->lv_refcount <= 0)
5974 	list_free(l, TRUE);
5975 }
5976 
5977 /*
5978  * Free a list, including all items it points to.
5979  * Ignores the reference count.
5980  */
5981     void
5982 list_free(l, recurse)
5983     list_T  *l;
5984     int	    recurse;	/* Free Lists and Dictionaries recursively. */
5985 {
5986     listitem_T *item;
5987 
5988     /* Remove the list from the list of lists for garbage collection. */
5989     if (l->lv_used_prev == NULL)
5990 	first_list = l->lv_used_next;
5991     else
5992 	l->lv_used_prev->lv_used_next = l->lv_used_next;
5993     if (l->lv_used_next != NULL)
5994 	l->lv_used_next->lv_used_prev = l->lv_used_prev;
5995 
5996     for (item = l->lv_first; item != NULL; item = l->lv_first)
5997     {
5998 	/* Remove the item before deleting it. */
5999 	l->lv_first = item->li_next;
6000 	if (recurse || (item->li_tv.v_type != VAR_LIST
6001 					   && item->li_tv.v_type != VAR_DICT))
6002 	    clear_tv(&item->li_tv);
6003 	vim_free(item);
6004     }
6005     vim_free(l);
6006 }
6007 
6008 /*
6009  * Allocate a list item.
6010  */
6011     listitem_T *
6012 listitem_alloc()
6013 {
6014     return (listitem_T *)alloc(sizeof(listitem_T));
6015 }
6016 
6017 /*
6018  * Free a list item.  Also clears the value.  Does not notify watchers.
6019  */
6020     void
6021 listitem_free(item)
6022     listitem_T *item;
6023 {
6024     clear_tv(&item->li_tv);
6025     vim_free(item);
6026 }
6027 
6028 /*
6029  * Remove a list item from a List and free it.  Also clears the value.
6030  */
6031     void
6032 listitem_remove(l, item)
6033     list_T  *l;
6034     listitem_T *item;
6035 {
6036     vimlist_remove(l, item, item);
6037     listitem_free(item);
6038 }
6039 
6040 /*
6041  * Get the number of items in a list.
6042  */
6043     static long
6044 list_len(l)
6045     list_T	*l;
6046 {
6047     if (l == NULL)
6048 	return 0L;
6049     return l->lv_len;
6050 }
6051 
6052 /*
6053  * Return TRUE when two lists have exactly the same values.
6054  */
6055     static int
6056 list_equal(l1, l2, ic, recursive)
6057     list_T	*l1;
6058     list_T	*l2;
6059     int		ic;	/* ignore case for strings */
6060     int		recursive;  /* TRUE when used recursively */
6061 {
6062     listitem_T	*item1, *item2;
6063 
6064     if (l1 == NULL || l2 == NULL)
6065 	return FALSE;
6066     if (l1 == l2)
6067 	return TRUE;
6068     if (list_len(l1) != list_len(l2))
6069 	return FALSE;
6070 
6071     for (item1 = l1->lv_first, item2 = l2->lv_first;
6072 	    item1 != NULL && item2 != NULL;
6073 			       item1 = item1->li_next, item2 = item2->li_next)
6074 	if (!tv_equal(&item1->li_tv, &item2->li_tv, ic, recursive))
6075 	    return FALSE;
6076     return item1 == NULL && item2 == NULL;
6077 }
6078 
6079 #if defined(FEAT_RUBY) || defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) \
6080 	|| defined(FEAT_MZSCHEME) || defined(FEAT_LUA) || defined(PROTO)
6081 /*
6082  * Return the dictitem that an entry in a hashtable points to.
6083  */
6084     dictitem_T *
6085 dict_lookup(hi)
6086     hashitem_T *hi;
6087 {
6088     return HI2DI(hi);
6089 }
6090 #endif
6091 
6092 /*
6093  * Return TRUE when two dictionaries have exactly the same key/values.
6094  */
6095     static int
6096 dict_equal(d1, d2, ic, recursive)
6097     dict_T	*d1;
6098     dict_T	*d2;
6099     int		ic;	/* ignore case for strings */
6100     int		recursive; /* TRUE when used recursively */
6101 {
6102     hashitem_T	*hi;
6103     dictitem_T	*item2;
6104     int		todo;
6105 
6106     if (d1 == NULL || d2 == NULL)
6107 	return FALSE;
6108     if (d1 == d2)
6109 	return TRUE;
6110     if (dict_len(d1) != dict_len(d2))
6111 	return FALSE;
6112 
6113     todo = (int)d1->dv_hashtab.ht_used;
6114     for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
6115     {
6116 	if (!HASHITEM_EMPTY(hi))
6117 	{
6118 	    item2 = dict_find(d2, hi->hi_key, -1);
6119 	    if (item2 == NULL)
6120 		return FALSE;
6121 	    if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic, recursive))
6122 		return FALSE;
6123 	    --todo;
6124 	}
6125     }
6126     return TRUE;
6127 }
6128 
6129 static int tv_equal_recurse_limit;
6130 
6131 /*
6132  * Return TRUE if "tv1" and "tv2" have the same value.
6133  * Compares the items just like "==" would compare them, but strings and
6134  * numbers are different.  Floats and numbers are also different.
6135  */
6136     static int
6137 tv_equal(tv1, tv2, ic, recursive)
6138     typval_T *tv1;
6139     typval_T *tv2;
6140     int	     ic;	    /* ignore case */
6141     int	     recursive;	    /* TRUE when used recursively */
6142 {
6143     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
6144     char_u	*s1, *s2;
6145     static int  recursive_cnt = 0;	    /* catch recursive loops */
6146     int		r;
6147 
6148     if (tv1->v_type != tv2->v_type)
6149 	return FALSE;
6150 
6151     /* Catch lists and dicts that have an endless loop by limiting
6152      * recursiveness to a limit.  We guess they are equal then.
6153      * A fixed limit has the problem of still taking an awful long time.
6154      * Reduce the limit every time running into it. That should work fine for
6155      * deeply linked structures that are not recursively linked and catch
6156      * recursiveness quickly. */
6157     if (!recursive)
6158 	tv_equal_recurse_limit = 1000;
6159     if (recursive_cnt >= tv_equal_recurse_limit)
6160     {
6161 	--tv_equal_recurse_limit;
6162 	return TRUE;
6163     }
6164 
6165     switch (tv1->v_type)
6166     {
6167 	case VAR_LIST:
6168 	    ++recursive_cnt;
6169 	    r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic, TRUE);
6170 	    --recursive_cnt;
6171 	    return r;
6172 
6173 	case VAR_DICT:
6174 	    ++recursive_cnt;
6175 	    r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic, TRUE);
6176 	    --recursive_cnt;
6177 	    return r;
6178 
6179 	case VAR_FUNC:
6180 	    return (tv1->vval.v_string != NULL
6181 		    && tv2->vval.v_string != NULL
6182 		    && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
6183 
6184 	case VAR_NUMBER:
6185 	    return tv1->vval.v_number == tv2->vval.v_number;
6186 
6187 #ifdef FEAT_FLOAT
6188 	case VAR_FLOAT:
6189 	    return tv1->vval.v_float == tv2->vval.v_float;
6190 #endif
6191 
6192 	case VAR_STRING:
6193 	    s1 = get_tv_string_buf(tv1, buf1);
6194 	    s2 = get_tv_string_buf(tv2, buf2);
6195 	    return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
6196     }
6197 
6198     EMSG2(_(e_intern2), "tv_equal()");
6199     return TRUE;
6200 }
6201 
6202 /*
6203  * Locate item with index "n" in list "l" and return it.
6204  * A negative index is counted from the end; -1 is the last item.
6205  * Returns NULL when "n" is out of range.
6206  */
6207     listitem_T *
6208 list_find(l, n)
6209     list_T	*l;
6210     long	n;
6211 {
6212     listitem_T	*item;
6213     long	idx;
6214 
6215     if (l == NULL)
6216 	return NULL;
6217 
6218     /* Negative index is relative to the end. */
6219     if (n < 0)
6220 	n = l->lv_len + n;
6221 
6222     /* Check for index out of range. */
6223     if (n < 0 || n >= l->lv_len)
6224 	return NULL;
6225 
6226     /* When there is a cached index may start search from there. */
6227     if (l->lv_idx_item != NULL)
6228     {
6229 	if (n < l->lv_idx / 2)
6230 	{
6231 	    /* closest to the start of the list */
6232 	    item = l->lv_first;
6233 	    idx = 0;
6234 	}
6235 	else if (n > (l->lv_idx + l->lv_len) / 2)
6236 	{
6237 	    /* closest to the end of the list */
6238 	    item = l->lv_last;
6239 	    idx = l->lv_len - 1;
6240 	}
6241 	else
6242 	{
6243 	    /* closest to the cached index */
6244 	    item = l->lv_idx_item;
6245 	    idx = l->lv_idx;
6246 	}
6247     }
6248     else
6249     {
6250 	if (n < l->lv_len / 2)
6251 	{
6252 	    /* closest to the start of the list */
6253 	    item = l->lv_first;
6254 	    idx = 0;
6255 	}
6256 	else
6257 	{
6258 	    /* closest to the end of the list */
6259 	    item = l->lv_last;
6260 	    idx = l->lv_len - 1;
6261 	}
6262     }
6263 
6264     while (n > idx)
6265     {
6266 	/* search forward */
6267 	item = item->li_next;
6268 	++idx;
6269     }
6270     while (n < idx)
6271     {
6272 	/* search backward */
6273 	item = item->li_prev;
6274 	--idx;
6275     }
6276 
6277     /* cache the used index */
6278     l->lv_idx = idx;
6279     l->lv_idx_item = item;
6280 
6281     return item;
6282 }
6283 
6284 /*
6285  * Get list item "l[idx]" as a number.
6286  */
6287     static long
6288 list_find_nr(l, idx, errorp)
6289     list_T	*l;
6290     long	idx;
6291     int		*errorp;	/* set to TRUE when something wrong */
6292 {
6293     listitem_T	*li;
6294 
6295     li = list_find(l, idx);
6296     if (li == NULL)
6297     {
6298 	if (errorp != NULL)
6299 	    *errorp = TRUE;
6300 	return -1L;
6301     }
6302     return get_tv_number_chk(&li->li_tv, errorp);
6303 }
6304 
6305 /*
6306  * Get list item "l[idx - 1]" as a string.  Returns NULL for failure.
6307  */
6308     char_u *
6309 list_find_str(l, idx)
6310     list_T	*l;
6311     long	idx;
6312 {
6313     listitem_T	*li;
6314 
6315     li = list_find(l, idx - 1);
6316     if (li == NULL)
6317     {
6318 	EMSGN(_(e_listidx), idx);
6319 	return NULL;
6320     }
6321     return get_tv_string(&li->li_tv);
6322 }
6323 
6324 /*
6325  * Locate "item" list "l" and return its index.
6326  * Returns -1 when "item" is not in the list.
6327  */
6328     static long
6329 list_idx_of_item(l, item)
6330     list_T	*l;
6331     listitem_T	*item;
6332 {
6333     long	idx = 0;
6334     listitem_T	*li;
6335 
6336     if (l == NULL)
6337 	return -1;
6338     idx = 0;
6339     for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6340 	++idx;
6341     if (li == NULL)
6342 	return -1;
6343     return idx;
6344 }
6345 
6346 /*
6347  * Append item "item" to the end of list "l".
6348  */
6349     void
6350 list_append(l, item)
6351     list_T	*l;
6352     listitem_T	*item;
6353 {
6354     if (l->lv_last == NULL)
6355     {
6356 	/* empty list */
6357 	l->lv_first = item;
6358 	l->lv_last = item;
6359 	item->li_prev = NULL;
6360     }
6361     else
6362     {
6363 	l->lv_last->li_next = item;
6364 	item->li_prev = l->lv_last;
6365 	l->lv_last = item;
6366     }
6367     ++l->lv_len;
6368     item->li_next = NULL;
6369 }
6370 
6371 /*
6372  * Append typval_T "tv" to the end of list "l".
6373  * Return FAIL when out of memory.
6374  */
6375     int
6376 list_append_tv(l, tv)
6377     list_T	*l;
6378     typval_T	*tv;
6379 {
6380     listitem_T	*li = listitem_alloc();
6381 
6382     if (li == NULL)
6383 	return FAIL;
6384     copy_tv(tv, &li->li_tv);
6385     list_append(l, li);
6386     return OK;
6387 }
6388 
6389 /*
6390  * Add a dictionary to a list.  Used by getqflist().
6391  * Return FAIL when out of memory.
6392  */
6393     int
6394 list_append_dict(list, dict)
6395     list_T	*list;
6396     dict_T	*dict;
6397 {
6398     listitem_T	*li = listitem_alloc();
6399 
6400     if (li == NULL)
6401 	return FAIL;
6402     li->li_tv.v_type = VAR_DICT;
6403     li->li_tv.v_lock = 0;
6404     li->li_tv.vval.v_dict = dict;
6405     list_append(list, li);
6406     ++dict->dv_refcount;
6407     return OK;
6408 }
6409 
6410 /*
6411  * Make a copy of "str" and append it as an item to list "l".
6412  * When "len" >= 0 use "str[len]".
6413  * Returns FAIL when out of memory.
6414  */
6415     int
6416 list_append_string(l, str, len)
6417     list_T	*l;
6418     char_u	*str;
6419     int		len;
6420 {
6421     listitem_T *li = listitem_alloc();
6422 
6423     if (li == NULL)
6424 	return FAIL;
6425     list_append(l, li);
6426     li->li_tv.v_type = VAR_STRING;
6427     li->li_tv.v_lock = 0;
6428     if (str == NULL)
6429 	li->li_tv.vval.v_string = NULL;
6430     else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6431 						 : vim_strsave(str))) == NULL)
6432 	return FAIL;
6433     return OK;
6434 }
6435 
6436 /*
6437  * Append "n" to list "l".
6438  * Returns FAIL when out of memory.
6439  */
6440     static int
6441 list_append_number(l, n)
6442     list_T	*l;
6443     varnumber_T	n;
6444 {
6445     listitem_T	*li;
6446 
6447     li = listitem_alloc();
6448     if (li == NULL)
6449 	return FAIL;
6450     li->li_tv.v_type = VAR_NUMBER;
6451     li->li_tv.v_lock = 0;
6452     li->li_tv.vval.v_number = n;
6453     list_append(l, li);
6454     return OK;
6455 }
6456 
6457 /*
6458  * Insert typval_T "tv" in list "l" before "item".
6459  * If "item" is NULL append at the end.
6460  * Return FAIL when out of memory.
6461  */
6462     int
6463 list_insert_tv(l, tv, item)
6464     list_T	*l;
6465     typval_T	*tv;
6466     listitem_T	*item;
6467 {
6468     listitem_T	*ni = listitem_alloc();
6469 
6470     if (ni == NULL)
6471 	return FAIL;
6472     copy_tv(tv, &ni->li_tv);
6473     list_insert(l, ni, item);
6474     return OK;
6475 }
6476 
6477     void
6478 list_insert(l, ni, item)
6479     list_T	*l;
6480     listitem_T	*ni;
6481     listitem_T	*item;
6482 {
6483     if (item == NULL)
6484 	/* Append new item at end of list. */
6485 	list_append(l, ni);
6486     else
6487     {
6488 	/* Insert new item before existing item. */
6489 	ni->li_prev = item->li_prev;
6490 	ni->li_next = item;
6491 	if (item->li_prev == NULL)
6492 	{
6493 	    l->lv_first = ni;
6494 	    ++l->lv_idx;
6495 	}
6496 	else
6497 	{
6498 	    item->li_prev->li_next = ni;
6499 	    l->lv_idx_item = NULL;
6500 	}
6501 	item->li_prev = ni;
6502 	++l->lv_len;
6503     }
6504 }
6505 
6506 /*
6507  * Extend "l1" with "l2".
6508  * If "bef" is NULL append at the end, otherwise insert before this item.
6509  * Returns FAIL when out of memory.
6510  */
6511     static int
6512 list_extend(l1, l2, bef)
6513     list_T	*l1;
6514     list_T	*l2;
6515     listitem_T	*bef;
6516 {
6517     listitem_T	*item;
6518     int		todo = l2->lv_len;
6519 
6520     /* We also quit the loop when we have inserted the original item count of
6521      * the list, avoid a hang when we extend a list with itself. */
6522     for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6523 	if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6524 	    return FAIL;
6525     return OK;
6526 }
6527 
6528 /*
6529  * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6530  * Return FAIL when out of memory.
6531  */
6532     static int
6533 list_concat(l1, l2, tv)
6534     list_T	*l1;
6535     list_T	*l2;
6536     typval_T	*tv;
6537 {
6538     list_T	*l;
6539 
6540     if (l1 == NULL || l2 == NULL)
6541 	return FAIL;
6542 
6543     /* make a copy of the first list. */
6544     l = list_copy(l1, FALSE, 0);
6545     if (l == NULL)
6546 	return FAIL;
6547     tv->v_type = VAR_LIST;
6548     tv->vval.v_list = l;
6549 
6550     /* append all items from the second list */
6551     return list_extend(l, l2, NULL);
6552 }
6553 
6554 /*
6555  * Make a copy of list "orig".  Shallow if "deep" is FALSE.
6556  * The refcount of the new list is set to 1.
6557  * See item_copy() for "copyID".
6558  * Returns NULL when out of memory.
6559  */
6560     static list_T *
6561 list_copy(orig, deep, copyID)
6562     list_T	*orig;
6563     int		deep;
6564     int		copyID;
6565 {
6566     list_T	*copy;
6567     listitem_T	*item;
6568     listitem_T	*ni;
6569 
6570     if (orig == NULL)
6571 	return NULL;
6572 
6573     copy = list_alloc();
6574     if (copy != NULL)
6575     {
6576 	if (copyID != 0)
6577 	{
6578 	    /* Do this before adding the items, because one of the items may
6579 	     * refer back to this list. */
6580 	    orig->lv_copyID = copyID;
6581 	    orig->lv_copylist = copy;
6582 	}
6583 	for (item = orig->lv_first; item != NULL && !got_int;
6584 							 item = item->li_next)
6585 	{
6586 	    ni = listitem_alloc();
6587 	    if (ni == NULL)
6588 		break;
6589 	    if (deep)
6590 	    {
6591 		if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6592 		{
6593 		    vim_free(ni);
6594 		    break;
6595 		}
6596 	    }
6597 	    else
6598 		copy_tv(&item->li_tv, &ni->li_tv);
6599 	    list_append(copy, ni);
6600 	}
6601 	++copy->lv_refcount;
6602 	if (item != NULL)
6603 	{
6604 	    list_unref(copy);
6605 	    copy = NULL;
6606 	}
6607     }
6608 
6609     return copy;
6610 }
6611 
6612 /*
6613  * Remove items "item" to "item2" from list "l".
6614  * Does not free the listitem or the value!
6615  * This used to be called list_remove, but that conflicts with a Sun header
6616  * file.
6617  */
6618     void
6619 vimlist_remove(l, item, item2)
6620     list_T	*l;
6621     listitem_T	*item;
6622     listitem_T	*item2;
6623 {
6624     listitem_T	*ip;
6625 
6626     /* notify watchers */
6627     for (ip = item; ip != NULL; ip = ip->li_next)
6628     {
6629 	--l->lv_len;
6630 	list_fix_watch(l, ip);
6631 	if (ip == item2)
6632 	    break;
6633     }
6634 
6635     if (item2->li_next == NULL)
6636 	l->lv_last = item->li_prev;
6637     else
6638 	item2->li_next->li_prev = item->li_prev;
6639     if (item->li_prev == NULL)
6640 	l->lv_first = item2->li_next;
6641     else
6642 	item->li_prev->li_next = item2->li_next;
6643     l->lv_idx_item = NULL;
6644 }
6645 
6646 /*
6647  * Return an allocated string with the string representation of a list.
6648  * May return NULL.
6649  */
6650     static char_u *
6651 list2string(tv, copyID)
6652     typval_T	*tv;
6653     int		copyID;
6654 {
6655     garray_T	ga;
6656 
6657     if (tv->vval.v_list == NULL)
6658 	return NULL;
6659     ga_init2(&ga, (int)sizeof(char), 80);
6660     ga_append(&ga, '[');
6661     if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6662     {
6663 	vim_free(ga.ga_data);
6664 	return NULL;
6665     }
6666     ga_append(&ga, ']');
6667     ga_append(&ga, NUL);
6668     return (char_u *)ga.ga_data;
6669 }
6670 
6671 typedef struct join_S {
6672     char_u	*s;
6673     char_u	*tofree;
6674 } join_T;
6675 
6676     static int
6677 list_join_inner(gap, l, sep, echo_style, copyID, join_gap)
6678     garray_T	*gap;		/* to store the result in */
6679     list_T	*l;
6680     char_u	*sep;
6681     int		echo_style;
6682     int		copyID;
6683     garray_T	*join_gap;	/* to keep each list item string */
6684 {
6685     int		i;
6686     join_T	*p;
6687     int		len;
6688     int		sumlen = 0;
6689     int		first = TRUE;
6690     char_u	*tofree;
6691     char_u	numbuf[NUMBUFLEN];
6692     listitem_T	*item;
6693     char_u	*s;
6694 
6695     /* Stringify each item in the list. */
6696     for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6697     {
6698 	if (echo_style)
6699 	    s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6700 	else
6701 	    s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6702 	if (s == NULL)
6703 	    return FAIL;
6704 
6705 	len = (int)STRLEN(s);
6706 	sumlen += len;
6707 
6708 	ga_grow(join_gap, 1);
6709 	p = ((join_T *)join_gap->ga_data) + (join_gap->ga_len++);
6710 	if (tofree != NULL || s != numbuf)
6711 	{
6712 	    p->s = s;
6713 	    p->tofree = tofree;
6714 	}
6715 	else
6716 	{
6717 	    p->s = vim_strnsave(s, len);
6718 	    p->tofree = p->s;
6719 	}
6720 
6721 	line_breakcheck();
6722 	if (did_echo_string_emsg)  /* recursion error, bail out */
6723 	    break;
6724     }
6725 
6726     /* Allocate result buffer with its total size, avoid re-allocation and
6727      * multiple copy operations.  Add 2 for a tailing ']' and NUL. */
6728     if (join_gap->ga_len >= 2)
6729 	sumlen += (int)STRLEN(sep) * (join_gap->ga_len - 1);
6730     if (ga_grow(gap, sumlen + 2) == FAIL)
6731 	return FAIL;
6732 
6733     for (i = 0; i < join_gap->ga_len && !got_int; ++i)
6734     {
6735 	if (first)
6736 	    first = FALSE;
6737 	else
6738 	    ga_concat(gap, sep);
6739 	p = ((join_T *)join_gap->ga_data) + i;
6740 
6741 	if (p->s != NULL)
6742 	    ga_concat(gap, p->s);
6743 	line_breakcheck();
6744     }
6745 
6746     return OK;
6747 }
6748 
6749 /*
6750  * Join list "l" into a string in "*gap", using separator "sep".
6751  * When "echo_style" is TRUE use String as echoed, otherwise as inside a List.
6752  * Return FAIL or OK.
6753  */
6754     static int
6755 list_join(gap, l, sep, echo_style, copyID)
6756     garray_T	*gap;
6757     list_T	*l;
6758     char_u	*sep;
6759     int		echo_style;
6760     int		copyID;
6761 {
6762     garray_T	join_ga;
6763     int		retval;
6764     join_T	*p;
6765     int		i;
6766 
6767     ga_init2(&join_ga, (int)sizeof(join_T), l->lv_len);
6768     retval = list_join_inner(gap, l, sep, echo_style, copyID, &join_ga);
6769 
6770     /* Dispose each item in join_ga. */
6771     if (join_ga.ga_data != NULL)
6772     {
6773 	p = (join_T *)join_ga.ga_data;
6774 	for (i = 0; i < join_ga.ga_len; ++i)
6775 	{
6776 	    vim_free(p->tofree);
6777 	    ++p;
6778 	}
6779 	ga_clear(&join_ga);
6780     }
6781 
6782     return retval;
6783 }
6784 
6785 /*
6786  * Garbage collection for lists and dictionaries.
6787  *
6788  * We use reference counts to be able to free most items right away when they
6789  * are no longer used.  But for composite items it's possible that it becomes
6790  * unused while the reference count is > 0: When there is a recursive
6791  * reference.  Example:
6792  *	:let l = [1, 2, 3]
6793  *	:let d = {9: l}
6794  *	:let l[1] = d
6795  *
6796  * Since this is quite unusual we handle this with garbage collection: every
6797  * once in a while find out which lists and dicts are not referenced from any
6798  * variable.
6799  *
6800  * Here is a good reference text about garbage collection (refers to Python
6801  * but it applies to all reference-counting mechanisms):
6802  *	http://python.ca/nas/python/gc/
6803  */
6804 
6805 /*
6806  * Do garbage collection for lists and dicts.
6807  * Return TRUE if some memory was freed.
6808  */
6809     int
6810 garbage_collect()
6811 {
6812     int		copyID;
6813     buf_T	*buf;
6814     win_T	*wp;
6815     int		i;
6816     funccall_T	*fc, **pfc;
6817     int		did_free;
6818     int		did_free_funccal = FALSE;
6819 #ifdef FEAT_WINDOWS
6820     tabpage_T	*tp;
6821 #endif
6822 
6823     /* Only do this once. */
6824     want_garbage_collect = FALSE;
6825     may_garbage_collect = FALSE;
6826     garbage_collect_at_exit = FALSE;
6827 
6828     /* We advance by two because we add one for items referenced through
6829      * previous_funccal. */
6830     current_copyID += COPYID_INC;
6831     copyID = current_copyID;
6832 
6833     /*
6834      * 1. Go through all accessible variables and mark all lists and dicts
6835      *    with copyID.
6836      */
6837 
6838     /* Don't free variables in the previous_funccal list unless they are only
6839      * referenced through previous_funccal.  This must be first, because if
6840      * the item is referenced elsewhere the funccal must not be freed. */
6841     for (fc = previous_funccal; fc != NULL; fc = fc->caller)
6842     {
6843 	set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1);
6844 	set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1);
6845     }
6846 
6847     /* script-local variables */
6848     for (i = 1; i <= ga_scripts.ga_len; ++i)
6849 	set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6850 
6851     /* buffer-local variables */
6852     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6853 	set_ref_in_item(&buf->b_bufvar.di_tv, copyID);
6854 
6855     /* window-local variables */
6856     FOR_ALL_TAB_WINDOWS(tp, wp)
6857 	set_ref_in_item(&wp->w_winvar.di_tv, copyID);
6858 #ifdef FEAT_AUTOCMD
6859     if (aucmd_win != NULL)
6860 	set_ref_in_item(&aucmd_win->w_winvar.di_tv, copyID);
6861 #endif
6862 
6863 #ifdef FEAT_WINDOWS
6864     /* tabpage-local variables */
6865     for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6866 	set_ref_in_item(&tp->tp_winvar.di_tv, copyID);
6867 #endif
6868 
6869     /* global variables */
6870     set_ref_in_ht(&globvarht, copyID);
6871 
6872     /* function-local variables */
6873     for (fc = current_funccal; fc != NULL; fc = fc->caller)
6874     {
6875 	set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6876 	set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6877     }
6878 
6879     /* v: vars */
6880     set_ref_in_ht(&vimvarht, copyID);
6881 
6882 #ifdef FEAT_LUA
6883     set_ref_in_lua(copyID);
6884 #endif
6885 
6886 #ifdef FEAT_PYTHON
6887     set_ref_in_python(copyID);
6888 #endif
6889 
6890 #ifdef FEAT_PYTHON3
6891     set_ref_in_python3(copyID);
6892 #endif
6893 
6894     /*
6895      * 2. Free lists and dictionaries that are not referenced.
6896      */
6897     did_free = free_unref_items(copyID);
6898 
6899     /*
6900      * 3. Check if any funccal can be freed now.
6901      */
6902     for (pfc = &previous_funccal; *pfc != NULL; )
6903     {
6904 	if (can_free_funccal(*pfc, copyID))
6905 	{
6906 	    fc = *pfc;
6907 	    *pfc = fc->caller;
6908 	    free_funccal(fc, TRUE);
6909 	    did_free = TRUE;
6910 	    did_free_funccal = TRUE;
6911 	}
6912 	else
6913 	    pfc = &(*pfc)->caller;
6914     }
6915     if (did_free_funccal)
6916 	/* When a funccal was freed some more items might be garbage
6917 	 * collected, so run again. */
6918 	(void)garbage_collect();
6919 
6920     return did_free;
6921 }
6922 
6923 /*
6924  * Free lists and dictionaries that are no longer referenced.
6925  */
6926     static int
6927 free_unref_items(copyID)
6928     int copyID;
6929 {
6930     dict_T	*dd;
6931     list_T	*ll;
6932     int		did_free = FALSE;
6933 
6934     /*
6935      * Go through the list of dicts and free items without the copyID.
6936      */
6937     for (dd = first_dict; dd != NULL; )
6938 	if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK))
6939 	{
6940 	    /* Free the Dictionary and ordinary items it contains, but don't
6941 	     * recurse into Lists and Dictionaries, they will be in the list
6942 	     * of dicts or list of lists. */
6943 	    dict_free(dd, FALSE);
6944 	    did_free = TRUE;
6945 
6946 	    /* restart, next dict may also have been freed */
6947 	    dd = first_dict;
6948 	}
6949 	else
6950 	    dd = dd->dv_used_next;
6951 
6952     /*
6953      * Go through the list of lists and free items without the copyID.
6954      * But don't free a list that has a watcher (used in a for loop), these
6955      * are not referenced anywhere.
6956      */
6957     for (ll = first_list; ll != NULL; )
6958 	if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)
6959 						      && ll->lv_watch == NULL)
6960 	{
6961 	    /* Free the List and ordinary items it contains, but don't recurse
6962 	     * into Lists and Dictionaries, they will be in the list of dicts
6963 	     * or list of lists. */
6964 	    list_free(ll, FALSE);
6965 	    did_free = TRUE;
6966 
6967 	    /* restart, next list may also have been freed */
6968 	    ll = first_list;
6969 	}
6970 	else
6971 	    ll = ll->lv_used_next;
6972 
6973     return did_free;
6974 }
6975 
6976 /*
6977  * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6978  */
6979     void
6980 set_ref_in_ht(ht, copyID)
6981     hashtab_T	*ht;
6982     int		copyID;
6983 {
6984     int		todo;
6985     hashitem_T	*hi;
6986 
6987     todo = (int)ht->ht_used;
6988     for (hi = ht->ht_array; todo > 0; ++hi)
6989 	if (!HASHITEM_EMPTY(hi))
6990 	{
6991 	    --todo;
6992 	    set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6993 	}
6994 }
6995 
6996 /*
6997  * Mark all lists and dicts referenced through list "l" with "copyID".
6998  */
6999     void
7000 set_ref_in_list(l, copyID)
7001     list_T	*l;
7002     int		copyID;
7003 {
7004     listitem_T *li;
7005 
7006     for (li = l->lv_first; li != NULL; li = li->li_next)
7007 	set_ref_in_item(&li->li_tv, copyID);
7008 }
7009 
7010 /*
7011  * Mark all lists and dicts referenced through typval "tv" with "copyID".
7012  */
7013     void
7014 set_ref_in_item(tv, copyID)
7015     typval_T	*tv;
7016     int		copyID;
7017 {
7018     dict_T	*dd;
7019     list_T	*ll;
7020 
7021     switch (tv->v_type)
7022     {
7023 	case VAR_DICT:
7024 	    dd = tv->vval.v_dict;
7025 	    if (dd != NULL && dd->dv_copyID != copyID)
7026 	    {
7027 		/* Didn't see this dict yet. */
7028 		dd->dv_copyID = copyID;
7029 		set_ref_in_ht(&dd->dv_hashtab, copyID);
7030 	    }
7031 	    break;
7032 
7033 	case VAR_LIST:
7034 	    ll = tv->vval.v_list;
7035 	    if (ll != NULL && ll->lv_copyID != copyID)
7036 	    {
7037 		/* Didn't see this list yet. */
7038 		ll->lv_copyID = copyID;
7039 		set_ref_in_list(ll, copyID);
7040 	    }
7041 	    break;
7042     }
7043     return;
7044 }
7045 
7046 /*
7047  * Allocate an empty header for a dictionary.
7048  */
7049     dict_T *
7050 dict_alloc()
7051 {
7052     dict_T *d;
7053 
7054     d = (dict_T *)alloc(sizeof(dict_T));
7055     if (d != NULL)
7056     {
7057 	/* Add the dict to the list of dicts for garbage collection. */
7058 	if (first_dict != NULL)
7059 	    first_dict->dv_used_prev = d;
7060 	d->dv_used_next = first_dict;
7061 	d->dv_used_prev = NULL;
7062 	first_dict = d;
7063 
7064 	hash_init(&d->dv_hashtab);
7065 	d->dv_lock = 0;
7066 	d->dv_scope = 0;
7067 	d->dv_refcount = 0;
7068 	d->dv_copyID = 0;
7069     }
7070     return d;
7071 }
7072 
7073 /*
7074  * Allocate an empty dict for a return value.
7075  * Returns OK or FAIL.
7076  */
7077     static int
7078 rettv_dict_alloc(rettv)
7079     typval_T	*rettv;
7080 {
7081     dict_T	*d = dict_alloc();
7082 
7083     if (d == NULL)
7084 	return FAIL;
7085 
7086     rettv->vval.v_dict = d;
7087     rettv->v_type = VAR_DICT;
7088     ++d->dv_refcount;
7089     return OK;
7090 }
7091 
7092 
7093 /*
7094  * Unreference a Dictionary: decrement the reference count and free it when it
7095  * becomes zero.
7096  */
7097     void
7098 dict_unref(d)
7099     dict_T *d;
7100 {
7101     if (d != NULL && --d->dv_refcount <= 0)
7102 	dict_free(d, TRUE);
7103 }
7104 
7105 /*
7106  * Free a Dictionary, including all items it contains.
7107  * Ignores the reference count.
7108  */
7109     void
7110 dict_free(d, recurse)
7111     dict_T  *d;
7112     int	    recurse;	/* Free Lists and Dictionaries recursively. */
7113 {
7114     int		todo;
7115     hashitem_T	*hi;
7116     dictitem_T	*di;
7117 
7118     /* Remove the dict from the list of dicts for garbage collection. */
7119     if (d->dv_used_prev == NULL)
7120 	first_dict = d->dv_used_next;
7121     else
7122 	d->dv_used_prev->dv_used_next = d->dv_used_next;
7123     if (d->dv_used_next != NULL)
7124 	d->dv_used_next->dv_used_prev = d->dv_used_prev;
7125 
7126     /* Lock the hashtab, we don't want it to resize while freeing items. */
7127     hash_lock(&d->dv_hashtab);
7128     todo = (int)d->dv_hashtab.ht_used;
7129     for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
7130     {
7131 	if (!HASHITEM_EMPTY(hi))
7132 	{
7133 	    /* Remove the item before deleting it, just in case there is
7134 	     * something recursive causing trouble. */
7135 	    di = HI2DI(hi);
7136 	    hash_remove(&d->dv_hashtab, hi);
7137 	    if (recurse || (di->di_tv.v_type != VAR_LIST
7138 					     && di->di_tv.v_type != VAR_DICT))
7139 		clear_tv(&di->di_tv);
7140 	    vim_free(di);
7141 	    --todo;
7142 	}
7143     }
7144     hash_clear(&d->dv_hashtab);
7145     vim_free(d);
7146 }
7147 
7148 /*
7149  * Allocate a Dictionary item.
7150  * The "key" is copied to the new item.
7151  * Note that the value of the item "di_tv" still needs to be initialized!
7152  * Returns NULL when out of memory.
7153  */
7154     dictitem_T *
7155 dictitem_alloc(key)
7156     char_u	*key;
7157 {
7158     dictitem_T *di;
7159 
7160     di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
7161     if (di != NULL)
7162     {
7163 	STRCPY(di->di_key, key);
7164 	di->di_flags = 0;
7165     }
7166     return di;
7167 }
7168 
7169 /*
7170  * Make a copy of a Dictionary item.
7171  */
7172     static dictitem_T *
7173 dictitem_copy(org)
7174     dictitem_T *org;
7175 {
7176     dictitem_T *di;
7177 
7178     di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
7179 						      + STRLEN(org->di_key)));
7180     if (di != NULL)
7181     {
7182 	STRCPY(di->di_key, org->di_key);
7183 	di->di_flags = 0;
7184 	copy_tv(&org->di_tv, &di->di_tv);
7185     }
7186     return di;
7187 }
7188 
7189 /*
7190  * Remove item "item" from Dictionary "dict" and free it.
7191  */
7192     static void
7193 dictitem_remove(dict, item)
7194     dict_T	*dict;
7195     dictitem_T	*item;
7196 {
7197     hashitem_T	*hi;
7198 
7199     hi = hash_find(&dict->dv_hashtab, item->di_key);
7200     if (HASHITEM_EMPTY(hi))
7201 	EMSG2(_(e_intern2), "dictitem_remove()");
7202     else
7203 	hash_remove(&dict->dv_hashtab, hi);
7204     dictitem_free(item);
7205 }
7206 
7207 /*
7208  * Free a dict item.  Also clears the value.
7209  */
7210     void
7211 dictitem_free(item)
7212     dictitem_T *item;
7213 {
7214     clear_tv(&item->di_tv);
7215     vim_free(item);
7216 }
7217 
7218 /*
7219  * Make a copy of dict "d".  Shallow if "deep" is FALSE.
7220  * The refcount of the new dict is set to 1.
7221  * See item_copy() for "copyID".
7222  * Returns NULL when out of memory.
7223  */
7224     static dict_T *
7225 dict_copy(orig, deep, copyID)
7226     dict_T	*orig;
7227     int		deep;
7228     int		copyID;
7229 {
7230     dict_T	*copy;
7231     dictitem_T	*di;
7232     int		todo;
7233     hashitem_T	*hi;
7234 
7235     if (orig == NULL)
7236 	return NULL;
7237 
7238     copy = dict_alloc();
7239     if (copy != NULL)
7240     {
7241 	if (copyID != 0)
7242 	{
7243 	    orig->dv_copyID = copyID;
7244 	    orig->dv_copydict = copy;
7245 	}
7246 	todo = (int)orig->dv_hashtab.ht_used;
7247 	for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7248 	{
7249 	    if (!HASHITEM_EMPTY(hi))
7250 	    {
7251 		--todo;
7252 
7253 		di = dictitem_alloc(hi->hi_key);
7254 		if (di == NULL)
7255 		    break;
7256 		if (deep)
7257 		{
7258 		    if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
7259 							      copyID) == FAIL)
7260 		    {
7261 			vim_free(di);
7262 			break;
7263 		    }
7264 		}
7265 		else
7266 		    copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
7267 		if (dict_add(copy, di) == FAIL)
7268 		{
7269 		    dictitem_free(di);
7270 		    break;
7271 		}
7272 	    }
7273 	}
7274 
7275 	++copy->dv_refcount;
7276 	if (todo > 0)
7277 	{
7278 	    dict_unref(copy);
7279 	    copy = NULL;
7280 	}
7281     }
7282 
7283     return copy;
7284 }
7285 
7286 /*
7287  * Add item "item" to Dictionary "d".
7288  * Returns FAIL when out of memory and when key already exists.
7289  */
7290     int
7291 dict_add(d, item)
7292     dict_T	*d;
7293     dictitem_T	*item;
7294 {
7295     return hash_add(&d->dv_hashtab, item->di_key);
7296 }
7297 
7298 /*
7299  * Add a number or string entry to dictionary "d".
7300  * When "str" is NULL use number "nr", otherwise use "str".
7301  * Returns FAIL when out of memory and when key already exists.
7302  */
7303     int
7304 dict_add_nr_str(d, key, nr, str)
7305     dict_T	*d;
7306     char	*key;
7307     long	nr;
7308     char_u	*str;
7309 {
7310     dictitem_T	*item;
7311 
7312     item = dictitem_alloc((char_u *)key);
7313     if (item == NULL)
7314 	return FAIL;
7315     item->di_tv.v_lock = 0;
7316     if (str == NULL)
7317     {
7318 	item->di_tv.v_type = VAR_NUMBER;
7319 	item->di_tv.vval.v_number = nr;
7320     }
7321     else
7322     {
7323 	item->di_tv.v_type = VAR_STRING;
7324 	item->di_tv.vval.v_string = vim_strsave(str);
7325     }
7326     if (dict_add(d, item) == FAIL)
7327     {
7328 	dictitem_free(item);
7329 	return FAIL;
7330     }
7331     return OK;
7332 }
7333 
7334 /*
7335  * Add a list entry to dictionary "d".
7336  * Returns FAIL when out of memory and when key already exists.
7337  */
7338     int
7339 dict_add_list(d, key, list)
7340     dict_T	*d;
7341     char	*key;
7342     list_T	*list;
7343 {
7344     dictitem_T	*item;
7345 
7346     item = dictitem_alloc((char_u *)key);
7347     if (item == NULL)
7348 	return FAIL;
7349     item->di_tv.v_lock = 0;
7350     item->di_tv.v_type = VAR_LIST;
7351     item->di_tv.vval.v_list = list;
7352     if (dict_add(d, item) == FAIL)
7353     {
7354 	dictitem_free(item);
7355 	return FAIL;
7356     }
7357     ++list->lv_refcount;
7358     return OK;
7359 }
7360 
7361 /*
7362  * Get the number of items in a Dictionary.
7363  */
7364     static long
7365 dict_len(d)
7366     dict_T	*d;
7367 {
7368     if (d == NULL)
7369 	return 0L;
7370     return (long)d->dv_hashtab.ht_used;
7371 }
7372 
7373 /*
7374  * Find item "key[len]" in Dictionary "d".
7375  * If "len" is negative use strlen(key).
7376  * Returns NULL when not found.
7377  */
7378     dictitem_T *
7379 dict_find(d, key, len)
7380     dict_T	*d;
7381     char_u	*key;
7382     int		len;
7383 {
7384 #define AKEYLEN 200
7385     char_u	buf[AKEYLEN];
7386     char_u	*akey;
7387     char_u	*tofree = NULL;
7388     hashitem_T	*hi;
7389 
7390     if (len < 0)
7391 	akey = key;
7392     else if (len >= AKEYLEN)
7393     {
7394 	tofree = akey = vim_strnsave(key, len);
7395 	if (akey == NULL)
7396 	    return NULL;
7397     }
7398     else
7399     {
7400 	/* Avoid a malloc/free by using buf[]. */
7401 	vim_strncpy(buf, key, len);
7402 	akey = buf;
7403     }
7404 
7405     hi = hash_find(&d->dv_hashtab, akey);
7406     vim_free(tofree);
7407     if (HASHITEM_EMPTY(hi))
7408 	return NULL;
7409     return HI2DI(hi);
7410 }
7411 
7412 /*
7413  * Get a string item from a dictionary.
7414  * When "save" is TRUE allocate memory for it.
7415  * Returns NULL if the entry doesn't exist or out of memory.
7416  */
7417     char_u *
7418 get_dict_string(d, key, save)
7419     dict_T	*d;
7420     char_u	*key;
7421     int		save;
7422 {
7423     dictitem_T	*di;
7424     char_u	*s;
7425 
7426     di = dict_find(d, key, -1);
7427     if (di == NULL)
7428 	return NULL;
7429     s = get_tv_string(&di->di_tv);
7430     if (save && s != NULL)
7431 	s = vim_strsave(s);
7432     return s;
7433 }
7434 
7435 /*
7436  * Get a number item from a dictionary.
7437  * Returns 0 if the entry doesn't exist or out of memory.
7438  */
7439     long
7440 get_dict_number(d, key)
7441     dict_T	*d;
7442     char_u	*key;
7443 {
7444     dictitem_T	*di;
7445 
7446     di = dict_find(d, key, -1);
7447     if (di == NULL)
7448 	return 0;
7449     return get_tv_number(&di->di_tv);
7450 }
7451 
7452 /*
7453  * Return an allocated string with the string representation of a Dictionary.
7454  * May return NULL.
7455  */
7456     static char_u *
7457 dict2string(tv, copyID)
7458     typval_T	*tv;
7459     int		copyID;
7460 {
7461     garray_T	ga;
7462     int		first = TRUE;
7463     char_u	*tofree;
7464     char_u	numbuf[NUMBUFLEN];
7465     hashitem_T	*hi;
7466     char_u	*s;
7467     dict_T	*d;
7468     int		todo;
7469 
7470     if ((d = tv->vval.v_dict) == NULL)
7471 	return NULL;
7472     ga_init2(&ga, (int)sizeof(char), 80);
7473     ga_append(&ga, '{');
7474 
7475     todo = (int)d->dv_hashtab.ht_used;
7476     for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7477     {
7478 	if (!HASHITEM_EMPTY(hi))
7479 	{
7480 	    --todo;
7481 
7482 	    if (first)
7483 		first = FALSE;
7484 	    else
7485 		ga_concat(&ga, (char_u *)", ");
7486 
7487 	    tofree = string_quote(hi->hi_key, FALSE);
7488 	    if (tofree != NULL)
7489 	    {
7490 		ga_concat(&ga, tofree);
7491 		vim_free(tofree);
7492 	    }
7493 	    ga_concat(&ga, (char_u *)": ");
7494 	    s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7495 	    if (s != NULL)
7496 		ga_concat(&ga, s);
7497 	    vim_free(tofree);
7498 	    if (s == NULL || did_echo_string_emsg)
7499 		break;
7500 	    line_breakcheck();
7501 
7502 	}
7503     }
7504     if (todo > 0)
7505     {
7506 	vim_free(ga.ga_data);
7507 	return NULL;
7508     }
7509 
7510     ga_append(&ga, '}');
7511     ga_append(&ga, NUL);
7512     return (char_u *)ga.ga_data;
7513 }
7514 
7515 /*
7516  * Allocate a variable for a Dictionary and fill it from "*arg".
7517  * Return OK or FAIL.  Returns NOTDONE for {expr}.
7518  */
7519     static int
7520 get_dict_tv(arg, rettv, evaluate)
7521     char_u	**arg;
7522     typval_T	*rettv;
7523     int		evaluate;
7524 {
7525     dict_T	*d = NULL;
7526     typval_T	tvkey;
7527     typval_T	tv;
7528     char_u	*key = NULL;
7529     dictitem_T	*item;
7530     char_u	*start = skipwhite(*arg + 1);
7531     char_u	buf[NUMBUFLEN];
7532 
7533     /*
7534      * First check if it's not a curly-braces thing: {expr}.
7535      * Must do this without evaluating, otherwise a function may be called
7536      * twice.  Unfortunately this means we need to call eval1() twice for the
7537      * first item.
7538      * But {} is an empty Dictionary.
7539      */
7540     if (*start != '}')
7541     {
7542 	if (eval1(&start, &tv, FALSE) == FAIL)	/* recursive! */
7543 	    return FAIL;
7544 	if (*start == '}')
7545 	    return NOTDONE;
7546     }
7547 
7548     if (evaluate)
7549     {
7550 	d = dict_alloc();
7551 	if (d == NULL)
7552 	    return FAIL;
7553     }
7554     tvkey.v_type = VAR_UNKNOWN;
7555     tv.v_type = VAR_UNKNOWN;
7556 
7557     *arg = skipwhite(*arg + 1);
7558     while (**arg != '}' && **arg != NUL)
7559     {
7560 	if (eval1(arg, &tvkey, evaluate) == FAIL)	/* recursive! */
7561 	    goto failret;
7562 	if (**arg != ':')
7563 	{
7564 	    EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7565 	    clear_tv(&tvkey);
7566 	    goto failret;
7567 	}
7568 	if (evaluate)
7569 	{
7570 	    key = get_tv_string_buf_chk(&tvkey, buf);
7571 	    if (key == NULL || *key == NUL)
7572 	    {
7573 		/* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7574 		if (key != NULL)
7575 		    EMSG(_(e_emptykey));
7576 		clear_tv(&tvkey);
7577 		goto failret;
7578 	    }
7579 	}
7580 
7581 	*arg = skipwhite(*arg + 1);
7582 	if (eval1(arg, &tv, evaluate) == FAIL)	/* recursive! */
7583 	{
7584 	    if (evaluate)
7585 		clear_tv(&tvkey);
7586 	    goto failret;
7587 	}
7588 	if (evaluate)
7589 	{
7590 	    item = dict_find(d, key, -1);
7591 	    if (item != NULL)
7592 	    {
7593 		EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7594 		clear_tv(&tvkey);
7595 		clear_tv(&tv);
7596 		goto failret;
7597 	    }
7598 	    item = dictitem_alloc(key);
7599 	    clear_tv(&tvkey);
7600 	    if (item != NULL)
7601 	    {
7602 		item->di_tv = tv;
7603 		item->di_tv.v_lock = 0;
7604 		if (dict_add(d, item) == FAIL)
7605 		    dictitem_free(item);
7606 	    }
7607 	}
7608 
7609 	if (**arg == '}')
7610 	    break;
7611 	if (**arg != ',')
7612 	{
7613 	    EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7614 	    goto failret;
7615 	}
7616 	*arg = skipwhite(*arg + 1);
7617     }
7618 
7619     if (**arg != '}')
7620     {
7621 	EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7622 failret:
7623 	if (evaluate)
7624 	    dict_free(d, TRUE);
7625 	return FAIL;
7626     }
7627 
7628     *arg = skipwhite(*arg + 1);
7629     if (evaluate)
7630     {
7631 	rettv->v_type = VAR_DICT;
7632 	rettv->vval.v_dict = d;
7633 	++d->dv_refcount;
7634     }
7635 
7636     return OK;
7637 }
7638 
7639 /*
7640  * Return a string with the string representation of a variable.
7641  * If the memory is allocated "tofree" is set to it, otherwise NULL.
7642  * "numbuf" is used for a number.
7643  * Does not put quotes around strings, as ":echo" displays values.
7644  * When "copyID" is not NULL replace recursive lists and dicts with "...".
7645  * May return NULL.
7646  */
7647     static char_u *
7648 echo_string(tv, tofree, numbuf, copyID)
7649     typval_T	*tv;
7650     char_u	**tofree;
7651     char_u	*numbuf;
7652     int		copyID;
7653 {
7654     static int	recurse = 0;
7655     char_u	*r = NULL;
7656 
7657     if (recurse >= DICT_MAXNEST)
7658     {
7659 	if (!did_echo_string_emsg)
7660 	{
7661 	    /* Only give this message once for a recursive call to avoid
7662 	     * flooding the user with errors.  And stop iterating over lists
7663 	     * and dicts. */
7664 	    did_echo_string_emsg = TRUE;
7665 	    EMSG(_("E724: variable nested too deep for displaying"));
7666 	}
7667 	*tofree = NULL;
7668 	return (char_u *)"{E724}";
7669     }
7670     ++recurse;
7671 
7672     switch (tv->v_type)
7673     {
7674 	case VAR_FUNC:
7675 	    *tofree = NULL;
7676 	    r = tv->vval.v_string;
7677 	    break;
7678 
7679 	case VAR_LIST:
7680 	    if (tv->vval.v_list == NULL)
7681 	    {
7682 		*tofree = NULL;
7683 		r = NULL;
7684 	    }
7685 	    else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7686 	    {
7687 		*tofree = NULL;
7688 		r = (char_u *)"[...]";
7689 	    }
7690 	    else
7691 	    {
7692 		tv->vval.v_list->lv_copyID = copyID;
7693 		*tofree = list2string(tv, copyID);
7694 		r = *tofree;
7695 	    }
7696 	    break;
7697 
7698 	case VAR_DICT:
7699 	    if (tv->vval.v_dict == NULL)
7700 	    {
7701 		*tofree = NULL;
7702 		r = NULL;
7703 	    }
7704 	    else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7705 	    {
7706 		*tofree = NULL;
7707 		r = (char_u *)"{...}";
7708 	    }
7709 	    else
7710 	    {
7711 		tv->vval.v_dict->dv_copyID = copyID;
7712 		*tofree = dict2string(tv, copyID);
7713 		r = *tofree;
7714 	    }
7715 	    break;
7716 
7717 	case VAR_STRING:
7718 	case VAR_NUMBER:
7719 	    *tofree = NULL;
7720 	    r = get_tv_string_buf(tv, numbuf);
7721 	    break;
7722 
7723 #ifdef FEAT_FLOAT
7724 	case VAR_FLOAT:
7725 	    *tofree = NULL;
7726 	    vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7727 	    r = numbuf;
7728 	    break;
7729 #endif
7730 
7731 	default:
7732 	    EMSG2(_(e_intern2), "echo_string()");
7733 	    *tofree = NULL;
7734     }
7735 
7736     if (--recurse == 0)
7737 	did_echo_string_emsg = FALSE;
7738     return r;
7739 }
7740 
7741 /*
7742  * Return a string with the string representation of a variable.
7743  * If the memory is allocated "tofree" is set to it, otherwise NULL.
7744  * "numbuf" is used for a number.
7745  * Puts quotes around strings, so that they can be parsed back by eval().
7746  * May return NULL.
7747  */
7748     static char_u *
7749 tv2string(tv, tofree, numbuf, copyID)
7750     typval_T	*tv;
7751     char_u	**tofree;
7752     char_u	*numbuf;
7753     int		copyID;
7754 {
7755     switch (tv->v_type)
7756     {
7757 	case VAR_FUNC:
7758 	    *tofree = string_quote(tv->vval.v_string, TRUE);
7759 	    return *tofree;
7760 	case VAR_STRING:
7761 	    *tofree = string_quote(tv->vval.v_string, FALSE);
7762 	    return *tofree;
7763 #ifdef FEAT_FLOAT
7764 	case VAR_FLOAT:
7765 	    *tofree = NULL;
7766 	    vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7767 	    return numbuf;
7768 #endif
7769 	case VAR_NUMBER:
7770 	case VAR_LIST:
7771 	case VAR_DICT:
7772 	    break;
7773 	default:
7774 	    EMSG2(_(e_intern2), "tv2string()");
7775     }
7776     return echo_string(tv, tofree, numbuf, copyID);
7777 }
7778 
7779 /*
7780  * Return string "str" in ' quotes, doubling ' characters.
7781  * If "str" is NULL an empty string is assumed.
7782  * If "function" is TRUE make it function('string').
7783  */
7784     static char_u *
7785 string_quote(str, function)
7786     char_u	*str;
7787     int		function;
7788 {
7789     unsigned	len;
7790     char_u	*p, *r, *s;
7791 
7792     len = (function ? 13 : 3);
7793     if (str != NULL)
7794     {
7795 	len += (unsigned)STRLEN(str);
7796 	for (p = str; *p != NUL; mb_ptr_adv(p))
7797 	    if (*p == '\'')
7798 		++len;
7799     }
7800     s = r = alloc(len);
7801     if (r != NULL)
7802     {
7803 	if (function)
7804 	{
7805 	    STRCPY(r, "function('");
7806 	    r += 10;
7807 	}
7808 	else
7809 	    *r++ = '\'';
7810 	if (str != NULL)
7811 	    for (p = str; *p != NUL; )
7812 	    {
7813 		if (*p == '\'')
7814 		    *r++ = '\'';
7815 		MB_COPY_CHAR(p, r);
7816 	    }
7817 	*r++ = '\'';
7818 	if (function)
7819 	    *r++ = ')';
7820 	*r++ = NUL;
7821     }
7822     return s;
7823 }
7824 
7825 #ifdef FEAT_FLOAT
7826 /*
7827  * Convert the string "text" to a floating point number.
7828  * This uses strtod().  setlocale(LC_NUMERIC, "C") has been used to make sure
7829  * this always uses a decimal point.
7830  * Returns the length of the text that was consumed.
7831  */
7832     static int
7833 string2float(text, value)
7834     char_u	*text;
7835     float_T	*value;	    /* result stored here */
7836 {
7837     char	*s = (char *)text;
7838     float_T	f;
7839 
7840     f = strtod(s, &s);
7841     *value = f;
7842     return (int)((char_u *)s - text);
7843 }
7844 #endif
7845 
7846 /*
7847  * Get the value of an environment variable.
7848  * "arg" is pointing to the '$'.  It is advanced to after the name.
7849  * If the environment variable was not set, silently assume it is empty.
7850  * Return FAIL if the name is invalid.
7851  */
7852     static int
7853 get_env_tv(arg, rettv, evaluate)
7854     char_u	**arg;
7855     typval_T	*rettv;
7856     int		evaluate;
7857 {
7858     char_u	*string = NULL;
7859     int		len;
7860     int		cc;
7861     char_u	*name;
7862     int		mustfree = FALSE;
7863 
7864     ++*arg;
7865     name = *arg;
7866     len = get_env_len(arg);
7867     if (evaluate)
7868     {
7869 	if (len == 0)
7870            return FAIL; /* can't be an environment variable */
7871 
7872 	cc = name[len];
7873 	name[len] = NUL;
7874 	/* first try vim_getenv(), fast for normal environment vars */
7875 	string = vim_getenv(name, &mustfree);
7876 	if (string != NULL && *string != NUL)
7877 	{
7878 	    if (!mustfree)
7879 		string = vim_strsave(string);
7880 	}
7881 	else
7882 	{
7883 	    if (mustfree)
7884 		vim_free(string);
7885 
7886 	    /* next try expanding things like $VIM and ${HOME} */
7887 	    string = expand_env_save(name - 1);
7888 	    if (string != NULL && *string == '$')
7889 	    {
7890 		vim_free(string);
7891 		string = NULL;
7892 	    }
7893 	}
7894 	name[len] = cc;
7895 
7896 	rettv->v_type = VAR_STRING;
7897 	rettv->vval.v_string = string;
7898     }
7899 
7900     return OK;
7901 }
7902 
7903 /*
7904  * Array with names and number of arguments of all internal functions
7905  * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7906  */
7907 static struct fst
7908 {
7909     char	*f_name;	/* function name */
7910     char	f_min_argc;	/* minimal number of arguments */
7911     char	f_max_argc;	/* maximal number of arguments */
7912     void	(*f_func) __ARGS((typval_T *args, typval_T *rvar));
7913 				/* implementation of function */
7914 } functions[] =
7915 {
7916 #ifdef FEAT_FLOAT
7917     {"abs",		1, 1, f_abs},
7918     {"acos",		1, 1, f_acos},	/* WJMc */
7919 #endif
7920     {"add",		2, 2, f_add},
7921     {"and",		2, 2, f_and},
7922     {"append",		2, 2, f_append},
7923     {"argc",		0, 0, f_argc},
7924     {"argidx",		0, 0, f_argidx},
7925     {"arglistid",	0, 2, f_arglistid},
7926     {"argv",		0, 1, f_argv},
7927 #ifdef FEAT_FLOAT
7928     {"asin",		1, 1, f_asin},	/* WJMc */
7929     {"atan",		1, 1, f_atan},
7930     {"atan2",		2, 2, f_atan2},
7931 #endif
7932     {"browse",		4, 4, f_browse},
7933     {"browsedir",	2, 2, f_browsedir},
7934     {"bufexists",	1, 1, f_bufexists},
7935     {"buffer_exists",	1, 1, f_bufexists},	/* obsolete */
7936     {"buffer_name",	1, 1, f_bufname},	/* obsolete */
7937     {"buffer_number",	1, 1, f_bufnr},		/* obsolete */
7938     {"buflisted",	1, 1, f_buflisted},
7939     {"bufloaded",	1, 1, f_bufloaded},
7940     {"bufname",		1, 1, f_bufname},
7941     {"bufnr",		1, 2, f_bufnr},
7942     {"bufwinnr",	1, 1, f_bufwinnr},
7943     {"byte2line",	1, 1, f_byte2line},
7944     {"byteidx",		2, 2, f_byteidx},
7945     {"byteidxcomp",	2, 2, f_byteidxcomp},
7946     {"call",		2, 3, f_call},
7947 #ifdef FEAT_FLOAT
7948     {"ceil",		1, 1, f_ceil},
7949 #endif
7950     {"changenr",	0, 0, f_changenr},
7951     {"char2nr",		1, 2, f_char2nr},
7952     {"cindent",		1, 1, f_cindent},
7953     {"clearmatches",	0, 0, f_clearmatches},
7954     {"col",		1, 1, f_col},
7955 #if defined(FEAT_INS_EXPAND)
7956     {"complete",	2, 2, f_complete},
7957     {"complete_add",	1, 1, f_complete_add},
7958     {"complete_check",	0, 0, f_complete_check},
7959 #endif
7960     {"confirm",		1, 4, f_confirm},
7961     {"copy",		1, 1, f_copy},
7962 #ifdef FEAT_FLOAT
7963     {"cos",		1, 1, f_cos},
7964     {"cosh",		1, 1, f_cosh},
7965 #endif
7966     {"count",		2, 4, f_count},
7967     {"cscope_connection",0,3, f_cscope_connection},
7968     {"cursor",		1, 3, f_cursor},
7969     {"deepcopy",	1, 2, f_deepcopy},
7970     {"delete",		1, 1, f_delete},
7971     {"did_filetype",	0, 0, f_did_filetype},
7972     {"diff_filler",	1, 1, f_diff_filler},
7973     {"diff_hlID",	2, 2, f_diff_hlID},
7974     {"empty",		1, 1, f_empty},
7975     {"escape",		2, 2, f_escape},
7976     {"eval",		1, 1, f_eval},
7977     {"eventhandler",	0, 0, f_eventhandler},
7978     {"executable",	1, 1, f_executable},
7979     {"exepath",		1, 1, f_exepath},
7980     {"exists",		1, 1, f_exists},
7981 #ifdef FEAT_FLOAT
7982     {"exp",		1, 1, f_exp},
7983 #endif
7984     {"expand",		1, 3, f_expand},
7985     {"extend",		2, 3, f_extend},
7986     {"feedkeys",	1, 2, f_feedkeys},
7987     {"file_readable",	1, 1, f_filereadable},	/* obsolete */
7988     {"filereadable",	1, 1, f_filereadable},
7989     {"filewritable",	1, 1, f_filewritable},
7990     {"filter",		2, 2, f_filter},
7991     {"finddir",		1, 3, f_finddir},
7992     {"findfile",	1, 3, f_findfile},
7993 #ifdef FEAT_FLOAT
7994     {"float2nr",	1, 1, f_float2nr},
7995     {"floor",		1, 1, f_floor},
7996     {"fmod",		2, 2, f_fmod},
7997 #endif
7998     {"fnameescape",	1, 1, f_fnameescape},
7999     {"fnamemodify",	2, 2, f_fnamemodify},
8000     {"foldclosed",	1, 1, f_foldclosed},
8001     {"foldclosedend",	1, 1, f_foldclosedend},
8002     {"foldlevel",	1, 1, f_foldlevel},
8003     {"foldtext",	0, 0, f_foldtext},
8004     {"foldtextresult",	1, 1, f_foldtextresult},
8005     {"foreground",	0, 0, f_foreground},
8006     {"function",	1, 1, f_function},
8007     {"garbagecollect",	0, 1, f_garbagecollect},
8008     {"get",		2, 3, f_get},
8009     {"getbufline",	2, 3, f_getbufline},
8010     {"getbufvar",	2, 3, f_getbufvar},
8011     {"getchar",		0, 1, f_getchar},
8012     {"getcharmod",	0, 0, f_getcharmod},
8013     {"getcmdline",	0, 0, f_getcmdline},
8014     {"getcmdpos",	0, 0, f_getcmdpos},
8015     {"getcmdtype",	0, 0, f_getcmdtype},
8016     {"getcmdwintype",	0, 0, f_getcmdwintype},
8017     {"getcurpos",	0, 0, f_getcurpos},
8018     {"getcwd",		0, 0, f_getcwd},
8019     {"getfontname",	0, 1, f_getfontname},
8020     {"getfperm",	1, 1, f_getfperm},
8021     {"getfsize",	1, 1, f_getfsize},
8022     {"getftime",	1, 1, f_getftime},
8023     {"getftype",	1, 1, f_getftype},
8024     {"getline",		1, 2, f_getline},
8025     {"getloclist",	1, 1, f_getqflist},
8026     {"getmatches",	0, 0, f_getmatches},
8027     {"getpid",		0, 0, f_getpid},
8028     {"getpos",		1, 1, f_getpos},
8029     {"getqflist",	0, 0, f_getqflist},
8030     {"getreg",		0, 3, f_getreg},
8031     {"getregtype",	0, 1, f_getregtype},
8032     {"gettabvar",	2, 3, f_gettabvar},
8033     {"gettabwinvar",	3, 4, f_gettabwinvar},
8034     {"getwinposx",	0, 0, f_getwinposx},
8035     {"getwinposy",	0, 0, f_getwinposy},
8036     {"getwinvar",	2, 3, f_getwinvar},
8037     {"glob",		1, 3, f_glob},
8038     {"globpath",	2, 4, f_globpath},
8039     {"has",		1, 1, f_has},
8040     {"has_key",		2, 2, f_has_key},
8041     {"haslocaldir",	0, 0, f_haslocaldir},
8042     {"hasmapto",	1, 3, f_hasmapto},
8043     {"highlightID",	1, 1, f_hlID},		/* obsolete */
8044     {"highlight_exists",1, 1, f_hlexists},	/* obsolete */
8045     {"histadd",		2, 2, f_histadd},
8046     {"histdel",		1, 2, f_histdel},
8047     {"histget",		1, 2, f_histget},
8048     {"histnr",		1, 1, f_histnr},
8049     {"hlID",		1, 1, f_hlID},
8050     {"hlexists",	1, 1, f_hlexists},
8051     {"hostname",	0, 0, f_hostname},
8052     {"iconv",		3, 3, f_iconv},
8053     {"indent",		1, 1, f_indent},
8054     {"index",		2, 4, f_index},
8055     {"input",		1, 3, f_input},
8056     {"inputdialog",	1, 3, f_inputdialog},
8057     {"inputlist",	1, 1, f_inputlist},
8058     {"inputrestore",	0, 0, f_inputrestore},
8059     {"inputsave",	0, 0, f_inputsave},
8060     {"inputsecret",	1, 2, f_inputsecret},
8061     {"insert",		2, 3, f_insert},
8062     {"invert",		1, 1, f_invert},
8063     {"isdirectory",	1, 1, f_isdirectory},
8064     {"islocked",	1, 1, f_islocked},
8065     {"items",		1, 1, f_items},
8066     {"join",		1, 2, f_join},
8067     {"keys",		1, 1, f_keys},
8068     {"last_buffer_nr",	0, 0, f_last_buffer_nr},/* obsolete */
8069     {"len",		1, 1, f_len},
8070     {"libcall",		3, 3, f_libcall},
8071     {"libcallnr",	3, 3, f_libcallnr},
8072     {"line",		1, 1, f_line},
8073     {"line2byte",	1, 1, f_line2byte},
8074     {"lispindent",	1, 1, f_lispindent},
8075     {"localtime",	0, 0, f_localtime},
8076 #ifdef FEAT_FLOAT
8077     {"log",		1, 1, f_log},
8078     {"log10",		1, 1, f_log10},
8079 #endif
8080 #ifdef FEAT_LUA
8081     {"luaeval",		1, 2, f_luaeval},
8082 #endif
8083     {"map",		2, 2, f_map},
8084     {"maparg",		1, 4, f_maparg},
8085     {"mapcheck",	1, 3, f_mapcheck},
8086     {"match",		2, 4, f_match},
8087     {"matchadd",	2, 4, f_matchadd},
8088     {"matchaddpos",	2, 4, f_matchaddpos},
8089     {"matcharg",	1, 1, f_matcharg},
8090     {"matchdelete",	1, 1, f_matchdelete},
8091     {"matchend",	2, 4, f_matchend},
8092     {"matchlist",	2, 4, f_matchlist},
8093     {"matchstr",	2, 4, f_matchstr},
8094     {"max",		1, 1, f_max},
8095     {"min",		1, 1, f_min},
8096 #ifdef vim_mkdir
8097     {"mkdir",		1, 3, f_mkdir},
8098 #endif
8099     {"mode",		0, 1, f_mode},
8100 #ifdef FEAT_MZSCHEME
8101     {"mzeval",		1, 1, f_mzeval},
8102 #endif
8103     {"nextnonblank",	1, 1, f_nextnonblank},
8104     {"nr2char",		1, 2, f_nr2char},
8105     {"or",		2, 2, f_or},
8106     {"pathshorten",	1, 1, f_pathshorten},
8107 #ifdef FEAT_FLOAT
8108     {"pow",		2, 2, f_pow},
8109 #endif
8110     {"prevnonblank",	1, 1, f_prevnonblank},
8111     {"printf",		2, 19, f_printf},
8112     {"pumvisible",	0, 0, f_pumvisible},
8113 #ifdef FEAT_PYTHON3
8114     {"py3eval",		1, 1, f_py3eval},
8115 #endif
8116 #ifdef FEAT_PYTHON
8117     {"pyeval",		1, 1, f_pyeval},
8118 #endif
8119     {"range",		1, 3, f_range},
8120     {"readfile",	1, 3, f_readfile},
8121     {"reltime",		0, 2, f_reltime},
8122     {"reltimestr",	1, 1, f_reltimestr},
8123     {"remote_expr",	2, 3, f_remote_expr},
8124     {"remote_foreground", 1, 1, f_remote_foreground},
8125     {"remote_peek",	1, 2, f_remote_peek},
8126     {"remote_read",	1, 1, f_remote_read},
8127     {"remote_send",	2, 3, f_remote_send},
8128     {"remove",		2, 3, f_remove},
8129     {"rename",		2, 2, f_rename},
8130     {"repeat",		2, 2, f_repeat},
8131     {"resolve",		1, 1, f_resolve},
8132     {"reverse",		1, 1, f_reverse},
8133 #ifdef FEAT_FLOAT
8134     {"round",		1, 1, f_round},
8135 #endif
8136     {"screenattr",	2, 2, f_screenattr},
8137     {"screenchar",	2, 2, f_screenchar},
8138     {"screencol",	0, 0, f_screencol},
8139     {"screenrow",	0, 0, f_screenrow},
8140     {"search",		1, 4, f_search},
8141     {"searchdecl",	1, 3, f_searchdecl},
8142     {"searchpair",	3, 7, f_searchpair},
8143     {"searchpairpos",	3, 7, f_searchpairpos},
8144     {"searchpos",	1, 4, f_searchpos},
8145     {"server2client",	2, 2, f_server2client},
8146     {"serverlist",	0, 0, f_serverlist},
8147     {"setbufvar",	3, 3, f_setbufvar},
8148     {"setcmdpos",	1, 1, f_setcmdpos},
8149     {"setline",		2, 2, f_setline},
8150     {"setloclist",	2, 3, f_setloclist},
8151     {"setmatches",	1, 1, f_setmatches},
8152     {"setpos",		2, 2, f_setpos},
8153     {"setqflist",	1, 2, f_setqflist},
8154     {"setreg",		2, 3, f_setreg},
8155     {"settabvar",	3, 3, f_settabvar},
8156     {"settabwinvar",	4, 4, f_settabwinvar},
8157     {"setwinvar",	3, 3, f_setwinvar},
8158 #ifdef FEAT_CRYPT
8159     {"sha256",		1, 1, f_sha256},
8160 #endif
8161     {"shellescape",	1, 2, f_shellescape},
8162     {"shiftwidth",	0, 0, f_shiftwidth},
8163     {"simplify",	1, 1, f_simplify},
8164 #ifdef FEAT_FLOAT
8165     {"sin",		1, 1, f_sin},
8166     {"sinh",		1, 1, f_sinh},
8167 #endif
8168     {"sort",		1, 3, f_sort},
8169     {"soundfold",	1, 1, f_soundfold},
8170     {"spellbadword",	0, 1, f_spellbadword},
8171     {"spellsuggest",	1, 3, f_spellsuggest},
8172     {"split",		1, 3, f_split},
8173 #ifdef FEAT_FLOAT
8174     {"sqrt",		1, 1, f_sqrt},
8175     {"str2float",	1, 1, f_str2float},
8176 #endif
8177     {"str2nr",		1, 2, f_str2nr},
8178     {"strchars",	1, 1, f_strchars},
8179     {"strdisplaywidth",	1, 2, f_strdisplaywidth},
8180 #ifdef HAVE_STRFTIME
8181     {"strftime",	1, 2, f_strftime},
8182 #endif
8183     {"stridx",		2, 3, f_stridx},
8184     {"string",		1, 1, f_string},
8185     {"strlen",		1, 1, f_strlen},
8186     {"strpart",		2, 3, f_strpart},
8187     {"strridx",		2, 3, f_strridx},
8188     {"strtrans",	1, 1, f_strtrans},
8189     {"strwidth",	1, 1, f_strwidth},
8190     {"submatch",	1, 2, f_submatch},
8191     {"substitute",	4, 4, f_substitute},
8192     {"synID",		3, 3, f_synID},
8193     {"synIDattr",	2, 3, f_synIDattr},
8194     {"synIDtrans",	1, 1, f_synIDtrans},
8195     {"synconcealed",	2, 2, f_synconcealed},
8196     {"synstack",	2, 2, f_synstack},
8197     {"system",		1, 2, f_system},
8198     {"systemlist",	1, 2, f_systemlist},
8199     {"tabpagebuflist",	0, 1, f_tabpagebuflist},
8200     {"tabpagenr",	0, 1, f_tabpagenr},
8201     {"tabpagewinnr",	1, 2, f_tabpagewinnr},
8202     {"tagfiles",	0, 0, f_tagfiles},
8203     {"taglist",		1, 1, f_taglist},
8204 #ifdef FEAT_FLOAT
8205     {"tan",		1, 1, f_tan},
8206     {"tanh",		1, 1, f_tanh},
8207 #endif
8208     {"tempname",	0, 0, f_tempname},
8209     {"test",		1, 1, f_test},
8210     {"tolower",		1, 1, f_tolower},
8211     {"toupper",		1, 1, f_toupper},
8212     {"tr",		3, 3, f_tr},
8213 #ifdef FEAT_FLOAT
8214     {"trunc",		1, 1, f_trunc},
8215 #endif
8216     {"type",		1, 1, f_type},
8217     {"undofile",	1, 1, f_undofile},
8218     {"undotree",	0, 0, f_undotree},
8219     {"uniq",		1, 3, f_uniq},
8220     {"values",		1, 1, f_values},
8221     {"virtcol",		1, 1, f_virtcol},
8222     {"visualmode",	0, 1, f_visualmode},
8223     {"wildmenumode",	0, 0, f_wildmenumode},
8224     {"winbufnr",	1, 1, f_winbufnr},
8225     {"wincol",		0, 0, f_wincol},
8226     {"winheight",	1, 1, f_winheight},
8227     {"winline",		0, 0, f_winline},
8228     {"winnr",		0, 1, f_winnr},
8229     {"winrestcmd",	0, 0, f_winrestcmd},
8230     {"winrestview",	1, 1, f_winrestview},
8231     {"winsaveview",	0, 0, f_winsaveview},
8232     {"winwidth",	1, 1, f_winwidth},
8233     {"writefile",	2, 3, f_writefile},
8234     {"xor",		2, 2, f_xor},
8235 };
8236 
8237 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
8238 
8239 /*
8240  * Function given to ExpandGeneric() to obtain the list of internal
8241  * or user defined function names.
8242  */
8243     char_u *
8244 get_function_name(xp, idx)
8245     expand_T	*xp;
8246     int		idx;
8247 {
8248     static int	intidx = -1;
8249     char_u	*name;
8250 
8251     if (idx == 0)
8252 	intidx = -1;
8253     if (intidx < 0)
8254     {
8255 	name = get_user_func_name(xp, idx);
8256 	if (name != NULL)
8257 	    return name;
8258     }
8259     if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
8260     {
8261 	STRCPY(IObuff, functions[intidx].f_name);
8262 	STRCAT(IObuff, "(");
8263 	if (functions[intidx].f_max_argc == 0)
8264 	    STRCAT(IObuff, ")");
8265 	return IObuff;
8266     }
8267 
8268     return NULL;
8269 }
8270 
8271 /*
8272  * Function given to ExpandGeneric() to obtain the list of internal or
8273  * user defined variable or function names.
8274  */
8275     char_u *
8276 get_expr_name(xp, idx)
8277     expand_T	*xp;
8278     int		idx;
8279 {
8280     static int	intidx = -1;
8281     char_u	*name;
8282 
8283     if (idx == 0)
8284 	intidx = -1;
8285     if (intidx < 0)
8286     {
8287 	name = get_function_name(xp, idx);
8288 	if (name != NULL)
8289 	    return name;
8290     }
8291     return get_user_var_name(xp, ++intidx);
8292 }
8293 
8294 #endif /* FEAT_CMDL_COMPL */
8295 
8296 #if defined(EBCDIC) || defined(PROTO)
8297 /*
8298  * Compare struct fst by function name.
8299  */
8300     static int
8301 compare_func_name(s1, s2)
8302     const void *s1;
8303     const void *s2;
8304 {
8305     struct fst *p1 = (struct fst *)s1;
8306     struct fst *p2 = (struct fst *)s2;
8307 
8308     return STRCMP(p1->f_name, p2->f_name);
8309 }
8310 
8311 /*
8312  * Sort the function table by function name.
8313  * The sorting of the table above is ASCII dependant.
8314  * On machines using EBCDIC we have to sort it.
8315  */
8316     static void
8317 sortFunctions()
8318 {
8319     int		funcCnt = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
8320 
8321     qsort(functions, (size_t)funcCnt, sizeof(struct fst), compare_func_name);
8322 }
8323 #endif
8324 
8325 
8326 /*
8327  * Find internal function in table above.
8328  * Return index, or -1 if not found
8329  */
8330     static int
8331 find_internal_func(name)
8332     char_u	*name;		/* name of the function */
8333 {
8334     int		first = 0;
8335     int		last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
8336     int		cmp;
8337     int		x;
8338 
8339     /*
8340      * Find the function name in the table. Binary search.
8341      */
8342     while (first <= last)
8343     {
8344 	x = first + ((unsigned)(last - first) >> 1);
8345 	cmp = STRCMP(name, functions[x].f_name);
8346 	if (cmp < 0)
8347 	    last = x - 1;
8348 	else if (cmp > 0)
8349 	    first = x + 1;
8350 	else
8351 	    return x;
8352     }
8353     return -1;
8354 }
8355 
8356 /*
8357  * Check if "name" is a variable of type VAR_FUNC.  If so, return the function
8358  * name it contains, otherwise return "name".
8359  */
8360     static char_u *
8361 deref_func_name(name, lenp, no_autoload)
8362     char_u	*name;
8363     int		*lenp;
8364     int		no_autoload;
8365 {
8366     dictitem_T	*v;
8367     int		cc;
8368 
8369     cc = name[*lenp];
8370     name[*lenp] = NUL;
8371     v = find_var(name, NULL, no_autoload);
8372     name[*lenp] = cc;
8373     if (v != NULL && v->di_tv.v_type == VAR_FUNC)
8374     {
8375 	if (v->di_tv.vval.v_string == NULL)
8376 	{
8377 	    *lenp = 0;
8378 	    return (char_u *)"";	/* just in case */
8379 	}
8380 	*lenp = (int)STRLEN(v->di_tv.vval.v_string);
8381 	return v->di_tv.vval.v_string;
8382     }
8383 
8384     return name;
8385 }
8386 
8387 /*
8388  * Allocate a variable for the result of a function.
8389  * Return OK or FAIL.
8390  */
8391     static int
8392 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
8393 							   evaluate, selfdict)
8394     char_u	*name;		/* name of the function */
8395     int		len;		/* length of "name" */
8396     typval_T	*rettv;
8397     char_u	**arg;		/* argument, pointing to the '(' */
8398     linenr_T	firstline;	/* first line of range */
8399     linenr_T	lastline;	/* last line of range */
8400     int		*doesrange;	/* return: function handled range */
8401     int		evaluate;
8402     dict_T	*selfdict;	/* Dictionary for "self" */
8403 {
8404     char_u	*argp;
8405     int		ret = OK;
8406     typval_T	argvars[MAX_FUNC_ARGS + 1];	/* vars for arguments */
8407     int		argcount = 0;		/* number of arguments found */
8408 
8409     /*
8410      * Get the arguments.
8411      */
8412     argp = *arg;
8413     while (argcount < MAX_FUNC_ARGS)
8414     {
8415 	argp = skipwhite(argp + 1);	    /* skip the '(' or ',' */
8416 	if (*argp == ')' || *argp == ',' || *argp == NUL)
8417 	    break;
8418 	if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
8419 	{
8420 	    ret = FAIL;
8421 	    break;
8422 	}
8423 	++argcount;
8424 	if (*argp != ',')
8425 	    break;
8426     }
8427     if (*argp == ')')
8428 	++argp;
8429     else
8430 	ret = FAIL;
8431 
8432     if (ret == OK)
8433 	ret = call_func(name, len, rettv, argcount, argvars,
8434 			  firstline, lastline, doesrange, evaluate, selfdict);
8435     else if (!aborting())
8436     {
8437 	if (argcount == MAX_FUNC_ARGS)
8438 	    emsg_funcname(N_("E740: Too many arguments for function %s"), name);
8439 	else
8440 	    emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
8441     }
8442 
8443     while (--argcount >= 0)
8444 	clear_tv(&argvars[argcount]);
8445 
8446     *arg = skipwhite(argp);
8447     return ret;
8448 }
8449 
8450 
8451 /*
8452  * Call a function with its resolved parameters
8453  * Return FAIL when the function can't be called,  OK otherwise.
8454  * Also returns OK when an error was encountered while executing the function.
8455  */
8456     static int
8457 call_func(funcname, len, rettv, argcount, argvars, firstline, lastline,
8458 						doesrange, evaluate, selfdict)
8459     char_u	*funcname;	/* name of the function */
8460     int		len;		/* length of "name" */
8461     typval_T	*rettv;		/* return value goes here */
8462     int		argcount;	/* number of "argvars" */
8463     typval_T	*argvars;	/* vars for arguments, must have "argcount"
8464 				   PLUS ONE elements! */
8465     linenr_T	firstline;	/* first line of range */
8466     linenr_T	lastline;	/* last line of range */
8467     int		*doesrange;	/* return: function handled range */
8468     int		evaluate;
8469     dict_T	*selfdict;	/* Dictionary for "self" */
8470 {
8471     int		ret = FAIL;
8472 #define ERROR_UNKNOWN	0
8473 #define ERROR_TOOMANY	1
8474 #define ERROR_TOOFEW	2
8475 #define ERROR_SCRIPT	3
8476 #define ERROR_DICT	4
8477 #define ERROR_NONE	5
8478 #define ERROR_OTHER	6
8479     int		error = ERROR_NONE;
8480     int		i;
8481     int		llen;
8482     ufunc_T	*fp;
8483 #define FLEN_FIXED 40
8484     char_u	fname_buf[FLEN_FIXED + 1];
8485     char_u	*fname;
8486     char_u	*name;
8487 
8488     /* Make a copy of the name, if it comes from a funcref variable it could
8489      * be changed or deleted in the called function. */
8490     name = vim_strnsave(funcname, len);
8491     if (name == NULL)
8492 	return ret;
8493 
8494     /*
8495      * In a script change <SID>name() and s:name() to K_SNR 123_name().
8496      * Change <SNR>123_name() to K_SNR 123_name().
8497      * Use fname_buf[] when it fits, otherwise allocate memory (slow).
8498      */
8499     llen = eval_fname_script(name);
8500     if (llen > 0)
8501     {
8502 	fname_buf[0] = K_SPECIAL;
8503 	fname_buf[1] = KS_EXTRA;
8504 	fname_buf[2] = (int)KE_SNR;
8505 	i = 3;
8506 	if (eval_fname_sid(name))	/* "<SID>" or "s:" */
8507 	{
8508 	    if (current_SID <= 0)
8509 		error = ERROR_SCRIPT;
8510 	    else
8511 	    {
8512 		sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
8513 		i = (int)STRLEN(fname_buf);
8514 	    }
8515 	}
8516 	if (i + STRLEN(name + llen) < FLEN_FIXED)
8517 	{
8518 	    STRCPY(fname_buf + i, name + llen);
8519 	    fname = fname_buf;
8520 	}
8521 	else
8522 	{
8523 	    fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8524 	    if (fname == NULL)
8525 		error = ERROR_OTHER;
8526 	    else
8527 	    {
8528 		mch_memmove(fname, fname_buf, (size_t)i);
8529 		STRCPY(fname + i, name + llen);
8530 	    }
8531 	}
8532     }
8533     else
8534 	fname = name;
8535 
8536     *doesrange = FALSE;
8537 
8538 
8539     /* execute the function if no errors detected and executing */
8540     if (evaluate && error == ERROR_NONE)
8541     {
8542 	char_u *rfname = fname;
8543 
8544 	/* Ignore "g:" before a function name. */
8545 	if (fname[0] == 'g' && fname[1] == ':')
8546 	    rfname = fname + 2;
8547 
8548 	rettv->v_type = VAR_NUMBER;	/* default rettv is number zero */
8549 	rettv->vval.v_number = 0;
8550 	error = ERROR_UNKNOWN;
8551 
8552 	if (!builtin_function(rfname, -1))
8553 	{
8554 	    /*
8555 	     * User defined function.
8556 	     */
8557 	    fp = find_func(rfname);
8558 
8559 #ifdef FEAT_AUTOCMD
8560 	    /* Trigger FuncUndefined event, may load the function. */
8561 	    if (fp == NULL
8562 		    && apply_autocmds(EVENT_FUNCUNDEFINED,
8563 						     rfname, rfname, TRUE, NULL)
8564 		    && !aborting())
8565 	    {
8566 		/* executed an autocommand, search for the function again */
8567 		fp = find_func(rfname);
8568 	    }
8569 #endif
8570 	    /* Try loading a package. */
8571 	    if (fp == NULL && script_autoload(rfname, TRUE) && !aborting())
8572 	    {
8573 		/* loaded a package, search for the function again */
8574 		fp = find_func(rfname);
8575 	    }
8576 
8577 	    if (fp != NULL)
8578 	    {
8579 		if (fp->uf_flags & FC_RANGE)
8580 		    *doesrange = TRUE;
8581 		if (argcount < fp->uf_args.ga_len)
8582 		    error = ERROR_TOOFEW;
8583 		else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8584 		    error = ERROR_TOOMANY;
8585 		else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8586 		    error = ERROR_DICT;
8587 		else
8588 		{
8589 		    /*
8590 		     * Call the user function.
8591 		     * Save and restore search patterns, script variables and
8592 		     * redo buffer.
8593 		     */
8594 		    save_search_patterns();
8595 		    saveRedobuff();
8596 		    ++fp->uf_calls;
8597 		    call_user_func(fp, argcount, argvars, rettv,
8598 					       firstline, lastline,
8599 				  (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8600 		    if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8601 						      && fp->uf_refcount <= 0)
8602 			/* Function was unreferenced while being used, free it
8603 			 * now. */
8604 			func_free(fp);
8605 		    restoreRedobuff();
8606 		    restore_search_patterns();
8607 		    error = ERROR_NONE;
8608 		}
8609 	    }
8610 	}
8611 	else
8612 	{
8613 	    /*
8614 	     * Find the function name in the table, call its implementation.
8615 	     */
8616 	    i = find_internal_func(fname);
8617 	    if (i >= 0)
8618 	    {
8619 		if (argcount < functions[i].f_min_argc)
8620 		    error = ERROR_TOOFEW;
8621 		else if (argcount > functions[i].f_max_argc)
8622 		    error = ERROR_TOOMANY;
8623 		else
8624 		{
8625 		    argvars[argcount].v_type = VAR_UNKNOWN;
8626 		    functions[i].f_func(argvars, rettv);
8627 		    error = ERROR_NONE;
8628 		}
8629 	    }
8630 	}
8631 	/*
8632 	 * The function call (or "FuncUndefined" autocommand sequence) might
8633 	 * have been aborted by an error, an interrupt, or an explicitly thrown
8634 	 * exception that has not been caught so far.  This situation can be
8635 	 * tested for by calling aborting().  For an error in an internal
8636 	 * function or for the "E132" error in call_user_func(), however, the
8637 	 * throw point at which the "force_abort" flag (temporarily reset by
8638 	 * emsg()) is normally updated has not been reached yet. We need to
8639 	 * update that flag first to make aborting() reliable.
8640 	 */
8641 	update_force_abort();
8642     }
8643     if (error == ERROR_NONE)
8644 	ret = OK;
8645 
8646     /*
8647      * Report an error unless the argument evaluation or function call has been
8648      * cancelled due to an aborting error, an interrupt, or an exception.
8649      */
8650     if (!aborting())
8651     {
8652 	switch (error)
8653 	{
8654 	    case ERROR_UNKNOWN:
8655 		    emsg_funcname(N_("E117: Unknown function: %s"), name);
8656 		    break;
8657 	    case ERROR_TOOMANY:
8658 		    emsg_funcname(e_toomanyarg, name);
8659 		    break;
8660 	    case ERROR_TOOFEW:
8661 		    emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8662 									name);
8663 		    break;
8664 	    case ERROR_SCRIPT:
8665 		    emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8666 									name);
8667 		    break;
8668 	    case ERROR_DICT:
8669 		    emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8670 									name);
8671 		    break;
8672 	}
8673     }
8674 
8675     if (fname != name && fname != fname_buf)
8676 	vim_free(fname);
8677     vim_free(name);
8678 
8679     return ret;
8680 }
8681 
8682 /*
8683  * Give an error message with a function name.  Handle <SNR> things.
8684  * "ermsg" is to be passed without translation, use N_() instead of _().
8685  */
8686     static void
8687 emsg_funcname(ermsg, name)
8688     char	*ermsg;
8689     char_u	*name;
8690 {
8691     char_u	*p;
8692 
8693     if (*name == K_SPECIAL)
8694 	p = concat_str((char_u *)"<SNR>", name + 3);
8695     else
8696 	p = name;
8697     EMSG2(_(ermsg), p);
8698     if (p != name)
8699 	vim_free(p);
8700 }
8701 
8702 /*
8703  * Return TRUE for a non-zero Number and a non-empty String.
8704  */
8705     static int
8706 non_zero_arg(argvars)
8707     typval_T	*argvars;
8708 {
8709     return ((argvars[0].v_type == VAR_NUMBER
8710 		&& argvars[0].vval.v_number != 0)
8711 	    || (argvars[0].v_type == VAR_STRING
8712 		&& argvars[0].vval.v_string != NULL
8713 		&& *argvars[0].vval.v_string != NUL));
8714 }
8715 
8716 /*********************************************
8717  * Implementation of the built-in functions
8718  */
8719 
8720 #ifdef FEAT_FLOAT
8721 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8722 
8723 /*
8724  * Get the float value of "argvars[0]" into "f".
8725  * Returns FAIL when the argument is not a Number or Float.
8726  */
8727     static int
8728 get_float_arg(argvars, f)
8729     typval_T	*argvars;
8730     float_T	*f;
8731 {
8732     if (argvars[0].v_type == VAR_FLOAT)
8733     {
8734 	*f = argvars[0].vval.v_float;
8735 	return OK;
8736     }
8737     if (argvars[0].v_type == VAR_NUMBER)
8738     {
8739 	*f = (float_T)argvars[0].vval.v_number;
8740 	return OK;
8741     }
8742     EMSG(_("E808: Number or Float required"));
8743     return FAIL;
8744 }
8745 
8746 /*
8747  * "abs(expr)" function
8748  */
8749     static void
8750 f_abs(argvars, rettv)
8751     typval_T	*argvars;
8752     typval_T	*rettv;
8753 {
8754     if (argvars[0].v_type == VAR_FLOAT)
8755     {
8756 	rettv->v_type = VAR_FLOAT;
8757 	rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8758     }
8759     else
8760     {
8761 	varnumber_T	n;
8762 	int		error = FALSE;
8763 
8764 	n = get_tv_number_chk(&argvars[0], &error);
8765 	if (error)
8766 	    rettv->vval.v_number = -1;
8767 	else if (n > 0)
8768 	    rettv->vval.v_number = n;
8769 	else
8770 	    rettv->vval.v_number = -n;
8771     }
8772 }
8773 
8774 /*
8775  * "acos()" function
8776  */
8777     static void
8778 f_acos(argvars, rettv)
8779     typval_T	*argvars;
8780     typval_T	*rettv;
8781 {
8782     float_T	f;
8783 
8784     rettv->v_type = VAR_FLOAT;
8785     if (get_float_arg(argvars, &f) == OK)
8786 	rettv->vval.v_float = acos(f);
8787     else
8788 	rettv->vval.v_float = 0.0;
8789 }
8790 #endif
8791 
8792 /*
8793  * "add(list, item)" function
8794  */
8795     static void
8796 f_add(argvars, rettv)
8797     typval_T	*argvars;
8798     typval_T	*rettv;
8799 {
8800     list_T	*l;
8801 
8802     rettv->vval.v_number = 1; /* Default: Failed */
8803     if (argvars[0].v_type == VAR_LIST)
8804     {
8805 	if ((l = argvars[0].vval.v_list) != NULL
8806 		&& !tv_check_lock(l->lv_lock, (char_u *)_("add() argument"))
8807 		&& list_append_tv(l, &argvars[1]) == OK)
8808 	    copy_tv(&argvars[0], rettv);
8809     }
8810     else
8811 	EMSG(_(e_listreq));
8812 }
8813 
8814 /*
8815  * "and(expr, expr)" function
8816  */
8817     static void
8818 f_and(argvars, rettv)
8819     typval_T	*argvars;
8820     typval_T	*rettv;
8821 {
8822     rettv->vval.v_number = get_tv_number_chk(&argvars[0], NULL)
8823 					& get_tv_number_chk(&argvars[1], NULL);
8824 }
8825 
8826 /*
8827  * "append(lnum, string/list)" function
8828  */
8829     static void
8830 f_append(argvars, rettv)
8831     typval_T	*argvars;
8832     typval_T	*rettv;
8833 {
8834     long	lnum;
8835     char_u	*line;
8836     list_T	*l = NULL;
8837     listitem_T	*li = NULL;
8838     typval_T	*tv;
8839     long	added = 0;
8840 
8841     /* When coming here from Insert mode, sync undo, so that this can be
8842      * undone separately from what was previously inserted. */
8843     if (u_sync_once == 2)
8844     {
8845 	u_sync_once = 1; /* notify that u_sync() was called */
8846 	u_sync(TRUE);
8847     }
8848 
8849     lnum = get_tv_lnum(argvars);
8850     if (lnum >= 0
8851 	    && lnum <= curbuf->b_ml.ml_line_count
8852 	    && u_save(lnum, lnum + 1) == OK)
8853     {
8854 	if (argvars[1].v_type == VAR_LIST)
8855 	{
8856 	    l = argvars[1].vval.v_list;
8857 	    if (l == NULL)
8858 		return;
8859 	    li = l->lv_first;
8860 	}
8861 	for (;;)
8862 	{
8863 	    if (l == NULL)
8864 		tv = &argvars[1];	/* append a string */
8865 	    else if (li == NULL)
8866 		break;			/* end of list */
8867 	    else
8868 		tv = &li->li_tv;	/* append item from list */
8869 	    line = get_tv_string_chk(tv);
8870 	    if (line == NULL)		/* type error */
8871 	    {
8872 		rettv->vval.v_number = 1;	/* Failed */
8873 		break;
8874 	    }
8875 	    ml_append(lnum + added, line, (colnr_T)0, FALSE);
8876 	    ++added;
8877 	    if (l == NULL)
8878 		break;
8879 	    li = li->li_next;
8880 	}
8881 
8882 	appended_lines_mark(lnum, added);
8883 	if (curwin->w_cursor.lnum > lnum)
8884 	    curwin->w_cursor.lnum += added;
8885     }
8886     else
8887 	rettv->vval.v_number = 1;	/* Failed */
8888 }
8889 
8890 /*
8891  * "argc()" function
8892  */
8893     static void
8894 f_argc(argvars, rettv)
8895     typval_T	*argvars UNUSED;
8896     typval_T	*rettv;
8897 {
8898     rettv->vval.v_number = ARGCOUNT;
8899 }
8900 
8901 /*
8902  * "argidx()" function
8903  */
8904     static void
8905 f_argidx(argvars, rettv)
8906     typval_T	*argvars UNUSED;
8907     typval_T	*rettv;
8908 {
8909     rettv->vval.v_number = curwin->w_arg_idx;
8910 }
8911 
8912 /*
8913  * "arglistid()" function
8914  */
8915     static void
8916 f_arglistid(argvars, rettv)
8917     typval_T	*argvars UNUSED;
8918     typval_T	*rettv;
8919 {
8920     win_T	*wp;
8921     tabpage_T	*tp = NULL;
8922     long	n;
8923 
8924     rettv->vval.v_number = -1;
8925     if (argvars[0].v_type != VAR_UNKNOWN)
8926     {
8927 	if (argvars[1].v_type != VAR_UNKNOWN)
8928 	{
8929 	    n = get_tv_number(&argvars[1]);
8930 	    if (n >= 0)
8931 		tp = find_tabpage(n);
8932 	}
8933 	else
8934 	    tp = curtab;
8935 
8936 	if (tp != NULL)
8937 	{
8938 	    wp = find_win_by_nr(&argvars[0], tp);
8939 	    if (wp != NULL)
8940 		rettv->vval.v_number = wp->w_alist->id;
8941 	}
8942     }
8943     else
8944 	rettv->vval.v_number = curwin->w_alist->id;
8945 }
8946 
8947 /*
8948  * "argv(nr)" function
8949  */
8950     static void
8951 f_argv(argvars, rettv)
8952     typval_T	*argvars;
8953     typval_T	*rettv;
8954 {
8955     int		idx;
8956 
8957     if (argvars[0].v_type != VAR_UNKNOWN)
8958     {
8959 	idx = get_tv_number_chk(&argvars[0], NULL);
8960 	if (idx >= 0 && idx < ARGCOUNT)
8961 	    rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8962 	else
8963 	    rettv->vval.v_string = NULL;
8964 	rettv->v_type = VAR_STRING;
8965     }
8966     else if (rettv_list_alloc(rettv) == OK)
8967 	for (idx = 0; idx < ARGCOUNT; ++idx)
8968 	    list_append_string(rettv->vval.v_list,
8969 					       alist_name(&ARGLIST[idx]), -1);
8970 }
8971 
8972 #ifdef FEAT_FLOAT
8973 /*
8974  * "asin()" function
8975  */
8976     static void
8977 f_asin(argvars, rettv)
8978     typval_T	*argvars;
8979     typval_T	*rettv;
8980 {
8981     float_T	f;
8982 
8983     rettv->v_type = VAR_FLOAT;
8984     if (get_float_arg(argvars, &f) == OK)
8985 	rettv->vval.v_float = asin(f);
8986     else
8987 	rettv->vval.v_float = 0.0;
8988 }
8989 
8990 /*
8991  * "atan()" function
8992  */
8993     static void
8994 f_atan(argvars, rettv)
8995     typval_T	*argvars;
8996     typval_T	*rettv;
8997 {
8998     float_T	f;
8999 
9000     rettv->v_type = VAR_FLOAT;
9001     if (get_float_arg(argvars, &f) == OK)
9002 	rettv->vval.v_float = atan(f);
9003     else
9004 	rettv->vval.v_float = 0.0;
9005 }
9006 
9007 /*
9008  * "atan2()" function
9009  */
9010     static void
9011 f_atan2(argvars, rettv)
9012     typval_T	*argvars;
9013     typval_T	*rettv;
9014 {
9015     float_T	fx, fy;
9016 
9017     rettv->v_type = VAR_FLOAT;
9018     if (get_float_arg(argvars, &fx) == OK
9019 				     && get_float_arg(&argvars[1], &fy) == OK)
9020 	rettv->vval.v_float = atan2(fx, fy);
9021     else
9022 	rettv->vval.v_float = 0.0;
9023 }
9024 #endif
9025 
9026 /*
9027  * "browse(save, title, initdir, default)" function
9028  */
9029     static void
9030 f_browse(argvars, rettv)
9031     typval_T	*argvars UNUSED;
9032     typval_T	*rettv;
9033 {
9034 #ifdef FEAT_BROWSE
9035     int		save;
9036     char_u	*title;
9037     char_u	*initdir;
9038     char_u	*defname;
9039     char_u	buf[NUMBUFLEN];
9040     char_u	buf2[NUMBUFLEN];
9041     int		error = FALSE;
9042 
9043     save = get_tv_number_chk(&argvars[0], &error);
9044     title = get_tv_string_chk(&argvars[1]);
9045     initdir = get_tv_string_buf_chk(&argvars[2], buf);
9046     defname = get_tv_string_buf_chk(&argvars[3], buf2);
9047 
9048     if (error || title == NULL || initdir == NULL || defname == NULL)
9049 	rettv->vval.v_string = NULL;
9050     else
9051 	rettv->vval.v_string =
9052 		 do_browse(save ? BROWSE_SAVE : 0,
9053 				 title, defname, NULL, initdir, NULL, curbuf);
9054 #else
9055     rettv->vval.v_string = NULL;
9056 #endif
9057     rettv->v_type = VAR_STRING;
9058 }
9059 
9060 /*
9061  * "browsedir(title, initdir)" function
9062  */
9063     static void
9064 f_browsedir(argvars, rettv)
9065     typval_T	*argvars UNUSED;
9066     typval_T	*rettv;
9067 {
9068 #ifdef FEAT_BROWSE
9069     char_u	*title;
9070     char_u	*initdir;
9071     char_u	buf[NUMBUFLEN];
9072 
9073     title = get_tv_string_chk(&argvars[0]);
9074     initdir = get_tv_string_buf_chk(&argvars[1], buf);
9075 
9076     if (title == NULL || initdir == NULL)
9077 	rettv->vval.v_string = NULL;
9078     else
9079 	rettv->vval.v_string = do_browse(BROWSE_DIR,
9080 				    title, NULL, NULL, initdir, NULL, curbuf);
9081 #else
9082     rettv->vval.v_string = NULL;
9083 #endif
9084     rettv->v_type = VAR_STRING;
9085 }
9086 
9087 static buf_T *find_buffer __ARGS((typval_T *avar));
9088 
9089 /*
9090  * Find a buffer by number or exact name.
9091  */
9092     static buf_T *
9093 find_buffer(avar)
9094     typval_T	*avar;
9095 {
9096     buf_T	*buf = NULL;
9097 
9098     if (avar->v_type == VAR_NUMBER)
9099 	buf = buflist_findnr((int)avar->vval.v_number);
9100     else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
9101     {
9102 	buf = buflist_findname_exp(avar->vval.v_string);
9103 	if (buf == NULL)
9104 	{
9105 	    /* No full path name match, try a match with a URL or a "nofile"
9106 	     * buffer, these don't use the full path. */
9107 	    for (buf = firstbuf; buf != NULL; buf = buf->b_next)
9108 		if (buf->b_fname != NULL
9109 			&& (path_with_url(buf->b_fname)
9110 #ifdef FEAT_QUICKFIX
9111 			    || bt_nofile(buf)
9112 #endif
9113 			   )
9114 			&& STRCMP(buf->b_fname, avar->vval.v_string) == 0)
9115 		    break;
9116 	}
9117     }
9118     return buf;
9119 }
9120 
9121 /*
9122  * "bufexists(expr)" function
9123  */
9124     static void
9125 f_bufexists(argvars, rettv)
9126     typval_T	*argvars;
9127     typval_T	*rettv;
9128 {
9129     rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
9130 }
9131 
9132 /*
9133  * "buflisted(expr)" function
9134  */
9135     static void
9136 f_buflisted(argvars, rettv)
9137     typval_T	*argvars;
9138     typval_T	*rettv;
9139 {
9140     buf_T	*buf;
9141 
9142     buf = find_buffer(&argvars[0]);
9143     rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
9144 }
9145 
9146 /*
9147  * "bufloaded(expr)" function
9148  */
9149     static void
9150 f_bufloaded(argvars, rettv)
9151     typval_T	*argvars;
9152     typval_T	*rettv;
9153 {
9154     buf_T	*buf;
9155 
9156     buf = find_buffer(&argvars[0]);
9157     rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
9158 }
9159 
9160 static buf_T *get_buf_tv __ARGS((typval_T *tv, int curtab_only));
9161 
9162 /*
9163  * Get buffer by number or pattern.
9164  */
9165     static buf_T *
9166 get_buf_tv(tv, curtab_only)
9167     typval_T	*tv;
9168     int		curtab_only;
9169 {
9170     char_u	*name = tv->vval.v_string;
9171     int		save_magic;
9172     char_u	*save_cpo;
9173     buf_T	*buf;
9174 
9175     if (tv->v_type == VAR_NUMBER)
9176 	return buflist_findnr((int)tv->vval.v_number);
9177     if (tv->v_type != VAR_STRING)
9178 	return NULL;
9179     if (name == NULL || *name == NUL)
9180 	return curbuf;
9181     if (name[0] == '$' && name[1] == NUL)
9182 	return lastbuf;
9183 
9184     /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
9185     save_magic = p_magic;
9186     p_magic = TRUE;
9187     save_cpo = p_cpo;
9188     p_cpo = (char_u *)"";
9189 
9190     buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
9191 						    TRUE, FALSE, curtab_only));
9192 
9193     p_magic = save_magic;
9194     p_cpo = save_cpo;
9195 
9196     /* If not found, try expanding the name, like done for bufexists(). */
9197     if (buf == NULL)
9198 	buf = find_buffer(tv);
9199 
9200     return buf;
9201 }
9202 
9203 /*
9204  * "bufname(expr)" function
9205  */
9206     static void
9207 f_bufname(argvars, rettv)
9208     typval_T	*argvars;
9209     typval_T	*rettv;
9210 {
9211     buf_T	*buf;
9212 
9213     (void)get_tv_number(&argvars[0]);	    /* issue errmsg if type error */
9214     ++emsg_off;
9215     buf = get_buf_tv(&argvars[0], FALSE);
9216     rettv->v_type = VAR_STRING;
9217     if (buf != NULL && buf->b_fname != NULL)
9218 	rettv->vval.v_string = vim_strsave(buf->b_fname);
9219     else
9220 	rettv->vval.v_string = NULL;
9221     --emsg_off;
9222 }
9223 
9224 /*
9225  * "bufnr(expr)" function
9226  */
9227     static void
9228 f_bufnr(argvars, rettv)
9229     typval_T	*argvars;
9230     typval_T	*rettv;
9231 {
9232     buf_T	*buf;
9233     int		error = FALSE;
9234     char_u	*name;
9235 
9236     (void)get_tv_number(&argvars[0]);	    /* issue errmsg if type error */
9237     ++emsg_off;
9238     buf = get_buf_tv(&argvars[0], FALSE);
9239     --emsg_off;
9240 
9241     /* If the buffer isn't found and the second argument is not zero create a
9242      * new buffer. */
9243     if (buf == NULL
9244 	    && argvars[1].v_type != VAR_UNKNOWN
9245 	    && get_tv_number_chk(&argvars[1], &error) != 0
9246 	    && !error
9247 	    && (name = get_tv_string_chk(&argvars[0])) != NULL
9248 	    && !error)
9249 	buf = buflist_new(name, NULL, (linenr_T)1, 0);
9250 
9251     if (buf != NULL)
9252 	rettv->vval.v_number = buf->b_fnum;
9253     else
9254 	rettv->vval.v_number = -1;
9255 }
9256 
9257 /*
9258  * "bufwinnr(nr)" function
9259  */
9260     static void
9261 f_bufwinnr(argvars, rettv)
9262     typval_T	*argvars;
9263     typval_T	*rettv;
9264 {
9265 #ifdef FEAT_WINDOWS
9266     win_T	*wp;
9267     int		winnr = 0;
9268 #endif
9269     buf_T	*buf;
9270 
9271     (void)get_tv_number(&argvars[0]);	    /* issue errmsg if type error */
9272     ++emsg_off;
9273     buf = get_buf_tv(&argvars[0], TRUE);
9274 #ifdef FEAT_WINDOWS
9275     for (wp = firstwin; wp; wp = wp->w_next)
9276     {
9277 	++winnr;
9278 	if (wp->w_buffer == buf)
9279 	    break;
9280     }
9281     rettv->vval.v_number = (wp != NULL ? winnr : -1);
9282 #else
9283     rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
9284 #endif
9285     --emsg_off;
9286 }
9287 
9288 /*
9289  * "byte2line(byte)" function
9290  */
9291     static void
9292 f_byte2line(argvars, rettv)
9293     typval_T	*argvars UNUSED;
9294     typval_T	*rettv;
9295 {
9296 #ifndef FEAT_BYTEOFF
9297     rettv->vval.v_number = -1;
9298 #else
9299     long	boff = 0;
9300 
9301     boff = get_tv_number(&argvars[0]) - 1;  /* boff gets -1 on type error */
9302     if (boff < 0)
9303 	rettv->vval.v_number = -1;
9304     else
9305 	rettv->vval.v_number = ml_find_line_or_offset(curbuf,
9306 							  (linenr_T)0, &boff);
9307 #endif
9308 }
9309 
9310     static void
9311 byteidx(argvars, rettv, comp)
9312     typval_T	*argvars;
9313     typval_T	*rettv;
9314     int		comp UNUSED;
9315 {
9316 #ifdef FEAT_MBYTE
9317     char_u	*t;
9318 #endif
9319     char_u	*str;
9320     long	idx;
9321 
9322     str = get_tv_string_chk(&argvars[0]);
9323     idx = get_tv_number_chk(&argvars[1], NULL);
9324     rettv->vval.v_number = -1;
9325     if (str == NULL || idx < 0)
9326 	return;
9327 
9328 #ifdef FEAT_MBYTE
9329     t = str;
9330     for ( ; idx > 0; idx--)
9331     {
9332 	if (*t == NUL)		/* EOL reached */
9333 	    return;
9334 	if (enc_utf8 && comp)
9335 	    t += utf_ptr2len(t);
9336 	else
9337 	    t += (*mb_ptr2len)(t);
9338     }
9339     rettv->vval.v_number = (varnumber_T)(t - str);
9340 #else
9341     if ((size_t)idx <= STRLEN(str))
9342 	rettv->vval.v_number = idx;
9343 #endif
9344 }
9345 
9346 /*
9347  * "byteidx()" function
9348  */
9349     static void
9350 f_byteidx(argvars, rettv)
9351     typval_T	*argvars;
9352     typval_T	*rettv;
9353 {
9354     byteidx(argvars, rettv, FALSE);
9355 }
9356 
9357 /*
9358  * "byteidxcomp()" function
9359  */
9360     static void
9361 f_byteidxcomp(argvars, rettv)
9362     typval_T	*argvars;
9363     typval_T	*rettv;
9364 {
9365     byteidx(argvars, rettv, TRUE);
9366 }
9367 
9368     int
9369 func_call(name, args, selfdict, rettv)
9370     char_u	*name;
9371     typval_T	*args;
9372     dict_T	*selfdict;
9373     typval_T	*rettv;
9374 {
9375     listitem_T	*item;
9376     typval_T	argv[MAX_FUNC_ARGS + 1];
9377     int		argc = 0;
9378     int		dummy;
9379     int		r = 0;
9380 
9381     for (item = args->vval.v_list->lv_first; item != NULL;
9382 							 item = item->li_next)
9383     {
9384 	if (argc == MAX_FUNC_ARGS)
9385 	{
9386 	    EMSG(_("E699: Too many arguments"));
9387 	    break;
9388 	}
9389 	/* Make a copy of each argument.  This is needed to be able to set
9390 	 * v_lock to VAR_FIXED in the copy without changing the original list.
9391 	 */
9392 	copy_tv(&item->li_tv, &argv[argc++]);
9393     }
9394 
9395     if (item == NULL)
9396 	r = call_func(name, (int)STRLEN(name), rettv, argc, argv,
9397 				 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
9398 						      &dummy, TRUE, selfdict);
9399 
9400     /* Free the arguments. */
9401     while (argc > 0)
9402 	clear_tv(&argv[--argc]);
9403 
9404     return r;
9405 }
9406 
9407 /*
9408  * "call(func, arglist)" function
9409  */
9410     static void
9411 f_call(argvars, rettv)
9412     typval_T	*argvars;
9413     typval_T	*rettv;
9414 {
9415     char_u	*func;
9416     dict_T	*selfdict = NULL;
9417 
9418     if (argvars[1].v_type != VAR_LIST)
9419     {
9420 	EMSG(_(e_listreq));
9421 	return;
9422     }
9423     if (argvars[1].vval.v_list == NULL)
9424 	return;
9425 
9426     if (argvars[0].v_type == VAR_FUNC)
9427 	func = argvars[0].vval.v_string;
9428     else
9429 	func = get_tv_string(&argvars[0]);
9430     if (*func == NUL)
9431 	return;		/* type error or empty name */
9432 
9433     if (argvars[2].v_type != VAR_UNKNOWN)
9434     {
9435 	if (argvars[2].v_type != VAR_DICT)
9436 	{
9437 	    EMSG(_(e_dictreq));
9438 	    return;
9439 	}
9440 	selfdict = argvars[2].vval.v_dict;
9441     }
9442 
9443     (void)func_call(func, &argvars[1], selfdict, rettv);
9444 }
9445 
9446 #ifdef FEAT_FLOAT
9447 /*
9448  * "ceil({float})" function
9449  */
9450     static void
9451 f_ceil(argvars, rettv)
9452     typval_T	*argvars;
9453     typval_T	*rettv;
9454 {
9455     float_T	f;
9456 
9457     rettv->v_type = VAR_FLOAT;
9458     if (get_float_arg(argvars, &f) == OK)
9459 	rettv->vval.v_float = ceil(f);
9460     else
9461 	rettv->vval.v_float = 0.0;
9462 }
9463 #endif
9464 
9465 /*
9466  * "changenr()" function
9467  */
9468     static void
9469 f_changenr(argvars, rettv)
9470     typval_T	*argvars UNUSED;
9471     typval_T	*rettv;
9472 {
9473     rettv->vval.v_number = curbuf->b_u_seq_cur;
9474 }
9475 
9476 /*
9477  * "char2nr(string)" function
9478  */
9479     static void
9480 f_char2nr(argvars, rettv)
9481     typval_T	*argvars;
9482     typval_T	*rettv;
9483 {
9484 #ifdef FEAT_MBYTE
9485     if (has_mbyte)
9486     {
9487 	int	utf8 = 0;
9488 
9489 	if (argvars[1].v_type != VAR_UNKNOWN)
9490 	    utf8 = get_tv_number_chk(&argvars[1], NULL);
9491 
9492 	if (utf8)
9493 	    rettv->vval.v_number = (*utf_ptr2char)(get_tv_string(&argvars[0]));
9494 	else
9495 	    rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
9496     }
9497     else
9498 #endif
9499     rettv->vval.v_number = get_tv_string(&argvars[0])[0];
9500 }
9501 
9502 /*
9503  * "cindent(lnum)" function
9504  */
9505     static void
9506 f_cindent(argvars, rettv)
9507     typval_T	*argvars UNUSED;
9508     typval_T	*rettv;
9509 {
9510 #ifdef FEAT_CINDENT
9511     pos_T	pos;
9512     linenr_T	lnum;
9513 
9514     pos = curwin->w_cursor;
9515     lnum = get_tv_lnum(argvars);
9516     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9517     {
9518 	curwin->w_cursor.lnum = lnum;
9519 	rettv->vval.v_number = get_c_indent();
9520 	curwin->w_cursor = pos;
9521     }
9522     else
9523 #endif
9524 	rettv->vval.v_number = -1;
9525 }
9526 
9527 /*
9528  * "clearmatches()" function
9529  */
9530     static void
9531 f_clearmatches(argvars, rettv)
9532     typval_T	*argvars UNUSED;
9533     typval_T	*rettv UNUSED;
9534 {
9535 #ifdef FEAT_SEARCH_EXTRA
9536     clear_matches(curwin);
9537 #endif
9538 }
9539 
9540 /*
9541  * "col(string)" function
9542  */
9543     static void
9544 f_col(argvars, rettv)
9545     typval_T	*argvars;
9546     typval_T	*rettv;
9547 {
9548     colnr_T	col = 0;
9549     pos_T	*fp;
9550     int		fnum = curbuf->b_fnum;
9551 
9552     fp = var2fpos(&argvars[0], FALSE, &fnum);
9553     if (fp != NULL && fnum == curbuf->b_fnum)
9554     {
9555 	if (fp->col == MAXCOL)
9556 	{
9557 	    /* '> can be MAXCOL, get the length of the line then */
9558 	    if (fp->lnum <= curbuf->b_ml.ml_line_count)
9559 		col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
9560 	    else
9561 		col = MAXCOL;
9562 	}
9563 	else
9564 	{
9565 	    col = fp->col + 1;
9566 #ifdef FEAT_VIRTUALEDIT
9567 	    /* col(".") when the cursor is on the NUL at the end of the line
9568 	     * because of "coladd" can be seen as an extra column. */
9569 	    if (virtual_active() && fp == &curwin->w_cursor)
9570 	    {
9571 		char_u	*p = ml_get_cursor();
9572 
9573 		if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
9574 				 curwin->w_virtcol - curwin->w_cursor.coladd))
9575 		{
9576 # ifdef FEAT_MBYTE
9577 		    int		l;
9578 
9579 		    if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
9580 			col += l;
9581 # else
9582 		    if (*p != NUL && p[1] == NUL)
9583 			++col;
9584 # endif
9585 		}
9586 	    }
9587 #endif
9588 	}
9589     }
9590     rettv->vval.v_number = col;
9591 }
9592 
9593 #if defined(FEAT_INS_EXPAND)
9594 /*
9595  * "complete()" function
9596  */
9597     static void
9598 f_complete(argvars, rettv)
9599     typval_T	*argvars;
9600     typval_T	*rettv UNUSED;
9601 {
9602     int	    startcol;
9603 
9604     if ((State & INSERT) == 0)
9605     {
9606 	EMSG(_("E785: complete() can only be used in Insert mode"));
9607 	return;
9608     }
9609 
9610     /* Check for undo allowed here, because if something was already inserted
9611      * the line was already saved for undo and this check isn't done. */
9612     if (!undo_allowed())
9613 	return;
9614 
9615     if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
9616     {
9617 	EMSG(_(e_invarg));
9618 	return;
9619     }
9620 
9621     startcol = get_tv_number_chk(&argvars[0], NULL);
9622     if (startcol <= 0)
9623 	return;
9624 
9625     set_completion(startcol - 1, argvars[1].vval.v_list);
9626 }
9627 
9628 /*
9629  * "complete_add()" function
9630  */
9631     static void
9632 f_complete_add(argvars, rettv)
9633     typval_T	*argvars;
9634     typval_T	*rettv;
9635 {
9636     rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
9637 }
9638 
9639 /*
9640  * "complete_check()" function
9641  */
9642     static void
9643 f_complete_check(argvars, rettv)
9644     typval_T	*argvars UNUSED;
9645     typval_T	*rettv;
9646 {
9647     int		saved = RedrawingDisabled;
9648 
9649     RedrawingDisabled = 0;
9650     ins_compl_check_keys(0);
9651     rettv->vval.v_number = compl_interrupted;
9652     RedrawingDisabled = saved;
9653 }
9654 #endif
9655 
9656 /*
9657  * "confirm(message, buttons[, default [, type]])" function
9658  */
9659     static void
9660 f_confirm(argvars, rettv)
9661     typval_T	*argvars UNUSED;
9662     typval_T	*rettv UNUSED;
9663 {
9664 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
9665     char_u	*message;
9666     char_u	*buttons = NULL;
9667     char_u	buf[NUMBUFLEN];
9668     char_u	buf2[NUMBUFLEN];
9669     int		def = 1;
9670     int		type = VIM_GENERIC;
9671     char_u	*typestr;
9672     int		error = FALSE;
9673 
9674     message = get_tv_string_chk(&argvars[0]);
9675     if (message == NULL)
9676 	error = TRUE;
9677     if (argvars[1].v_type != VAR_UNKNOWN)
9678     {
9679 	buttons = get_tv_string_buf_chk(&argvars[1], buf);
9680 	if (buttons == NULL)
9681 	    error = TRUE;
9682 	if (argvars[2].v_type != VAR_UNKNOWN)
9683 	{
9684 	    def = get_tv_number_chk(&argvars[2], &error);
9685 	    if (argvars[3].v_type != VAR_UNKNOWN)
9686 	    {
9687 		typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9688 		if (typestr == NULL)
9689 		    error = TRUE;
9690 		else
9691 		{
9692 		    switch (TOUPPER_ASC(*typestr))
9693 		    {
9694 			case 'E': type = VIM_ERROR; break;
9695 			case 'Q': type = VIM_QUESTION; break;
9696 			case 'I': type = VIM_INFO; break;
9697 			case 'W': type = VIM_WARNING; break;
9698 			case 'G': type = VIM_GENERIC; break;
9699 		    }
9700 		}
9701 	    }
9702 	}
9703     }
9704 
9705     if (buttons == NULL || *buttons == NUL)
9706 	buttons = (char_u *)_("&Ok");
9707 
9708     if (!error)
9709 	rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9710 							    def, NULL, FALSE);
9711 #endif
9712 }
9713 
9714 /*
9715  * "copy()" function
9716  */
9717     static void
9718 f_copy(argvars, rettv)
9719     typval_T	*argvars;
9720     typval_T	*rettv;
9721 {
9722     item_copy(&argvars[0], rettv, FALSE, 0);
9723 }
9724 
9725 #ifdef FEAT_FLOAT
9726 /*
9727  * "cos()" function
9728  */
9729     static void
9730 f_cos(argvars, rettv)
9731     typval_T	*argvars;
9732     typval_T	*rettv;
9733 {
9734     float_T	f;
9735 
9736     rettv->v_type = VAR_FLOAT;
9737     if (get_float_arg(argvars, &f) == OK)
9738 	rettv->vval.v_float = cos(f);
9739     else
9740 	rettv->vval.v_float = 0.0;
9741 }
9742 
9743 /*
9744  * "cosh()" function
9745  */
9746     static void
9747 f_cosh(argvars, rettv)
9748     typval_T	*argvars;
9749     typval_T	*rettv;
9750 {
9751     float_T	f;
9752 
9753     rettv->v_type = VAR_FLOAT;
9754     if (get_float_arg(argvars, &f) == OK)
9755 	rettv->vval.v_float = cosh(f);
9756     else
9757 	rettv->vval.v_float = 0.0;
9758 }
9759 #endif
9760 
9761 /*
9762  * "count()" function
9763  */
9764     static void
9765 f_count(argvars, rettv)
9766     typval_T	*argvars;
9767     typval_T	*rettv;
9768 {
9769     long	n = 0;
9770     int		ic = FALSE;
9771 
9772     if (argvars[0].v_type == VAR_LIST)
9773     {
9774 	listitem_T	*li;
9775 	list_T		*l;
9776 	long		idx;
9777 
9778 	if ((l = argvars[0].vval.v_list) != NULL)
9779 	{
9780 	    li = l->lv_first;
9781 	    if (argvars[2].v_type != VAR_UNKNOWN)
9782 	    {
9783 		int error = FALSE;
9784 
9785 		ic = get_tv_number_chk(&argvars[2], &error);
9786 		if (argvars[3].v_type != VAR_UNKNOWN)
9787 		{
9788 		    idx = get_tv_number_chk(&argvars[3], &error);
9789 		    if (!error)
9790 		    {
9791 			li = list_find(l, idx);
9792 			if (li == NULL)
9793 			    EMSGN(_(e_listidx), idx);
9794 		    }
9795 		}
9796 		if (error)
9797 		    li = NULL;
9798 	    }
9799 
9800 	    for ( ; li != NULL; li = li->li_next)
9801 		if (tv_equal(&li->li_tv, &argvars[1], ic, FALSE))
9802 		    ++n;
9803 	}
9804     }
9805     else if (argvars[0].v_type == VAR_DICT)
9806     {
9807 	int		todo;
9808 	dict_T		*d;
9809 	hashitem_T	*hi;
9810 
9811 	if ((d = argvars[0].vval.v_dict) != NULL)
9812 	{
9813 	    int error = FALSE;
9814 
9815 	    if (argvars[2].v_type != VAR_UNKNOWN)
9816 	    {
9817 		ic = get_tv_number_chk(&argvars[2], &error);
9818 		if (argvars[3].v_type != VAR_UNKNOWN)
9819 		    EMSG(_(e_invarg));
9820 	    }
9821 
9822 	    todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9823 	    for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9824 	    {
9825 		if (!HASHITEM_EMPTY(hi))
9826 		{
9827 		    --todo;
9828 		    if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic, FALSE))
9829 			++n;
9830 		}
9831 	    }
9832 	}
9833     }
9834     else
9835 	EMSG2(_(e_listdictarg), "count()");
9836     rettv->vval.v_number = n;
9837 }
9838 
9839 /*
9840  * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9841  *
9842  * Checks the existence of a cscope connection.
9843  */
9844     static void
9845 f_cscope_connection(argvars, rettv)
9846     typval_T	*argvars UNUSED;
9847     typval_T	*rettv UNUSED;
9848 {
9849 #ifdef FEAT_CSCOPE
9850     int		num = 0;
9851     char_u	*dbpath = NULL;
9852     char_u	*prepend = NULL;
9853     char_u	buf[NUMBUFLEN];
9854 
9855     if (argvars[0].v_type != VAR_UNKNOWN
9856 	    && argvars[1].v_type != VAR_UNKNOWN)
9857     {
9858 	num = (int)get_tv_number(&argvars[0]);
9859 	dbpath = get_tv_string(&argvars[1]);
9860 	if (argvars[2].v_type != VAR_UNKNOWN)
9861 	    prepend = get_tv_string_buf(&argvars[2], buf);
9862     }
9863 
9864     rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9865 #endif
9866 }
9867 
9868 /*
9869  * "cursor(lnum, col)" function
9870  *
9871  * Moves the cursor to the specified line and column.
9872  * Returns 0 when the position could be set, -1 otherwise.
9873  */
9874     static void
9875 f_cursor(argvars, rettv)
9876     typval_T	*argvars;
9877     typval_T	*rettv;
9878 {
9879     long	line, col;
9880 #ifdef FEAT_VIRTUALEDIT
9881     long	coladd = 0;
9882 #endif
9883 
9884     rettv->vval.v_number = -1;
9885     if (argvars[1].v_type == VAR_UNKNOWN)
9886     {
9887 	pos_T	    pos;
9888 	colnr_T	    curswant = -1;
9889 
9890 	if (list2fpos(argvars, &pos, NULL, &curswant) == FAIL)
9891 	    return;
9892 	line = pos.lnum;
9893 	col = pos.col;
9894 #ifdef FEAT_VIRTUALEDIT
9895 	coladd = pos.coladd;
9896 #endif
9897 	if (curswant >= 0)
9898 	    curwin->w_curswant = curswant - 1;
9899     }
9900     else
9901     {
9902 	line = get_tv_lnum(argvars);
9903 	col = get_tv_number_chk(&argvars[1], NULL);
9904 #ifdef FEAT_VIRTUALEDIT
9905 	if (argvars[2].v_type != VAR_UNKNOWN)
9906 	    coladd = get_tv_number_chk(&argvars[2], NULL);
9907 #endif
9908     }
9909     if (line < 0 || col < 0
9910 #ifdef FEAT_VIRTUALEDIT
9911 			    || coladd < 0
9912 #endif
9913 	    )
9914 	return;		/* type error; errmsg already given */
9915     if (line > 0)
9916 	curwin->w_cursor.lnum = line;
9917     if (col > 0)
9918 	curwin->w_cursor.col = col - 1;
9919 #ifdef FEAT_VIRTUALEDIT
9920     curwin->w_cursor.coladd = coladd;
9921 #endif
9922 
9923     /* Make sure the cursor is in a valid position. */
9924     check_cursor();
9925 #ifdef FEAT_MBYTE
9926     /* Correct cursor for multi-byte character. */
9927     if (has_mbyte)
9928 	mb_adjust_cursor();
9929 #endif
9930 
9931     curwin->w_set_curswant = TRUE;
9932     rettv->vval.v_number = 0;
9933 }
9934 
9935 /*
9936  * "deepcopy()" function
9937  */
9938     static void
9939 f_deepcopy(argvars, rettv)
9940     typval_T	*argvars;
9941     typval_T	*rettv;
9942 {
9943     int		noref = 0;
9944 
9945     if (argvars[1].v_type != VAR_UNKNOWN)
9946 	noref = get_tv_number_chk(&argvars[1], NULL);
9947     if (noref < 0 || noref > 1)
9948 	EMSG(_(e_invarg));
9949     else
9950     {
9951 	current_copyID += COPYID_INC;
9952 	item_copy(&argvars[0], rettv, TRUE, noref == 0 ? current_copyID : 0);
9953     }
9954 }
9955 
9956 /*
9957  * "delete()" function
9958  */
9959     static void
9960 f_delete(argvars, rettv)
9961     typval_T	*argvars;
9962     typval_T	*rettv;
9963 {
9964     if (check_restricted() || check_secure())
9965 	rettv->vval.v_number = -1;
9966     else
9967 	rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9968 }
9969 
9970 /*
9971  * "did_filetype()" function
9972  */
9973     static void
9974 f_did_filetype(argvars, rettv)
9975     typval_T	*argvars UNUSED;
9976     typval_T	*rettv UNUSED;
9977 {
9978 #ifdef FEAT_AUTOCMD
9979     rettv->vval.v_number = did_filetype;
9980 #endif
9981 }
9982 
9983 /*
9984  * "diff_filler()" function
9985  */
9986     static void
9987 f_diff_filler(argvars, rettv)
9988     typval_T	*argvars UNUSED;
9989     typval_T	*rettv UNUSED;
9990 {
9991 #ifdef FEAT_DIFF
9992     rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9993 #endif
9994 }
9995 
9996 /*
9997  * "diff_hlID()" function
9998  */
9999     static void
10000 f_diff_hlID(argvars, rettv)
10001     typval_T	*argvars UNUSED;
10002     typval_T	*rettv UNUSED;
10003 {
10004 #ifdef FEAT_DIFF
10005     linenr_T		lnum = get_tv_lnum(argvars);
10006     static linenr_T	prev_lnum = 0;
10007     static int		changedtick = 0;
10008     static int		fnum = 0;
10009     static int		change_start = 0;
10010     static int		change_end = 0;
10011     static hlf_T	hlID = (hlf_T)0;
10012     int			filler_lines;
10013     int			col;
10014 
10015     if (lnum < 0)	/* ignore type error in {lnum} arg */
10016 	lnum = 0;
10017     if (lnum != prev_lnum
10018 	    || changedtick != curbuf->b_changedtick
10019 	    || fnum != curbuf->b_fnum)
10020     {
10021 	/* New line, buffer, change: need to get the values. */
10022 	filler_lines = diff_check(curwin, lnum);
10023 	if (filler_lines < 0)
10024 	{
10025 	    if (filler_lines == -1)
10026 	    {
10027 		change_start = MAXCOL;
10028 		change_end = -1;
10029 		if (diff_find_change(curwin, lnum, &change_start, &change_end))
10030 		    hlID = HLF_ADD;	/* added line */
10031 		else
10032 		    hlID = HLF_CHD;	/* changed line */
10033 	    }
10034 	    else
10035 		hlID = HLF_ADD;	/* added line */
10036 	}
10037 	else
10038 	    hlID = (hlf_T)0;
10039 	prev_lnum = lnum;
10040 	changedtick = curbuf->b_changedtick;
10041 	fnum = curbuf->b_fnum;
10042     }
10043 
10044     if (hlID == HLF_CHD || hlID == HLF_TXD)
10045     {
10046 	col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
10047 	if (col >= change_start && col <= change_end)
10048 	    hlID = HLF_TXD;			/* changed text */
10049 	else
10050 	    hlID = HLF_CHD;			/* changed line */
10051     }
10052     rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
10053 #endif
10054 }
10055 
10056 /*
10057  * "empty({expr})" function
10058  */
10059     static void
10060 f_empty(argvars, rettv)
10061     typval_T	*argvars;
10062     typval_T	*rettv;
10063 {
10064     int		n;
10065 
10066     switch (argvars[0].v_type)
10067     {
10068 	case VAR_STRING:
10069 	case VAR_FUNC:
10070 	    n = argvars[0].vval.v_string == NULL
10071 					  || *argvars[0].vval.v_string == NUL;
10072 	    break;
10073 	case VAR_NUMBER:
10074 	    n = argvars[0].vval.v_number == 0;
10075 	    break;
10076 #ifdef FEAT_FLOAT
10077 	case VAR_FLOAT:
10078 	    n = argvars[0].vval.v_float == 0.0;
10079 	    break;
10080 #endif
10081 	case VAR_LIST:
10082 	    n = argvars[0].vval.v_list == NULL
10083 				  || argvars[0].vval.v_list->lv_first == NULL;
10084 	    break;
10085 	case VAR_DICT:
10086 	    n = argvars[0].vval.v_dict == NULL
10087 			|| argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
10088 	    break;
10089 	default:
10090 	    EMSG2(_(e_intern2), "f_empty()");
10091 	    n = 0;
10092     }
10093 
10094     rettv->vval.v_number = n;
10095 }
10096 
10097 /*
10098  * "escape({string}, {chars})" function
10099  */
10100     static void
10101 f_escape(argvars, rettv)
10102     typval_T	*argvars;
10103     typval_T	*rettv;
10104 {
10105     char_u	buf[NUMBUFLEN];
10106 
10107     rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
10108 					 get_tv_string_buf(&argvars[1], buf));
10109     rettv->v_type = VAR_STRING;
10110 }
10111 
10112 /*
10113  * "eval()" function
10114  */
10115     static void
10116 f_eval(argvars, rettv)
10117     typval_T	*argvars;
10118     typval_T	*rettv;
10119 {
10120     char_u	*s;
10121 
10122     s = get_tv_string_chk(&argvars[0]);
10123     if (s != NULL)
10124 	s = skipwhite(s);
10125 
10126     if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
10127     {
10128 	rettv->v_type = VAR_NUMBER;
10129 	rettv->vval.v_number = 0;
10130     }
10131     else if (*s != NUL)
10132 	EMSG(_(e_trailing));
10133 }
10134 
10135 /*
10136  * "eventhandler()" function
10137  */
10138     static void
10139 f_eventhandler(argvars, rettv)
10140     typval_T	*argvars UNUSED;
10141     typval_T	*rettv;
10142 {
10143     rettv->vval.v_number = vgetc_busy;
10144 }
10145 
10146 /*
10147  * "executable()" function
10148  */
10149     static void
10150 f_executable(argvars, rettv)
10151     typval_T	*argvars;
10152     typval_T	*rettv;
10153 {
10154     rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]), NULL);
10155 }
10156 
10157 /*
10158  * "exepath()" function
10159  */
10160     static void
10161 f_exepath(argvars, rettv)
10162     typval_T	*argvars;
10163     typval_T	*rettv;
10164 {
10165     char_u *p = NULL;
10166 
10167     (void)mch_can_exe(get_tv_string(&argvars[0]), &p);
10168     rettv->v_type = VAR_STRING;
10169     rettv->vval.v_string = p;
10170 }
10171 
10172 /*
10173  * "exists()" function
10174  */
10175     static void
10176 f_exists(argvars, rettv)
10177     typval_T	*argvars;
10178     typval_T	*rettv;
10179 {
10180     char_u	*p;
10181     char_u	*name;
10182     int		n = FALSE;
10183     int		len = 0;
10184 
10185     p = get_tv_string(&argvars[0]);
10186     if (*p == '$')			/* environment variable */
10187     {
10188 	/* first try "normal" environment variables (fast) */
10189 	if (mch_getenv(p + 1) != NULL)
10190 	    n = TRUE;
10191 	else
10192 	{
10193 	    /* try expanding things like $VIM and ${HOME} */
10194 	    p = expand_env_save(p);
10195 	    if (p != NULL && *p != '$')
10196 		n = TRUE;
10197 	    vim_free(p);
10198 	}
10199     }
10200     else if (*p == '&' || *p == '+')			/* option */
10201     {
10202 	n = (get_option_tv(&p, NULL, TRUE) == OK);
10203 	if (*skipwhite(p) != NUL)
10204 	    n = FALSE;			/* trailing garbage */
10205     }
10206     else if (*p == '*')			/* internal or user defined function */
10207     {
10208 	n = function_exists(p + 1);
10209     }
10210     else if (*p == ':')
10211     {
10212 	n = cmd_exists(p + 1);
10213     }
10214     else if (*p == '#')
10215     {
10216 #ifdef FEAT_AUTOCMD
10217 	if (p[1] == '#')
10218 	    n = autocmd_supported(p + 2);
10219 	else
10220 	    n = au_exists(p + 1);
10221 #endif
10222     }
10223     else				/* internal variable */
10224     {
10225 	char_u	    *tofree;
10226 	typval_T    tv;
10227 
10228 	/* get_name_len() takes care of expanding curly braces */
10229 	name = p;
10230 	len = get_name_len(&p, &tofree, TRUE, FALSE);
10231 	if (len > 0)
10232 	{
10233 	    if (tofree != NULL)
10234 		name = tofree;
10235 	    n = (get_var_tv(name, len, &tv, FALSE, TRUE) == OK);
10236 	    if (n)
10237 	    {
10238 		/* handle d.key, l[idx], f(expr) */
10239 		n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
10240 		if (n)
10241 		    clear_tv(&tv);
10242 	    }
10243 	}
10244 	if (*p != NUL)
10245 	    n = FALSE;
10246 
10247 	vim_free(tofree);
10248     }
10249 
10250     rettv->vval.v_number = n;
10251 }
10252 
10253 #ifdef FEAT_FLOAT
10254 /*
10255  * "exp()" function
10256  */
10257     static void
10258 f_exp(argvars, rettv)
10259     typval_T	*argvars;
10260     typval_T	*rettv;
10261 {
10262     float_T	f;
10263 
10264     rettv->v_type = VAR_FLOAT;
10265     if (get_float_arg(argvars, &f) == OK)
10266 	rettv->vval.v_float = exp(f);
10267     else
10268 	rettv->vval.v_float = 0.0;
10269 }
10270 #endif
10271 
10272 /*
10273  * "expand()" function
10274  */
10275     static void
10276 f_expand(argvars, rettv)
10277     typval_T	*argvars;
10278     typval_T	*rettv;
10279 {
10280     char_u	*s;
10281     int		len;
10282     char_u	*errormsg;
10283     int		options = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
10284     expand_T	xpc;
10285     int		error = FALSE;
10286     char_u	*result;
10287 
10288     rettv->v_type = VAR_STRING;
10289     if (argvars[1].v_type != VAR_UNKNOWN
10290 	    && argvars[2].v_type != VAR_UNKNOWN
10291 	    && get_tv_number_chk(&argvars[2], &error)
10292 	    && !error)
10293     {
10294 	rettv->v_type = VAR_LIST;
10295 	rettv->vval.v_list = NULL;
10296     }
10297 
10298     s = get_tv_string(&argvars[0]);
10299     if (*s == '%' || *s == '#' || *s == '<')
10300     {
10301 	++emsg_off;
10302 	result = eval_vars(s, s, &len, NULL, &errormsg, NULL);
10303 	--emsg_off;
10304 	if (rettv->v_type == VAR_LIST)
10305 	{
10306 	    if (rettv_list_alloc(rettv) != FAIL && result != NULL)
10307 		list_append_string(rettv->vval.v_list, result, -1);
10308 	    else
10309 		vim_free(result);
10310 	}
10311 	else
10312 	    rettv->vval.v_string = result;
10313     }
10314     else
10315     {
10316 	/* When the optional second argument is non-zero, don't remove matches
10317 	 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
10318 	if (argvars[1].v_type != VAR_UNKNOWN
10319 				    && get_tv_number_chk(&argvars[1], &error))
10320 	    options |= WILD_KEEP_ALL;
10321 	if (!error)
10322 	{
10323 	    ExpandInit(&xpc);
10324 	    xpc.xp_context = EXPAND_FILES;
10325 	    if (p_wic)
10326 		options += WILD_ICASE;
10327 	    if (rettv->v_type == VAR_STRING)
10328 		rettv->vval.v_string = ExpandOne(&xpc, s, NULL,
10329 							   options, WILD_ALL);
10330 	    else if (rettv_list_alloc(rettv) != FAIL)
10331 	    {
10332 		int i;
10333 
10334 		ExpandOne(&xpc, s, NULL, options, WILD_ALL_KEEP);
10335 		for (i = 0; i < xpc.xp_numfiles; i++)
10336 		    list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
10337 		ExpandCleanup(&xpc);
10338 	    }
10339 	}
10340 	else
10341 	    rettv->vval.v_string = NULL;
10342     }
10343 }
10344 
10345 /*
10346  * Go over all entries in "d2" and add them to "d1".
10347  * When "action" is "error" then a duplicate key is an error.
10348  * When "action" is "force" then a duplicate key is overwritten.
10349  * Otherwise duplicate keys are ignored ("action" is "keep").
10350  */
10351     void
10352 dict_extend(d1, d2, action)
10353     dict_T	*d1;
10354     dict_T	*d2;
10355     char_u	*action;
10356 {
10357     dictitem_T	*di1;
10358     hashitem_T	*hi2;
10359     int		todo;
10360 
10361     todo = (int)d2->dv_hashtab.ht_used;
10362     for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
10363     {
10364 	if (!HASHITEM_EMPTY(hi2))
10365 	{
10366 	    --todo;
10367 	    di1 = dict_find(d1, hi2->hi_key, -1);
10368 	    if (d1->dv_scope != 0)
10369 	    {
10370 		/* Disallow replacing a builtin function in l: and g:.
10371 		 * Check the key to be valid when adding to any
10372 		 * scope. */
10373 		if (d1->dv_scope == VAR_DEF_SCOPE
10374 			&& HI2DI(hi2)->di_tv.v_type == VAR_FUNC
10375 			&& var_check_func_name(hi2->hi_key,
10376 							 di1 == NULL))
10377 		    break;
10378 		if (!valid_varname(hi2->hi_key))
10379 		    break;
10380 	    }
10381 	    if (di1 == NULL)
10382 	    {
10383 		di1 = dictitem_copy(HI2DI(hi2));
10384 		if (di1 != NULL && dict_add(d1, di1) == FAIL)
10385 		    dictitem_free(di1);
10386 	    }
10387 	    else if (*action == 'e')
10388 	    {
10389 		EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
10390 		break;
10391 	    }
10392 	    else if (*action == 'f' && HI2DI(hi2) != di1)
10393 	    {
10394 		clear_tv(&di1->di_tv);
10395 		copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
10396 	    }
10397 	}
10398     }
10399 }
10400 
10401 /*
10402  * "extend(list, list [, idx])" function
10403  * "extend(dict, dict [, action])" function
10404  */
10405     static void
10406 f_extend(argvars, rettv)
10407     typval_T	*argvars;
10408     typval_T	*rettv;
10409 {
10410     char      *arg_errmsg = N_("extend() argument");
10411 
10412     if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
10413     {
10414 	list_T		*l1, *l2;
10415 	listitem_T	*item;
10416 	long		before;
10417 	int		error = FALSE;
10418 
10419 	l1 = argvars[0].vval.v_list;
10420 	l2 = argvars[1].vval.v_list;
10421 	if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)_(arg_errmsg))
10422 		&& l2 != NULL)
10423 	{
10424 	    if (argvars[2].v_type != VAR_UNKNOWN)
10425 	    {
10426 		before = get_tv_number_chk(&argvars[2], &error);
10427 		if (error)
10428 		    return;		/* type error; errmsg already given */
10429 
10430 		if (before == l1->lv_len)
10431 		    item = NULL;
10432 		else
10433 		{
10434 		    item = list_find(l1, before);
10435 		    if (item == NULL)
10436 		    {
10437 			EMSGN(_(e_listidx), before);
10438 			return;
10439 		    }
10440 		}
10441 	    }
10442 	    else
10443 		item = NULL;
10444 	    list_extend(l1, l2, item);
10445 
10446 	    copy_tv(&argvars[0], rettv);
10447 	}
10448     }
10449     else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
10450     {
10451 	dict_T	*d1, *d2;
10452 	char_u	*action;
10453 	int	i;
10454 
10455 	d1 = argvars[0].vval.v_dict;
10456 	d2 = argvars[1].vval.v_dict;
10457 	if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)_(arg_errmsg))
10458 		&& d2 != NULL)
10459 	{
10460 	    /* Check the third argument. */
10461 	    if (argvars[2].v_type != VAR_UNKNOWN)
10462 	    {
10463 		static char *(av[]) = {"keep", "force", "error"};
10464 
10465 		action = get_tv_string_chk(&argvars[2]);
10466 		if (action == NULL)
10467 		    return;		/* type error; errmsg already given */
10468 		for (i = 0; i < 3; ++i)
10469 		    if (STRCMP(action, av[i]) == 0)
10470 			break;
10471 		if (i == 3)
10472 		{
10473 		    EMSG2(_(e_invarg2), action);
10474 		    return;
10475 		}
10476 	    }
10477 	    else
10478 		action = (char_u *)"force";
10479 
10480 	    dict_extend(d1, d2, action);
10481 
10482 	    copy_tv(&argvars[0], rettv);
10483 	}
10484     }
10485     else
10486 	EMSG2(_(e_listdictarg), "extend()");
10487 }
10488 
10489 /*
10490  * "feedkeys()" function
10491  */
10492     static void
10493 f_feedkeys(argvars, rettv)
10494     typval_T    *argvars;
10495     typval_T    *rettv UNUSED;
10496 {
10497     int		remap = TRUE;
10498     char_u	*keys, *flags;
10499     char_u	nbuf[NUMBUFLEN];
10500     int		typed = FALSE;
10501     char_u	*keys_esc;
10502 
10503     /* This is not allowed in the sandbox.  If the commands would still be
10504      * executed in the sandbox it would be OK, but it probably happens later,
10505      * when "sandbox" is no longer set. */
10506     if (check_secure())
10507 	return;
10508 
10509     keys = get_tv_string(&argvars[0]);
10510     if (*keys != NUL)
10511     {
10512 	if (argvars[1].v_type != VAR_UNKNOWN)
10513 	{
10514 	    flags = get_tv_string_buf(&argvars[1], nbuf);
10515 	    for ( ; *flags != NUL; ++flags)
10516 	    {
10517 		switch (*flags)
10518 		{
10519 		    case 'n': remap = FALSE; break;
10520 		    case 'm': remap = TRUE; break;
10521 		    case 't': typed = TRUE; break;
10522 		}
10523 	    }
10524 	}
10525 
10526 	/* Need to escape K_SPECIAL and CSI before putting the string in the
10527 	 * typeahead buffer. */
10528 	keys_esc = vim_strsave_escape_csi(keys);
10529 	if (keys_esc != NULL)
10530 	{
10531 	    ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
10532 					       typebuf.tb_len, !typed, FALSE);
10533 	    vim_free(keys_esc);
10534 	    if (vgetc_busy)
10535 		typebuf_was_filled = TRUE;
10536 	}
10537     }
10538 }
10539 
10540 /*
10541  * "filereadable()" function
10542  */
10543     static void
10544 f_filereadable(argvars, rettv)
10545     typval_T	*argvars;
10546     typval_T	*rettv;
10547 {
10548     int		fd;
10549     char_u	*p;
10550     int		n;
10551 
10552 #ifndef O_NONBLOCK
10553 # define O_NONBLOCK 0
10554 #endif
10555     p = get_tv_string(&argvars[0]);
10556     if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
10557 					      O_RDONLY | O_NONBLOCK, 0)) >= 0)
10558     {
10559 	n = TRUE;
10560 	close(fd);
10561     }
10562     else
10563 	n = FALSE;
10564 
10565     rettv->vval.v_number = n;
10566 }
10567 
10568 /*
10569  * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
10570  * rights to write into.
10571  */
10572     static void
10573 f_filewritable(argvars, rettv)
10574     typval_T	*argvars;
10575     typval_T	*rettv;
10576 {
10577     rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
10578 }
10579 
10580 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
10581 
10582     static void
10583 findfilendir(argvars, rettv, find_what)
10584     typval_T	*argvars UNUSED;
10585     typval_T	*rettv;
10586     int		find_what UNUSED;
10587 {
10588 #ifdef FEAT_SEARCHPATH
10589     char_u	*fname;
10590     char_u	*fresult = NULL;
10591     char_u	*path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
10592     char_u	*p;
10593     char_u	pathbuf[NUMBUFLEN];
10594     int		count = 1;
10595     int		first = TRUE;
10596     int		error = FALSE;
10597 #endif
10598 
10599     rettv->vval.v_string = NULL;
10600     rettv->v_type = VAR_STRING;
10601 
10602 #ifdef FEAT_SEARCHPATH
10603     fname = get_tv_string(&argvars[0]);
10604 
10605     if (argvars[1].v_type != VAR_UNKNOWN)
10606     {
10607 	p = get_tv_string_buf_chk(&argvars[1], pathbuf);
10608 	if (p == NULL)
10609 	    error = TRUE;
10610 	else
10611 	{
10612 	    if (*p != NUL)
10613 		path = p;
10614 
10615 	    if (argvars[2].v_type != VAR_UNKNOWN)
10616 		count = get_tv_number_chk(&argvars[2], &error);
10617 	}
10618     }
10619 
10620     if (count < 0 && rettv_list_alloc(rettv) == FAIL)
10621 	error = TRUE;
10622 
10623     if (*fname != NUL && !error)
10624     {
10625 	do
10626 	{
10627 	    if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST)
10628 		vim_free(fresult);
10629 	    fresult = find_file_in_path_option(first ? fname : NULL,
10630 					       first ? (int)STRLEN(fname) : 0,
10631 					0, first, path,
10632 					find_what,
10633 					curbuf->b_ffname,
10634 					find_what == FINDFILE_DIR
10635 					    ? (char_u *)"" : curbuf->b_p_sua);
10636 	    first = FALSE;
10637 
10638 	    if (fresult != NULL && rettv->v_type == VAR_LIST)
10639 		list_append_string(rettv->vval.v_list, fresult, -1);
10640 
10641 	} while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
10642     }
10643 
10644     if (rettv->v_type == VAR_STRING)
10645 	rettv->vval.v_string = fresult;
10646 #endif
10647 }
10648 
10649 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
10650 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
10651 
10652 /*
10653  * Implementation of map() and filter().
10654  */
10655     static void
10656 filter_map(argvars, rettv, map)
10657     typval_T	*argvars;
10658     typval_T	*rettv;
10659     int		map;
10660 {
10661     char_u	buf[NUMBUFLEN];
10662     char_u	*expr;
10663     listitem_T	*li, *nli;
10664     list_T	*l = NULL;
10665     dictitem_T	*di;
10666     hashtab_T	*ht;
10667     hashitem_T	*hi;
10668     dict_T	*d = NULL;
10669     typval_T	save_val;
10670     typval_T	save_key;
10671     int		rem;
10672     int		todo;
10673     char_u	*ermsg = (char_u *)(map ? "map()" : "filter()");
10674     char	*arg_errmsg = (map ? N_("map() argument")
10675 				   : N_("filter() argument"));
10676     int		save_did_emsg;
10677     int		idx = 0;
10678 
10679     if (argvars[0].v_type == VAR_LIST)
10680     {
10681 	if ((l = argvars[0].vval.v_list) == NULL
10682 		|| tv_check_lock(l->lv_lock, (char_u *)_(arg_errmsg)))
10683 	    return;
10684     }
10685     else if (argvars[0].v_type == VAR_DICT)
10686     {
10687 	if ((d = argvars[0].vval.v_dict) == NULL
10688 		|| tv_check_lock(d->dv_lock, (char_u *)_(arg_errmsg)))
10689 	    return;
10690     }
10691     else
10692     {
10693 	EMSG2(_(e_listdictarg), ermsg);
10694 	return;
10695     }
10696 
10697     expr = get_tv_string_buf_chk(&argvars[1], buf);
10698     /* On type errors, the preceding call has already displayed an error
10699      * message.  Avoid a misleading error message for an empty string that
10700      * was not passed as argument. */
10701     if (expr != NULL)
10702     {
10703 	prepare_vimvar(VV_VAL, &save_val);
10704 	expr = skipwhite(expr);
10705 
10706 	/* We reset "did_emsg" to be able to detect whether an error
10707 	 * occurred during evaluation of the expression. */
10708 	save_did_emsg = did_emsg;
10709 	did_emsg = FALSE;
10710 
10711 	prepare_vimvar(VV_KEY, &save_key);
10712 	if (argvars[0].v_type == VAR_DICT)
10713 	{
10714 	    vimvars[VV_KEY].vv_type = VAR_STRING;
10715 
10716 	    ht = &d->dv_hashtab;
10717 	    hash_lock(ht);
10718 	    todo = (int)ht->ht_used;
10719 	    for (hi = ht->ht_array; todo > 0; ++hi)
10720 	    {
10721 		if (!HASHITEM_EMPTY(hi))
10722 		{
10723 		    --todo;
10724 		    di = HI2DI(hi);
10725 		    if (tv_check_lock(di->di_tv.v_lock,
10726 						     (char_u *)_(arg_errmsg)))
10727 			break;
10728 		    vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
10729 		    if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
10730 								  || did_emsg)
10731 			break;
10732 		    if (!map && rem)
10733 			dictitem_remove(d, di);
10734 		    clear_tv(&vimvars[VV_KEY].vv_tv);
10735 		}
10736 	    }
10737 	    hash_unlock(ht);
10738 	}
10739 	else
10740 	{
10741 	    vimvars[VV_KEY].vv_type = VAR_NUMBER;
10742 
10743 	    for (li = l->lv_first; li != NULL; li = nli)
10744 	    {
10745 		if (tv_check_lock(li->li_tv.v_lock, (char_u *)_(arg_errmsg)))
10746 		    break;
10747 		nli = li->li_next;
10748 		vimvars[VV_KEY].vv_nr = idx;
10749 		if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10750 								  || did_emsg)
10751 		    break;
10752 		if (!map && rem)
10753 		    listitem_remove(l, li);
10754 		++idx;
10755 	    }
10756 	}
10757 
10758 	restore_vimvar(VV_KEY, &save_key);
10759 	restore_vimvar(VV_VAL, &save_val);
10760 
10761 	did_emsg |= save_did_emsg;
10762     }
10763 
10764     copy_tv(&argvars[0], rettv);
10765 }
10766 
10767     static int
10768 filter_map_one(tv, expr, map, remp)
10769     typval_T	*tv;
10770     char_u	*expr;
10771     int		map;
10772     int		*remp;
10773 {
10774     typval_T	rettv;
10775     char_u	*s;
10776     int		retval = FAIL;
10777 
10778     copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10779     s = expr;
10780     if (eval1(&s, &rettv, TRUE) == FAIL)
10781 	goto theend;
10782     if (*s != NUL)  /* check for trailing chars after expr */
10783     {
10784 	EMSG2(_(e_invexpr2), s);
10785 	goto theend;
10786     }
10787     if (map)
10788     {
10789 	/* map(): replace the list item value */
10790 	clear_tv(tv);
10791 	rettv.v_lock = 0;
10792 	*tv = rettv;
10793     }
10794     else
10795     {
10796 	int	    error = FALSE;
10797 
10798 	/* filter(): when expr is zero remove the item */
10799 	*remp = (get_tv_number_chk(&rettv, &error) == 0);
10800 	clear_tv(&rettv);
10801 	/* On type error, nothing has been removed; return FAIL to stop the
10802 	 * loop.  The error message was given by get_tv_number_chk(). */
10803 	if (error)
10804 	    goto theend;
10805     }
10806     retval = OK;
10807 theend:
10808     clear_tv(&vimvars[VV_VAL].vv_tv);
10809     return retval;
10810 }
10811 
10812 /*
10813  * "filter()" function
10814  */
10815     static void
10816 f_filter(argvars, rettv)
10817     typval_T	*argvars;
10818     typval_T	*rettv;
10819 {
10820     filter_map(argvars, rettv, FALSE);
10821 }
10822 
10823 /*
10824  * "finddir({fname}[, {path}[, {count}]])" function
10825  */
10826     static void
10827 f_finddir(argvars, rettv)
10828     typval_T	*argvars;
10829     typval_T	*rettv;
10830 {
10831     findfilendir(argvars, rettv, FINDFILE_DIR);
10832 }
10833 
10834 /*
10835  * "findfile({fname}[, {path}[, {count}]])" function
10836  */
10837     static void
10838 f_findfile(argvars, rettv)
10839     typval_T	*argvars;
10840     typval_T	*rettv;
10841 {
10842     findfilendir(argvars, rettv, FINDFILE_FILE);
10843 }
10844 
10845 #ifdef FEAT_FLOAT
10846 /*
10847  * "float2nr({float})" function
10848  */
10849     static void
10850 f_float2nr(argvars, rettv)
10851     typval_T	*argvars;
10852     typval_T	*rettv;
10853 {
10854     float_T	f;
10855 
10856     if (get_float_arg(argvars, &f) == OK)
10857     {
10858 	if (f < -0x7fffffff)
10859 	    rettv->vval.v_number = -0x7fffffff;
10860 	else if (f > 0x7fffffff)
10861 	    rettv->vval.v_number = 0x7fffffff;
10862 	else
10863 	    rettv->vval.v_number = (varnumber_T)f;
10864     }
10865 }
10866 
10867 /*
10868  * "floor({float})" function
10869  */
10870     static void
10871 f_floor(argvars, rettv)
10872     typval_T	*argvars;
10873     typval_T	*rettv;
10874 {
10875     float_T	f;
10876 
10877     rettv->v_type = VAR_FLOAT;
10878     if (get_float_arg(argvars, &f) == OK)
10879 	rettv->vval.v_float = floor(f);
10880     else
10881 	rettv->vval.v_float = 0.0;
10882 }
10883 
10884 /*
10885  * "fmod()" function
10886  */
10887     static void
10888 f_fmod(argvars, rettv)
10889     typval_T	*argvars;
10890     typval_T	*rettv;
10891 {
10892     float_T	fx, fy;
10893 
10894     rettv->v_type = VAR_FLOAT;
10895     if (get_float_arg(argvars, &fx) == OK
10896 				     && get_float_arg(&argvars[1], &fy) == OK)
10897 	rettv->vval.v_float = fmod(fx, fy);
10898     else
10899 	rettv->vval.v_float = 0.0;
10900 }
10901 #endif
10902 
10903 /*
10904  * "fnameescape({string})" function
10905  */
10906     static void
10907 f_fnameescape(argvars, rettv)
10908     typval_T	*argvars;
10909     typval_T	*rettv;
10910 {
10911     rettv->vval.v_string = vim_strsave_fnameescape(
10912 					   get_tv_string(&argvars[0]), FALSE);
10913     rettv->v_type = VAR_STRING;
10914 }
10915 
10916 /*
10917  * "fnamemodify({fname}, {mods})" function
10918  */
10919     static void
10920 f_fnamemodify(argvars, rettv)
10921     typval_T	*argvars;
10922     typval_T	*rettv;
10923 {
10924     char_u	*fname;
10925     char_u	*mods;
10926     int		usedlen = 0;
10927     int		len;
10928     char_u	*fbuf = NULL;
10929     char_u	buf[NUMBUFLEN];
10930 
10931     fname = get_tv_string_chk(&argvars[0]);
10932     mods = get_tv_string_buf_chk(&argvars[1], buf);
10933     if (fname == NULL || mods == NULL)
10934 	fname = NULL;
10935     else
10936     {
10937 	len = (int)STRLEN(fname);
10938 	(void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10939     }
10940 
10941     rettv->v_type = VAR_STRING;
10942     if (fname == NULL)
10943 	rettv->vval.v_string = NULL;
10944     else
10945 	rettv->vval.v_string = vim_strnsave(fname, len);
10946     vim_free(fbuf);
10947 }
10948 
10949 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10950 
10951 /*
10952  * "foldclosed()" function
10953  */
10954     static void
10955 foldclosed_both(argvars, rettv, end)
10956     typval_T	*argvars UNUSED;
10957     typval_T	*rettv;
10958     int		end UNUSED;
10959 {
10960 #ifdef FEAT_FOLDING
10961     linenr_T	lnum;
10962     linenr_T	first, last;
10963 
10964     lnum = get_tv_lnum(argvars);
10965     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10966     {
10967 	if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10968 	{
10969 	    if (end)
10970 		rettv->vval.v_number = (varnumber_T)last;
10971 	    else
10972 		rettv->vval.v_number = (varnumber_T)first;
10973 	    return;
10974 	}
10975     }
10976 #endif
10977     rettv->vval.v_number = -1;
10978 }
10979 
10980 /*
10981  * "foldclosed()" function
10982  */
10983     static void
10984 f_foldclosed(argvars, rettv)
10985     typval_T	*argvars;
10986     typval_T	*rettv;
10987 {
10988     foldclosed_both(argvars, rettv, FALSE);
10989 }
10990 
10991 /*
10992  * "foldclosedend()" function
10993  */
10994     static void
10995 f_foldclosedend(argvars, rettv)
10996     typval_T	*argvars;
10997     typval_T	*rettv;
10998 {
10999     foldclosed_both(argvars, rettv, TRUE);
11000 }
11001 
11002 /*
11003  * "foldlevel()" function
11004  */
11005     static void
11006 f_foldlevel(argvars, rettv)
11007     typval_T	*argvars UNUSED;
11008     typval_T	*rettv UNUSED;
11009 {
11010 #ifdef FEAT_FOLDING
11011     linenr_T	lnum;
11012 
11013     lnum = get_tv_lnum(argvars);
11014     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
11015 	rettv->vval.v_number = foldLevel(lnum);
11016 #endif
11017 }
11018 
11019 /*
11020  * "foldtext()" function
11021  */
11022     static void
11023 f_foldtext(argvars, rettv)
11024     typval_T	*argvars UNUSED;
11025     typval_T	*rettv;
11026 {
11027 #ifdef FEAT_FOLDING
11028     linenr_T	lnum;
11029     char_u	*s;
11030     char_u	*r;
11031     int		len;
11032     char	*txt;
11033 #endif
11034 
11035     rettv->v_type = VAR_STRING;
11036     rettv->vval.v_string = NULL;
11037 #ifdef FEAT_FOLDING
11038     if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
11039 	    && (linenr_T)vimvars[VV_FOLDEND].vv_nr
11040 						 <= curbuf->b_ml.ml_line_count
11041 	    && vimvars[VV_FOLDDASHES].vv_str != NULL)
11042     {
11043 	/* Find first non-empty line in the fold. */
11044 	lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
11045 	while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
11046 	{
11047 	    if (!linewhite(lnum))
11048 		break;
11049 	    ++lnum;
11050 	}
11051 
11052 	/* Find interesting text in this line. */
11053 	s = skipwhite(ml_get(lnum));
11054 	/* skip C comment-start */
11055 	if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
11056 	{
11057 	    s = skipwhite(s + 2);
11058 	    if (*skipwhite(s) == NUL
11059 			    && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
11060 	    {
11061 		s = skipwhite(ml_get(lnum + 1));
11062 		if (*s == '*')
11063 		    s = skipwhite(s + 1);
11064 	    }
11065 	}
11066 	txt = _("+-%s%3ld lines: ");
11067 	r = alloc((unsigned)(STRLEN(txt)
11068 		    + STRLEN(vimvars[VV_FOLDDASHES].vv_str)    /* for %s */
11069 		    + 20				    /* for %3ld */
11070 		    + STRLEN(s)));			    /* concatenated */
11071 	if (r != NULL)
11072 	{
11073 	    sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
11074 		    (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
11075 				- (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
11076 	    len = (int)STRLEN(r);
11077 	    STRCAT(r, s);
11078 	    /* remove 'foldmarker' and 'commentstring' */
11079 	    foldtext_cleanup(r + len);
11080 	    rettv->vval.v_string = r;
11081 	}
11082     }
11083 #endif
11084 }
11085 
11086 /*
11087  * "foldtextresult(lnum)" function
11088  */
11089     static void
11090 f_foldtextresult(argvars, rettv)
11091     typval_T	*argvars UNUSED;
11092     typval_T	*rettv;
11093 {
11094 #ifdef FEAT_FOLDING
11095     linenr_T	lnum;
11096     char_u	*text;
11097     char_u	buf[51];
11098     foldinfo_T  foldinfo;
11099     int		fold_count;
11100 #endif
11101 
11102     rettv->v_type = VAR_STRING;
11103     rettv->vval.v_string = NULL;
11104 #ifdef FEAT_FOLDING
11105     lnum = get_tv_lnum(argvars);
11106     /* treat illegal types and illegal string values for {lnum} the same */
11107     if (lnum < 0)
11108 	lnum = 0;
11109     fold_count = foldedCount(curwin, lnum, &foldinfo);
11110     if (fold_count > 0)
11111     {
11112 	text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
11113 							      &foldinfo, buf);
11114 	if (text == buf)
11115 	    text = vim_strsave(text);
11116 	rettv->vval.v_string = text;
11117     }
11118 #endif
11119 }
11120 
11121 /*
11122  * "foreground()" function
11123  */
11124     static void
11125 f_foreground(argvars, rettv)
11126     typval_T	*argvars UNUSED;
11127     typval_T	*rettv UNUSED;
11128 {
11129 #ifdef FEAT_GUI
11130     if (gui.in_use)
11131 	gui_mch_set_foreground();
11132 #else
11133 # ifdef WIN32
11134     win32_set_foreground();
11135 # endif
11136 #endif
11137 }
11138 
11139 /*
11140  * "function()" function
11141  */
11142     static void
11143 f_function(argvars, rettv)
11144     typval_T	*argvars;
11145     typval_T	*rettv;
11146 {
11147     char_u	*s;
11148 
11149     s = get_tv_string(&argvars[0]);
11150     if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
11151 	EMSG2(_(e_invarg2), s);
11152     /* Don't check an autoload name for existence here. */
11153     else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
11154 	EMSG2(_("E700: Unknown function: %s"), s);
11155     else
11156     {
11157 	if (STRNCMP(s, "s:", 2) == 0 || STRNCMP(s, "<SID>", 5) == 0)
11158 	{
11159 	    char	sid_buf[25];
11160 	    int		off = *s == 's' ? 2 : 5;
11161 
11162 	    /* Expand s: and <SID> into <SNR>nr_, so that the function can
11163 	     * also be called from another script. Using trans_function_name()
11164 	     * would also work, but some plugins depend on the name being
11165 	     * printable text. */
11166 	    sprintf(sid_buf, "<SNR>%ld_", (long)current_SID);
11167 	    rettv->vval.v_string =
11168 			    alloc((int)(STRLEN(sid_buf) + STRLEN(s + off) + 1));
11169 	    if (rettv->vval.v_string != NULL)
11170 	    {
11171 		STRCPY(rettv->vval.v_string, sid_buf);
11172 		STRCAT(rettv->vval.v_string, s + off);
11173 	    }
11174 	}
11175 	else
11176 	    rettv->vval.v_string = vim_strsave(s);
11177 	rettv->v_type = VAR_FUNC;
11178     }
11179 }
11180 
11181 /*
11182  * "garbagecollect()" function
11183  */
11184     static void
11185 f_garbagecollect(argvars, rettv)
11186     typval_T	*argvars;
11187     typval_T	*rettv UNUSED;
11188 {
11189     /* This is postponed until we are back at the toplevel, because we may be
11190      * using Lists and Dicts internally.  E.g.: ":echo [garbagecollect()]". */
11191     want_garbage_collect = TRUE;
11192 
11193     if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
11194 	garbage_collect_at_exit = TRUE;
11195 }
11196 
11197 /*
11198  * "get()" function
11199  */
11200     static void
11201 f_get(argvars, rettv)
11202     typval_T	*argvars;
11203     typval_T	*rettv;
11204 {
11205     listitem_T	*li;
11206     list_T	*l;
11207     dictitem_T	*di;
11208     dict_T	*d;
11209     typval_T	*tv = NULL;
11210 
11211     if (argvars[0].v_type == VAR_LIST)
11212     {
11213 	if ((l = argvars[0].vval.v_list) != NULL)
11214 	{
11215 	    int		error = FALSE;
11216 
11217 	    li = list_find(l, get_tv_number_chk(&argvars[1], &error));
11218 	    if (!error && li != NULL)
11219 		tv = &li->li_tv;
11220 	}
11221     }
11222     else if (argvars[0].v_type == VAR_DICT)
11223     {
11224 	if ((d = argvars[0].vval.v_dict) != NULL)
11225 	{
11226 	    di = dict_find(d, get_tv_string(&argvars[1]), -1);
11227 	    if (di != NULL)
11228 		tv = &di->di_tv;
11229 	}
11230     }
11231     else
11232 	EMSG2(_(e_listdictarg), "get()");
11233 
11234     if (tv == NULL)
11235     {
11236 	if (argvars[2].v_type != VAR_UNKNOWN)
11237 	    copy_tv(&argvars[2], rettv);
11238     }
11239     else
11240 	copy_tv(tv, rettv);
11241 }
11242 
11243 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
11244 
11245 /*
11246  * Get line or list of lines from buffer "buf" into "rettv".
11247  * Return a range (from start to end) of lines in rettv from the specified
11248  * buffer.
11249  * If 'retlist' is TRUE, then the lines are returned as a Vim List.
11250  */
11251     static void
11252 get_buffer_lines(buf, start, end, retlist, rettv)
11253     buf_T	*buf;
11254     linenr_T	start;
11255     linenr_T	end;
11256     int		retlist;
11257     typval_T	*rettv;
11258 {
11259     char_u	*p;
11260 
11261     rettv->v_type = VAR_STRING;
11262     rettv->vval.v_string = NULL;
11263     if (retlist && rettv_list_alloc(rettv) == FAIL)
11264 	return;
11265 
11266     if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
11267 	return;
11268 
11269     if (!retlist)
11270     {
11271 	if (start >= 1 && start <= buf->b_ml.ml_line_count)
11272 	    p = ml_get_buf(buf, start, FALSE);
11273 	else
11274 	    p = (char_u *)"";
11275 	rettv->vval.v_string = vim_strsave(p);
11276     }
11277     else
11278     {
11279 	if (end < start)
11280 	    return;
11281 
11282 	if (start < 1)
11283 	    start = 1;
11284 	if (end > buf->b_ml.ml_line_count)
11285 	    end = buf->b_ml.ml_line_count;
11286 	while (start <= end)
11287 	    if (list_append_string(rettv->vval.v_list,
11288 				 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
11289 		break;
11290     }
11291 }
11292 
11293 /*
11294  * "getbufline()" function
11295  */
11296     static void
11297 f_getbufline(argvars, rettv)
11298     typval_T	*argvars;
11299     typval_T	*rettv;
11300 {
11301     linenr_T	lnum;
11302     linenr_T	end;
11303     buf_T	*buf;
11304 
11305     (void)get_tv_number(&argvars[0]);	    /* issue errmsg if type error */
11306     ++emsg_off;
11307     buf = get_buf_tv(&argvars[0], FALSE);
11308     --emsg_off;
11309 
11310     lnum = get_tv_lnum_buf(&argvars[1], buf);
11311     if (argvars[2].v_type == VAR_UNKNOWN)
11312 	end = lnum;
11313     else
11314 	end = get_tv_lnum_buf(&argvars[2], buf);
11315 
11316     get_buffer_lines(buf, lnum, end, TRUE, rettv);
11317 }
11318 
11319 /*
11320  * "getbufvar()" function
11321  */
11322     static void
11323 f_getbufvar(argvars, rettv)
11324     typval_T	*argvars;
11325     typval_T	*rettv;
11326 {
11327     buf_T	*buf;
11328     buf_T	*save_curbuf;
11329     char_u	*varname;
11330     dictitem_T	*v;
11331     int		done = FALSE;
11332 
11333     (void)get_tv_number(&argvars[0]);	    /* issue errmsg if type error */
11334     varname = get_tv_string_chk(&argvars[1]);
11335     ++emsg_off;
11336     buf = get_buf_tv(&argvars[0], FALSE);
11337 
11338     rettv->v_type = VAR_STRING;
11339     rettv->vval.v_string = NULL;
11340 
11341     if (buf != NULL && varname != NULL)
11342     {
11343 	/* set curbuf to be our buf, temporarily */
11344 	save_curbuf = curbuf;
11345 	curbuf = buf;
11346 
11347 	if (*varname == '&')	/* buffer-local-option */
11348 	{
11349 	    if (get_option_tv(&varname, rettv, TRUE) == OK)
11350 		done = TRUE;
11351 	}
11352 	else if (STRCMP(varname, "changedtick") == 0)
11353 	{
11354 	    rettv->v_type = VAR_NUMBER;
11355 	    rettv->vval.v_number = curbuf->b_changedtick;
11356 	    done = TRUE;
11357 	}
11358 	else
11359 	{
11360 	    /* Look up the variable. */
11361 	    /* Let getbufvar({nr}, "") return the "b:" dictionary. */
11362 	    v = find_var_in_ht(&curbuf->b_vars->dv_hashtab,
11363 							 'b', varname, FALSE);
11364 	    if (v != NULL)
11365 	    {
11366 		copy_tv(&v->di_tv, rettv);
11367 		done = TRUE;
11368 	    }
11369 	}
11370 
11371 	/* restore previous notion of curbuf */
11372 	curbuf = save_curbuf;
11373     }
11374 
11375     if (!done && argvars[2].v_type != VAR_UNKNOWN)
11376 	/* use the default value */
11377 	copy_tv(&argvars[2], rettv);
11378 
11379     --emsg_off;
11380 }
11381 
11382 /*
11383  * "getchar()" function
11384  */
11385     static void
11386 f_getchar(argvars, rettv)
11387     typval_T	*argvars;
11388     typval_T	*rettv;
11389 {
11390     varnumber_T		n;
11391     int			error = FALSE;
11392 
11393     /* Position the cursor.  Needed after a message that ends in a space. */
11394     windgoto(msg_row, msg_col);
11395 
11396     ++no_mapping;
11397     ++allow_keys;
11398     for (;;)
11399     {
11400 	if (argvars[0].v_type == VAR_UNKNOWN)
11401 	    /* getchar(): blocking wait. */
11402 	    n = safe_vgetc();
11403 	else if (get_tv_number_chk(&argvars[0], &error) == 1)
11404 	    /* getchar(1): only check if char avail */
11405 	    n = vpeekc_any();
11406 	else if (error || vpeekc_any() == NUL)
11407 	    /* illegal argument or getchar(0) and no char avail: return zero */
11408 	    n = 0;
11409 	else
11410 	    /* getchar(0) and char avail: return char */
11411 	    n = safe_vgetc();
11412 
11413 	if (n == K_IGNORE)
11414 	    continue;
11415 	break;
11416     }
11417     --no_mapping;
11418     --allow_keys;
11419 
11420     vimvars[VV_MOUSE_WIN].vv_nr = 0;
11421     vimvars[VV_MOUSE_LNUM].vv_nr = 0;
11422     vimvars[VV_MOUSE_COL].vv_nr = 0;
11423 
11424     rettv->vval.v_number = n;
11425     if (IS_SPECIAL(n) || mod_mask != 0)
11426     {
11427 	char_u		temp[10];   /* modifier: 3, mbyte-char: 6, NUL: 1 */
11428 	int		i = 0;
11429 
11430 	/* Turn a special key into three bytes, plus modifier. */
11431 	if (mod_mask != 0)
11432 	{
11433 	    temp[i++] = K_SPECIAL;
11434 	    temp[i++] = KS_MODIFIER;
11435 	    temp[i++] = mod_mask;
11436 	}
11437 	if (IS_SPECIAL(n))
11438 	{
11439 	    temp[i++] = K_SPECIAL;
11440 	    temp[i++] = K_SECOND(n);
11441 	    temp[i++] = K_THIRD(n);
11442 	}
11443 #ifdef FEAT_MBYTE
11444 	else if (has_mbyte)
11445 	    i += (*mb_char2bytes)(n, temp + i);
11446 #endif
11447 	else
11448 	    temp[i++] = n;
11449 	temp[i++] = NUL;
11450 	rettv->v_type = VAR_STRING;
11451 	rettv->vval.v_string = vim_strsave(temp);
11452 
11453 #ifdef FEAT_MOUSE
11454 	if (is_mouse_key(n))
11455 	{
11456 	    int		row = mouse_row;
11457 	    int		col = mouse_col;
11458 	    win_T	*win;
11459 	    linenr_T	lnum;
11460 # ifdef FEAT_WINDOWS
11461 	    win_T	*wp;
11462 # endif
11463 	    int		winnr = 1;
11464 
11465 	    if (row >= 0 && col >= 0)
11466 	    {
11467 		/* Find the window at the mouse coordinates and compute the
11468 		 * text position. */
11469 		win = mouse_find_win(&row, &col);
11470 		(void)mouse_comp_pos(win, &row, &col, &lnum);
11471 # ifdef FEAT_WINDOWS
11472 		for (wp = firstwin; wp != win; wp = wp->w_next)
11473 		    ++winnr;
11474 # endif
11475 		vimvars[VV_MOUSE_WIN].vv_nr = winnr;
11476 		vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
11477 		vimvars[VV_MOUSE_COL].vv_nr = col + 1;
11478 	    }
11479 	}
11480 #endif
11481     }
11482 }
11483 
11484 /*
11485  * "getcharmod()" function
11486  */
11487     static void
11488 f_getcharmod(argvars, rettv)
11489     typval_T	*argvars UNUSED;
11490     typval_T	*rettv;
11491 {
11492     rettv->vval.v_number = mod_mask;
11493 }
11494 
11495 /*
11496  * "getcmdline()" function
11497  */
11498     static void
11499 f_getcmdline(argvars, rettv)
11500     typval_T	*argvars UNUSED;
11501     typval_T	*rettv;
11502 {
11503     rettv->v_type = VAR_STRING;
11504     rettv->vval.v_string = get_cmdline_str();
11505 }
11506 
11507 /*
11508  * "getcmdpos()" function
11509  */
11510     static void
11511 f_getcmdpos(argvars, rettv)
11512     typval_T	*argvars UNUSED;
11513     typval_T	*rettv;
11514 {
11515     rettv->vval.v_number = get_cmdline_pos() + 1;
11516 }
11517 
11518 /*
11519  * "getcmdtype()" function
11520  */
11521     static void
11522 f_getcmdtype(argvars, rettv)
11523     typval_T	*argvars UNUSED;
11524     typval_T	*rettv;
11525 {
11526     rettv->v_type = VAR_STRING;
11527     rettv->vval.v_string = alloc(2);
11528     if (rettv->vval.v_string != NULL)
11529     {
11530 	rettv->vval.v_string[0] = get_cmdline_type();
11531 	rettv->vval.v_string[1] = NUL;
11532     }
11533 }
11534 
11535 /*
11536  * "getcmdwintype()" function
11537  */
11538     static void
11539 f_getcmdwintype(argvars, rettv)
11540     typval_T	*argvars UNUSED;
11541     typval_T	*rettv;
11542 {
11543     rettv->v_type = VAR_STRING;
11544     rettv->vval.v_string = NULL;
11545 #ifdef FEAT_CMDWIN
11546     rettv->vval.v_string = alloc(2);
11547     if (rettv->vval.v_string != NULL)
11548     {
11549 	rettv->vval.v_string[0] = cmdwin_type;
11550 	rettv->vval.v_string[1] = NUL;
11551     }
11552 #endif
11553 }
11554 
11555 /*
11556  * "getcwd()" function
11557  */
11558     static void
11559 f_getcwd(argvars, rettv)
11560     typval_T	*argvars UNUSED;
11561     typval_T	*rettv;
11562 {
11563     char_u	*cwd;
11564 
11565     rettv->v_type = VAR_STRING;
11566     rettv->vval.v_string = NULL;
11567     cwd = alloc(MAXPATHL);
11568     if (cwd != NULL)
11569     {
11570 	if (mch_dirname(cwd, MAXPATHL) != FAIL)
11571 	{
11572 	    rettv->vval.v_string = vim_strsave(cwd);
11573 #ifdef BACKSLASH_IN_FILENAME
11574 	    if (rettv->vval.v_string != NULL)
11575 		slash_adjust(rettv->vval.v_string);
11576 #endif
11577 	}
11578 	vim_free(cwd);
11579     }
11580 }
11581 
11582 /*
11583  * "getfontname()" function
11584  */
11585     static void
11586 f_getfontname(argvars, rettv)
11587     typval_T	*argvars UNUSED;
11588     typval_T	*rettv;
11589 {
11590     rettv->v_type = VAR_STRING;
11591     rettv->vval.v_string = NULL;
11592 #ifdef FEAT_GUI
11593     if (gui.in_use)
11594     {
11595 	GuiFont font;
11596 	char_u	*name = NULL;
11597 
11598 	if (argvars[0].v_type == VAR_UNKNOWN)
11599 	{
11600 	    /* Get the "Normal" font.  Either the name saved by
11601 	     * hl_set_font_name() or from the font ID. */
11602 	    font = gui.norm_font;
11603 	    name = hl_get_font_name();
11604 	}
11605 	else
11606 	{
11607 	    name = get_tv_string(&argvars[0]);
11608 	    if (STRCMP(name, "*") == 0)	    /* don't use font dialog */
11609 		return;
11610 	    font = gui_mch_get_font(name, FALSE);
11611 	    if (font == NOFONT)
11612 		return;	    /* Invalid font name, return empty string. */
11613 	}
11614 	rettv->vval.v_string = gui_mch_get_fontname(font, name);
11615 	if (argvars[0].v_type != VAR_UNKNOWN)
11616 	    gui_mch_free_font(font);
11617     }
11618 #endif
11619 }
11620 
11621 /*
11622  * "getfperm({fname})" function
11623  */
11624     static void
11625 f_getfperm(argvars, rettv)
11626     typval_T	*argvars;
11627     typval_T	*rettv;
11628 {
11629     char_u	*fname;
11630     struct stat st;
11631     char_u	*perm = NULL;
11632     char_u	flags[] = "rwx";
11633     int		i;
11634 
11635     fname = get_tv_string(&argvars[0]);
11636 
11637     rettv->v_type = VAR_STRING;
11638     if (mch_stat((char *)fname, &st) >= 0)
11639     {
11640 	perm = vim_strsave((char_u *)"---------");
11641 	if (perm != NULL)
11642 	{
11643 	    for (i = 0; i < 9; i++)
11644 	    {
11645 		if (st.st_mode & (1 << (8 - i)))
11646 		    perm[i] = flags[i % 3];
11647 	    }
11648 	}
11649     }
11650     rettv->vval.v_string = perm;
11651 }
11652 
11653 /*
11654  * "getfsize({fname})" function
11655  */
11656     static void
11657 f_getfsize(argvars, rettv)
11658     typval_T	*argvars;
11659     typval_T	*rettv;
11660 {
11661     char_u	*fname;
11662     struct stat	st;
11663 
11664     fname = get_tv_string(&argvars[0]);
11665 
11666     rettv->v_type = VAR_NUMBER;
11667 
11668     if (mch_stat((char *)fname, &st) >= 0)
11669     {
11670 	if (mch_isdir(fname))
11671 	    rettv->vval.v_number = 0;
11672 	else
11673 	{
11674 	    rettv->vval.v_number = (varnumber_T)st.st_size;
11675 
11676 	    /* non-perfect check for overflow */
11677 	    if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
11678 		rettv->vval.v_number = -2;
11679 	}
11680     }
11681     else
11682 	  rettv->vval.v_number = -1;
11683 }
11684 
11685 /*
11686  * "getftime({fname})" function
11687  */
11688     static void
11689 f_getftime(argvars, rettv)
11690     typval_T	*argvars;
11691     typval_T	*rettv;
11692 {
11693     char_u	*fname;
11694     struct stat	st;
11695 
11696     fname = get_tv_string(&argvars[0]);
11697 
11698     if (mch_stat((char *)fname, &st) >= 0)
11699 	rettv->vval.v_number = (varnumber_T)st.st_mtime;
11700     else
11701 	rettv->vval.v_number = -1;
11702 }
11703 
11704 /*
11705  * "getftype({fname})" function
11706  */
11707     static void
11708 f_getftype(argvars, rettv)
11709     typval_T	*argvars;
11710     typval_T	*rettv;
11711 {
11712     char_u	*fname;
11713     struct stat st;
11714     char_u	*type = NULL;
11715     char	*t;
11716 
11717     fname = get_tv_string(&argvars[0]);
11718 
11719     rettv->v_type = VAR_STRING;
11720     if (mch_lstat((char *)fname, &st) >= 0)
11721     {
11722 #ifdef S_ISREG
11723 	if (S_ISREG(st.st_mode))
11724 	    t = "file";
11725 	else if (S_ISDIR(st.st_mode))
11726 	    t = "dir";
11727 # ifdef S_ISLNK
11728 	else if (S_ISLNK(st.st_mode))
11729 	    t = "link";
11730 # endif
11731 # ifdef S_ISBLK
11732 	else if (S_ISBLK(st.st_mode))
11733 	    t = "bdev";
11734 # endif
11735 # ifdef S_ISCHR
11736 	else if (S_ISCHR(st.st_mode))
11737 	    t = "cdev";
11738 # endif
11739 # ifdef S_ISFIFO
11740 	else if (S_ISFIFO(st.st_mode))
11741 	    t = "fifo";
11742 # endif
11743 # ifdef S_ISSOCK
11744 	else if (S_ISSOCK(st.st_mode))
11745 	    t = "fifo";
11746 # endif
11747 	else
11748 	    t = "other";
11749 #else
11750 # ifdef S_IFMT
11751 	switch (st.st_mode & S_IFMT)
11752 	{
11753 	    case S_IFREG: t = "file"; break;
11754 	    case S_IFDIR: t = "dir"; break;
11755 #  ifdef S_IFLNK
11756 	    case S_IFLNK: t = "link"; break;
11757 #  endif
11758 #  ifdef S_IFBLK
11759 	    case S_IFBLK: t = "bdev"; break;
11760 #  endif
11761 #  ifdef S_IFCHR
11762 	    case S_IFCHR: t = "cdev"; break;
11763 #  endif
11764 #  ifdef S_IFIFO
11765 	    case S_IFIFO: t = "fifo"; break;
11766 #  endif
11767 #  ifdef S_IFSOCK
11768 	    case S_IFSOCK: t = "socket"; break;
11769 #  endif
11770 	    default: t = "other";
11771 	}
11772 # else
11773 	if (mch_isdir(fname))
11774 	    t = "dir";
11775 	else
11776 	    t = "file";
11777 # endif
11778 #endif
11779 	type = vim_strsave((char_u *)t);
11780     }
11781     rettv->vval.v_string = type;
11782 }
11783 
11784 /*
11785  * "getline(lnum, [end])" function
11786  */
11787     static void
11788 f_getline(argvars, rettv)
11789     typval_T	*argvars;
11790     typval_T	*rettv;
11791 {
11792     linenr_T	lnum;
11793     linenr_T	end;
11794     int		retlist;
11795 
11796     lnum = get_tv_lnum(argvars);
11797     if (argvars[1].v_type == VAR_UNKNOWN)
11798     {
11799 	end = 0;
11800 	retlist = FALSE;
11801     }
11802     else
11803     {
11804 	end = get_tv_lnum(&argvars[1]);
11805 	retlist = TRUE;
11806     }
11807 
11808     get_buffer_lines(curbuf, lnum, end, retlist, rettv);
11809 }
11810 
11811 /*
11812  * "getmatches()" function
11813  */
11814     static void
11815 f_getmatches(argvars, rettv)
11816     typval_T	*argvars UNUSED;
11817     typval_T	*rettv UNUSED;
11818 {
11819 #ifdef FEAT_SEARCH_EXTRA
11820     dict_T	*dict;
11821     matchitem_T	*cur = curwin->w_match_head;
11822     int		i;
11823 
11824     if (rettv_list_alloc(rettv) == OK)
11825     {
11826 	while (cur != NULL)
11827 	{
11828 	    dict = dict_alloc();
11829 	    if (dict == NULL)
11830 		return;
11831 	    if (cur->match.regprog == NULL)
11832 	    {
11833 		/* match added with matchaddpos() */
11834 		for (i = 0; i < MAXPOSMATCH; ++i)
11835 		{
11836 		    llpos_T	*llpos;
11837 		    char	buf[6];
11838 		    list_T	*l;
11839 
11840 		    llpos = &cur->pos.pos[i];
11841 		    if (llpos->lnum == 0)
11842 			break;
11843 		    l = list_alloc();
11844 		    if (l == NULL)
11845 			break;
11846 		    list_append_number(l, (varnumber_T)llpos->lnum);
11847 		    if (llpos->col > 0)
11848 		    {
11849 			list_append_number(l, (varnumber_T)llpos->col);
11850 			list_append_number(l, (varnumber_T)llpos->len);
11851 		    }
11852 		    sprintf(buf, "pos%d", i + 1);
11853 		    dict_add_list(dict, buf, l);
11854 		}
11855 	    }
11856 	    else
11857 	    {
11858 		dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11859 	    }
11860 	    dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11861 	    dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11862 	    dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11863 	    list_append_dict(rettv->vval.v_list, dict);
11864 	    cur = cur->next;
11865 	}
11866     }
11867 #endif
11868 }
11869 
11870 /*
11871  * "getpid()" function
11872  */
11873     static void
11874 f_getpid(argvars, rettv)
11875     typval_T	*argvars UNUSED;
11876     typval_T	*rettv;
11877 {
11878     rettv->vval.v_number = mch_get_pid();
11879 }
11880 
11881 static void getpos_both __ARGS((typval_T *argvars, typval_T *rettv, int getcurpos));
11882 
11883 /*
11884  * "getcurpos()" function
11885  */
11886     static void
11887 f_getcurpos(argvars, rettv)
11888     typval_T	*argvars;
11889     typval_T	*rettv;
11890 {
11891     getpos_both(argvars, rettv, TRUE);
11892 }
11893 
11894 /*
11895  * "getpos(string)" function
11896  */
11897     static void
11898 f_getpos(argvars, rettv)
11899     typval_T	*argvars;
11900     typval_T	*rettv;
11901 {
11902     getpos_both(argvars, rettv, FALSE);
11903 }
11904 
11905     static void
11906 getpos_both(argvars, rettv, getcurpos)
11907     typval_T	*argvars;
11908     typval_T	*rettv;
11909     int		getcurpos;
11910 {
11911     pos_T	*fp;
11912     list_T	*l;
11913     int		fnum = -1;
11914 
11915     if (rettv_list_alloc(rettv) == OK)
11916     {
11917 	l = rettv->vval.v_list;
11918 	if (getcurpos)
11919 	    fp = &curwin->w_cursor;
11920 	else
11921 	    fp = var2fpos(&argvars[0], TRUE, &fnum);
11922 	if (fnum != -1)
11923 	    list_append_number(l, (varnumber_T)fnum);
11924 	else
11925 	    list_append_number(l, (varnumber_T)0);
11926 	list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11927 							    : (varnumber_T)0);
11928 	list_append_number(l, (fp != NULL)
11929 		     ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11930 							    : (varnumber_T)0);
11931 	list_append_number(l,
11932 #ifdef FEAT_VIRTUALEDIT
11933 				(fp != NULL) ? (varnumber_T)fp->coladd :
11934 #endif
11935 							      (varnumber_T)0);
11936 	if (getcurpos)
11937 	    list_append_number(l, (varnumber_T)curwin->w_curswant + 1);
11938     }
11939     else
11940 	rettv->vval.v_number = FALSE;
11941 }
11942 
11943 /*
11944  * "getqflist()" and "getloclist()" functions
11945  */
11946     static void
11947 f_getqflist(argvars, rettv)
11948     typval_T	*argvars UNUSED;
11949     typval_T	*rettv UNUSED;
11950 {
11951 #ifdef FEAT_QUICKFIX
11952     win_T	*wp;
11953 #endif
11954 
11955 #ifdef FEAT_QUICKFIX
11956     if (rettv_list_alloc(rettv) == OK)
11957     {
11958 	wp = NULL;
11959 	if (argvars[0].v_type != VAR_UNKNOWN)	/* getloclist() */
11960 	{
11961 	    wp = find_win_by_nr(&argvars[0], NULL);
11962 	    if (wp == NULL)
11963 		return;
11964 	}
11965 
11966 	(void)get_errorlist(wp, rettv->vval.v_list);
11967     }
11968 #endif
11969 }
11970 
11971 /*
11972  * "getreg()" function
11973  */
11974     static void
11975 f_getreg(argvars, rettv)
11976     typval_T	*argvars;
11977     typval_T	*rettv;
11978 {
11979     char_u	*strregname;
11980     int		regname;
11981     int		arg2 = FALSE;
11982     int		return_list = FALSE;
11983     int		error = FALSE;
11984 
11985     if (argvars[0].v_type != VAR_UNKNOWN)
11986     {
11987 	strregname = get_tv_string_chk(&argvars[0]);
11988 	error = strregname == NULL;
11989 	if (argvars[1].v_type != VAR_UNKNOWN)
11990 	{
11991 	    arg2 = get_tv_number_chk(&argvars[1], &error);
11992 	    if (!error && argvars[2].v_type != VAR_UNKNOWN)
11993 		return_list = get_tv_number_chk(&argvars[2], &error);
11994 	}
11995     }
11996     else
11997 	strregname = vimvars[VV_REG].vv_str;
11998 
11999     if (error)
12000 	return;
12001 
12002     regname = (strregname == NULL ? '"' : *strregname);
12003     if (regname == 0)
12004 	regname = '"';
12005 
12006     if (return_list)
12007     {
12008 	rettv->v_type = VAR_LIST;
12009 	rettv->vval.v_list = (list_T *)get_reg_contents(regname,
12010 				      (arg2 ? GREG_EXPR_SRC : 0) | GREG_LIST);
12011     }
12012     else
12013     {
12014 	rettv->v_type = VAR_STRING;
12015 	rettv->vval.v_string = get_reg_contents(regname,
12016 						    arg2 ? GREG_EXPR_SRC : 0);
12017     }
12018 }
12019 
12020 /*
12021  * "getregtype()" function
12022  */
12023     static void
12024 f_getregtype(argvars, rettv)
12025     typval_T	*argvars;
12026     typval_T	*rettv;
12027 {
12028     char_u	*strregname;
12029     int		regname;
12030     char_u	buf[NUMBUFLEN + 2];
12031     long	reglen = 0;
12032 
12033     if (argvars[0].v_type != VAR_UNKNOWN)
12034     {
12035 	strregname = get_tv_string_chk(&argvars[0]);
12036 	if (strregname == NULL)	    /* type error; errmsg already given */
12037 	{
12038 	    rettv->v_type = VAR_STRING;
12039 	    rettv->vval.v_string = NULL;
12040 	    return;
12041 	}
12042     }
12043     else
12044 	/* Default to v:register */
12045 	strregname = vimvars[VV_REG].vv_str;
12046 
12047     regname = (strregname == NULL ? '"' : *strregname);
12048     if (regname == 0)
12049 	regname = '"';
12050 
12051     buf[0] = NUL;
12052     buf[1] = NUL;
12053     switch (get_reg_type(regname, &reglen))
12054     {
12055 	case MLINE: buf[0] = 'V'; break;
12056 	case MCHAR: buf[0] = 'v'; break;
12057 	case MBLOCK:
12058 		buf[0] = Ctrl_V;
12059 		sprintf((char *)buf + 1, "%ld", reglen + 1);
12060 		break;
12061     }
12062     rettv->v_type = VAR_STRING;
12063     rettv->vval.v_string = vim_strsave(buf);
12064 }
12065 
12066 /*
12067  * "gettabvar()" function
12068  */
12069     static void
12070 f_gettabvar(argvars, rettv)
12071     typval_T	*argvars;
12072     typval_T	*rettv;
12073 {
12074     win_T	*oldcurwin;
12075     tabpage_T	*tp, *oldtabpage;
12076     dictitem_T	*v;
12077     char_u	*varname;
12078     int		done = FALSE;
12079 
12080     rettv->v_type = VAR_STRING;
12081     rettv->vval.v_string = NULL;
12082 
12083     varname = get_tv_string_chk(&argvars[1]);
12084     tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
12085     if (tp != NULL && varname != NULL)
12086     {
12087 	/* Set tp to be our tabpage, temporarily.  Also set the window to the
12088 	 * first window in the tabpage, otherwise the window is not valid. */
12089 	if (switch_win(&oldcurwin, &oldtabpage, tp->tp_firstwin, tp, TRUE)
12090 									== OK)
12091 	{
12092 	    /* look up the variable */
12093 	    /* Let gettabvar({nr}, "") return the "t:" dictionary. */
12094 	    v = find_var_in_ht(&tp->tp_vars->dv_hashtab, 't', varname, FALSE);
12095 	    if (v != NULL)
12096 	    {
12097 		copy_tv(&v->di_tv, rettv);
12098 		done = TRUE;
12099 	    }
12100 	}
12101 
12102 	/* restore previous notion of curwin */
12103 	restore_win(oldcurwin, oldtabpage, TRUE);
12104     }
12105 
12106     if (!done && argvars[2].v_type != VAR_UNKNOWN)
12107 	copy_tv(&argvars[2], rettv);
12108 }
12109 
12110 /*
12111  * "gettabwinvar()" function
12112  */
12113     static void
12114 f_gettabwinvar(argvars, rettv)
12115     typval_T	*argvars;
12116     typval_T	*rettv;
12117 {
12118     getwinvar(argvars, rettv, 1);
12119 }
12120 
12121 /*
12122  * "getwinposx()" function
12123  */
12124     static void
12125 f_getwinposx(argvars, rettv)
12126     typval_T	*argvars UNUSED;
12127     typval_T	*rettv;
12128 {
12129     rettv->vval.v_number = -1;
12130 #ifdef FEAT_GUI
12131     if (gui.in_use)
12132     {
12133 	int	    x, y;
12134 
12135 	if (gui_mch_get_winpos(&x, &y) == OK)
12136 	    rettv->vval.v_number = x;
12137     }
12138 #endif
12139 }
12140 
12141 /*
12142  * "getwinposy()" function
12143  */
12144     static void
12145 f_getwinposy(argvars, rettv)
12146     typval_T	*argvars UNUSED;
12147     typval_T	*rettv;
12148 {
12149     rettv->vval.v_number = -1;
12150 #ifdef FEAT_GUI
12151     if (gui.in_use)
12152     {
12153 	int	    x, y;
12154 
12155 	if (gui_mch_get_winpos(&x, &y) == OK)
12156 	    rettv->vval.v_number = y;
12157     }
12158 #endif
12159 }
12160 
12161 /*
12162  * Find window specified by "vp" in tabpage "tp".
12163  */
12164     static win_T *
12165 find_win_by_nr(vp, tp)
12166     typval_T	*vp;
12167     tabpage_T	*tp UNUSED;	/* NULL for current tab page */
12168 {
12169 #ifdef FEAT_WINDOWS
12170     win_T	*wp;
12171 #endif
12172     int		nr;
12173 
12174     nr = get_tv_number_chk(vp, NULL);
12175 
12176 #ifdef FEAT_WINDOWS
12177     if (nr < 0)
12178 	return NULL;
12179     if (nr == 0)
12180 	return curwin;
12181 
12182     for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
12183 						  wp != NULL; wp = wp->w_next)
12184 	if (--nr <= 0)
12185 	    break;
12186     return wp;
12187 #else
12188     if (nr == 0 || nr == 1)
12189 	return curwin;
12190     return NULL;
12191 #endif
12192 }
12193 
12194 /*
12195  * "getwinvar()" function
12196  */
12197     static void
12198 f_getwinvar(argvars, rettv)
12199     typval_T	*argvars;
12200     typval_T	*rettv;
12201 {
12202     getwinvar(argvars, rettv, 0);
12203 }
12204 
12205 /*
12206  * getwinvar() and gettabwinvar()
12207  */
12208     static void
12209 getwinvar(argvars, rettv, off)
12210     typval_T	*argvars;
12211     typval_T	*rettv;
12212     int		off;	    /* 1 for gettabwinvar() */
12213 {
12214     win_T	*win, *oldcurwin;
12215     char_u	*varname;
12216     dictitem_T	*v;
12217     tabpage_T	*tp = NULL;
12218     tabpage_T	*oldtabpage;
12219     int		done = FALSE;
12220 
12221 #ifdef FEAT_WINDOWS
12222     if (off == 1)
12223 	tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
12224     else
12225 	tp = curtab;
12226 #endif
12227     win = find_win_by_nr(&argvars[off], tp);
12228     varname = get_tv_string_chk(&argvars[off + 1]);
12229     ++emsg_off;
12230 
12231     rettv->v_type = VAR_STRING;
12232     rettv->vval.v_string = NULL;
12233 
12234     if (win != NULL && varname != NULL)
12235     {
12236 	/* Set curwin to be our win, temporarily.  Also set the tabpage,
12237 	 * otherwise the window is not valid. */
12238 	if (switch_win(&oldcurwin, &oldtabpage, win, tp, TRUE) == OK)
12239 	{
12240 	    if (*varname == '&')	/* window-local-option */
12241 	    {
12242 		if (get_option_tv(&varname, rettv, 1) == OK)
12243 		    done = TRUE;
12244 	    }
12245 	    else
12246 	    {
12247 		/* Look up the variable. */
12248 		/* Let getwinvar({nr}, "") return the "w:" dictionary. */
12249 		v = find_var_in_ht(&win->w_vars->dv_hashtab, 'w',
12250 							      varname, FALSE);
12251 		if (v != NULL)
12252 		{
12253 		    copy_tv(&v->di_tv, rettv);
12254 		    done = TRUE;
12255 		}
12256 	    }
12257 	}
12258 
12259 	/* restore previous notion of curwin */
12260 	restore_win(oldcurwin, oldtabpage, TRUE);
12261     }
12262 
12263     if (!done && argvars[off + 2].v_type != VAR_UNKNOWN)
12264 	/* use the default return value */
12265 	copy_tv(&argvars[off + 2], rettv);
12266 
12267     --emsg_off;
12268 }
12269 
12270 /*
12271  * "glob()" function
12272  */
12273     static void
12274 f_glob(argvars, rettv)
12275     typval_T	*argvars;
12276     typval_T	*rettv;
12277 {
12278     int		options = WILD_SILENT|WILD_USE_NL;
12279     expand_T	xpc;
12280     int		error = FALSE;
12281 
12282     /* When the optional second argument is non-zero, don't remove matches
12283      * for 'wildignore' and don't put matches for 'suffixes' at the end. */
12284     rettv->v_type = VAR_STRING;
12285     if (argvars[1].v_type != VAR_UNKNOWN)
12286     {
12287 	if (get_tv_number_chk(&argvars[1], &error))
12288 	    options |= WILD_KEEP_ALL;
12289 	if (argvars[2].v_type != VAR_UNKNOWN
12290 				    && get_tv_number_chk(&argvars[2], &error))
12291 	{
12292 	    rettv->v_type = VAR_LIST;
12293 	    rettv->vval.v_list = NULL;
12294 	}
12295     }
12296     if (!error)
12297     {
12298 	ExpandInit(&xpc);
12299 	xpc.xp_context = EXPAND_FILES;
12300 	if (p_wic)
12301 	    options += WILD_ICASE;
12302 	if (rettv->v_type == VAR_STRING)
12303 	    rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
12304 						     NULL, options, WILD_ALL);
12305 	else if (rettv_list_alloc(rettv) != FAIL)
12306 	{
12307 	  int i;
12308 
12309 	  ExpandOne(&xpc, get_tv_string(&argvars[0]),
12310 						NULL, options, WILD_ALL_KEEP);
12311 	  for (i = 0; i < xpc.xp_numfiles; i++)
12312 	      list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
12313 
12314 	  ExpandCleanup(&xpc);
12315 	}
12316     }
12317     else
12318 	rettv->vval.v_string = NULL;
12319 }
12320 
12321 /*
12322  * "globpath()" function
12323  */
12324     static void
12325 f_globpath(argvars, rettv)
12326     typval_T	*argvars;
12327     typval_T	*rettv;
12328 {
12329     int		flags = 0;
12330     char_u	buf1[NUMBUFLEN];
12331     char_u	*file = get_tv_string_buf_chk(&argvars[1], buf1);
12332     int		error = FALSE;
12333     garray_T	ga;
12334     int		i;
12335 
12336     /* When the optional second argument is non-zero, don't remove matches
12337     * for 'wildignore' and don't put matches for 'suffixes' at the end. */
12338     rettv->v_type = VAR_STRING;
12339     if (argvars[2].v_type != VAR_UNKNOWN)
12340     {
12341 	if (get_tv_number_chk(&argvars[2], &error))
12342 	    flags |= WILD_KEEP_ALL;
12343 	if (argvars[3].v_type != VAR_UNKNOWN
12344 				    && get_tv_number_chk(&argvars[3], &error))
12345 	{
12346 	    rettv->v_type = VAR_LIST;
12347 	    rettv->vval.v_list = NULL;
12348 	}
12349     }
12350     if (file != NULL && !error)
12351     {
12352 	ga_init2(&ga, (int)sizeof(char_u *), 10);
12353 	globpath(get_tv_string(&argvars[0]), file, &ga, flags);
12354 	if (rettv->v_type == VAR_STRING)
12355 	    rettv->vval.v_string = ga_concat_strings(&ga, "\n");
12356 	else if (rettv_list_alloc(rettv) != FAIL)
12357 	    for (i = 0; i < ga.ga_len; ++i)
12358 		list_append_string(rettv->vval.v_list,
12359 					    ((char_u **)(ga.ga_data))[i], -1);
12360 	ga_clear_strings(&ga);
12361     }
12362     else
12363 	rettv->vval.v_string = NULL;
12364 }
12365 
12366 /*
12367  * "has()" function
12368  */
12369     static void
12370 f_has(argvars, rettv)
12371     typval_T	*argvars;
12372     typval_T	*rettv;
12373 {
12374     int		i;
12375     char_u	*name;
12376     int		n = FALSE;
12377     static char	*(has_list[]) =
12378     {
12379 #ifdef AMIGA
12380 	"amiga",
12381 # ifdef FEAT_ARP
12382 	"arp",
12383 # endif
12384 #endif
12385 #ifdef __BEOS__
12386 	"beos",
12387 #endif
12388 #ifdef MSDOS
12389 # ifdef DJGPP
12390 	"dos32",
12391 # else
12392 	"dos16",
12393 # endif
12394 #endif
12395 #ifdef MACOS
12396 	"mac",
12397 #endif
12398 #if defined(MACOS_X_UNIX)
12399 	"macunix",
12400 #endif
12401 #ifdef OS2
12402 	"os2",
12403 #endif
12404 #ifdef __QNX__
12405 	"qnx",
12406 #endif
12407 #ifdef UNIX
12408 	"unix",
12409 #endif
12410 #ifdef VMS
12411 	"vms",
12412 #endif
12413 #ifdef WIN16
12414 	"win16",
12415 #endif
12416 #ifdef WIN32
12417 	"win32",
12418 #endif
12419 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
12420 	"win32unix",
12421 #endif
12422 #if defined(WIN64) || defined(_WIN64)
12423 	"win64",
12424 #endif
12425 #ifdef EBCDIC
12426 	"ebcdic",
12427 #endif
12428 #ifndef CASE_INSENSITIVE_FILENAME
12429 	"fname_case",
12430 #endif
12431 #ifdef HAVE_ACL
12432 	"acl",
12433 #endif
12434 #ifdef FEAT_ARABIC
12435 	"arabic",
12436 #endif
12437 #ifdef FEAT_AUTOCMD
12438 	"autocmd",
12439 #endif
12440 #ifdef FEAT_BEVAL
12441 	"balloon_eval",
12442 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
12443 	"balloon_multiline",
12444 # endif
12445 #endif
12446 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
12447 	"builtin_terms",
12448 # ifdef ALL_BUILTIN_TCAPS
12449 	"all_builtin_terms",
12450 # endif
12451 #endif
12452 #if defined(FEAT_BROWSE) && (defined(USE_FILE_CHOOSER) \
12453 	|| defined(FEAT_GUI_W32) \
12454 	|| defined(FEAT_GUI_MOTIF))
12455 	"browsefilter",
12456 #endif
12457 #ifdef FEAT_BYTEOFF
12458 	"byte_offset",
12459 #endif
12460 #ifdef FEAT_CINDENT
12461 	"cindent",
12462 #endif
12463 #ifdef FEAT_CLIENTSERVER
12464 	"clientserver",
12465 #endif
12466 #ifdef FEAT_CLIPBOARD
12467 	"clipboard",
12468 #endif
12469 #ifdef FEAT_CMDL_COMPL
12470 	"cmdline_compl",
12471 #endif
12472 #ifdef FEAT_CMDHIST
12473 	"cmdline_hist",
12474 #endif
12475 #ifdef FEAT_COMMENTS
12476 	"comments",
12477 #endif
12478 #ifdef FEAT_CONCEAL
12479 	"conceal",
12480 #endif
12481 #ifdef FEAT_CRYPT
12482 	"cryptv",
12483 #endif
12484 #ifdef FEAT_CSCOPE
12485 	"cscope",
12486 #endif
12487 #ifdef FEAT_CURSORBIND
12488 	"cursorbind",
12489 #endif
12490 #ifdef CURSOR_SHAPE
12491 	"cursorshape",
12492 #endif
12493 #ifdef DEBUG
12494 	"debug",
12495 #endif
12496 #ifdef FEAT_CON_DIALOG
12497 	"dialog_con",
12498 #endif
12499 #ifdef FEAT_GUI_DIALOG
12500 	"dialog_gui",
12501 #endif
12502 #ifdef FEAT_DIFF
12503 	"diff",
12504 #endif
12505 #ifdef FEAT_DIGRAPHS
12506 	"digraphs",
12507 #endif
12508 #ifdef FEAT_DIRECTX
12509 	"directx",
12510 #endif
12511 #ifdef FEAT_DND
12512 	"dnd",
12513 #endif
12514 #ifdef FEAT_EMACS_TAGS
12515 	"emacs_tags",
12516 #endif
12517 	"eval",	    /* always present, of course! */
12518 #ifdef FEAT_EX_EXTRA
12519 	"ex_extra",
12520 #endif
12521 #ifdef FEAT_SEARCH_EXTRA
12522 	"extra_search",
12523 #endif
12524 #ifdef FEAT_FKMAP
12525 	"farsi",
12526 #endif
12527 #ifdef FEAT_SEARCHPATH
12528 	"file_in_path",
12529 #endif
12530 #ifdef FEAT_FILTERPIPE
12531 	"filterpipe",
12532 #endif
12533 #ifdef FEAT_FIND_ID
12534 	"find_in_path",
12535 #endif
12536 #ifdef FEAT_FLOAT
12537 	"float",
12538 #endif
12539 #ifdef FEAT_FOLDING
12540 	"folding",
12541 #endif
12542 #ifdef FEAT_FOOTER
12543 	"footer",
12544 #endif
12545 #if !defined(USE_SYSTEM) && defined(UNIX)
12546 	"fork",
12547 #endif
12548 #ifdef FEAT_GETTEXT
12549 	"gettext",
12550 #endif
12551 #ifdef FEAT_GUI
12552 	"gui",
12553 #endif
12554 #ifdef FEAT_GUI_ATHENA
12555 # ifdef FEAT_GUI_NEXTAW
12556 	"gui_neXtaw",
12557 # else
12558 	"gui_athena",
12559 # endif
12560 #endif
12561 #ifdef FEAT_GUI_GTK
12562 	"gui_gtk",
12563 	"gui_gtk2",
12564 #endif
12565 #ifdef FEAT_GUI_GNOME
12566 	"gui_gnome",
12567 #endif
12568 #ifdef FEAT_GUI_MAC
12569 	"gui_mac",
12570 #endif
12571 #ifdef FEAT_GUI_MOTIF
12572 	"gui_motif",
12573 #endif
12574 #ifdef FEAT_GUI_PHOTON
12575 	"gui_photon",
12576 #endif
12577 #ifdef FEAT_GUI_W16
12578 	"gui_win16",
12579 #endif
12580 #ifdef FEAT_GUI_W32
12581 	"gui_win32",
12582 #endif
12583 #ifdef FEAT_HANGULIN
12584 	"hangul_input",
12585 #endif
12586 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
12587 	"iconv",
12588 #endif
12589 #ifdef FEAT_INS_EXPAND
12590 	"insert_expand",
12591 #endif
12592 #ifdef FEAT_JUMPLIST
12593 	"jumplist",
12594 #endif
12595 #ifdef FEAT_KEYMAP
12596 	"keymap",
12597 #endif
12598 #ifdef FEAT_LANGMAP
12599 	"langmap",
12600 #endif
12601 #ifdef FEAT_LIBCALL
12602 	"libcall",
12603 #endif
12604 #ifdef FEAT_LINEBREAK
12605 	"linebreak",
12606 #endif
12607 #ifdef FEAT_LISP
12608 	"lispindent",
12609 #endif
12610 #ifdef FEAT_LISTCMDS
12611 	"listcmds",
12612 #endif
12613 #ifdef FEAT_LOCALMAP
12614 	"localmap",
12615 #endif
12616 #ifdef FEAT_LUA
12617 # ifndef DYNAMIC_LUA
12618 	"lua",
12619 # endif
12620 #endif
12621 #ifdef FEAT_MENU
12622 	"menu",
12623 #endif
12624 #ifdef FEAT_SESSION
12625 	"mksession",
12626 #endif
12627 #ifdef FEAT_MODIFY_FNAME
12628 	"modify_fname",
12629 #endif
12630 #ifdef FEAT_MOUSE
12631 	"mouse",
12632 #endif
12633 #ifdef FEAT_MOUSESHAPE
12634 	"mouseshape",
12635 #endif
12636 #if defined(UNIX) || defined(VMS)
12637 # ifdef FEAT_MOUSE_DEC
12638 	"mouse_dec",
12639 # endif
12640 # ifdef FEAT_MOUSE_GPM
12641 	"mouse_gpm",
12642 # endif
12643 # ifdef FEAT_MOUSE_JSB
12644 	"mouse_jsbterm",
12645 # endif
12646 # ifdef FEAT_MOUSE_NET
12647 	"mouse_netterm",
12648 # endif
12649 # ifdef FEAT_MOUSE_PTERM
12650 	"mouse_pterm",
12651 # endif
12652 # ifdef FEAT_MOUSE_SGR
12653 	"mouse_sgr",
12654 # endif
12655 # ifdef FEAT_SYSMOUSE
12656 	"mouse_sysmouse",
12657 # endif
12658 # ifdef FEAT_MOUSE_URXVT
12659 	"mouse_urxvt",
12660 # endif
12661 # ifdef FEAT_MOUSE_XTERM
12662 	"mouse_xterm",
12663 # endif
12664 #endif
12665 #ifdef FEAT_MBYTE
12666 	"multi_byte",
12667 #endif
12668 #ifdef FEAT_MBYTE_IME
12669 	"multi_byte_ime",
12670 #endif
12671 #ifdef FEAT_MULTI_LANG
12672 	"multi_lang",
12673 #endif
12674 #ifdef FEAT_MZSCHEME
12675 #ifndef DYNAMIC_MZSCHEME
12676 	"mzscheme",
12677 #endif
12678 #endif
12679 #ifdef FEAT_OLE
12680 	"ole",
12681 #endif
12682 #ifdef FEAT_PATH_EXTRA
12683 	"path_extra",
12684 #endif
12685 #ifdef FEAT_PERL
12686 #ifndef DYNAMIC_PERL
12687 	"perl",
12688 #endif
12689 #endif
12690 #ifdef FEAT_PERSISTENT_UNDO
12691 	"persistent_undo",
12692 #endif
12693 #ifdef FEAT_PYTHON
12694 #ifndef DYNAMIC_PYTHON
12695 	"python",
12696 #endif
12697 #endif
12698 #ifdef FEAT_PYTHON3
12699 #ifndef DYNAMIC_PYTHON3
12700 	"python3",
12701 #endif
12702 #endif
12703 #ifdef FEAT_POSTSCRIPT
12704 	"postscript",
12705 #endif
12706 #ifdef FEAT_PRINTER
12707 	"printer",
12708 #endif
12709 #ifdef FEAT_PROFILE
12710 	"profile",
12711 #endif
12712 #ifdef FEAT_RELTIME
12713 	"reltime",
12714 #endif
12715 #ifdef FEAT_QUICKFIX
12716 	"quickfix",
12717 #endif
12718 #ifdef FEAT_RIGHTLEFT
12719 	"rightleft",
12720 #endif
12721 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
12722 	"ruby",
12723 #endif
12724 #ifdef FEAT_SCROLLBIND
12725 	"scrollbind",
12726 #endif
12727 #ifdef FEAT_CMDL_INFO
12728 	"showcmd",
12729 	"cmdline_info",
12730 #endif
12731 #ifdef FEAT_SIGNS
12732 	"signs",
12733 #endif
12734 #ifdef FEAT_SMARTINDENT
12735 	"smartindent",
12736 #endif
12737 #ifdef FEAT_SNIFF
12738 	"sniff",
12739 #endif
12740 #ifdef STARTUPTIME
12741 	"startuptime",
12742 #endif
12743 #ifdef FEAT_STL_OPT
12744 	"statusline",
12745 #endif
12746 #ifdef FEAT_SUN_WORKSHOP
12747 	"sun_workshop",
12748 #endif
12749 #ifdef FEAT_NETBEANS_INTG
12750 	"netbeans_intg",
12751 #endif
12752 #ifdef FEAT_SPELL
12753 	"spell",
12754 #endif
12755 #ifdef FEAT_SYN_HL
12756 	"syntax",
12757 #endif
12758 #if defined(USE_SYSTEM) || !defined(UNIX)
12759 	"system",
12760 #endif
12761 #ifdef FEAT_TAG_BINS
12762 	"tag_binary",
12763 #endif
12764 #ifdef FEAT_TAG_OLDSTATIC
12765 	"tag_old_static",
12766 #endif
12767 #ifdef FEAT_TAG_ANYWHITE
12768 	"tag_any_white",
12769 #endif
12770 #ifdef FEAT_TCL
12771 # ifndef DYNAMIC_TCL
12772 	"tcl",
12773 # endif
12774 #endif
12775 #ifdef TERMINFO
12776 	"terminfo",
12777 #endif
12778 #ifdef FEAT_TERMRESPONSE
12779 	"termresponse",
12780 #endif
12781 #ifdef FEAT_TEXTOBJ
12782 	"textobjects",
12783 #endif
12784 #ifdef HAVE_TGETENT
12785 	"tgetent",
12786 #endif
12787 #ifdef FEAT_TITLE
12788 	"title",
12789 #endif
12790 #ifdef FEAT_TOOLBAR
12791 	"toolbar",
12792 #endif
12793 #if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
12794 	"unnamedplus",
12795 #endif
12796 #ifdef FEAT_USR_CMDS
12797 	"user-commands",    /* was accidentally included in 5.4 */
12798 	"user_commands",
12799 #endif
12800 #ifdef FEAT_VIMINFO
12801 	"viminfo",
12802 #endif
12803 #ifdef FEAT_VERTSPLIT
12804 	"vertsplit",
12805 #endif
12806 #ifdef FEAT_VIRTUALEDIT
12807 	"virtualedit",
12808 #endif
12809 	"visual",
12810 #ifdef FEAT_VISUALEXTRA
12811 	"visualextra",
12812 #endif
12813 #ifdef FEAT_VREPLACE
12814 	"vreplace",
12815 #endif
12816 #ifdef FEAT_WILDIGN
12817 	"wildignore",
12818 #endif
12819 #ifdef FEAT_WILDMENU
12820 	"wildmenu",
12821 #endif
12822 #ifdef FEAT_WINDOWS
12823 	"windows",
12824 #endif
12825 #ifdef FEAT_WAK
12826 	"winaltkeys",
12827 #endif
12828 #ifdef FEAT_WRITEBACKUP
12829 	"writebackup",
12830 #endif
12831 #ifdef FEAT_XIM
12832 	"xim",
12833 #endif
12834 #ifdef FEAT_XFONTSET
12835 	"xfontset",
12836 #endif
12837 #ifdef FEAT_XPM_W32
12838 	"xpm",
12839 	"xpm_w32",	/* for backward compatibility */
12840 #else
12841 # if defined(HAVE_XPM)
12842 	"xpm",
12843 # endif
12844 #endif
12845 #ifdef USE_XSMP
12846 	"xsmp",
12847 #endif
12848 #ifdef USE_XSMP_INTERACT
12849 	"xsmp_interact",
12850 #endif
12851 #ifdef FEAT_XCLIPBOARD
12852 	"xterm_clipboard",
12853 #endif
12854 #ifdef FEAT_XTERM_SAVE
12855 	"xterm_save",
12856 #endif
12857 #if defined(UNIX) && defined(FEAT_X11)
12858 	"X11",
12859 #endif
12860 	NULL
12861     };
12862 
12863     name = get_tv_string(&argvars[0]);
12864     for (i = 0; has_list[i] != NULL; ++i)
12865 	if (STRICMP(name, has_list[i]) == 0)
12866 	{
12867 	    n = TRUE;
12868 	    break;
12869 	}
12870 
12871     if (n == FALSE)
12872     {
12873 	if (STRNICMP(name, "patch", 5) == 0)
12874 	{
12875 	    if (name[5] == '-'
12876 		    && STRLEN(name) > 11
12877 		    && vim_isdigit(name[6])
12878 		    && vim_isdigit(name[8])
12879 		    && vim_isdigit(name[10]))
12880 	    {
12881 		int major = atoi((char *)name + 6);
12882 		int minor = atoi((char *)name + 8);
12883 
12884 		/* Expect "patch-9.9.01234". */
12885 		n = (major < VIM_VERSION_MAJOR
12886 		     || (major == VIM_VERSION_MAJOR
12887 			 && (minor < VIM_VERSION_MINOR
12888 			     || (minor == VIM_VERSION_MINOR
12889 				 && has_patch(atoi((char *)name + 10))))));
12890 	    }
12891 	    else
12892 		n = has_patch(atoi((char *)name + 5));
12893 	}
12894 	else if (STRICMP(name, "vim_starting") == 0)
12895 	    n = (starting != 0);
12896 #ifdef FEAT_MBYTE
12897 	else if (STRICMP(name, "multi_byte_encoding") == 0)
12898 	    n = has_mbyte;
12899 #endif
12900 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
12901 	else if (STRICMP(name, "balloon_multiline") == 0)
12902 	    n = multiline_balloon_available();
12903 #endif
12904 #ifdef DYNAMIC_TCL
12905 	else if (STRICMP(name, "tcl") == 0)
12906 	    n = tcl_enabled(FALSE);
12907 #endif
12908 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
12909 	else if (STRICMP(name, "iconv") == 0)
12910 	    n = iconv_enabled(FALSE);
12911 #endif
12912 #ifdef DYNAMIC_LUA
12913 	else if (STRICMP(name, "lua") == 0)
12914 	    n = lua_enabled(FALSE);
12915 #endif
12916 #ifdef DYNAMIC_MZSCHEME
12917 	else if (STRICMP(name, "mzscheme") == 0)
12918 	    n = mzscheme_enabled(FALSE);
12919 #endif
12920 #ifdef DYNAMIC_RUBY
12921 	else if (STRICMP(name, "ruby") == 0)
12922 	    n = ruby_enabled(FALSE);
12923 #endif
12924 #ifdef FEAT_PYTHON
12925 #ifdef DYNAMIC_PYTHON
12926 	else if (STRICMP(name, "python") == 0)
12927 	    n = python_enabled(FALSE);
12928 #endif
12929 #endif
12930 #ifdef FEAT_PYTHON3
12931 #ifdef DYNAMIC_PYTHON3
12932 	else if (STRICMP(name, "python3") == 0)
12933 	    n = python3_enabled(FALSE);
12934 #endif
12935 #endif
12936 #ifdef DYNAMIC_PERL
12937 	else if (STRICMP(name, "perl") == 0)
12938 	    n = perl_enabled(FALSE);
12939 #endif
12940 #ifdef FEAT_GUI
12941 	else if (STRICMP(name, "gui_running") == 0)
12942 	    n = (gui.in_use || gui.starting);
12943 # ifdef FEAT_GUI_W32
12944 	else if (STRICMP(name, "gui_win32s") == 0)
12945 	    n = gui_is_win32s();
12946 # endif
12947 # ifdef FEAT_BROWSE
12948 	else if (STRICMP(name, "browse") == 0)
12949 	    n = gui.in_use;	/* gui_mch_browse() works when GUI is running */
12950 # endif
12951 #endif
12952 #ifdef FEAT_SYN_HL
12953 	else if (STRICMP(name, "syntax_items") == 0)
12954 	    n = syntax_present(curwin);
12955 #endif
12956 #if defined(WIN3264)
12957 	else if (STRICMP(name, "win95") == 0)
12958 	    n = mch_windows95();
12959 #endif
12960 #ifdef FEAT_NETBEANS_INTG
12961 	else if (STRICMP(name, "netbeans_enabled") == 0)
12962 	    n = netbeans_active();
12963 #endif
12964     }
12965 
12966     rettv->vval.v_number = n;
12967 }
12968 
12969 /*
12970  * "has_key()" function
12971  */
12972     static void
12973 f_has_key(argvars, rettv)
12974     typval_T	*argvars;
12975     typval_T	*rettv;
12976 {
12977     if (argvars[0].v_type != VAR_DICT)
12978     {
12979 	EMSG(_(e_dictreq));
12980 	return;
12981     }
12982     if (argvars[0].vval.v_dict == NULL)
12983 	return;
12984 
12985     rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
12986 				      get_tv_string(&argvars[1]), -1) != NULL;
12987 }
12988 
12989 /*
12990  * "haslocaldir()" function
12991  */
12992     static void
12993 f_haslocaldir(argvars, rettv)
12994     typval_T	*argvars UNUSED;
12995     typval_T	*rettv;
12996 {
12997     rettv->vval.v_number = (curwin->w_localdir != NULL);
12998 }
12999 
13000 /*
13001  * "hasmapto()" function
13002  */
13003     static void
13004 f_hasmapto(argvars, rettv)
13005     typval_T	*argvars;
13006     typval_T	*rettv;
13007 {
13008     char_u	*name;
13009     char_u	*mode;
13010     char_u	buf[NUMBUFLEN];
13011     int		abbr = FALSE;
13012 
13013     name = get_tv_string(&argvars[0]);
13014     if (argvars[1].v_type == VAR_UNKNOWN)
13015 	mode = (char_u *)"nvo";
13016     else
13017     {
13018 	mode = get_tv_string_buf(&argvars[1], buf);
13019 	if (argvars[2].v_type != VAR_UNKNOWN)
13020 	    abbr = get_tv_number(&argvars[2]);
13021     }
13022 
13023     if (map_to_exists(name, mode, abbr))
13024 	rettv->vval.v_number = TRUE;
13025     else
13026 	rettv->vval.v_number = FALSE;
13027 }
13028 
13029 /*
13030  * "histadd()" function
13031  */
13032     static void
13033 f_histadd(argvars, rettv)
13034     typval_T	*argvars UNUSED;
13035     typval_T	*rettv;
13036 {
13037 #ifdef FEAT_CMDHIST
13038     int		histype;
13039     char_u	*str;
13040     char_u	buf[NUMBUFLEN];
13041 #endif
13042 
13043     rettv->vval.v_number = FALSE;
13044     if (check_restricted() || check_secure())
13045 	return;
13046 #ifdef FEAT_CMDHIST
13047     str = get_tv_string_chk(&argvars[0]);	/* NULL on type error */
13048     histype = str != NULL ? get_histtype(str) : -1;
13049     if (histype >= 0)
13050     {
13051 	str = get_tv_string_buf(&argvars[1], buf);
13052 	if (*str != NUL)
13053 	{
13054 	    init_history();
13055 	    add_to_history(histype, str, FALSE, NUL);
13056 	    rettv->vval.v_number = TRUE;
13057 	    return;
13058 	}
13059     }
13060 #endif
13061 }
13062 
13063 /*
13064  * "histdel()" function
13065  */
13066     static void
13067 f_histdel(argvars, rettv)
13068     typval_T	*argvars UNUSED;
13069     typval_T	*rettv UNUSED;
13070 {
13071 #ifdef FEAT_CMDHIST
13072     int		n;
13073     char_u	buf[NUMBUFLEN];
13074     char_u	*str;
13075 
13076     str = get_tv_string_chk(&argvars[0]);	/* NULL on type error */
13077     if (str == NULL)
13078 	n = 0;
13079     else if (argvars[1].v_type == VAR_UNKNOWN)
13080 	/* only one argument: clear entire history */
13081 	n = clr_history(get_histtype(str));
13082     else if (argvars[1].v_type == VAR_NUMBER)
13083 	/* index given: remove that entry */
13084 	n = del_history_idx(get_histtype(str),
13085 					  (int)get_tv_number(&argvars[1]));
13086     else
13087 	/* string given: remove all matching entries */
13088 	n = del_history_entry(get_histtype(str),
13089 				      get_tv_string_buf(&argvars[1], buf));
13090     rettv->vval.v_number = n;
13091 #endif
13092 }
13093 
13094 /*
13095  * "histget()" function
13096  */
13097     static void
13098 f_histget(argvars, rettv)
13099     typval_T	*argvars UNUSED;
13100     typval_T	*rettv;
13101 {
13102 #ifdef FEAT_CMDHIST
13103     int		type;
13104     int		idx;
13105     char_u	*str;
13106 
13107     str = get_tv_string_chk(&argvars[0]);	/* NULL on type error */
13108     if (str == NULL)
13109 	rettv->vval.v_string = NULL;
13110     else
13111     {
13112 	type = get_histtype(str);
13113 	if (argvars[1].v_type == VAR_UNKNOWN)
13114 	    idx = get_history_idx(type);
13115 	else
13116 	    idx = (int)get_tv_number_chk(&argvars[1], NULL);
13117 						    /* -1 on type error */
13118 	rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
13119     }
13120 #else
13121     rettv->vval.v_string = NULL;
13122 #endif
13123     rettv->v_type = VAR_STRING;
13124 }
13125 
13126 /*
13127  * "histnr()" function
13128  */
13129     static void
13130 f_histnr(argvars, rettv)
13131     typval_T	*argvars UNUSED;
13132     typval_T	*rettv;
13133 {
13134     int		i;
13135 
13136 #ifdef FEAT_CMDHIST
13137     char_u	*history = get_tv_string_chk(&argvars[0]);
13138 
13139     i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
13140     if (i >= HIST_CMD && i < HIST_COUNT)
13141 	i = get_history_idx(i);
13142     else
13143 #endif
13144 	i = -1;
13145     rettv->vval.v_number = i;
13146 }
13147 
13148 /*
13149  * "highlightID(name)" function
13150  */
13151     static void
13152 f_hlID(argvars, rettv)
13153     typval_T	*argvars;
13154     typval_T	*rettv;
13155 {
13156     rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
13157 }
13158 
13159 /*
13160  * "highlight_exists()" function
13161  */
13162     static void
13163 f_hlexists(argvars, rettv)
13164     typval_T	*argvars;
13165     typval_T	*rettv;
13166 {
13167     rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
13168 }
13169 
13170 /*
13171  * "hostname()" function
13172  */
13173     static void
13174 f_hostname(argvars, rettv)
13175     typval_T	*argvars UNUSED;
13176     typval_T	*rettv;
13177 {
13178     char_u hostname[256];
13179 
13180     mch_get_host_name(hostname, 256);
13181     rettv->v_type = VAR_STRING;
13182     rettv->vval.v_string = vim_strsave(hostname);
13183 }
13184 
13185 /*
13186  * iconv() function
13187  */
13188     static void
13189 f_iconv(argvars, rettv)
13190     typval_T	*argvars UNUSED;
13191     typval_T	*rettv;
13192 {
13193 #ifdef FEAT_MBYTE
13194     char_u	buf1[NUMBUFLEN];
13195     char_u	buf2[NUMBUFLEN];
13196     char_u	*from, *to, *str;
13197     vimconv_T	vimconv;
13198 #endif
13199 
13200     rettv->v_type = VAR_STRING;
13201     rettv->vval.v_string = NULL;
13202 
13203 #ifdef FEAT_MBYTE
13204     str = get_tv_string(&argvars[0]);
13205     from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
13206     to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
13207     vimconv.vc_type = CONV_NONE;
13208     convert_setup(&vimconv, from, to);
13209 
13210     /* If the encodings are equal, no conversion needed. */
13211     if (vimconv.vc_type == CONV_NONE)
13212 	rettv->vval.v_string = vim_strsave(str);
13213     else
13214 	rettv->vval.v_string = string_convert(&vimconv, str, NULL);
13215 
13216     convert_setup(&vimconv, NULL, NULL);
13217     vim_free(from);
13218     vim_free(to);
13219 #endif
13220 }
13221 
13222 /*
13223  * "indent()" function
13224  */
13225     static void
13226 f_indent(argvars, rettv)
13227     typval_T	*argvars;
13228     typval_T	*rettv;
13229 {
13230     linenr_T	lnum;
13231 
13232     lnum = get_tv_lnum(argvars);
13233     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
13234 	rettv->vval.v_number = get_indent_lnum(lnum);
13235     else
13236 	rettv->vval.v_number = -1;
13237 }
13238 
13239 /*
13240  * "index()" function
13241  */
13242     static void
13243 f_index(argvars, rettv)
13244     typval_T	*argvars;
13245     typval_T	*rettv;
13246 {
13247     list_T	*l;
13248     listitem_T	*item;
13249     long	idx = 0;
13250     int		ic = FALSE;
13251 
13252     rettv->vval.v_number = -1;
13253     if (argvars[0].v_type != VAR_LIST)
13254     {
13255 	EMSG(_(e_listreq));
13256 	return;
13257     }
13258     l = argvars[0].vval.v_list;
13259     if (l != NULL)
13260     {
13261 	item = l->lv_first;
13262 	if (argvars[2].v_type != VAR_UNKNOWN)
13263 	{
13264 	    int		error = FALSE;
13265 
13266 	    /* Start at specified item.  Use the cached index that list_find()
13267 	     * sets, so that a negative number also works. */
13268 	    item = list_find(l, get_tv_number_chk(&argvars[2], &error));
13269 	    idx = l->lv_idx;
13270 	    if (argvars[3].v_type != VAR_UNKNOWN)
13271 		ic = get_tv_number_chk(&argvars[3], &error);
13272 	    if (error)
13273 		item = NULL;
13274 	}
13275 
13276 	for ( ; item != NULL; item = item->li_next, ++idx)
13277 	    if (tv_equal(&item->li_tv, &argvars[1], ic, FALSE))
13278 	    {
13279 		rettv->vval.v_number = idx;
13280 		break;
13281 	    }
13282     }
13283 }
13284 
13285 static int inputsecret_flag = 0;
13286 
13287 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
13288 
13289 /*
13290  * This function is used by f_input() and f_inputdialog() functions. The third
13291  * argument to f_input() specifies the type of completion to use at the
13292  * prompt. The third argument to f_inputdialog() specifies the value to return
13293  * when the user cancels the prompt.
13294  */
13295     static void
13296 get_user_input(argvars, rettv, inputdialog)
13297     typval_T	*argvars;
13298     typval_T	*rettv;
13299     int		inputdialog;
13300 {
13301     char_u	*prompt = get_tv_string_chk(&argvars[0]);
13302     char_u	*p = NULL;
13303     int		c;
13304     char_u	buf[NUMBUFLEN];
13305     int		cmd_silent_save = cmd_silent;
13306     char_u	*defstr = (char_u *)"";
13307     int		xp_type = EXPAND_NOTHING;
13308     char_u	*xp_arg = NULL;
13309 
13310     rettv->v_type = VAR_STRING;
13311     rettv->vval.v_string = NULL;
13312 
13313 #ifdef NO_CONSOLE_INPUT
13314     /* While starting up, there is no place to enter text. */
13315     if (no_console_input())
13316 	return;
13317 #endif
13318 
13319     cmd_silent = FALSE;		/* Want to see the prompt. */
13320     if (prompt != NULL)
13321     {
13322 	/* Only the part of the message after the last NL is considered as
13323 	 * prompt for the command line */
13324 	p = vim_strrchr(prompt, '\n');
13325 	if (p == NULL)
13326 	    p = prompt;
13327 	else
13328 	{
13329 	    ++p;
13330 	    c = *p;
13331 	    *p = NUL;
13332 	    msg_start();
13333 	    msg_clr_eos();
13334 	    msg_puts_attr(prompt, echo_attr);
13335 	    msg_didout = FALSE;
13336 	    msg_starthere();
13337 	    *p = c;
13338 	}
13339 	cmdline_row = msg_row;
13340 
13341 	if (argvars[1].v_type != VAR_UNKNOWN)
13342 	{
13343 	    defstr = get_tv_string_buf_chk(&argvars[1], buf);
13344 	    if (defstr != NULL)
13345 		stuffReadbuffSpec(defstr);
13346 
13347 	    if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
13348 	    {
13349 		char_u	*xp_name;
13350 		int	xp_namelen;
13351 		long	argt;
13352 
13353 		/* input() with a third argument: completion */
13354 		rettv->vval.v_string = NULL;
13355 
13356 		xp_name = get_tv_string_buf_chk(&argvars[2], buf);
13357 		if (xp_name == NULL)
13358 		    return;
13359 
13360 		xp_namelen = (int)STRLEN(xp_name);
13361 
13362 		if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
13363 							     &xp_arg) == FAIL)
13364 		    return;
13365 	    }
13366 	}
13367 
13368 	if (defstr != NULL)
13369 	{
13370 # ifdef FEAT_EX_EXTRA
13371 	    int save_ex_normal_busy = ex_normal_busy;
13372 	    ex_normal_busy = 0;
13373 # endif
13374 	    rettv->vval.v_string =
13375 		getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
13376 				  xp_type, xp_arg);
13377 # ifdef FEAT_EX_EXTRA
13378 	    ex_normal_busy = save_ex_normal_busy;
13379 # endif
13380 	}
13381 	if (inputdialog && rettv->vval.v_string == NULL
13382 		&& argvars[1].v_type != VAR_UNKNOWN
13383 		&& argvars[2].v_type != VAR_UNKNOWN)
13384 	    rettv->vval.v_string = vim_strsave(get_tv_string_buf(
13385 							   &argvars[2], buf));
13386 
13387 	vim_free(xp_arg);
13388 
13389 	/* since the user typed this, no need to wait for return */
13390 	need_wait_return = FALSE;
13391 	msg_didout = FALSE;
13392     }
13393     cmd_silent = cmd_silent_save;
13394 }
13395 
13396 /*
13397  * "input()" function
13398  *     Also handles inputsecret() when inputsecret is set.
13399  */
13400     static void
13401 f_input(argvars, rettv)
13402     typval_T	*argvars;
13403     typval_T	*rettv;
13404 {
13405     get_user_input(argvars, rettv, FALSE);
13406 }
13407 
13408 /*
13409  * "inputdialog()" function
13410  */
13411     static void
13412 f_inputdialog(argvars, rettv)
13413     typval_T	*argvars;
13414     typval_T	*rettv;
13415 {
13416 #if defined(FEAT_GUI_TEXTDIALOG)
13417     /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
13418     if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
13419     {
13420 	char_u	*message;
13421 	char_u	buf[NUMBUFLEN];
13422 	char_u	*defstr = (char_u *)"";
13423 
13424 	message = get_tv_string_chk(&argvars[0]);
13425 	if (argvars[1].v_type != VAR_UNKNOWN
13426 		&& (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
13427 	    vim_strncpy(IObuff, defstr, IOSIZE - 1);
13428 	else
13429 	    IObuff[0] = NUL;
13430 	if (message != NULL && defstr != NULL
13431 		&& do_dialog(VIM_QUESTION, NULL, message,
13432 			  (char_u *)_("&OK\n&Cancel"), 1, IObuff, FALSE) == 1)
13433 	    rettv->vval.v_string = vim_strsave(IObuff);
13434 	else
13435 	{
13436 	    if (message != NULL && defstr != NULL
13437 					&& argvars[1].v_type != VAR_UNKNOWN
13438 					&& argvars[2].v_type != VAR_UNKNOWN)
13439 		rettv->vval.v_string = vim_strsave(
13440 				      get_tv_string_buf(&argvars[2], buf));
13441 	    else
13442 		rettv->vval.v_string = NULL;
13443 	}
13444 	rettv->v_type = VAR_STRING;
13445     }
13446     else
13447 #endif
13448 	get_user_input(argvars, rettv, TRUE);
13449 }
13450 
13451 /*
13452  * "inputlist()" function
13453  */
13454     static void
13455 f_inputlist(argvars, rettv)
13456     typval_T	*argvars;
13457     typval_T	*rettv;
13458 {
13459     listitem_T	*li;
13460     int		selected;
13461     int		mouse_used;
13462 
13463 #ifdef NO_CONSOLE_INPUT
13464     /* While starting up, there is no place to enter text. */
13465     if (no_console_input())
13466 	return;
13467 #endif
13468     if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
13469     {
13470 	EMSG2(_(e_listarg), "inputlist()");
13471 	return;
13472     }
13473 
13474     msg_start();
13475     msg_row = Rows - 1;	/* for when 'cmdheight' > 1 */
13476     lines_left = Rows;	/* avoid more prompt */
13477     msg_scroll = TRUE;
13478     msg_clr_eos();
13479 
13480     for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
13481     {
13482 	msg_puts(get_tv_string(&li->li_tv));
13483 	msg_putchar('\n');
13484     }
13485 
13486     /* Ask for choice. */
13487     selected = prompt_for_number(&mouse_used);
13488     if (mouse_used)
13489 	selected -= lines_left;
13490 
13491     rettv->vval.v_number = selected;
13492 }
13493 
13494 
13495 static garray_T	    ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
13496 
13497 /*
13498  * "inputrestore()" function
13499  */
13500     static void
13501 f_inputrestore(argvars, rettv)
13502     typval_T	*argvars UNUSED;
13503     typval_T	*rettv;
13504 {
13505     if (ga_userinput.ga_len > 0)
13506     {
13507 	--ga_userinput.ga_len;
13508 	restore_typeahead((tasave_T *)(ga_userinput.ga_data)
13509 						       + ga_userinput.ga_len);
13510 	/* default return is zero == OK */
13511     }
13512     else if (p_verbose > 1)
13513     {
13514 	verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
13515 	rettv->vval.v_number = 1; /* Failed */
13516     }
13517 }
13518 
13519 /*
13520  * "inputsave()" function
13521  */
13522     static void
13523 f_inputsave(argvars, rettv)
13524     typval_T	*argvars UNUSED;
13525     typval_T	*rettv;
13526 {
13527     /* Add an entry to the stack of typeahead storage. */
13528     if (ga_grow(&ga_userinput, 1) == OK)
13529     {
13530 	save_typeahead((tasave_T *)(ga_userinput.ga_data)
13531 						       + ga_userinput.ga_len);
13532 	++ga_userinput.ga_len;
13533 	/* default return is zero == OK */
13534     }
13535     else
13536 	rettv->vval.v_number = 1; /* Failed */
13537 }
13538 
13539 /*
13540  * "inputsecret()" function
13541  */
13542     static void
13543 f_inputsecret(argvars, rettv)
13544     typval_T	*argvars;
13545     typval_T	*rettv;
13546 {
13547     ++cmdline_star;
13548     ++inputsecret_flag;
13549     f_input(argvars, rettv);
13550     --cmdline_star;
13551     --inputsecret_flag;
13552 }
13553 
13554 /*
13555  * "insert()" function
13556  */
13557     static void
13558 f_insert(argvars, rettv)
13559     typval_T	*argvars;
13560     typval_T	*rettv;
13561 {
13562     long	before = 0;
13563     listitem_T	*item;
13564     list_T	*l;
13565     int		error = FALSE;
13566 
13567     if (argvars[0].v_type != VAR_LIST)
13568 	EMSG2(_(e_listarg), "insert()");
13569     else if ((l = argvars[0].vval.v_list) != NULL
13570 	    && !tv_check_lock(l->lv_lock, (char_u *)_("insert() argument")))
13571     {
13572 	if (argvars[2].v_type != VAR_UNKNOWN)
13573 	    before = get_tv_number_chk(&argvars[2], &error);
13574 	if (error)
13575 	    return;		/* type error; errmsg already given */
13576 
13577 	if (before == l->lv_len)
13578 	    item = NULL;
13579 	else
13580 	{
13581 	    item = list_find(l, before);
13582 	    if (item == NULL)
13583 	    {
13584 		EMSGN(_(e_listidx), before);
13585 		l = NULL;
13586 	    }
13587 	}
13588 	if (l != NULL)
13589 	{
13590 	    list_insert_tv(l, &argvars[1], item);
13591 	    copy_tv(&argvars[0], rettv);
13592 	}
13593     }
13594 }
13595 
13596 /*
13597  * "invert(expr)" function
13598  */
13599     static void
13600 f_invert(argvars, rettv)
13601     typval_T	*argvars;
13602     typval_T	*rettv;
13603 {
13604     rettv->vval.v_number = ~get_tv_number_chk(&argvars[0], NULL);
13605 }
13606 
13607 /*
13608  * "isdirectory()" function
13609  */
13610     static void
13611 f_isdirectory(argvars, rettv)
13612     typval_T	*argvars;
13613     typval_T	*rettv;
13614 {
13615     rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
13616 }
13617 
13618 /*
13619  * "islocked()" function
13620  */
13621     static void
13622 f_islocked(argvars, rettv)
13623     typval_T	*argvars;
13624     typval_T	*rettv;
13625 {
13626     lval_T	lv;
13627     char_u	*end;
13628     dictitem_T	*di;
13629 
13630     rettv->vval.v_number = -1;
13631     end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE,
13632 					GLV_NO_AUTOLOAD, FNE_CHECK_START);
13633     if (end != NULL && lv.ll_name != NULL)
13634     {
13635 	if (*end != NUL)
13636 	    EMSG(_(e_trailing));
13637 	else
13638 	{
13639 	    if (lv.ll_tv == NULL)
13640 	    {
13641 		if (check_changedtick(lv.ll_name))
13642 		    rettv->vval.v_number = 1;	    /* always locked */
13643 		else
13644 		{
13645 		    di = find_var(lv.ll_name, NULL, TRUE);
13646 		    if (di != NULL)
13647 		    {
13648 			/* Consider a variable locked when:
13649 			 * 1. the variable itself is locked
13650 			 * 2. the value of the variable is locked.
13651 			 * 3. the List or Dict value is locked.
13652 			 */
13653 			rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
13654 						  || tv_islocked(&di->di_tv));
13655 		    }
13656 		}
13657 	    }
13658 	    else if (lv.ll_range)
13659 		EMSG(_("E786: Range not allowed"));
13660 	    else if (lv.ll_newkey != NULL)
13661 		EMSG2(_(e_dictkey), lv.ll_newkey);
13662 	    else if (lv.ll_list != NULL)
13663 		/* List item. */
13664 		rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
13665 	    else
13666 		/* Dictionary item. */
13667 		rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
13668 	}
13669     }
13670 
13671     clear_lval(&lv);
13672 }
13673 
13674 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
13675 
13676 /*
13677  * Turn a dict into a list:
13678  * "what" == 0: list of keys
13679  * "what" == 1: list of values
13680  * "what" == 2: list of items
13681  */
13682     static void
13683 dict_list(argvars, rettv, what)
13684     typval_T	*argvars;
13685     typval_T	*rettv;
13686     int		what;
13687 {
13688     list_T	*l2;
13689     dictitem_T	*di;
13690     hashitem_T	*hi;
13691     listitem_T	*li;
13692     listitem_T	*li2;
13693     dict_T	*d;
13694     int		todo;
13695 
13696     if (argvars[0].v_type != VAR_DICT)
13697     {
13698 	EMSG(_(e_dictreq));
13699 	return;
13700     }
13701     if ((d = argvars[0].vval.v_dict) == NULL)
13702 	return;
13703 
13704     if (rettv_list_alloc(rettv) == FAIL)
13705 	return;
13706 
13707     todo = (int)d->dv_hashtab.ht_used;
13708     for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13709     {
13710 	if (!HASHITEM_EMPTY(hi))
13711 	{
13712 	    --todo;
13713 	    di = HI2DI(hi);
13714 
13715 	    li = listitem_alloc();
13716 	    if (li == NULL)
13717 		break;
13718 	    list_append(rettv->vval.v_list, li);
13719 
13720 	    if (what == 0)
13721 	    {
13722 		/* keys() */
13723 		li->li_tv.v_type = VAR_STRING;
13724 		li->li_tv.v_lock = 0;
13725 		li->li_tv.vval.v_string = vim_strsave(di->di_key);
13726 	    }
13727 	    else if (what == 1)
13728 	    {
13729 		/* values() */
13730 		copy_tv(&di->di_tv, &li->li_tv);
13731 	    }
13732 	    else
13733 	    {
13734 		/* items() */
13735 		l2 = list_alloc();
13736 		li->li_tv.v_type = VAR_LIST;
13737 		li->li_tv.v_lock = 0;
13738 		li->li_tv.vval.v_list = l2;
13739 		if (l2 == NULL)
13740 		    break;
13741 		++l2->lv_refcount;
13742 
13743 		li2 = listitem_alloc();
13744 		if (li2 == NULL)
13745 		    break;
13746 		list_append(l2, li2);
13747 		li2->li_tv.v_type = VAR_STRING;
13748 		li2->li_tv.v_lock = 0;
13749 		li2->li_tv.vval.v_string = vim_strsave(di->di_key);
13750 
13751 		li2 = listitem_alloc();
13752 		if (li2 == NULL)
13753 		    break;
13754 		list_append(l2, li2);
13755 		copy_tv(&di->di_tv, &li2->li_tv);
13756 	    }
13757 	}
13758     }
13759 }
13760 
13761 /*
13762  * "items(dict)" function
13763  */
13764     static void
13765 f_items(argvars, rettv)
13766     typval_T	*argvars;
13767     typval_T	*rettv;
13768 {
13769     dict_list(argvars, rettv, 2);
13770 }
13771 
13772 /*
13773  * "join()" function
13774  */
13775     static void
13776 f_join(argvars, rettv)
13777     typval_T	*argvars;
13778     typval_T	*rettv;
13779 {
13780     garray_T	ga;
13781     char_u	*sep;
13782 
13783     if (argvars[0].v_type != VAR_LIST)
13784     {
13785 	EMSG(_(e_listreq));
13786 	return;
13787     }
13788     if (argvars[0].vval.v_list == NULL)
13789 	return;
13790     if (argvars[1].v_type == VAR_UNKNOWN)
13791 	sep = (char_u *)" ";
13792     else
13793 	sep = get_tv_string_chk(&argvars[1]);
13794 
13795     rettv->v_type = VAR_STRING;
13796 
13797     if (sep != NULL)
13798     {
13799 	ga_init2(&ga, (int)sizeof(char), 80);
13800 	list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
13801 	ga_append(&ga, NUL);
13802 	rettv->vval.v_string = (char_u *)ga.ga_data;
13803     }
13804     else
13805 	rettv->vval.v_string = NULL;
13806 }
13807 
13808 /*
13809  * "keys()" function
13810  */
13811     static void
13812 f_keys(argvars, rettv)
13813     typval_T	*argvars;
13814     typval_T	*rettv;
13815 {
13816     dict_list(argvars, rettv, 0);
13817 }
13818 
13819 /*
13820  * "last_buffer_nr()" function.
13821  */
13822     static void
13823 f_last_buffer_nr(argvars, rettv)
13824     typval_T	*argvars UNUSED;
13825     typval_T	*rettv;
13826 {
13827     int		n = 0;
13828     buf_T	*buf;
13829 
13830     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
13831 	if (n < buf->b_fnum)
13832 	    n = buf->b_fnum;
13833 
13834     rettv->vval.v_number = n;
13835 }
13836 
13837 /*
13838  * "len()" function
13839  */
13840     static void
13841 f_len(argvars, rettv)
13842     typval_T	*argvars;
13843     typval_T	*rettv;
13844 {
13845     switch (argvars[0].v_type)
13846     {
13847 	case VAR_STRING:
13848 	case VAR_NUMBER:
13849 	    rettv->vval.v_number = (varnumber_T)STRLEN(
13850 					       get_tv_string(&argvars[0]));
13851 	    break;
13852 	case VAR_LIST:
13853 	    rettv->vval.v_number = list_len(argvars[0].vval.v_list);
13854 	    break;
13855 	case VAR_DICT:
13856 	    rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
13857 	    break;
13858 	default:
13859 	    EMSG(_("E701: Invalid type for len()"));
13860 	    break;
13861     }
13862 }
13863 
13864 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
13865 
13866     static void
13867 libcall_common(argvars, rettv, type)
13868     typval_T	*argvars;
13869     typval_T	*rettv;
13870     int		type;
13871 {
13872 #ifdef FEAT_LIBCALL
13873     char_u		*string_in;
13874     char_u		**string_result;
13875     int			nr_result;
13876 #endif
13877 
13878     rettv->v_type = type;
13879     if (type != VAR_NUMBER)
13880 	rettv->vval.v_string = NULL;
13881 
13882     if (check_restricted() || check_secure())
13883 	return;
13884 
13885 #ifdef FEAT_LIBCALL
13886     /* The first two args must be strings, otherwise its meaningless */
13887     if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
13888     {
13889 	string_in = NULL;
13890 	if (argvars[2].v_type == VAR_STRING)
13891 	    string_in = argvars[2].vval.v_string;
13892 	if (type == VAR_NUMBER)
13893 	    string_result = NULL;
13894 	else
13895 	    string_result = &rettv->vval.v_string;
13896 	if (mch_libcall(argvars[0].vval.v_string,
13897 			     argvars[1].vval.v_string,
13898 			     string_in,
13899 			     argvars[2].vval.v_number,
13900 			     string_result,
13901 			     &nr_result) == OK
13902 		&& type == VAR_NUMBER)
13903 	    rettv->vval.v_number = nr_result;
13904     }
13905 #endif
13906 }
13907 
13908 /*
13909  * "libcall()" function
13910  */
13911     static void
13912 f_libcall(argvars, rettv)
13913     typval_T	*argvars;
13914     typval_T	*rettv;
13915 {
13916     libcall_common(argvars, rettv, VAR_STRING);
13917 }
13918 
13919 /*
13920  * "libcallnr()" function
13921  */
13922     static void
13923 f_libcallnr(argvars, rettv)
13924     typval_T	*argvars;
13925     typval_T	*rettv;
13926 {
13927     libcall_common(argvars, rettv, VAR_NUMBER);
13928 }
13929 
13930 /*
13931  * "line(string)" function
13932  */
13933     static void
13934 f_line(argvars, rettv)
13935     typval_T	*argvars;
13936     typval_T	*rettv;
13937 {
13938     linenr_T	lnum = 0;
13939     pos_T	*fp;
13940     int		fnum;
13941 
13942     fp = var2fpos(&argvars[0], TRUE, &fnum);
13943     if (fp != NULL)
13944 	lnum = fp->lnum;
13945     rettv->vval.v_number = lnum;
13946 }
13947 
13948 /*
13949  * "line2byte(lnum)" function
13950  */
13951     static void
13952 f_line2byte(argvars, rettv)
13953     typval_T	*argvars UNUSED;
13954     typval_T	*rettv;
13955 {
13956 #ifndef FEAT_BYTEOFF
13957     rettv->vval.v_number = -1;
13958 #else
13959     linenr_T	lnum;
13960 
13961     lnum = get_tv_lnum(argvars);
13962     if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
13963 	rettv->vval.v_number = -1;
13964     else
13965 	rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
13966     if (rettv->vval.v_number >= 0)
13967 	++rettv->vval.v_number;
13968 #endif
13969 }
13970 
13971 /*
13972  * "lispindent(lnum)" function
13973  */
13974     static void
13975 f_lispindent(argvars, rettv)
13976     typval_T	*argvars UNUSED;
13977     typval_T	*rettv;
13978 {
13979 #ifdef FEAT_LISP
13980     pos_T	pos;
13981     linenr_T	lnum;
13982 
13983     pos = curwin->w_cursor;
13984     lnum = get_tv_lnum(argvars);
13985     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
13986     {
13987 	curwin->w_cursor.lnum = lnum;
13988 	rettv->vval.v_number = get_lisp_indent();
13989 	curwin->w_cursor = pos;
13990     }
13991     else
13992 #endif
13993 	rettv->vval.v_number = -1;
13994 }
13995 
13996 /*
13997  * "localtime()" function
13998  */
13999     static void
14000 f_localtime(argvars, rettv)
14001     typval_T	*argvars UNUSED;
14002     typval_T	*rettv;
14003 {
14004     rettv->vval.v_number = (varnumber_T)time(NULL);
14005 }
14006 
14007 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
14008 
14009     static void
14010 get_maparg(argvars, rettv, exact)
14011     typval_T	*argvars;
14012     typval_T	*rettv;
14013     int		exact;
14014 {
14015     char_u	*keys;
14016     char_u	*which;
14017     char_u	buf[NUMBUFLEN];
14018     char_u	*keys_buf = NULL;
14019     char_u	*rhs;
14020     int		mode;
14021     int		abbr = FALSE;
14022     int		get_dict = FALSE;
14023     mapblock_T	*mp;
14024     int		buffer_local;
14025 
14026     /* return empty string for failure */
14027     rettv->v_type = VAR_STRING;
14028     rettv->vval.v_string = NULL;
14029 
14030     keys = get_tv_string(&argvars[0]);
14031     if (*keys == NUL)
14032 	return;
14033 
14034     if (argvars[1].v_type != VAR_UNKNOWN)
14035     {
14036 	which = get_tv_string_buf_chk(&argvars[1], buf);
14037 	if (argvars[2].v_type != VAR_UNKNOWN)
14038 	{
14039 	    abbr = get_tv_number(&argvars[2]);
14040 	    if (argvars[3].v_type != VAR_UNKNOWN)
14041 		get_dict = get_tv_number(&argvars[3]);
14042 	}
14043     }
14044     else
14045 	which = (char_u *)"";
14046     if (which == NULL)
14047 	return;
14048 
14049     mode = get_map_mode(&which, 0);
14050 
14051     keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
14052     rhs = check_map(keys, mode, exact, FALSE, abbr, &mp, &buffer_local);
14053     vim_free(keys_buf);
14054 
14055     if (!get_dict)
14056     {
14057 	/* Return a string. */
14058 	if (rhs != NULL)
14059 	    rettv->vval.v_string = str2special_save(rhs, FALSE);
14060 
14061     }
14062     else if (rettv_dict_alloc(rettv) != FAIL && rhs != NULL)
14063     {
14064 	/* Return a dictionary. */
14065 	char_u	    *lhs = str2special_save(mp->m_keys, TRUE);
14066 	char_u	    *mapmode = map_mode_to_chars(mp->m_mode);
14067 	dict_T	    *dict = rettv->vval.v_dict;
14068 
14069 	dict_add_nr_str(dict, "lhs",	 0L, lhs);
14070 	dict_add_nr_str(dict, "rhs",     0L, mp->m_orig_str);
14071 	dict_add_nr_str(dict, "noremap", mp->m_noremap ? 1L : 0L , NULL);
14072 	dict_add_nr_str(dict, "expr",    mp->m_expr    ? 1L : 0L, NULL);
14073 	dict_add_nr_str(dict, "silent",  mp->m_silent  ? 1L : 0L, NULL);
14074 	dict_add_nr_str(dict, "sid",     (long)mp->m_script_ID, NULL);
14075 	dict_add_nr_str(dict, "buffer",  (long)buffer_local, NULL);
14076 	dict_add_nr_str(dict, "nowait",  mp->m_nowait  ? 1L : 0L, NULL);
14077 	dict_add_nr_str(dict, "mode",    0L, mapmode);
14078 
14079 	vim_free(lhs);
14080 	vim_free(mapmode);
14081     }
14082 }
14083 
14084 #ifdef FEAT_FLOAT
14085 /*
14086  * "log()" function
14087  */
14088     static void
14089 f_log(argvars, rettv)
14090     typval_T	*argvars;
14091     typval_T	*rettv;
14092 {
14093     float_T	f;
14094 
14095     rettv->v_type = VAR_FLOAT;
14096     if (get_float_arg(argvars, &f) == OK)
14097 	rettv->vval.v_float = log(f);
14098     else
14099 	rettv->vval.v_float = 0.0;
14100 }
14101 
14102 /*
14103  * "log10()" function
14104  */
14105     static void
14106 f_log10(argvars, rettv)
14107     typval_T	*argvars;
14108     typval_T	*rettv;
14109 {
14110     float_T	f;
14111 
14112     rettv->v_type = VAR_FLOAT;
14113     if (get_float_arg(argvars, &f) == OK)
14114 	rettv->vval.v_float = log10(f);
14115     else
14116 	rettv->vval.v_float = 0.0;
14117 }
14118 #endif
14119 
14120 #ifdef FEAT_LUA
14121 /*
14122  * "luaeval()" function
14123  */
14124     static void
14125 f_luaeval(argvars, rettv)
14126     typval_T	*argvars;
14127     typval_T	*rettv;
14128 {
14129     char_u	*str;
14130     char_u	buf[NUMBUFLEN];
14131 
14132     str = get_tv_string_buf(&argvars[0], buf);
14133     do_luaeval(str, argvars + 1, rettv);
14134 }
14135 #endif
14136 
14137 /*
14138  * "map()" function
14139  */
14140     static void
14141 f_map(argvars, rettv)
14142     typval_T	*argvars;
14143     typval_T	*rettv;
14144 {
14145     filter_map(argvars, rettv, TRUE);
14146 }
14147 
14148 /*
14149  * "maparg()" function
14150  */
14151     static void
14152 f_maparg(argvars, rettv)
14153     typval_T	*argvars;
14154     typval_T	*rettv;
14155 {
14156     get_maparg(argvars, rettv, TRUE);
14157 }
14158 
14159 /*
14160  * "mapcheck()" function
14161  */
14162     static void
14163 f_mapcheck(argvars, rettv)
14164     typval_T	*argvars;
14165     typval_T	*rettv;
14166 {
14167     get_maparg(argvars, rettv, FALSE);
14168 }
14169 
14170 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
14171 
14172     static void
14173 find_some_match(argvars, rettv, type)
14174     typval_T	*argvars;
14175     typval_T	*rettv;
14176     int		type;
14177 {
14178     char_u	*str = NULL;
14179     long	len = 0;
14180     char_u	*expr = NULL;
14181     char_u	*pat;
14182     regmatch_T	regmatch;
14183     char_u	patbuf[NUMBUFLEN];
14184     char_u	strbuf[NUMBUFLEN];
14185     char_u	*save_cpo;
14186     long	start = 0;
14187     long	nth = 1;
14188     colnr_T	startcol = 0;
14189     int		match = 0;
14190     list_T	*l = NULL;
14191     listitem_T	*li = NULL;
14192     long	idx = 0;
14193     char_u	*tofree = NULL;
14194 
14195     /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14196     save_cpo = p_cpo;
14197     p_cpo = (char_u *)"";
14198 
14199     rettv->vval.v_number = -1;
14200     if (type == 3)
14201     {
14202 	/* return empty list when there are no matches */
14203 	if (rettv_list_alloc(rettv) == FAIL)
14204 	    goto theend;
14205     }
14206     else if (type == 2)
14207     {
14208 	rettv->v_type = VAR_STRING;
14209 	rettv->vval.v_string = NULL;
14210     }
14211 
14212     if (argvars[0].v_type == VAR_LIST)
14213     {
14214 	if ((l = argvars[0].vval.v_list) == NULL)
14215 	    goto theend;
14216 	li = l->lv_first;
14217     }
14218     else
14219     {
14220 	expr = str = get_tv_string(&argvars[0]);
14221 	len = (long)STRLEN(str);
14222     }
14223 
14224     pat = get_tv_string_buf_chk(&argvars[1], patbuf);
14225     if (pat == NULL)
14226 	goto theend;
14227 
14228     if (argvars[2].v_type != VAR_UNKNOWN)
14229     {
14230 	int	    error = FALSE;
14231 
14232 	start = get_tv_number_chk(&argvars[2], &error);
14233 	if (error)
14234 	    goto theend;
14235 	if (l != NULL)
14236 	{
14237 	    li = list_find(l, start);
14238 	    if (li == NULL)
14239 		goto theend;
14240 	    idx = l->lv_idx;	/* use the cached index */
14241 	}
14242 	else
14243 	{
14244 	    if (start < 0)
14245 		start = 0;
14246 	    if (start > len)
14247 		goto theend;
14248 	    /* When "count" argument is there ignore matches before "start",
14249 	     * otherwise skip part of the string.  Differs when pattern is "^"
14250 	     * or "\<". */
14251 	    if (argvars[3].v_type != VAR_UNKNOWN)
14252 		startcol = start;
14253 	    else
14254 	    {
14255 		str += start;
14256 		len -= start;
14257 	    }
14258 	}
14259 
14260 	if (argvars[3].v_type != VAR_UNKNOWN)
14261 	    nth = get_tv_number_chk(&argvars[3], &error);
14262 	if (error)
14263 	    goto theend;
14264     }
14265 
14266     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
14267     if (regmatch.regprog != NULL)
14268     {
14269 	regmatch.rm_ic = p_ic;
14270 
14271 	for (;;)
14272 	{
14273 	    if (l != NULL)
14274 	    {
14275 		if (li == NULL)
14276 		{
14277 		    match = FALSE;
14278 		    break;
14279 		}
14280 		vim_free(tofree);
14281 		str = echo_string(&li->li_tv, &tofree, strbuf, 0);
14282 		if (str == NULL)
14283 		    break;
14284 	    }
14285 
14286 	    match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
14287 
14288 	    if (match && --nth <= 0)
14289 		break;
14290 	    if (l == NULL && !match)
14291 		break;
14292 
14293 	    /* Advance to just after the match. */
14294 	    if (l != NULL)
14295 	    {
14296 		li = li->li_next;
14297 		++idx;
14298 	    }
14299 	    else
14300 	    {
14301 #ifdef FEAT_MBYTE
14302 		startcol = (colnr_T)(regmatch.startp[0]
14303 				    + (*mb_ptr2len)(regmatch.startp[0]) - str);
14304 #else
14305 		startcol = (colnr_T)(regmatch.startp[0] + 1 - str);
14306 #endif
14307 		if (startcol > (colnr_T)len
14308 				      || str + startcol <= regmatch.startp[0])
14309 		{
14310 		    match = FALSE;
14311 		    break;
14312 		}
14313 	    }
14314 	}
14315 
14316 	if (match)
14317 	{
14318 	    if (type == 3)
14319 	    {
14320 		int i;
14321 
14322 		/* return list with matched string and submatches */
14323 		for (i = 0; i < NSUBEXP; ++i)
14324 		{
14325 		    if (regmatch.endp[i] == NULL)
14326 		    {
14327 			if (list_append_string(rettv->vval.v_list,
14328 						     (char_u *)"", 0) == FAIL)
14329 			    break;
14330 		    }
14331 		    else if (list_append_string(rettv->vval.v_list,
14332 				regmatch.startp[i],
14333 				(int)(regmatch.endp[i] - regmatch.startp[i]))
14334 			    == FAIL)
14335 			break;
14336 		}
14337 	    }
14338 	    else if (type == 2)
14339 	    {
14340 		/* return matched string */
14341 		if (l != NULL)
14342 		    copy_tv(&li->li_tv, rettv);
14343 		else
14344 		    rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
14345 				(int)(regmatch.endp[0] - regmatch.startp[0]));
14346 	    }
14347 	    else if (l != NULL)
14348 		rettv->vval.v_number = idx;
14349 	    else
14350 	    {
14351 		if (type != 0)
14352 		    rettv->vval.v_number =
14353 				      (varnumber_T)(regmatch.startp[0] - str);
14354 		else
14355 		    rettv->vval.v_number =
14356 					(varnumber_T)(regmatch.endp[0] - str);
14357 		rettv->vval.v_number += (varnumber_T)(str - expr);
14358 	    }
14359 	}
14360 	vim_regfree(regmatch.regprog);
14361     }
14362 
14363 theend:
14364     vim_free(tofree);
14365     p_cpo = save_cpo;
14366 }
14367 
14368 /*
14369  * "match()" function
14370  */
14371     static void
14372 f_match(argvars, rettv)
14373     typval_T	*argvars;
14374     typval_T	*rettv;
14375 {
14376     find_some_match(argvars, rettv, 1);
14377 }
14378 
14379 /*
14380  * "matchadd()" function
14381  */
14382     static void
14383 f_matchadd(argvars, rettv)
14384     typval_T	*argvars UNUSED;
14385     typval_T	*rettv UNUSED;
14386 {
14387 #ifdef FEAT_SEARCH_EXTRA
14388     char_u	buf[NUMBUFLEN];
14389     char_u	*grp = get_tv_string_buf_chk(&argvars[0], buf);	/* group */
14390     char_u	*pat = get_tv_string_buf_chk(&argvars[1], buf);	/* pattern */
14391     int		prio = 10;	/* default priority */
14392     int		id = -1;
14393     int		error = FALSE;
14394 
14395     rettv->vval.v_number = -1;
14396 
14397     if (grp == NULL || pat == NULL)
14398 	return;
14399     if (argvars[2].v_type != VAR_UNKNOWN)
14400     {
14401 	prio = get_tv_number_chk(&argvars[2], &error);
14402 	if (argvars[3].v_type != VAR_UNKNOWN)
14403 	    id = get_tv_number_chk(&argvars[3], &error);
14404     }
14405     if (error == TRUE)
14406 	return;
14407     if (id >= 1 && id <= 3)
14408     {
14409 	EMSGN("E798: ID is reserved for \":match\": %ld", id);
14410 	return;
14411     }
14412 
14413     rettv->vval.v_number = match_add(curwin, grp, pat, prio, id, NULL);
14414 #endif
14415 }
14416 
14417 /*
14418  * "matchaddpos()" function
14419  */
14420     static void
14421 f_matchaddpos(argvars, rettv)
14422     typval_T	*argvars UNUSED;
14423     typval_T	*rettv UNUSED;
14424 {
14425 #ifdef FEAT_SEARCH_EXTRA
14426     char_u	buf[NUMBUFLEN];
14427     char_u	*group;
14428     int		prio = 10;
14429     int		id = -1;
14430     int		error = FALSE;
14431     list_T	*l;
14432 
14433     rettv->vval.v_number = -1;
14434 
14435     group = get_tv_string_buf_chk(&argvars[0], buf);
14436     if (group == NULL)
14437 	return;
14438 
14439     if (argvars[1].v_type != VAR_LIST)
14440     {
14441 	EMSG2(_(e_listarg), "matchaddpos()");
14442 	return;
14443     }
14444     l = argvars[1].vval.v_list;
14445     if (l == NULL)
14446 	return;
14447 
14448     if (argvars[2].v_type != VAR_UNKNOWN)
14449     {
14450 	prio = get_tv_number_chk(&argvars[2], &error);
14451 	if (argvars[3].v_type != VAR_UNKNOWN)
14452 	    id = get_tv_number_chk(&argvars[3], &error);
14453     }
14454     if (error == TRUE)
14455 	return;
14456 
14457     /* id == 3 is ok because matchaddpos() is supposed to substitute :3match */
14458     if (id == 1 || id == 2)
14459     {
14460 	EMSGN("E798: ID is reserved for \":match\": %ld", id);
14461 	return;
14462     }
14463 
14464     rettv->vval.v_number = match_add(curwin, group, NULL, prio, id, l);
14465 #endif
14466 }
14467 
14468 /*
14469  * "matcharg()" function
14470  */
14471     static void
14472 f_matcharg(argvars, rettv)
14473     typval_T	*argvars UNUSED;
14474     typval_T	*rettv;
14475 {
14476     if (rettv_list_alloc(rettv) == OK)
14477     {
14478 #ifdef FEAT_SEARCH_EXTRA
14479 	int	    id = get_tv_number(&argvars[0]);
14480 	matchitem_T *m;
14481 
14482 	if (id >= 1 && id <= 3)
14483 	{
14484 	    if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
14485 	    {
14486 		list_append_string(rettv->vval.v_list,
14487 						syn_id2name(m->hlg_id), -1);
14488 		list_append_string(rettv->vval.v_list, m->pattern, -1);
14489 	    }
14490 	    else
14491 	    {
14492 		list_append_string(rettv->vval.v_list, NULL, -1);
14493 		list_append_string(rettv->vval.v_list, NULL, -1);
14494 	    }
14495 	}
14496 #endif
14497     }
14498 }
14499 
14500 /*
14501  * "matchdelete()" function
14502  */
14503     static void
14504 f_matchdelete(argvars, rettv)
14505     typval_T	*argvars UNUSED;
14506     typval_T	*rettv UNUSED;
14507 {
14508 #ifdef FEAT_SEARCH_EXTRA
14509     rettv->vval.v_number = match_delete(curwin,
14510 				       (int)get_tv_number(&argvars[0]), TRUE);
14511 #endif
14512 }
14513 
14514 /*
14515  * "matchend()" function
14516  */
14517     static void
14518 f_matchend(argvars, rettv)
14519     typval_T	*argvars;
14520     typval_T	*rettv;
14521 {
14522     find_some_match(argvars, rettv, 0);
14523 }
14524 
14525 /*
14526  * "matchlist()" function
14527  */
14528     static void
14529 f_matchlist(argvars, rettv)
14530     typval_T	*argvars;
14531     typval_T	*rettv;
14532 {
14533     find_some_match(argvars, rettv, 3);
14534 }
14535 
14536 /*
14537  * "matchstr()" function
14538  */
14539     static void
14540 f_matchstr(argvars, rettv)
14541     typval_T	*argvars;
14542     typval_T	*rettv;
14543 {
14544     find_some_match(argvars, rettv, 2);
14545 }
14546 
14547 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
14548 
14549     static void
14550 max_min(argvars, rettv, domax)
14551     typval_T	*argvars;
14552     typval_T	*rettv;
14553     int		domax;
14554 {
14555     long	n = 0;
14556     long	i;
14557     int		error = FALSE;
14558 
14559     if (argvars[0].v_type == VAR_LIST)
14560     {
14561 	list_T		*l;
14562 	listitem_T	*li;
14563 
14564 	l = argvars[0].vval.v_list;
14565 	if (l != NULL)
14566 	{
14567 	    li = l->lv_first;
14568 	    if (li != NULL)
14569 	    {
14570 		n = get_tv_number_chk(&li->li_tv, &error);
14571 		for (;;)
14572 		{
14573 		    li = li->li_next;
14574 		    if (li == NULL)
14575 			break;
14576 		    i = get_tv_number_chk(&li->li_tv, &error);
14577 		    if (domax ? i > n : i < n)
14578 			n = i;
14579 		}
14580 	    }
14581 	}
14582     }
14583     else if (argvars[0].v_type == VAR_DICT)
14584     {
14585 	dict_T		*d;
14586 	int		first = TRUE;
14587 	hashitem_T	*hi;
14588 	int		todo;
14589 
14590 	d = argvars[0].vval.v_dict;
14591 	if (d != NULL)
14592 	{
14593 	    todo = (int)d->dv_hashtab.ht_used;
14594 	    for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
14595 	    {
14596 		if (!HASHITEM_EMPTY(hi))
14597 		{
14598 		    --todo;
14599 		    i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
14600 		    if (first)
14601 		    {
14602 			n = i;
14603 			first = FALSE;
14604 		    }
14605 		    else if (domax ? i > n : i < n)
14606 			n = i;
14607 		}
14608 	    }
14609 	}
14610     }
14611     else
14612 	EMSG(_(e_listdictarg));
14613     rettv->vval.v_number = error ? 0 : n;
14614 }
14615 
14616 /*
14617  * "max()" function
14618  */
14619     static void
14620 f_max(argvars, rettv)
14621     typval_T	*argvars;
14622     typval_T	*rettv;
14623 {
14624     max_min(argvars, rettv, TRUE);
14625 }
14626 
14627 /*
14628  * "min()" function
14629  */
14630     static void
14631 f_min(argvars, rettv)
14632     typval_T	*argvars;
14633     typval_T	*rettv;
14634 {
14635     max_min(argvars, rettv, FALSE);
14636 }
14637 
14638 static int mkdir_recurse __ARGS((char_u *dir, int prot));
14639 
14640 /*
14641  * Create the directory in which "dir" is located, and higher levels when
14642  * needed.
14643  */
14644     static int
14645 mkdir_recurse(dir, prot)
14646     char_u	*dir;
14647     int		prot;
14648 {
14649     char_u	*p;
14650     char_u	*updir;
14651     int		r = FAIL;
14652 
14653     /* Get end of directory name in "dir".
14654      * We're done when it's "/" or "c:/". */
14655     p = gettail_sep(dir);
14656     if (p <= get_past_head(dir))
14657 	return OK;
14658 
14659     /* If the directory exists we're done.  Otherwise: create it.*/
14660     updir = vim_strnsave(dir, (int)(p - dir));
14661     if (updir == NULL)
14662 	return FAIL;
14663     if (mch_isdir(updir))
14664 	r = OK;
14665     else if (mkdir_recurse(updir, prot) == OK)
14666 	r = vim_mkdir_emsg(updir, prot);
14667     vim_free(updir);
14668     return r;
14669 }
14670 
14671 #ifdef vim_mkdir
14672 /*
14673  * "mkdir()" function
14674  */
14675     static void
14676 f_mkdir(argvars, rettv)
14677     typval_T	*argvars;
14678     typval_T	*rettv;
14679 {
14680     char_u	*dir;
14681     char_u	buf[NUMBUFLEN];
14682     int		prot = 0755;
14683 
14684     rettv->vval.v_number = FAIL;
14685     if (check_restricted() || check_secure())
14686 	return;
14687 
14688     dir = get_tv_string_buf(&argvars[0], buf);
14689     if (*dir == NUL)
14690 	rettv->vval.v_number = FAIL;
14691     else
14692     {
14693 	if (*gettail(dir) == NUL)
14694 	    /* remove trailing slashes */
14695 	    *gettail_sep(dir) = NUL;
14696 
14697 	if (argvars[1].v_type != VAR_UNKNOWN)
14698 	{
14699 	    if (argvars[2].v_type != VAR_UNKNOWN)
14700 		prot = get_tv_number_chk(&argvars[2], NULL);
14701 	    if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
14702 		mkdir_recurse(dir, prot);
14703 	}
14704 	rettv->vval.v_number = prot == -1 ? FAIL : vim_mkdir_emsg(dir, prot);
14705     }
14706 }
14707 #endif
14708 
14709 /*
14710  * "mode()" function
14711  */
14712     static void
14713 f_mode(argvars, rettv)
14714     typval_T	*argvars;
14715     typval_T	*rettv;
14716 {
14717     char_u	buf[3];
14718 
14719     buf[1] = NUL;
14720     buf[2] = NUL;
14721 
14722     if (VIsual_active)
14723     {
14724 	if (VIsual_select)
14725 	    buf[0] = VIsual_mode + 's' - 'v';
14726 	else
14727 	    buf[0] = VIsual_mode;
14728     }
14729     else if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
14730 		|| State == CONFIRM)
14731     {
14732 	buf[0] = 'r';
14733 	if (State == ASKMORE)
14734 	    buf[1] = 'm';
14735 	else if (State == CONFIRM)
14736 	    buf[1] = '?';
14737     }
14738     else if (State == EXTERNCMD)
14739 	buf[0] = '!';
14740     else if (State & INSERT)
14741     {
14742 #ifdef FEAT_VREPLACE
14743 	if (State & VREPLACE_FLAG)
14744 	{
14745 	    buf[0] = 'R';
14746 	    buf[1] = 'v';
14747 	}
14748 	else
14749 #endif
14750 	if (State & REPLACE_FLAG)
14751 	    buf[0] = 'R';
14752 	else
14753 	    buf[0] = 'i';
14754     }
14755     else if (State & CMDLINE)
14756     {
14757 	buf[0] = 'c';
14758 	if (exmode_active)
14759 	    buf[1] = 'v';
14760     }
14761     else if (exmode_active)
14762     {
14763 	buf[0] = 'c';
14764 	buf[1] = 'e';
14765     }
14766     else
14767     {
14768 	buf[0] = 'n';
14769 	if (finish_op)
14770 	    buf[1] = 'o';
14771     }
14772 
14773     /* Clear out the minor mode when the argument is not a non-zero number or
14774      * non-empty string.  */
14775     if (!non_zero_arg(&argvars[0]))
14776 	buf[1] = NUL;
14777 
14778     rettv->vval.v_string = vim_strsave(buf);
14779     rettv->v_type = VAR_STRING;
14780 }
14781 
14782 #if defined(FEAT_MZSCHEME) || defined(PROTO)
14783 /*
14784  * "mzeval()" function
14785  */
14786     static void
14787 f_mzeval(argvars, rettv)
14788     typval_T	*argvars;
14789     typval_T	*rettv;
14790 {
14791     char_u	*str;
14792     char_u	buf[NUMBUFLEN];
14793 
14794     str = get_tv_string_buf(&argvars[0], buf);
14795     do_mzeval(str, rettv);
14796 }
14797 
14798     void
14799 mzscheme_call_vim(name, args, rettv)
14800     char_u	*name;
14801     typval_T	*args;
14802     typval_T	*rettv;
14803 {
14804     typval_T argvars[3];
14805 
14806     argvars[0].v_type = VAR_STRING;
14807     argvars[0].vval.v_string = name;
14808     copy_tv(args, &argvars[1]);
14809     argvars[2].v_type = VAR_UNKNOWN;
14810     f_call(argvars, rettv);
14811     clear_tv(&argvars[1]);
14812 }
14813 #endif
14814 
14815 /*
14816  * "nextnonblank()" function
14817  */
14818     static void
14819 f_nextnonblank(argvars, rettv)
14820     typval_T	*argvars;
14821     typval_T	*rettv;
14822 {
14823     linenr_T	lnum;
14824 
14825     for (lnum = get_tv_lnum(argvars); ; ++lnum)
14826     {
14827 	if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
14828 	{
14829 	    lnum = 0;
14830 	    break;
14831 	}
14832 	if (*skipwhite(ml_get(lnum)) != NUL)
14833 	    break;
14834     }
14835     rettv->vval.v_number = lnum;
14836 }
14837 
14838 /*
14839  * "nr2char()" function
14840  */
14841     static void
14842 f_nr2char(argvars, rettv)
14843     typval_T	*argvars;
14844     typval_T	*rettv;
14845 {
14846     char_u	buf[NUMBUFLEN];
14847 
14848 #ifdef FEAT_MBYTE
14849     if (has_mbyte)
14850     {
14851 	int	utf8 = 0;
14852 
14853 	if (argvars[1].v_type != VAR_UNKNOWN)
14854 	    utf8 = get_tv_number_chk(&argvars[1], NULL);
14855 	if (utf8)
14856 	    buf[(*utf_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
14857 	else
14858 	    buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
14859     }
14860     else
14861 #endif
14862     {
14863 	buf[0] = (char_u)get_tv_number(&argvars[0]);
14864 	buf[1] = NUL;
14865     }
14866     rettv->v_type = VAR_STRING;
14867     rettv->vval.v_string = vim_strsave(buf);
14868 }
14869 
14870 /*
14871  * "or(expr, expr)" function
14872  */
14873     static void
14874 f_or(argvars, rettv)
14875     typval_T	*argvars;
14876     typval_T	*rettv;
14877 {
14878     rettv->vval.v_number = get_tv_number_chk(&argvars[0], NULL)
14879 					| get_tv_number_chk(&argvars[1], NULL);
14880 }
14881 
14882 /*
14883  * "pathshorten()" function
14884  */
14885     static void
14886 f_pathshorten(argvars, rettv)
14887     typval_T	*argvars;
14888     typval_T	*rettv;
14889 {
14890     char_u	*p;
14891 
14892     rettv->v_type = VAR_STRING;
14893     p = get_tv_string_chk(&argvars[0]);
14894     if (p == NULL)
14895 	rettv->vval.v_string = NULL;
14896     else
14897     {
14898 	p = vim_strsave(p);
14899 	rettv->vval.v_string = p;
14900 	if (p != NULL)
14901 	    shorten_dir(p);
14902     }
14903 }
14904 
14905 #ifdef FEAT_FLOAT
14906 /*
14907  * "pow()" function
14908  */
14909     static void
14910 f_pow(argvars, rettv)
14911     typval_T	*argvars;
14912     typval_T	*rettv;
14913 {
14914     float_T	fx, fy;
14915 
14916     rettv->v_type = VAR_FLOAT;
14917     if (get_float_arg(argvars, &fx) == OK
14918 				     && get_float_arg(&argvars[1], &fy) == OK)
14919 	rettv->vval.v_float = pow(fx, fy);
14920     else
14921 	rettv->vval.v_float = 0.0;
14922 }
14923 #endif
14924 
14925 /*
14926  * "prevnonblank()" function
14927  */
14928     static void
14929 f_prevnonblank(argvars, rettv)
14930     typval_T	*argvars;
14931     typval_T	*rettv;
14932 {
14933     linenr_T	lnum;
14934 
14935     lnum = get_tv_lnum(argvars);
14936     if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
14937 	lnum = 0;
14938     else
14939 	while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
14940 	    --lnum;
14941     rettv->vval.v_number = lnum;
14942 }
14943 
14944 #ifdef HAVE_STDARG_H
14945 /* This dummy va_list is here because:
14946  * - passing a NULL pointer doesn't work when va_list isn't a pointer
14947  * - locally in the function results in a "used before set" warning
14948  * - using va_start() to initialize it gives "function with fixed args" error */
14949 static va_list	ap;
14950 #endif
14951 
14952 /*
14953  * "printf()" function
14954  */
14955     static void
14956 f_printf(argvars, rettv)
14957     typval_T	*argvars;
14958     typval_T	*rettv;
14959 {
14960     rettv->v_type = VAR_STRING;
14961     rettv->vval.v_string = NULL;
14962 #ifdef HAVE_STDARG_H	    /* only very old compilers can't do this */
14963     {
14964 	char_u	buf[NUMBUFLEN];
14965 	int	len;
14966 	char_u	*s;
14967 	int	saved_did_emsg = did_emsg;
14968 	char	*fmt;
14969 
14970 	/* Get the required length, allocate the buffer and do it for real. */
14971 	did_emsg = FALSE;
14972 	fmt = (char *)get_tv_string_buf(&argvars[0], buf);
14973 	len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
14974 	if (!did_emsg)
14975 	{
14976 	    s = alloc(len + 1);
14977 	    if (s != NULL)
14978 	    {
14979 		rettv->vval.v_string = s;
14980 		(void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
14981 	    }
14982 	}
14983 	did_emsg |= saved_did_emsg;
14984     }
14985 #endif
14986 }
14987 
14988 /*
14989  * "pumvisible()" function
14990  */
14991     static void
14992 f_pumvisible(argvars, rettv)
14993     typval_T	*argvars UNUSED;
14994     typval_T	*rettv UNUSED;
14995 {
14996 #ifdef FEAT_INS_EXPAND
14997     if (pum_visible())
14998 	rettv->vval.v_number = 1;
14999 #endif
15000 }
15001 
15002 #ifdef FEAT_PYTHON3
15003 /*
15004  * "py3eval()" function
15005  */
15006     static void
15007 f_py3eval(argvars, rettv)
15008     typval_T	*argvars;
15009     typval_T	*rettv;
15010 {
15011     char_u	*str;
15012     char_u	buf[NUMBUFLEN];
15013 
15014     str = get_tv_string_buf(&argvars[0], buf);
15015     do_py3eval(str, rettv);
15016 }
15017 #endif
15018 
15019 #ifdef FEAT_PYTHON
15020 /*
15021  * "pyeval()" function
15022  */
15023     static void
15024 f_pyeval(argvars, rettv)
15025     typval_T	*argvars;
15026     typval_T	*rettv;
15027 {
15028     char_u	*str;
15029     char_u	buf[NUMBUFLEN];
15030 
15031     str = get_tv_string_buf(&argvars[0], buf);
15032     do_pyeval(str, rettv);
15033 }
15034 #endif
15035 
15036 /*
15037  * "range()" function
15038  */
15039     static void
15040 f_range(argvars, rettv)
15041     typval_T	*argvars;
15042     typval_T	*rettv;
15043 {
15044     long	start;
15045     long	end;
15046     long	stride = 1;
15047     long	i;
15048     int		error = FALSE;
15049 
15050     start = get_tv_number_chk(&argvars[0], &error);
15051     if (argvars[1].v_type == VAR_UNKNOWN)
15052     {
15053 	end = start - 1;
15054 	start = 0;
15055     }
15056     else
15057     {
15058 	end = get_tv_number_chk(&argvars[1], &error);
15059 	if (argvars[2].v_type != VAR_UNKNOWN)
15060 	    stride = get_tv_number_chk(&argvars[2], &error);
15061     }
15062 
15063     if (error)
15064 	return;		/* type error; errmsg already given */
15065     if (stride == 0)
15066 	EMSG(_("E726: Stride is zero"));
15067     else if (stride > 0 ? end + 1 < start : end - 1 > start)
15068 	EMSG(_("E727: Start past end"));
15069     else
15070     {
15071 	if (rettv_list_alloc(rettv) == OK)
15072 	    for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
15073 		if (list_append_number(rettv->vval.v_list,
15074 						      (varnumber_T)i) == FAIL)
15075 		    break;
15076     }
15077 }
15078 
15079 /*
15080  * "readfile()" function
15081  */
15082     static void
15083 f_readfile(argvars, rettv)
15084     typval_T	*argvars;
15085     typval_T	*rettv;
15086 {
15087     int		binary = FALSE;
15088     int		failed = FALSE;
15089     char_u	*fname;
15090     FILE	*fd;
15091     char_u	buf[(IOSIZE/256)*256];	/* rounded to avoid odd + 1 */
15092     int		io_size = sizeof(buf);
15093     int		readlen;		/* size of last fread() */
15094     char_u	*prev	 = NULL;	/* previously read bytes, if any */
15095     long	prevlen  = 0;		/* length of data in prev */
15096     long	prevsize = 0;		/* size of prev buffer */
15097     long	maxline  = MAXLNUM;
15098     long	cnt	 = 0;
15099     char_u	*p;			/* position in buf */
15100     char_u	*start;			/* start of current line */
15101 
15102     if (argvars[1].v_type != VAR_UNKNOWN)
15103     {
15104 	if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
15105 	    binary = TRUE;
15106 	if (argvars[2].v_type != VAR_UNKNOWN)
15107 	    maxline = get_tv_number(&argvars[2]);
15108     }
15109 
15110     if (rettv_list_alloc(rettv) == FAIL)
15111 	return;
15112 
15113     /* Always open the file in binary mode, library functions have a mind of
15114      * their own about CR-LF conversion. */
15115     fname = get_tv_string(&argvars[0]);
15116     if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
15117     {
15118 	EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
15119 	return;
15120     }
15121 
15122     while (cnt < maxline || maxline < 0)
15123     {
15124 	readlen = (int)fread(buf, 1, io_size, fd);
15125 
15126 	/* This for loop processes what was read, but is also entered at end
15127 	 * of file so that either:
15128 	 * - an incomplete line gets written
15129 	 * - a "binary" file gets an empty line at the end if it ends in a
15130 	 *   newline.  */
15131 	for (p = buf, start = buf;
15132 		p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
15133 		++p)
15134 	{
15135 	    if (*p == '\n' || readlen <= 0)
15136 	    {
15137 		listitem_T  *li;
15138 		char_u	    *s	= NULL;
15139 		long_u	    len = p - start;
15140 
15141 		/* Finished a line.  Remove CRs before NL. */
15142 		if (readlen > 0 && !binary)
15143 		{
15144 		    while (len > 0 && start[len - 1] == '\r')
15145 			--len;
15146 		    /* removal may cross back to the "prev" string */
15147 		    if (len == 0)
15148 			while (prevlen > 0 && prev[prevlen - 1] == '\r')
15149 			    --prevlen;
15150 		}
15151 		if (prevlen == 0)
15152 		    s = vim_strnsave(start, (int)len);
15153 		else
15154 		{
15155 		    /* Change "prev" buffer to be the right size.  This way
15156 		     * the bytes are only copied once, and very long lines are
15157 		     * allocated only once.  */
15158 		    if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
15159 		    {
15160 			mch_memmove(s + prevlen, start, len);
15161 			s[prevlen + len] = NUL;
15162 			prev = NULL; /* the list will own the string */
15163 			prevlen = prevsize = 0;
15164 		    }
15165 		}
15166 		if (s == NULL)
15167 		{
15168 		    do_outofmem_msg((long_u) prevlen + len + 1);
15169 		    failed = TRUE;
15170 		    break;
15171 		}
15172 
15173 		if ((li = listitem_alloc()) == NULL)
15174 		{
15175 		    vim_free(s);
15176 		    failed = TRUE;
15177 		    break;
15178 		}
15179 		li->li_tv.v_type = VAR_STRING;
15180 		li->li_tv.v_lock = 0;
15181 		li->li_tv.vval.v_string = s;
15182 		list_append(rettv->vval.v_list, li);
15183 
15184 		start = p + 1; /* step over newline */
15185 		if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
15186 		    break;
15187 	    }
15188 	    else if (*p == NUL)
15189 		*p = '\n';
15190 #ifdef FEAT_MBYTE
15191 	    /* Check for utf8 "bom"; U+FEFF is encoded as EF BB BF.  Do this
15192 	     * when finding the BF and check the previous two bytes. */
15193 	    else if (*p == 0xbf && enc_utf8 && !binary)
15194 	    {
15195 		/* Find the two bytes before the 0xbf.	If p is at buf, or buf
15196 		 * + 1, these may be in the "prev" string. */
15197 		char_u back1 = p >= buf + 1 ? p[-1]
15198 				     : prevlen >= 1 ? prev[prevlen - 1] : NUL;
15199 		char_u back2 = p >= buf + 2 ? p[-2]
15200 			  : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
15201 			  : prevlen >= 2 ? prev[prevlen - 2] : NUL;
15202 
15203 		if (back2 == 0xef && back1 == 0xbb)
15204 		{
15205 		    char_u *dest = p - 2;
15206 
15207 		    /* Usually a BOM is at the beginning of a file, and so at
15208 		     * the beginning of a line; then we can just step over it.
15209 		     */
15210 		    if (start == dest)
15211 			start = p + 1;
15212 		    else
15213 		    {
15214 			/* have to shuffle buf to close gap */
15215 			int adjust_prevlen = 0;
15216 
15217 			if (dest < buf)
15218 			{
15219 			    adjust_prevlen = (int)(buf - dest); /* must be 1 or 2 */
15220 			    dest = buf;
15221 			}
15222 			if (readlen > p - buf + 1)
15223 			    mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
15224 			readlen -= 3 - adjust_prevlen;
15225 			prevlen -= adjust_prevlen;
15226 			p = dest - 1;
15227 		    }
15228 		}
15229 	    }
15230 #endif
15231 	} /* for */
15232 
15233 	if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
15234 	    break;
15235 	if (start < p)
15236 	{
15237 	    /* There's part of a line in buf, store it in "prev". */
15238 	    if (p - start + prevlen >= prevsize)
15239 	    {
15240 		/* need bigger "prev" buffer */
15241 		char_u *newprev;
15242 
15243 		/* A common use case is ordinary text files and "prev" gets a
15244 		 * fragment of a line, so the first allocation is made
15245 		 * small, to avoid repeatedly 'allocing' large and
15246 		 * 'reallocing' small. */
15247 		if (prevsize == 0)
15248 		    prevsize = (long)(p - start);
15249 		else
15250 		{
15251 		    long grow50pc = (prevsize * 3) / 2;
15252 		    long growmin  = (long)((p - start) * 2 + prevlen);
15253 		    prevsize = grow50pc > growmin ? grow50pc : growmin;
15254 		}
15255 		newprev = prev == NULL ? alloc(prevsize)
15256 						: vim_realloc(prev, prevsize);
15257 		if (newprev == NULL)
15258 		{
15259 		    do_outofmem_msg((long_u)prevsize);
15260 		    failed = TRUE;
15261 		    break;
15262 		}
15263 		prev = newprev;
15264 	    }
15265 	    /* Add the line part to end of "prev". */
15266 	    mch_memmove(prev + prevlen, start, p - start);
15267 	    prevlen += (long)(p - start);
15268 	}
15269     } /* while */
15270 
15271     /*
15272      * For a negative line count use only the lines at the end of the file,
15273      * free the rest.
15274      */
15275     if (!failed && maxline < 0)
15276 	while (cnt > -maxline)
15277 	{
15278 	    listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
15279 	    --cnt;
15280 	}
15281 
15282     if (failed)
15283     {
15284 	list_free(rettv->vval.v_list, TRUE);
15285 	/* readfile doc says an empty list is returned on error */
15286 	rettv->vval.v_list = list_alloc();
15287     }
15288 
15289     vim_free(prev);
15290     fclose(fd);
15291 }
15292 
15293 #if defined(FEAT_RELTIME)
15294 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
15295 
15296 /*
15297  * Convert a List to proftime_T.
15298  * Return FAIL when there is something wrong.
15299  */
15300     static int
15301 list2proftime(arg, tm)
15302     typval_T	*arg;
15303     proftime_T  *tm;
15304 {
15305     long	n1, n2;
15306     int	error = FALSE;
15307 
15308     if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
15309 					     || arg->vval.v_list->lv_len != 2)
15310 	return FAIL;
15311     n1 = list_find_nr(arg->vval.v_list, 0L, &error);
15312     n2 = list_find_nr(arg->vval.v_list, 1L, &error);
15313 # ifdef WIN3264
15314     tm->HighPart = n1;
15315     tm->LowPart = n2;
15316 # else
15317     tm->tv_sec = n1;
15318     tm->tv_usec = n2;
15319 # endif
15320     return error ? FAIL : OK;
15321 }
15322 #endif /* FEAT_RELTIME */
15323 
15324 /*
15325  * "reltime()" function
15326  */
15327     static void
15328 f_reltime(argvars, rettv)
15329     typval_T	*argvars UNUSED;
15330     typval_T	*rettv UNUSED;
15331 {
15332 #ifdef FEAT_RELTIME
15333     proftime_T	res;
15334     proftime_T	start;
15335 
15336     if (argvars[0].v_type == VAR_UNKNOWN)
15337     {
15338 	/* No arguments: get current time. */
15339 	profile_start(&res);
15340     }
15341     else if (argvars[1].v_type == VAR_UNKNOWN)
15342     {
15343 	if (list2proftime(&argvars[0], &res) == FAIL)
15344 	    return;
15345 	profile_end(&res);
15346     }
15347     else
15348     {
15349 	/* Two arguments: compute the difference. */
15350 	if (list2proftime(&argvars[0], &start) == FAIL
15351 		|| list2proftime(&argvars[1], &res) == FAIL)
15352 	    return;
15353 	profile_sub(&res, &start);
15354     }
15355 
15356     if (rettv_list_alloc(rettv) == OK)
15357     {
15358 	long	n1, n2;
15359 
15360 # ifdef WIN3264
15361 	n1 = res.HighPart;
15362 	n2 = res.LowPart;
15363 # else
15364 	n1 = res.tv_sec;
15365 	n2 = res.tv_usec;
15366 # endif
15367 	list_append_number(rettv->vval.v_list, (varnumber_T)n1);
15368 	list_append_number(rettv->vval.v_list, (varnumber_T)n2);
15369     }
15370 #endif
15371 }
15372 
15373 /*
15374  * "reltimestr()" function
15375  */
15376     static void
15377 f_reltimestr(argvars, rettv)
15378     typval_T	*argvars UNUSED;
15379     typval_T	*rettv;
15380 {
15381 #ifdef FEAT_RELTIME
15382     proftime_T	tm;
15383 #endif
15384 
15385     rettv->v_type = VAR_STRING;
15386     rettv->vval.v_string = NULL;
15387 #ifdef FEAT_RELTIME
15388     if (list2proftime(&argvars[0], &tm) == OK)
15389 	rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
15390 #endif
15391 }
15392 
15393 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
15394 static void make_connection __ARGS((void));
15395 static int check_connection __ARGS((void));
15396 
15397     static void
15398 make_connection()
15399 {
15400     if (X_DISPLAY == NULL
15401 # ifdef FEAT_GUI
15402 	    && !gui.in_use
15403 # endif
15404 	    )
15405     {
15406 	x_force_connect = TRUE;
15407 	setup_term_clip();
15408 	x_force_connect = FALSE;
15409     }
15410 }
15411 
15412     static int
15413 check_connection()
15414 {
15415     make_connection();
15416     if (X_DISPLAY == NULL)
15417     {
15418 	EMSG(_("E240: No connection to Vim server"));
15419 	return FAIL;
15420     }
15421     return OK;
15422 }
15423 #endif
15424 
15425 #ifdef FEAT_CLIENTSERVER
15426 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
15427 
15428     static void
15429 remote_common(argvars, rettv, expr)
15430     typval_T	*argvars;
15431     typval_T	*rettv;
15432     int		expr;
15433 {
15434     char_u	*server_name;
15435     char_u	*keys;
15436     char_u	*r = NULL;
15437     char_u	buf[NUMBUFLEN];
15438 # ifdef WIN32
15439     HWND	w;
15440 # else
15441     Window	w;
15442 # endif
15443 
15444     if (check_restricted() || check_secure())
15445 	return;
15446 
15447 # ifdef FEAT_X11
15448     if (check_connection() == FAIL)
15449 	return;
15450 # endif
15451 
15452     server_name = get_tv_string_chk(&argvars[0]);
15453     if (server_name == NULL)
15454 	return;		/* type error; errmsg already given */
15455     keys = get_tv_string_buf(&argvars[1], buf);
15456 # ifdef WIN32
15457     if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
15458 # else
15459     if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
15460 									  < 0)
15461 # endif
15462     {
15463 	if (r != NULL)
15464 	    EMSG(r);		/* sending worked but evaluation failed */
15465 	else
15466 	    EMSG2(_("E241: Unable to send to %s"), server_name);
15467 	return;
15468     }
15469 
15470     rettv->vval.v_string = r;
15471 
15472     if (argvars[2].v_type != VAR_UNKNOWN)
15473     {
15474 	dictitem_T	v;
15475 	char_u		str[30];
15476 	char_u		*idvar;
15477 
15478 	sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
15479 	v.di_tv.v_type = VAR_STRING;
15480 	v.di_tv.vval.v_string = vim_strsave(str);
15481 	idvar = get_tv_string_chk(&argvars[2]);
15482 	if (idvar != NULL)
15483 	    set_var(idvar, &v.di_tv, FALSE);
15484 	vim_free(v.di_tv.vval.v_string);
15485     }
15486 }
15487 #endif
15488 
15489 /*
15490  * "remote_expr()" function
15491  */
15492     static void
15493 f_remote_expr(argvars, rettv)
15494     typval_T	*argvars UNUSED;
15495     typval_T	*rettv;
15496 {
15497     rettv->v_type = VAR_STRING;
15498     rettv->vval.v_string = NULL;
15499 #ifdef FEAT_CLIENTSERVER
15500     remote_common(argvars, rettv, TRUE);
15501 #endif
15502 }
15503 
15504 /*
15505  * "remote_foreground()" function
15506  */
15507     static void
15508 f_remote_foreground(argvars, rettv)
15509     typval_T	*argvars UNUSED;
15510     typval_T	*rettv UNUSED;
15511 {
15512 #ifdef FEAT_CLIENTSERVER
15513 # ifdef WIN32
15514     /* On Win32 it's done in this application. */
15515     {
15516 	char_u	*server_name = get_tv_string_chk(&argvars[0]);
15517 
15518 	if (server_name != NULL)
15519 	    serverForeground(server_name);
15520     }
15521 # else
15522     /* Send a foreground() expression to the server. */
15523     argvars[1].v_type = VAR_STRING;
15524     argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
15525     argvars[2].v_type = VAR_UNKNOWN;
15526     remote_common(argvars, rettv, TRUE);
15527     vim_free(argvars[1].vval.v_string);
15528 # endif
15529 #endif
15530 }
15531 
15532     static void
15533 f_remote_peek(argvars, rettv)
15534     typval_T	*argvars UNUSED;
15535     typval_T	*rettv;
15536 {
15537 #ifdef FEAT_CLIENTSERVER
15538     dictitem_T	v;
15539     char_u	*s = NULL;
15540 # ifdef WIN32
15541     long_u	n = 0;
15542 # endif
15543     char_u	*serverid;
15544 
15545     if (check_restricted() || check_secure())
15546     {
15547 	rettv->vval.v_number = -1;
15548 	return;
15549     }
15550     serverid = get_tv_string_chk(&argvars[0]);
15551     if (serverid == NULL)
15552     {
15553 	rettv->vval.v_number = -1;
15554 	return;		/* type error; errmsg already given */
15555     }
15556 # ifdef WIN32
15557     sscanf(serverid, SCANF_HEX_LONG_U, &n);
15558     if (n == 0)
15559 	rettv->vval.v_number = -1;
15560     else
15561     {
15562 	s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
15563 	rettv->vval.v_number = (s != NULL);
15564     }
15565 # else
15566     if (check_connection() == FAIL)
15567 	return;
15568 
15569     rettv->vval.v_number = serverPeekReply(X_DISPLAY,
15570 						serverStrToWin(serverid), &s);
15571 # endif
15572 
15573     if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
15574     {
15575 	char_u		*retvar;
15576 
15577 	v.di_tv.v_type = VAR_STRING;
15578 	v.di_tv.vval.v_string = vim_strsave(s);
15579 	retvar = get_tv_string_chk(&argvars[1]);
15580 	if (retvar != NULL)
15581 	    set_var(retvar, &v.di_tv, FALSE);
15582 	vim_free(v.di_tv.vval.v_string);
15583     }
15584 #else
15585     rettv->vval.v_number = -1;
15586 #endif
15587 }
15588 
15589     static void
15590 f_remote_read(argvars, rettv)
15591     typval_T	*argvars UNUSED;
15592     typval_T	*rettv;
15593 {
15594     char_u	*r = NULL;
15595 
15596 #ifdef FEAT_CLIENTSERVER
15597     char_u	*serverid = get_tv_string_chk(&argvars[0]);
15598 
15599     if (serverid != NULL && !check_restricted() && !check_secure())
15600     {
15601 # ifdef WIN32
15602 	/* The server's HWND is encoded in the 'id' parameter */
15603 	long_u		n = 0;
15604 
15605 	sscanf(serverid, SCANF_HEX_LONG_U, &n);
15606 	if (n != 0)
15607 	    r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
15608 	if (r == NULL)
15609 # else
15610 	if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
15611 		serverStrToWin(serverid), &r, FALSE) < 0)
15612 # endif
15613 	    EMSG(_("E277: Unable to read a server reply"));
15614     }
15615 #endif
15616     rettv->v_type = VAR_STRING;
15617     rettv->vval.v_string = r;
15618 }
15619 
15620 /*
15621  * "remote_send()" function
15622  */
15623     static void
15624 f_remote_send(argvars, rettv)
15625     typval_T	*argvars UNUSED;
15626     typval_T	*rettv;
15627 {
15628     rettv->v_type = VAR_STRING;
15629     rettv->vval.v_string = NULL;
15630 #ifdef FEAT_CLIENTSERVER
15631     remote_common(argvars, rettv, FALSE);
15632 #endif
15633 }
15634 
15635 /*
15636  * "remove()" function
15637  */
15638     static void
15639 f_remove(argvars, rettv)
15640     typval_T	*argvars;
15641     typval_T	*rettv;
15642 {
15643     list_T	*l;
15644     listitem_T	*item, *item2;
15645     listitem_T	*li;
15646     long	idx;
15647     long	end;
15648     char_u	*key;
15649     dict_T	*d;
15650     dictitem_T	*di;
15651     char	*arg_errmsg = N_("remove() argument");
15652 
15653     if (argvars[0].v_type == VAR_DICT)
15654     {
15655 	if (argvars[2].v_type != VAR_UNKNOWN)
15656 	    EMSG2(_(e_toomanyarg), "remove()");
15657 	else if ((d = argvars[0].vval.v_dict) != NULL
15658 		&& !tv_check_lock(d->dv_lock, (char_u *)_(arg_errmsg)))
15659 	{
15660 	    key = get_tv_string_chk(&argvars[1]);
15661 	    if (key != NULL)
15662 	    {
15663 		di = dict_find(d, key, -1);
15664 		if (di == NULL)
15665 		    EMSG2(_(e_dictkey), key);
15666 		else
15667 		{
15668 		    *rettv = di->di_tv;
15669 		    init_tv(&di->di_tv);
15670 		    dictitem_remove(d, di);
15671 		}
15672 	    }
15673 	}
15674     }
15675     else if (argvars[0].v_type != VAR_LIST)
15676 	EMSG2(_(e_listdictarg), "remove()");
15677     else if ((l = argvars[0].vval.v_list) != NULL
15678 	    && !tv_check_lock(l->lv_lock, (char_u *)_(arg_errmsg)))
15679     {
15680 	int	    error = FALSE;
15681 
15682 	idx = get_tv_number_chk(&argvars[1], &error);
15683 	if (error)
15684 	    ;		/* type error: do nothing, errmsg already given */
15685 	else if ((item = list_find(l, idx)) == NULL)
15686 	    EMSGN(_(e_listidx), idx);
15687 	else
15688 	{
15689 	    if (argvars[2].v_type == VAR_UNKNOWN)
15690 	    {
15691 		/* Remove one item, return its value. */
15692 		vimlist_remove(l, item, item);
15693 		*rettv = item->li_tv;
15694 		vim_free(item);
15695 	    }
15696 	    else
15697 	    {
15698 		/* Remove range of items, return list with values. */
15699 		end = get_tv_number_chk(&argvars[2], &error);
15700 		if (error)
15701 		    ;		/* type error: do nothing */
15702 		else if ((item2 = list_find(l, end)) == NULL)
15703 		    EMSGN(_(e_listidx), end);
15704 		else
15705 		{
15706 		    int	    cnt = 0;
15707 
15708 		    for (li = item; li != NULL; li = li->li_next)
15709 		    {
15710 			++cnt;
15711 			if (li == item2)
15712 			    break;
15713 		    }
15714 		    if (li == NULL)  /* didn't find "item2" after "item" */
15715 			EMSG(_(e_invrange));
15716 		    else
15717 		    {
15718 			vimlist_remove(l, item, item2);
15719 			if (rettv_list_alloc(rettv) == OK)
15720 			{
15721 			    l = rettv->vval.v_list;
15722 			    l->lv_first = item;
15723 			    l->lv_last = item2;
15724 			    item->li_prev = NULL;
15725 			    item2->li_next = NULL;
15726 			    l->lv_len = cnt;
15727 			}
15728 		    }
15729 		}
15730 	    }
15731 	}
15732     }
15733 }
15734 
15735 /*
15736  * "rename({from}, {to})" function
15737  */
15738     static void
15739 f_rename(argvars, rettv)
15740     typval_T	*argvars;
15741     typval_T	*rettv;
15742 {
15743     char_u	buf[NUMBUFLEN];
15744 
15745     if (check_restricted() || check_secure())
15746 	rettv->vval.v_number = -1;
15747     else
15748 	rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
15749 				      get_tv_string_buf(&argvars[1], buf));
15750 }
15751 
15752 /*
15753  * "repeat()" function
15754  */
15755     static void
15756 f_repeat(argvars, rettv)
15757     typval_T	*argvars;
15758     typval_T	*rettv;
15759 {
15760     char_u	*p;
15761     int		n;
15762     int		slen;
15763     int		len;
15764     char_u	*r;
15765     int		i;
15766 
15767     n = get_tv_number(&argvars[1]);
15768     if (argvars[0].v_type == VAR_LIST)
15769     {
15770 	if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
15771 	    while (n-- > 0)
15772 		if (list_extend(rettv->vval.v_list,
15773 					argvars[0].vval.v_list, NULL) == FAIL)
15774 		    break;
15775     }
15776     else
15777     {
15778 	p = get_tv_string(&argvars[0]);
15779 	rettv->v_type = VAR_STRING;
15780 	rettv->vval.v_string = NULL;
15781 
15782 	slen = (int)STRLEN(p);
15783 	len = slen * n;
15784 	if (len <= 0)
15785 	    return;
15786 
15787 	r = alloc(len + 1);
15788 	if (r != NULL)
15789 	{
15790 	    for (i = 0; i < n; i++)
15791 		mch_memmove(r + i * slen, p, (size_t)slen);
15792 	    r[len] = NUL;
15793 	}
15794 
15795 	rettv->vval.v_string = r;
15796     }
15797 }
15798 
15799 /*
15800  * "resolve()" function
15801  */
15802     static void
15803 f_resolve(argvars, rettv)
15804     typval_T	*argvars;
15805     typval_T	*rettv;
15806 {
15807     char_u	*p;
15808 #ifdef HAVE_READLINK
15809     char_u	*buf = NULL;
15810 #endif
15811 
15812     p = get_tv_string(&argvars[0]);
15813 #ifdef FEAT_SHORTCUT
15814     {
15815 	char_u	*v = NULL;
15816 
15817 	v = mch_resolve_shortcut(p);
15818 	if (v != NULL)
15819 	    rettv->vval.v_string = v;
15820 	else
15821 	    rettv->vval.v_string = vim_strsave(p);
15822     }
15823 #else
15824 # ifdef HAVE_READLINK
15825     {
15826 	char_u	*cpy;
15827 	int	len;
15828 	char_u	*remain = NULL;
15829 	char_u	*q;
15830 	int	is_relative_to_current = FALSE;
15831 	int	has_trailing_pathsep = FALSE;
15832 	int	limit = 100;
15833 
15834 	p = vim_strsave(p);
15835 
15836 	if (p[0] == '.' && (vim_ispathsep(p[1])
15837 				   || (p[1] == '.' && (vim_ispathsep(p[2])))))
15838 	    is_relative_to_current = TRUE;
15839 
15840 	len = STRLEN(p);
15841 	if (len > 0 && after_pathsep(p, p + len))
15842 	{
15843 	    has_trailing_pathsep = TRUE;
15844 	    p[len - 1] = NUL; /* the trailing slash breaks readlink() */
15845 	}
15846 
15847 	q = getnextcomp(p);
15848 	if (*q != NUL)
15849 	{
15850 	    /* Separate the first path component in "p", and keep the
15851 	     * remainder (beginning with the path separator). */
15852 	    remain = vim_strsave(q - 1);
15853 	    q[-1] = NUL;
15854 	}
15855 
15856 	buf = alloc(MAXPATHL + 1);
15857 	if (buf == NULL)
15858 	    goto fail;
15859 
15860 	for (;;)
15861 	{
15862 	    for (;;)
15863 	    {
15864 		len = readlink((char *)p, (char *)buf, MAXPATHL);
15865 		if (len <= 0)
15866 		    break;
15867 		buf[len] = NUL;
15868 
15869 		if (limit-- == 0)
15870 		{
15871 		    vim_free(p);
15872 		    vim_free(remain);
15873 		    EMSG(_("E655: Too many symbolic links (cycle?)"));
15874 		    rettv->vval.v_string = NULL;
15875 		    goto fail;
15876 		}
15877 
15878 		/* Ensure that the result will have a trailing path separator
15879 		 * if the argument has one. */
15880 		if (remain == NULL && has_trailing_pathsep)
15881 		    add_pathsep(buf);
15882 
15883 		/* Separate the first path component in the link value and
15884 		 * concatenate the remainders. */
15885 		q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
15886 		if (*q != NUL)
15887 		{
15888 		    if (remain == NULL)
15889 			remain = vim_strsave(q - 1);
15890 		    else
15891 		    {
15892 			cpy = concat_str(q - 1, remain);
15893 			if (cpy != NULL)
15894 			{
15895 			    vim_free(remain);
15896 			    remain = cpy;
15897 			}
15898 		    }
15899 		    q[-1] = NUL;
15900 		}
15901 
15902 		q = gettail(p);
15903 		if (q > p && *q == NUL)
15904 		{
15905 		    /* Ignore trailing path separator. */
15906 		    q[-1] = NUL;
15907 		    q = gettail(p);
15908 		}
15909 		if (q > p && !mch_isFullName(buf))
15910 		{
15911 		    /* symlink is relative to directory of argument */
15912 		    cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
15913 		    if (cpy != NULL)
15914 		    {
15915 			STRCPY(cpy, p);
15916 			STRCPY(gettail(cpy), buf);
15917 			vim_free(p);
15918 			p = cpy;
15919 		    }
15920 		}
15921 		else
15922 		{
15923 		    vim_free(p);
15924 		    p = vim_strsave(buf);
15925 		}
15926 	    }
15927 
15928 	    if (remain == NULL)
15929 		break;
15930 
15931 	    /* Append the first path component of "remain" to "p". */
15932 	    q = getnextcomp(remain + 1);
15933 	    len = q - remain - (*q != NUL);
15934 	    cpy = vim_strnsave(p, STRLEN(p) + len);
15935 	    if (cpy != NULL)
15936 	    {
15937 		STRNCAT(cpy, remain, len);
15938 		vim_free(p);
15939 		p = cpy;
15940 	    }
15941 	    /* Shorten "remain". */
15942 	    if (*q != NUL)
15943 		STRMOVE(remain, q - 1);
15944 	    else
15945 	    {
15946 		vim_free(remain);
15947 		remain = NULL;
15948 	    }
15949 	}
15950 
15951 	/* If the result is a relative path name, make it explicitly relative to
15952 	 * the current directory if and only if the argument had this form. */
15953 	if (!vim_ispathsep(*p))
15954 	{
15955 	    if (is_relative_to_current
15956 		    && *p != NUL
15957 		    && !(p[0] == '.'
15958 			&& (p[1] == NUL
15959 			    || vim_ispathsep(p[1])
15960 			    || (p[1] == '.'
15961 				&& (p[2] == NUL
15962 				    || vim_ispathsep(p[2]))))))
15963 	    {
15964 		/* Prepend "./". */
15965 		cpy = concat_str((char_u *)"./", p);
15966 		if (cpy != NULL)
15967 		{
15968 		    vim_free(p);
15969 		    p = cpy;
15970 		}
15971 	    }
15972 	    else if (!is_relative_to_current)
15973 	    {
15974 		/* Strip leading "./". */
15975 		q = p;
15976 		while (q[0] == '.' && vim_ispathsep(q[1]))
15977 		    q += 2;
15978 		if (q > p)
15979 		    STRMOVE(p, p + 2);
15980 	    }
15981 	}
15982 
15983 	/* Ensure that the result will have no trailing path separator
15984 	 * if the argument had none.  But keep "/" or "//". */
15985 	if (!has_trailing_pathsep)
15986 	{
15987 	    q = p + STRLEN(p);
15988 	    if (after_pathsep(p, q))
15989 		*gettail_sep(p) = NUL;
15990 	}
15991 
15992 	rettv->vval.v_string = p;
15993     }
15994 # else
15995     rettv->vval.v_string = vim_strsave(p);
15996 # endif
15997 #endif
15998 
15999     simplify_filename(rettv->vval.v_string);
16000 
16001 #ifdef HAVE_READLINK
16002 fail:
16003     vim_free(buf);
16004 #endif
16005     rettv->v_type = VAR_STRING;
16006 }
16007 
16008 /*
16009  * "reverse({list})" function
16010  */
16011     static void
16012 f_reverse(argvars, rettv)
16013     typval_T	*argvars;
16014     typval_T	*rettv;
16015 {
16016     list_T	*l;
16017     listitem_T	*li, *ni;
16018 
16019     if (argvars[0].v_type != VAR_LIST)
16020 	EMSG2(_(e_listarg), "reverse()");
16021     else if ((l = argvars[0].vval.v_list) != NULL
16022 	    && !tv_check_lock(l->lv_lock, (char_u *)_("reverse() argument")))
16023     {
16024 	li = l->lv_last;
16025 	l->lv_first = l->lv_last = NULL;
16026 	l->lv_len = 0;
16027 	while (li != NULL)
16028 	{
16029 	    ni = li->li_prev;
16030 	    list_append(l, li);
16031 	    li = ni;
16032 	}
16033 	rettv->vval.v_list = l;
16034 	rettv->v_type = VAR_LIST;
16035 	++l->lv_refcount;
16036 	l->lv_idx = l->lv_len - l->lv_idx - 1;
16037     }
16038 }
16039 
16040 #define SP_NOMOVE	0x01	    /* don't move cursor */
16041 #define SP_REPEAT	0x02	    /* repeat to find outer pair */
16042 #define SP_RETCOUNT	0x04	    /* return matchcount */
16043 #define SP_SETPCMARK	0x08	    /* set previous context mark */
16044 #define SP_START	0x10	    /* accept match at start position */
16045 #define SP_SUBPAT	0x20	    /* return nr of matching sub-pattern */
16046 #define SP_END		0x40	    /* leave cursor at end of match */
16047 
16048 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
16049 
16050 /*
16051  * Get flags for a search function.
16052  * Possibly sets "p_ws".
16053  * Returns BACKWARD, FORWARD or zero (for an error).
16054  */
16055     static int
16056 get_search_arg(varp, flagsp)
16057     typval_T	*varp;
16058     int		*flagsp;
16059 {
16060     int		dir = FORWARD;
16061     char_u	*flags;
16062     char_u	nbuf[NUMBUFLEN];
16063     int		mask;
16064 
16065     if (varp->v_type != VAR_UNKNOWN)
16066     {
16067 	flags = get_tv_string_buf_chk(varp, nbuf);
16068 	if (flags == NULL)
16069 	    return 0;		/* type error; errmsg already given */
16070 	while (*flags != NUL)
16071 	{
16072 	    switch (*flags)
16073 	    {
16074 		case 'b': dir = BACKWARD; break;
16075 		case 'w': p_ws = TRUE; break;
16076 		case 'W': p_ws = FALSE; break;
16077 		default:  mask = 0;
16078 			  if (flagsp != NULL)
16079 			     switch (*flags)
16080 			     {
16081 				 case 'c': mask = SP_START; break;
16082 				 case 'e': mask = SP_END; break;
16083 				 case 'm': mask = SP_RETCOUNT; break;
16084 				 case 'n': mask = SP_NOMOVE; break;
16085 				 case 'p': mask = SP_SUBPAT; break;
16086 				 case 'r': mask = SP_REPEAT; break;
16087 				 case 's': mask = SP_SETPCMARK; break;
16088 			     }
16089 			  if (mask == 0)
16090 			  {
16091 			      EMSG2(_(e_invarg2), flags);
16092 			      dir = 0;
16093 			  }
16094 			  else
16095 			      *flagsp |= mask;
16096 	    }
16097 	    if (dir == 0)
16098 		break;
16099 	    ++flags;
16100 	}
16101     }
16102     return dir;
16103 }
16104 
16105 /*
16106  * Shared by search() and searchpos() functions
16107  */
16108     static int
16109 search_cmn(argvars, match_pos, flagsp)
16110     typval_T	*argvars;
16111     pos_T	*match_pos;
16112     int		*flagsp;
16113 {
16114     int		flags;
16115     char_u	*pat;
16116     pos_T	pos;
16117     pos_T	save_cursor;
16118     int		save_p_ws = p_ws;
16119     int		dir;
16120     int		retval = 0;	/* default: FAIL */
16121     long	lnum_stop = 0;
16122     proftime_T	tm;
16123 #ifdef FEAT_RELTIME
16124     long	time_limit = 0;
16125 #endif
16126     int		options = SEARCH_KEEP;
16127     int		subpatnum;
16128 
16129     pat = get_tv_string(&argvars[0]);
16130     dir = get_search_arg(&argvars[1], flagsp);	/* may set p_ws */
16131     if (dir == 0)
16132 	goto theend;
16133     flags = *flagsp;
16134     if (flags & SP_START)
16135 	options |= SEARCH_START;
16136     if (flags & SP_END)
16137 	options |= SEARCH_END;
16138 
16139     /* Optional arguments: line number to stop searching and timeout. */
16140     if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
16141     {
16142 	lnum_stop = get_tv_number_chk(&argvars[2], NULL);
16143 	if (lnum_stop < 0)
16144 	    goto theend;
16145 #ifdef FEAT_RELTIME
16146 	if (argvars[3].v_type != VAR_UNKNOWN)
16147 	{
16148 	    time_limit = get_tv_number_chk(&argvars[3], NULL);
16149 	    if (time_limit < 0)
16150 		goto theend;
16151 	}
16152 #endif
16153     }
16154 
16155 #ifdef FEAT_RELTIME
16156     /* Set the time limit, if there is one. */
16157     profile_setlimit(time_limit, &tm);
16158 #endif
16159 
16160     /*
16161      * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
16162      * Check to make sure only those flags are set.
16163      * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
16164      * flags cannot be set. Check for that condition also.
16165      */
16166     if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
16167 	    || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
16168     {
16169 	EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
16170 	goto theend;
16171     }
16172 
16173     pos = save_cursor = curwin->w_cursor;
16174     subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
16175 				options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
16176     if (subpatnum != FAIL)
16177     {
16178 	if (flags & SP_SUBPAT)
16179 	    retval = subpatnum;
16180 	else
16181 	    retval = pos.lnum;
16182 	if (flags & SP_SETPCMARK)
16183 	    setpcmark();
16184 	curwin->w_cursor = pos;
16185 	if (match_pos != NULL)
16186 	{
16187 	    /* Store the match cursor position */
16188 	    match_pos->lnum = pos.lnum;
16189 	    match_pos->col = pos.col + 1;
16190 	}
16191 	/* "/$" will put the cursor after the end of the line, may need to
16192 	 * correct that here */
16193 	check_cursor();
16194     }
16195 
16196     /* If 'n' flag is used: restore cursor position. */
16197     if (flags & SP_NOMOVE)
16198 	curwin->w_cursor = save_cursor;
16199     else
16200 	curwin->w_set_curswant = TRUE;
16201 theend:
16202     p_ws = save_p_ws;
16203 
16204     return retval;
16205 }
16206 
16207 #ifdef FEAT_FLOAT
16208 
16209 /*
16210  * round() is not in C90, use ceil() or floor() instead.
16211  */
16212     float_T
16213 vim_round(f)
16214     float_T f;
16215 {
16216     return f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
16217 }
16218 
16219 /*
16220  * "round({float})" function
16221  */
16222     static void
16223 f_round(argvars, rettv)
16224     typval_T	*argvars;
16225     typval_T	*rettv;
16226 {
16227     float_T	f;
16228 
16229     rettv->v_type = VAR_FLOAT;
16230     if (get_float_arg(argvars, &f) == OK)
16231 	rettv->vval.v_float = vim_round(f);
16232     else
16233 	rettv->vval.v_float = 0.0;
16234 }
16235 #endif
16236 
16237 /*
16238  * "screenattr()" function
16239  */
16240     static void
16241 f_screenattr(argvars, rettv)
16242     typval_T	*argvars UNUSED;
16243     typval_T	*rettv;
16244 {
16245     int		row;
16246     int		col;
16247     int		c;
16248 
16249     row = get_tv_number_chk(&argvars[0], NULL) - 1;
16250     col = get_tv_number_chk(&argvars[1], NULL) - 1;
16251     if (row < 0 || row >= screen_Rows
16252 	    || col < 0 || col >= screen_Columns)
16253 	c = -1;
16254     else
16255 	c = ScreenAttrs[LineOffset[row] + col];
16256     rettv->vval.v_number = c;
16257 }
16258 
16259 /*
16260  * "screenchar()" function
16261  */
16262     static void
16263 f_screenchar(argvars, rettv)
16264     typval_T	*argvars UNUSED;
16265     typval_T	*rettv;
16266 {
16267     int		row;
16268     int		col;
16269     int		off;
16270     int		c;
16271 
16272     row = get_tv_number_chk(&argvars[0], NULL) - 1;
16273     col = get_tv_number_chk(&argvars[1], NULL) - 1;
16274     if (row < 0 || row >= screen_Rows
16275 	    || col < 0 || col >= screen_Columns)
16276 	c = -1;
16277     else
16278     {
16279 	off = LineOffset[row] + col;
16280 #ifdef FEAT_MBYTE
16281 	if (enc_utf8 && ScreenLinesUC[off] != 0)
16282 	    c = ScreenLinesUC[off];
16283 	else
16284 #endif
16285 	    c = ScreenLines[off];
16286     }
16287     rettv->vval.v_number = c;
16288 }
16289 
16290 /*
16291  * "screencol()" function
16292  *
16293  * First column is 1 to be consistent with virtcol().
16294  */
16295     static void
16296 f_screencol(argvars, rettv)
16297     typval_T	*argvars UNUSED;
16298     typval_T	*rettv;
16299 {
16300     rettv->vval.v_number = screen_screencol() + 1;
16301 }
16302 
16303 /*
16304  * "screenrow()" function
16305  */
16306     static void
16307 f_screenrow(argvars, rettv)
16308     typval_T	*argvars UNUSED;
16309     typval_T	*rettv;
16310 {
16311     rettv->vval.v_number = screen_screenrow() + 1;
16312 }
16313 
16314 /*
16315  * "search()" function
16316  */
16317     static void
16318 f_search(argvars, rettv)
16319     typval_T	*argvars;
16320     typval_T	*rettv;
16321 {
16322     int		flags = 0;
16323 
16324     rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
16325 }
16326 
16327 /*
16328  * "searchdecl()" function
16329  */
16330     static void
16331 f_searchdecl(argvars, rettv)
16332     typval_T	*argvars;
16333     typval_T	*rettv;
16334 {
16335     int		locally = 1;
16336     int		thisblock = 0;
16337     int		error = FALSE;
16338     char_u	*name;
16339 
16340     rettv->vval.v_number = 1;	/* default: FAIL */
16341 
16342     name = get_tv_string_chk(&argvars[0]);
16343     if (argvars[1].v_type != VAR_UNKNOWN)
16344     {
16345 	locally = get_tv_number_chk(&argvars[1], &error) == 0;
16346 	if (!error && argvars[2].v_type != VAR_UNKNOWN)
16347 	    thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
16348     }
16349     if (!error && name != NULL)
16350 	rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
16351 				     locally, thisblock, SEARCH_KEEP) == FAIL;
16352 }
16353 
16354 /*
16355  * Used by searchpair() and searchpairpos()
16356  */
16357     static int
16358 searchpair_cmn(argvars, match_pos)
16359     typval_T	*argvars;
16360     pos_T	*match_pos;
16361 {
16362     char_u	*spat, *mpat, *epat;
16363     char_u	*skip;
16364     int		save_p_ws = p_ws;
16365     int		dir;
16366     int		flags = 0;
16367     char_u	nbuf1[NUMBUFLEN];
16368     char_u	nbuf2[NUMBUFLEN];
16369     char_u	nbuf3[NUMBUFLEN];
16370     int		retval = 0;		/* default: FAIL */
16371     long	lnum_stop = 0;
16372     long	time_limit = 0;
16373 
16374     /* Get the three pattern arguments: start, middle, end. */
16375     spat = get_tv_string_chk(&argvars[0]);
16376     mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
16377     epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
16378     if (spat == NULL || mpat == NULL || epat == NULL)
16379 	goto theend;	    /* type error */
16380 
16381     /* Handle the optional fourth argument: flags */
16382     dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
16383     if (dir == 0)
16384 	goto theend;
16385 
16386     /* Don't accept SP_END or SP_SUBPAT.
16387      * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
16388      */
16389     if ((flags & (SP_END | SP_SUBPAT)) != 0
16390 	    || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
16391     {
16392 	EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
16393 	goto theend;
16394     }
16395 
16396     /* Using 'r' implies 'W', otherwise it doesn't work. */
16397     if (flags & SP_REPEAT)
16398 	p_ws = FALSE;
16399 
16400     /* Optional fifth argument: skip expression */
16401     if (argvars[3].v_type == VAR_UNKNOWN
16402 	    || argvars[4].v_type == VAR_UNKNOWN)
16403 	skip = (char_u *)"";
16404     else
16405     {
16406 	skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
16407 	if (argvars[5].v_type != VAR_UNKNOWN)
16408 	{
16409 	    lnum_stop = get_tv_number_chk(&argvars[5], NULL);
16410 	    if (lnum_stop < 0)
16411 		goto theend;
16412 #ifdef FEAT_RELTIME
16413 	    if (argvars[6].v_type != VAR_UNKNOWN)
16414 	    {
16415 		time_limit = get_tv_number_chk(&argvars[6], NULL);
16416 		if (time_limit < 0)
16417 		    goto theend;
16418 	    }
16419 #endif
16420 	}
16421     }
16422     if (skip == NULL)
16423 	goto theend;	    /* type error */
16424 
16425     retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
16426 					    match_pos, lnum_stop, time_limit);
16427 
16428 theend:
16429     p_ws = save_p_ws;
16430 
16431     return retval;
16432 }
16433 
16434 /*
16435  * "searchpair()" function
16436  */
16437     static void
16438 f_searchpair(argvars, rettv)
16439     typval_T	*argvars;
16440     typval_T	*rettv;
16441 {
16442     rettv->vval.v_number = searchpair_cmn(argvars, NULL);
16443 }
16444 
16445 /*
16446  * "searchpairpos()" function
16447  */
16448     static void
16449 f_searchpairpos(argvars, rettv)
16450     typval_T	*argvars;
16451     typval_T	*rettv;
16452 {
16453     pos_T	match_pos;
16454     int		lnum = 0;
16455     int		col = 0;
16456 
16457     if (rettv_list_alloc(rettv) == FAIL)
16458 	return;
16459 
16460     if (searchpair_cmn(argvars, &match_pos) > 0)
16461     {
16462 	lnum = match_pos.lnum;
16463 	col = match_pos.col;
16464     }
16465 
16466     list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
16467     list_append_number(rettv->vval.v_list, (varnumber_T)col);
16468 }
16469 
16470 /*
16471  * Search for a start/middle/end thing.
16472  * Used by searchpair(), see its documentation for the details.
16473  * Returns 0 or -1 for no match,
16474  */
16475     long
16476 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
16477 							lnum_stop, time_limit)
16478     char_u	*spat;	    /* start pattern */
16479     char_u	*mpat;	    /* middle pattern */
16480     char_u	*epat;	    /* end pattern */
16481     int		dir;	    /* BACKWARD or FORWARD */
16482     char_u	*skip;	    /* skip expression */
16483     int		flags;	    /* SP_SETPCMARK and other SP_ values */
16484     pos_T	*match_pos;
16485     linenr_T	lnum_stop;  /* stop at this line if not zero */
16486     long	time_limit UNUSED; /* stop after this many msec */
16487 {
16488     char_u	*save_cpo;
16489     char_u	*pat, *pat2 = NULL, *pat3 = NULL;
16490     long	retval = 0;
16491     pos_T	pos;
16492     pos_T	firstpos;
16493     pos_T	foundpos;
16494     pos_T	save_cursor;
16495     pos_T	save_pos;
16496     int		n;
16497     int		r;
16498     int		nest = 1;
16499     int		err;
16500     int		options = SEARCH_KEEP;
16501     proftime_T	tm;
16502 
16503     /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16504     save_cpo = p_cpo;
16505     p_cpo = empty_option;
16506 
16507 #ifdef FEAT_RELTIME
16508     /* Set the time limit, if there is one. */
16509     profile_setlimit(time_limit, &tm);
16510 #endif
16511 
16512     /* Make two search patterns: start/end (pat2, for in nested pairs) and
16513      * start/middle/end (pat3, for the top pair). */
16514     pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
16515     pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
16516     if (pat2 == NULL || pat3 == NULL)
16517 	goto theend;
16518     sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
16519     if (*mpat == NUL)
16520 	STRCPY(pat3, pat2);
16521     else
16522 	sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
16523 							    spat, epat, mpat);
16524     if (flags & SP_START)
16525 	options |= SEARCH_START;
16526 
16527     save_cursor = curwin->w_cursor;
16528     pos = curwin->w_cursor;
16529     clearpos(&firstpos);
16530     clearpos(&foundpos);
16531     pat = pat3;
16532     for (;;)
16533     {
16534 	n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
16535 					   options, RE_SEARCH, lnum_stop, &tm);
16536 	if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
16537 	    /* didn't find it or found the first match again: FAIL */
16538 	    break;
16539 
16540 	if (firstpos.lnum == 0)
16541 	    firstpos = pos;
16542 	if (equalpos(pos, foundpos))
16543 	{
16544 	    /* Found the same position again.  Can happen with a pattern that
16545 	     * has "\zs" at the end and searching backwards.  Advance one
16546 	     * character and try again. */
16547 	    if (dir == BACKWARD)
16548 		decl(&pos);
16549 	    else
16550 		incl(&pos);
16551 	}
16552 	foundpos = pos;
16553 
16554 	/* clear the start flag to avoid getting stuck here */
16555 	options &= ~SEARCH_START;
16556 
16557 	/* If the skip pattern matches, ignore this match. */
16558 	if (*skip != NUL)
16559 	{
16560 	    save_pos = curwin->w_cursor;
16561 	    curwin->w_cursor = pos;
16562 	    r = eval_to_bool(skip, &err, NULL, FALSE);
16563 	    curwin->w_cursor = save_pos;
16564 	    if (err)
16565 	    {
16566 		/* Evaluating {skip} caused an error, break here. */
16567 		curwin->w_cursor = save_cursor;
16568 		retval = -1;
16569 		break;
16570 	    }
16571 	    if (r)
16572 		continue;
16573 	}
16574 
16575 	if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
16576 	{
16577 	    /* Found end when searching backwards or start when searching
16578 	     * forward: nested pair. */
16579 	    ++nest;
16580 	    pat = pat2;		/* nested, don't search for middle */
16581 	}
16582 	else
16583 	{
16584 	    /* Found end when searching forward or start when searching
16585 	     * backward: end of (nested) pair; or found middle in outer pair. */
16586 	    if (--nest == 1)
16587 		pat = pat3;	/* outer level, search for middle */
16588 	}
16589 
16590 	if (nest == 0)
16591 	{
16592 	    /* Found the match: return matchcount or line number. */
16593 	    if (flags & SP_RETCOUNT)
16594 		++retval;
16595 	    else
16596 		retval = pos.lnum;
16597 	    if (flags & SP_SETPCMARK)
16598 		setpcmark();
16599 	    curwin->w_cursor = pos;
16600 	    if (!(flags & SP_REPEAT))
16601 		break;
16602 	    nest = 1;	    /* search for next unmatched */
16603 	}
16604     }
16605 
16606     if (match_pos != NULL)
16607     {
16608 	/* Store the match cursor position */
16609 	match_pos->lnum = curwin->w_cursor.lnum;
16610 	match_pos->col = curwin->w_cursor.col + 1;
16611     }
16612 
16613     /* If 'n' flag is used or search failed: restore cursor position. */
16614     if ((flags & SP_NOMOVE) || retval == 0)
16615 	curwin->w_cursor = save_cursor;
16616 
16617 theend:
16618     vim_free(pat2);
16619     vim_free(pat3);
16620     if (p_cpo == empty_option)
16621 	p_cpo = save_cpo;
16622     else
16623 	/* Darn, evaluating the {skip} expression changed the value. */
16624 	free_string_option(save_cpo);
16625 
16626     return retval;
16627 }
16628 
16629 /*
16630  * "searchpos()" function
16631  */
16632     static void
16633 f_searchpos(argvars, rettv)
16634     typval_T	*argvars;
16635     typval_T	*rettv;
16636 {
16637     pos_T	match_pos;
16638     int		lnum = 0;
16639     int		col = 0;
16640     int		n;
16641     int		flags = 0;
16642 
16643     if (rettv_list_alloc(rettv) == FAIL)
16644 	return;
16645 
16646     n = search_cmn(argvars, &match_pos, &flags);
16647     if (n > 0)
16648     {
16649 	lnum = match_pos.lnum;
16650 	col = match_pos.col;
16651     }
16652 
16653     list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
16654     list_append_number(rettv->vval.v_list, (varnumber_T)col);
16655     if (flags & SP_SUBPAT)
16656 	list_append_number(rettv->vval.v_list, (varnumber_T)n);
16657 }
16658 
16659 
16660     static void
16661 f_server2client(argvars, rettv)
16662     typval_T	*argvars UNUSED;
16663     typval_T	*rettv;
16664 {
16665 #ifdef FEAT_CLIENTSERVER
16666     char_u	buf[NUMBUFLEN];
16667     char_u	*server = get_tv_string_chk(&argvars[0]);
16668     char_u	*reply = get_tv_string_buf_chk(&argvars[1], buf);
16669 
16670     rettv->vval.v_number = -1;
16671     if (server == NULL || reply == NULL)
16672 	return;
16673     if (check_restricted() || check_secure())
16674 	return;
16675 # ifdef FEAT_X11
16676     if (check_connection() == FAIL)
16677 	return;
16678 # endif
16679 
16680     if (serverSendReply(server, reply) < 0)
16681     {
16682 	EMSG(_("E258: Unable to send to client"));
16683 	return;
16684     }
16685     rettv->vval.v_number = 0;
16686 #else
16687     rettv->vval.v_number = -1;
16688 #endif
16689 }
16690 
16691     static void
16692 f_serverlist(argvars, rettv)
16693     typval_T	*argvars UNUSED;
16694     typval_T	*rettv;
16695 {
16696     char_u	*r = NULL;
16697 
16698 #ifdef FEAT_CLIENTSERVER
16699 # ifdef WIN32
16700     r = serverGetVimNames();
16701 # else
16702     make_connection();
16703     if (X_DISPLAY != NULL)
16704 	r = serverGetVimNames(X_DISPLAY);
16705 # endif
16706 #endif
16707     rettv->v_type = VAR_STRING;
16708     rettv->vval.v_string = r;
16709 }
16710 
16711 /*
16712  * "setbufvar()" function
16713  */
16714     static void
16715 f_setbufvar(argvars, rettv)
16716     typval_T	*argvars;
16717     typval_T	*rettv UNUSED;
16718 {
16719     buf_T	*buf;
16720     aco_save_T	aco;
16721     char_u	*varname, *bufvarname;
16722     typval_T	*varp;
16723     char_u	nbuf[NUMBUFLEN];
16724 
16725     if (check_restricted() || check_secure())
16726 	return;
16727     (void)get_tv_number(&argvars[0]);	    /* issue errmsg if type error */
16728     varname = get_tv_string_chk(&argvars[1]);
16729     buf = get_buf_tv(&argvars[0], FALSE);
16730     varp = &argvars[2];
16731 
16732     if (buf != NULL && varname != NULL && varp != NULL)
16733     {
16734 	/* set curbuf to be our buf, temporarily */
16735 	aucmd_prepbuf(&aco, buf);
16736 
16737 	if (*varname == '&')
16738 	{
16739 	    long	numval;
16740 	    char_u	*strval;
16741 	    int		error = FALSE;
16742 
16743 	    ++varname;
16744 	    numval = get_tv_number_chk(varp, &error);
16745 	    strval = get_tv_string_buf_chk(varp, nbuf);
16746 	    if (!error && strval != NULL)
16747 		set_option_value(varname, numval, strval, OPT_LOCAL);
16748 	}
16749 	else
16750 	{
16751 	    bufvarname = alloc((unsigned)STRLEN(varname) + 3);
16752 	    if (bufvarname != NULL)
16753 	    {
16754 		STRCPY(bufvarname, "b:");
16755 		STRCPY(bufvarname + 2, varname);
16756 		set_var(bufvarname, varp, TRUE);
16757 		vim_free(bufvarname);
16758 	    }
16759 	}
16760 
16761 	/* reset notion of buffer */
16762 	aucmd_restbuf(&aco);
16763     }
16764 }
16765 
16766 /*
16767  * "setcmdpos()" function
16768  */
16769     static void
16770 f_setcmdpos(argvars, rettv)
16771     typval_T	*argvars;
16772     typval_T	*rettv;
16773 {
16774     int		pos = (int)get_tv_number(&argvars[0]) - 1;
16775 
16776     if (pos >= 0)
16777 	rettv->vval.v_number = set_cmdline_pos(pos);
16778 }
16779 
16780 /*
16781  * "setline()" function
16782  */
16783     static void
16784 f_setline(argvars, rettv)
16785     typval_T	*argvars;
16786     typval_T	*rettv;
16787 {
16788     linenr_T	lnum;
16789     char_u	*line = NULL;
16790     list_T	*l = NULL;
16791     listitem_T	*li = NULL;
16792     long	added = 0;
16793     linenr_T	lcount = curbuf->b_ml.ml_line_count;
16794 
16795     lnum = get_tv_lnum(&argvars[0]);
16796     if (argvars[1].v_type == VAR_LIST)
16797     {
16798 	l = argvars[1].vval.v_list;
16799 	li = l->lv_first;
16800     }
16801     else
16802 	line = get_tv_string_chk(&argvars[1]);
16803 
16804     /* default result is zero == OK */
16805     for (;;)
16806     {
16807 	if (l != NULL)
16808 	{
16809 	    /* list argument, get next string */
16810 	    if (li == NULL)
16811 		break;
16812 	    line = get_tv_string_chk(&li->li_tv);
16813 	    li = li->li_next;
16814 	}
16815 
16816 	rettv->vval.v_number = 1;	/* FAIL */
16817 	if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
16818 	    break;
16819 
16820 	/* When coming here from Insert mode, sync undo, so that this can be
16821 	 * undone separately from what was previously inserted. */
16822 	if (u_sync_once == 2)
16823 	{
16824 	    u_sync_once = 1; /* notify that u_sync() was called */
16825 	    u_sync(TRUE);
16826 	}
16827 
16828 	if (lnum <= curbuf->b_ml.ml_line_count)
16829 	{
16830 	    /* existing line, replace it */
16831 	    if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
16832 	    {
16833 		changed_bytes(lnum, 0);
16834 		if (lnum == curwin->w_cursor.lnum)
16835 		    check_cursor_col();
16836 		rettv->vval.v_number = 0;	/* OK */
16837 	    }
16838 	}
16839 	else if (added > 0 || u_save(lnum - 1, lnum) == OK)
16840 	{
16841 	    /* lnum is one past the last line, append the line */
16842 	    ++added;
16843 	    if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
16844 		rettv->vval.v_number = 0;	/* OK */
16845 	}
16846 
16847 	if (l == NULL)			/* only one string argument */
16848 	    break;
16849 	++lnum;
16850     }
16851 
16852     if (added > 0)
16853 	appended_lines_mark(lcount, added);
16854 }
16855 
16856 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
16857 
16858 /*
16859  * Used by "setqflist()" and "setloclist()" functions
16860  */
16861     static void
16862 set_qf_ll_list(wp, list_arg, action_arg, rettv)
16863     win_T	*wp UNUSED;
16864     typval_T	*list_arg UNUSED;
16865     typval_T	*action_arg UNUSED;
16866     typval_T	*rettv;
16867 {
16868 #ifdef FEAT_QUICKFIX
16869     char_u	*act;
16870     int		action = ' ';
16871 #endif
16872 
16873     rettv->vval.v_number = -1;
16874 
16875 #ifdef FEAT_QUICKFIX
16876     if (list_arg->v_type != VAR_LIST)
16877 	EMSG(_(e_listreq));
16878     else
16879     {
16880 	list_T  *l = list_arg->vval.v_list;
16881 
16882 	if (action_arg->v_type == VAR_STRING)
16883 	{
16884 	    act = get_tv_string_chk(action_arg);
16885 	    if (act == NULL)
16886 		return;		/* type error; errmsg already given */
16887 	    if (*act == 'a' || *act == 'r')
16888 		action = *act;
16889 	}
16890 
16891 	if (l != NULL && set_errorlist(wp, l, action,
16892 	       (char_u *)(wp == NULL ? "setqflist()" : "setloclist()")) == OK)
16893 	    rettv->vval.v_number = 0;
16894     }
16895 #endif
16896 }
16897 
16898 /*
16899  * "setloclist()" function
16900  */
16901     static void
16902 f_setloclist(argvars, rettv)
16903     typval_T	*argvars;
16904     typval_T	*rettv;
16905 {
16906     win_T	*win;
16907 
16908     rettv->vval.v_number = -1;
16909 
16910     win = find_win_by_nr(&argvars[0], NULL);
16911     if (win != NULL)
16912 	set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
16913 }
16914 
16915 /*
16916  * "setmatches()" function
16917  */
16918     static void
16919 f_setmatches(argvars, rettv)
16920     typval_T	*argvars UNUSED;
16921     typval_T	*rettv UNUSED;
16922 {
16923 #ifdef FEAT_SEARCH_EXTRA
16924     list_T	*l;
16925     listitem_T	*li;
16926     dict_T	*d;
16927 
16928     rettv->vval.v_number = -1;
16929     if (argvars[0].v_type != VAR_LIST)
16930     {
16931 	EMSG(_(e_listreq));
16932 	return;
16933     }
16934     if ((l = argvars[0].vval.v_list) != NULL)
16935     {
16936 
16937 	/* To some extent make sure that we are dealing with a list from
16938 	 * "getmatches()". */
16939 	li = l->lv_first;
16940 	while (li != NULL)
16941 	{
16942 	    if (li->li_tv.v_type != VAR_DICT
16943 		    || (d = li->li_tv.vval.v_dict) == NULL)
16944 	    {
16945 		EMSG(_(e_invarg));
16946 		return;
16947 	    }
16948 	    if (!(dict_find(d, (char_u *)"group", -1) != NULL
16949 			&& dict_find(d, (char_u *)"pattern", -1) != NULL
16950 			&& dict_find(d, (char_u *)"priority", -1) != NULL
16951 			&& dict_find(d, (char_u *)"id", -1) != NULL))
16952 	    {
16953 		EMSG(_(e_invarg));
16954 		return;
16955 	    }
16956 	    li = li->li_next;
16957 	}
16958 
16959 	clear_matches(curwin);
16960 	li = l->lv_first;
16961 	while (li != NULL)
16962 	{
16963 	    d = li->li_tv.vval.v_dict;
16964 	    match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
16965 		    get_dict_string(d, (char_u *)"pattern", FALSE),
16966 		    (int)get_dict_number(d, (char_u *)"priority"),
16967 		    (int)get_dict_number(d, (char_u *)"id"), NULL);
16968 	    li = li->li_next;
16969 	}
16970 	rettv->vval.v_number = 0;
16971     }
16972 #endif
16973 }
16974 
16975 /*
16976  * "setpos()" function
16977  */
16978     static void
16979 f_setpos(argvars, rettv)
16980     typval_T	*argvars;
16981     typval_T	*rettv;
16982 {
16983     pos_T	pos;
16984     int		fnum;
16985     char_u	*name;
16986     colnr_T	curswant = -1;
16987 
16988     rettv->vval.v_number = -1;
16989     name = get_tv_string_chk(argvars);
16990     if (name != NULL)
16991     {
16992 	if (list2fpos(&argvars[1], &pos, &fnum, &curswant) == OK)
16993 	{
16994 	    if (--pos.col < 0)
16995 		pos.col = 0;
16996 	    if (name[0] == '.' && name[1] == NUL)
16997 	    {
16998 		/* set cursor */
16999 		if (fnum == curbuf->b_fnum)
17000 		{
17001 		    curwin->w_cursor = pos;
17002 		    if (curswant >= 0)
17003 			curwin->w_curswant = curswant - 1;
17004 		    check_cursor();
17005 		    rettv->vval.v_number = 0;
17006 		}
17007 		else
17008 		    EMSG(_(e_invarg));
17009 	    }
17010 	    else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
17011 	    {
17012 		/* set mark */
17013 		if (setmark_pos(name[1], &pos, fnum) == OK)
17014 		    rettv->vval.v_number = 0;
17015 	    }
17016 	    else
17017 		EMSG(_(e_invarg));
17018 	}
17019     }
17020 }
17021 
17022 /*
17023  * "setqflist()" function
17024  */
17025     static void
17026 f_setqflist(argvars, rettv)
17027     typval_T	*argvars;
17028     typval_T	*rettv;
17029 {
17030     set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
17031 }
17032 
17033 /*
17034  * "setreg()" function
17035  */
17036     static void
17037 f_setreg(argvars, rettv)
17038     typval_T	*argvars;
17039     typval_T	*rettv;
17040 {
17041     int		regname;
17042     char_u	*strregname;
17043     char_u	*stropt;
17044     char_u	*strval;
17045     int		append;
17046     char_u	yank_type;
17047     long	block_len;
17048 
17049     block_len = -1;
17050     yank_type = MAUTO;
17051     append = FALSE;
17052 
17053     strregname = get_tv_string_chk(argvars);
17054     rettv->vval.v_number = 1;		/* FAIL is default */
17055 
17056     if (strregname == NULL)
17057 	return;		/* type error; errmsg already given */
17058     regname = *strregname;
17059     if (regname == 0 || regname == '@')
17060 	regname = '"';
17061 
17062     if (argvars[2].v_type != VAR_UNKNOWN)
17063     {
17064 	stropt = get_tv_string_chk(&argvars[2]);
17065 	if (stropt == NULL)
17066 	    return;		/* type error */
17067 	for (; *stropt != NUL; ++stropt)
17068 	    switch (*stropt)
17069 	    {
17070 		case 'a': case 'A':	/* append */
17071 		    append = TRUE;
17072 		    break;
17073 		case 'v': case 'c':	/* character-wise selection */
17074 		    yank_type = MCHAR;
17075 		    break;
17076 		case 'V': case 'l':	/* line-wise selection */
17077 		    yank_type = MLINE;
17078 		    break;
17079 		case 'b': case Ctrl_V:	/* block-wise selection */
17080 		    yank_type = MBLOCK;
17081 		    if (VIM_ISDIGIT(stropt[1]))
17082 		    {
17083 			++stropt;
17084 			block_len = getdigits(&stropt) - 1;
17085 			--stropt;
17086 		    }
17087 		    break;
17088 	    }
17089     }
17090 
17091     if (argvars[1].v_type == VAR_LIST)
17092     {
17093 	char_u		**lstval;
17094 	char_u		**allocval;
17095 	char_u		buf[NUMBUFLEN];
17096 	char_u		**curval;
17097 	char_u		**curallocval;
17098 	int		len = argvars[1].vval.v_list->lv_len;
17099 	listitem_T	*li;
17100 
17101 	/* First half: use for pointers to result lines; second half: use for
17102 	 * pointers to allocated copies. */
17103 	lstval = (char_u **)alloc(sizeof(char_u *) * ((len + 1) * 2));
17104 	if (lstval == NULL)
17105 	    return;
17106 	curval = lstval;
17107 	allocval = lstval + len + 2;
17108 	curallocval = allocval;
17109 
17110 	for (li = argvars[1].vval.v_list->lv_first; li != NULL;
17111 							     li = li->li_next)
17112 	{
17113 	    strval = get_tv_string_buf_chk(&li->li_tv, buf);
17114 	    if (strval == NULL)
17115 		goto free_lstval;
17116 	    if (strval == buf)
17117 	    {
17118 		/* Need to make a copy, next get_tv_string_buf_chk() will
17119 		 * overwrite the string. */
17120 		strval = vim_strsave(buf);
17121 		if (strval == NULL)
17122 		    goto free_lstval;
17123 		*curallocval++ = strval;
17124 	    }
17125 	    *curval++ = strval;
17126 	}
17127 	*curval++ = NULL;
17128 
17129 	write_reg_contents_lst(regname, lstval, -1,
17130 						append, yank_type, block_len);
17131 free_lstval:
17132 	while (curallocval > allocval)
17133 	    vim_free(*--curallocval);
17134 	vim_free(lstval);
17135     }
17136     else
17137     {
17138 	strval = get_tv_string_chk(&argvars[1]);
17139 	if (strval == NULL)
17140 	    return;
17141 	write_reg_contents_ex(regname, strval, -1,
17142 						append, yank_type, block_len);
17143     }
17144     rettv->vval.v_number = 0;
17145 }
17146 
17147 /*
17148  * "settabvar()" function
17149  */
17150     static void
17151 f_settabvar(argvars, rettv)
17152     typval_T	*argvars;
17153     typval_T	*rettv;
17154 {
17155 #ifdef FEAT_WINDOWS
17156     tabpage_T	*save_curtab;
17157     tabpage_T	*tp;
17158 #endif
17159     char_u	*varname, *tabvarname;
17160     typval_T	*varp;
17161 
17162     rettv->vval.v_number = 0;
17163 
17164     if (check_restricted() || check_secure())
17165 	return;
17166 
17167 #ifdef FEAT_WINDOWS
17168     tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
17169 #endif
17170     varname = get_tv_string_chk(&argvars[1]);
17171     varp = &argvars[2];
17172 
17173     if (varname != NULL && varp != NULL
17174 #ifdef FEAT_WINDOWS
17175 	    && tp != NULL
17176 #endif
17177 	    )
17178     {
17179 #ifdef FEAT_WINDOWS
17180 	save_curtab = curtab;
17181 	goto_tabpage_tp(tp, FALSE, FALSE);
17182 #endif
17183 
17184 	tabvarname = alloc((unsigned)STRLEN(varname) + 3);
17185 	if (tabvarname != NULL)
17186 	{
17187 	    STRCPY(tabvarname, "t:");
17188 	    STRCPY(tabvarname + 2, varname);
17189 	    set_var(tabvarname, varp, TRUE);
17190 	    vim_free(tabvarname);
17191 	}
17192 
17193 #ifdef FEAT_WINDOWS
17194 	/* Restore current tabpage */
17195 	if (valid_tabpage(save_curtab))
17196 	    goto_tabpage_tp(save_curtab, FALSE, FALSE);
17197 #endif
17198     }
17199 }
17200 
17201 /*
17202  * "settabwinvar()" function
17203  */
17204     static void
17205 f_settabwinvar(argvars, rettv)
17206     typval_T	*argvars;
17207     typval_T	*rettv;
17208 {
17209     setwinvar(argvars, rettv, 1);
17210 }
17211 
17212 /*
17213  * "setwinvar()" function
17214  */
17215     static void
17216 f_setwinvar(argvars, rettv)
17217     typval_T	*argvars;
17218     typval_T	*rettv;
17219 {
17220     setwinvar(argvars, rettv, 0);
17221 }
17222 
17223 /*
17224  * "setwinvar()" and "settabwinvar()" functions
17225  */
17226 
17227     static void
17228 setwinvar(argvars, rettv, off)
17229     typval_T	*argvars;
17230     typval_T	*rettv UNUSED;
17231     int		off;
17232 {
17233     win_T	*win;
17234 #ifdef FEAT_WINDOWS
17235     win_T	*save_curwin;
17236     tabpage_T	*save_curtab;
17237 #endif
17238     char_u	*varname, *winvarname;
17239     typval_T	*varp;
17240     char_u	nbuf[NUMBUFLEN];
17241     tabpage_T	*tp = NULL;
17242 
17243     if (check_restricted() || check_secure())
17244 	return;
17245 
17246 #ifdef FEAT_WINDOWS
17247     if (off == 1)
17248 	tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
17249     else
17250 	tp = curtab;
17251 #endif
17252     win = find_win_by_nr(&argvars[off], tp);
17253     varname = get_tv_string_chk(&argvars[off + 1]);
17254     varp = &argvars[off + 2];
17255 
17256     if (win != NULL && varname != NULL && varp != NULL)
17257     {
17258 #ifdef FEAT_WINDOWS
17259 	if (switch_win(&save_curwin, &save_curtab, win, tp, TRUE) == OK)
17260 #endif
17261 	{
17262 	    if (*varname == '&')
17263 	    {
17264 		long	numval;
17265 		char_u	*strval;
17266 		int		error = FALSE;
17267 
17268 		++varname;
17269 		numval = get_tv_number_chk(varp, &error);
17270 		strval = get_tv_string_buf_chk(varp, nbuf);
17271 		if (!error && strval != NULL)
17272 		    set_option_value(varname, numval, strval, OPT_LOCAL);
17273 	    }
17274 	    else
17275 	    {
17276 		winvarname = alloc((unsigned)STRLEN(varname) + 3);
17277 		if (winvarname != NULL)
17278 		{
17279 		    STRCPY(winvarname, "w:");
17280 		    STRCPY(winvarname + 2, varname);
17281 		    set_var(winvarname, varp, TRUE);
17282 		    vim_free(winvarname);
17283 		}
17284 	    }
17285 	}
17286 #ifdef FEAT_WINDOWS
17287 	restore_win(save_curwin, save_curtab, TRUE);
17288 #endif
17289     }
17290 }
17291 
17292 #ifdef FEAT_CRYPT
17293 /*
17294  * "sha256({string})" function
17295  */
17296     static void
17297 f_sha256(argvars, rettv)
17298     typval_T	*argvars;
17299     typval_T	*rettv;
17300 {
17301     char_u	*p;
17302 
17303     p = get_tv_string(&argvars[0]);
17304     rettv->vval.v_string = vim_strsave(
17305 				    sha256_bytes(p, (int)STRLEN(p), NULL, 0));
17306     rettv->v_type = VAR_STRING;
17307 }
17308 #endif /* FEAT_CRYPT */
17309 
17310 /*
17311  * "shellescape({string})" function
17312  */
17313     static void
17314 f_shellescape(argvars, rettv)
17315     typval_T	*argvars;
17316     typval_T	*rettv;
17317 {
17318     rettv->vval.v_string = vim_strsave_shellescape(
17319 		get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]), TRUE);
17320     rettv->v_type = VAR_STRING;
17321 }
17322 
17323 /*
17324  * shiftwidth() function
17325  */
17326     static void
17327 f_shiftwidth(argvars, rettv)
17328     typval_T	*argvars UNUSED;
17329     typval_T	*rettv;
17330 {
17331     rettv->vval.v_number = get_sw_value(curbuf);
17332 }
17333 
17334 /*
17335  * "simplify()" function
17336  */
17337     static void
17338 f_simplify(argvars, rettv)
17339     typval_T	*argvars;
17340     typval_T	*rettv;
17341 {
17342     char_u	*p;
17343 
17344     p = get_tv_string(&argvars[0]);
17345     rettv->vval.v_string = vim_strsave(p);
17346     simplify_filename(rettv->vval.v_string);	/* simplify in place */
17347     rettv->v_type = VAR_STRING;
17348 }
17349 
17350 #ifdef FEAT_FLOAT
17351 /*
17352  * "sin()" function
17353  */
17354     static void
17355 f_sin(argvars, rettv)
17356     typval_T	*argvars;
17357     typval_T	*rettv;
17358 {
17359     float_T	f;
17360 
17361     rettv->v_type = VAR_FLOAT;
17362     if (get_float_arg(argvars, &f) == OK)
17363 	rettv->vval.v_float = sin(f);
17364     else
17365 	rettv->vval.v_float = 0.0;
17366 }
17367 
17368 /*
17369  * "sinh()" function
17370  */
17371     static void
17372 f_sinh(argvars, rettv)
17373     typval_T	*argvars;
17374     typval_T	*rettv;
17375 {
17376     float_T	f;
17377 
17378     rettv->v_type = VAR_FLOAT;
17379     if (get_float_arg(argvars, &f) == OK)
17380 	rettv->vval.v_float = sinh(f);
17381     else
17382 	rettv->vval.v_float = 0.0;
17383 }
17384 #endif
17385 
17386 static int
17387 #ifdef __BORLANDC__
17388     _RTLENTRYF
17389 #endif
17390 	item_compare __ARGS((const void *s1, const void *s2));
17391 static int
17392 #ifdef __BORLANDC__
17393     _RTLENTRYF
17394 #endif
17395 	item_compare2 __ARGS((const void *s1, const void *s2));
17396 
17397 /* struct used in the array that's given to qsort() */
17398 typedef struct
17399 {
17400     listitem_T	*item;
17401     int		idx;
17402 } sortItem_T;
17403 
17404 static int	item_compare_ic;
17405 static int	item_compare_numeric;
17406 static char_u	*item_compare_func;
17407 static dict_T	*item_compare_selfdict;
17408 static int	item_compare_func_err;
17409 static int	item_compare_keep_zero;
17410 static void	do_sort_uniq __ARGS((typval_T *argvars, typval_T *rettv, int sort));
17411 #define ITEM_COMPARE_FAIL 999
17412 
17413 /*
17414  * Compare functions for f_sort() and f_uniq() below.
17415  */
17416     static int
17417 #ifdef __BORLANDC__
17418 _RTLENTRYF
17419 #endif
17420 item_compare(s1, s2)
17421     const void	*s1;
17422     const void	*s2;
17423 {
17424     sortItem_T  *si1, *si2;
17425     typval_T	*tv1, *tv2;
17426     char_u	*p1, *p2;
17427     char_u	*tofree1 = NULL, *tofree2 = NULL;
17428     int		res;
17429     char_u	numbuf1[NUMBUFLEN];
17430     char_u	numbuf2[NUMBUFLEN];
17431 
17432     si1 = (sortItem_T *)s1;
17433     si2 = (sortItem_T *)s2;
17434     tv1 = &si1->item->li_tv;
17435     tv2 = &si2->item->li_tv;
17436     /* tv2string() puts quotes around a string and allocates memory.  Don't do
17437      * that for string variables. Use a single quote when comparing with a
17438      * non-string to do what the docs promise. */
17439     if (tv1->v_type == VAR_STRING)
17440     {
17441 	if (tv2->v_type != VAR_STRING || item_compare_numeric)
17442 	    p1 = (char_u *)"'";
17443 	else
17444 	    p1 = tv1->vval.v_string;
17445     }
17446     else
17447 	p1 = tv2string(tv1, &tofree1, numbuf1, 0);
17448     if (tv2->v_type == VAR_STRING)
17449     {
17450 	if (tv1->v_type != VAR_STRING || item_compare_numeric)
17451 	    p2 = (char_u *)"'";
17452 	else
17453 	    p2 = tv2->vval.v_string;
17454     }
17455     else
17456 	p2 = tv2string(tv2, &tofree2, numbuf2, 0);
17457     if (p1 == NULL)
17458 	p1 = (char_u *)"";
17459     if (p2 == NULL)
17460 	p2 = (char_u *)"";
17461     if (!item_compare_numeric)
17462     {
17463 	if (item_compare_ic)
17464 	    res = STRICMP(p1, p2);
17465 	else
17466 	    res = STRCMP(p1, p2);
17467     }
17468     else
17469     {
17470 	double n1, n2;
17471 	n1 = strtod((char *)p1, (char **)&p1);
17472 	n2 = strtod((char *)p2, (char **)&p2);
17473 	res = n1 == n2 ? 0 : n1 > n2 ? 1 : -1;
17474     }
17475 
17476     /* When the result would be zero, compare the item indexes.  Makes the
17477      * sort stable. */
17478     if (res == 0 && !item_compare_keep_zero)
17479 	res = si1->idx > si2->idx ? 1 : -1;
17480 
17481     vim_free(tofree1);
17482     vim_free(tofree2);
17483     return res;
17484 }
17485 
17486     static int
17487 #ifdef __BORLANDC__
17488 _RTLENTRYF
17489 #endif
17490 item_compare2(s1, s2)
17491     const void	*s1;
17492     const void	*s2;
17493 {
17494     sortItem_T  *si1, *si2;
17495     int		res;
17496     typval_T	rettv;
17497     typval_T	argv[3];
17498     int		dummy;
17499 
17500     /* shortcut after failure in previous call; compare all items equal */
17501     if (item_compare_func_err)
17502 	return 0;
17503 
17504     si1 = (sortItem_T *)s1;
17505     si2 = (sortItem_T *)s2;
17506 
17507     /* Copy the values.  This is needed to be able to set v_lock to VAR_FIXED
17508      * in the copy without changing the original list items. */
17509     copy_tv(&si1->item->li_tv, &argv[0]);
17510     copy_tv(&si2->item->li_tv, &argv[1]);
17511 
17512     rettv.v_type = VAR_UNKNOWN;		/* clear_tv() uses this */
17513     res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
17514 				 &rettv, 2, argv, 0L, 0L, &dummy, TRUE,
17515 				 item_compare_selfdict);
17516     clear_tv(&argv[0]);
17517     clear_tv(&argv[1]);
17518 
17519     if (res == FAIL)
17520 	res = ITEM_COMPARE_FAIL;
17521     else
17522 	res = get_tv_number_chk(&rettv, &item_compare_func_err);
17523     if (item_compare_func_err)
17524 	res = ITEM_COMPARE_FAIL;  /* return value has wrong type */
17525     clear_tv(&rettv);
17526 
17527     /* When the result would be zero, compare the pointers themselves.  Makes
17528      * the sort stable. */
17529     if (res == 0 && !item_compare_keep_zero)
17530 	res = si1->idx > si2->idx ? 1 : -1;
17531 
17532     return res;
17533 }
17534 
17535 /*
17536  * "sort({list})" function
17537  */
17538     static void
17539 do_sort_uniq(argvars, rettv, sort)
17540     typval_T	*argvars;
17541     typval_T	*rettv;
17542     int		sort;
17543 {
17544     list_T	*l;
17545     listitem_T	*li;
17546     sortItem_T	*ptrs;
17547     long	len;
17548     long	i;
17549 
17550     if (argvars[0].v_type != VAR_LIST)
17551 	EMSG2(_(e_listarg), sort ? "sort()" : "uniq()");
17552     else
17553     {
17554 	l = argvars[0].vval.v_list;
17555 	if (l == NULL || tv_check_lock(l->lv_lock,
17556 	       (char_u *)(sort ? _("sort() argument") : _("uniq() argument"))))
17557 	    return;
17558 	rettv->vval.v_list = l;
17559 	rettv->v_type = VAR_LIST;
17560 	++l->lv_refcount;
17561 
17562 	len = list_len(l);
17563 	if (len <= 1)
17564 	    return;	/* short list sorts pretty quickly */
17565 
17566 	item_compare_ic = FALSE;
17567 	item_compare_numeric = FALSE;
17568 	item_compare_func = NULL;
17569 	item_compare_selfdict = NULL;
17570 	if (argvars[1].v_type != VAR_UNKNOWN)
17571 	{
17572 	    /* optional second argument: {func} */
17573 	    if (argvars[1].v_type == VAR_FUNC)
17574 		item_compare_func = argvars[1].vval.v_string;
17575 	    else
17576 	    {
17577 		int	    error = FALSE;
17578 
17579 		i = get_tv_number_chk(&argvars[1], &error);
17580 		if (error)
17581 		    return;		/* type error; errmsg already given */
17582 		if (i == 1)
17583 		    item_compare_ic = TRUE;
17584 		else
17585 		    item_compare_func = get_tv_string(&argvars[1]);
17586 		if (item_compare_func != NULL)
17587 		{
17588 		    if (STRCMP(item_compare_func, "n") == 0)
17589 		    {
17590 			item_compare_func = NULL;
17591 			item_compare_numeric = TRUE;
17592 		    }
17593 		    else if (STRCMP(item_compare_func, "i") == 0)
17594 		    {
17595 			item_compare_func = NULL;
17596 			item_compare_ic = TRUE;
17597 		    }
17598 		}
17599 	    }
17600 
17601 	    if (argvars[2].v_type != VAR_UNKNOWN)
17602 	    {
17603 		/* optional third argument: {dict} */
17604 		if (argvars[2].v_type != VAR_DICT)
17605 		{
17606 		    EMSG(_(e_dictreq));
17607 		    return;
17608 		}
17609 		item_compare_selfdict = argvars[2].vval.v_dict;
17610 	    }
17611 	}
17612 
17613 	/* Make an array with each entry pointing to an item in the List. */
17614 	ptrs = (sortItem_T *)alloc((int)(len * sizeof(sortItem_T)));
17615 	if (ptrs == NULL)
17616 	    return;
17617 
17618 	i = 0;
17619 	if (sort)
17620 	{
17621 	    /* sort(): ptrs will be the list to sort */
17622 	    for (li = l->lv_first; li != NULL; li = li->li_next)
17623 	    {
17624 		ptrs[i].item = li;
17625 		ptrs[i].idx = i;
17626 		++i;
17627 	    }
17628 
17629 	    item_compare_func_err = FALSE;
17630 	    item_compare_keep_zero = FALSE;
17631 	    /* test the compare function */
17632 	    if (item_compare_func != NULL
17633 		    && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
17634 							 == ITEM_COMPARE_FAIL)
17635 		EMSG(_("E702: Sort compare function failed"));
17636 	    else
17637 	    {
17638 		/* Sort the array with item pointers. */
17639 		qsort((void *)ptrs, (size_t)len, sizeof(sortItem_T),
17640 		    item_compare_func == NULL ? item_compare : item_compare2);
17641 
17642 		if (!item_compare_func_err)
17643 		{
17644 		    /* Clear the List and append the items in sorted order. */
17645 		    l->lv_first = l->lv_last = l->lv_idx_item = NULL;
17646 		    l->lv_len = 0;
17647 		    for (i = 0; i < len; ++i)
17648 			list_append(l, ptrs[i].item);
17649 		}
17650 	    }
17651 	}
17652 	else
17653 	{
17654 	    int	(*item_compare_func_ptr)__ARGS((const void *, const void *));
17655 
17656 	    /* f_uniq(): ptrs will be a stack of items to remove */
17657 	    item_compare_func_err = FALSE;
17658 	    item_compare_keep_zero = TRUE;
17659 	    item_compare_func_ptr = item_compare_func
17660 					       ? item_compare2 : item_compare;
17661 
17662 	    for (li = l->lv_first; li != NULL && li->li_next != NULL;
17663 							     li = li->li_next)
17664 	    {
17665 		if (item_compare_func_ptr((void *)&li, (void *)&li->li_next)
17666 									 == 0)
17667 		    ptrs[i++].item = li;
17668 		if (item_compare_func_err)
17669 		{
17670 		    EMSG(_("E882: Uniq compare function failed"));
17671 		    break;
17672 		}
17673 	    }
17674 
17675 	    if (!item_compare_func_err)
17676 	    {
17677 		while (--i >= 0)
17678 		{
17679 		    li = ptrs[i].item->li_next;
17680 		    ptrs[i].item->li_next = li->li_next;
17681 		    if (li->li_next != NULL)
17682 			li->li_next->li_prev = ptrs[i].item;
17683 		    else
17684 			l->lv_last = ptrs[i].item;
17685 		    list_fix_watch(l, li);
17686 		    listitem_free(li);
17687 		    l->lv_len--;
17688 		}
17689 	    }
17690 	}
17691 
17692 	vim_free(ptrs);
17693     }
17694 }
17695 
17696 /*
17697  * "sort({list})" function
17698  */
17699     static void
17700 f_sort(argvars, rettv)
17701     typval_T	*argvars;
17702     typval_T	*rettv;
17703 {
17704     do_sort_uniq(argvars, rettv, TRUE);
17705 }
17706 
17707 /*
17708  * "uniq({list})" function
17709  */
17710     static void
17711 f_uniq(argvars, rettv)
17712     typval_T	*argvars;
17713     typval_T	*rettv;
17714 {
17715     do_sort_uniq(argvars, rettv, FALSE);
17716 }
17717 
17718 /*
17719  * "soundfold({word})" function
17720  */
17721     static void
17722 f_soundfold(argvars, rettv)
17723     typval_T	*argvars;
17724     typval_T	*rettv;
17725 {
17726     char_u	*s;
17727 
17728     rettv->v_type = VAR_STRING;
17729     s = get_tv_string(&argvars[0]);
17730 #ifdef FEAT_SPELL
17731     rettv->vval.v_string = eval_soundfold(s);
17732 #else
17733     rettv->vval.v_string = vim_strsave(s);
17734 #endif
17735 }
17736 
17737 /*
17738  * "spellbadword()" function
17739  */
17740     static void
17741 f_spellbadword(argvars, rettv)
17742     typval_T	*argvars UNUSED;
17743     typval_T	*rettv;
17744 {
17745     char_u	*word = (char_u *)"";
17746     hlf_T	attr = HLF_COUNT;
17747     int		len = 0;
17748 
17749     if (rettv_list_alloc(rettv) == FAIL)
17750 	return;
17751 
17752 #ifdef FEAT_SPELL
17753     if (argvars[0].v_type == VAR_UNKNOWN)
17754     {
17755 	/* Find the start and length of the badly spelled word. */
17756 	len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
17757 	if (len != 0)
17758 	    word = ml_get_cursor();
17759     }
17760     else if (curwin->w_p_spell && *curbuf->b_s.b_p_spl != NUL)
17761     {
17762 	char_u	*str = get_tv_string_chk(&argvars[0]);
17763 	int	capcol = -1;
17764 
17765 	if (str != NULL)
17766 	{
17767 	    /* Check the argument for spelling. */
17768 	    while (*str != NUL)
17769 	    {
17770 		len = spell_check(curwin, str, &attr, &capcol, FALSE);
17771 		if (attr != HLF_COUNT)
17772 		{
17773 		    word = str;
17774 		    break;
17775 		}
17776 		str += len;
17777 	    }
17778 	}
17779     }
17780 #endif
17781 
17782     list_append_string(rettv->vval.v_list, word, len);
17783     list_append_string(rettv->vval.v_list, (char_u *)(
17784 			attr == HLF_SPB ? "bad" :
17785 			attr == HLF_SPR ? "rare" :
17786 			attr == HLF_SPL ? "local" :
17787 			attr == HLF_SPC ? "caps" :
17788 			""), -1);
17789 }
17790 
17791 /*
17792  * "spellsuggest()" function
17793  */
17794     static void
17795 f_spellsuggest(argvars, rettv)
17796     typval_T	*argvars UNUSED;
17797     typval_T	*rettv;
17798 {
17799 #ifdef FEAT_SPELL
17800     char_u	*str;
17801     int		typeerr = FALSE;
17802     int		maxcount;
17803     garray_T	ga;
17804     int		i;
17805     listitem_T	*li;
17806     int		need_capital = FALSE;
17807 #endif
17808 
17809     if (rettv_list_alloc(rettv) == FAIL)
17810 	return;
17811 
17812 #ifdef FEAT_SPELL
17813     if (curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL)
17814     {
17815 	str = get_tv_string(&argvars[0]);
17816 	if (argvars[1].v_type != VAR_UNKNOWN)
17817 	{
17818 	    maxcount = get_tv_number_chk(&argvars[1], &typeerr);
17819 	    if (maxcount <= 0)
17820 		return;
17821 	    if (argvars[2].v_type != VAR_UNKNOWN)
17822 	    {
17823 		need_capital = get_tv_number_chk(&argvars[2], &typeerr);
17824 		if (typeerr)
17825 		    return;
17826 	    }
17827 	}
17828 	else
17829 	    maxcount = 25;
17830 
17831 	spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
17832 
17833 	for (i = 0; i < ga.ga_len; ++i)
17834 	{
17835 	    str = ((char_u **)ga.ga_data)[i];
17836 
17837 	    li = listitem_alloc();
17838 	    if (li == NULL)
17839 		vim_free(str);
17840 	    else
17841 	    {
17842 		li->li_tv.v_type = VAR_STRING;
17843 		li->li_tv.v_lock = 0;
17844 		li->li_tv.vval.v_string = str;
17845 		list_append(rettv->vval.v_list, li);
17846 	    }
17847 	}
17848 	ga_clear(&ga);
17849     }
17850 #endif
17851 }
17852 
17853     static void
17854 f_split(argvars, rettv)
17855     typval_T	*argvars;
17856     typval_T	*rettv;
17857 {
17858     char_u	*str;
17859     char_u	*end;
17860     char_u	*pat = NULL;
17861     regmatch_T	regmatch;
17862     char_u	patbuf[NUMBUFLEN];
17863     char_u	*save_cpo;
17864     int		match;
17865     colnr_T	col = 0;
17866     int		keepempty = FALSE;
17867     int		typeerr = FALSE;
17868 
17869     /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
17870     save_cpo = p_cpo;
17871     p_cpo = (char_u *)"";
17872 
17873     str = get_tv_string(&argvars[0]);
17874     if (argvars[1].v_type != VAR_UNKNOWN)
17875     {
17876 	pat = get_tv_string_buf_chk(&argvars[1], patbuf);
17877 	if (pat == NULL)
17878 	    typeerr = TRUE;
17879 	if (argvars[2].v_type != VAR_UNKNOWN)
17880 	    keepempty = get_tv_number_chk(&argvars[2], &typeerr);
17881     }
17882     if (pat == NULL || *pat == NUL)
17883 	pat = (char_u *)"[\\x01- ]\\+";
17884 
17885     if (rettv_list_alloc(rettv) == FAIL)
17886 	return;
17887     if (typeerr)
17888 	return;
17889 
17890     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
17891     if (regmatch.regprog != NULL)
17892     {
17893 	regmatch.rm_ic = FALSE;
17894 	while (*str != NUL || keepempty)
17895 	{
17896 	    if (*str == NUL)
17897 		match = FALSE;	/* empty item at the end */
17898 	    else
17899 		match = vim_regexec_nl(&regmatch, str, col);
17900 	    if (match)
17901 		end = regmatch.startp[0];
17902 	    else
17903 		end = str + STRLEN(str);
17904 	    if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
17905 			   && *str != NUL && match && end < regmatch.endp[0]))
17906 	    {
17907 		if (list_append_string(rettv->vval.v_list, str,
17908 						    (int)(end - str)) == FAIL)
17909 		    break;
17910 	    }
17911 	    if (!match)
17912 		break;
17913 	    /* Advance to just after the match. */
17914 	    if (regmatch.endp[0] > str)
17915 		col = 0;
17916 	    else
17917 	    {
17918 		/* Don't get stuck at the same match. */
17919 #ifdef FEAT_MBYTE
17920 		col = (*mb_ptr2len)(regmatch.endp[0]);
17921 #else
17922 		col = 1;
17923 #endif
17924 	    }
17925 	    str = regmatch.endp[0];
17926 	}
17927 
17928 	vim_regfree(regmatch.regprog);
17929     }
17930 
17931     p_cpo = save_cpo;
17932 }
17933 
17934 #ifdef FEAT_FLOAT
17935 /*
17936  * "sqrt()" function
17937  */
17938     static void
17939 f_sqrt(argvars, rettv)
17940     typval_T	*argvars;
17941     typval_T	*rettv;
17942 {
17943     float_T	f;
17944 
17945     rettv->v_type = VAR_FLOAT;
17946     if (get_float_arg(argvars, &f) == OK)
17947 	rettv->vval.v_float = sqrt(f);
17948     else
17949 	rettv->vval.v_float = 0.0;
17950 }
17951 
17952 /*
17953  * "str2float()" function
17954  */
17955     static void
17956 f_str2float(argvars, rettv)
17957     typval_T	*argvars;
17958     typval_T	*rettv;
17959 {
17960     char_u *p = skipwhite(get_tv_string(&argvars[0]));
17961 
17962     if (*p == '+')
17963 	p = skipwhite(p + 1);
17964     (void)string2float(p, &rettv->vval.v_float);
17965     rettv->v_type = VAR_FLOAT;
17966 }
17967 #endif
17968 
17969 /*
17970  * "str2nr()" function
17971  */
17972     static void
17973 f_str2nr(argvars, rettv)
17974     typval_T	*argvars;
17975     typval_T	*rettv;
17976 {
17977     int		base = 10;
17978     char_u	*p;
17979     long	n;
17980 
17981     if (argvars[1].v_type != VAR_UNKNOWN)
17982     {
17983 	base = get_tv_number(&argvars[1]);
17984 	if (base != 8 && base != 10 && base != 16)
17985 	{
17986 	    EMSG(_(e_invarg));
17987 	    return;
17988 	}
17989     }
17990 
17991     p = skipwhite(get_tv_string(&argvars[0]));
17992     if (*p == '+')
17993 	p = skipwhite(p + 1);
17994     vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
17995     rettv->vval.v_number = n;
17996 }
17997 
17998 #ifdef HAVE_STRFTIME
17999 /*
18000  * "strftime({format}[, {time}])" function
18001  */
18002     static void
18003 f_strftime(argvars, rettv)
18004     typval_T	*argvars;
18005     typval_T	*rettv;
18006 {
18007     char_u	result_buf[256];
18008     struct tm	*curtime;
18009     time_t	seconds;
18010     char_u	*p;
18011 
18012     rettv->v_type = VAR_STRING;
18013 
18014     p = get_tv_string(&argvars[0]);
18015     if (argvars[1].v_type == VAR_UNKNOWN)
18016 	seconds = time(NULL);
18017     else
18018 	seconds = (time_t)get_tv_number(&argvars[1]);
18019     curtime = localtime(&seconds);
18020     /* MSVC returns NULL for an invalid value of seconds. */
18021     if (curtime == NULL)
18022 	rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
18023     else
18024     {
18025 # ifdef FEAT_MBYTE
18026 	vimconv_T   conv;
18027 	char_u	    *enc;
18028 
18029 	conv.vc_type = CONV_NONE;
18030 	enc = enc_locale();
18031 	convert_setup(&conv, p_enc, enc);
18032 	if (conv.vc_type != CONV_NONE)
18033 	    p = string_convert(&conv, p, NULL);
18034 # endif
18035 	if (p != NULL)
18036 	    (void)strftime((char *)result_buf, sizeof(result_buf),
18037 							  (char *)p, curtime);
18038 	else
18039 	    result_buf[0] = NUL;
18040 
18041 # ifdef FEAT_MBYTE
18042 	if (conv.vc_type != CONV_NONE)
18043 	    vim_free(p);
18044 	convert_setup(&conv, enc, p_enc);
18045 	if (conv.vc_type != CONV_NONE)
18046 	    rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
18047 	else
18048 # endif
18049 	    rettv->vval.v_string = vim_strsave(result_buf);
18050 
18051 # ifdef FEAT_MBYTE
18052 	/* Release conversion descriptors */
18053 	convert_setup(&conv, NULL, NULL);
18054 	vim_free(enc);
18055 # endif
18056     }
18057 }
18058 #endif
18059 
18060 /*
18061  * "stridx()" function
18062  */
18063     static void
18064 f_stridx(argvars, rettv)
18065     typval_T	*argvars;
18066     typval_T	*rettv;
18067 {
18068     char_u	buf[NUMBUFLEN];
18069     char_u	*needle;
18070     char_u	*haystack;
18071     char_u	*save_haystack;
18072     char_u	*pos;
18073     int		start_idx;
18074 
18075     needle = get_tv_string_chk(&argvars[1]);
18076     save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
18077     rettv->vval.v_number = -1;
18078     if (needle == NULL || haystack == NULL)
18079 	return;		/* type error; errmsg already given */
18080 
18081     if (argvars[2].v_type != VAR_UNKNOWN)
18082     {
18083 	int	    error = FALSE;
18084 
18085 	start_idx = get_tv_number_chk(&argvars[2], &error);
18086 	if (error || start_idx >= (int)STRLEN(haystack))
18087 	    return;
18088 	if (start_idx >= 0)
18089 	    haystack += start_idx;
18090     }
18091 
18092     pos	= (char_u *)strstr((char *)haystack, (char *)needle);
18093     if (pos != NULL)
18094 	rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
18095 }
18096 
18097 /*
18098  * "string()" function
18099  */
18100     static void
18101 f_string(argvars, rettv)
18102     typval_T	*argvars;
18103     typval_T	*rettv;
18104 {
18105     char_u	*tofree;
18106     char_u	numbuf[NUMBUFLEN];
18107 
18108     rettv->v_type = VAR_STRING;
18109     rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
18110     /* Make a copy if we have a value but it's not in allocated memory. */
18111     if (rettv->vval.v_string != NULL && tofree == NULL)
18112 	rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
18113 }
18114 
18115 /*
18116  * "strlen()" function
18117  */
18118     static void
18119 f_strlen(argvars, rettv)
18120     typval_T	*argvars;
18121     typval_T	*rettv;
18122 {
18123     rettv->vval.v_number = (varnumber_T)(STRLEN(
18124 					      get_tv_string(&argvars[0])));
18125 }
18126 
18127 /*
18128  * "strchars()" function
18129  */
18130     static void
18131 f_strchars(argvars, rettv)
18132     typval_T	*argvars;
18133     typval_T	*rettv;
18134 {
18135     char_u		*s = get_tv_string(&argvars[0]);
18136 #ifdef FEAT_MBYTE
18137     varnumber_T		len = 0;
18138 
18139     while (*s != NUL)
18140     {
18141 	mb_cptr2char_adv(&s);
18142 	++len;
18143     }
18144     rettv->vval.v_number = len;
18145 #else
18146     rettv->vval.v_number = (varnumber_T)(STRLEN(s));
18147 #endif
18148 }
18149 
18150 /*
18151  * "strdisplaywidth()" function
18152  */
18153     static void
18154 f_strdisplaywidth(argvars, rettv)
18155     typval_T	*argvars;
18156     typval_T	*rettv;
18157 {
18158     char_u	*s = get_tv_string(&argvars[0]);
18159     int		col = 0;
18160 
18161     if (argvars[1].v_type != VAR_UNKNOWN)
18162 	col = get_tv_number(&argvars[1]);
18163 
18164     rettv->vval.v_number = (varnumber_T)(linetabsize_col(col, s) - col);
18165 }
18166 
18167 /*
18168  * "strwidth()" function
18169  */
18170     static void
18171 f_strwidth(argvars, rettv)
18172     typval_T	*argvars;
18173     typval_T	*rettv;
18174 {
18175     char_u	*s = get_tv_string(&argvars[0]);
18176 
18177     rettv->vval.v_number = (varnumber_T)(
18178 #ifdef FEAT_MBYTE
18179 	    mb_string2cells(s, -1)
18180 #else
18181 	    STRLEN(s)
18182 #endif
18183 	    );
18184 }
18185 
18186 /*
18187  * "strpart()" function
18188  */
18189     static void
18190 f_strpart(argvars, rettv)
18191     typval_T	*argvars;
18192     typval_T	*rettv;
18193 {
18194     char_u	*p;
18195     int		n;
18196     int		len;
18197     int		slen;
18198     int		error = FALSE;
18199 
18200     p = get_tv_string(&argvars[0]);
18201     slen = (int)STRLEN(p);
18202 
18203     n = get_tv_number_chk(&argvars[1], &error);
18204     if (error)
18205 	len = 0;
18206     else if (argvars[2].v_type != VAR_UNKNOWN)
18207 	len = get_tv_number(&argvars[2]);
18208     else
18209 	len = slen - n;	    /* default len: all bytes that are available. */
18210 
18211     /*
18212      * Only return the overlap between the specified part and the actual
18213      * string.
18214      */
18215     if (n < 0)
18216     {
18217 	len += n;
18218 	n = 0;
18219     }
18220     else if (n > slen)
18221 	n = slen;
18222     if (len < 0)
18223 	len = 0;
18224     else if (n + len > slen)
18225 	len = slen - n;
18226 
18227     rettv->v_type = VAR_STRING;
18228     rettv->vval.v_string = vim_strnsave(p + n, len);
18229 }
18230 
18231 /*
18232  * "strridx()" function
18233  */
18234     static void
18235 f_strridx(argvars, rettv)
18236     typval_T	*argvars;
18237     typval_T	*rettv;
18238 {
18239     char_u	buf[NUMBUFLEN];
18240     char_u	*needle;
18241     char_u	*haystack;
18242     char_u	*rest;
18243     char_u	*lastmatch = NULL;
18244     int		haystack_len, end_idx;
18245 
18246     needle = get_tv_string_chk(&argvars[1]);
18247     haystack = get_tv_string_buf_chk(&argvars[0], buf);
18248 
18249     rettv->vval.v_number = -1;
18250     if (needle == NULL || haystack == NULL)
18251 	return;		/* type error; errmsg already given */
18252 
18253     haystack_len = (int)STRLEN(haystack);
18254     if (argvars[2].v_type != VAR_UNKNOWN)
18255     {
18256 	/* Third argument: upper limit for index */
18257 	end_idx = get_tv_number_chk(&argvars[2], NULL);
18258 	if (end_idx < 0)
18259 	    return;	/* can never find a match */
18260     }
18261     else
18262 	end_idx = haystack_len;
18263 
18264     if (*needle == NUL)
18265     {
18266 	/* Empty string matches past the end. */
18267 	lastmatch = haystack + end_idx;
18268     }
18269     else
18270     {
18271 	for (rest = haystack; *rest != '\0'; ++rest)
18272 	{
18273 	    rest = (char_u *)strstr((char *)rest, (char *)needle);
18274 	    if (rest == NULL || rest > haystack + end_idx)
18275 		break;
18276 	    lastmatch = rest;
18277 	}
18278     }
18279 
18280     if (lastmatch == NULL)
18281 	rettv->vval.v_number = -1;
18282     else
18283 	rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
18284 }
18285 
18286 /*
18287  * "strtrans()" function
18288  */
18289     static void
18290 f_strtrans(argvars, rettv)
18291     typval_T	*argvars;
18292     typval_T	*rettv;
18293 {
18294     rettv->v_type = VAR_STRING;
18295     rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
18296 }
18297 
18298 /*
18299  * "submatch()" function
18300  */
18301     static void
18302 f_submatch(argvars, rettv)
18303     typval_T	*argvars;
18304     typval_T	*rettv;
18305 {
18306     int		error = FALSE;
18307     int		no;
18308     int		retList = 0;
18309 
18310     no = (int)get_tv_number_chk(&argvars[0], &error);
18311     if (error)
18312 	return;
18313     error = FALSE;
18314     if (argvars[1].v_type != VAR_UNKNOWN)
18315 	retList = get_tv_number_chk(&argvars[1], &error);
18316     if (error)
18317 	return;
18318 
18319     if (retList == 0)
18320     {
18321 	rettv->v_type = VAR_STRING;
18322 	rettv->vval.v_string = reg_submatch(no);
18323     }
18324     else
18325     {
18326 	rettv->v_type = VAR_LIST;
18327 	rettv->vval.v_list = reg_submatch_list(no);
18328     }
18329 }
18330 
18331 /*
18332  * "substitute()" function
18333  */
18334     static void
18335 f_substitute(argvars, rettv)
18336     typval_T	*argvars;
18337     typval_T	*rettv;
18338 {
18339     char_u	patbuf[NUMBUFLEN];
18340     char_u	subbuf[NUMBUFLEN];
18341     char_u	flagsbuf[NUMBUFLEN];
18342 
18343     char_u	*str = get_tv_string_chk(&argvars[0]);
18344     char_u	*pat = get_tv_string_buf_chk(&argvars[1], patbuf);
18345     char_u	*sub = get_tv_string_buf_chk(&argvars[2], subbuf);
18346     char_u	*flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
18347 
18348     rettv->v_type = VAR_STRING;
18349     if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
18350 	rettv->vval.v_string = NULL;
18351     else
18352 	rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
18353 }
18354 
18355 /*
18356  * "synID(lnum, col, trans)" function
18357  */
18358     static void
18359 f_synID(argvars, rettv)
18360     typval_T	*argvars UNUSED;
18361     typval_T	*rettv;
18362 {
18363     int		id = 0;
18364 #ifdef FEAT_SYN_HL
18365     long	lnum;
18366     long	col;
18367     int		trans;
18368     int		transerr = FALSE;
18369 
18370     lnum = get_tv_lnum(argvars);		/* -1 on type error */
18371     col = get_tv_number(&argvars[1]) - 1;	/* -1 on type error */
18372     trans = get_tv_number_chk(&argvars[2], &transerr);
18373 
18374     if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
18375 	    && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
18376 	id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
18377 #endif
18378 
18379     rettv->vval.v_number = id;
18380 }
18381 
18382 /*
18383  * "synIDattr(id, what [, mode])" function
18384  */
18385     static void
18386 f_synIDattr(argvars, rettv)
18387     typval_T	*argvars UNUSED;
18388     typval_T	*rettv;
18389 {
18390     char_u	*p = NULL;
18391 #ifdef FEAT_SYN_HL
18392     int		id;
18393     char_u	*what;
18394     char_u	*mode;
18395     char_u	modebuf[NUMBUFLEN];
18396     int		modec;
18397 
18398     id = get_tv_number(&argvars[0]);
18399     what = get_tv_string(&argvars[1]);
18400     if (argvars[2].v_type != VAR_UNKNOWN)
18401     {
18402 	mode = get_tv_string_buf(&argvars[2], modebuf);
18403 	modec = TOLOWER_ASC(mode[0]);
18404 	if (modec != 't' && modec != 'c' && modec != 'g')
18405 	    modec = 0;	/* replace invalid with current */
18406     }
18407     else
18408     {
18409 #ifdef FEAT_GUI
18410 	if (gui.in_use)
18411 	    modec = 'g';
18412 	else
18413 #endif
18414 	    if (t_colors > 1)
18415 	    modec = 'c';
18416 	else
18417 	    modec = 't';
18418     }
18419 
18420 
18421     switch (TOLOWER_ASC(what[0]))
18422     {
18423 	case 'b':
18424 		if (TOLOWER_ASC(what[1]) == 'g')	/* bg[#] */
18425 		    p = highlight_color(id, what, modec);
18426 		else					/* bold */
18427 		    p = highlight_has_attr(id, HL_BOLD, modec);
18428 		break;
18429 
18430 	case 'f':					/* fg[#] or font */
18431 		p = highlight_color(id, what, modec);
18432 		break;
18433 
18434 	case 'i':
18435 		if (TOLOWER_ASC(what[1]) == 'n')	/* inverse */
18436 		    p = highlight_has_attr(id, HL_INVERSE, modec);
18437 		else					/* italic */
18438 		    p = highlight_has_attr(id, HL_ITALIC, modec);
18439 		break;
18440 
18441 	case 'n':					/* name */
18442 		p = get_highlight_name(NULL, id - 1);
18443 		break;
18444 
18445 	case 'r':					/* reverse */
18446 		p = highlight_has_attr(id, HL_INVERSE, modec);
18447 		break;
18448 
18449 	case 's':
18450 		if (TOLOWER_ASC(what[1]) == 'p')	/* sp[#] */
18451 		    p = highlight_color(id, what, modec);
18452 		else					/* standout */
18453 		    p = highlight_has_attr(id, HL_STANDOUT, modec);
18454 		break;
18455 
18456 	case 'u':
18457 		if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
18458 							/* underline */
18459 		    p = highlight_has_attr(id, HL_UNDERLINE, modec);
18460 		else
18461 							/* undercurl */
18462 		    p = highlight_has_attr(id, HL_UNDERCURL, modec);
18463 		break;
18464     }
18465 
18466     if (p != NULL)
18467 	p = vim_strsave(p);
18468 #endif
18469     rettv->v_type = VAR_STRING;
18470     rettv->vval.v_string = p;
18471 }
18472 
18473 /*
18474  * "synIDtrans(id)" function
18475  */
18476     static void
18477 f_synIDtrans(argvars, rettv)
18478     typval_T	*argvars UNUSED;
18479     typval_T	*rettv;
18480 {
18481     int		id;
18482 
18483 #ifdef FEAT_SYN_HL
18484     id = get_tv_number(&argvars[0]);
18485 
18486     if (id > 0)
18487 	id = syn_get_final_id(id);
18488     else
18489 #endif
18490 	id = 0;
18491 
18492     rettv->vval.v_number = id;
18493 }
18494 
18495 /*
18496  * "synconcealed(lnum, col)" function
18497  */
18498     static void
18499 f_synconcealed(argvars, rettv)
18500     typval_T	*argvars UNUSED;
18501     typval_T	*rettv;
18502 {
18503 #if defined(FEAT_SYN_HL) && defined(FEAT_CONCEAL)
18504     long	lnum;
18505     long	col;
18506     int		syntax_flags = 0;
18507     int		cchar;
18508     int		matchid = 0;
18509     char_u	str[NUMBUFLEN];
18510 #endif
18511 
18512     rettv->v_type = VAR_LIST;
18513     rettv->vval.v_list = NULL;
18514 
18515 #if defined(FEAT_SYN_HL) && defined(FEAT_CONCEAL)
18516     lnum = get_tv_lnum(argvars);		/* -1 on type error */
18517     col = get_tv_number(&argvars[1]) - 1;	/* -1 on type error */
18518 
18519     vim_memset(str, NUL, sizeof(str));
18520 
18521     if (rettv_list_alloc(rettv) != FAIL)
18522     {
18523 	if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
18524 	    && col >= 0 && col <= (long)STRLEN(ml_get(lnum))
18525 	    && curwin->w_p_cole > 0)
18526 	{
18527 	    (void)syn_get_id(curwin, lnum, col, FALSE, NULL, FALSE);
18528 	    syntax_flags = get_syntax_info(&matchid);
18529 
18530 	    /* get the conceal character */
18531 	    if ((syntax_flags & HL_CONCEAL) && curwin->w_p_cole < 3)
18532 	    {
18533 		cchar = syn_get_sub_char();
18534 		if (cchar == NUL && curwin->w_p_cole == 1 && lcs_conceal != NUL)
18535 		    cchar = lcs_conceal;
18536 		if (cchar != NUL)
18537 		{
18538 # ifdef FEAT_MBYTE
18539 		    if (has_mbyte)
18540 			(*mb_char2bytes)(cchar, str);
18541 		    else
18542 # endif
18543 			str[0] = cchar;
18544 		}
18545 	    }
18546 	}
18547 
18548 	list_append_number(rettv->vval.v_list,
18549 					    (syntax_flags & HL_CONCEAL) != 0);
18550 	/* -1 to auto-determine strlen */
18551 	list_append_string(rettv->vval.v_list, str, -1);
18552 	list_append_number(rettv->vval.v_list, matchid);
18553     }
18554 #endif
18555 }
18556 
18557 /*
18558  * "synstack(lnum, col)" function
18559  */
18560     static void
18561 f_synstack(argvars, rettv)
18562     typval_T	*argvars UNUSED;
18563     typval_T	*rettv;
18564 {
18565 #ifdef FEAT_SYN_HL
18566     long	lnum;
18567     long	col;
18568     int		i;
18569     int		id;
18570 #endif
18571 
18572     rettv->v_type = VAR_LIST;
18573     rettv->vval.v_list = NULL;
18574 
18575 #ifdef FEAT_SYN_HL
18576     lnum = get_tv_lnum(argvars);		/* -1 on type error */
18577     col = get_tv_number(&argvars[1]) - 1;	/* -1 on type error */
18578 
18579     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
18580 	    && col >= 0 && col <= (long)STRLEN(ml_get(lnum))
18581 	    && rettv_list_alloc(rettv) != FAIL)
18582     {
18583 	(void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
18584 	for (i = 0; ; ++i)
18585 	{
18586 	    id = syn_get_stack_item(i);
18587 	    if (id < 0)
18588 		break;
18589 	    if (list_append_number(rettv->vval.v_list, id) == FAIL)
18590 		break;
18591 	}
18592     }
18593 #endif
18594 }
18595 
18596     static void
18597 get_cmd_output_as_rettv(argvars, rettv, retlist)
18598     typval_T	*argvars;
18599     typval_T	*rettv;
18600     int		retlist;
18601 {
18602     char_u	*res = NULL;
18603     char_u	*p;
18604     char_u	*infile = NULL;
18605     char_u	buf[NUMBUFLEN];
18606     int		err = FALSE;
18607     FILE	*fd;
18608     list_T	*list = NULL;
18609     int		flags = SHELL_SILENT;
18610 
18611     rettv->v_type = VAR_STRING;
18612     rettv->vval.v_string = NULL;
18613     if (check_restricted() || check_secure())
18614 	goto errret;
18615 
18616     if (argvars[1].v_type != VAR_UNKNOWN)
18617     {
18618 	/*
18619 	 * Write the string to a temp file, to be used for input of the shell
18620 	 * command.
18621 	 */
18622 	if ((infile = vim_tempname('i')) == NULL)
18623 	{
18624 	    EMSG(_(e_notmp));
18625 	    goto errret;
18626 	}
18627 
18628 	fd = mch_fopen((char *)infile, WRITEBIN);
18629 	if (fd == NULL)
18630 	{
18631 	    EMSG2(_(e_notopen), infile);
18632 	    goto errret;
18633 	}
18634 	if (argvars[1].v_type == VAR_LIST)
18635 	{
18636 	    if (write_list(fd, argvars[1].vval.v_list, TRUE) == FAIL)
18637 		err = TRUE;
18638 	}
18639 	else
18640 	{
18641 	    size_t len;
18642 
18643 	    p = get_tv_string_buf_chk(&argvars[1], buf);
18644 	    if (p == NULL)
18645 	    {
18646 		fclose(fd);
18647 		goto errret;		/* type error; errmsg already given */
18648 	    }
18649 	    len = STRLEN(p);
18650 	    if (len > 0 && fwrite(p, len, 1, fd) != 1)
18651 		err = TRUE;
18652 	}
18653 	if (fclose(fd) != 0)
18654 	    err = TRUE;
18655 	if (err)
18656 	{
18657 	    EMSG(_("E677: Error writing temp file"));
18658 	    goto errret;
18659 	}
18660     }
18661 
18662     /* Omit SHELL_COOKED when invoked with ":silent".  Avoids that the shell
18663      * echoes typeahead, that messes up the display. */
18664     if (!msg_silent)
18665 	flags += SHELL_COOKED;
18666 
18667     if (retlist)
18668     {
18669 	int		len;
18670 	listitem_T	*li;
18671 	char_u		*s = NULL;
18672 	char_u		*start;
18673 	char_u		*end;
18674 	int		i;
18675 
18676 	res = get_cmd_output(get_tv_string(&argvars[0]), infile, flags, &len);
18677 	if (res == NULL)
18678 	    goto errret;
18679 
18680 	list = list_alloc();
18681 	if (list == NULL)
18682 	    goto errret;
18683 
18684 	for (i = 0; i < len; ++i)
18685 	{
18686 	    start = res + i;
18687 	    while (i < len && res[i] != NL)
18688 		++i;
18689 	    end = res + i;
18690 
18691 	    s = alloc((unsigned)(end - start + 1));
18692 	    if (s == NULL)
18693 		goto errret;
18694 
18695 	    for (p = s; start < end; ++p, ++start)
18696 		*p = *start == NUL ? NL : *start;
18697 	    *p = NUL;
18698 
18699 	    li = listitem_alloc();
18700 	    if (li == NULL)
18701 	    {
18702 		vim_free(s);
18703 		goto errret;
18704 	    }
18705 	    li->li_tv.v_type = VAR_STRING;
18706 	    li->li_tv.vval.v_string = s;
18707 	    list_append(list, li);
18708 	}
18709 
18710 	++list->lv_refcount;
18711 	rettv->v_type = VAR_LIST;
18712 	rettv->vval.v_list = list;
18713 	list = NULL;
18714     }
18715     else
18716     {
18717 	res = get_cmd_output(get_tv_string(&argvars[0]), infile, flags, NULL);
18718 #ifdef USE_CR
18719 	/* translate <CR> into <NL> */
18720 	if (res != NULL)
18721 	{
18722 	    char_u	*s;
18723 
18724 	    for (s = res; *s; ++s)
18725 	    {
18726 		if (*s == CAR)
18727 		    *s = NL;
18728 	    }
18729 	}
18730 #else
18731 # ifdef USE_CRNL
18732 	/* translate <CR><NL> into <NL> */
18733 	if (res != NULL)
18734 	{
18735 	    char_u	*s, *d;
18736 
18737 	    d = res;
18738 	    for (s = res; *s; ++s)
18739 	    {
18740 		if (s[0] == CAR && s[1] == NL)
18741 		    ++s;
18742 		*d++ = *s;
18743 	    }
18744 	    *d = NUL;
18745 	}
18746 # endif
18747 #endif
18748 	rettv->vval.v_string = res;
18749 	res = NULL;
18750     }
18751 
18752 errret:
18753     if (infile != NULL)
18754     {
18755 	mch_remove(infile);
18756 	vim_free(infile);
18757     }
18758     if (res != NULL)
18759 	vim_free(res);
18760     if (list != NULL)
18761 	list_free(list, TRUE);
18762 }
18763 
18764 /*
18765  * "system()" function
18766  */
18767     static void
18768 f_system(argvars, rettv)
18769     typval_T	*argvars;
18770     typval_T	*rettv;
18771 {
18772     get_cmd_output_as_rettv(argvars, rettv, FALSE);
18773 }
18774 
18775 /*
18776  * "systemlist()" function
18777  */
18778     static void
18779 f_systemlist(argvars, rettv)
18780     typval_T	*argvars;
18781     typval_T	*rettv;
18782 {
18783     get_cmd_output_as_rettv(argvars, rettv, TRUE);
18784 }
18785 
18786 /*
18787  * "tabpagebuflist()" function
18788  */
18789     static void
18790 f_tabpagebuflist(argvars, rettv)
18791     typval_T	*argvars UNUSED;
18792     typval_T	*rettv UNUSED;
18793 {
18794 #ifdef FEAT_WINDOWS
18795     tabpage_T	*tp;
18796     win_T	*wp = NULL;
18797 
18798     if (argvars[0].v_type == VAR_UNKNOWN)
18799 	wp = firstwin;
18800     else
18801     {
18802 	tp = find_tabpage((int)get_tv_number(&argvars[0]));
18803 	if (tp != NULL)
18804 	    wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
18805     }
18806     if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
18807     {
18808 	for (; wp != NULL; wp = wp->w_next)
18809 	    if (list_append_number(rettv->vval.v_list,
18810 						wp->w_buffer->b_fnum) == FAIL)
18811 		break;
18812     }
18813 #endif
18814 }
18815 
18816 
18817 /*
18818  * "tabpagenr()" function
18819  */
18820     static void
18821 f_tabpagenr(argvars, rettv)
18822     typval_T	*argvars UNUSED;
18823     typval_T	*rettv;
18824 {
18825     int		nr = 1;
18826 #ifdef FEAT_WINDOWS
18827     char_u	*arg;
18828 
18829     if (argvars[0].v_type != VAR_UNKNOWN)
18830     {
18831 	arg = get_tv_string_chk(&argvars[0]);
18832 	nr = 0;
18833 	if (arg != NULL)
18834 	{
18835 	    if (STRCMP(arg, "$") == 0)
18836 		nr = tabpage_index(NULL) - 1;
18837 	    else
18838 		EMSG2(_(e_invexpr2), arg);
18839 	}
18840     }
18841     else
18842 	nr = tabpage_index(curtab);
18843 #endif
18844     rettv->vval.v_number = nr;
18845 }
18846 
18847 
18848 #ifdef FEAT_WINDOWS
18849 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
18850 
18851 /*
18852  * Common code for tabpagewinnr() and winnr().
18853  */
18854     static int
18855 get_winnr(tp, argvar)
18856     tabpage_T	*tp;
18857     typval_T	*argvar;
18858 {
18859     win_T	*twin;
18860     int		nr = 1;
18861     win_T	*wp;
18862     char_u	*arg;
18863 
18864     twin = (tp == curtab) ? curwin : tp->tp_curwin;
18865     if (argvar->v_type != VAR_UNKNOWN)
18866     {
18867 	arg = get_tv_string_chk(argvar);
18868 	if (arg == NULL)
18869 	    nr = 0;		/* type error; errmsg already given */
18870 	else if (STRCMP(arg, "$") == 0)
18871 	    twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
18872 	else if (STRCMP(arg, "#") == 0)
18873 	{
18874 	    twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
18875 	    if (twin == NULL)
18876 		nr = 0;
18877 	}
18878 	else
18879 	{
18880 	    EMSG2(_(e_invexpr2), arg);
18881 	    nr = 0;
18882 	}
18883     }
18884 
18885     if (nr > 0)
18886 	for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
18887 					      wp != twin; wp = wp->w_next)
18888 	{
18889 	    if (wp == NULL)
18890 	    {
18891 		/* didn't find it in this tabpage */
18892 		nr = 0;
18893 		break;
18894 	    }
18895 	    ++nr;
18896 	}
18897     return nr;
18898 }
18899 #endif
18900 
18901 /*
18902  * "tabpagewinnr()" function
18903  */
18904     static void
18905 f_tabpagewinnr(argvars, rettv)
18906     typval_T	*argvars UNUSED;
18907     typval_T	*rettv;
18908 {
18909     int		nr = 1;
18910 #ifdef FEAT_WINDOWS
18911     tabpage_T	*tp;
18912 
18913     tp = find_tabpage((int)get_tv_number(&argvars[0]));
18914     if (tp == NULL)
18915 	nr = 0;
18916     else
18917 	nr = get_winnr(tp, &argvars[1]);
18918 #endif
18919     rettv->vval.v_number = nr;
18920 }
18921 
18922 
18923 /*
18924  * "tagfiles()" function
18925  */
18926     static void
18927 f_tagfiles(argvars, rettv)
18928     typval_T	*argvars UNUSED;
18929     typval_T	*rettv;
18930 {
18931     char_u	*fname;
18932     tagname_T	tn;
18933     int		first;
18934 
18935     if (rettv_list_alloc(rettv) == FAIL)
18936 	return;
18937     fname = alloc(MAXPATHL);
18938     if (fname == NULL)
18939 	return;
18940 
18941     for (first = TRUE; ; first = FALSE)
18942 	if (get_tagfname(&tn, first, fname) == FAIL
18943 		|| list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
18944 	    break;
18945     tagname_free(&tn);
18946     vim_free(fname);
18947 }
18948 
18949 /*
18950  * "taglist()" function
18951  */
18952     static void
18953 f_taglist(argvars, rettv)
18954     typval_T  *argvars;
18955     typval_T  *rettv;
18956 {
18957     char_u  *tag_pattern;
18958 
18959     tag_pattern = get_tv_string(&argvars[0]);
18960 
18961     rettv->vval.v_number = FALSE;
18962     if (*tag_pattern == NUL)
18963 	return;
18964 
18965     if (rettv_list_alloc(rettv) == OK)
18966 	(void)get_tags(rettv->vval.v_list, tag_pattern);
18967 }
18968 
18969 /*
18970  * "tempname()" function
18971  */
18972     static void
18973 f_tempname(argvars, rettv)
18974     typval_T	*argvars UNUSED;
18975     typval_T	*rettv;
18976 {
18977     static int	x = 'A';
18978 
18979     rettv->v_type = VAR_STRING;
18980     rettv->vval.v_string = vim_tempname(x);
18981 
18982     /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
18983      * names.  Skip 'I' and 'O', they are used for shell redirection. */
18984     do
18985     {
18986 	if (x == 'Z')
18987 	    x = '0';
18988 	else if (x == '9')
18989 	    x = 'A';
18990 	else
18991 	{
18992 #ifdef EBCDIC
18993 	    if (x == 'I')
18994 		x = 'J';
18995 	    else if (x == 'R')
18996 		x = 'S';
18997 	    else
18998 #endif
18999 		++x;
19000 	}
19001     } while (x == 'I' || x == 'O');
19002 }
19003 
19004 /*
19005  * "test(list)" function: Just checking the walls...
19006  */
19007     static void
19008 f_test(argvars, rettv)
19009     typval_T	*argvars UNUSED;
19010     typval_T	*rettv UNUSED;
19011 {
19012     /* Used for unit testing.  Change the code below to your liking. */
19013 #if 0
19014     listitem_T	*li;
19015     list_T	*l;
19016     char_u	*bad, *good;
19017 
19018     if (argvars[0].v_type != VAR_LIST)
19019 	return;
19020     l = argvars[0].vval.v_list;
19021     if (l == NULL)
19022 	return;
19023     li = l->lv_first;
19024     if (li == NULL)
19025 	return;
19026     bad = get_tv_string(&li->li_tv);
19027     li = li->li_next;
19028     if (li == NULL)
19029 	return;
19030     good = get_tv_string(&li->li_tv);
19031     rettv->vval.v_number = test_edit_score(bad, good);
19032 #endif
19033 }
19034 
19035 #ifdef FEAT_FLOAT
19036 /*
19037  * "tan()" function
19038  */
19039     static void
19040 f_tan(argvars, rettv)
19041     typval_T	*argvars;
19042     typval_T	*rettv;
19043 {
19044     float_T	f;
19045 
19046     rettv->v_type = VAR_FLOAT;
19047     if (get_float_arg(argvars, &f) == OK)
19048 	rettv->vval.v_float = tan(f);
19049     else
19050 	rettv->vval.v_float = 0.0;
19051 }
19052 
19053 /*
19054  * "tanh()" function
19055  */
19056     static void
19057 f_tanh(argvars, rettv)
19058     typval_T	*argvars;
19059     typval_T	*rettv;
19060 {
19061     float_T	f;
19062 
19063     rettv->v_type = VAR_FLOAT;
19064     if (get_float_arg(argvars, &f) == OK)
19065 	rettv->vval.v_float = tanh(f);
19066     else
19067 	rettv->vval.v_float = 0.0;
19068 }
19069 #endif
19070 
19071 /*
19072  * "tolower(string)" function
19073  */
19074     static void
19075 f_tolower(argvars, rettv)
19076     typval_T	*argvars;
19077     typval_T	*rettv;
19078 {
19079     char_u	*p;
19080 
19081     p = vim_strsave(get_tv_string(&argvars[0]));
19082     rettv->v_type = VAR_STRING;
19083     rettv->vval.v_string = p;
19084 
19085     if (p != NULL)
19086 	while (*p != NUL)
19087 	{
19088 #ifdef FEAT_MBYTE
19089 	    int		l;
19090 
19091 	    if (enc_utf8)
19092 	    {
19093 		int c, lc;
19094 
19095 		c = utf_ptr2char(p);
19096 		lc = utf_tolower(c);
19097 		l = utf_ptr2len(p);
19098 		/* TODO: reallocate string when byte count changes. */
19099 		if (utf_char2len(lc) == l)
19100 		    utf_char2bytes(lc, p);
19101 		p += l;
19102 	    }
19103 	    else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
19104 		p += l;		/* skip multi-byte character */
19105 	    else
19106 #endif
19107 	    {
19108 		*p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
19109 		++p;
19110 	    }
19111 	}
19112 }
19113 
19114 /*
19115  * "toupper(string)" function
19116  */
19117     static void
19118 f_toupper(argvars, rettv)
19119     typval_T	*argvars;
19120     typval_T	*rettv;
19121 {
19122     rettv->v_type = VAR_STRING;
19123     rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
19124 }
19125 
19126 /*
19127  * "tr(string, fromstr, tostr)" function
19128  */
19129     static void
19130 f_tr(argvars, rettv)
19131     typval_T	*argvars;
19132     typval_T	*rettv;
19133 {
19134     char_u	*in_str;
19135     char_u	*fromstr;
19136     char_u	*tostr;
19137     char_u	*p;
19138 #ifdef FEAT_MBYTE
19139     int		inlen;
19140     int		fromlen;
19141     int		tolen;
19142     int		idx;
19143     char_u	*cpstr;
19144     int		cplen;
19145     int		first = TRUE;
19146 #endif
19147     char_u	buf[NUMBUFLEN];
19148     char_u	buf2[NUMBUFLEN];
19149     garray_T	ga;
19150 
19151     in_str = get_tv_string(&argvars[0]);
19152     fromstr = get_tv_string_buf_chk(&argvars[1], buf);
19153     tostr = get_tv_string_buf_chk(&argvars[2], buf2);
19154 
19155     /* Default return value: empty string. */
19156     rettv->v_type = VAR_STRING;
19157     rettv->vval.v_string = NULL;
19158     if (fromstr == NULL || tostr == NULL)
19159 	    return;		/* type error; errmsg already given */
19160     ga_init2(&ga, (int)sizeof(char), 80);
19161 
19162 #ifdef FEAT_MBYTE
19163     if (!has_mbyte)
19164 #endif
19165 	/* not multi-byte: fromstr and tostr must be the same length */
19166 	if (STRLEN(fromstr) != STRLEN(tostr))
19167 	{
19168 #ifdef FEAT_MBYTE
19169 error:
19170 #endif
19171 	    EMSG2(_(e_invarg2), fromstr);
19172 	    ga_clear(&ga);
19173 	    return;
19174 	}
19175 
19176     /* fromstr and tostr have to contain the same number of chars */
19177     while (*in_str != NUL)
19178     {
19179 #ifdef FEAT_MBYTE
19180 	if (has_mbyte)
19181 	{
19182 	    inlen = (*mb_ptr2len)(in_str);
19183 	    cpstr = in_str;
19184 	    cplen = inlen;
19185 	    idx = 0;
19186 	    for (p = fromstr; *p != NUL; p += fromlen)
19187 	    {
19188 		fromlen = (*mb_ptr2len)(p);
19189 		if (fromlen == inlen && STRNCMP(in_str, p, inlen) == 0)
19190 		{
19191 		    for (p = tostr; *p != NUL; p += tolen)
19192 		    {
19193 			tolen = (*mb_ptr2len)(p);
19194 			if (idx-- == 0)
19195 			{
19196 			    cplen = tolen;
19197 			    cpstr = p;
19198 			    break;
19199 			}
19200 		    }
19201 		    if (*p == NUL)	/* tostr is shorter than fromstr */
19202 			goto error;
19203 		    break;
19204 		}
19205 		++idx;
19206 	    }
19207 
19208 	    if (first && cpstr == in_str)
19209 	    {
19210 		/* Check that fromstr and tostr have the same number of
19211 		 * (multi-byte) characters.  Done only once when a character
19212 		 * of in_str doesn't appear in fromstr. */
19213 		first = FALSE;
19214 		for (p = tostr; *p != NUL; p += tolen)
19215 		{
19216 		    tolen = (*mb_ptr2len)(p);
19217 		    --idx;
19218 		}
19219 		if (idx != 0)
19220 		    goto error;
19221 	    }
19222 
19223 	    ga_grow(&ga, cplen);
19224 	    mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
19225 	    ga.ga_len += cplen;
19226 
19227 	    in_str += inlen;
19228 	}
19229 	else
19230 #endif
19231 	{
19232 	    /* When not using multi-byte chars we can do it faster. */
19233 	    p = vim_strchr(fromstr, *in_str);
19234 	    if (p != NULL)
19235 		ga_append(&ga, tostr[p - fromstr]);
19236 	    else
19237 		ga_append(&ga, *in_str);
19238 	    ++in_str;
19239 	}
19240     }
19241 
19242     /* add a terminating NUL */
19243     ga_grow(&ga, 1);
19244     ga_append(&ga, NUL);
19245 
19246     rettv->vval.v_string = ga.ga_data;
19247 }
19248 
19249 #ifdef FEAT_FLOAT
19250 /*
19251  * "trunc({float})" function
19252  */
19253     static void
19254 f_trunc(argvars, rettv)
19255     typval_T	*argvars;
19256     typval_T	*rettv;
19257 {
19258     float_T	f;
19259 
19260     rettv->v_type = VAR_FLOAT;
19261     if (get_float_arg(argvars, &f) == OK)
19262 	/* trunc() is not in C90, use floor() or ceil() instead. */
19263 	rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
19264     else
19265 	rettv->vval.v_float = 0.0;
19266 }
19267 #endif
19268 
19269 /*
19270  * "type(expr)" function
19271  */
19272     static void
19273 f_type(argvars, rettv)
19274     typval_T	*argvars;
19275     typval_T	*rettv;
19276 {
19277     int n;
19278 
19279     switch (argvars[0].v_type)
19280     {
19281 	case VAR_NUMBER: n = 0; break;
19282 	case VAR_STRING: n = 1; break;
19283 	case VAR_FUNC:   n = 2; break;
19284 	case VAR_LIST:   n = 3; break;
19285 	case VAR_DICT:   n = 4; break;
19286 #ifdef FEAT_FLOAT
19287 	case VAR_FLOAT:  n = 5; break;
19288 #endif
19289 	default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
19290     }
19291     rettv->vval.v_number = n;
19292 }
19293 
19294 /*
19295  * "undofile(name)" function
19296  */
19297     static void
19298 f_undofile(argvars, rettv)
19299     typval_T	*argvars UNUSED;
19300     typval_T	*rettv;
19301 {
19302     rettv->v_type = VAR_STRING;
19303 #ifdef FEAT_PERSISTENT_UNDO
19304     {
19305 	char_u *fname = get_tv_string(&argvars[0]);
19306 
19307 	if (*fname == NUL)
19308 	{
19309 	    /* If there is no file name there will be no undo file. */
19310 	    rettv->vval.v_string = NULL;
19311 	}
19312 	else
19313 	{
19314 	    char_u *ffname = FullName_save(fname, FALSE);
19315 
19316 	    if (ffname != NULL)
19317 		rettv->vval.v_string = u_get_undo_file_name(ffname, FALSE);
19318 	    vim_free(ffname);
19319 	}
19320     }
19321 #else
19322     rettv->vval.v_string = NULL;
19323 #endif
19324 }
19325 
19326 /*
19327  * "undotree()" function
19328  */
19329     static void
19330 f_undotree(argvars, rettv)
19331     typval_T	*argvars UNUSED;
19332     typval_T	*rettv;
19333 {
19334     if (rettv_dict_alloc(rettv) == OK)
19335     {
19336 	dict_T *dict = rettv->vval.v_dict;
19337 	list_T *list;
19338 
19339 	dict_add_nr_str(dict, "synced", (long)curbuf->b_u_synced, NULL);
19340 	dict_add_nr_str(dict, "seq_last", curbuf->b_u_seq_last, NULL);
19341 	dict_add_nr_str(dict, "save_last",
19342 					(long)curbuf->b_u_save_nr_last, NULL);
19343 	dict_add_nr_str(dict, "seq_cur", curbuf->b_u_seq_cur, NULL);
19344 	dict_add_nr_str(dict, "time_cur", (long)curbuf->b_u_time_cur, NULL);
19345 	dict_add_nr_str(dict, "save_cur", (long)curbuf->b_u_save_nr_cur, NULL);
19346 
19347 	list = list_alloc();
19348 	if (list != NULL)
19349 	{
19350 	    u_eval_tree(curbuf->b_u_oldhead, list);
19351 	    dict_add_list(dict, "entries", list);
19352 	}
19353     }
19354 }
19355 
19356 /*
19357  * "values(dict)" function
19358  */
19359     static void
19360 f_values(argvars, rettv)
19361     typval_T	*argvars;
19362     typval_T	*rettv;
19363 {
19364     dict_list(argvars, rettv, 1);
19365 }
19366 
19367 /*
19368  * "virtcol(string)" function
19369  */
19370     static void
19371 f_virtcol(argvars, rettv)
19372     typval_T	*argvars;
19373     typval_T	*rettv;
19374 {
19375     colnr_T	vcol = 0;
19376     pos_T	*fp;
19377     int		fnum = curbuf->b_fnum;
19378 
19379     fp = var2fpos(&argvars[0], FALSE, &fnum);
19380     if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
19381 						    && fnum == curbuf->b_fnum)
19382     {
19383 	getvvcol(curwin, fp, NULL, NULL, &vcol);
19384 	++vcol;
19385     }
19386 
19387     rettv->vval.v_number = vcol;
19388 }
19389 
19390 /*
19391  * "visualmode()" function
19392  */
19393     static void
19394 f_visualmode(argvars, rettv)
19395     typval_T	*argvars UNUSED;
19396     typval_T	*rettv UNUSED;
19397 {
19398     char_u	str[2];
19399 
19400     rettv->v_type = VAR_STRING;
19401     str[0] = curbuf->b_visual_mode_eval;
19402     str[1] = NUL;
19403     rettv->vval.v_string = vim_strsave(str);
19404 
19405     /* A non-zero number or non-empty string argument: reset mode. */
19406     if (non_zero_arg(&argvars[0]))
19407 	curbuf->b_visual_mode_eval = NUL;
19408 }
19409 
19410 /*
19411  * "wildmenumode()" function
19412  */
19413     static void
19414 f_wildmenumode(argvars, rettv)
19415     typval_T	*argvars UNUSED;
19416     typval_T	*rettv UNUSED;
19417 {
19418 #ifdef FEAT_WILDMENU
19419     if (wild_menu_showing)
19420 	rettv->vval.v_number = 1;
19421 #endif
19422 }
19423 
19424 /*
19425  * "winbufnr(nr)" function
19426  */
19427     static void
19428 f_winbufnr(argvars, rettv)
19429     typval_T	*argvars;
19430     typval_T	*rettv;
19431 {
19432     win_T	*wp;
19433 
19434     wp = find_win_by_nr(&argvars[0], NULL);
19435     if (wp == NULL)
19436 	rettv->vval.v_number = -1;
19437     else
19438 	rettv->vval.v_number = wp->w_buffer->b_fnum;
19439 }
19440 
19441 /*
19442  * "wincol()" function
19443  */
19444     static void
19445 f_wincol(argvars, rettv)
19446     typval_T	*argvars UNUSED;
19447     typval_T	*rettv;
19448 {
19449     validate_cursor();
19450     rettv->vval.v_number = curwin->w_wcol + 1;
19451 }
19452 
19453 /*
19454  * "winheight(nr)" function
19455  */
19456     static void
19457 f_winheight(argvars, rettv)
19458     typval_T	*argvars;
19459     typval_T	*rettv;
19460 {
19461     win_T	*wp;
19462 
19463     wp = find_win_by_nr(&argvars[0], NULL);
19464     if (wp == NULL)
19465 	rettv->vval.v_number = -1;
19466     else
19467 	rettv->vval.v_number = wp->w_height;
19468 }
19469 
19470 /*
19471  * "winline()" function
19472  */
19473     static void
19474 f_winline(argvars, rettv)
19475     typval_T	*argvars UNUSED;
19476     typval_T	*rettv;
19477 {
19478     validate_cursor();
19479     rettv->vval.v_number = curwin->w_wrow + 1;
19480 }
19481 
19482 /*
19483  * "winnr()" function
19484  */
19485     static void
19486 f_winnr(argvars, rettv)
19487     typval_T	*argvars UNUSED;
19488     typval_T	*rettv;
19489 {
19490     int		nr = 1;
19491 
19492 #ifdef FEAT_WINDOWS
19493     nr = get_winnr(curtab, &argvars[0]);
19494 #endif
19495     rettv->vval.v_number = nr;
19496 }
19497 
19498 /*
19499  * "winrestcmd()" function
19500  */
19501     static void
19502 f_winrestcmd(argvars, rettv)
19503     typval_T	*argvars UNUSED;
19504     typval_T	*rettv;
19505 {
19506 #ifdef FEAT_WINDOWS
19507     win_T	*wp;
19508     int		winnr = 1;
19509     garray_T	ga;
19510     char_u	buf[50];
19511 
19512     ga_init2(&ga, (int)sizeof(char), 70);
19513     for (wp = firstwin; wp != NULL; wp = wp->w_next)
19514     {
19515 	sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
19516 	ga_concat(&ga, buf);
19517 # ifdef FEAT_VERTSPLIT
19518 	sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
19519 	ga_concat(&ga, buf);
19520 # endif
19521 	++winnr;
19522     }
19523     ga_append(&ga, NUL);
19524 
19525     rettv->vval.v_string = ga.ga_data;
19526 #else
19527     rettv->vval.v_string = NULL;
19528 #endif
19529     rettv->v_type = VAR_STRING;
19530 }
19531 
19532 /*
19533  * "winrestview()" function
19534  */
19535     static void
19536 f_winrestview(argvars, rettv)
19537     typval_T	*argvars;
19538     typval_T	*rettv UNUSED;
19539 {
19540     dict_T	*dict;
19541 
19542     if (argvars[0].v_type != VAR_DICT
19543 	    || (dict = argvars[0].vval.v_dict) == NULL)
19544 	EMSG(_(e_invarg));
19545     else
19546     {
19547 	if (dict_find(dict, (char_u *)"lnum", -1) != NULL)
19548 	    curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
19549 	if (dict_find(dict, (char_u *)"col", -1) != NULL)
19550 	    curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
19551 #ifdef FEAT_VIRTUALEDIT
19552 	if (dict_find(dict, (char_u *)"coladd", -1) != NULL)
19553 	    curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
19554 #endif
19555 	if (dict_find(dict, (char_u *)"curswant", -1) != NULL)
19556 	{
19557 	    curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
19558 	    curwin->w_set_curswant = FALSE;
19559 	}
19560 
19561 	if (dict_find(dict, (char_u *)"topline", -1) != NULL)
19562 	    set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
19563 #ifdef FEAT_DIFF
19564 	if (dict_find(dict, (char_u *)"topfill", -1) != NULL)
19565 	    curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
19566 #endif
19567 	if (dict_find(dict, (char_u *)"leftcol", -1) != NULL)
19568 	    curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
19569 	if (dict_find(dict, (char_u *)"skipcol", -1) != NULL)
19570 	    curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
19571 
19572 	check_cursor();
19573 	win_new_height(curwin, curwin->w_height);
19574 # ifdef FEAT_VERTSPLIT
19575 	win_new_width(curwin, W_WIDTH(curwin));
19576 # endif
19577 	changed_window_setting();
19578 
19579 	if (curwin->w_topline <= 0)
19580 	    curwin->w_topline = 1;
19581 	if (curwin->w_topline > curbuf->b_ml.ml_line_count)
19582 	    curwin->w_topline = curbuf->b_ml.ml_line_count;
19583 #ifdef FEAT_DIFF
19584 	check_topfill(curwin, TRUE);
19585 #endif
19586     }
19587 }
19588 
19589 /*
19590  * "winsaveview()" function
19591  */
19592     static void
19593 f_winsaveview(argvars, rettv)
19594     typval_T	*argvars UNUSED;
19595     typval_T	*rettv;
19596 {
19597     dict_T	*dict;
19598 
19599     if (rettv_dict_alloc(rettv) == FAIL)
19600 	return;
19601     dict = rettv->vval.v_dict;
19602 
19603     dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
19604     dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
19605 #ifdef FEAT_VIRTUALEDIT
19606     dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
19607 #endif
19608     update_curswant();
19609     dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
19610 
19611     dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
19612 #ifdef FEAT_DIFF
19613     dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
19614 #endif
19615     dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
19616     dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
19617 }
19618 
19619 /*
19620  * "winwidth(nr)" function
19621  */
19622     static void
19623 f_winwidth(argvars, rettv)
19624     typval_T	*argvars;
19625     typval_T	*rettv;
19626 {
19627     win_T	*wp;
19628 
19629     wp = find_win_by_nr(&argvars[0], NULL);
19630     if (wp == NULL)
19631 	rettv->vval.v_number = -1;
19632     else
19633 #ifdef FEAT_VERTSPLIT
19634 	rettv->vval.v_number = wp->w_width;
19635 #else
19636 	rettv->vval.v_number = Columns;
19637 #endif
19638 }
19639 
19640 /*
19641  * Write list of strings to file
19642  */
19643     static int
19644 write_list(fd, list, binary)
19645     FILE	*fd;
19646     list_T	*list;
19647     int		binary;
19648 {
19649     listitem_T	*li;
19650     int		c;
19651     int		ret = OK;
19652     char_u	*s;
19653 
19654     for (li = list->lv_first; li != NULL; li = li->li_next)
19655     {
19656 	for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
19657 	{
19658 	    if (*s == '\n')
19659 		c = putc(NUL, fd);
19660 	    else
19661 		c = putc(*s, fd);
19662 	    if (c == EOF)
19663 	    {
19664 		ret = FAIL;
19665 		break;
19666 	    }
19667 	}
19668 	if (!binary || li->li_next != NULL)
19669 	    if (putc('\n', fd) == EOF)
19670 	    {
19671 		ret = FAIL;
19672 		break;
19673 	    }
19674 	if (ret == FAIL)
19675 	{
19676 	    EMSG(_(e_write));
19677 	    break;
19678 	}
19679     }
19680     return ret;
19681 }
19682 
19683 /*
19684  * "writefile()" function
19685  */
19686     static void
19687 f_writefile(argvars, rettv)
19688     typval_T	*argvars;
19689     typval_T	*rettv;
19690 {
19691     int		binary = FALSE;
19692     char_u	*fname;
19693     FILE	*fd;
19694     int		ret = 0;
19695 
19696     if (check_restricted() || check_secure())
19697 	return;
19698 
19699     if (argvars[0].v_type != VAR_LIST)
19700     {
19701 	EMSG2(_(e_listarg), "writefile()");
19702 	return;
19703     }
19704     if (argvars[0].vval.v_list == NULL)
19705 	return;
19706 
19707     if (argvars[2].v_type != VAR_UNKNOWN
19708 			      && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
19709 	binary = TRUE;
19710 
19711     /* Always open the file in binary mode, library functions have a mind of
19712      * their own about CR-LF conversion. */
19713     fname = get_tv_string(&argvars[1]);
19714     if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
19715     {
19716 	EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
19717 	ret = -1;
19718     }
19719     else
19720     {
19721 	if (write_list(fd, argvars[0].vval.v_list, binary) == FAIL)
19722 	    ret = -1;
19723 	fclose(fd);
19724     }
19725 
19726     rettv->vval.v_number = ret;
19727 }
19728 
19729 /*
19730  * "xor(expr, expr)" function
19731  */
19732     static void
19733 f_xor(argvars, rettv)
19734     typval_T	*argvars;
19735     typval_T	*rettv;
19736 {
19737     rettv->vval.v_number = get_tv_number_chk(&argvars[0], NULL)
19738 					^ get_tv_number_chk(&argvars[1], NULL);
19739 }
19740 
19741 
19742 /*
19743  * Translate a String variable into a position.
19744  * Returns NULL when there is an error.
19745  */
19746     static pos_T *
19747 var2fpos(varp, dollar_lnum, fnum)
19748     typval_T	*varp;
19749     int		dollar_lnum;	/* TRUE when $ is last line */
19750     int		*fnum;		/* set to fnum for '0, 'A, etc. */
19751 {
19752     char_u		*name;
19753     static pos_T	pos;
19754     pos_T		*pp;
19755 
19756     /* Argument can be [lnum, col, coladd]. */
19757     if (varp->v_type == VAR_LIST)
19758     {
19759 	list_T		*l;
19760 	int		len;
19761 	int		error = FALSE;
19762 	listitem_T	*li;
19763 
19764 	l = varp->vval.v_list;
19765 	if (l == NULL)
19766 	    return NULL;
19767 
19768 	/* Get the line number */
19769 	pos.lnum = list_find_nr(l, 0L, &error);
19770 	if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
19771 	    return NULL;	/* invalid line number */
19772 
19773 	/* Get the column number */
19774 	pos.col = list_find_nr(l, 1L, &error);
19775 	if (error)
19776 	    return NULL;
19777 	len = (long)STRLEN(ml_get(pos.lnum));
19778 
19779 	/* We accept "$" for the column number: last column. */
19780 	li = list_find(l, 1L);
19781 	if (li != NULL && li->li_tv.v_type == VAR_STRING
19782 		&& li->li_tv.vval.v_string != NULL
19783 		&& STRCMP(li->li_tv.vval.v_string, "$") == 0)
19784 	    pos.col = len + 1;
19785 
19786 	/* Accept a position up to the NUL after the line. */
19787 	if (pos.col == 0 || (int)pos.col > len + 1)
19788 	    return NULL;	/* invalid column number */
19789 	--pos.col;
19790 
19791 #ifdef FEAT_VIRTUALEDIT
19792 	/* Get the virtual offset.  Defaults to zero. */
19793 	pos.coladd = list_find_nr(l, 2L, &error);
19794 	if (error)
19795 	    pos.coladd = 0;
19796 #endif
19797 
19798 	return &pos;
19799     }
19800 
19801     name = get_tv_string_chk(varp);
19802     if (name == NULL)
19803 	return NULL;
19804     if (name[0] == '.')				/* cursor */
19805 	return &curwin->w_cursor;
19806     if (name[0] == 'v' && name[1] == NUL)	/* Visual start */
19807     {
19808 	if (VIsual_active)
19809 	    return &VIsual;
19810 	return &curwin->w_cursor;
19811     }
19812     if (name[0] == '\'')			/* mark */
19813     {
19814 	pp = getmark_buf_fnum(curbuf, name[1], FALSE, fnum);
19815 	if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
19816 	    return NULL;
19817 	return pp;
19818     }
19819 
19820 #ifdef FEAT_VIRTUALEDIT
19821     pos.coladd = 0;
19822 #endif
19823 
19824     if (name[0] == 'w' && dollar_lnum)
19825     {
19826 	pos.col = 0;
19827 	if (name[1] == '0')		/* "w0": first visible line */
19828 	{
19829 	    update_topline();
19830 	    pos.lnum = curwin->w_topline;
19831 	    return &pos;
19832 	}
19833 	else if (name[1] == '$')	/* "w$": last visible line */
19834 	{
19835 	    validate_botline();
19836 	    pos.lnum = curwin->w_botline - 1;
19837 	    return &pos;
19838 	}
19839     }
19840     else if (name[0] == '$')		/* last column or line */
19841     {
19842 	if (dollar_lnum)
19843 	{
19844 	    pos.lnum = curbuf->b_ml.ml_line_count;
19845 	    pos.col = 0;
19846 	}
19847 	else
19848 	{
19849 	    pos.lnum = curwin->w_cursor.lnum;
19850 	    pos.col = (colnr_T)STRLEN(ml_get_curline());
19851 	}
19852 	return &pos;
19853     }
19854     return NULL;
19855 }
19856 
19857 /*
19858  * Convert list in "arg" into a position and optional file number.
19859  * When "fnump" is NULL there is no file number, only 3 items.
19860  * Note that the column is passed on as-is, the caller may want to decrement
19861  * it to use 1 for the first column.
19862  * Return FAIL when conversion is not possible, doesn't check the position for
19863  * validity.
19864  */
19865     static int
19866 list2fpos(arg, posp, fnump, curswantp)
19867     typval_T	*arg;
19868     pos_T	*posp;
19869     int		*fnump;
19870     colnr_T	*curswantp;
19871 {
19872     list_T	*l = arg->vval.v_list;
19873     long	i = 0;
19874     long	n;
19875 
19876     /* List must be: [fnum, lnum, col, coladd, curswant], where "fnum" is only
19877      * there when "fnump" isn't NULL; "coladd" and "curswant" are optional. */
19878     if (arg->v_type != VAR_LIST
19879 	    || l == NULL
19880 	    || l->lv_len < (fnump == NULL ? 2 : 3)
19881 	    || l->lv_len > (fnump == NULL ? 4 : 5))
19882 	return FAIL;
19883 
19884     if (fnump != NULL)
19885     {
19886 	n = list_find_nr(l, i++, NULL);	/* fnum */
19887 	if (n < 0)
19888 	    return FAIL;
19889 	if (n == 0)
19890 	    n = curbuf->b_fnum;		/* current buffer */
19891 	*fnump = n;
19892     }
19893 
19894     n = list_find_nr(l, i++, NULL);	/* lnum */
19895     if (n < 0)
19896 	return FAIL;
19897     posp->lnum = n;
19898 
19899     n = list_find_nr(l, i++, NULL);	/* col */
19900     if (n < 0)
19901 	return FAIL;
19902     posp->col = n;
19903 
19904 #ifdef FEAT_VIRTUALEDIT
19905     n = list_find_nr(l, i, NULL);	/* off */
19906     if (n < 0)
19907 	posp->coladd = 0;
19908     else
19909 	posp->coladd = n;
19910 #endif
19911 
19912     if (curswantp != NULL)
19913 	*curswantp = list_find_nr(l, i + 1, NULL);  /* curswant */
19914 
19915     return OK;
19916 }
19917 
19918 /*
19919  * Get the length of an environment variable name.
19920  * Advance "arg" to the first character after the name.
19921  * Return 0 for error.
19922  */
19923     static int
19924 get_env_len(arg)
19925     char_u	**arg;
19926 {
19927     char_u	*p;
19928     int		len;
19929 
19930     for (p = *arg; vim_isIDc(*p); ++p)
19931 	;
19932     if (p == *arg)	    /* no name found */
19933 	return 0;
19934 
19935     len = (int)(p - *arg);
19936     *arg = p;
19937     return len;
19938 }
19939 
19940 /*
19941  * Get the length of the name of a function or internal variable.
19942  * "arg" is advanced to the first non-white character after the name.
19943  * Return 0 if something is wrong.
19944  */
19945     static int
19946 get_id_len(arg)
19947     char_u	**arg;
19948 {
19949     char_u	*p;
19950     int		len;
19951 
19952     /* Find the end of the name. */
19953     for (p = *arg; eval_isnamec(*p); ++p)
19954 	;
19955     if (p == *arg)	    /* no name found */
19956 	return 0;
19957 
19958     len = (int)(p - *arg);
19959     *arg = skipwhite(p);
19960 
19961     return len;
19962 }
19963 
19964 /*
19965  * Get the length of the name of a variable or function.
19966  * Only the name is recognized, does not handle ".key" or "[idx]".
19967  * "arg" is advanced to the first non-white character after the name.
19968  * Return -1 if curly braces expansion failed.
19969  * Return 0 if something else is wrong.
19970  * If the name contains 'magic' {}'s, expand them and return the
19971  * expanded name in an allocated string via 'alias' - caller must free.
19972  */
19973     static int
19974 get_name_len(arg, alias, evaluate, verbose)
19975     char_u	**arg;
19976     char_u	**alias;
19977     int		evaluate;
19978     int		verbose;
19979 {
19980     int		len;
19981     char_u	*p;
19982     char_u	*expr_start;
19983     char_u	*expr_end;
19984 
19985     *alias = NULL;  /* default to no alias */
19986 
19987     if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
19988 						  && (*arg)[2] == (int)KE_SNR)
19989     {
19990 	/* hard coded <SNR>, already translated */
19991 	*arg += 3;
19992 	return get_id_len(arg) + 3;
19993     }
19994     len = eval_fname_script(*arg);
19995     if (len > 0)
19996     {
19997 	/* literal "<SID>", "s:" or "<SNR>" */
19998 	*arg += len;
19999     }
20000 
20001     /*
20002      * Find the end of the name; check for {} construction.
20003      */
20004     p = find_name_end(*arg, &expr_start, &expr_end,
20005 					       len > 0 ? 0 : FNE_CHECK_START);
20006     if (expr_start != NULL)
20007     {
20008 	char_u	*temp_string;
20009 
20010 	if (!evaluate)
20011 	{
20012 	    len += (int)(p - *arg);
20013 	    *arg = skipwhite(p);
20014 	    return len;
20015 	}
20016 
20017 	/*
20018 	 * Include any <SID> etc in the expanded string:
20019 	 * Thus the -len here.
20020 	 */
20021 	temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
20022 	if (temp_string == NULL)
20023 	    return -1;
20024 	*alias = temp_string;
20025 	*arg = skipwhite(p);
20026 	return (int)STRLEN(temp_string);
20027     }
20028 
20029     len += get_id_len(arg);
20030     if (len == 0 && verbose)
20031 	EMSG2(_(e_invexpr2), *arg);
20032 
20033     return len;
20034 }
20035 
20036 /*
20037  * Find the end of a variable or function name, taking care of magic braces.
20038  * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
20039  * start and end of the first magic braces item.
20040  * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
20041  * Return a pointer to just after the name.  Equal to "arg" if there is no
20042  * valid name.
20043  */
20044     static char_u *
20045 find_name_end(arg, expr_start, expr_end, flags)
20046     char_u	*arg;
20047     char_u	**expr_start;
20048     char_u	**expr_end;
20049     int		flags;
20050 {
20051     int		mb_nest = 0;
20052     int		br_nest = 0;
20053     char_u	*p;
20054 
20055     if (expr_start != NULL)
20056     {
20057 	*expr_start = NULL;
20058 	*expr_end = NULL;
20059     }
20060 
20061     /* Quick check for valid starting character. */
20062     if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
20063 	return arg;
20064 
20065     for (p = arg; *p != NUL
20066 		    && (eval_isnamec(*p)
20067 			|| *p == '{'
20068 			|| ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
20069 			|| mb_nest != 0
20070 			|| br_nest != 0); mb_ptr_adv(p))
20071     {
20072 	if (*p == '\'')
20073 	{
20074 	    /* skip over 'string' to avoid counting [ and ] inside it. */
20075 	    for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
20076 		;
20077 	    if (*p == NUL)
20078 		break;
20079 	}
20080 	else if (*p == '"')
20081 	{
20082 	    /* skip over "str\"ing" to avoid counting [ and ] inside it. */
20083 	    for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
20084 		if (*p == '\\' && p[1] != NUL)
20085 		    ++p;
20086 	    if (*p == NUL)
20087 		break;
20088 	}
20089 
20090 	if (mb_nest == 0)
20091 	{
20092 	    if (*p == '[')
20093 		++br_nest;
20094 	    else if (*p == ']')
20095 		--br_nest;
20096 	}
20097 
20098 	if (br_nest == 0)
20099 	{
20100 	    if (*p == '{')
20101 	    {
20102 		mb_nest++;
20103 		if (expr_start != NULL && *expr_start == NULL)
20104 		    *expr_start = p;
20105 	    }
20106 	    else if (*p == '}')
20107 	    {
20108 		mb_nest--;
20109 		if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
20110 		    *expr_end = p;
20111 	    }
20112 	}
20113     }
20114 
20115     return p;
20116 }
20117 
20118 /*
20119  * Expands out the 'magic' {}'s in a variable/function name.
20120  * Note that this can call itself recursively, to deal with
20121  * constructs like foo{bar}{baz}{bam}
20122  * The four pointer arguments point to "foo{expre}ss{ion}bar"
20123  *			"in_start"      ^
20124  *			"expr_start"	   ^
20125  *			"expr_end"		 ^
20126  *			"in_end"			    ^
20127  *
20128  * Returns a new allocated string, which the caller must free.
20129  * Returns NULL for failure.
20130  */
20131     static char_u *
20132 make_expanded_name(in_start, expr_start, expr_end, in_end)
20133     char_u	*in_start;
20134     char_u	*expr_start;
20135     char_u	*expr_end;
20136     char_u	*in_end;
20137 {
20138     char_u	c1;
20139     char_u	*retval = NULL;
20140     char_u	*temp_result;
20141     char_u	*nextcmd = NULL;
20142 
20143     if (expr_end == NULL || in_end == NULL)
20144 	return NULL;
20145     *expr_start	= NUL;
20146     *expr_end = NUL;
20147     c1 = *in_end;
20148     *in_end = NUL;
20149 
20150     temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
20151     if (temp_result != NULL && nextcmd == NULL)
20152     {
20153 	retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
20154 						   + (in_end - expr_end) + 1));
20155 	if (retval != NULL)
20156 	{
20157 	    STRCPY(retval, in_start);
20158 	    STRCAT(retval, temp_result);
20159 	    STRCAT(retval, expr_end + 1);
20160 	}
20161     }
20162     vim_free(temp_result);
20163 
20164     *in_end = c1;		/* put char back for error messages */
20165     *expr_start = '{';
20166     *expr_end = '}';
20167 
20168     if (retval != NULL)
20169     {
20170 	temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
20171 	if (expr_start != NULL)
20172 	{
20173 	    /* Further expansion! */
20174 	    temp_result = make_expanded_name(retval, expr_start,
20175 						       expr_end, temp_result);
20176 	    vim_free(retval);
20177 	    retval = temp_result;
20178 	}
20179     }
20180 
20181     return retval;
20182 }
20183 
20184 /*
20185  * Return TRUE if character "c" can be used in a variable or function name.
20186  * Does not include '{' or '}' for magic braces.
20187  */
20188     static int
20189 eval_isnamec(c)
20190     int	    c;
20191 {
20192     return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
20193 }
20194 
20195 /*
20196  * Return TRUE if character "c" can be used as the first character in a
20197  * variable or function name (excluding '{' and '}').
20198  */
20199     static int
20200 eval_isnamec1(c)
20201     int	    c;
20202 {
20203     return (ASCII_ISALPHA(c) || c == '_');
20204 }
20205 
20206 /*
20207  * Set number v: variable to "val".
20208  */
20209     void
20210 set_vim_var_nr(idx, val)
20211     int		idx;
20212     long	val;
20213 {
20214     vimvars[idx].vv_nr = val;
20215 }
20216 
20217 /*
20218  * Get number v: variable value.
20219  */
20220     long
20221 get_vim_var_nr(idx)
20222     int		idx;
20223 {
20224     return vimvars[idx].vv_nr;
20225 }
20226 
20227 /*
20228  * Get string v: variable value.  Uses a static buffer, can only be used once.
20229  */
20230     char_u *
20231 get_vim_var_str(idx)
20232     int		idx;
20233 {
20234     return get_tv_string(&vimvars[idx].vv_tv);
20235 }
20236 
20237 /*
20238  * Get List v: variable value.  Caller must take care of reference count when
20239  * needed.
20240  */
20241     list_T *
20242 get_vim_var_list(idx)
20243     int		idx;
20244 {
20245     return vimvars[idx].vv_list;
20246 }
20247 
20248 /*
20249  * Set v:char to character "c".
20250  */
20251     void
20252 set_vim_var_char(c)
20253     int c;
20254 {
20255     char_u	buf[MB_MAXBYTES + 1];
20256 
20257 #ifdef FEAT_MBYTE
20258     if (has_mbyte)
20259 	buf[(*mb_char2bytes)(c, buf)] = NUL;
20260     else
20261 #endif
20262     {
20263 	buf[0] = c;
20264 	buf[1] = NUL;
20265     }
20266     set_vim_var_string(VV_CHAR, buf, -1);
20267 }
20268 
20269 /*
20270  * Set v:count to "count" and v:count1 to "count1".
20271  * When "set_prevcount" is TRUE first set v:prevcount from v:count.
20272  */
20273     void
20274 set_vcount(count, count1, set_prevcount)
20275     long	count;
20276     long	count1;
20277     int		set_prevcount;
20278 {
20279     if (set_prevcount)
20280 	vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
20281     vimvars[VV_COUNT].vv_nr = count;
20282     vimvars[VV_COUNT1].vv_nr = count1;
20283 }
20284 
20285 /*
20286  * Set string v: variable to a copy of "val".
20287  */
20288     void
20289 set_vim_var_string(idx, val, len)
20290     int		idx;
20291     char_u	*val;
20292     int		len;	    /* length of "val" to use or -1 (whole string) */
20293 {
20294     /* Need to do this (at least) once, since we can't initialize a union.
20295      * Will always be invoked when "v:progname" is set. */
20296     vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
20297 
20298     vim_free(vimvars[idx].vv_str);
20299     if (val == NULL)
20300 	vimvars[idx].vv_str = NULL;
20301     else if (len == -1)
20302 	vimvars[idx].vv_str = vim_strsave(val);
20303     else
20304 	vimvars[idx].vv_str = vim_strnsave(val, len);
20305 }
20306 
20307 /*
20308  * Set List v: variable to "val".
20309  */
20310     void
20311 set_vim_var_list(idx, val)
20312     int		idx;
20313     list_T	*val;
20314 {
20315     list_unref(vimvars[idx].vv_list);
20316     vimvars[idx].vv_list = val;
20317     if (val != NULL)
20318 	++val->lv_refcount;
20319 }
20320 
20321 /*
20322  * Set v:register if needed.
20323  */
20324     void
20325 set_reg_var(c)
20326     int		c;
20327 {
20328     char_u	regname;
20329 
20330     if (c == 0 || c == ' ')
20331 	regname = '"';
20332     else
20333 	regname = c;
20334     /* Avoid free/alloc when the value is already right. */
20335     if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
20336 	set_vim_var_string(VV_REG, &regname, 1);
20337 }
20338 
20339 /*
20340  * Get or set v:exception.  If "oldval" == NULL, return the current value.
20341  * Otherwise, restore the value to "oldval" and return NULL.
20342  * Must always be called in pairs to save and restore v:exception!  Does not
20343  * take care of memory allocations.
20344  */
20345     char_u *
20346 v_exception(oldval)
20347     char_u	*oldval;
20348 {
20349     if (oldval == NULL)
20350 	return vimvars[VV_EXCEPTION].vv_str;
20351 
20352     vimvars[VV_EXCEPTION].vv_str = oldval;
20353     return NULL;
20354 }
20355 
20356 /*
20357  * Get or set v:throwpoint.  If "oldval" == NULL, return the current value.
20358  * Otherwise, restore the value to "oldval" and return NULL.
20359  * Must always be called in pairs to save and restore v:throwpoint!  Does not
20360  * take care of memory allocations.
20361  */
20362     char_u *
20363 v_throwpoint(oldval)
20364     char_u	*oldval;
20365 {
20366     if (oldval == NULL)
20367 	return vimvars[VV_THROWPOINT].vv_str;
20368 
20369     vimvars[VV_THROWPOINT].vv_str = oldval;
20370     return NULL;
20371 }
20372 
20373 #if defined(FEAT_AUTOCMD) || defined(PROTO)
20374 /*
20375  * Set v:cmdarg.
20376  * If "eap" != NULL, use "eap" to generate the value and return the old value.
20377  * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
20378  * Must always be called in pairs!
20379  */
20380     char_u *
20381 set_cmdarg(eap, oldarg)
20382     exarg_T	*eap;
20383     char_u	*oldarg;
20384 {
20385     char_u	*oldval;
20386     char_u	*newval;
20387     unsigned	len;
20388 
20389     oldval = vimvars[VV_CMDARG].vv_str;
20390     if (eap == NULL)
20391     {
20392 	vim_free(oldval);
20393 	vimvars[VV_CMDARG].vv_str = oldarg;
20394 	return NULL;
20395     }
20396 
20397     if (eap->force_bin == FORCE_BIN)
20398 	len = 6;
20399     else if (eap->force_bin == FORCE_NOBIN)
20400 	len = 8;
20401     else
20402 	len = 0;
20403 
20404     if (eap->read_edit)
20405 	len += 7;
20406 
20407     if (eap->force_ff != 0)
20408 	len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
20409 # ifdef FEAT_MBYTE
20410     if (eap->force_enc != 0)
20411 	len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
20412     if (eap->bad_char != 0)
20413 	len += 7 + 4;  /* " ++bad=" + "keep" or "drop" */
20414 # endif
20415 
20416     newval = alloc(len + 1);
20417     if (newval == NULL)
20418 	return NULL;
20419 
20420     if (eap->force_bin == FORCE_BIN)
20421 	sprintf((char *)newval, " ++bin");
20422     else if (eap->force_bin == FORCE_NOBIN)
20423 	sprintf((char *)newval, " ++nobin");
20424     else
20425 	*newval = NUL;
20426 
20427     if (eap->read_edit)
20428 	STRCAT(newval, " ++edit");
20429 
20430     if (eap->force_ff != 0)
20431 	sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
20432 						eap->cmd + eap->force_ff);
20433 # ifdef FEAT_MBYTE
20434     if (eap->force_enc != 0)
20435 	sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
20436 					       eap->cmd + eap->force_enc);
20437     if (eap->bad_char == BAD_KEEP)
20438 	STRCPY(newval + STRLEN(newval), " ++bad=keep");
20439     else if (eap->bad_char == BAD_DROP)
20440 	STRCPY(newval + STRLEN(newval), " ++bad=drop");
20441     else if (eap->bad_char != 0)
20442 	sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
20443 # endif
20444     vimvars[VV_CMDARG].vv_str = newval;
20445     return oldval;
20446 }
20447 #endif
20448 
20449 /*
20450  * Get the value of internal variable "name".
20451  * Return OK or FAIL.
20452  */
20453     static int
20454 get_var_tv(name, len, rettv, verbose, no_autoload)
20455     char_u	*name;
20456     int		len;		/* length of "name" */
20457     typval_T	*rettv;		/* NULL when only checking existence */
20458     int		verbose;	/* may give error message */
20459     int		no_autoload;	/* do not use script autoloading */
20460 {
20461     int		ret = OK;
20462     typval_T	*tv = NULL;
20463     typval_T	atv;
20464     dictitem_T	*v;
20465     int		cc;
20466 
20467     /* truncate the name, so that we can use strcmp() */
20468     cc = name[len];
20469     name[len] = NUL;
20470 
20471     /*
20472      * Check for "b:changedtick".
20473      */
20474     if (STRCMP(name, "b:changedtick") == 0)
20475     {
20476 	atv.v_type = VAR_NUMBER;
20477 	atv.vval.v_number = curbuf->b_changedtick;
20478 	tv = &atv;
20479     }
20480 
20481     /*
20482      * Check for user-defined variables.
20483      */
20484     else
20485     {
20486 	v = find_var(name, NULL, no_autoload);
20487 	if (v != NULL)
20488 	    tv = &v->di_tv;
20489     }
20490 
20491     if (tv == NULL)
20492     {
20493 	if (rettv != NULL && verbose)
20494 	    EMSG2(_(e_undefvar), name);
20495 	ret = FAIL;
20496     }
20497     else if (rettv != NULL)
20498 	copy_tv(tv, rettv);
20499 
20500     name[len] = cc;
20501 
20502     return ret;
20503 }
20504 
20505 /*
20506  * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
20507  * Also handle function call with Funcref variable: func(expr)
20508  * Can all be combined: dict.func(expr)[idx]['func'](expr)
20509  */
20510     static int
20511 handle_subscript(arg, rettv, evaluate, verbose)
20512     char_u	**arg;
20513     typval_T	*rettv;
20514     int		evaluate;	/* do more than finding the end */
20515     int		verbose;	/* give error messages */
20516 {
20517     int		ret = OK;
20518     dict_T	*selfdict = NULL;
20519     char_u	*s;
20520     int		len;
20521     typval_T	functv;
20522 
20523     while (ret == OK
20524 	    && (**arg == '['
20525 		|| (**arg == '.' && rettv->v_type == VAR_DICT)
20526 		|| (**arg == '(' && (!evaluate || rettv->v_type == VAR_FUNC)))
20527 	    && !vim_iswhite(*(*arg - 1)))
20528     {
20529 	if (**arg == '(')
20530 	{
20531 	    /* need to copy the funcref so that we can clear rettv */
20532 	    if (evaluate)
20533 	    {
20534 		functv = *rettv;
20535 		rettv->v_type = VAR_UNKNOWN;
20536 
20537 		/* Invoke the function.  Recursive! */
20538 		s = functv.vval.v_string;
20539 	    }
20540 	    else
20541 		s = (char_u *)"";
20542 	    ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
20543 			curwin->w_cursor.lnum, curwin->w_cursor.lnum,
20544 			&len, evaluate, selfdict);
20545 
20546 	    /* Clear the funcref afterwards, so that deleting it while
20547 	     * evaluating the arguments is possible (see test55). */
20548 	    if (evaluate)
20549 		clear_tv(&functv);
20550 
20551 	    /* Stop the expression evaluation when immediately aborting on
20552 	     * error, or when an interrupt occurred or an exception was thrown
20553 	     * but not caught. */
20554 	    if (aborting())
20555 	    {
20556 		if (ret == OK)
20557 		    clear_tv(rettv);
20558 		ret = FAIL;
20559 	    }
20560 	    dict_unref(selfdict);
20561 	    selfdict = NULL;
20562 	}
20563 	else /* **arg == '[' || **arg == '.' */
20564 	{
20565 	    dict_unref(selfdict);
20566 	    if (rettv->v_type == VAR_DICT)
20567 	    {
20568 		selfdict = rettv->vval.v_dict;
20569 		if (selfdict != NULL)
20570 		    ++selfdict->dv_refcount;
20571 	    }
20572 	    else
20573 		selfdict = NULL;
20574 	    if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
20575 	    {
20576 		clear_tv(rettv);
20577 		ret = FAIL;
20578 	    }
20579 	}
20580     }
20581     dict_unref(selfdict);
20582     return ret;
20583 }
20584 
20585 /*
20586  * Allocate memory for a variable type-value, and make it empty (0 or NULL
20587  * value).
20588  */
20589     static typval_T *
20590 alloc_tv()
20591 {
20592     return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
20593 }
20594 
20595 /*
20596  * Allocate memory for a variable type-value, and assign a string to it.
20597  * The string "s" must have been allocated, it is consumed.
20598  * Return NULL for out of memory, the variable otherwise.
20599  */
20600     static typval_T *
20601 alloc_string_tv(s)
20602     char_u	*s;
20603 {
20604     typval_T	*rettv;
20605 
20606     rettv = alloc_tv();
20607     if (rettv != NULL)
20608     {
20609 	rettv->v_type = VAR_STRING;
20610 	rettv->vval.v_string = s;
20611     }
20612     else
20613 	vim_free(s);
20614     return rettv;
20615 }
20616 
20617 /*
20618  * Free the memory for a variable type-value.
20619  */
20620     void
20621 free_tv(varp)
20622     typval_T *varp;
20623 {
20624     if (varp != NULL)
20625     {
20626 	switch (varp->v_type)
20627 	{
20628 	    case VAR_FUNC:
20629 		func_unref(varp->vval.v_string);
20630 		/*FALLTHROUGH*/
20631 	    case VAR_STRING:
20632 		vim_free(varp->vval.v_string);
20633 		break;
20634 	    case VAR_LIST:
20635 		list_unref(varp->vval.v_list);
20636 		break;
20637 	    case VAR_DICT:
20638 		dict_unref(varp->vval.v_dict);
20639 		break;
20640 	    case VAR_NUMBER:
20641 #ifdef FEAT_FLOAT
20642 	    case VAR_FLOAT:
20643 #endif
20644 	    case VAR_UNKNOWN:
20645 		break;
20646 	    default:
20647 		EMSG2(_(e_intern2), "free_tv()");
20648 		break;
20649 	}
20650 	vim_free(varp);
20651     }
20652 }
20653 
20654 /*
20655  * Free the memory for a variable value and set the value to NULL or 0.
20656  */
20657     void
20658 clear_tv(varp)
20659     typval_T *varp;
20660 {
20661     if (varp != NULL)
20662     {
20663 	switch (varp->v_type)
20664 	{
20665 	    case VAR_FUNC:
20666 		func_unref(varp->vval.v_string);
20667 		/*FALLTHROUGH*/
20668 	    case VAR_STRING:
20669 		vim_free(varp->vval.v_string);
20670 		varp->vval.v_string = NULL;
20671 		break;
20672 	    case VAR_LIST:
20673 		list_unref(varp->vval.v_list);
20674 		varp->vval.v_list = NULL;
20675 		break;
20676 	    case VAR_DICT:
20677 		dict_unref(varp->vval.v_dict);
20678 		varp->vval.v_dict = NULL;
20679 		break;
20680 	    case VAR_NUMBER:
20681 		varp->vval.v_number = 0;
20682 		break;
20683 #ifdef FEAT_FLOAT
20684 	    case VAR_FLOAT:
20685 		varp->vval.v_float = 0.0;
20686 		break;
20687 #endif
20688 	    case VAR_UNKNOWN:
20689 		break;
20690 	    default:
20691 		EMSG2(_(e_intern2), "clear_tv()");
20692 	}
20693 	varp->v_lock = 0;
20694     }
20695 }
20696 
20697 /*
20698  * Set the value of a variable to NULL without freeing items.
20699  */
20700     static void
20701 init_tv(varp)
20702     typval_T *varp;
20703 {
20704     if (varp != NULL)
20705 	vim_memset(varp, 0, sizeof(typval_T));
20706 }
20707 
20708 /*
20709  * Get the number value of a variable.
20710  * If it is a String variable, uses vim_str2nr().
20711  * For incompatible types, return 0.
20712  * get_tv_number_chk() is similar to get_tv_number(), but informs the
20713  * caller of incompatible types: it sets *denote to TRUE if "denote"
20714  * is not NULL or returns -1 otherwise.
20715  */
20716     static long
20717 get_tv_number(varp)
20718     typval_T	*varp;
20719 {
20720     int		error = FALSE;
20721 
20722     return get_tv_number_chk(varp, &error);	/* return 0L on error */
20723 }
20724 
20725     long
20726 get_tv_number_chk(varp, denote)
20727     typval_T	*varp;
20728     int		*denote;
20729 {
20730     long	n = 0L;
20731 
20732     switch (varp->v_type)
20733     {
20734 	case VAR_NUMBER:
20735 	    return (long)(varp->vval.v_number);
20736 #ifdef FEAT_FLOAT
20737 	case VAR_FLOAT:
20738 	    EMSG(_("E805: Using a Float as a Number"));
20739 	    break;
20740 #endif
20741 	case VAR_FUNC:
20742 	    EMSG(_("E703: Using a Funcref as a Number"));
20743 	    break;
20744 	case VAR_STRING:
20745 	    if (varp->vval.v_string != NULL)
20746 		vim_str2nr(varp->vval.v_string, NULL, NULL,
20747 							TRUE, TRUE, &n, NULL);
20748 	    return n;
20749 	case VAR_LIST:
20750 	    EMSG(_("E745: Using a List as a Number"));
20751 	    break;
20752 	case VAR_DICT:
20753 	    EMSG(_("E728: Using a Dictionary as a Number"));
20754 	    break;
20755 	default:
20756 	    EMSG2(_(e_intern2), "get_tv_number()");
20757 	    break;
20758     }
20759     if (denote == NULL)		/* useful for values that must be unsigned */
20760 	n = -1;
20761     else
20762 	*denote = TRUE;
20763     return n;
20764 }
20765 
20766 /*
20767  * Get the lnum from the first argument.
20768  * Also accepts ".", "$", etc., but that only works for the current buffer.
20769  * Returns -1 on error.
20770  */
20771     static linenr_T
20772 get_tv_lnum(argvars)
20773     typval_T	*argvars;
20774 {
20775     typval_T	rettv;
20776     linenr_T	lnum;
20777 
20778     lnum = get_tv_number_chk(&argvars[0], NULL);
20779     if (lnum == 0)  /* no valid number, try using line() */
20780     {
20781 	rettv.v_type = VAR_NUMBER;
20782 	f_line(argvars, &rettv);
20783 	lnum = rettv.vval.v_number;
20784 	clear_tv(&rettv);
20785     }
20786     return lnum;
20787 }
20788 
20789 /*
20790  * Get the lnum from the first argument.
20791  * Also accepts "$", then "buf" is used.
20792  * Returns 0 on error.
20793  */
20794     static linenr_T
20795 get_tv_lnum_buf(argvars, buf)
20796     typval_T	*argvars;
20797     buf_T	*buf;
20798 {
20799     if (argvars[0].v_type == VAR_STRING
20800 	    && argvars[0].vval.v_string != NULL
20801 	    && argvars[0].vval.v_string[0] == '$'
20802 	    && buf != NULL)
20803 	return buf->b_ml.ml_line_count;
20804     return get_tv_number_chk(&argvars[0], NULL);
20805 }
20806 
20807 /*
20808  * Get the string value of a variable.
20809  * If it is a Number variable, the number is converted into a string.
20810  * get_tv_string() uses a single, static buffer.  YOU CAN ONLY USE IT ONCE!
20811  * get_tv_string_buf() uses a given buffer.
20812  * If the String variable has never been set, return an empty string.
20813  * Never returns NULL;
20814  * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
20815  * NULL on error.
20816  */
20817     static char_u *
20818 get_tv_string(varp)
20819     typval_T	*varp;
20820 {
20821     static char_u   mybuf[NUMBUFLEN];
20822 
20823     return get_tv_string_buf(varp, mybuf);
20824 }
20825 
20826     static char_u *
20827 get_tv_string_buf(varp, buf)
20828     typval_T	*varp;
20829     char_u	*buf;
20830 {
20831     char_u	*res =  get_tv_string_buf_chk(varp, buf);
20832 
20833     return res != NULL ? res : (char_u *)"";
20834 }
20835 
20836 /*
20837  * Careful: This uses a single, static buffer.  YOU CAN ONLY USE IT ONCE!
20838  */
20839     char_u *
20840 get_tv_string_chk(varp)
20841     typval_T	*varp;
20842 {
20843     static char_u   mybuf[NUMBUFLEN];
20844 
20845     return get_tv_string_buf_chk(varp, mybuf);
20846 }
20847 
20848     static char_u *
20849 get_tv_string_buf_chk(varp, buf)
20850     typval_T	*varp;
20851     char_u	*buf;
20852 {
20853     switch (varp->v_type)
20854     {
20855 	case VAR_NUMBER:
20856 	    sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
20857 	    return buf;
20858 	case VAR_FUNC:
20859 	    EMSG(_("E729: using Funcref as a String"));
20860 	    break;
20861 	case VAR_LIST:
20862 	    EMSG(_("E730: using List as a String"));
20863 	    break;
20864 	case VAR_DICT:
20865 	    EMSG(_("E731: using Dictionary as a String"));
20866 	    break;
20867 #ifdef FEAT_FLOAT
20868 	case VAR_FLOAT:
20869 	    EMSG(_(e_float_as_string));
20870 	    break;
20871 #endif
20872 	case VAR_STRING:
20873 	    if (varp->vval.v_string != NULL)
20874 		return varp->vval.v_string;
20875 	    return (char_u *)"";
20876 	default:
20877 	    EMSG2(_(e_intern2), "get_tv_string_buf()");
20878 	    break;
20879     }
20880     return NULL;
20881 }
20882 
20883 /*
20884  * Find variable "name" in the list of variables.
20885  * Return a pointer to it if found, NULL if not found.
20886  * Careful: "a:0" variables don't have a name.
20887  * When "htp" is not NULL we are writing to the variable, set "htp" to the
20888  * hashtab_T used.
20889  */
20890     static dictitem_T *
20891 find_var(name, htp, no_autoload)
20892     char_u	*name;
20893     hashtab_T	**htp;
20894     int		no_autoload;
20895 {
20896     char_u	*varname;
20897     hashtab_T	*ht;
20898 
20899     ht = find_var_ht(name, &varname);
20900     if (htp != NULL)
20901 	*htp = ht;
20902     if (ht == NULL)
20903 	return NULL;
20904     return find_var_in_ht(ht, *name, varname, no_autoload || htp != NULL);
20905 }
20906 
20907 /*
20908  * Find variable "varname" in hashtab "ht" with name "htname".
20909  * Returns NULL if not found.
20910  */
20911     static dictitem_T *
20912 find_var_in_ht(ht, htname, varname, no_autoload)
20913     hashtab_T	*ht;
20914     int		htname;
20915     char_u	*varname;
20916     int		no_autoload;
20917 {
20918     hashitem_T	*hi;
20919 
20920     if (*varname == NUL)
20921     {
20922 	/* Must be something like "s:", otherwise "ht" would be NULL. */
20923 	switch (htname)
20924 	{
20925 	    case 's': return &SCRIPT_SV(current_SID)->sv_var;
20926 	    case 'g': return &globvars_var;
20927 	    case 'v': return &vimvars_var;
20928 	    case 'b': return &curbuf->b_bufvar;
20929 	    case 'w': return &curwin->w_winvar;
20930 #ifdef FEAT_WINDOWS
20931 	    case 't': return &curtab->tp_winvar;
20932 #endif
20933 	    case 'l': return current_funccal == NULL
20934 					? NULL : &current_funccal->l_vars_var;
20935 	    case 'a': return current_funccal == NULL
20936 				       ? NULL : &current_funccal->l_avars_var;
20937 	}
20938 	return NULL;
20939     }
20940 
20941     hi = hash_find(ht, varname);
20942     if (HASHITEM_EMPTY(hi))
20943     {
20944 	/* For global variables we may try auto-loading the script.  If it
20945 	 * worked find the variable again.  Don't auto-load a script if it was
20946 	 * loaded already, otherwise it would be loaded every time when
20947 	 * checking if a function name is a Funcref variable. */
20948 	if (ht == &globvarht && !no_autoload)
20949 	{
20950 	    /* Note: script_autoload() may make "hi" invalid. It must either
20951 	     * be obtained again or not used. */
20952 	    if (!script_autoload(varname, FALSE) || aborting())
20953 		return NULL;
20954 	    hi = hash_find(ht, varname);
20955 	}
20956 	if (HASHITEM_EMPTY(hi))
20957 	    return NULL;
20958     }
20959     return HI2DI(hi);
20960 }
20961 
20962 /*
20963  * Find the hashtab used for a variable name.
20964  * Set "varname" to the start of name without ':'.
20965  */
20966     static hashtab_T *
20967 find_var_ht(name, varname)
20968     char_u  *name;
20969     char_u  **varname;
20970 {
20971     hashitem_T	*hi;
20972 
20973     if (name[1] != ':')
20974     {
20975 	/* The name must not start with a colon or #. */
20976 	if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
20977 	    return NULL;
20978 	*varname = name;
20979 
20980 	/* "version" is "v:version" in all scopes */
20981 	hi = hash_find(&compat_hashtab, name);
20982 	if (!HASHITEM_EMPTY(hi))
20983 	    return &compat_hashtab;
20984 
20985 	if (current_funccal == NULL)
20986 	    return &globvarht;			/* global variable */
20987 	return &current_funccal->l_vars.dv_hashtab; /* l: variable */
20988     }
20989     *varname = name + 2;
20990     if (*name == 'g')				/* global variable */
20991 	return &globvarht;
20992     /* There must be no ':' or '#' in the rest of the name, unless g: is used
20993      */
20994     if (vim_strchr(name + 2, ':') != NULL
20995 			       || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
20996 	return NULL;
20997     if (*name == 'b')				/* buffer variable */
20998 	return &curbuf->b_vars->dv_hashtab;
20999     if (*name == 'w')				/* window variable */
21000 	return &curwin->w_vars->dv_hashtab;
21001 #ifdef FEAT_WINDOWS
21002     if (*name == 't')				/* tab page variable */
21003 	return &curtab->tp_vars->dv_hashtab;
21004 #endif
21005     if (*name == 'v')				/* v: variable */
21006 	return &vimvarht;
21007     if (*name == 'a' && current_funccal != NULL) /* function argument */
21008 	return &current_funccal->l_avars.dv_hashtab;
21009     if (*name == 'l' && current_funccal != NULL) /* local function variable */
21010 	return &current_funccal->l_vars.dv_hashtab;
21011     if (*name == 's'				/* script variable */
21012 	    && current_SID > 0 && current_SID <= ga_scripts.ga_len)
21013 	return &SCRIPT_VARS(current_SID);
21014     return NULL;
21015 }
21016 
21017 /*
21018  * Get the string value of a (global/local) variable.
21019  * Note: see get_tv_string() for how long the pointer remains valid.
21020  * Returns NULL when it doesn't exist.
21021  */
21022     char_u *
21023 get_var_value(name)
21024     char_u	*name;
21025 {
21026     dictitem_T	*v;
21027 
21028     v = find_var(name, NULL, FALSE);
21029     if (v == NULL)
21030 	return NULL;
21031     return get_tv_string(&v->di_tv);
21032 }
21033 
21034 /*
21035  * Allocate a new hashtab for a sourced script.  It will be used while
21036  * sourcing this script and when executing functions defined in the script.
21037  */
21038     void
21039 new_script_vars(id)
21040     scid_T id;
21041 {
21042     int		i;
21043     hashtab_T	*ht;
21044     scriptvar_T *sv;
21045 
21046     if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
21047     {
21048 	/* Re-allocating ga_data means that an ht_array pointing to
21049 	 * ht_smallarray becomes invalid.  We can recognize this: ht_mask is
21050 	 * at its init value.  Also reset "v_dict", it's always the same. */
21051 	for (i = 1; i <= ga_scripts.ga_len; ++i)
21052 	{
21053 	    ht = &SCRIPT_VARS(i);
21054 	    if (ht->ht_mask == HT_INIT_SIZE - 1)
21055 		ht->ht_array = ht->ht_smallarray;
21056 	    sv = SCRIPT_SV(i);
21057 	    sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
21058 	}
21059 
21060 	while (ga_scripts.ga_len < id)
21061 	{
21062 	    sv = SCRIPT_SV(ga_scripts.ga_len + 1) =
21063 		(scriptvar_T *)alloc_clear(sizeof(scriptvar_T));
21064 	    init_var_dict(&sv->sv_dict, &sv->sv_var, VAR_SCOPE);
21065 	    ++ga_scripts.ga_len;
21066 	}
21067     }
21068 }
21069 
21070 /*
21071  * Initialize dictionary "dict" as a scope and set variable "dict_var" to
21072  * point to it.
21073  */
21074     void
21075 init_var_dict(dict, dict_var, scope)
21076     dict_T	*dict;
21077     dictitem_T	*dict_var;
21078     int		scope;
21079 {
21080     hash_init(&dict->dv_hashtab);
21081     dict->dv_lock = 0;
21082     dict->dv_scope = scope;
21083     dict->dv_refcount = DO_NOT_FREE_CNT;
21084     dict->dv_copyID = 0;
21085     dict_var->di_tv.vval.v_dict = dict;
21086     dict_var->di_tv.v_type = VAR_DICT;
21087     dict_var->di_tv.v_lock = VAR_FIXED;
21088     dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21089     dict_var->di_key[0] = NUL;
21090 }
21091 
21092 /*
21093  * Unreference a dictionary initialized by init_var_dict().
21094  */
21095     void
21096 unref_var_dict(dict)
21097     dict_T	*dict;
21098 {
21099     /* Now the dict needs to be freed if no one else is using it, go back to
21100      * normal reference counting. */
21101     dict->dv_refcount -= DO_NOT_FREE_CNT - 1;
21102     dict_unref(dict);
21103 }
21104 
21105 /*
21106  * Clean up a list of internal variables.
21107  * Frees all allocated variables and the value they contain.
21108  * Clears hashtab "ht", does not free it.
21109  */
21110     void
21111 vars_clear(ht)
21112     hashtab_T *ht;
21113 {
21114     vars_clear_ext(ht, TRUE);
21115 }
21116 
21117 /*
21118  * Like vars_clear(), but only free the value if "free_val" is TRUE.
21119  */
21120     static void
21121 vars_clear_ext(ht, free_val)
21122     hashtab_T	*ht;
21123     int		free_val;
21124 {
21125     int		todo;
21126     hashitem_T	*hi;
21127     dictitem_T	*v;
21128 
21129     hash_lock(ht);
21130     todo = (int)ht->ht_used;
21131     for (hi = ht->ht_array; todo > 0; ++hi)
21132     {
21133 	if (!HASHITEM_EMPTY(hi))
21134 	{
21135 	    --todo;
21136 
21137 	    /* Free the variable.  Don't remove it from the hashtab,
21138 	     * ht_array might change then.  hash_clear() takes care of it
21139 	     * later. */
21140 	    v = HI2DI(hi);
21141 	    if (free_val)
21142 		clear_tv(&v->di_tv);
21143 	    if ((v->di_flags & DI_FLAGS_FIX) == 0)
21144 		vim_free(v);
21145 	}
21146     }
21147     hash_clear(ht);
21148     ht->ht_used = 0;
21149 }
21150 
21151 /*
21152  * Delete a variable from hashtab "ht" at item "hi".
21153  * Clear the variable value and free the dictitem.
21154  */
21155     static void
21156 delete_var(ht, hi)
21157     hashtab_T	*ht;
21158     hashitem_T	*hi;
21159 {
21160     dictitem_T	*di = HI2DI(hi);
21161 
21162     hash_remove(ht, hi);
21163     clear_tv(&di->di_tv);
21164     vim_free(di);
21165 }
21166 
21167 /*
21168  * List the value of one internal variable.
21169  */
21170     static void
21171 list_one_var(v, prefix, first)
21172     dictitem_T	*v;
21173     char_u	*prefix;
21174     int		*first;
21175 {
21176     char_u	*tofree;
21177     char_u	*s;
21178     char_u	numbuf[NUMBUFLEN];
21179 
21180     current_copyID += COPYID_INC;
21181     s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID);
21182     list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
21183 					 s == NULL ? (char_u *)"" : s, first);
21184     vim_free(tofree);
21185 }
21186 
21187     static void
21188 list_one_var_a(prefix, name, type, string, first)
21189     char_u	*prefix;
21190     char_u	*name;
21191     int		type;
21192     char_u	*string;
21193     int		*first;  /* when TRUE clear rest of screen and set to FALSE */
21194 {
21195     /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
21196     msg_start();
21197     msg_puts(prefix);
21198     if (name != NULL)	/* "a:" vars don't have a name stored */
21199 	msg_puts(name);
21200     msg_putchar(' ');
21201     msg_advance(22);
21202     if (type == VAR_NUMBER)
21203 	msg_putchar('#');
21204     else if (type == VAR_FUNC)
21205 	msg_putchar('*');
21206     else if (type == VAR_LIST)
21207     {
21208 	msg_putchar('[');
21209 	if (*string == '[')
21210 	    ++string;
21211     }
21212     else if (type == VAR_DICT)
21213     {
21214 	msg_putchar('{');
21215 	if (*string == '{')
21216 	    ++string;
21217     }
21218     else
21219 	msg_putchar(' ');
21220 
21221     msg_outtrans(string);
21222 
21223     if (type == VAR_FUNC)
21224 	msg_puts((char_u *)"()");
21225     if (*first)
21226     {
21227 	msg_clr_eos();
21228 	*first = FALSE;
21229     }
21230 }
21231 
21232 /*
21233  * Set variable "name" to value in "tv".
21234  * If the variable already exists, the value is updated.
21235  * Otherwise the variable is created.
21236  */
21237     static void
21238 set_var(name, tv, copy)
21239     char_u	*name;
21240     typval_T	*tv;
21241     int		copy;	    /* make copy of value in "tv" */
21242 {
21243     dictitem_T	*v;
21244     char_u	*varname;
21245     hashtab_T	*ht;
21246 
21247     ht = find_var_ht(name, &varname);
21248     if (ht == NULL || *varname == NUL)
21249     {
21250 	EMSG2(_(e_illvar), name);
21251 	return;
21252     }
21253     v = find_var_in_ht(ht, 0, varname, TRUE);
21254 
21255     if (tv->v_type == VAR_FUNC && var_check_func_name(name, v == NULL))
21256 	return;
21257 
21258     if (v != NULL)
21259     {
21260 	/* existing variable, need to clear the value */
21261 	if (var_check_ro(v->di_flags, name)
21262 				      || tv_check_lock(v->di_tv.v_lock, name))
21263 	    return;
21264 	if (v->di_tv.v_type != tv->v_type
21265 		&& !((v->di_tv.v_type == VAR_STRING
21266 			|| v->di_tv.v_type == VAR_NUMBER)
21267 		    && (tv->v_type == VAR_STRING
21268 			|| tv->v_type == VAR_NUMBER))
21269 #ifdef FEAT_FLOAT
21270 		&& !((v->di_tv.v_type == VAR_NUMBER
21271 			|| v->di_tv.v_type == VAR_FLOAT)
21272 		    && (tv->v_type == VAR_NUMBER
21273 			|| tv->v_type == VAR_FLOAT))
21274 #endif
21275 		)
21276 	{
21277 	    EMSG2(_("E706: Variable type mismatch for: %s"), name);
21278 	    return;
21279 	}
21280 
21281 	/*
21282 	 * Handle setting internal v: variables separately: we don't change
21283 	 * the type.
21284 	 */
21285 	if (ht == &vimvarht)
21286 	{
21287 	    if (v->di_tv.v_type == VAR_STRING)
21288 	    {
21289 		vim_free(v->di_tv.vval.v_string);
21290 		if (copy || tv->v_type != VAR_STRING)
21291 		    v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
21292 		else
21293 		{
21294 		    /* Take over the string to avoid an extra alloc/free. */
21295 		    v->di_tv.vval.v_string = tv->vval.v_string;
21296 		    tv->vval.v_string = NULL;
21297 		}
21298 	    }
21299 	    else if (v->di_tv.v_type != VAR_NUMBER)
21300 		EMSG2(_(e_intern2), "set_var()");
21301 	    else
21302 	    {
21303 		v->di_tv.vval.v_number = get_tv_number(tv);
21304 		if (STRCMP(varname, "searchforward") == 0)
21305 		    set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
21306 #ifdef FEAT_SEARCH_EXTRA
21307 		else if (STRCMP(varname, "hlsearch") == 0)
21308 		{
21309 		    no_hlsearch = !v->di_tv.vval.v_number;
21310 		    redraw_all_later(SOME_VALID);
21311 		}
21312 #endif
21313 	    }
21314 	    return;
21315 	}
21316 
21317 	clear_tv(&v->di_tv);
21318     }
21319     else		    /* add a new variable */
21320     {
21321 	/* Can't add "v:" variable. */
21322 	if (ht == &vimvarht)
21323 	{
21324 	    EMSG2(_(e_illvar), name);
21325 	    return;
21326 	}
21327 
21328 	/* Make sure the variable name is valid. */
21329 	if (!valid_varname(varname))
21330 	    return;
21331 
21332 	v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21333 							  + STRLEN(varname)));
21334 	if (v == NULL)
21335 	    return;
21336 	STRCPY(v->di_key, varname);
21337 	if (hash_add(ht, DI2HIKEY(v)) == FAIL)
21338 	{
21339 	    vim_free(v);
21340 	    return;
21341 	}
21342 	v->di_flags = 0;
21343     }
21344 
21345     if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
21346 	copy_tv(tv, &v->di_tv);
21347     else
21348     {
21349 	v->di_tv = *tv;
21350 	v->di_tv.v_lock = 0;
21351 	init_tv(tv);
21352     }
21353 }
21354 
21355 /*
21356  * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
21357  * Also give an error message.
21358  */
21359     static int
21360 var_check_ro(flags, name)
21361     int		flags;
21362     char_u	*name;
21363 {
21364     if (flags & DI_FLAGS_RO)
21365     {
21366 	EMSG2(_(e_readonlyvar), name);
21367 	return TRUE;
21368     }
21369     if ((flags & DI_FLAGS_RO_SBX) && sandbox)
21370     {
21371 	EMSG2(_(e_readonlysbx), name);
21372 	return TRUE;
21373     }
21374     return FALSE;
21375 }
21376 
21377 /*
21378  * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
21379  * Also give an error message.
21380  */
21381     static int
21382 var_check_fixed(flags, name)
21383     int		flags;
21384     char_u	*name;
21385 {
21386     if (flags & DI_FLAGS_FIX)
21387     {
21388 	EMSG2(_("E795: Cannot delete variable %s"), name);
21389 	return TRUE;
21390     }
21391     return FALSE;
21392 }
21393 
21394 /*
21395  * Check if a funcref is assigned to a valid variable name.
21396  * Return TRUE and give an error if not.
21397  */
21398     static int
21399 var_check_func_name(name, new_var)
21400     char_u *name;    /* points to start of variable name */
21401     int    new_var;  /* TRUE when creating the variable */
21402 {
21403     /* Allow for w: b: s: and t:. */
21404     if (!(vim_strchr((char_u *)"wbst", name[0]) != NULL && name[1] == ':')
21405 	    && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
21406 						     ? name[2] : name[0]))
21407     {
21408 	EMSG2(_("E704: Funcref variable name must start with a capital: %s"),
21409 									name);
21410 	return TRUE;
21411     }
21412     /* Don't allow hiding a function.  When "v" is not NULL we might be
21413      * assigning another function to the same var, the type is checked
21414      * below. */
21415     if (new_var && function_exists(name))
21416     {
21417 	EMSG2(_("E705: Variable name conflicts with existing function: %s"),
21418 								    name);
21419 	return TRUE;
21420     }
21421     return FALSE;
21422 }
21423 
21424 /*
21425  * Check if a variable name is valid.
21426  * Return FALSE and give an error if not.
21427  */
21428     static int
21429 valid_varname(varname)
21430     char_u *varname;
21431 {
21432     char_u *p;
21433 
21434     for (p = varname; *p != NUL; ++p)
21435 	if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
21436 						   && *p != AUTOLOAD_CHAR)
21437 	{
21438 	    EMSG2(_(e_illvar), varname);
21439 	    return FALSE;
21440 	}
21441     return TRUE;
21442 }
21443 
21444 /*
21445  * Return TRUE if typeval "tv" is set to be locked (immutable).
21446  * Also give an error message, using "name".
21447  */
21448     static int
21449 tv_check_lock(lock, name)
21450     int		lock;
21451     char_u	*name;
21452 {
21453     if (lock & VAR_LOCKED)
21454     {
21455 	EMSG2(_("E741: Value is locked: %s"),
21456 				name == NULL ? (char_u *)_("Unknown") : name);
21457 	return TRUE;
21458     }
21459     if (lock & VAR_FIXED)
21460     {
21461 	EMSG2(_("E742: Cannot change value of %s"),
21462 				name == NULL ? (char_u *)_("Unknown") : name);
21463 	return TRUE;
21464     }
21465     return FALSE;
21466 }
21467 
21468 /*
21469  * Copy the values from typval_T "from" to typval_T "to".
21470  * When needed allocates string or increases reference count.
21471  * Does not make a copy of a list or dict but copies the reference!
21472  * It is OK for "from" and "to" to point to the same item.  This is used to
21473  * make a copy later.
21474  */
21475     void
21476 copy_tv(from, to)
21477     typval_T *from;
21478     typval_T *to;
21479 {
21480     to->v_type = from->v_type;
21481     to->v_lock = 0;
21482     switch (from->v_type)
21483     {
21484 	case VAR_NUMBER:
21485 	    to->vval.v_number = from->vval.v_number;
21486 	    break;
21487 #ifdef FEAT_FLOAT
21488 	case VAR_FLOAT:
21489 	    to->vval.v_float = from->vval.v_float;
21490 	    break;
21491 #endif
21492 	case VAR_STRING:
21493 	case VAR_FUNC:
21494 	    if (from->vval.v_string == NULL)
21495 		to->vval.v_string = NULL;
21496 	    else
21497 	    {
21498 		to->vval.v_string = vim_strsave(from->vval.v_string);
21499 		if (from->v_type == VAR_FUNC)
21500 		    func_ref(to->vval.v_string);
21501 	    }
21502 	    break;
21503 	case VAR_LIST:
21504 	    if (from->vval.v_list == NULL)
21505 		to->vval.v_list = NULL;
21506 	    else
21507 	    {
21508 		to->vval.v_list = from->vval.v_list;
21509 		++to->vval.v_list->lv_refcount;
21510 	    }
21511 	    break;
21512 	case VAR_DICT:
21513 	    if (from->vval.v_dict == NULL)
21514 		to->vval.v_dict = NULL;
21515 	    else
21516 	    {
21517 		to->vval.v_dict = from->vval.v_dict;
21518 		++to->vval.v_dict->dv_refcount;
21519 	    }
21520 	    break;
21521 	default:
21522 	    EMSG2(_(e_intern2), "copy_tv()");
21523 	    break;
21524     }
21525 }
21526 
21527 /*
21528  * Make a copy of an item.
21529  * Lists and Dictionaries are also copied.  A deep copy if "deep" is set.
21530  * For deepcopy() "copyID" is zero for a full copy or the ID for when a
21531  * reference to an already copied list/dict can be used.
21532  * Returns FAIL or OK.
21533  */
21534     static int
21535 item_copy(from, to, deep, copyID)
21536     typval_T	*from;
21537     typval_T	*to;
21538     int		deep;
21539     int		copyID;
21540 {
21541     static int	recurse = 0;
21542     int		ret = OK;
21543 
21544     if (recurse >= DICT_MAXNEST)
21545     {
21546 	EMSG(_("E698: variable nested too deep for making a copy"));
21547 	return FAIL;
21548     }
21549     ++recurse;
21550 
21551     switch (from->v_type)
21552     {
21553 	case VAR_NUMBER:
21554 #ifdef FEAT_FLOAT
21555 	case VAR_FLOAT:
21556 #endif
21557 	case VAR_STRING:
21558 	case VAR_FUNC:
21559 	    copy_tv(from, to);
21560 	    break;
21561 	case VAR_LIST:
21562 	    to->v_type = VAR_LIST;
21563 	    to->v_lock = 0;
21564 	    if (from->vval.v_list == NULL)
21565 		to->vval.v_list = NULL;
21566 	    else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
21567 	    {
21568 		/* use the copy made earlier */
21569 		to->vval.v_list = from->vval.v_list->lv_copylist;
21570 		++to->vval.v_list->lv_refcount;
21571 	    }
21572 	    else
21573 		to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
21574 	    if (to->vval.v_list == NULL)
21575 		ret = FAIL;
21576 	    break;
21577 	case VAR_DICT:
21578 	    to->v_type = VAR_DICT;
21579 	    to->v_lock = 0;
21580 	    if (from->vval.v_dict == NULL)
21581 		to->vval.v_dict = NULL;
21582 	    else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
21583 	    {
21584 		/* use the copy made earlier */
21585 		to->vval.v_dict = from->vval.v_dict->dv_copydict;
21586 		++to->vval.v_dict->dv_refcount;
21587 	    }
21588 	    else
21589 		to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
21590 	    if (to->vval.v_dict == NULL)
21591 		ret = FAIL;
21592 	    break;
21593 	default:
21594 	    EMSG2(_(e_intern2), "item_copy()");
21595 	    ret = FAIL;
21596     }
21597     --recurse;
21598     return ret;
21599 }
21600 
21601 /*
21602  * ":echo expr1 ..."	print each argument separated with a space, add a
21603  *			newline at the end.
21604  * ":echon expr1 ..."	print each argument plain.
21605  */
21606     void
21607 ex_echo(eap)
21608     exarg_T	*eap;
21609 {
21610     char_u	*arg = eap->arg;
21611     typval_T	rettv;
21612     char_u	*tofree;
21613     char_u	*p;
21614     int		needclr = TRUE;
21615     int		atstart = TRUE;
21616     char_u	numbuf[NUMBUFLEN];
21617 
21618     if (eap->skip)
21619 	++emsg_skip;
21620     while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
21621     {
21622 	/* If eval1() causes an error message the text from the command may
21623 	 * still need to be cleared. E.g., "echo 22,44". */
21624 	need_clr_eos = needclr;
21625 
21626 	p = arg;
21627 	if (eval1(&arg, &rettv, !eap->skip) == FAIL)
21628 	{
21629 	    /*
21630 	     * Report the invalid expression unless the expression evaluation
21631 	     * has been cancelled due to an aborting error, an interrupt, or an
21632 	     * exception.
21633 	     */
21634 	    if (!aborting())
21635 		EMSG2(_(e_invexpr2), p);
21636 	    need_clr_eos = FALSE;
21637 	    break;
21638 	}
21639 	need_clr_eos = FALSE;
21640 
21641 	if (!eap->skip)
21642 	{
21643 	    if (atstart)
21644 	    {
21645 		atstart = FALSE;
21646 		/* Call msg_start() after eval1(), evaluating the expression
21647 		 * may cause a message to appear. */
21648 		if (eap->cmdidx == CMD_echo)
21649 		{
21650 		    /* Mark the saved text as finishing the line, so that what
21651 		     * follows is displayed on a new line when scrolling back
21652 		     * at the more prompt. */
21653 		    msg_sb_eol();
21654 		    msg_start();
21655 		}
21656 	    }
21657 	    else if (eap->cmdidx == CMD_echo)
21658 		msg_puts_attr((char_u *)" ", echo_attr);
21659 	    current_copyID += COPYID_INC;
21660 	    p = echo_string(&rettv, &tofree, numbuf, current_copyID);
21661 	    if (p != NULL)
21662 		for ( ; *p != NUL && !got_int; ++p)
21663 		{
21664 		    if (*p == '\n' || *p == '\r' || *p == TAB)
21665 		    {
21666 			if (*p != TAB && needclr)
21667 			{
21668 			    /* remove any text still there from the command */
21669 			    msg_clr_eos();
21670 			    needclr = FALSE;
21671 			}
21672 			msg_putchar_attr(*p, echo_attr);
21673 		    }
21674 		    else
21675 		    {
21676 #ifdef FEAT_MBYTE
21677 			if (has_mbyte)
21678 			{
21679 			    int i = (*mb_ptr2len)(p);
21680 
21681 			    (void)msg_outtrans_len_attr(p, i, echo_attr);
21682 			    p += i - 1;
21683 			}
21684 			else
21685 #endif
21686 			    (void)msg_outtrans_len_attr(p, 1, echo_attr);
21687 		    }
21688 		}
21689 	    vim_free(tofree);
21690 	}
21691 	clear_tv(&rettv);
21692 	arg = skipwhite(arg);
21693     }
21694     eap->nextcmd = check_nextcmd(arg);
21695 
21696     if (eap->skip)
21697 	--emsg_skip;
21698     else
21699     {
21700 	/* remove text that may still be there from the command */
21701 	if (needclr)
21702 	    msg_clr_eos();
21703 	if (eap->cmdidx == CMD_echo)
21704 	    msg_end();
21705     }
21706 }
21707 
21708 /*
21709  * ":echohl {name}".
21710  */
21711     void
21712 ex_echohl(eap)
21713     exarg_T	*eap;
21714 {
21715     int		id;
21716 
21717     id = syn_name2id(eap->arg);
21718     if (id == 0)
21719 	echo_attr = 0;
21720     else
21721 	echo_attr = syn_id2attr(id);
21722 }
21723 
21724 /*
21725  * ":execute expr1 ..."	execute the result of an expression.
21726  * ":echomsg expr1 ..."	Print a message
21727  * ":echoerr expr1 ..."	Print an error
21728  * Each gets spaces around each argument and a newline at the end for
21729  * echo commands
21730  */
21731     void
21732 ex_execute(eap)
21733     exarg_T	*eap;
21734 {
21735     char_u	*arg = eap->arg;
21736     typval_T	rettv;
21737     int		ret = OK;
21738     char_u	*p;
21739     garray_T	ga;
21740     int		len;
21741     int		save_did_emsg;
21742 
21743     ga_init2(&ga, 1, 80);
21744 
21745     if (eap->skip)
21746 	++emsg_skip;
21747     while (*arg != NUL && *arg != '|' && *arg != '\n')
21748     {
21749 	p = arg;
21750 	if (eval1(&arg, &rettv, !eap->skip) == FAIL)
21751 	{
21752 	    /*
21753 	     * Report the invalid expression unless the expression evaluation
21754 	     * has been cancelled due to an aborting error, an interrupt, or an
21755 	     * exception.
21756 	     */
21757 	    if (!aborting())
21758 		EMSG2(_(e_invexpr2), p);
21759 	    ret = FAIL;
21760 	    break;
21761 	}
21762 
21763 	if (!eap->skip)
21764 	{
21765 	    p = get_tv_string(&rettv);
21766 	    len = (int)STRLEN(p);
21767 	    if (ga_grow(&ga, len + 2) == FAIL)
21768 	    {
21769 		clear_tv(&rettv);
21770 		ret = FAIL;
21771 		break;
21772 	    }
21773 	    if (ga.ga_len)
21774 		((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
21775 	    STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
21776 	    ga.ga_len += len;
21777 	}
21778 
21779 	clear_tv(&rettv);
21780 	arg = skipwhite(arg);
21781     }
21782 
21783     if (ret != FAIL && ga.ga_data != NULL)
21784     {
21785 	if (eap->cmdidx == CMD_echomsg)
21786 	{
21787 	    MSG_ATTR(ga.ga_data, echo_attr);
21788 	    out_flush();
21789 	}
21790 	else if (eap->cmdidx == CMD_echoerr)
21791 	{
21792 	    /* We don't want to abort following commands, restore did_emsg. */
21793 	    save_did_emsg = did_emsg;
21794 	    EMSG((char_u *)ga.ga_data);
21795 	    if (!force_abort)
21796 		did_emsg = save_did_emsg;
21797 	}
21798 	else if (eap->cmdidx == CMD_execute)
21799 	    do_cmdline((char_u *)ga.ga_data,
21800 		       eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
21801     }
21802 
21803     ga_clear(&ga);
21804 
21805     if (eap->skip)
21806 	--emsg_skip;
21807 
21808     eap->nextcmd = check_nextcmd(arg);
21809 }
21810 
21811 /*
21812  * Skip over the name of an option: "&option", "&g:option" or "&l:option".
21813  * "arg" points to the "&" or '+' when called, to "option" when returning.
21814  * Returns NULL when no option name found.  Otherwise pointer to the char
21815  * after the option name.
21816  */
21817     static char_u *
21818 find_option_end(arg, opt_flags)
21819     char_u	**arg;
21820     int		*opt_flags;
21821 {
21822     char_u	*p = *arg;
21823 
21824     ++p;
21825     if (*p == 'g' && p[1] == ':')
21826     {
21827 	*opt_flags = OPT_GLOBAL;
21828 	p += 2;
21829     }
21830     else if (*p == 'l' && p[1] == ':')
21831     {
21832 	*opt_flags = OPT_LOCAL;
21833 	p += 2;
21834     }
21835     else
21836 	*opt_flags = 0;
21837 
21838     if (!ASCII_ISALPHA(*p))
21839 	return NULL;
21840     *arg = p;
21841 
21842     if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
21843 	p += 4;	    /* termcap option */
21844     else
21845 	while (ASCII_ISALPHA(*p))
21846 	    ++p;
21847     return p;
21848 }
21849 
21850 /*
21851  * ":function"
21852  */
21853     void
21854 ex_function(eap)
21855     exarg_T	*eap;
21856 {
21857     char_u	*theline;
21858     int		i;
21859     int		j;
21860     int		c;
21861     int		saved_did_emsg;
21862     int		saved_wait_return = need_wait_return;
21863     char_u	*name = NULL;
21864     char_u	*p;
21865     char_u	*arg;
21866     char_u	*line_arg = NULL;
21867     garray_T	newargs;
21868     garray_T	newlines;
21869     int		varargs = FALSE;
21870     int		mustend = FALSE;
21871     int		flags = 0;
21872     ufunc_T	*fp;
21873     int		indent;
21874     int		nesting;
21875     char_u	*skip_until = NULL;
21876     dictitem_T	*v;
21877     funcdict_T	fudi;
21878     static int	func_nr = 0;	    /* number for nameless function */
21879     int		paren;
21880     hashtab_T	*ht;
21881     int		todo;
21882     hashitem_T	*hi;
21883     int		sourcing_lnum_off;
21884 
21885     /*
21886      * ":function" without argument: list functions.
21887      */
21888     if (ends_excmd(*eap->arg))
21889     {
21890 	if (!eap->skip)
21891 	{
21892 	    todo = (int)func_hashtab.ht_used;
21893 	    for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
21894 	    {
21895 		if (!HASHITEM_EMPTY(hi))
21896 		{
21897 		    --todo;
21898 		    fp = HI2UF(hi);
21899 		    if (!isdigit(*fp->uf_name))
21900 			list_func_head(fp, FALSE);
21901 		}
21902 	    }
21903 	}
21904 	eap->nextcmd = check_nextcmd(eap->arg);
21905 	return;
21906     }
21907 
21908     /*
21909      * ":function /pat": list functions matching pattern.
21910      */
21911     if (*eap->arg == '/')
21912     {
21913 	p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
21914 	if (!eap->skip)
21915 	{
21916 	    regmatch_T	regmatch;
21917 
21918 	    c = *p;
21919 	    *p = NUL;
21920 	    regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
21921 	    *p = c;
21922 	    if (regmatch.regprog != NULL)
21923 	    {
21924 		regmatch.rm_ic = p_ic;
21925 
21926 		todo = (int)func_hashtab.ht_used;
21927 		for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
21928 		{
21929 		    if (!HASHITEM_EMPTY(hi))
21930 		    {
21931 			--todo;
21932 			fp = HI2UF(hi);
21933 			if (!isdigit(*fp->uf_name)
21934 				    && vim_regexec(&regmatch, fp->uf_name, 0))
21935 			    list_func_head(fp, FALSE);
21936 		    }
21937 		}
21938 		vim_regfree(regmatch.regprog);
21939 	    }
21940 	}
21941 	if (*p == '/')
21942 	    ++p;
21943 	eap->nextcmd = check_nextcmd(p);
21944 	return;
21945     }
21946 
21947     /*
21948      * Get the function name.  There are these situations:
21949      * func	    normal function name
21950      *		    "name" == func, "fudi.fd_dict" == NULL
21951      * dict.func    new dictionary entry
21952      *		    "name" == NULL, "fudi.fd_dict" set,
21953      *		    "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
21954      * dict.func    existing dict entry with a Funcref
21955      *		    "name" == func, "fudi.fd_dict" set,
21956      *		    "fudi.fd_di" set, "fudi.fd_newkey" == NULL
21957      * dict.func    existing dict entry that's not a Funcref
21958      *		    "name" == NULL, "fudi.fd_dict" set,
21959      *		    "fudi.fd_di" set, "fudi.fd_newkey" == NULL
21960      * s:func	    script-local function name
21961      * g:func	    global function name, same as "func"
21962      */
21963     p = eap->arg;
21964     name = trans_function_name(&p, eap->skip, 0, &fudi);
21965     paren = (vim_strchr(p, '(') != NULL);
21966     if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
21967     {
21968 	/*
21969 	 * Return on an invalid expression in braces, unless the expression
21970 	 * evaluation has been cancelled due to an aborting error, an
21971 	 * interrupt, or an exception.
21972 	 */
21973 	if (!aborting())
21974 	{
21975 	    if (!eap->skip && fudi.fd_newkey != NULL)
21976 		EMSG2(_(e_dictkey), fudi.fd_newkey);
21977 	    vim_free(fudi.fd_newkey);
21978 	    return;
21979 	}
21980 	else
21981 	    eap->skip = TRUE;
21982     }
21983 
21984     /* An error in a function call during evaluation of an expression in magic
21985      * braces should not cause the function not to be defined. */
21986     saved_did_emsg = did_emsg;
21987     did_emsg = FALSE;
21988 
21989     /*
21990      * ":function func" with only function name: list function.
21991      */
21992     if (!paren)
21993     {
21994 	if (!ends_excmd(*skipwhite(p)))
21995 	{
21996 	    EMSG(_(e_trailing));
21997 	    goto ret_free;
21998 	}
21999 	eap->nextcmd = check_nextcmd(p);
22000 	if (eap->nextcmd != NULL)
22001 	    *p = NUL;
22002 	if (!eap->skip && !got_int)
22003 	{
22004 	    fp = find_func(name);
22005 	    if (fp != NULL)
22006 	    {
22007 		list_func_head(fp, TRUE);
22008 		for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
22009 		{
22010 		    if (FUNCLINE(fp, j) == NULL)
22011 			continue;
22012 		    msg_putchar('\n');
22013 		    msg_outnum((long)(j + 1));
22014 		    if (j < 9)
22015 			msg_putchar(' ');
22016 		    if (j < 99)
22017 			msg_putchar(' ');
22018 		    msg_prt_line(FUNCLINE(fp, j), FALSE);
22019 		    out_flush();	/* show a line at a time */
22020 		    ui_breakcheck();
22021 		}
22022 		if (!got_int)
22023 		{
22024 		    msg_putchar('\n');
22025 		    msg_puts((char_u *)"   endfunction");
22026 		}
22027 	    }
22028 	    else
22029 		emsg_funcname(N_("E123: Undefined function: %s"), name);
22030 	}
22031 	goto ret_free;
22032     }
22033 
22034     /*
22035      * ":function name(arg1, arg2)" Define function.
22036      */
22037     p = skipwhite(p);
22038     if (*p != '(')
22039     {
22040 	if (!eap->skip)
22041 	{
22042 	    EMSG2(_("E124: Missing '(': %s"), eap->arg);
22043 	    goto ret_free;
22044 	}
22045 	/* attempt to continue by skipping some text */
22046 	if (vim_strchr(p, '(') != NULL)
22047 	    p = vim_strchr(p, '(');
22048     }
22049     p = skipwhite(p + 1);
22050 
22051     ga_init2(&newargs, (int)sizeof(char_u *), 3);
22052     ga_init2(&newlines, (int)sizeof(char_u *), 3);
22053 
22054     if (!eap->skip)
22055     {
22056 	/* Check the name of the function.  Unless it's a dictionary function
22057 	 * (that we are overwriting). */
22058 	if (name != NULL)
22059 	    arg = name;
22060 	else
22061 	    arg = fudi.fd_newkey;
22062 	if (arg != NULL && (fudi.fd_di == NULL
22063 				     || fudi.fd_di->di_tv.v_type != VAR_FUNC))
22064 	{
22065 	    if (*arg == K_SPECIAL)
22066 		j = 3;
22067 	    else
22068 		j = 0;
22069 	    while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
22070 						      : eval_isnamec(arg[j])))
22071 		++j;
22072 	    if (arg[j] != NUL)
22073 		emsg_funcname((char *)e_invarg2, arg);
22074 	}
22075 	/* Disallow using the g: dict. */
22076 	if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE)
22077 	    EMSG(_("E862: Cannot use g: here"));
22078     }
22079 
22080     /*
22081      * Isolate the arguments: "arg1, arg2, ...)"
22082      */
22083     while (*p != ')')
22084     {
22085 	if (p[0] == '.' && p[1] == '.' && p[2] == '.')
22086 	{
22087 	    varargs = TRUE;
22088 	    p += 3;
22089 	    mustend = TRUE;
22090 	}
22091 	else
22092 	{
22093 	    arg = p;
22094 	    while (ASCII_ISALNUM(*p) || *p == '_')
22095 		++p;
22096 	    if (arg == p || isdigit(*arg)
22097 		    || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
22098 		    || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
22099 	    {
22100 		if (!eap->skip)
22101 		    EMSG2(_("E125: Illegal argument: %s"), arg);
22102 		break;
22103 	    }
22104 	    if (ga_grow(&newargs, 1) == FAIL)
22105 		goto erret;
22106 	    c = *p;
22107 	    *p = NUL;
22108 	    arg = vim_strsave(arg);
22109 	    if (arg == NULL)
22110 		goto erret;
22111 
22112 	    /* Check for duplicate argument name. */
22113 	    for (i = 0; i < newargs.ga_len; ++i)
22114 		if (STRCMP(((char_u **)(newargs.ga_data))[i], arg) == 0)
22115 		{
22116 		    EMSG2(_("E853: Duplicate argument name: %s"), arg);
22117 		    vim_free(arg);
22118 		    goto erret;
22119 		}
22120 
22121 	    ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
22122 	    *p = c;
22123 	    newargs.ga_len++;
22124 	    if (*p == ',')
22125 		++p;
22126 	    else
22127 		mustend = TRUE;
22128 	}
22129 	p = skipwhite(p);
22130 	if (mustend && *p != ')')
22131 	{
22132 	    if (!eap->skip)
22133 		EMSG2(_(e_invarg2), eap->arg);
22134 	    break;
22135 	}
22136     }
22137     ++p;	/* skip the ')' */
22138 
22139     /* find extra arguments "range", "dict" and "abort" */
22140     for (;;)
22141     {
22142 	p = skipwhite(p);
22143 	if (STRNCMP(p, "range", 5) == 0)
22144 	{
22145 	    flags |= FC_RANGE;
22146 	    p += 5;
22147 	}
22148 	else if (STRNCMP(p, "dict", 4) == 0)
22149 	{
22150 	    flags |= FC_DICT;
22151 	    p += 4;
22152 	}
22153 	else if (STRNCMP(p, "abort", 5) == 0)
22154 	{
22155 	    flags |= FC_ABORT;
22156 	    p += 5;
22157 	}
22158 	else
22159 	    break;
22160     }
22161 
22162     /* When there is a line break use what follows for the function body.
22163      * Makes 'exe "func Test()\n...\nendfunc"' work. */
22164     if (*p == '\n')
22165 	line_arg = p + 1;
22166     else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
22167 	EMSG(_(e_trailing));
22168 
22169     /*
22170      * Read the body of the function, until ":endfunction" is found.
22171      */
22172     if (KeyTyped)
22173     {
22174 	/* Check if the function already exists, don't let the user type the
22175 	 * whole function before telling him it doesn't work!  For a script we
22176 	 * need to skip the body to be able to find what follows. */
22177 	if (!eap->skip && !eap->forceit)
22178 	{
22179 	    if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
22180 		EMSG(_(e_funcdict));
22181 	    else if (name != NULL && find_func(name) != NULL)
22182 		emsg_funcname(e_funcexts, name);
22183 	}
22184 
22185 	if (!eap->skip && did_emsg)
22186 	    goto erret;
22187 
22188 	msg_putchar('\n');	    /* don't overwrite the function name */
22189 	cmdline_row = msg_row;
22190     }
22191 
22192     indent = 2;
22193     nesting = 0;
22194     for (;;)
22195     {
22196 	if (KeyTyped)
22197 	{
22198 	    msg_scroll = TRUE;
22199 	    saved_wait_return = FALSE;
22200 	}
22201 	need_wait_return = FALSE;
22202 	sourcing_lnum_off = sourcing_lnum;
22203 
22204 	if (line_arg != NULL)
22205 	{
22206 	    /* Use eap->arg, split up in parts by line breaks. */
22207 	    theline = line_arg;
22208 	    p = vim_strchr(theline, '\n');
22209 	    if (p == NULL)
22210 		line_arg += STRLEN(line_arg);
22211 	    else
22212 	    {
22213 		*p = NUL;
22214 		line_arg = p + 1;
22215 	    }
22216 	}
22217 	else if (eap->getline == NULL)
22218 	    theline = getcmdline(':', 0L, indent);
22219 	else
22220 	    theline = eap->getline(':', eap->cookie, indent);
22221 	if (KeyTyped)
22222 	    lines_left = Rows - 1;
22223 	if (theline == NULL)
22224 	{
22225 	    EMSG(_("E126: Missing :endfunction"));
22226 	    goto erret;
22227 	}
22228 
22229 	/* Detect line continuation: sourcing_lnum increased more than one. */
22230 	if (sourcing_lnum > sourcing_lnum_off + 1)
22231 	    sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
22232 	else
22233 	    sourcing_lnum_off = 0;
22234 
22235 	if (skip_until != NULL)
22236 	{
22237 	    /* between ":append" and "." and between ":python <<EOF" and "EOF"
22238 	     * don't check for ":endfunc". */
22239 	    if (STRCMP(theline, skip_until) == 0)
22240 	    {
22241 		vim_free(skip_until);
22242 		skip_until = NULL;
22243 	    }
22244 	}
22245 	else
22246 	{
22247 	    /* skip ':' and blanks*/
22248 	    for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
22249 		;
22250 
22251 	    /* Check for "endfunction". */
22252 	    if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
22253 	    {
22254 		if (line_arg == NULL)
22255 		    vim_free(theline);
22256 		break;
22257 	    }
22258 
22259 	    /* Increase indent inside "if", "while", "for" and "try", decrease
22260 	     * at "end". */
22261 	    if (indent > 2 && STRNCMP(p, "end", 3) == 0)
22262 		indent -= 2;
22263 	    else if (STRNCMP(p, "if", 2) == 0
22264 		    || STRNCMP(p, "wh", 2) == 0
22265 		    || STRNCMP(p, "for", 3) == 0
22266 		    || STRNCMP(p, "try", 3) == 0)
22267 		indent += 2;
22268 
22269 	    /* Check for defining a function inside this function. */
22270 	    if (checkforcmd(&p, "function", 2))
22271 	    {
22272 		if (*p == '!')
22273 		    p = skipwhite(p + 1);
22274 		p += eval_fname_script(p);
22275 		if (ASCII_ISALPHA(*p))
22276 		{
22277 		    vim_free(trans_function_name(&p, TRUE, 0, NULL));
22278 		    if (*skipwhite(p) == '(')
22279 		    {
22280 			++nesting;
22281 			indent += 2;
22282 		    }
22283 		}
22284 	    }
22285 
22286 	    /* Check for ":append" or ":insert". */
22287 	    p = skip_range(p, NULL);
22288 	    if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
22289 		    || (p[0] == 'i'
22290 			&& (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
22291 				&& (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
22292 		skip_until = vim_strsave((char_u *)".");
22293 
22294 	    /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
22295 	    arg = skipwhite(skiptowhite(p));
22296 	    if (arg[0] == '<' && arg[1] =='<'
22297 		    && ((p[0] == 'p' && p[1] == 'y'
22298 				    && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
22299 			|| (p[0] == 'p' && p[1] == 'e'
22300 				    && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
22301 			|| (p[0] == 't' && p[1] == 'c'
22302 				    && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
22303 			|| (p[0] == 'l' && p[1] == 'u' && p[2] == 'a'
22304 				    && !ASCII_ISALPHA(p[3]))
22305 			|| (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
22306 				    && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
22307 			|| (p[0] == 'm' && p[1] == 'z'
22308 				    && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
22309 			))
22310 	    {
22311 		/* ":python <<" continues until a dot, like ":append" */
22312 		p = skipwhite(arg + 2);
22313 		if (*p == NUL)
22314 		    skip_until = vim_strsave((char_u *)".");
22315 		else
22316 		    skip_until = vim_strsave(p);
22317 	    }
22318 	}
22319 
22320 	/* Add the line to the function. */
22321 	if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
22322 	{
22323 	    if (line_arg == NULL)
22324 		vim_free(theline);
22325 	    goto erret;
22326 	}
22327 
22328 	/* Copy the line to newly allocated memory.  get_one_sourceline()
22329 	 * allocates 250 bytes per line, this saves 80% on average.  The cost
22330 	 * is an extra alloc/free. */
22331 	p = vim_strsave(theline);
22332 	if (p != NULL)
22333 	{
22334 	    if (line_arg == NULL)
22335 		vim_free(theline);
22336 	    theline = p;
22337 	}
22338 
22339 	((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
22340 
22341 	/* Add NULL lines for continuation lines, so that the line count is
22342 	 * equal to the index in the growarray.   */
22343 	while (sourcing_lnum_off-- > 0)
22344 	    ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
22345 
22346 	/* Check for end of eap->arg. */
22347 	if (line_arg != NULL && *line_arg == NUL)
22348 	    line_arg = NULL;
22349     }
22350 
22351     /* Don't define the function when skipping commands or when an error was
22352      * detected. */
22353     if (eap->skip || did_emsg)
22354 	goto erret;
22355 
22356     /*
22357      * If there are no errors, add the function
22358      */
22359     if (fudi.fd_dict == NULL)
22360     {
22361 	v = find_var(name, &ht, FALSE);
22362 	if (v != NULL && v->di_tv.v_type == VAR_FUNC)
22363 	{
22364 	    emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
22365 									name);
22366 	    goto erret;
22367 	}
22368 
22369 	fp = find_func(name);
22370 	if (fp != NULL)
22371 	{
22372 	    if (!eap->forceit)
22373 	    {
22374 		emsg_funcname(e_funcexts, name);
22375 		goto erret;
22376 	    }
22377 	    if (fp->uf_calls > 0)
22378 	    {
22379 		emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
22380 									name);
22381 		goto erret;
22382 	    }
22383 	    /* redefine existing function */
22384 	    ga_clear_strings(&(fp->uf_args));
22385 	    ga_clear_strings(&(fp->uf_lines));
22386 	    vim_free(name);
22387 	    name = NULL;
22388 	}
22389     }
22390     else
22391     {
22392 	char	numbuf[20];
22393 
22394 	fp = NULL;
22395 	if (fudi.fd_newkey == NULL && !eap->forceit)
22396 	{
22397 	    EMSG(_(e_funcdict));
22398 	    goto erret;
22399 	}
22400 	if (fudi.fd_di == NULL)
22401 	{
22402 	    /* Can't add a function to a locked dictionary */
22403 	    if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
22404 		goto erret;
22405 	}
22406 	    /* Can't change an existing function if it is locked */
22407 	else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
22408 	    goto erret;
22409 
22410 	/* Give the function a sequential number.  Can only be used with a
22411 	 * Funcref! */
22412 	vim_free(name);
22413 	sprintf(numbuf, "%d", ++func_nr);
22414 	name = vim_strsave((char_u *)numbuf);
22415 	if (name == NULL)
22416 	    goto erret;
22417     }
22418 
22419     if (fp == NULL)
22420     {
22421 	if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
22422 	{
22423 	    int	    slen, plen;
22424 	    char_u  *scriptname;
22425 
22426 	    /* Check that the autoload name matches the script name. */
22427 	    j = FAIL;
22428 	    if (sourcing_name != NULL)
22429 	    {
22430 		scriptname = autoload_name(name);
22431 		if (scriptname != NULL)
22432 		{
22433 		    p = vim_strchr(scriptname, '/');
22434 		    plen = (int)STRLEN(p);
22435 		    slen = (int)STRLEN(sourcing_name);
22436 		    if (slen > plen && fnamecmp(p,
22437 					    sourcing_name + slen - plen) == 0)
22438 			j = OK;
22439 		    vim_free(scriptname);
22440 		}
22441 	    }
22442 	    if (j == FAIL)
22443 	    {
22444 		EMSG2(_("E746: Function name does not match script file name: %s"), name);
22445 		goto erret;
22446 	    }
22447 	}
22448 
22449 	fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
22450 	if (fp == NULL)
22451 	    goto erret;
22452 
22453 	if (fudi.fd_dict != NULL)
22454 	{
22455 	    if (fudi.fd_di == NULL)
22456 	    {
22457 		/* add new dict entry */
22458 		fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
22459 		if (fudi.fd_di == NULL)
22460 		{
22461 		    vim_free(fp);
22462 		    goto erret;
22463 		}
22464 		if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
22465 		{
22466 		    vim_free(fudi.fd_di);
22467 		    vim_free(fp);
22468 		    goto erret;
22469 		}
22470 	    }
22471 	    else
22472 		/* overwrite existing dict entry */
22473 		clear_tv(&fudi.fd_di->di_tv);
22474 	    fudi.fd_di->di_tv.v_type = VAR_FUNC;
22475 	    fudi.fd_di->di_tv.v_lock = 0;
22476 	    fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
22477 	    fp->uf_refcount = 1;
22478 
22479 	    /* behave like "dict" was used */
22480 	    flags |= FC_DICT;
22481 	}
22482 
22483 	/* insert the new function in the function list */
22484 	STRCPY(fp->uf_name, name);
22485 	hash_add(&func_hashtab, UF2HIKEY(fp));
22486     }
22487     fp->uf_args = newargs;
22488     fp->uf_lines = newlines;
22489 #ifdef FEAT_PROFILE
22490     fp->uf_tml_count = NULL;
22491     fp->uf_tml_total = NULL;
22492     fp->uf_tml_self = NULL;
22493     fp->uf_profiling = FALSE;
22494     if (prof_def_func())
22495 	func_do_profile(fp);
22496 #endif
22497     fp->uf_varargs = varargs;
22498     fp->uf_flags = flags;
22499     fp->uf_calls = 0;
22500     fp->uf_script_ID = current_SID;
22501     goto ret_free;
22502 
22503 erret:
22504     ga_clear_strings(&newargs);
22505     ga_clear_strings(&newlines);
22506 ret_free:
22507     vim_free(skip_until);
22508     vim_free(fudi.fd_newkey);
22509     vim_free(name);
22510     did_emsg |= saved_did_emsg;
22511     need_wait_return |= saved_wait_return;
22512 }
22513 
22514 /*
22515  * Get a function name, translating "<SID>" and "<SNR>".
22516  * Also handles a Funcref in a List or Dictionary.
22517  * Returns the function name in allocated memory, or NULL for failure.
22518  * flags:
22519  * TFN_INT:         internal function name OK
22520  * TFN_QUIET:       be quiet
22521  * TFN_NO_AUTOLOAD: do not use script autoloading
22522  * Advances "pp" to just after the function name (if no error).
22523  */
22524     static char_u *
22525 trans_function_name(pp, skip, flags, fdp)
22526     char_u	**pp;
22527     int		skip;		/* only find the end, don't evaluate */
22528     int		flags;
22529     funcdict_T	*fdp;		/* return: info about dictionary used */
22530 {
22531     char_u	*name = NULL;
22532     char_u	*start;
22533     char_u	*end;
22534     int		lead;
22535     char_u	sid_buf[20];
22536     int		len;
22537     lval_T	lv;
22538 
22539     if (fdp != NULL)
22540 	vim_memset(fdp, 0, sizeof(funcdict_T));
22541     start = *pp;
22542 
22543     /* Check for hard coded <SNR>: already translated function ID (from a user
22544      * command). */
22545     if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
22546 						   && (*pp)[2] == (int)KE_SNR)
22547     {
22548 	*pp += 3;
22549 	len = get_id_len(pp) + 3;
22550 	return vim_strnsave(start, len);
22551     }
22552 
22553     /* A name starting with "<SID>" or "<SNR>" is local to a script.  But
22554      * don't skip over "s:", get_lval() needs it for "s:dict.func". */
22555     lead = eval_fname_script(start);
22556     if (lead > 2)
22557 	start += lead;
22558 
22559     /* Note that TFN_ flags use the same values as GLV_ flags. */
22560     end = get_lval(start, NULL, &lv, FALSE, skip, flags,
22561 					      lead > 2 ? 0 : FNE_CHECK_START);
22562     if (end == start)
22563     {
22564 	if (!skip)
22565 	    EMSG(_("E129: Function name required"));
22566 	goto theend;
22567     }
22568     if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
22569     {
22570 	/*
22571 	 * Report an invalid expression in braces, unless the expression
22572 	 * evaluation has been cancelled due to an aborting error, an
22573 	 * interrupt, or an exception.
22574 	 */
22575 	if (!aborting())
22576 	{
22577 	    if (end != NULL)
22578 		EMSG2(_(e_invarg2), start);
22579 	}
22580 	else
22581 	    *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
22582 	goto theend;
22583     }
22584 
22585     if (lv.ll_tv != NULL)
22586     {
22587 	if (fdp != NULL)
22588 	{
22589 	    fdp->fd_dict = lv.ll_dict;
22590 	    fdp->fd_newkey = lv.ll_newkey;
22591 	    lv.ll_newkey = NULL;
22592 	    fdp->fd_di = lv.ll_di;
22593 	}
22594 	if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
22595 	{
22596 	    name = vim_strsave(lv.ll_tv->vval.v_string);
22597 	    *pp = end;
22598 	}
22599 	else
22600 	{
22601 	    if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
22602 			     || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
22603 		EMSG(_(e_funcref));
22604 	    else
22605 		*pp = end;
22606 	    name = NULL;
22607 	}
22608 	goto theend;
22609     }
22610 
22611     if (lv.ll_name == NULL)
22612     {
22613 	/* Error found, but continue after the function name. */
22614 	*pp = end;
22615 	goto theend;
22616     }
22617 
22618     /* Check if the name is a Funcref.  If so, use the value. */
22619     if (lv.ll_exp_name != NULL)
22620     {
22621 	len = (int)STRLEN(lv.ll_exp_name);
22622 	name = deref_func_name(lv.ll_exp_name, &len, flags & TFN_NO_AUTOLOAD);
22623 	if (name == lv.ll_exp_name)
22624 	    name = NULL;
22625     }
22626     else
22627     {
22628 	len = (int)(end - *pp);
22629 	name = deref_func_name(*pp, &len, flags & TFN_NO_AUTOLOAD);
22630 	if (name == *pp)
22631 	    name = NULL;
22632     }
22633     if (name != NULL)
22634     {
22635 	name = vim_strsave(name);
22636 	*pp = end;
22637 	if (STRNCMP(name, "<SNR>", 5) == 0)
22638 	{
22639 	    /* Change "<SNR>" to the byte sequence. */
22640 	    name[0] = K_SPECIAL;
22641 	    name[1] = KS_EXTRA;
22642 	    name[2] = (int)KE_SNR;
22643 	    mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1);
22644 	}
22645 	goto theend;
22646     }
22647 
22648     if (lv.ll_exp_name != NULL)
22649     {
22650 	len = (int)STRLEN(lv.ll_exp_name);
22651 	if (lead <= 2 && lv.ll_name == lv.ll_exp_name
22652 					 && STRNCMP(lv.ll_name, "s:", 2) == 0)
22653 	{
22654 	    /* When there was "s:" already or the name expanded to get a
22655 	     * leading "s:" then remove it. */
22656 	    lv.ll_name += 2;
22657 	    len -= 2;
22658 	    lead = 2;
22659 	}
22660     }
22661     else
22662     {
22663 	/* skip over "s:" and "g:" */
22664 	if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':'))
22665 	    lv.ll_name += 2;
22666 	len = (int)(end - lv.ll_name);
22667     }
22668 
22669     /*
22670      * Copy the function name to allocated memory.
22671      * Accept <SID>name() inside a script, translate into <SNR>123_name().
22672      * Accept <SNR>123_name() outside a script.
22673      */
22674     if (skip)
22675 	lead = 0;	/* do nothing */
22676     else if (lead > 0)
22677     {
22678 	lead = 3;
22679 	if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
22680 						       || eval_fname_sid(*pp))
22681 	{
22682 	    /* It's "s:" or "<SID>" */
22683 	    if (current_SID <= 0)
22684 	    {
22685 		EMSG(_(e_usingsid));
22686 		goto theend;
22687 	    }
22688 	    sprintf((char *)sid_buf, "%ld_", (long)current_SID);
22689 	    lead += (int)STRLEN(sid_buf);
22690 	}
22691     }
22692     else if (!(flags & TFN_INT) && builtin_function(lv.ll_name, len))
22693     {
22694 	EMSG2(_("E128: Function name must start with a capital or \"s:\": %s"),
22695 								       start);
22696 	goto theend;
22697     }
22698     if (!skip && !(flags & TFN_QUIET))
22699     {
22700 	char_u *cp = vim_strchr(lv.ll_name, ':');
22701 
22702 	if (cp != NULL && cp < end)
22703 	{
22704 	    EMSG2(_("E884: Function name cannot contain a colon: %s"), start);
22705 	    goto theend;
22706 	}
22707     }
22708 
22709     name = alloc((unsigned)(len + lead + 1));
22710     if (name != NULL)
22711     {
22712 	if (lead > 0)
22713 	{
22714 	    name[0] = K_SPECIAL;
22715 	    name[1] = KS_EXTRA;
22716 	    name[2] = (int)KE_SNR;
22717 	    if (lead > 3)	/* If it's "<SID>" */
22718 		STRCPY(name + 3, sid_buf);
22719 	}
22720 	mch_memmove(name + lead, lv.ll_name, (size_t)len);
22721 	name[lead + len] = NUL;
22722     }
22723     *pp = end;
22724 
22725 theend:
22726     clear_lval(&lv);
22727     return name;
22728 }
22729 
22730 /*
22731  * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
22732  * Return 2 if "p" starts with "s:".
22733  * Return 0 otherwise.
22734  */
22735     static int
22736 eval_fname_script(p)
22737     char_u	*p;
22738 {
22739     if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
22740 					  || STRNICMP(p + 1, "SNR>", 4) == 0))
22741 	return 5;
22742     if (p[0] == 's' && p[1] == ':')
22743 	return 2;
22744     return 0;
22745 }
22746 
22747 /*
22748  * Return TRUE if "p" starts with "<SID>" or "s:".
22749  * Only works if eval_fname_script() returned non-zero for "p"!
22750  */
22751     static int
22752 eval_fname_sid(p)
22753     char_u	*p;
22754 {
22755     return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
22756 }
22757 
22758 /*
22759  * List the head of the function: "name(arg1, arg2)".
22760  */
22761     static void
22762 list_func_head(fp, indent)
22763     ufunc_T	*fp;
22764     int		indent;
22765 {
22766     int		j;
22767 
22768     msg_start();
22769     if (indent)
22770 	MSG_PUTS("   ");
22771     MSG_PUTS("function ");
22772     if (fp->uf_name[0] == K_SPECIAL)
22773     {
22774 	MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
22775 	msg_puts(fp->uf_name + 3);
22776     }
22777     else
22778 	msg_puts(fp->uf_name);
22779     msg_putchar('(');
22780     for (j = 0; j < fp->uf_args.ga_len; ++j)
22781     {
22782 	if (j)
22783 	    MSG_PUTS(", ");
22784 	msg_puts(FUNCARG(fp, j));
22785     }
22786     if (fp->uf_varargs)
22787     {
22788 	if (j)
22789 	    MSG_PUTS(", ");
22790 	MSG_PUTS("...");
22791     }
22792     msg_putchar(')');
22793     if (fp->uf_flags & FC_ABORT)
22794 	MSG_PUTS(" abort");
22795     if (fp->uf_flags & FC_RANGE)
22796 	MSG_PUTS(" range");
22797     if (fp->uf_flags & FC_DICT)
22798 	MSG_PUTS(" dict");
22799     msg_clr_eos();
22800     if (p_verbose > 0)
22801 	last_set_msg(fp->uf_script_ID);
22802 }
22803 
22804 /*
22805  * Find a function by name, return pointer to it in ufuncs.
22806  * Return NULL for unknown function.
22807  */
22808     static ufunc_T *
22809 find_func(name)
22810     char_u	*name;
22811 {
22812     hashitem_T	*hi;
22813 
22814     hi = hash_find(&func_hashtab, name);
22815     if (!HASHITEM_EMPTY(hi))
22816 	return HI2UF(hi);
22817     return NULL;
22818 }
22819 
22820 #if defined(EXITFREE) || defined(PROTO)
22821     void
22822 free_all_functions()
22823 {
22824     hashitem_T	*hi;
22825 
22826     /* Need to start all over every time, because func_free() may change the
22827      * hash table. */
22828     while (func_hashtab.ht_used > 0)
22829 	for (hi = func_hashtab.ht_array; ; ++hi)
22830 	    if (!HASHITEM_EMPTY(hi))
22831 	    {
22832 		func_free(HI2UF(hi));
22833 		break;
22834 	    }
22835 }
22836 #endif
22837 
22838     int
22839 translated_function_exists(name)
22840     char_u	*name;
22841 {
22842     if (builtin_function(name, -1))
22843 	return find_internal_func(name) >= 0;
22844     return find_func(name) != NULL;
22845 }
22846 
22847 /*
22848  * Return TRUE if a function "name" exists.
22849  */
22850     static int
22851 function_exists(name)
22852     char_u *name;
22853 {
22854     char_u  *nm = name;
22855     char_u  *p;
22856     int	    n = FALSE;
22857 
22858     p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET|TFN_NO_AUTOLOAD,
22859 			    NULL);
22860     nm = skipwhite(nm);
22861 
22862     /* Only accept "funcname", "funcname ", "funcname (..." and
22863      * "funcname(...", not "funcname!...". */
22864     if (p != NULL && (*nm == NUL || *nm == '('))
22865 	n = translated_function_exists(p);
22866     vim_free(p);
22867     return n;
22868 }
22869 
22870     char_u *
22871 get_expanded_name(name, check)
22872     char_u	*name;
22873     int		check;
22874 {
22875     char_u	*nm = name;
22876     char_u	*p;
22877 
22878     p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
22879 
22880     if (p != NULL && *nm == NUL)
22881 	if (!check || translated_function_exists(p))
22882 	    return p;
22883 
22884     vim_free(p);
22885     return NULL;
22886 }
22887 
22888 /*
22889  * Return TRUE if "name" looks like a builtin function name: starts with a
22890  * lower case letter and doesn't contain AUTOLOAD_CHAR.
22891  * "len" is the length of "name", or -1 for NUL terminated.
22892  */
22893     static int
22894 builtin_function(name, len)
22895     char_u *name;
22896     int len;
22897 {
22898     char_u *p;
22899 
22900     if (!ASCII_ISLOWER(name[0]))
22901 	return FALSE;
22902     p = vim_strchr(name, AUTOLOAD_CHAR);
22903     return p == NULL || (len > 0 && p > name + len);
22904 }
22905 
22906 #if defined(FEAT_PROFILE) || defined(PROTO)
22907 /*
22908  * Start profiling function "fp".
22909  */
22910     static void
22911 func_do_profile(fp)
22912     ufunc_T	*fp;
22913 {
22914     int		len = fp->uf_lines.ga_len;
22915 
22916     if (len == 0)
22917 	len = 1;  /* avoid getting error for allocating zero bytes */
22918     fp->uf_tm_count = 0;
22919     profile_zero(&fp->uf_tm_self);
22920     profile_zero(&fp->uf_tm_total);
22921     if (fp->uf_tml_count == NULL)
22922 	fp->uf_tml_count = (int *)alloc_clear((unsigned) (sizeof(int) * len));
22923     if (fp->uf_tml_total == NULL)
22924 	fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
22925 						  (sizeof(proftime_T) * len));
22926     if (fp->uf_tml_self == NULL)
22927 	fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
22928 						  (sizeof(proftime_T) * len));
22929     fp->uf_tml_idx = -1;
22930     if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
22931 						   || fp->uf_tml_self == NULL)
22932 	return;	    /* out of memory */
22933 
22934     fp->uf_profiling = TRUE;
22935 }
22936 
22937 /*
22938  * Dump the profiling results for all functions in file "fd".
22939  */
22940     void
22941 func_dump_profile(fd)
22942     FILE    *fd;
22943 {
22944     hashitem_T	*hi;
22945     int		todo;
22946     ufunc_T	*fp;
22947     int		i;
22948     ufunc_T	**sorttab;
22949     int		st_len = 0;
22950 
22951     todo = (int)func_hashtab.ht_used;
22952     if (todo == 0)
22953 	return;     /* nothing to dump */
22954 
22955     sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
22956 
22957     for (hi = func_hashtab.ht_array; todo > 0; ++hi)
22958     {
22959 	if (!HASHITEM_EMPTY(hi))
22960 	{
22961 	    --todo;
22962 	    fp = HI2UF(hi);
22963 	    if (fp->uf_profiling)
22964 	    {
22965 		if (sorttab != NULL)
22966 		    sorttab[st_len++] = fp;
22967 
22968 		if (fp->uf_name[0] == K_SPECIAL)
22969 		    fprintf(fd, "FUNCTION  <SNR>%s()\n", fp->uf_name + 3);
22970 		else
22971 		    fprintf(fd, "FUNCTION  %s()\n", fp->uf_name);
22972 		if (fp->uf_tm_count == 1)
22973 		    fprintf(fd, "Called 1 time\n");
22974 		else
22975 		    fprintf(fd, "Called %d times\n", fp->uf_tm_count);
22976 		fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
22977 		fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
22978 		fprintf(fd, "\n");
22979 		fprintf(fd, "count  total (s)   self (s)\n");
22980 
22981 		for (i = 0; i < fp->uf_lines.ga_len; ++i)
22982 		{
22983 		    if (FUNCLINE(fp, i) == NULL)
22984 			continue;
22985 		    prof_func_line(fd, fp->uf_tml_count[i],
22986 			     &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
22987 		    fprintf(fd, "%s\n", FUNCLINE(fp, i));
22988 		}
22989 		fprintf(fd, "\n");
22990 	    }
22991 	}
22992     }
22993 
22994     if (sorttab != NULL && st_len > 0)
22995     {
22996 	qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
22997 							      prof_total_cmp);
22998 	prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
22999 	qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
23000 							      prof_self_cmp);
23001 	prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
23002     }
23003 
23004     vim_free(sorttab);
23005 }
23006 
23007     static void
23008 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
23009     FILE	*fd;
23010     ufunc_T	**sorttab;
23011     int		st_len;
23012     char	*title;
23013     int		prefer_self;	/* when equal print only self time */
23014 {
23015     int		i;
23016     ufunc_T	*fp;
23017 
23018     fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
23019     fprintf(fd, "count  total (s)   self (s)  function\n");
23020     for (i = 0; i < 20 && i < st_len; ++i)
23021     {
23022 	fp = sorttab[i];
23023 	prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
23024 								 prefer_self);
23025 	if (fp->uf_name[0] == K_SPECIAL)
23026 	    fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
23027 	else
23028 	    fprintf(fd, " %s()\n", fp->uf_name);
23029     }
23030     fprintf(fd, "\n");
23031 }
23032 
23033 /*
23034  * Print the count and times for one function or function line.
23035  */
23036     static void
23037 prof_func_line(fd, count, total, self, prefer_self)
23038     FILE	*fd;
23039     int		count;
23040     proftime_T	*total;
23041     proftime_T	*self;
23042     int		prefer_self;	/* when equal print only self time */
23043 {
23044     if (count > 0)
23045     {
23046 	fprintf(fd, "%5d ", count);
23047 	if (prefer_self && profile_equal(total, self))
23048 	    fprintf(fd, "           ");
23049 	else
23050 	    fprintf(fd, "%s ", profile_msg(total));
23051 	if (!prefer_self && profile_equal(total, self))
23052 	    fprintf(fd, "           ");
23053 	else
23054 	    fprintf(fd, "%s ", profile_msg(self));
23055     }
23056     else
23057 	fprintf(fd, "                            ");
23058 }
23059 
23060 /*
23061  * Compare function for total time sorting.
23062  */
23063     static int
23064 #ifdef __BORLANDC__
23065 _RTLENTRYF
23066 #endif
23067 prof_total_cmp(s1, s2)
23068     const void	*s1;
23069     const void	*s2;
23070 {
23071     ufunc_T	*p1, *p2;
23072 
23073     p1 = *(ufunc_T **)s1;
23074     p2 = *(ufunc_T **)s2;
23075     return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
23076 }
23077 
23078 /*
23079  * Compare function for self time sorting.
23080  */
23081     static int
23082 #ifdef __BORLANDC__
23083 _RTLENTRYF
23084 #endif
23085 prof_self_cmp(s1, s2)
23086     const void	*s1;
23087     const void	*s2;
23088 {
23089     ufunc_T	*p1, *p2;
23090 
23091     p1 = *(ufunc_T **)s1;
23092     p2 = *(ufunc_T **)s2;
23093     return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
23094 }
23095 
23096 #endif
23097 
23098 /*
23099  * If "name" has a package name try autoloading the script for it.
23100  * Return TRUE if a package was loaded.
23101  */
23102     static int
23103 script_autoload(name, reload)
23104     char_u	*name;
23105     int		reload;	    /* load script again when already loaded */
23106 {
23107     char_u	*p;
23108     char_u	*scriptname, *tofree;
23109     int		ret = FALSE;
23110     int		i;
23111 
23112     /* If there is no '#' after name[0] there is no package name. */
23113     p = vim_strchr(name, AUTOLOAD_CHAR);
23114     if (p == NULL || p == name)
23115 	return FALSE;
23116 
23117     tofree = scriptname = autoload_name(name);
23118 
23119     /* Find the name in the list of previously loaded package names.  Skip
23120      * "autoload/", it's always the same. */
23121     for (i = 0; i < ga_loaded.ga_len; ++i)
23122 	if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
23123 	    break;
23124     if (!reload && i < ga_loaded.ga_len)
23125 	ret = FALSE;	    /* was loaded already */
23126     else
23127     {
23128 	/* Remember the name if it wasn't loaded already. */
23129 	if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
23130 	{
23131 	    ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
23132 	    tofree = NULL;
23133 	}
23134 
23135 	/* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
23136 	if (source_runtime(scriptname, FALSE) == OK)
23137 	    ret = TRUE;
23138     }
23139 
23140     vim_free(tofree);
23141     return ret;
23142 }
23143 
23144 /*
23145  * Return the autoload script name for a function or variable name.
23146  * Returns NULL when out of memory.
23147  */
23148     static char_u *
23149 autoload_name(name)
23150     char_u	*name;
23151 {
23152     char_u	*p;
23153     char_u	*scriptname;
23154 
23155     /* Get the script file name: replace '#' with '/', append ".vim". */
23156     scriptname = alloc((unsigned)(STRLEN(name) + 14));
23157     if (scriptname == NULL)
23158 	return FALSE;
23159     STRCPY(scriptname, "autoload/");
23160     STRCAT(scriptname, name);
23161     *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
23162     STRCAT(scriptname, ".vim");
23163     while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
23164 	*p = '/';
23165     return scriptname;
23166 }
23167 
23168 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
23169 
23170 /*
23171  * Function given to ExpandGeneric() to obtain the list of user defined
23172  * function names.
23173  */
23174     char_u *
23175 get_user_func_name(xp, idx)
23176     expand_T	*xp;
23177     int		idx;
23178 {
23179     static long_u	done;
23180     static hashitem_T	*hi;
23181     ufunc_T		*fp;
23182 
23183     if (idx == 0)
23184     {
23185 	done = 0;
23186 	hi = func_hashtab.ht_array;
23187     }
23188     if (done < func_hashtab.ht_used)
23189     {
23190 	if (done++ > 0)
23191 	    ++hi;
23192 	while (HASHITEM_EMPTY(hi))
23193 	    ++hi;
23194 	fp = HI2UF(hi);
23195 
23196 	if (fp->uf_flags & FC_DICT)
23197 	    return (char_u *)""; /* don't show dict functions */
23198 
23199 	if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
23200 	    return fp->uf_name;	/* prevents overflow */
23201 
23202 	cat_func_name(IObuff, fp);
23203 	if (xp->xp_context != EXPAND_USER_FUNC)
23204 	{
23205 	    STRCAT(IObuff, "(");
23206 	    if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
23207 		STRCAT(IObuff, ")");
23208 	}
23209 	return IObuff;
23210     }
23211     return NULL;
23212 }
23213 
23214 #endif /* FEAT_CMDL_COMPL */
23215 
23216 /*
23217  * Copy the function name of "fp" to buffer "buf".
23218  * "buf" must be able to hold the function name plus three bytes.
23219  * Takes care of script-local function names.
23220  */
23221     static void
23222 cat_func_name(buf, fp)
23223     char_u	*buf;
23224     ufunc_T	*fp;
23225 {
23226     if (fp->uf_name[0] == K_SPECIAL)
23227     {
23228 	STRCPY(buf, "<SNR>");
23229 	STRCAT(buf, fp->uf_name + 3);
23230     }
23231     else
23232 	STRCPY(buf, fp->uf_name);
23233 }
23234 
23235 /*
23236  * ":delfunction {name}"
23237  */
23238     void
23239 ex_delfunction(eap)
23240     exarg_T	*eap;
23241 {
23242     ufunc_T	*fp = NULL;
23243     char_u	*p;
23244     char_u	*name;
23245     funcdict_T	fudi;
23246 
23247     p = eap->arg;
23248     name = trans_function_name(&p, eap->skip, 0, &fudi);
23249     vim_free(fudi.fd_newkey);
23250     if (name == NULL)
23251     {
23252 	if (fudi.fd_dict != NULL && !eap->skip)
23253 	    EMSG(_(e_funcref));
23254 	return;
23255     }
23256     if (!ends_excmd(*skipwhite(p)))
23257     {
23258 	vim_free(name);
23259 	EMSG(_(e_trailing));
23260 	return;
23261     }
23262     eap->nextcmd = check_nextcmd(p);
23263     if (eap->nextcmd != NULL)
23264 	*p = NUL;
23265 
23266     if (!eap->skip)
23267 	fp = find_func(name);
23268     vim_free(name);
23269 
23270     if (!eap->skip)
23271     {
23272 	if (fp == NULL)
23273 	{
23274 	    EMSG2(_(e_nofunc), eap->arg);
23275 	    return;
23276 	}
23277 	if (fp->uf_calls > 0)
23278 	{
23279 	    EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
23280 	    return;
23281 	}
23282 
23283 	if (fudi.fd_dict != NULL)
23284 	{
23285 	    /* Delete the dict item that refers to the function, it will
23286 	     * invoke func_unref() and possibly delete the function. */
23287 	    dictitem_remove(fudi.fd_dict, fudi.fd_di);
23288 	}
23289 	else
23290 	    func_free(fp);
23291     }
23292 }
23293 
23294 /*
23295  * Free a function and remove it from the list of functions.
23296  */
23297     static void
23298 func_free(fp)
23299     ufunc_T *fp;
23300 {
23301     hashitem_T	*hi;
23302 
23303     /* clear this function */
23304     ga_clear_strings(&(fp->uf_args));
23305     ga_clear_strings(&(fp->uf_lines));
23306 #ifdef FEAT_PROFILE
23307     vim_free(fp->uf_tml_count);
23308     vim_free(fp->uf_tml_total);
23309     vim_free(fp->uf_tml_self);
23310 #endif
23311 
23312     /* remove the function from the function hashtable */
23313     hi = hash_find(&func_hashtab, UF2HIKEY(fp));
23314     if (HASHITEM_EMPTY(hi))
23315 	EMSG2(_(e_intern2), "func_free()");
23316     else
23317 	hash_remove(&func_hashtab, hi);
23318 
23319     vim_free(fp);
23320 }
23321 
23322 /*
23323  * Unreference a Function: decrement the reference count and free it when it
23324  * becomes zero.  Only for numbered functions.
23325  */
23326     void
23327 func_unref(name)
23328     char_u	*name;
23329 {
23330     ufunc_T *fp;
23331 
23332     if (name != NULL && isdigit(*name))
23333     {
23334 	fp = find_func(name);
23335 	if (fp == NULL)
23336 	    EMSG2(_(e_intern2), "func_unref()");
23337 	else if (--fp->uf_refcount <= 0)
23338 	{
23339 	    /* Only delete it when it's not being used.  Otherwise it's done
23340 	     * when "uf_calls" becomes zero. */
23341 	    if (fp->uf_calls == 0)
23342 		func_free(fp);
23343 	}
23344     }
23345 }
23346 
23347 /*
23348  * Count a reference to a Function.
23349  */
23350     void
23351 func_ref(name)
23352     char_u	*name;
23353 {
23354     ufunc_T *fp;
23355 
23356     if (name != NULL && isdigit(*name))
23357     {
23358 	fp = find_func(name);
23359 	if (fp == NULL)
23360 	    EMSG2(_(e_intern2), "func_ref()");
23361 	else
23362 	    ++fp->uf_refcount;
23363     }
23364 }
23365 
23366 /*
23367  * Call a user function.
23368  */
23369     static void
23370 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
23371     ufunc_T	*fp;		/* pointer to function */
23372     int		argcount;	/* nr of args */
23373     typval_T	*argvars;	/* arguments */
23374     typval_T	*rettv;		/* return value */
23375     linenr_T	firstline;	/* first line of range */
23376     linenr_T	lastline;	/* last line of range */
23377     dict_T	*selfdict;	/* Dictionary for "self" */
23378 {
23379     char_u	*save_sourcing_name;
23380     linenr_T	save_sourcing_lnum;
23381     scid_T	save_current_SID;
23382     funccall_T	*fc;
23383     int		save_did_emsg;
23384     static int	depth = 0;
23385     dictitem_T	*v;
23386     int		fixvar_idx = 0;	/* index in fixvar[] */
23387     int		i;
23388     int		ai;
23389     char_u	numbuf[NUMBUFLEN];
23390     char_u	*name;
23391 #ifdef FEAT_PROFILE
23392     proftime_T	wait_start;
23393     proftime_T	call_start;
23394 #endif
23395 
23396     /* If depth of calling is getting too high, don't execute the function */
23397     if (depth >= p_mfd)
23398     {
23399 	EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
23400 	rettv->v_type = VAR_NUMBER;
23401 	rettv->vval.v_number = -1;
23402 	return;
23403     }
23404     ++depth;
23405 
23406     line_breakcheck();		/* check for CTRL-C hit */
23407 
23408     fc = (funccall_T *)alloc(sizeof(funccall_T));
23409     fc->caller = current_funccal;
23410     current_funccal = fc;
23411     fc->func = fp;
23412     fc->rettv = rettv;
23413     rettv->vval.v_number = 0;
23414     fc->linenr = 0;
23415     fc->returned = FALSE;
23416     fc->level = ex_nesting_level;
23417     /* Check if this function has a breakpoint. */
23418     fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
23419     fc->dbg_tick = debug_tick;
23420 
23421     /*
23422      * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
23423      * with names up to VAR_SHORT_LEN long.  This avoids having to alloc/free
23424      * each argument variable and saves a lot of time.
23425      */
23426     /*
23427      * Init l: variables.
23428      */
23429     init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE);
23430     if (selfdict != NULL)
23431     {
23432 	/* Set l:self to "selfdict".  Use "name" to avoid a warning from
23433 	 * some compiler that checks the destination size. */
23434 	v = &fc->fixvar[fixvar_idx++].var;
23435 	name = v->di_key;
23436 	STRCPY(name, "self");
23437 	v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
23438 	hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
23439 	v->di_tv.v_type = VAR_DICT;
23440 	v->di_tv.v_lock = 0;
23441 	v->di_tv.vval.v_dict = selfdict;
23442 	++selfdict->dv_refcount;
23443     }
23444 
23445     /*
23446      * Init a: variables.
23447      * Set a:0 to "argcount".
23448      * Set a:000 to a list with room for the "..." arguments.
23449      */
23450     init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE);
23451     add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
23452 				(varnumber_T)(argcount - fp->uf_args.ga_len));
23453     /* Use "name" to avoid a warning from some compiler that checks the
23454      * destination size. */
23455     v = &fc->fixvar[fixvar_idx++].var;
23456     name = v->di_key;
23457     STRCPY(name, "000");
23458     v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
23459     hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
23460     v->di_tv.v_type = VAR_LIST;
23461     v->di_tv.v_lock = VAR_FIXED;
23462     v->di_tv.vval.v_list = &fc->l_varlist;
23463     vim_memset(&fc->l_varlist, 0, sizeof(list_T));
23464     fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
23465     fc->l_varlist.lv_lock = VAR_FIXED;
23466 
23467     /*
23468      * Set a:firstline to "firstline" and a:lastline to "lastline".
23469      * Set a:name to named arguments.
23470      * Set a:N to the "..." arguments.
23471      */
23472     add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
23473 						      (varnumber_T)firstline);
23474     add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
23475 						       (varnumber_T)lastline);
23476     for (i = 0; i < argcount; ++i)
23477     {
23478 	ai = i - fp->uf_args.ga_len;
23479 	if (ai < 0)
23480 	    /* named argument a:name */
23481 	    name = FUNCARG(fp, i);
23482 	else
23483 	{
23484 	    /* "..." argument a:1, a:2, etc. */
23485 	    sprintf((char *)numbuf, "%d", ai + 1);
23486 	    name = numbuf;
23487 	}
23488 	if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
23489 	{
23490 	    v = &fc->fixvar[fixvar_idx++].var;
23491 	    v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
23492 	}
23493 	else
23494 	{
23495 	    v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
23496 							     + STRLEN(name)));
23497 	    if (v == NULL)
23498 		break;
23499 	    v->di_flags = DI_FLAGS_RO;
23500 	}
23501 	STRCPY(v->di_key, name);
23502 	hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
23503 
23504 	/* Note: the values are copied directly to avoid alloc/free.
23505 	 * "argvars" must have VAR_FIXED for v_lock. */
23506 	v->di_tv = argvars[i];
23507 	v->di_tv.v_lock = VAR_FIXED;
23508 
23509 	if (ai >= 0 && ai < MAX_FUNC_ARGS)
23510 	{
23511 	    list_append(&fc->l_varlist, &fc->l_listitems[ai]);
23512 	    fc->l_listitems[ai].li_tv = argvars[i];
23513 	    fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
23514 	}
23515     }
23516 
23517     /* Don't redraw while executing the function. */
23518     ++RedrawingDisabled;
23519     save_sourcing_name = sourcing_name;
23520     save_sourcing_lnum = sourcing_lnum;
23521     sourcing_lnum = 1;
23522     sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
23523 		: STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
23524     if (sourcing_name != NULL)
23525     {
23526 	if (save_sourcing_name != NULL
23527 			  && STRNCMP(save_sourcing_name, "function ", 9) == 0)
23528 	    sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
23529 	else
23530 	    STRCPY(sourcing_name, "function ");
23531 	cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
23532 
23533 	if (p_verbose >= 12)
23534 	{
23535 	    ++no_wait_return;
23536 	    verbose_enter_scroll();
23537 
23538 	    smsg((char_u *)_("calling %s"), sourcing_name);
23539 	    if (p_verbose >= 14)
23540 	    {
23541 		char_u	buf[MSG_BUF_LEN];
23542 		char_u	numbuf2[NUMBUFLEN];
23543 		char_u	*tofree;
23544 		char_u	*s;
23545 
23546 		msg_puts((char_u *)"(");
23547 		for (i = 0; i < argcount; ++i)
23548 		{
23549 		    if (i > 0)
23550 			msg_puts((char_u *)", ");
23551 		    if (argvars[i].v_type == VAR_NUMBER)
23552 			msg_outnum((long)argvars[i].vval.v_number);
23553 		    else
23554 		    {
23555 			/* Do not want errors such as E724 here. */
23556 			++emsg_off;
23557 			s = tv2string(&argvars[i], &tofree, numbuf2, 0);
23558 			--emsg_off;
23559 			if (s != NULL)
23560 			{
23561 			    if (vim_strsize(s) > MSG_BUF_CLEN)
23562 			    {
23563 				trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN);
23564 				s = buf;
23565 			    }
23566 			    msg_puts(s);
23567 			    vim_free(tofree);
23568 			}
23569 		    }
23570 		}
23571 		msg_puts((char_u *)")");
23572 	    }
23573 	    msg_puts((char_u *)"\n");   /* don't overwrite this either */
23574 
23575 	    verbose_leave_scroll();
23576 	    --no_wait_return;
23577 	}
23578     }
23579 #ifdef FEAT_PROFILE
23580     if (do_profiling == PROF_YES)
23581     {
23582 	if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
23583 	    func_do_profile(fp);
23584 	if (fp->uf_profiling
23585 		    || (fc->caller != NULL && fc->caller->func->uf_profiling))
23586 	{
23587 	    ++fp->uf_tm_count;
23588 	    profile_start(&call_start);
23589 	    profile_zero(&fp->uf_tm_children);
23590 	}
23591 	script_prof_save(&wait_start);
23592     }
23593 #endif
23594 
23595     save_current_SID = current_SID;
23596     current_SID = fp->uf_script_ID;
23597     save_did_emsg = did_emsg;
23598     did_emsg = FALSE;
23599 
23600     /* call do_cmdline() to execute the lines */
23601     do_cmdline(NULL, get_func_line, (void *)fc,
23602 				     DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
23603 
23604     --RedrawingDisabled;
23605 
23606     /* when the function was aborted because of an error, return -1 */
23607     if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
23608     {
23609 	clear_tv(rettv);
23610 	rettv->v_type = VAR_NUMBER;
23611 	rettv->vval.v_number = -1;
23612     }
23613 
23614 #ifdef FEAT_PROFILE
23615     if (do_profiling == PROF_YES && (fp->uf_profiling
23616 		    || (fc->caller != NULL && fc->caller->func->uf_profiling)))
23617     {
23618 	profile_end(&call_start);
23619 	profile_sub_wait(&wait_start, &call_start);
23620 	profile_add(&fp->uf_tm_total, &call_start);
23621 	profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
23622 	if (fc->caller != NULL && fc->caller->func->uf_profiling)
23623 	{
23624 	    profile_add(&fc->caller->func->uf_tm_children, &call_start);
23625 	    profile_add(&fc->caller->func->uf_tml_children, &call_start);
23626 	}
23627     }
23628 #endif
23629 
23630     /* when being verbose, mention the return value */
23631     if (p_verbose >= 12)
23632     {
23633 	++no_wait_return;
23634 	verbose_enter_scroll();
23635 
23636 	if (aborting())
23637 	    smsg((char_u *)_("%s aborted"), sourcing_name);
23638 	else if (fc->rettv->v_type == VAR_NUMBER)
23639 	    smsg((char_u *)_("%s returning #%ld"), sourcing_name,
23640 					       (long)fc->rettv->vval.v_number);
23641 	else
23642 	{
23643 	    char_u	buf[MSG_BUF_LEN];
23644 	    char_u	numbuf2[NUMBUFLEN];
23645 	    char_u	*tofree;
23646 	    char_u	*s;
23647 
23648 	    /* The value may be very long.  Skip the middle part, so that we
23649 	     * have some idea how it starts and ends. smsg() would always
23650 	     * truncate it at the end. Don't want errors such as E724 here. */
23651 	    ++emsg_off;
23652 	    s = tv2string(fc->rettv, &tofree, numbuf2, 0);
23653 	    --emsg_off;
23654 	    if (s != NULL)
23655 	    {
23656 		if (vim_strsize(s) > MSG_BUF_CLEN)
23657 		{
23658 		    trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN);
23659 		    s = buf;
23660 		}
23661 		smsg((char_u *)_("%s returning %s"), sourcing_name, s);
23662 		vim_free(tofree);
23663 	    }
23664 	}
23665 	msg_puts((char_u *)"\n");   /* don't overwrite this either */
23666 
23667 	verbose_leave_scroll();
23668 	--no_wait_return;
23669     }
23670 
23671     vim_free(sourcing_name);
23672     sourcing_name = save_sourcing_name;
23673     sourcing_lnum = save_sourcing_lnum;
23674     current_SID = save_current_SID;
23675 #ifdef FEAT_PROFILE
23676     if (do_profiling == PROF_YES)
23677 	script_prof_restore(&wait_start);
23678 #endif
23679 
23680     if (p_verbose >= 12 && sourcing_name != NULL)
23681     {
23682 	++no_wait_return;
23683 	verbose_enter_scroll();
23684 
23685 	smsg((char_u *)_("continuing in %s"), sourcing_name);
23686 	msg_puts((char_u *)"\n");   /* don't overwrite this either */
23687 
23688 	verbose_leave_scroll();
23689 	--no_wait_return;
23690     }
23691 
23692     did_emsg |= save_did_emsg;
23693     current_funccal = fc->caller;
23694     --depth;
23695 
23696     /* If the a:000 list and the l: and a: dicts are not referenced we can
23697      * free the funccall_T and what's in it. */
23698     if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
23699 	    && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
23700 	    && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
23701     {
23702 	free_funccal(fc, FALSE);
23703     }
23704     else
23705     {
23706 	hashitem_T	*hi;
23707 	listitem_T	*li;
23708 	int		todo;
23709 
23710 	/* "fc" is still in use.  This can happen when returning "a:000" or
23711 	 * assigning "l:" to a global variable.
23712 	 * Link "fc" in the list for garbage collection later. */
23713 	fc->caller = previous_funccal;
23714 	previous_funccal = fc;
23715 
23716 	/* Make a copy of the a: variables, since we didn't do that above. */
23717 	todo = (int)fc->l_avars.dv_hashtab.ht_used;
23718 	for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
23719 	{
23720 	    if (!HASHITEM_EMPTY(hi))
23721 	    {
23722 		--todo;
23723 		v = HI2DI(hi);
23724 		copy_tv(&v->di_tv, &v->di_tv);
23725 	    }
23726 	}
23727 
23728 	/* Make a copy of the a:000 items, since we didn't do that above. */
23729 	for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
23730 	    copy_tv(&li->li_tv, &li->li_tv);
23731     }
23732 }
23733 
23734 /*
23735  * Return TRUE if items in "fc" do not have "copyID".  That means they are not
23736  * referenced from anywhere that is in use.
23737  */
23738     static int
23739 can_free_funccal(fc, copyID)
23740     funccall_T	*fc;
23741     int		copyID;
23742 {
23743     return (fc->l_varlist.lv_copyID != copyID
23744 	    && fc->l_vars.dv_copyID != copyID
23745 	    && fc->l_avars.dv_copyID != copyID);
23746 }
23747 
23748 /*
23749  * Free "fc" and what it contains.
23750  */
23751    static void
23752 free_funccal(fc, free_val)
23753     funccall_T	*fc;
23754     int		free_val;  /* a: vars were allocated */
23755 {
23756     listitem_T	*li;
23757 
23758     /* The a: variables typevals may not have been allocated, only free the
23759      * allocated variables. */
23760     vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
23761 
23762     /* free all l: variables */
23763     vars_clear(&fc->l_vars.dv_hashtab);
23764 
23765     /* Free the a:000 variables if they were allocated. */
23766     if (free_val)
23767 	for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
23768 	    clear_tv(&li->li_tv);
23769 
23770     vim_free(fc);
23771 }
23772 
23773 /*
23774  * Add a number variable "name" to dict "dp" with value "nr".
23775  */
23776     static void
23777 add_nr_var(dp, v, name, nr)
23778     dict_T	*dp;
23779     dictitem_T	*v;
23780     char	*name;
23781     varnumber_T nr;
23782 {
23783     STRCPY(v->di_key, name);
23784     v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
23785     hash_add(&dp->dv_hashtab, DI2HIKEY(v));
23786     v->di_tv.v_type = VAR_NUMBER;
23787     v->di_tv.v_lock = VAR_FIXED;
23788     v->di_tv.vval.v_number = nr;
23789 }
23790 
23791 /*
23792  * ":return [expr]"
23793  */
23794     void
23795 ex_return(eap)
23796     exarg_T	*eap;
23797 {
23798     char_u	*arg = eap->arg;
23799     typval_T	rettv;
23800     int		returning = FALSE;
23801 
23802     if (current_funccal == NULL)
23803     {
23804 	EMSG(_("E133: :return not inside a function"));
23805 	return;
23806     }
23807 
23808     if (eap->skip)
23809 	++emsg_skip;
23810 
23811     eap->nextcmd = NULL;
23812     if ((*arg != NUL && *arg != '|' && *arg != '\n')
23813 	    && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
23814     {
23815 	if (!eap->skip)
23816 	    returning = do_return(eap, FALSE, TRUE, &rettv);
23817 	else
23818 	    clear_tv(&rettv);
23819     }
23820     /* It's safer to return also on error. */
23821     else if (!eap->skip)
23822     {
23823 	/*
23824 	 * Return unless the expression evaluation has been cancelled due to an
23825 	 * aborting error, an interrupt, or an exception.
23826 	 */
23827 	if (!aborting())
23828 	    returning = do_return(eap, FALSE, TRUE, NULL);
23829     }
23830 
23831     /* When skipping or the return gets pending, advance to the next command
23832      * in this line (!returning).  Otherwise, ignore the rest of the line.
23833      * Following lines will be ignored by get_func_line(). */
23834     if (returning)
23835 	eap->nextcmd = NULL;
23836     else if (eap->nextcmd == NULL)	    /* no argument */
23837 	eap->nextcmd = check_nextcmd(arg);
23838 
23839     if (eap->skip)
23840 	--emsg_skip;
23841 }
23842 
23843 /*
23844  * Return from a function.  Possibly makes the return pending.  Also called
23845  * for a pending return at the ":endtry" or after returning from an extra
23846  * do_cmdline().  "reanimate" is used in the latter case.  "is_cmd" is set
23847  * when called due to a ":return" command.  "rettv" may point to a typval_T
23848  * with the return rettv.  Returns TRUE when the return can be carried out,
23849  * FALSE when the return gets pending.
23850  */
23851     int
23852 do_return(eap, reanimate, is_cmd, rettv)
23853     exarg_T	*eap;
23854     int		reanimate;
23855     int		is_cmd;
23856     void	*rettv;
23857 {
23858     int		idx;
23859     struct condstack *cstack = eap->cstack;
23860 
23861     if (reanimate)
23862 	/* Undo the return. */
23863 	current_funccal->returned = FALSE;
23864 
23865     /*
23866      * Cleanup (and inactivate) conditionals, but stop when a try conditional
23867      * not in its finally clause (which then is to be executed next) is found.
23868      * In this case, make the ":return" pending for execution at the ":endtry".
23869      * Otherwise, return normally.
23870      */
23871     idx = cleanup_conditionals(eap->cstack, 0, TRUE);
23872     if (idx >= 0)
23873     {
23874 	cstack->cs_pending[idx] = CSTP_RETURN;
23875 
23876 	if (!is_cmd && !reanimate)
23877 	    /* A pending return again gets pending.  "rettv" points to an
23878 	     * allocated variable with the rettv of the original ":return"'s
23879 	     * argument if present or is NULL else. */
23880 	    cstack->cs_rettv[idx] = rettv;
23881 	else
23882 	{
23883 	    /* When undoing a return in order to make it pending, get the stored
23884 	     * return rettv. */
23885 	    if (reanimate)
23886 		rettv = current_funccal->rettv;
23887 
23888 	    if (rettv != NULL)
23889 	    {
23890 		/* Store the value of the pending return. */
23891 		if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
23892 		    *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
23893 		else
23894 		    EMSG(_(e_outofmem));
23895 	    }
23896 	    else
23897 		cstack->cs_rettv[idx] = NULL;
23898 
23899 	    if (reanimate)
23900 	    {
23901 		/* The pending return value could be overwritten by a ":return"
23902 		 * without argument in a finally clause; reset the default
23903 		 * return value. */
23904 		current_funccal->rettv->v_type = VAR_NUMBER;
23905 		current_funccal->rettv->vval.v_number = 0;
23906 	    }
23907 	}
23908 	report_make_pending(CSTP_RETURN, rettv);
23909     }
23910     else
23911     {
23912 	current_funccal->returned = TRUE;
23913 
23914 	/* If the return is carried out now, store the return value.  For
23915 	 * a return immediately after reanimation, the value is already
23916 	 * there. */
23917 	if (!reanimate && rettv != NULL)
23918 	{
23919 	    clear_tv(current_funccal->rettv);
23920 	    *current_funccal->rettv = *(typval_T *)rettv;
23921 	    if (!is_cmd)
23922 		vim_free(rettv);
23923 	}
23924     }
23925 
23926     return idx < 0;
23927 }
23928 
23929 /*
23930  * Free the variable with a pending return value.
23931  */
23932     void
23933 discard_pending_return(rettv)
23934     void	*rettv;
23935 {
23936     free_tv((typval_T *)rettv);
23937 }
23938 
23939 /*
23940  * Generate a return command for producing the value of "rettv".  The result
23941  * is an allocated string.  Used by report_pending() for verbose messages.
23942  */
23943     char_u *
23944 get_return_cmd(rettv)
23945     void	*rettv;
23946 {
23947     char_u	*s = NULL;
23948     char_u	*tofree = NULL;
23949     char_u	numbuf[NUMBUFLEN];
23950 
23951     if (rettv != NULL)
23952 	s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
23953     if (s == NULL)
23954 	s = (char_u *)"";
23955 
23956     STRCPY(IObuff, ":return ");
23957     STRNCPY(IObuff + 8, s, IOSIZE - 8);
23958     if (STRLEN(s) + 8 >= IOSIZE)
23959 	STRCPY(IObuff + IOSIZE - 4, "...");
23960     vim_free(tofree);
23961     return vim_strsave(IObuff);
23962 }
23963 
23964 /*
23965  * Get next function line.
23966  * Called by do_cmdline() to get the next line.
23967  * Returns allocated string, or NULL for end of function.
23968  */
23969     char_u *
23970 get_func_line(c, cookie, indent)
23971     int	    c UNUSED;
23972     void    *cookie;
23973     int	    indent UNUSED;
23974 {
23975     funccall_T	*fcp = (funccall_T *)cookie;
23976     ufunc_T	*fp = fcp->func;
23977     char_u	*retval;
23978     garray_T	*gap;  /* growarray with function lines */
23979 
23980     /* If breakpoints have been added/deleted need to check for it. */
23981     if (fcp->dbg_tick != debug_tick)
23982     {
23983 	fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
23984 							       sourcing_lnum);
23985 	fcp->dbg_tick = debug_tick;
23986     }
23987 #ifdef FEAT_PROFILE
23988     if (do_profiling == PROF_YES)
23989 	func_line_end(cookie);
23990 #endif
23991 
23992     gap = &fp->uf_lines;
23993     if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
23994 	    || fcp->returned)
23995 	retval = NULL;
23996     else
23997     {
23998 	/* Skip NULL lines (continuation lines). */
23999 	while (fcp->linenr < gap->ga_len
24000 			  && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
24001 	    ++fcp->linenr;
24002 	if (fcp->linenr >= gap->ga_len)
24003 	    retval = NULL;
24004 	else
24005 	{
24006 	    retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
24007 	    sourcing_lnum = fcp->linenr;
24008 #ifdef FEAT_PROFILE
24009 	    if (do_profiling == PROF_YES)
24010 		func_line_start(cookie);
24011 #endif
24012 	}
24013     }
24014 
24015     /* Did we encounter a breakpoint? */
24016     if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
24017     {
24018 	dbg_breakpoint(fp->uf_name, sourcing_lnum);
24019 	/* Find next breakpoint. */
24020 	fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
24021 							       sourcing_lnum);
24022 	fcp->dbg_tick = debug_tick;
24023     }
24024 
24025     return retval;
24026 }
24027 
24028 #if defined(FEAT_PROFILE) || defined(PROTO)
24029 /*
24030  * Called when starting to read a function line.
24031  * "sourcing_lnum" must be correct!
24032  * When skipping lines it may not actually be executed, but we won't find out
24033  * until later and we need to store the time now.
24034  */
24035     void
24036 func_line_start(cookie)
24037     void    *cookie;
24038 {
24039     funccall_T	*fcp = (funccall_T *)cookie;
24040     ufunc_T	*fp = fcp->func;
24041 
24042     if (fp->uf_profiling && sourcing_lnum >= 1
24043 				      && sourcing_lnum <= fp->uf_lines.ga_len)
24044     {
24045 	fp->uf_tml_idx = sourcing_lnum - 1;
24046 	/* Skip continuation lines. */
24047 	while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
24048 	    --fp->uf_tml_idx;
24049 	fp->uf_tml_execed = FALSE;
24050 	profile_start(&fp->uf_tml_start);
24051 	profile_zero(&fp->uf_tml_children);
24052 	profile_get_wait(&fp->uf_tml_wait);
24053     }
24054 }
24055 
24056 /*
24057  * Called when actually executing a function line.
24058  */
24059     void
24060 func_line_exec(cookie)
24061     void    *cookie;
24062 {
24063     funccall_T	*fcp = (funccall_T *)cookie;
24064     ufunc_T	*fp = fcp->func;
24065 
24066     if (fp->uf_profiling && fp->uf_tml_idx >= 0)
24067 	fp->uf_tml_execed = TRUE;
24068 }
24069 
24070 /*
24071  * Called when done with a function line.
24072  */
24073     void
24074 func_line_end(cookie)
24075     void    *cookie;
24076 {
24077     funccall_T	*fcp = (funccall_T *)cookie;
24078     ufunc_T	*fp = fcp->func;
24079 
24080     if (fp->uf_profiling && fp->uf_tml_idx >= 0)
24081     {
24082 	if (fp->uf_tml_execed)
24083 	{
24084 	    ++fp->uf_tml_count[fp->uf_tml_idx];
24085 	    profile_end(&fp->uf_tml_start);
24086 	    profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
24087 	    profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
24088 	    profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
24089 							&fp->uf_tml_children);
24090 	}
24091 	fp->uf_tml_idx = -1;
24092     }
24093 }
24094 #endif
24095 
24096 /*
24097  * Return TRUE if the currently active function should be ended, because a
24098  * return was encountered or an error occurred.  Used inside a ":while".
24099  */
24100     int
24101 func_has_ended(cookie)
24102     void    *cookie;
24103 {
24104     funccall_T  *fcp = (funccall_T *)cookie;
24105 
24106     /* Ignore the "abort" flag if the abortion behavior has been changed due to
24107      * an error inside a try conditional. */
24108     return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
24109 	    || fcp->returned);
24110 }
24111 
24112 /*
24113  * return TRUE if cookie indicates a function which "abort"s on errors.
24114  */
24115     int
24116 func_has_abort(cookie)
24117     void    *cookie;
24118 {
24119     return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
24120 }
24121 
24122 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
24123 typedef enum
24124 {
24125     VAR_FLAVOUR_DEFAULT,	/* doesn't start with uppercase */
24126     VAR_FLAVOUR_SESSION,	/* starts with uppercase, some lower */
24127     VAR_FLAVOUR_VIMINFO		/* all uppercase */
24128 } var_flavour_T;
24129 
24130 static var_flavour_T var_flavour __ARGS((char_u *varname));
24131 
24132     static var_flavour_T
24133 var_flavour(varname)
24134     char_u *varname;
24135 {
24136     char_u *p = varname;
24137 
24138     if (ASCII_ISUPPER(*p))
24139     {
24140 	while (*(++p))
24141 	    if (ASCII_ISLOWER(*p))
24142 		return VAR_FLAVOUR_SESSION;
24143 	return VAR_FLAVOUR_VIMINFO;
24144     }
24145     else
24146 	return VAR_FLAVOUR_DEFAULT;
24147 }
24148 #endif
24149 
24150 #if defined(FEAT_VIMINFO) || defined(PROTO)
24151 /*
24152  * Restore global vars that start with a capital from the viminfo file
24153  */
24154     int
24155 read_viminfo_varlist(virp, writing)
24156     vir_T	*virp;
24157     int		writing;
24158 {
24159     char_u	*tab;
24160     int		type = VAR_NUMBER;
24161     typval_T	tv;
24162 
24163     if (!writing && (find_viminfo_parameter('!') != NULL))
24164     {
24165 	tab = vim_strchr(virp->vir_line + 1, '\t');
24166 	if (tab != NULL)
24167 	{
24168 	    *tab++ = '\0';	/* isolate the variable name */
24169 	    switch (*tab)
24170 	    {
24171 		case 'S': type = VAR_STRING; break;
24172 #ifdef FEAT_FLOAT
24173 		case 'F': type = VAR_FLOAT; break;
24174 #endif
24175 		case 'D': type = VAR_DICT; break;
24176 		case 'L': type = VAR_LIST; break;
24177 	    }
24178 
24179 	    tab = vim_strchr(tab, '\t');
24180 	    if (tab != NULL)
24181 	    {
24182 		tv.v_type = type;
24183 		if (type == VAR_STRING || type == VAR_DICT || type == VAR_LIST)
24184 		    tv.vval.v_string = viminfo_readstring(virp,
24185 				       (int)(tab - virp->vir_line + 1), TRUE);
24186 #ifdef FEAT_FLOAT
24187 		else if (type == VAR_FLOAT)
24188 		    (void)string2float(tab + 1, &tv.vval.v_float);
24189 #endif
24190 		else
24191 		    tv.vval.v_number = atol((char *)tab + 1);
24192 		if (type == VAR_DICT || type == VAR_LIST)
24193 		{
24194 		    typval_T *etv = eval_expr(tv.vval.v_string, NULL);
24195 
24196 		    if (etv == NULL)
24197 			/* Failed to parse back the dict or list, use it as a
24198 			 * string. */
24199 			tv.v_type = VAR_STRING;
24200 		    else
24201 		    {
24202 			vim_free(tv.vval.v_string);
24203 			tv = *etv;
24204 			vim_free(etv);
24205 		    }
24206 		}
24207 
24208 		set_var(virp->vir_line + 1, &tv, FALSE);
24209 
24210 		if (tv.v_type == VAR_STRING)
24211 		    vim_free(tv.vval.v_string);
24212 		else if (tv.v_type == VAR_DICT || tv.v_type == VAR_LIST)
24213 		    clear_tv(&tv);
24214 	    }
24215 	}
24216     }
24217 
24218     return viminfo_readline(virp);
24219 }
24220 
24221 /*
24222  * Write global vars that start with a capital to the viminfo file
24223  */
24224     void
24225 write_viminfo_varlist(fp)
24226     FILE    *fp;
24227 {
24228     hashitem_T	*hi;
24229     dictitem_T	*this_var;
24230     int		todo;
24231     char	*s;
24232     char_u	*p;
24233     char_u	*tofree;
24234     char_u	numbuf[NUMBUFLEN];
24235 
24236     if (find_viminfo_parameter('!') == NULL)
24237 	return;
24238 
24239     fputs(_("\n# global variables:\n"), fp);
24240 
24241     todo = (int)globvarht.ht_used;
24242     for (hi = globvarht.ht_array; todo > 0; ++hi)
24243     {
24244 	if (!HASHITEM_EMPTY(hi))
24245 	{
24246 	    --todo;
24247 	    this_var = HI2DI(hi);
24248 	    if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
24249 	    {
24250 		switch (this_var->di_tv.v_type)
24251 		{
24252 		    case VAR_STRING: s = "STR"; break;
24253 		    case VAR_NUMBER: s = "NUM"; break;
24254 #ifdef FEAT_FLOAT
24255 		    case VAR_FLOAT:  s = "FLO"; break;
24256 #endif
24257 		    case VAR_DICT:   s = "DIC"; break;
24258 		    case VAR_LIST:   s = "LIS"; break;
24259 		    default: continue;
24260 		}
24261 		fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
24262 		p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
24263 		if (p != NULL)
24264 		    viminfo_writestring(fp, p);
24265 		vim_free(tofree);
24266 	    }
24267 	}
24268     }
24269 }
24270 #endif
24271 
24272 #if defined(FEAT_SESSION) || defined(PROTO)
24273     int
24274 store_session_globals(fd)
24275     FILE	*fd;
24276 {
24277     hashitem_T	*hi;
24278     dictitem_T	*this_var;
24279     int		todo;
24280     char_u	*p, *t;
24281 
24282     todo = (int)globvarht.ht_used;
24283     for (hi = globvarht.ht_array; todo > 0; ++hi)
24284     {
24285 	if (!HASHITEM_EMPTY(hi))
24286 	{
24287 	    --todo;
24288 	    this_var = HI2DI(hi);
24289 	    if ((this_var->di_tv.v_type == VAR_NUMBER
24290 			|| this_var->di_tv.v_type == VAR_STRING)
24291 		    && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
24292 	    {
24293 		/* Escape special characters with a backslash.  Turn a LF and
24294 		 * CR into \n and \r. */
24295 		p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
24296 							(char_u *)"\\\"\n\r");
24297 		if (p == NULL)	    /* out of memory */
24298 		    break;
24299 		for (t = p; *t != NUL; ++t)
24300 		    if (*t == '\n')
24301 			*t = 'n';
24302 		    else if (*t == '\r')
24303 			*t = 'r';
24304 		if ((fprintf(fd, "let %s = %c%s%c",
24305 				this_var->di_key,
24306 				(this_var->di_tv.v_type == VAR_STRING) ? '"'
24307 									: ' ',
24308 				p,
24309 				(this_var->di_tv.v_type == VAR_STRING) ? '"'
24310 								   : ' ') < 0)
24311 			|| put_eol(fd) == FAIL)
24312 		{
24313 		    vim_free(p);
24314 		    return FAIL;
24315 		}
24316 		vim_free(p);
24317 	    }
24318 #ifdef FEAT_FLOAT
24319 	    else if (this_var->di_tv.v_type == VAR_FLOAT
24320 		    && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
24321 	    {
24322 		float_T f = this_var->di_tv.vval.v_float;
24323 		int sign = ' ';
24324 
24325 		if (f < 0)
24326 		{
24327 		    f = -f;
24328 		    sign = '-';
24329 		}
24330 		if ((fprintf(fd, "let %s = %c%f",
24331 					       this_var->di_key, sign, f) < 0)
24332 			|| put_eol(fd) == FAIL)
24333 		    return FAIL;
24334 	    }
24335 #endif
24336 	}
24337     }
24338     return OK;
24339 }
24340 #endif
24341 
24342 /*
24343  * Display script name where an item was last set.
24344  * Should only be invoked when 'verbose' is non-zero.
24345  */
24346     void
24347 last_set_msg(scriptID)
24348     scid_T scriptID;
24349 {
24350     char_u *p;
24351 
24352     if (scriptID != 0)
24353     {
24354 	p = home_replace_save(NULL, get_scriptname(scriptID));
24355 	if (p != NULL)
24356 	{
24357 	    verbose_enter();
24358 	    MSG_PUTS(_("\n\tLast set from "));
24359 	    MSG_PUTS(p);
24360 	    vim_free(p);
24361 	    verbose_leave();
24362 	}
24363     }
24364 }
24365 
24366 /*
24367  * List v:oldfiles in a nice way.
24368  */
24369     void
24370 ex_oldfiles(eap)
24371     exarg_T	*eap UNUSED;
24372 {
24373     list_T	*l = vimvars[VV_OLDFILES].vv_list;
24374     listitem_T	*li;
24375     int		nr = 0;
24376 
24377     if (l == NULL)
24378 	msg((char_u *)_("No old files"));
24379     else
24380     {
24381 	msg_start();
24382 	msg_scroll = TRUE;
24383 	for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
24384 	{
24385 	    msg_outnum((long)++nr);
24386 	    MSG_PUTS(": ");
24387 	    msg_outtrans(get_tv_string(&li->li_tv));
24388 	    msg_putchar('\n');
24389 	    out_flush();	    /* output one line at a time */
24390 	    ui_breakcheck();
24391 	}
24392 	/* Assume "got_int" was set to truncate the listing. */
24393 	got_int = FALSE;
24394 
24395 #ifdef FEAT_BROWSE_CMD
24396 	if (cmdmod.browse)
24397 	{
24398 	    quit_more = FALSE;
24399 	    nr = prompt_for_number(FALSE);
24400 	    msg_starthere();
24401 	    if (nr > 0)
24402 	    {
24403 		char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
24404 								    (long)nr);
24405 
24406 		if (p != NULL)
24407 		{
24408 		    p = expand_env_save(p);
24409 		    eap->arg = p;
24410 		    eap->cmdidx = CMD_edit;
24411 		    cmdmod.browse = FALSE;
24412 		    do_exedit(eap, NULL);
24413 		    vim_free(p);
24414 		}
24415 	    }
24416 	}
24417 #endif
24418     }
24419 }
24420 
24421 #endif /* FEAT_EVAL */
24422 
24423 
24424 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
24425 
24426 #ifdef WIN3264
24427 /*
24428  * Functions for ":8" filename modifier: get 8.3 version of a filename.
24429  */
24430 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
24431 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
24432 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
24433 
24434 /*
24435  * Get the short path (8.3) for the filename in "fnamep".
24436  * Only works for a valid file name.
24437  * When the path gets longer "fnamep" is changed and the allocated buffer
24438  * is put in "bufp".
24439  * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
24440  * Returns OK on success, FAIL on failure.
24441  */
24442     static int
24443 get_short_pathname(fnamep, bufp, fnamelen)
24444     char_u	**fnamep;
24445     char_u	**bufp;
24446     int		*fnamelen;
24447 {
24448     int		l, len;
24449     char_u	*newbuf;
24450 
24451     len = *fnamelen;
24452     l = GetShortPathName(*fnamep, *fnamep, len);
24453     if (l > len - 1)
24454     {
24455 	/* If that doesn't work (not enough space), then save the string
24456 	 * and try again with a new buffer big enough. */
24457 	newbuf = vim_strnsave(*fnamep, l);
24458 	if (newbuf == NULL)
24459 	    return FAIL;
24460 
24461 	vim_free(*bufp);
24462 	*fnamep = *bufp = newbuf;
24463 
24464 	/* Really should always succeed, as the buffer is big enough. */
24465 	l = GetShortPathName(*fnamep, *fnamep, l+1);
24466     }
24467 
24468     *fnamelen = l;
24469     return OK;
24470 }
24471 
24472 /*
24473  * Get the short path (8.3) for the filename in "fname". The converted
24474  * path is returned in "bufp".
24475  *
24476  * Some of the directories specified in "fname" may not exist. This function
24477  * will shorten the existing directories at the beginning of the path and then
24478  * append the remaining non-existing path.
24479  *
24480  * fname - Pointer to the filename to shorten.  On return, contains the
24481  *	   pointer to the shortened pathname
24482  * bufp -  Pointer to an allocated buffer for the filename.
24483  * fnamelen - Length of the filename pointed to by fname
24484  *
24485  * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
24486  */
24487     static int
24488 shortpath_for_invalid_fname(fname, bufp, fnamelen)
24489     char_u	**fname;
24490     char_u	**bufp;
24491     int		*fnamelen;
24492 {
24493     char_u	*short_fname, *save_fname, *pbuf_unused;
24494     char_u	*endp, *save_endp;
24495     char_u	ch;
24496     int		old_len, len;
24497     int		new_len, sfx_len;
24498     int		retval = OK;
24499 
24500     /* Make a copy */
24501     old_len = *fnamelen;
24502     save_fname = vim_strnsave(*fname, old_len);
24503     pbuf_unused = NULL;
24504     short_fname = NULL;
24505 
24506     endp = save_fname + old_len - 1; /* Find the end of the copy */
24507     save_endp = endp;
24508 
24509     /*
24510      * Try shortening the supplied path till it succeeds by removing one
24511      * directory at a time from the tail of the path.
24512      */
24513     len = 0;
24514     for (;;)
24515     {
24516 	/* go back one path-separator */
24517 	while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
24518 	    --endp;
24519 	if (endp <= save_fname)
24520 	    break;		/* processed the complete path */
24521 
24522 	/*
24523 	 * Replace the path separator with a NUL and try to shorten the
24524 	 * resulting path.
24525 	 */
24526 	ch = *endp;
24527 	*endp = 0;
24528 	short_fname = save_fname;
24529 	len = (int)STRLEN(short_fname) + 1;
24530 	if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
24531 	{
24532 	    retval = FAIL;
24533 	    goto theend;
24534 	}
24535 	*endp = ch;	/* preserve the string */
24536 
24537 	if (len > 0)
24538 	    break;	/* successfully shortened the path */
24539 
24540 	/* failed to shorten the path. Skip the path separator */
24541 	--endp;
24542     }
24543 
24544     if (len > 0)
24545     {
24546 	/*
24547 	 * Succeeded in shortening the path. Now concatenate the shortened
24548 	 * path with the remaining path at the tail.
24549 	 */
24550 
24551 	/* Compute the length of the new path. */
24552 	sfx_len = (int)(save_endp - endp) + 1;
24553 	new_len = len + sfx_len;
24554 
24555 	*fnamelen = new_len;
24556 	vim_free(*bufp);
24557 	if (new_len > old_len)
24558 	{
24559 	    /* There is not enough space in the currently allocated string,
24560 	     * copy it to a buffer big enough. */
24561 	    *fname = *bufp = vim_strnsave(short_fname, new_len);
24562 	    if (*fname == NULL)
24563 	    {
24564 		retval = FAIL;
24565 		goto theend;
24566 	    }
24567 	}
24568 	else
24569 	{
24570 	    /* Transfer short_fname to the main buffer (it's big enough),
24571 	     * unless get_short_pathname() did its work in-place. */
24572 	    *fname = *bufp = save_fname;
24573 	    if (short_fname != save_fname)
24574 		vim_strncpy(save_fname, short_fname, len);
24575 	    save_fname = NULL;
24576 	}
24577 
24578 	/* concat the not-shortened part of the path */
24579 	vim_strncpy(*fname + len, endp, sfx_len);
24580 	(*fname)[new_len] = NUL;
24581     }
24582 
24583 theend:
24584     vim_free(pbuf_unused);
24585     vim_free(save_fname);
24586 
24587     return retval;
24588 }
24589 
24590 /*
24591  * Get a pathname for a partial path.
24592  * Returns OK for success, FAIL for failure.
24593  */
24594     static int
24595 shortpath_for_partial(fnamep, bufp, fnamelen)
24596     char_u	**fnamep;
24597     char_u	**bufp;
24598     int		*fnamelen;
24599 {
24600     int		sepcount, len, tflen;
24601     char_u	*p;
24602     char_u	*pbuf, *tfname;
24603     int		hasTilde;
24604 
24605     /* Count up the path separators from the RHS.. so we know which part
24606      * of the path to return. */
24607     sepcount = 0;
24608     for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
24609 	if (vim_ispathsep(*p))
24610 	    ++sepcount;
24611 
24612     /* Need full path first (use expand_env() to remove a "~/") */
24613     hasTilde = (**fnamep == '~');
24614     if (hasTilde)
24615 	pbuf = tfname = expand_env_save(*fnamep);
24616     else
24617 	pbuf = tfname = FullName_save(*fnamep, FALSE);
24618 
24619     len = tflen = (int)STRLEN(tfname);
24620 
24621     if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
24622 	return FAIL;
24623 
24624     if (len == 0)
24625     {
24626 	/* Don't have a valid filename, so shorten the rest of the
24627 	 * path if we can. This CAN give us invalid 8.3 filenames, but
24628 	 * there's not a lot of point in guessing what it might be.
24629 	 */
24630 	len = tflen;
24631 	if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
24632 	    return FAIL;
24633     }
24634 
24635     /* Count the paths backward to find the beginning of the desired string. */
24636     for (p = tfname + len - 1; p >= tfname; --p)
24637     {
24638 #ifdef FEAT_MBYTE
24639 	if (has_mbyte)
24640 	    p -= mb_head_off(tfname, p);
24641 #endif
24642 	if (vim_ispathsep(*p))
24643 	{
24644 	    if (sepcount == 0 || (hasTilde && sepcount == 1))
24645 		break;
24646 	    else
24647 		sepcount --;
24648 	}
24649     }
24650     if (hasTilde)
24651     {
24652 	--p;
24653 	if (p >= tfname)
24654 	    *p = '~';
24655 	else
24656 	    return FAIL;
24657     }
24658     else
24659 	++p;
24660 
24661     /* Copy in the string - p indexes into tfname - allocated at pbuf */
24662     vim_free(*bufp);
24663     *fnamelen = (int)STRLEN(p);
24664     *bufp = pbuf;
24665     *fnamep = p;
24666 
24667     return OK;
24668 }
24669 #endif /* WIN3264 */
24670 
24671 /*
24672  * Adjust a filename, according to a string of modifiers.
24673  * *fnamep must be NUL terminated when called.  When returning, the length is
24674  * determined by *fnamelen.
24675  * Returns VALID_ flags or -1 for failure.
24676  * When there is an error, *fnamep is set to NULL.
24677  */
24678     int
24679 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
24680     char_u	*src;		/* string with modifiers */
24681     int		*usedlen;	/* characters after src that are used */
24682     char_u	**fnamep;	/* file name so far */
24683     char_u	**bufp;		/* buffer for allocated file name or NULL */
24684     int		*fnamelen;	/* length of fnamep */
24685 {
24686     int		valid = 0;
24687     char_u	*tail;
24688     char_u	*s, *p, *pbuf;
24689     char_u	dirname[MAXPATHL];
24690     int		c;
24691     int		has_fullname = 0;
24692 #ifdef WIN3264
24693     char_u	*fname_start = *fnamep;
24694     int		has_shortname = 0;
24695 #endif
24696 
24697 repeat:
24698     /* ":p" - full path/file_name */
24699     if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
24700     {
24701 	has_fullname = 1;
24702 
24703 	valid |= VALID_PATH;
24704 	*usedlen += 2;
24705 
24706 	/* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
24707 	if ((*fnamep)[0] == '~'
24708 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
24709 		&& ((*fnamep)[1] == '/'
24710 # ifdef BACKSLASH_IN_FILENAME
24711 		    || (*fnamep)[1] == '\\'
24712 # endif
24713 		    || (*fnamep)[1] == NUL)
24714 
24715 #endif
24716 	   )
24717 	{
24718 	    *fnamep = expand_env_save(*fnamep);
24719 	    vim_free(*bufp);	/* free any allocated file name */
24720 	    *bufp = *fnamep;
24721 	    if (*fnamep == NULL)
24722 		return -1;
24723 	}
24724 
24725 	/* When "/." or "/.." is used: force expansion to get rid of it. */
24726 	for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
24727 	{
24728 	    if (vim_ispathsep(*p)
24729 		    && p[1] == '.'
24730 		    && (p[2] == NUL
24731 			|| vim_ispathsep(p[2])
24732 			|| (p[2] == '.'
24733 			    && (p[3] == NUL || vim_ispathsep(p[3])))))
24734 		break;
24735 	}
24736 
24737 	/* FullName_save() is slow, don't use it when not needed. */
24738 	if (*p != NUL || !vim_isAbsName(*fnamep))
24739 	{
24740 	    *fnamep = FullName_save(*fnamep, *p != NUL);
24741 	    vim_free(*bufp);	/* free any allocated file name */
24742 	    *bufp = *fnamep;
24743 	    if (*fnamep == NULL)
24744 		return -1;
24745 	}
24746 
24747 #ifdef WIN3264
24748 # if _WIN32_WINNT >= 0x0500
24749 	if (vim_strchr(*fnamep, '~') != NULL)
24750 	{
24751 	    /* Expand 8.3 filename to full path.  Needed to make sure the same
24752 	     * file does not have two different names.
24753 	     * Note: problem does not occur if _WIN32_WINNT < 0x0500. */
24754 	    p = alloc(_MAX_PATH + 1);
24755 	    if (p != NULL)
24756 	    {
24757 		if (GetLongPathName(*fnamep, p, MAXPATHL))
24758 		{
24759 		    vim_free(*bufp);
24760 		    *bufp = *fnamep = p;
24761 		}
24762 		else
24763 		    vim_free(p);
24764 	    }
24765 	}
24766 # endif
24767 #endif
24768 	/* Append a path separator to a directory. */
24769 	if (mch_isdir(*fnamep))
24770 	{
24771 	    /* Make room for one or two extra characters. */
24772 	    *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
24773 	    vim_free(*bufp);	/* free any allocated file name */
24774 	    *bufp = *fnamep;
24775 	    if (*fnamep == NULL)
24776 		return -1;
24777 	    add_pathsep(*fnamep);
24778 	}
24779     }
24780 
24781     /* ":." - path relative to the current directory */
24782     /* ":~" - path relative to the home directory */
24783     /* ":8" - shortname path - postponed till after */
24784     while (src[*usedlen] == ':'
24785 		  && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
24786     {
24787 	*usedlen += 2;
24788 	if (c == '8')
24789 	{
24790 #ifdef WIN3264
24791 	    has_shortname = 1; /* Postpone this. */
24792 #endif
24793 	    continue;
24794 	}
24795 	pbuf = NULL;
24796 	/* Need full path first (use expand_env() to remove a "~/") */
24797 	if (!has_fullname)
24798 	{
24799 	    if (c == '.' && **fnamep == '~')
24800 		p = pbuf = expand_env_save(*fnamep);
24801 	    else
24802 		p = pbuf = FullName_save(*fnamep, FALSE);
24803 	}
24804 	else
24805 	    p = *fnamep;
24806 
24807 	has_fullname = 0;
24808 
24809 	if (p != NULL)
24810 	{
24811 	    if (c == '.')
24812 	    {
24813 		mch_dirname(dirname, MAXPATHL);
24814 		s = shorten_fname(p, dirname);
24815 		if (s != NULL)
24816 		{
24817 		    *fnamep = s;
24818 		    if (pbuf != NULL)
24819 		    {
24820 			vim_free(*bufp);   /* free any allocated file name */
24821 			*bufp = pbuf;
24822 			pbuf = NULL;
24823 		    }
24824 		}
24825 	    }
24826 	    else
24827 	    {
24828 		home_replace(NULL, p, dirname, MAXPATHL, TRUE);
24829 		/* Only replace it when it starts with '~' */
24830 		if (*dirname == '~')
24831 		{
24832 		    s = vim_strsave(dirname);
24833 		    if (s != NULL)
24834 		    {
24835 			*fnamep = s;
24836 			vim_free(*bufp);
24837 			*bufp = s;
24838 		    }
24839 		}
24840 	    }
24841 	    vim_free(pbuf);
24842 	}
24843     }
24844 
24845     tail = gettail(*fnamep);
24846     *fnamelen = (int)STRLEN(*fnamep);
24847 
24848     /* ":h" - head, remove "/file_name", can be repeated  */
24849     /* Don't remove the first "/" or "c:\" */
24850     while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
24851     {
24852 	valid |= VALID_HEAD;
24853 	*usedlen += 2;
24854 	s = get_past_head(*fnamep);
24855 	while (tail > s && after_pathsep(s, tail))
24856 	    mb_ptr_back(*fnamep, tail);
24857 	*fnamelen = (int)(tail - *fnamep);
24858 #ifdef VMS
24859 	if (*fnamelen > 0)
24860 	    *fnamelen += 1; /* the path separator is part of the path */
24861 #endif
24862 	if (*fnamelen == 0)
24863 	{
24864 	    /* Result is empty.  Turn it into "." to make ":cd %:h" work. */
24865 	    p = vim_strsave((char_u *)".");
24866 	    if (p == NULL)
24867 		return -1;
24868 	    vim_free(*bufp);
24869 	    *bufp = *fnamep = tail = p;
24870 	    *fnamelen = 1;
24871 	}
24872 	else
24873 	{
24874 	    while (tail > s && !after_pathsep(s, tail))
24875 		mb_ptr_back(*fnamep, tail);
24876 	}
24877     }
24878 
24879     /* ":8" - shortname  */
24880     if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
24881     {
24882 	*usedlen += 2;
24883 #ifdef WIN3264
24884 	has_shortname = 1;
24885 #endif
24886     }
24887 
24888 #ifdef WIN3264
24889     /*
24890      * Handle ":8" after we have done 'heads' and before we do 'tails'.
24891      */
24892     if (has_shortname)
24893     {
24894 	/* Copy the string if it is shortened by :h and when it wasn't copied
24895 	 * yet, because we are going to change it in place.  Avoids changing
24896 	 * the buffer name for "%:8". */
24897 	if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start)
24898 	{
24899 	    p = vim_strnsave(*fnamep, *fnamelen);
24900 	    if (p == NULL)
24901 		return -1;
24902 	    vim_free(*bufp);
24903 	    *bufp = *fnamep = p;
24904 	}
24905 
24906 	/* Split into two implementations - makes it easier.  First is where
24907 	 * there isn't a full name already, second is where there is. */
24908 	if (!has_fullname && !vim_isAbsName(*fnamep))
24909 	{
24910 	    if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
24911 		return -1;
24912 	}
24913 	else
24914 	{
24915 	    int		l = *fnamelen;
24916 
24917 	    /* Simple case, already have the full-name.
24918 	     * Nearly always shorter, so try first time. */
24919 	    if (get_short_pathname(fnamep, bufp, &l) == FAIL)
24920 		return -1;
24921 
24922 	    if (l == 0)
24923 	    {
24924 		/* Couldn't find the filename, search the paths. */
24925 		l = *fnamelen;
24926 		if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
24927 		    return -1;
24928 	    }
24929 	    *fnamelen = l;
24930 	}
24931     }
24932 #endif /* WIN3264 */
24933 
24934     /* ":t" - tail, just the basename */
24935     if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
24936     {
24937 	*usedlen += 2;
24938 	*fnamelen -= (int)(tail - *fnamep);
24939 	*fnamep = tail;
24940     }
24941 
24942     /* ":e" - extension, can be repeated */
24943     /* ":r" - root, without extension, can be repeated */
24944     while (src[*usedlen] == ':'
24945 	    && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
24946     {
24947 	/* find a '.' in the tail:
24948 	 * - for second :e: before the current fname
24949 	 * - otherwise: The last '.'
24950 	 */
24951 	if (src[*usedlen + 1] == 'e' && *fnamep > tail)
24952 	    s = *fnamep - 2;
24953 	else
24954 	    s = *fnamep + *fnamelen - 1;
24955 	for ( ; s > tail; --s)
24956 	    if (s[0] == '.')
24957 		break;
24958 	if (src[*usedlen + 1] == 'e')		/* :e */
24959 	{
24960 	    if (s > tail)
24961 	    {
24962 		*fnamelen += (int)(*fnamep - (s + 1));
24963 		*fnamep = s + 1;
24964 #ifdef VMS
24965 		/* cut version from the extension */
24966 		s = *fnamep + *fnamelen - 1;
24967 		for ( ; s > *fnamep; --s)
24968 		    if (s[0] == ';')
24969 			break;
24970 		if (s > *fnamep)
24971 		    *fnamelen = s - *fnamep;
24972 #endif
24973 	    }
24974 	    else if (*fnamep <= tail)
24975 		*fnamelen = 0;
24976 	}
24977 	else				/* :r */
24978 	{
24979 	    if (s > tail)	/* remove one extension */
24980 		*fnamelen = (int)(s - *fnamep);
24981 	}
24982 	*usedlen += 2;
24983     }
24984 
24985     /* ":s?pat?foo?" - substitute */
24986     /* ":gs?pat?foo?" - global substitute */
24987     if (src[*usedlen] == ':'
24988 	    && (src[*usedlen + 1] == 's'
24989 		|| (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
24990     {
24991 	char_u	    *str;
24992 	char_u	    *pat;
24993 	char_u	    *sub;
24994 	int	    sep;
24995 	char_u	    *flags;
24996 	int	    didit = FALSE;
24997 
24998 	flags = (char_u *)"";
24999 	s = src + *usedlen + 2;
25000 	if (src[*usedlen + 1] == 'g')
25001 	{
25002 	    flags = (char_u *)"g";
25003 	    ++s;
25004 	}
25005 
25006 	sep = *s++;
25007 	if (sep)
25008 	{
25009 	    /* find end of pattern */
25010 	    p = vim_strchr(s, sep);
25011 	    if (p != NULL)
25012 	    {
25013 		pat = vim_strnsave(s, (int)(p - s));
25014 		if (pat != NULL)
25015 		{
25016 		    s = p + 1;
25017 		    /* find end of substitution */
25018 		    p = vim_strchr(s, sep);
25019 		    if (p != NULL)
25020 		    {
25021 			sub = vim_strnsave(s, (int)(p - s));
25022 			str = vim_strnsave(*fnamep, *fnamelen);
25023 			if (sub != NULL && str != NULL)
25024 			{
25025 			    *usedlen = (int)(p + 1 - src);
25026 			    s = do_string_sub(str, pat, sub, flags);
25027 			    if (s != NULL)
25028 			    {
25029 				*fnamep = s;
25030 				*fnamelen = (int)STRLEN(s);
25031 				vim_free(*bufp);
25032 				*bufp = s;
25033 				didit = TRUE;
25034 			    }
25035 			}
25036 			vim_free(sub);
25037 			vim_free(str);
25038 		    }
25039 		    vim_free(pat);
25040 		}
25041 	    }
25042 	    /* after using ":s", repeat all the modifiers */
25043 	    if (didit)
25044 		goto repeat;
25045 	}
25046     }
25047 
25048     if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S')
25049     {
25050 	p = vim_strsave_shellescape(*fnamep, FALSE, FALSE);
25051 	if (p == NULL)
25052 	    return -1;
25053 	vim_free(*bufp);
25054 	*bufp = *fnamep = p;
25055 	*fnamelen = (int)STRLEN(p);
25056 	*usedlen += 2;
25057     }
25058 
25059     return valid;
25060 }
25061 
25062 /*
25063  * Perform a substitution on "str" with pattern "pat" and substitute "sub".
25064  * "flags" can be "g" to do a global substitute.
25065  * Returns an allocated string, NULL for error.
25066  */
25067     char_u *
25068 do_string_sub(str, pat, sub, flags)
25069     char_u	*str;
25070     char_u	*pat;
25071     char_u	*sub;
25072     char_u	*flags;
25073 {
25074     int		sublen;
25075     regmatch_T	regmatch;
25076     int		i;
25077     int		do_all;
25078     char_u	*tail;
25079     garray_T	ga;
25080     char_u	*ret;
25081     char_u	*save_cpo;
25082     char_u	*zero_width = NULL;
25083 
25084     /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
25085     save_cpo = p_cpo;
25086     p_cpo = empty_option;
25087 
25088     ga_init2(&ga, 1, 200);
25089 
25090     do_all = (flags[0] == 'g');
25091 
25092     regmatch.rm_ic = p_ic;
25093     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
25094     if (regmatch.regprog != NULL)
25095     {
25096 	tail = str;
25097 	while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
25098 	{
25099 	    /* Skip empty match except for first match. */
25100 	    if (regmatch.startp[0] == regmatch.endp[0])
25101 	    {
25102 		if (zero_width == regmatch.startp[0])
25103 		{
25104 		    /* avoid getting stuck on a match with an empty string */
25105 		    i = MB_PTR2LEN(tail);
25106 		    mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail,
25107 								   (size_t)i);
25108 		    ga.ga_len += i;
25109 		    tail += i;
25110 		    continue;
25111 		}
25112 		zero_width = regmatch.startp[0];
25113 	    }
25114 
25115 	    /*
25116 	     * Get some space for a temporary buffer to do the substitution
25117 	     * into.  It will contain:
25118 	     * - The text up to where the match is.
25119 	     * - The substituted text.
25120 	     * - The text after the match.
25121 	     */
25122 	    sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
25123 	    if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
25124 			    (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
25125 	    {
25126 		ga_clear(&ga);
25127 		break;
25128 	    }
25129 
25130 	    /* copy the text up to where the match is */
25131 	    i = (int)(regmatch.startp[0] - tail);
25132 	    mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
25133 	    /* add the substituted text */
25134 	    (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
25135 					  + ga.ga_len + i, TRUE, TRUE, FALSE);
25136 	    ga.ga_len += i + sublen - 1;
25137 	    tail = regmatch.endp[0];
25138 	    if (*tail == NUL)
25139 		break;
25140 	    if (!do_all)
25141 		break;
25142 	}
25143 
25144 	if (ga.ga_data != NULL)
25145 	    STRCPY((char *)ga.ga_data + ga.ga_len, tail);
25146 
25147 	vim_regfree(regmatch.regprog);
25148     }
25149 
25150     ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
25151     ga_clear(&ga);
25152     if (p_cpo == empty_option)
25153 	p_cpo = save_cpo;
25154     else
25155 	/* Darn, evaluating {sub} expression changed the value. */
25156 	free_string_option(save_cpo);
25157 
25158     return ret;
25159 }
25160 
25161 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */
25162