xref: /vim-8.2.3635/src/eval.c (revision 05a7bb36)
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 #if defined(MSDOS) || defined(MSWIN)
14 # include <io.h>	/* for mch_open(), must be before vim.h */
15 #endif
16 
17 #include "vim.h"
18 
19 #ifdef AMIGA
20 # include <time.h>	/* for strftime() */
21 #endif
22 
23 #ifdef MACOS
24 # include <time.h>	/* for time_t */
25 #endif
26 
27 #ifdef HAVE_FCNTL_H
28 # include <fcntl.h>
29 #endif
30 
31 #if defined(FEAT_EVAL) || defined(PROTO)
32 
33 #define DICT_MAXNEST 100	/* maximum nesting of lists and dicts */
34 
35 /*
36  * In a hashtab item "hi_key" points to "di_key" in a dictitem.
37  * This avoids adding a pointer to the hashtab item.
38  * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
39  * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
40  * HI2DI() converts a hashitem pointer to a dictitem pointer.
41  */
42 static dictitem_T dumdi;
43 #define DI2HIKEY(di) ((di)->di_key)
44 #define HIKEY2DI(p)  ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
45 #define HI2DI(hi)     HIKEY2DI((hi)->hi_key)
46 
47 /*
48  * Structure returned by get_lval() and used by set_var_lval().
49  * For a plain name:
50  *	"name"	    points to the variable name.
51  *	"exp_name"  is NULL.
52  *	"tv"	    is NULL
53  * For a magic braces name:
54  *	"name"	    points to the expanded variable name.
55  *	"exp_name"  is non-NULL, to be freed later.
56  *	"tv"	    is NULL
57  * For an index in a list:
58  *	"name"	    points to the (expanded) variable name.
59  *	"exp_name"  NULL or non-NULL, to be freed later.
60  *	"tv"	    points to the (first) list item value
61  *	"li"	    points to the (first) list item
62  *	"range", "n1", "n2" and "empty2" indicate what items are used.
63  * For an existing Dict item:
64  *	"name"	    points to the (expanded) variable name.
65  *	"exp_name"  NULL or non-NULL, to be freed later.
66  *	"tv"	    points to the dict item value
67  *	"newkey"    is NULL
68  * For a non-existing Dict item:
69  *	"name"	    points to the (expanded) variable name.
70  *	"exp_name"  NULL or non-NULL, to be freed later.
71  *	"tv"	    points to the Dictionary typval_T
72  *	"newkey"    is the key for the new item.
73  */
74 typedef struct lval_S
75 {
76     char_u	*ll_name;	/* start of variable name (can be NULL) */
77     char_u	*ll_exp_name;	/* NULL or expanded name in allocated memory. */
78     typval_T	*ll_tv;		/* Typeval of item being used.  If "newkey"
79 				   isn't NULL it's the Dict to which to add
80 				   the item. */
81     listitem_T	*ll_li;		/* The list item or NULL. */
82     list_T	*ll_list;	/* The list or NULL. */
83     int		ll_range;	/* TRUE when a [i:j] range was used */
84     long	ll_n1;		/* First index for list */
85     long	ll_n2;		/* Second index for list range */
86     int		ll_empty2;	/* Second index is empty: [i:] */
87     dict_T	*ll_dict;	/* The Dictionary or NULL */
88     dictitem_T	*ll_di;		/* The dictitem or NULL */
89     char_u	*ll_newkey;	/* New key for Dict in alloc. mem or NULL. */
90 } lval_T;
91 
92 
93 static char *e_letunexp	= N_("E18: Unexpected characters in :let");
94 static char *e_listidx = N_("E684: list index out of range: %ld");
95 static char *e_undefvar = N_("E121: Undefined variable: %s");
96 static char *e_missbrac = N_("E111: Missing ']'");
97 static char *e_listarg = N_("E686: Argument of %s must be a List");
98 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
99 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
100 static char *e_listreq = N_("E714: List required");
101 static char *e_dictreq = N_("E715: Dictionary required");
102 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
103 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
104 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
105 static char *e_funcdict = N_("E717: Dictionary entry already exists");
106 static char *e_funcref = N_("E718: Funcref required");
107 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
108 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
109 static char *e_nofunc = N_("E130: Unknown function: %s");
110 static char *e_illvar = N_("E461: Illegal variable name: %s");
111 /*
112  * All user-defined global variables are stored in dictionary "globvardict".
113  * "globvars_var" is the variable that is used for "g:".
114  */
115 static dict_T		globvardict;
116 static dictitem_T	globvars_var;
117 #define globvarht globvardict.dv_hashtab
118 
119 /*
120  * Old Vim variables such as "v:version" are also available without the "v:".
121  * Also in functions.  We need a special hashtable for them.
122  */
123 static hashtab_T	compat_hashtab;
124 
125 /*
126  * When recursively copying lists and dicts we need to remember which ones we
127  * have done to avoid endless recursiveness.  This unique ID is used for that.
128  */
129 static int current_copyID = 0;
130 
131 /*
132  * Array to hold the hashtab with variables local to each sourced script.
133  * Each item holds a variable (nameless) that points to the dict_T.
134  */
135 typedef struct
136 {
137     dictitem_T	sv_var;
138     dict_T	sv_dict;
139 } scriptvar_T;
140 
141 static garray_T	    ga_scripts = {0, 0, sizeof(scriptvar_T), 4, NULL};
142 #define SCRIPT_SV(id) (((scriptvar_T *)ga_scripts.ga_data)[(id) - 1])
143 #define SCRIPT_VARS(id) (SCRIPT_SV(id).sv_dict.dv_hashtab)
144 
145 static int echo_attr = 0;   /* attributes used for ":echo" */
146 
147 /* Values for trans_function_name() argument: */
148 #define TFN_INT		1	/* internal function name OK */
149 #define TFN_QUIET	2	/* no error messages */
150 
151 /*
152  * Structure to hold info for a user function.
153  */
154 typedef struct ufunc ufunc_T;
155 
156 struct ufunc
157 {
158     int		uf_varargs;	/* variable nr of arguments */
159     int		uf_flags;
160     int		uf_calls;	/* nr of active calls */
161     garray_T	uf_args;	/* arguments */
162     garray_T	uf_lines;	/* function lines */
163 #ifdef FEAT_PROFILE
164     int		uf_profiling;	/* TRUE when func is being profiled */
165     /* profiling the function as a whole */
166     int		uf_tm_count;	/* nr of calls */
167     proftime_T	uf_tm_total;	/* time spend in function + children */
168     proftime_T	uf_tm_self;	/* time spend in function itself */
169     proftime_T	uf_tm_start;	/* time at function call */
170     proftime_T	uf_tm_children;	/* time spent in children this call */
171     /* profiling the function per line */
172     int		*uf_tml_count;	/* nr of times line was executed */
173     proftime_T	*uf_tml_total;	/* time spend in a line + children */
174     proftime_T	*uf_tml_self;	/* time spend in a line itself */
175     proftime_T	uf_tml_start;	/* start time for current line */
176     proftime_T	uf_tml_children; /* time spent in children for this line */
177     proftime_T	uf_tml_wait;	/* start wait time for current line */
178     int		uf_tml_idx;	/* index of line being timed; -1 if none */
179     int		uf_tml_execed;	/* line being timed was executed */
180 #endif
181     scid_T	uf_script_ID;	/* ID of script where function was defined,
182 				   used for s: variables */
183     int		uf_refcount;	/* for numbered function: reference count */
184     char_u	uf_name[1];	/* name of function (actually longer); can
185 				   start with <SNR>123_ (<SNR> is K_SPECIAL
186 				   KS_EXTRA KE_SNR) */
187 };
188 
189 /* function flags */
190 #define FC_ABORT    1		/* abort function on error */
191 #define FC_RANGE    2		/* function accepts range */
192 #define FC_DICT	    4		/* Dict function, uses "self" */
193 
194 #define DEL_REFCOUNT	999999	/* list/dict is being deleted */
195 
196 /*
197  * All user-defined functions are found in this hashtable.
198  */
199 static hashtab_T	func_hashtab;
200 
201 /* list heads for garbage collection */
202 static dict_T		*first_dict = NULL;	/* list of all dicts */
203 static list_T		*first_list = NULL;	/* list of all lists */
204 
205 /* From user function to hashitem and back. */
206 static ufunc_T dumuf;
207 #define UF2HIKEY(fp) ((fp)->uf_name)
208 #define HIKEY2UF(p)  ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
209 #define HI2UF(hi)     HIKEY2UF((hi)->hi_key)
210 
211 #define FUNCARG(fp, j)	((char_u **)(fp->uf_args.ga_data))[j]
212 #define FUNCLINE(fp, j)	((char_u **)(fp->uf_lines.ga_data))[j]
213 
214 #define MAX_FUNC_ARGS	20	/* maximum number of function arguments */
215 #define VAR_SHORT_LEN	20	/* short variable name length */
216 #define FIXVAR_CNT	12	/* number of fixed variables */
217 
218 /* structure to hold info for a function that is currently being executed. */
219 typedef struct funccall_S funccall_T;
220 
221 struct funccall_S
222 {
223     ufunc_T	*func;		/* function being called */
224     int		linenr;		/* next line to be executed */
225     int		returned;	/* ":return" used */
226     struct			/* fixed variables for arguments */
227     {
228 	dictitem_T	var;		/* variable (without room for name) */
229 	char_u	room[VAR_SHORT_LEN];	/* room for the name */
230     } fixvar[FIXVAR_CNT];
231     dict_T	l_vars;		/* l: local function variables */
232     dictitem_T	l_vars_var;	/* variable for l: scope */
233     dict_T	l_avars;	/* a: argument variables */
234     dictitem_T	l_avars_var;	/* variable for a: scope */
235     list_T	l_varlist;	/* list for a:000 */
236     listitem_T	l_listitems[MAX_FUNC_ARGS];	/* listitems for a:000 */
237     typval_T	*rettv;		/* return value */
238     linenr_T	breakpoint;	/* next line with breakpoint or zero */
239     int		dbg_tick;	/* debug_tick when breakpoint was set */
240     int		level;		/* top nesting level of executed function */
241 #ifdef FEAT_PROFILE
242     proftime_T	prof_child;	/* time spent in a child */
243 #endif
244     funccall_T	*caller;	/* calling function or NULL */
245 };
246 
247 /*
248  * Info used by a ":for" loop.
249  */
250 typedef struct
251 {
252     int		fi_semicolon;	/* TRUE if ending in '; var]' */
253     int		fi_varcount;	/* nr of variables in the list */
254     listwatch_T	fi_lw;		/* keep an eye on the item used. */
255     list_T	*fi_list;	/* list being used */
256 } forinfo_T;
257 
258 /*
259  * Struct used by trans_function_name()
260  */
261 typedef struct
262 {
263     dict_T	*fd_dict;	/* Dictionary used */
264     char_u	*fd_newkey;	/* new key in "dict" in allocated memory */
265     dictitem_T	*fd_di;		/* Dictionary item used */
266 } funcdict_T;
267 
268 
269 /*
270  * Array to hold the value of v: variables.
271  * The value is in a dictitem, so that it can also be used in the v: scope.
272  * The reason to use this table anyway is for very quick access to the
273  * variables with the VV_ defines.
274  */
275 #include "version.h"
276 
277 /* values for vv_flags: */
278 #define VV_COMPAT	1	/* compatible, also used without "v:" */
279 #define VV_RO		2	/* read-only */
280 #define VV_RO_SBX	4	/* read-only in the sandbox */
281 
282 #define VV_NAME(s, t)	s, {{t}}, {0}
283 
284 static struct vimvar
285 {
286     char	*vv_name;	/* name of variable, without v: */
287     dictitem_T	vv_di;		/* value and name for key */
288     char	vv_filler[16];	/* space for LONGEST name below!!! */
289     char	vv_flags;	/* VV_COMPAT, VV_RO, VV_RO_SBX */
290 } vimvars[VV_LEN] =
291 {
292     /*
293      * The order here must match the VV_ defines in vim.h!
294      * Initializing a union does not work, leave tv.vval empty to get zero's.
295      */
296     {VV_NAME("count",		 VAR_NUMBER), VV_COMPAT+VV_RO},
297     {VV_NAME("count1",		 VAR_NUMBER), VV_RO},
298     {VV_NAME("prevcount",	 VAR_NUMBER), VV_RO},
299     {VV_NAME("errmsg",		 VAR_STRING), VV_COMPAT},
300     {VV_NAME("warningmsg",	 VAR_STRING), 0},
301     {VV_NAME("statusmsg",	 VAR_STRING), 0},
302     {VV_NAME("shell_error",	 VAR_NUMBER), VV_COMPAT+VV_RO},
303     {VV_NAME("this_session",	 VAR_STRING), VV_COMPAT},
304     {VV_NAME("version",		 VAR_NUMBER), VV_COMPAT+VV_RO},
305     {VV_NAME("lnum",		 VAR_NUMBER), VV_RO_SBX},
306     {VV_NAME("termresponse",	 VAR_STRING), VV_RO},
307     {VV_NAME("fname",		 VAR_STRING), VV_RO},
308     {VV_NAME("lang",		 VAR_STRING), VV_RO},
309     {VV_NAME("lc_time",		 VAR_STRING), VV_RO},
310     {VV_NAME("ctype",		 VAR_STRING), VV_RO},
311     {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
312     {VV_NAME("charconvert_to",	 VAR_STRING), VV_RO},
313     {VV_NAME("fname_in",	 VAR_STRING), VV_RO},
314     {VV_NAME("fname_out",	 VAR_STRING), VV_RO},
315     {VV_NAME("fname_new",	 VAR_STRING), VV_RO},
316     {VV_NAME("fname_diff",	 VAR_STRING), VV_RO},
317     {VV_NAME("cmdarg",		 VAR_STRING), VV_RO},
318     {VV_NAME("foldstart",	 VAR_NUMBER), VV_RO_SBX},
319     {VV_NAME("foldend",		 VAR_NUMBER), VV_RO_SBX},
320     {VV_NAME("folddashes",	 VAR_STRING), VV_RO_SBX},
321     {VV_NAME("foldlevel",	 VAR_NUMBER), VV_RO_SBX},
322     {VV_NAME("progname",	 VAR_STRING), VV_RO},
323     {VV_NAME("servername",	 VAR_STRING), VV_RO},
324     {VV_NAME("dying",		 VAR_NUMBER), VV_RO},
325     {VV_NAME("exception",	 VAR_STRING), VV_RO},
326     {VV_NAME("throwpoint",	 VAR_STRING), VV_RO},
327     {VV_NAME("register",	 VAR_STRING), VV_RO},
328     {VV_NAME("cmdbang",		 VAR_NUMBER), VV_RO},
329     {VV_NAME("insertmode",	 VAR_STRING), VV_RO},
330     {VV_NAME("val",		 VAR_UNKNOWN), VV_RO},
331     {VV_NAME("key",		 VAR_UNKNOWN), VV_RO},
332     {VV_NAME("profiling",	 VAR_NUMBER), VV_RO},
333     {VV_NAME("fcs_reason",	 VAR_STRING), VV_RO},
334     {VV_NAME("fcs_choice",	 VAR_STRING), 0},
335     {VV_NAME("beval_bufnr",	 VAR_NUMBER), VV_RO},
336     {VV_NAME("beval_winnr",	 VAR_NUMBER), VV_RO},
337     {VV_NAME("beval_lnum",	 VAR_NUMBER), VV_RO},
338     {VV_NAME("beval_col",	 VAR_NUMBER), VV_RO},
339     {VV_NAME("beval_text",	 VAR_STRING), VV_RO},
340     {VV_NAME("scrollstart",	 VAR_STRING), 0},
341     {VV_NAME("swapname",	 VAR_STRING), VV_RO},
342     {VV_NAME("swapchoice",	 VAR_STRING), 0},
343     {VV_NAME("swapcommand",	 VAR_STRING), VV_RO},
344 };
345 
346 /* shorthand */
347 #define vv_type	vv_di.di_tv.v_type
348 #define vv_nr	vv_di.di_tv.vval.v_number
349 #define vv_str	vv_di.di_tv.vval.v_string
350 #define vv_tv	vv_di.di_tv
351 
352 /*
353  * The v: variables are stored in dictionary "vimvardict".
354  * "vimvars_var" is the variable that is used for the "l:" scope.
355  */
356 static dict_T		vimvardict;
357 static dictitem_T	vimvars_var;
358 #define vimvarht  vimvardict.dv_hashtab
359 
360 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
361 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
362 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
363 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
364 #endif
365 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
366 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
367 static char_u *skip_var_one __ARGS((char_u *arg));
368 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty));
369 static void list_glob_vars __ARGS((void));
370 static void list_buf_vars __ARGS((void));
371 static void list_win_vars __ARGS((void));
372 static void list_vim_vars __ARGS((void));
373 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg));
374 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
375 static int check_changedtick __ARGS((char_u *arg));
376 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
377 static void clear_lval __ARGS((lval_T *lp));
378 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
379 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u  *op));
380 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
381 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
382 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
383 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
384 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
385 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
386 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
387 static int tv_islocked __ARGS((typval_T *tv));
388 
389 static int eval0 __ARGS((char_u *arg,  typval_T *rettv, char_u **nextcmd, int evaluate));
390 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
391 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
392 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
393 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
394 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
395 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
396 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
397 
398 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
399 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
400 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
401 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
402 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
403 static list_T *list_alloc __ARGS((void));
404 static void list_free __ARGS((list_T *l));
405 static listitem_T *listitem_alloc __ARGS((void));
406 static void listitem_free __ARGS((listitem_T *item));
407 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
408 static long list_len __ARGS((list_T *l));
409 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
410 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
411 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
412 static listitem_T *list_find __ARGS((list_T *l, long n));
413 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
414 static void list_append __ARGS((list_T *l, listitem_T *item));
415 static int list_append_tv __ARGS((list_T *l, typval_T *tv));
416 static int list_append_string __ARGS((list_T *l, char_u *str, int len));
417 static int list_append_number __ARGS((list_T *l, varnumber_T n));
418 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
419 static int list_extend __ARGS((list_T	*l1, list_T *l2, listitem_T *bef));
420 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
421 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
422 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
423 static char_u *list2string __ARGS((typval_T *tv));
424 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo));
425 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
426 static void set_ref_in_list __ARGS((list_T *l, int copyID));
427 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
428 static void dict_unref __ARGS((dict_T *d));
429 static void dict_free __ARGS((dict_T *d));
430 static dictitem_T *dictitem_alloc __ARGS((char_u *key));
431 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
432 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
433 static void dictitem_free __ARGS((dictitem_T *item));
434 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
435 static int dict_add __ARGS((dict_T *d, dictitem_T *item));
436 static long dict_len __ARGS((dict_T *d));
437 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
438 static char_u *dict2string __ARGS((typval_T *tv));
439 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
440 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf));
441 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf));
442 static char_u *string_quote __ARGS((char_u *str, int function));
443 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
444 static int find_internal_func __ARGS((char_u *name));
445 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
446 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));
447 static int call_func __ARGS((char_u *name, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
448 static void emsg_funcname __ARGS((char *msg, char_u *name));
449 
450 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
451 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
452 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
453 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
454 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
455 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
456 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
457 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
458 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
459 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
460 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
461 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
462 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
463 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
464 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
465 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
466 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
467 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
468 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
469 #if defined(FEAT_INS_EXPAND)
470 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
471 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
472 #endif
473 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
474 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
475 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
476 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
478 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
480 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
481 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
482 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
494 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
495 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
496 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
501 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
505 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
506 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
508 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
509 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
510 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
570 #ifdef vim_mkdir
571 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
572 #endif
573 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
607 #ifdef HAVE_STRFTIME
608 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
609 #endif
610 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
623 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
625 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
640 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
641 
642 static pos_T *var2fpos __ARGS((typval_T *varp, int lnum));
643 static int get_env_len __ARGS((char_u **arg));
644 static int get_id_len __ARGS((char_u **arg));
645 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
646 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
647 #define FNE_INCL_BR	1	/* find_name_end(): include [] in name */
648 #define FNE_CHECK_START	2	/* find_name_end(): check name starts with
649 				   valid character */
650 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
651 static int eval_isnamec __ARGS((int c));
652 static int eval_isnamec1 __ARGS((int c));
653 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
654 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
655 static typval_T *alloc_tv __ARGS((void));
656 static typval_T *alloc_string_tv __ARGS((char_u *string));
657 static void init_tv __ARGS((typval_T *varp));
658 static long get_tv_number __ARGS((typval_T *varp));
659 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
660 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
661 static char_u *get_tv_string __ARGS((typval_T *varp));
662 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
663 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
664 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
665 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
666 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
667 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
668 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
669 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix));
670 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string));
671 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
672 static int var_check_ro __ARGS((int flags, char_u *name));
673 static int tv_check_lock __ARGS((int lock, char_u *name));
674 static void copy_tv __ARGS((typval_T *from, typval_T *to));
675 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
676 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
677 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
678 static int eval_fname_script __ARGS((char_u *p));
679 static int eval_fname_sid __ARGS((char_u *p));
680 static void list_func_head __ARGS((ufunc_T *fp, int indent));
681 static ufunc_T *find_func __ARGS((char_u *name));
682 static int function_exists __ARGS((char_u *name));
683 static int builtin_function __ARGS((char_u *name));
684 #ifdef FEAT_PROFILE
685 static void func_do_profile __ARGS((ufunc_T *fp));
686 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
687 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
688 static int
689 # ifdef __BORLANDC__
690     _RTLENTRYF
691 # endif
692 	prof_total_cmp __ARGS((const void *s1, const void *s2));
693 static int
694 # ifdef __BORLANDC__
695     _RTLENTRYF
696 # endif
697 	prof_self_cmp __ARGS((const void *s1, const void *s2));
698 #endif
699 static int script_autoload __ARGS((char_u *name, int reload));
700 static char_u *autoload_name __ARGS((char_u *name));
701 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
702 static void func_free __ARGS((ufunc_T *fp));
703 static void func_unref __ARGS((char_u *name));
704 static void func_ref __ARGS((char_u *name));
705 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));
706 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
707 
708 /* Character used as separated in autoload function/variable names. */
709 #define AUTOLOAD_CHAR '#'
710 
711 /*
712  * Initialize the global and v: variables.
713  */
714     void
715 eval_init()
716 {
717     int		    i;
718     struct vimvar   *p;
719 
720     init_var_dict(&globvardict, &globvars_var);
721     init_var_dict(&vimvardict, &vimvars_var);
722     hash_init(&compat_hashtab);
723     hash_init(&func_hashtab);
724 
725     for (i = 0; i < VV_LEN; ++i)
726     {
727 	p = &vimvars[i];
728 	STRCPY(p->vv_di.di_key, p->vv_name);
729 	if (p->vv_flags & VV_RO)
730 	    p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
731 	else if (p->vv_flags & VV_RO_SBX)
732 	    p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
733 	else
734 	    p->vv_di.di_flags = DI_FLAGS_FIX;
735 
736 	/* add to v: scope dict, unless the value is not always available */
737 	if (p->vv_type != VAR_UNKNOWN)
738 	    hash_add(&vimvarht, p->vv_di.di_key);
739 	if (p->vv_flags & VV_COMPAT)
740 	    /* add to compat scope dict */
741 	    hash_add(&compat_hashtab, p->vv_di.di_key);
742     }
743 }
744 
745 #if defined(EXITFREE) || defined(PROTO)
746     void
747 eval_clear()
748 {
749     int		    i;
750     struct vimvar   *p;
751 
752     for (i = 0; i < VV_LEN; ++i)
753     {
754 	p = &vimvars[i];
755 	if (p->vv_di.di_tv.v_type == VAR_STRING)
756 	{
757 	    vim_free(p->vv_di.di_tv.vval.v_string);
758 	    p->vv_di.di_tv.vval.v_string = NULL;
759 	}
760     }
761     hash_clear(&vimvarht);
762     hash_clear(&compat_hashtab);
763 
764     /* script-local variables */
765     for (i = 1; i <= ga_scripts.ga_len; ++i)
766 	vars_clear(&SCRIPT_VARS(i));
767     ga_clear(&ga_scripts);
768     free_scriptnames();
769 
770     /* global variables */
771     vars_clear(&globvarht);
772 
773     /* functions */
774     free_all_functions();
775     hash_clear(&func_hashtab);
776 
777     /* unreferenced lists and dicts */
778     (void)garbage_collect();
779 }
780 #endif
781 
782 /*
783  * Return the name of the executed function.
784  */
785     char_u *
786 func_name(cookie)
787     void *cookie;
788 {
789     return ((funccall_T *)cookie)->func->uf_name;
790 }
791 
792 /*
793  * Return the address holding the next breakpoint line for a funccall cookie.
794  */
795     linenr_T *
796 func_breakpoint(cookie)
797     void *cookie;
798 {
799     return &((funccall_T *)cookie)->breakpoint;
800 }
801 
802 /*
803  * Return the address holding the debug tick for a funccall cookie.
804  */
805     int *
806 func_dbg_tick(cookie)
807     void *cookie;
808 {
809     return &((funccall_T *)cookie)->dbg_tick;
810 }
811 
812 /*
813  * Return the nesting level for a funccall cookie.
814  */
815     int
816 func_level(cookie)
817     void *cookie;
818 {
819     return ((funccall_T *)cookie)->level;
820 }
821 
822 /* pointer to funccal for currently active function */
823 funccall_T *current_funccal = NULL;
824 
825 /*
826  * Return TRUE when a function was ended by a ":return" command.
827  */
828     int
829 current_func_returned()
830 {
831     return current_funccal->returned;
832 }
833 
834 
835 /*
836  * Set an internal variable to a string value. Creates the variable if it does
837  * not already exist.
838  */
839     void
840 set_internal_string_var(name, value)
841     char_u	*name;
842     char_u	*value;
843 {
844     char_u	*val;
845     typval_T	*tvp;
846 
847     val = vim_strsave(value);
848     if (val != NULL)
849     {
850 	tvp = alloc_string_tv(val);
851 	if (tvp != NULL)
852 	{
853 	    set_var(name, tvp, FALSE);
854 	    free_tv(tvp);
855 	}
856     }
857 }
858 
859 static lval_T	*redir_lval = NULL;
860 static char_u	*redir_endp = NULL;
861 static char_u	*redir_varname = NULL;
862 
863 /*
864  * Start recording command output to a variable
865  * Returns OK if successfully completed the setup.  FAIL otherwise.
866  */
867     int
868 var_redir_start(name, append)
869     char_u	*name;
870     int		append;		/* append to an existing variable */
871 {
872     int		save_emsg;
873     int		err;
874     typval_T	tv;
875 
876     /* Make sure a valid variable name is specified */
877     if (!eval_isnamec1(*name))
878     {
879 	EMSG(_(e_invarg));
880 	return FAIL;
881     }
882 
883     redir_varname = vim_strsave(name);
884     if (redir_varname == NULL)
885 	return FAIL;
886 
887     redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
888     if (redir_lval == NULL)
889     {
890 	var_redir_stop();
891 	return FAIL;
892     }
893 
894     /* Parse the variable name (can be a dict or list entry). */
895     redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
896 							     FNE_CHECK_START);
897     if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
898     {
899 	if (redir_endp != NULL && *redir_endp != NUL)
900 	    /* Trailing characters are present after the variable name */
901 	    EMSG(_(e_trailing));
902 	else
903 	    EMSG(_(e_invarg));
904 	var_redir_stop();
905 	return FAIL;
906     }
907 
908     /* check if we can write to the variable: set it to or append an empty
909      * string */
910     save_emsg = did_emsg;
911     did_emsg = FALSE;
912     tv.v_type = VAR_STRING;
913     tv.vval.v_string = (char_u *)"";
914     if (append)
915 	set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
916     else
917 	set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
918     err = did_emsg;
919     did_emsg += save_emsg;
920     if (err)
921     {
922 	var_redir_stop();
923 	return FAIL;
924     }
925     if (redir_lval->ll_newkey != NULL)
926     {
927 	/* Dictionary item was created, don't do it again. */
928 	vim_free(redir_lval->ll_newkey);
929 	redir_lval->ll_newkey = NULL;
930     }
931 
932     return OK;
933 }
934 
935 /*
936  * Append "value[len]" to the variable set by var_redir_start().
937  */
938     void
939 var_redir_str(value, len)
940     char_u	*value;
941     int		len;
942 {
943     char_u	*val;
944     typval_T	tv;
945     int		save_emsg;
946     int		err;
947 
948     if (redir_lval == NULL)
949 	return;
950 
951     if (len == -1)
952 	/* Append the entire string */
953 	val = vim_strsave(value);
954     else
955 	/* Append only the specified number of characters */
956 	val = vim_strnsave(value, len);
957     if (val == NULL)
958 	return;
959 
960     tv.v_type = VAR_STRING;
961     tv.vval.v_string = val;
962 
963     save_emsg = did_emsg;
964     did_emsg = FALSE;
965     set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
966     err = did_emsg;
967     did_emsg += save_emsg;
968     if (err)
969 	var_redir_stop();
970 
971     vim_free(tv.vval.v_string);
972 }
973 
974 /*
975  * Stop redirecting command output to a variable.
976  */
977     void
978 var_redir_stop()
979 {
980     if (redir_lval != NULL)
981     {
982 	clear_lval(redir_lval);
983 	vim_free(redir_lval);
984 	redir_lval = NULL;
985     }
986     vim_free(redir_varname);
987     redir_varname = NULL;
988 }
989 
990 # if defined(FEAT_MBYTE) || defined(PROTO)
991     int
992 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
993     char_u	*enc_from;
994     char_u	*enc_to;
995     char_u	*fname_from;
996     char_u	*fname_to;
997 {
998     int		err = FALSE;
999 
1000     set_vim_var_string(VV_CC_FROM, enc_from, -1);
1001     set_vim_var_string(VV_CC_TO, enc_to, -1);
1002     set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1003     set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1004     if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1005 	err = TRUE;
1006     set_vim_var_string(VV_CC_FROM, NULL, -1);
1007     set_vim_var_string(VV_CC_TO, NULL, -1);
1008     set_vim_var_string(VV_FNAME_IN, NULL, -1);
1009     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1010 
1011     if (err)
1012 	return FAIL;
1013     return OK;
1014 }
1015 # endif
1016 
1017 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1018     int
1019 eval_printexpr(fname, args)
1020     char_u	*fname;
1021     char_u	*args;
1022 {
1023     int		err = FALSE;
1024 
1025     set_vim_var_string(VV_FNAME_IN, fname, -1);
1026     set_vim_var_string(VV_CMDARG, args, -1);
1027     if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1028 	err = TRUE;
1029     set_vim_var_string(VV_FNAME_IN, NULL, -1);
1030     set_vim_var_string(VV_CMDARG, NULL, -1);
1031 
1032     if (err)
1033     {
1034 	mch_remove(fname);
1035 	return FAIL;
1036     }
1037     return OK;
1038 }
1039 # endif
1040 
1041 # if defined(FEAT_DIFF) || defined(PROTO)
1042     void
1043 eval_diff(origfile, newfile, outfile)
1044     char_u	*origfile;
1045     char_u	*newfile;
1046     char_u	*outfile;
1047 {
1048     int		err = FALSE;
1049 
1050     set_vim_var_string(VV_FNAME_IN, origfile, -1);
1051     set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1052     set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1053     (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1054     set_vim_var_string(VV_FNAME_IN, NULL, -1);
1055     set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1056     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1057 }
1058 
1059     void
1060 eval_patch(origfile, difffile, outfile)
1061     char_u	*origfile;
1062     char_u	*difffile;
1063     char_u	*outfile;
1064 {
1065     int		err;
1066 
1067     set_vim_var_string(VV_FNAME_IN, origfile, -1);
1068     set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1069     set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1070     (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1071     set_vim_var_string(VV_FNAME_IN, NULL, -1);
1072     set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1073     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1074 }
1075 # endif
1076 
1077 /*
1078  * Top level evaluation function, returning a boolean.
1079  * Sets "error" to TRUE if there was an error.
1080  * Return TRUE or FALSE.
1081  */
1082     int
1083 eval_to_bool(arg, error, nextcmd, skip)
1084     char_u	*arg;
1085     int		*error;
1086     char_u	**nextcmd;
1087     int		skip;	    /* only parse, don't execute */
1088 {
1089     typval_T	tv;
1090     int		retval = FALSE;
1091 
1092     if (skip)
1093 	++emsg_skip;
1094     if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1095 	*error = TRUE;
1096     else
1097     {
1098 	*error = FALSE;
1099 	if (!skip)
1100 	{
1101 	    retval = (get_tv_number_chk(&tv, error) != 0);
1102 	    clear_tv(&tv);
1103 	}
1104     }
1105     if (skip)
1106 	--emsg_skip;
1107 
1108     return retval;
1109 }
1110 
1111 /*
1112  * Top level evaluation function, returning a string.  If "skip" is TRUE,
1113  * only parsing to "nextcmd" is done, without reporting errors.  Return
1114  * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1115  */
1116     char_u *
1117 eval_to_string_skip(arg, nextcmd, skip)
1118     char_u	*arg;
1119     char_u	**nextcmd;
1120     int		skip;	    /* only parse, don't execute */
1121 {
1122     typval_T	tv;
1123     char_u	*retval;
1124 
1125     if (skip)
1126 	++emsg_skip;
1127     if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1128 	retval = NULL;
1129     else
1130     {
1131 	retval = vim_strsave(get_tv_string(&tv));
1132 	clear_tv(&tv);
1133     }
1134     if (skip)
1135 	--emsg_skip;
1136 
1137     return retval;
1138 }
1139 
1140 /*
1141  * Skip over an expression at "*pp".
1142  * Return FAIL for an error, OK otherwise.
1143  */
1144     int
1145 skip_expr(pp)
1146     char_u	**pp;
1147 {
1148     typval_T	rettv;
1149 
1150     *pp = skipwhite(*pp);
1151     return eval1(pp, &rettv, FALSE);
1152 }
1153 
1154 /*
1155  * Top level evaluation function, returning a string.
1156  * Return pointer to allocated memory, or NULL for failure.
1157  */
1158     char_u *
1159 eval_to_string(arg, nextcmd)
1160     char_u	*arg;
1161     char_u	**nextcmd;
1162 {
1163     typval_T	tv;
1164     char_u	*retval;
1165 
1166     if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1167 	retval = NULL;
1168     else
1169     {
1170 	retval = vim_strsave(get_tv_string(&tv));
1171 	clear_tv(&tv);
1172     }
1173 
1174     return retval;
1175 }
1176 
1177 /*
1178  * Call eval_to_string() with "sandbox" set and not using local variables.
1179  */
1180     char_u *
1181 eval_to_string_safe(arg, nextcmd)
1182     char_u	*arg;
1183     char_u	**nextcmd;
1184 {
1185     char_u	*retval;
1186     void	*save_funccalp;
1187 
1188     save_funccalp = save_funccal();
1189     ++sandbox;
1190     retval = eval_to_string(arg, nextcmd);
1191     --sandbox;
1192     restore_funccal(save_funccalp);
1193     return retval;
1194 }
1195 
1196 /*
1197  * Top level evaluation function, returning a number.
1198  * Evaluates "expr" silently.
1199  * Returns -1 for an error.
1200  */
1201     int
1202 eval_to_number(expr)
1203     char_u	*expr;
1204 {
1205     typval_T	rettv;
1206     int		retval;
1207     char_u	*p = skipwhite(expr);
1208 
1209     ++emsg_off;
1210 
1211     if (eval1(&p, &rettv, TRUE) == FAIL)
1212 	retval = -1;
1213     else
1214     {
1215 	retval = get_tv_number_chk(&rettv, NULL);
1216 	clear_tv(&rettv);
1217     }
1218     --emsg_off;
1219 
1220     return retval;
1221 }
1222 
1223 /*
1224  * Prepare v: variable "idx" to be used.
1225  * Save the current typeval in "save_tv".
1226  * When not used yet add the variable to the v: hashtable.
1227  */
1228     static void
1229 prepare_vimvar(idx, save_tv)
1230     int		idx;
1231     typval_T	*save_tv;
1232 {
1233     *save_tv = vimvars[idx].vv_tv;
1234     if (vimvars[idx].vv_type == VAR_UNKNOWN)
1235 	hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1236 }
1237 
1238 /*
1239  * Restore v: variable "idx" to typeval "save_tv".
1240  * When no longer defined, remove the variable from the v: hashtable.
1241  */
1242     static void
1243 restore_vimvar(idx, save_tv)
1244     int		idx;
1245     typval_T	*save_tv;
1246 {
1247     hashitem_T	*hi;
1248 
1249     clear_tv(&vimvars[idx].vv_tv);
1250     vimvars[idx].vv_tv = *save_tv;
1251     if (vimvars[idx].vv_type == VAR_UNKNOWN)
1252     {
1253 	hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1254 	if (HASHITEM_EMPTY(hi))
1255 	    EMSG2(_(e_intern2), "restore_vimvar()");
1256 	else
1257 	    hash_remove(&vimvarht, hi);
1258     }
1259 }
1260 
1261 #if defined(FEAT_SYN_HL) || defined(PROTO)
1262 /*
1263  * Evaluate an expression to a list with suggestions.
1264  * For the "expr:" part of 'spellsuggest'.
1265  */
1266     list_T *
1267 eval_spell_expr(badword, expr)
1268     char_u	*badword;
1269     char_u	*expr;
1270 {
1271     typval_T	save_val;
1272     typval_T	rettv;
1273     list_T	*list = NULL;
1274     char_u	*p = skipwhite(expr);
1275 
1276     /* Set "v:val" to the bad word. */
1277     prepare_vimvar(VV_VAL, &save_val);
1278     vimvars[VV_VAL].vv_type = VAR_STRING;
1279     vimvars[VV_VAL].vv_str = badword;
1280     if (p_verbose == 0)
1281 	++emsg_off;
1282 
1283     if (eval1(&p, &rettv, TRUE) == OK)
1284     {
1285 	if (rettv.v_type != VAR_LIST)
1286 	    clear_tv(&rettv);
1287 	else
1288 	    list = rettv.vval.v_list;
1289     }
1290 
1291     if (p_verbose == 0)
1292 	--emsg_off;
1293     vimvars[VV_VAL].vv_str = NULL;
1294     restore_vimvar(VV_VAL, &save_val);
1295 
1296     return list;
1297 }
1298 
1299 /*
1300  * "list" is supposed to contain two items: a word and a number.  Return the
1301  * word in "pp" and the number as the return value.
1302  * Return -1 if anything isn't right.
1303  * Used to get the good word and score from the eval_spell_expr() result.
1304  */
1305     int
1306 get_spellword(list, pp)
1307     list_T	*list;
1308     char_u	**pp;
1309 {
1310     listitem_T	*li;
1311 
1312     li = list->lv_first;
1313     if (li == NULL)
1314 	return -1;
1315     *pp = get_tv_string(&li->li_tv);
1316 
1317     li = li->li_next;
1318     if (li == NULL)
1319 	return -1;
1320     return get_tv_number(&li->li_tv);
1321 }
1322 #endif
1323 
1324 /*
1325  * Top level evaluation function.
1326  * Returns an allocated typval_T with the result.
1327  * Returns NULL when there is an error.
1328  */
1329     typval_T *
1330 eval_expr(arg, nextcmd)
1331     char_u	*arg;
1332     char_u	**nextcmd;
1333 {
1334     typval_T	*tv;
1335 
1336     tv = (typval_T *)alloc(sizeof(typval_T));
1337     if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1338     {
1339 	vim_free(tv);
1340 	tv = NULL;
1341     }
1342 
1343     return tv;
1344 }
1345 
1346 
1347 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1348 /*
1349  * Call some vimL function and return the result in "*rettv".
1350  * Uses argv[argc] for the function arguments.
1351  * Returns OK or FAIL.
1352  */
1353     static int
1354 call_vim_function(func, argc, argv, safe, rettv)
1355     char_u      *func;
1356     int		argc;
1357     char_u      **argv;
1358     int		safe;		/* use the sandbox */
1359     typval_T	*rettv;
1360 {
1361     typval_T	*argvars;
1362     long	n;
1363     int		len;
1364     int		i;
1365     int		doesrange;
1366     void	*save_funccalp = NULL;
1367     int		ret;
1368 
1369     argvars = (typval_T *)alloc((unsigned)(argc * sizeof(typval_T)));
1370     if (argvars == NULL)
1371 	return FAIL;
1372 
1373     for (i = 0; i < argc; i++)
1374     {
1375 	/* Pass a NULL or empty argument as an empty string */
1376 	if (argv[i] == NULL || *argv[i] == NUL)
1377 	{
1378 	    argvars[i].v_type = VAR_STRING;
1379 	    argvars[i].vval.v_string = (char_u *)"";
1380 	    continue;
1381 	}
1382 
1383 	/* Recognize a number argument, the others must be strings. */
1384 	vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1385 	if (len != 0 && len == (int)STRLEN(argv[i]))
1386 	{
1387 	    argvars[i].v_type = VAR_NUMBER;
1388 	    argvars[i].vval.v_number = n;
1389 	}
1390 	else
1391 	{
1392 	    argvars[i].v_type = VAR_STRING;
1393 	    argvars[i].vval.v_string = argv[i];
1394 	}
1395     }
1396 
1397     if (safe)
1398     {
1399 	save_funccalp = save_funccal();
1400 	++sandbox;
1401     }
1402 
1403     rettv->v_type = VAR_UNKNOWN;		/* clear_tv() uses this */
1404     ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1405 		    curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1406 		    &doesrange, TRUE, NULL);
1407     if (safe)
1408     {
1409 	--sandbox;
1410 	restore_funccal(save_funccalp);
1411     }
1412     vim_free(argvars);
1413 
1414     if (ret == FAIL)
1415 	clear_tv(rettv);
1416 
1417     return ret;
1418 }
1419 
1420 /*
1421  * Call vimL function "func" and return the result as a string.
1422  * Returns NULL when calling the function fails.
1423  * Uses argv[argc] for the function arguments.
1424  */
1425     void *
1426 call_func_retstr(func, argc, argv, safe)
1427     char_u      *func;
1428     int		argc;
1429     char_u      **argv;
1430     int		safe;		/* use the sandbox */
1431 {
1432     typval_T	rettv;
1433     char_u	*retval;
1434 
1435     if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1436 	return NULL;
1437 
1438     retval = vim_strsave(get_tv_string(&rettv));
1439     clear_tv(&rettv);
1440     return retval;
1441 }
1442 
1443 #if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1444 /*
1445  * Call vimL function "func" and return the result as a number.
1446  * Returns -1 when calling the function fails.
1447  * Uses argv[argc] for the function arguments.
1448  */
1449     long
1450 call_func_retnr(func, argc, argv, safe)
1451     char_u      *func;
1452     int		argc;
1453     char_u      **argv;
1454     int		safe;		/* use the sandbox */
1455 {
1456     typval_T	rettv;
1457     long	retval;
1458 
1459     if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1460 	return -1;
1461 
1462     retval = get_tv_number_chk(&rettv, NULL);
1463     clear_tv(&rettv);
1464     return retval;
1465 }
1466 #endif
1467 
1468 /*
1469  * Call vimL function "func" and return the result as a list
1470  * Uses argv[argc] for the function arguments.
1471  */
1472     void *
1473 call_func_retlist(func, argc, argv, safe)
1474     char_u      *func;
1475     int		argc;
1476     char_u      **argv;
1477     int		safe;		/* use the sandbox */
1478 {
1479     typval_T	rettv;
1480 
1481     if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1482 	return NULL;
1483 
1484     if (rettv.v_type != VAR_LIST)
1485     {
1486 	clear_tv(&rettv);
1487 	return NULL;
1488     }
1489 
1490     return rettv.vval.v_list;
1491 }
1492 
1493 #endif
1494 
1495 /*
1496  * Save the current function call pointer, and set it to NULL.
1497  * Used when executing autocommands and for ":source".
1498  */
1499     void *
1500 save_funccal()
1501 {
1502     funccall_T *fc = current_funccal;
1503 
1504     current_funccal = NULL;
1505     return (void *)fc;
1506 }
1507 
1508     void
1509 restore_funccal(vfc)
1510     void *vfc;
1511 {
1512     funccall_T *fc = (funccall_T *)vfc;
1513 
1514     current_funccal = fc;
1515 }
1516 
1517 #if defined(FEAT_PROFILE) || defined(PROTO)
1518 /*
1519  * Prepare profiling for entering a child or something else that is not
1520  * counted for the script/function itself.
1521  * Should always be called in pair with prof_child_exit().
1522  */
1523     void
1524 prof_child_enter(tm)
1525     proftime_T *tm;	/* place to store waittime */
1526 {
1527     funccall_T *fc = current_funccal;
1528 
1529     if (fc != NULL && fc->func->uf_profiling)
1530 	profile_start(&fc->prof_child);
1531     script_prof_save(tm);
1532 }
1533 
1534 /*
1535  * Take care of time spent in a child.
1536  * Should always be called after prof_child_enter().
1537  */
1538     void
1539 prof_child_exit(tm)
1540     proftime_T *tm;	/* where waittime was stored */
1541 {
1542     funccall_T *fc = current_funccal;
1543 
1544     if (fc != NULL && fc->func->uf_profiling)
1545     {
1546 	profile_end(&fc->prof_child);
1547 	profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1548 	profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1549 	profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1550     }
1551     script_prof_restore(tm);
1552 }
1553 #endif
1554 
1555 
1556 #ifdef FEAT_FOLDING
1557 /*
1558  * Evaluate 'foldexpr'.  Returns the foldlevel, and any character preceding
1559  * it in "*cp".  Doesn't give error messages.
1560  */
1561     int
1562 eval_foldexpr(arg, cp)
1563     char_u	*arg;
1564     int		*cp;
1565 {
1566     typval_T	tv;
1567     int		retval;
1568     char_u	*s;
1569 
1570     ++emsg_off;
1571     ++sandbox;
1572     *cp = NUL;
1573     if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1574 	retval = 0;
1575     else
1576     {
1577 	/* If the result is a number, just return the number. */
1578 	if (tv.v_type == VAR_NUMBER)
1579 	    retval = tv.vval.v_number;
1580 	else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1581 	    retval = 0;
1582 	else
1583 	{
1584 	    /* If the result is a string, check if there is a non-digit before
1585 	     * the number. */
1586 	    s = tv.vval.v_string;
1587 	    if (!VIM_ISDIGIT(*s) && *s != '-')
1588 		*cp = *s++;
1589 	    retval = atol((char *)s);
1590 	}
1591 	clear_tv(&tv);
1592     }
1593     --emsg_off;
1594     --sandbox;
1595 
1596     return retval;
1597 }
1598 #endif
1599 
1600 /*
1601  * ":let"			list all variable values
1602  * ":let var1 var2"		list variable values
1603  * ":let var = expr"		assignment command.
1604  * ":let var += expr"		assignment command.
1605  * ":let var -= expr"		assignment command.
1606  * ":let var .= expr"		assignment command.
1607  * ":let [var1, var2] = expr"	unpack list.
1608  */
1609     void
1610 ex_let(eap)
1611     exarg_T	*eap;
1612 {
1613     char_u	*arg = eap->arg;
1614     char_u	*expr = NULL;
1615     typval_T	rettv;
1616     int		i;
1617     int		var_count = 0;
1618     int		semicolon = 0;
1619     char_u	op[2];
1620 
1621     expr = skip_var_list(arg, &var_count, &semicolon);
1622     if (expr == NULL)
1623 	return;
1624     expr = vim_strchr(expr, '=');
1625     if (expr == NULL)
1626     {
1627 	/*
1628 	 * ":let" without "=": list variables
1629 	 */
1630 	if (*arg == '[')
1631 	    EMSG(_(e_invarg));
1632 	else if (!ends_excmd(*arg))
1633 	    /* ":let var1 var2" */
1634 	    arg = list_arg_vars(eap, arg);
1635 	else if (!eap->skip)
1636 	{
1637 	    /* ":let" */
1638 	    list_glob_vars();
1639 	    list_buf_vars();
1640 	    list_win_vars();
1641 	    list_vim_vars();
1642 	}
1643 	eap->nextcmd = check_nextcmd(arg);
1644     }
1645     else
1646     {
1647 	op[0] = '=';
1648 	op[1] = NUL;
1649 	if (expr > arg)
1650 	{
1651 	    if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1652 		op[0] = expr[-1];   /* +=, -= or .= */
1653 	}
1654 	expr = skipwhite(expr + 1);
1655 
1656 	if (eap->skip)
1657 	    ++emsg_skip;
1658 	i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1659 	if (eap->skip)
1660 	{
1661 	    if (i != FAIL)
1662 		clear_tv(&rettv);
1663 	    --emsg_skip;
1664 	}
1665 	else if (i != FAIL)
1666 	{
1667 	    (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1668 									  op);
1669 	    clear_tv(&rettv);
1670 	}
1671     }
1672 }
1673 
1674 /*
1675  * Assign the typevalue "tv" to the variable or variables at "arg_start".
1676  * Handles both "var" with any type and "[var, var; var]" with a list type.
1677  * When "nextchars" is not NULL it points to a string with characters that
1678  * must appear after the variable(s).  Use "+", "-" or "." for add, subtract
1679  * or concatenate.
1680  * Returns OK or FAIL;
1681  */
1682     static int
1683 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1684     char_u	*arg_start;
1685     typval_T	*tv;
1686     int		copy;		/* copy values from "tv", don't move */
1687     int		semicolon;	/* from skip_var_list() */
1688     int		var_count;	/* from skip_var_list() */
1689     char_u	*nextchars;
1690 {
1691     char_u	*arg = arg_start;
1692     list_T	*l;
1693     int		i;
1694     listitem_T	*item;
1695     typval_T	ltv;
1696 
1697     if (*arg != '[')
1698     {
1699 	/*
1700 	 * ":let var = expr" or ":for var in list"
1701 	 */
1702 	if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1703 	    return FAIL;
1704 	return OK;
1705     }
1706 
1707     /*
1708      * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1709      */
1710     if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1711     {
1712 	EMSG(_(e_listreq));
1713 	return FAIL;
1714     }
1715 
1716     i = list_len(l);
1717     if (semicolon == 0 && var_count < i)
1718     {
1719 	EMSG(_("E687: Less targets than List items"));
1720 	return FAIL;
1721     }
1722     if (var_count - semicolon > i)
1723     {
1724 	EMSG(_("E688: More targets than List items"));
1725 	return FAIL;
1726     }
1727 
1728     item = l->lv_first;
1729     while (*arg != ']')
1730     {
1731 	arg = skipwhite(arg + 1);
1732 	arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1733 	item = item->li_next;
1734 	if (arg == NULL)
1735 	    return FAIL;
1736 
1737 	arg = skipwhite(arg);
1738 	if (*arg == ';')
1739 	{
1740 	    /* Put the rest of the list (may be empty) in the var after ';'.
1741 	     * Create a new list for this. */
1742 	    l = list_alloc();
1743 	    if (l == NULL)
1744 		return FAIL;
1745 	    while (item != NULL)
1746 	    {
1747 		list_append_tv(l, &item->li_tv);
1748 		item = item->li_next;
1749 	    }
1750 
1751 	    ltv.v_type = VAR_LIST;
1752 	    ltv.v_lock = 0;
1753 	    ltv.vval.v_list = l;
1754 	    l->lv_refcount = 1;
1755 
1756 	    arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1757 						    (char_u *)"]", nextchars);
1758 	    clear_tv(&ltv);
1759 	    if (arg == NULL)
1760 		return FAIL;
1761 	    break;
1762 	}
1763 	else if (*arg != ',' && *arg != ']')
1764 	{
1765 	    EMSG2(_(e_intern2), "ex_let_vars()");
1766 	    return FAIL;
1767 	}
1768     }
1769 
1770     return OK;
1771 }
1772 
1773 /*
1774  * Skip over assignable variable "var" or list of variables "[var, var]".
1775  * Used for ":let varvar = expr" and ":for varvar in expr".
1776  * For "[var, var]" increment "*var_count" for each variable.
1777  * for "[var, var; var]" set "semicolon".
1778  * Return NULL for an error.
1779  */
1780     static char_u *
1781 skip_var_list(arg, var_count, semicolon)
1782     char_u	*arg;
1783     int		*var_count;
1784     int		*semicolon;
1785 {
1786     char_u	*p, *s;
1787 
1788     if (*arg == '[')
1789     {
1790 	/* "[var, var]": find the matching ']'. */
1791 	p = arg;
1792 	for (;;)
1793 	{
1794 	    p = skipwhite(p + 1);	/* skip whites after '[', ';' or ',' */
1795 	    s = skip_var_one(p);
1796 	    if (s == p)
1797 	    {
1798 		EMSG2(_(e_invarg2), p);
1799 		return NULL;
1800 	    }
1801 	    ++*var_count;
1802 
1803 	    p = skipwhite(s);
1804 	    if (*p == ']')
1805 		break;
1806 	    else if (*p == ';')
1807 	    {
1808 		if (*semicolon == 1)
1809 		{
1810 		    EMSG(_("Double ; in list of variables"));
1811 		    return NULL;
1812 		}
1813 		*semicolon = 1;
1814 	    }
1815 	    else if (*p != ',')
1816 	    {
1817 		EMSG2(_(e_invarg2), p);
1818 		return NULL;
1819 	    }
1820 	}
1821 	return p + 1;
1822     }
1823     else
1824 	return skip_var_one(arg);
1825 }
1826 
1827 /*
1828  * Skip one (assignable) variable name, includig @r, $VAR, &option, d.key,
1829  * l[idx].
1830  */
1831     static char_u *
1832 skip_var_one(arg)
1833     char_u	*arg;
1834 {
1835     if (*arg == '@' && arg[1] != NUL)
1836 	return arg + 2;
1837     return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1838 				   NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1839 }
1840 
1841 /*
1842  * List variables for hashtab "ht" with prefix "prefix".
1843  * If "empty" is TRUE also list NULL strings as empty strings.
1844  */
1845     static void
1846 list_hashtable_vars(ht, prefix, empty)
1847     hashtab_T	*ht;
1848     char_u	*prefix;
1849     int		empty;
1850 {
1851     hashitem_T	*hi;
1852     dictitem_T	*di;
1853     int		todo;
1854 
1855     todo = ht->ht_used;
1856     for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
1857     {
1858 	if (!HASHITEM_EMPTY(hi))
1859 	{
1860 	    --todo;
1861 	    di = HI2DI(hi);
1862 	    if (empty || di->di_tv.v_type != VAR_STRING
1863 					   || di->di_tv.vval.v_string != NULL)
1864 		list_one_var(di, prefix);
1865 	}
1866     }
1867 }
1868 
1869 /*
1870  * List global variables.
1871  */
1872     static void
1873 list_glob_vars()
1874 {
1875     list_hashtable_vars(&globvarht, (char_u *)"", TRUE);
1876 }
1877 
1878 /*
1879  * List buffer variables.
1880  */
1881     static void
1882 list_buf_vars()
1883 {
1884     char_u	numbuf[NUMBUFLEN];
1885 
1886     list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:", TRUE);
1887 
1888     sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
1889     list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER, numbuf);
1890 }
1891 
1892 /*
1893  * List window variables.
1894  */
1895     static void
1896 list_win_vars()
1897 {
1898     list_hashtable_vars(&curwin->w_vars.dv_hashtab, (char_u *)"w:", TRUE);
1899 }
1900 
1901 /*
1902  * List Vim variables.
1903  */
1904     static void
1905 list_vim_vars()
1906 {
1907     list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE);
1908 }
1909 
1910 /*
1911  * List variables in "arg".
1912  */
1913     static char_u *
1914 list_arg_vars(eap, arg)
1915     exarg_T	*eap;
1916     char_u	*arg;
1917 {
1918     int		error = FALSE;
1919     int		len;
1920     char_u	*name;
1921     char_u	*name_start;
1922     char_u	*arg_subsc;
1923     char_u	*tofree;
1924     typval_T    tv;
1925 
1926     while (!ends_excmd(*arg) && !got_int)
1927     {
1928 	if (error || eap->skip)
1929 	{
1930 	    arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1931 	    if (!vim_iswhite(*arg) && !ends_excmd(*arg))
1932 	    {
1933 		emsg_severe = TRUE;
1934 		EMSG(_(e_trailing));
1935 		break;
1936 	    }
1937 	}
1938 	else
1939 	{
1940 	    /* get_name_len() takes care of expanding curly braces */
1941 	    name_start = name = arg;
1942 	    len = get_name_len(&arg, &tofree, TRUE, TRUE);
1943 	    if (len <= 0)
1944 	    {
1945 		/* This is mainly to keep test 49 working: when expanding
1946 		 * curly braces fails overrule the exception error message. */
1947 		if (len < 0 && !aborting())
1948 		{
1949 		    emsg_severe = TRUE;
1950 		    EMSG2(_(e_invarg2), arg);
1951 		    break;
1952 		}
1953 		error = TRUE;
1954 	    }
1955 	    else
1956 	    {
1957 		if (tofree != NULL)
1958 		    name = tofree;
1959 		if (get_var_tv(name, len, &tv, TRUE) == FAIL)
1960 		    error = TRUE;
1961 		else
1962 		{
1963 		    /* handle d.key, l[idx], f(expr) */
1964 		    arg_subsc = arg;
1965 		    if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
1966 			error = TRUE;
1967 		    else
1968 		    {
1969 			if (arg == arg_subsc && len == 2 && name[1] == ':')
1970 			{
1971 			    switch (*name)
1972 			    {
1973 				case 'g': list_glob_vars(); break;
1974 				case 'b': list_buf_vars(); break;
1975 				case 'w': list_win_vars(); break;
1976 				case 'v': list_vim_vars(); break;
1977 				default:
1978 					  EMSG2(_("E738: Can't list variables for %s"), name);
1979 			    }
1980 			}
1981 			else
1982 			{
1983 			    char_u	numbuf[NUMBUFLEN];
1984 			    char_u	*tf;
1985 			    int		c;
1986 			    char_u	*s;
1987 
1988 			    s = echo_string(&tv, &tf, numbuf);
1989 			    c = *arg;
1990 			    *arg = NUL;
1991 			    list_one_var_a((char_u *)"",
1992 				    arg == arg_subsc ? name : name_start,
1993 				    tv.v_type, s == NULL ? (char_u *)"" : s);
1994 			    *arg = c;
1995 			    vim_free(tf);
1996 			}
1997 			clear_tv(&tv);
1998 		    }
1999 		}
2000 	    }
2001 
2002 	    vim_free(tofree);
2003 	}
2004 
2005 	arg = skipwhite(arg);
2006     }
2007 
2008     return arg;
2009 }
2010 
2011 /*
2012  * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2013  * Returns a pointer to the char just after the var name.
2014  * Returns NULL if there is an error.
2015  */
2016     static char_u *
2017 ex_let_one(arg, tv, copy, endchars, op)
2018     char_u	*arg;		/* points to variable name */
2019     typval_T	*tv;		/* value to assign to variable */
2020     int		copy;		/* copy value from "tv" */
2021     char_u	*endchars;	/* valid chars after variable name  or NULL */
2022     char_u	*op;		/* "+", "-", "."  or NULL*/
2023 {
2024     int		c1;
2025     char_u	*name;
2026     char_u	*p;
2027     char_u	*arg_end = NULL;
2028     int		len;
2029     int		opt_flags;
2030     char_u	*tofree = NULL;
2031 
2032     /*
2033      * ":let $VAR = expr": Set environment variable.
2034      */
2035     if (*arg == '$')
2036     {
2037 	/* Find the end of the name. */
2038 	++arg;
2039 	name = arg;
2040 	len = get_env_len(&arg);
2041 	if (len == 0)
2042 	    EMSG2(_(e_invarg2), name - 1);
2043 	else
2044 	{
2045 	    if (op != NULL && (*op == '+' || *op == '-'))
2046 		EMSG2(_(e_letwrong), op);
2047 	    else if (endchars != NULL
2048 			     && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2049 		EMSG(_(e_letunexp));
2050 	    else
2051 	    {
2052 		c1 = name[len];
2053 		name[len] = NUL;
2054 		p = get_tv_string_chk(tv);
2055 		if (p != NULL && op != NULL && *op == '.')
2056 		{
2057 		    int	    mustfree = FALSE;
2058 		    char_u  *s = vim_getenv(name, &mustfree);
2059 
2060 		    if (s != NULL)
2061 		    {
2062 			p = tofree = concat_str(s, p);
2063 			if (mustfree)
2064 			    vim_free(s);
2065 		    }
2066 		}
2067 		if (p != NULL)
2068 		{
2069 		    vim_setenv(name, p);
2070 		    if (STRICMP(name, "HOME") == 0)
2071 			init_homedir();
2072 		    else if (didset_vim && STRICMP(name, "VIM") == 0)
2073 			didset_vim = FALSE;
2074 		    else if (didset_vimruntime
2075 					&& STRICMP(name, "VIMRUNTIME") == 0)
2076 			didset_vimruntime = FALSE;
2077 		    arg_end = arg;
2078 		}
2079 		name[len] = c1;
2080 		vim_free(tofree);
2081 	    }
2082 	}
2083     }
2084 
2085     /*
2086      * ":let &option = expr": Set option value.
2087      * ":let &l:option = expr": Set local option value.
2088      * ":let &g:option = expr": Set global option value.
2089      */
2090     else if (*arg == '&')
2091     {
2092 	/* Find the end of the name. */
2093 	p = find_option_end(&arg, &opt_flags);
2094 	if (p == NULL || (endchars != NULL
2095 			      && vim_strchr(endchars, *skipwhite(p)) == NULL))
2096 	    EMSG(_(e_letunexp));
2097 	else
2098 	{
2099 	    long	n;
2100 	    int		opt_type;
2101 	    long	numval;
2102 	    char_u	*stringval = NULL;
2103 	    char_u	*s;
2104 
2105 	    c1 = *p;
2106 	    *p = NUL;
2107 
2108 	    n = get_tv_number(tv);
2109 	    s = get_tv_string_chk(tv);	    /* != NULL if number or string */
2110 	    if (s != NULL && op != NULL && *op != '=')
2111 	    {
2112 		opt_type = get_option_value(arg, &numval,
2113 						       &stringval, opt_flags);
2114 		if ((opt_type == 1 && *op == '.')
2115 			|| (opt_type == 0 && *op != '.'))
2116 		    EMSG2(_(e_letwrong), op);
2117 		else
2118 		{
2119 		    if (opt_type == 1)  /* number */
2120 		    {
2121 			if (*op == '+')
2122 			    n = numval + n;
2123 			else
2124 			    n = numval - n;
2125 		    }
2126 		    else if (opt_type == 0 && stringval != NULL) /* string */
2127 		    {
2128 			s = concat_str(stringval, s);
2129 			vim_free(stringval);
2130 			stringval = s;
2131 		    }
2132 		}
2133 	    }
2134 	    if (s != NULL)
2135 	    {
2136 		set_option_value(arg, n, s, opt_flags);
2137 		arg_end = p;
2138 	    }
2139 	    *p = c1;
2140 	    vim_free(stringval);
2141 	}
2142     }
2143 
2144     /*
2145      * ":let @r = expr": Set register contents.
2146      */
2147     else if (*arg == '@')
2148     {
2149 	++arg;
2150 	if (op != NULL && (*op == '+' || *op == '-'))
2151 	    EMSG2(_(e_letwrong), op);
2152 	else if (endchars != NULL
2153 			 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2154 	    EMSG(_(e_letunexp));
2155 	else
2156 	{
2157 	    char_u	*tofree = NULL;
2158 	    char_u	*s;
2159 
2160 	    p = get_tv_string_chk(tv);
2161 	    if (p != NULL && op != NULL && *op == '.')
2162 	    {
2163 		s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2164 		if (s != NULL)
2165 		{
2166 		    p = tofree = concat_str(s, p);
2167 		    vim_free(s);
2168 		}
2169 	    }
2170 	    if (p != NULL)
2171 	    {
2172 		write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2173 		arg_end = arg + 1;
2174 	    }
2175 	    vim_free(tofree);
2176 	}
2177     }
2178 
2179     /*
2180      * ":let var = expr": Set internal variable.
2181      * ":let {expr} = expr": Idem, name made with curly braces
2182      */
2183     else if (eval_isnamec1(*arg) || *arg == '{')
2184     {
2185 	lval_T	lv;
2186 
2187 	p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2188 	if (p != NULL && lv.ll_name != NULL)
2189 	{
2190 	    if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2191 		EMSG(_(e_letunexp));
2192 	    else
2193 	    {
2194 		set_var_lval(&lv, p, tv, copy, op);
2195 		arg_end = p;
2196 	    }
2197 	}
2198 	clear_lval(&lv);
2199     }
2200 
2201     else
2202 	EMSG2(_(e_invarg2), arg);
2203 
2204     return arg_end;
2205 }
2206 
2207 /*
2208  * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2209  */
2210     static int
2211 check_changedtick(arg)
2212     char_u	*arg;
2213 {
2214     if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2215     {
2216 	EMSG2(_(e_readonlyvar), arg);
2217 	return TRUE;
2218     }
2219     return FALSE;
2220 }
2221 
2222 /*
2223  * Get an lval: variable, Dict item or List item that can be assigned a value
2224  * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2225  * "name.key", "name.key[expr]" etc.
2226  * Indexing only works if "name" is an existing List or Dictionary.
2227  * "name" points to the start of the name.
2228  * If "rettv" is not NULL it points to the value to be assigned.
2229  * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2230  * wrong; must end in space or cmd separator.
2231  *
2232  * Returns a pointer to just after the name, including indexes.
2233  * When an evaluation error occurs "lp->ll_name" is NULL;
2234  * Returns NULL for a parsing error.  Still need to free items in "lp"!
2235  */
2236     static char_u *
2237 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2238     char_u	*name;
2239     typval_T	*rettv;
2240     lval_T	*lp;
2241     int		unlet;
2242     int		skip;
2243     int		quiet;	    /* don't give error messages */
2244     int		fne_flags;  /* flags for find_name_end() */
2245 {
2246     char_u	*p;
2247     char_u	*expr_start, *expr_end;
2248     int		cc;
2249     dictitem_T	*v;
2250     typval_T	var1;
2251     typval_T	var2;
2252     int		empty1 = FALSE;
2253     listitem_T	*ni;
2254     char_u	*key = NULL;
2255     int		len;
2256     hashtab_T	*ht;
2257 
2258     /* Clear everything in "lp". */
2259     vim_memset(lp, 0, sizeof(lval_T));
2260 
2261     if (skip)
2262     {
2263 	/* When skipping just find the end of the name. */
2264 	lp->ll_name = name;
2265 	return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2266     }
2267 
2268     /* Find the end of the name. */
2269     p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2270     if (expr_start != NULL)
2271     {
2272 	/* Don't expand the name when we already know there is an error. */
2273 	if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2274 						    && *p != '[' && *p != '.')
2275 	{
2276 	    EMSG(_(e_trailing));
2277 	    return NULL;
2278 	}
2279 
2280 	lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2281 	if (lp->ll_exp_name == NULL)
2282 	{
2283 	    /* Report an invalid expression in braces, unless the
2284 	     * expression evaluation has been cancelled due to an
2285 	     * aborting error, an interrupt, or an exception. */
2286 	    if (!aborting() && !quiet)
2287 	    {
2288 		emsg_severe = TRUE;
2289 		EMSG2(_(e_invarg2), name);
2290 		return NULL;
2291 	    }
2292 	}
2293 	lp->ll_name = lp->ll_exp_name;
2294     }
2295     else
2296 	lp->ll_name = name;
2297 
2298     /* Without [idx] or .key we are done. */
2299     if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2300 	return p;
2301 
2302     cc = *p;
2303     *p = NUL;
2304     v = find_var(lp->ll_name, &ht);
2305     if (v == NULL && !quiet)
2306 	EMSG2(_(e_undefvar), lp->ll_name);
2307     *p = cc;
2308     if (v == NULL)
2309 	return NULL;
2310 
2311     /*
2312      * Loop until no more [idx] or .key is following.
2313      */
2314     lp->ll_tv = &v->di_tv;
2315     while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2316     {
2317 	if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2318 		&& !(lp->ll_tv->v_type == VAR_DICT
2319 					   && lp->ll_tv->vval.v_dict != NULL))
2320 	{
2321 	    if (!quiet)
2322 		EMSG(_("E689: Can only index a List or Dictionary"));
2323 	    return NULL;
2324 	}
2325 	if (lp->ll_range)
2326 	{
2327 	    if (!quiet)
2328 		EMSG(_("E708: [:] must come last"));
2329 	    return NULL;
2330 	}
2331 
2332 	len = -1;
2333 	if (*p == '.')
2334 	{
2335 	    key = p + 1;
2336 	    for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2337 		;
2338 	    if (len == 0)
2339 	    {
2340 		if (!quiet)
2341 		    EMSG(_(e_emptykey));
2342 		return NULL;
2343 	    }
2344 	    p = key + len;
2345 	}
2346 	else
2347 	{
2348 	    /* Get the index [expr] or the first index [expr: ]. */
2349 	    p = skipwhite(p + 1);
2350 	    if (*p == ':')
2351 		empty1 = TRUE;
2352 	    else
2353 	    {
2354 		empty1 = FALSE;
2355 		if (eval1(&p, &var1, TRUE) == FAIL)	/* recursive! */
2356 		    return NULL;
2357 		if (get_tv_string_chk(&var1) == NULL)
2358 		{
2359 		    /* not a number or string */
2360 		    clear_tv(&var1);
2361 		    return NULL;
2362 		}
2363 	    }
2364 
2365 	    /* Optionally get the second index [ :expr]. */
2366 	    if (*p == ':')
2367 	    {
2368 		if (lp->ll_tv->v_type == VAR_DICT)
2369 		{
2370 		    if (!quiet)
2371 			EMSG(_(e_dictrange));
2372 		    if (!empty1)
2373 			clear_tv(&var1);
2374 		    return NULL;
2375 		}
2376 		if (rettv != NULL && (rettv->v_type != VAR_LIST
2377 					       || rettv->vval.v_list == NULL))
2378 		{
2379 		    if (!quiet)
2380 			EMSG(_("E709: [:] requires a List value"));
2381 		    if (!empty1)
2382 			clear_tv(&var1);
2383 		    return NULL;
2384 		}
2385 		p = skipwhite(p + 1);
2386 		if (*p == ']')
2387 		    lp->ll_empty2 = TRUE;
2388 		else
2389 		{
2390 		    lp->ll_empty2 = FALSE;
2391 		    if (eval1(&p, &var2, TRUE) == FAIL)	/* recursive! */
2392 		    {
2393 			if (!empty1)
2394 			    clear_tv(&var1);
2395 			return NULL;
2396 		    }
2397 		    if (get_tv_string_chk(&var2) == NULL)
2398 		    {
2399 			/* not a number or string */
2400 			if (!empty1)
2401 			    clear_tv(&var1);
2402 			clear_tv(&var2);
2403 			return NULL;
2404 		    }
2405 		}
2406 		lp->ll_range = TRUE;
2407 	    }
2408 	    else
2409 		lp->ll_range = FALSE;
2410 
2411 	    if (*p != ']')
2412 	    {
2413 		if (!quiet)
2414 		    EMSG(_(e_missbrac));
2415 		if (!empty1)
2416 		    clear_tv(&var1);
2417 		if (lp->ll_range && !lp->ll_empty2)
2418 		    clear_tv(&var2);
2419 		return NULL;
2420 	    }
2421 
2422 	    /* Skip to past ']'. */
2423 	    ++p;
2424 	}
2425 
2426 	if (lp->ll_tv->v_type == VAR_DICT)
2427 	{
2428 	    if (len == -1)
2429 	    {
2430 		/* "[key]": get key from "var1" */
2431 		key = get_tv_string(&var1);	/* is number or string */
2432 		if (*key == NUL)
2433 		{
2434 		    if (!quiet)
2435 			EMSG(_(e_emptykey));
2436 		    clear_tv(&var1);
2437 		    return NULL;
2438 		}
2439 	    }
2440 	    lp->ll_list = NULL;
2441 	    lp->ll_dict = lp->ll_tv->vval.v_dict;
2442 	    lp->ll_di = dict_find(lp->ll_dict, key, len);
2443 	    if (lp->ll_di == NULL)
2444 	    {
2445 		/* Key does not exist in dict: may need to add it. */
2446 		if (*p == '[' || *p == '.' || unlet)
2447 		{
2448 		    if (!quiet)
2449 			EMSG2(_(e_dictkey), key);
2450 		    if (len == -1)
2451 			clear_tv(&var1);
2452 		    return NULL;
2453 		}
2454 		if (len == -1)
2455 		    lp->ll_newkey = vim_strsave(key);
2456 		else
2457 		    lp->ll_newkey = vim_strnsave(key, len);
2458 		if (len == -1)
2459 		    clear_tv(&var1);
2460 		if (lp->ll_newkey == NULL)
2461 		    p = NULL;
2462 		break;
2463 	    }
2464 	    if (len == -1)
2465 		clear_tv(&var1);
2466 	    lp->ll_tv = &lp->ll_di->di_tv;
2467 	}
2468 	else
2469 	{
2470 	    /*
2471 	     * Get the number and item for the only or first index of the List.
2472 	     */
2473 	    if (empty1)
2474 		lp->ll_n1 = 0;
2475 	    else
2476 	    {
2477 		lp->ll_n1 = get_tv_number(&var1);   /* is number or string */
2478 		clear_tv(&var1);
2479 	    }
2480 	    lp->ll_dict = NULL;
2481 	    lp->ll_list = lp->ll_tv->vval.v_list;
2482 	    lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2483 	    if (lp->ll_li == NULL)
2484 	    {
2485 		if (!quiet)
2486 		    EMSGN(_(e_listidx), lp->ll_n1);
2487 		if (lp->ll_range && !lp->ll_empty2)
2488 		    clear_tv(&var2);
2489 		return NULL;
2490 	    }
2491 
2492 	    /*
2493 	     * May need to find the item or absolute index for the second
2494 	     * index of a range.
2495 	     * When no index given: "lp->ll_empty2" is TRUE.
2496 	     * Otherwise "lp->ll_n2" is set to the second index.
2497 	     */
2498 	    if (lp->ll_range && !lp->ll_empty2)
2499 	    {
2500 		lp->ll_n2 = get_tv_number(&var2);   /* is number or string */
2501 		clear_tv(&var2);
2502 		if (lp->ll_n2 < 0)
2503 		{
2504 		    ni = list_find(lp->ll_list, lp->ll_n2);
2505 		    if (ni == NULL)
2506 		    {
2507 			if (!quiet)
2508 			    EMSGN(_(e_listidx), lp->ll_n2);
2509 			return NULL;
2510 		    }
2511 		    lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2512 		}
2513 
2514 		/* Check that lp->ll_n2 isn't before lp->ll_n1. */
2515 		if (lp->ll_n1 < 0)
2516 		    lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2517 		if (lp->ll_n2 < lp->ll_n1)
2518 		{
2519 		    if (!quiet)
2520 			EMSGN(_(e_listidx), lp->ll_n2);
2521 		    return NULL;
2522 		}
2523 	    }
2524 
2525 	    lp->ll_tv = &lp->ll_li->li_tv;
2526 	}
2527     }
2528 
2529     return p;
2530 }
2531 
2532 /*
2533  * Clear lval "lp" that was filled by get_lval().
2534  */
2535     static void
2536 clear_lval(lp)
2537     lval_T	*lp;
2538 {
2539     vim_free(lp->ll_exp_name);
2540     vim_free(lp->ll_newkey);
2541 }
2542 
2543 /*
2544  * Set a variable that was parsed by get_lval() to "rettv".
2545  * "endp" points to just after the parsed name.
2546  * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2547  */
2548     static void
2549 set_var_lval(lp, endp, rettv, copy, op)
2550     lval_T	*lp;
2551     char_u	*endp;
2552     typval_T	*rettv;
2553     int		copy;
2554     char_u	*op;
2555 {
2556     int		cc;
2557     listitem_T	*ri;
2558     dictitem_T	*di;
2559 
2560     if (lp->ll_tv == NULL)
2561     {
2562 	if (!check_changedtick(lp->ll_name))
2563 	{
2564 	    cc = *endp;
2565 	    *endp = NUL;
2566 	    if (op != NULL && *op != '=')
2567 	    {
2568 		typval_T tv;
2569 
2570 		/* handle +=, -= and .= */
2571 		if (get_var_tv(lp->ll_name, STRLEN(lp->ll_name),
2572 							     &tv, TRUE) == OK)
2573 		{
2574 		    if (tv_op(&tv, rettv, op) == OK)
2575 			set_var(lp->ll_name, &tv, FALSE);
2576 		    clear_tv(&tv);
2577 		}
2578 	    }
2579 	    else
2580 		set_var(lp->ll_name, rettv, copy);
2581 	    *endp = cc;
2582 	}
2583     }
2584     else if (tv_check_lock(lp->ll_newkey == NULL
2585 		? lp->ll_tv->v_lock
2586 		: lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2587 	;
2588     else if (lp->ll_range)
2589     {
2590 	/*
2591 	 * Assign the List values to the list items.
2592 	 */
2593 	for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2594 	{
2595 	    if (op != NULL && *op != '=')
2596 		tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2597 	    else
2598 	    {
2599 		clear_tv(&lp->ll_li->li_tv);
2600 		copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2601 	    }
2602 	    ri = ri->li_next;
2603 	    if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2604 		break;
2605 	    if (lp->ll_li->li_next == NULL)
2606 	    {
2607 		/* Need to add an empty item. */
2608 		if (list_append_number(lp->ll_list, 0) == FAIL)
2609 		{
2610 		    ri = NULL;
2611 		    break;
2612 		}
2613 	    }
2614 	    lp->ll_li = lp->ll_li->li_next;
2615 	    ++lp->ll_n1;
2616 	}
2617 	if (ri != NULL)
2618 	    EMSG(_("E710: List value has more items than target"));
2619 	else if (lp->ll_empty2
2620 		? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2621 		: lp->ll_n1 != lp->ll_n2)
2622 	    EMSG(_("E711: List value has not enough items"));
2623     }
2624     else
2625     {
2626 	/*
2627 	 * Assign to a List or Dictionary item.
2628 	 */
2629 	if (lp->ll_newkey != NULL)
2630 	{
2631 	    if (op != NULL && *op != '=')
2632 	    {
2633 		EMSG2(_(e_letwrong), op);
2634 		return;
2635 	    }
2636 
2637 	    /* Need to add an item to the Dictionary. */
2638 	    di = dictitem_alloc(lp->ll_newkey);
2639 	    if (di == NULL)
2640 		return;
2641 	    if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2642 	    {
2643 		vim_free(di);
2644 		return;
2645 	    }
2646 	    lp->ll_tv = &di->di_tv;
2647 	}
2648 	else if (op != NULL && *op != '=')
2649 	{
2650 	    tv_op(lp->ll_tv, rettv, op);
2651 	    return;
2652 	}
2653 	else
2654 	    clear_tv(lp->ll_tv);
2655 
2656 	/*
2657 	 * Assign the value to the variable or list item.
2658 	 */
2659 	if (copy)
2660 	    copy_tv(rettv, lp->ll_tv);
2661 	else
2662 	{
2663 	    *lp->ll_tv = *rettv;
2664 	    lp->ll_tv->v_lock = 0;
2665 	    init_tv(rettv);
2666 	}
2667     }
2668 }
2669 
2670 /*
2671  * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2672  * Returns OK or FAIL.
2673  */
2674     static int
2675 tv_op(tv1, tv2, op)
2676     typval_T *tv1;
2677     typval_T *tv2;
2678     char_u  *op;
2679 {
2680     long	n;
2681     char_u	numbuf[NUMBUFLEN];
2682     char_u	*s;
2683 
2684     /* Can't do anything with a Funcref or a Dict on the right. */
2685     if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2686     {
2687 	switch (tv1->v_type)
2688 	{
2689 	    case VAR_DICT:
2690 	    case VAR_FUNC:
2691 		break;
2692 
2693 	    case VAR_LIST:
2694 		if (*op != '+' || tv2->v_type != VAR_LIST)
2695 		    break;
2696 		/* List += List */
2697 		if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2698 		    list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2699 		return OK;
2700 
2701 	    case VAR_NUMBER:
2702 	    case VAR_STRING:
2703 		if (tv2->v_type == VAR_LIST)
2704 		    break;
2705 		if (*op == '+' || *op == '-')
2706 		{
2707 		    /* nr += nr  or  nr -= nr*/
2708 		    n = get_tv_number(tv1);
2709 		    if (*op == '+')
2710 			n += get_tv_number(tv2);
2711 		    else
2712 			n -= get_tv_number(tv2);
2713 		    clear_tv(tv1);
2714 		    tv1->v_type = VAR_NUMBER;
2715 		    tv1->vval.v_number = n;
2716 		}
2717 		else
2718 		{
2719 		    /* str .= str */
2720 		    s = get_tv_string(tv1);
2721 		    s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2722 		    clear_tv(tv1);
2723 		    tv1->v_type = VAR_STRING;
2724 		    tv1->vval.v_string = s;
2725 		}
2726 		return OK;
2727 	}
2728     }
2729 
2730     EMSG2(_(e_letwrong), op);
2731     return FAIL;
2732 }
2733 
2734 /*
2735  * Add a watcher to a list.
2736  */
2737     static void
2738 list_add_watch(l, lw)
2739     list_T	*l;
2740     listwatch_T	*lw;
2741 {
2742     lw->lw_next = l->lv_watch;
2743     l->lv_watch = lw;
2744 }
2745 
2746 /*
2747  * Remove a watcher from a list.
2748  * No warning when it isn't found...
2749  */
2750     static void
2751 list_rem_watch(l, lwrem)
2752     list_T	*l;
2753     listwatch_T	*lwrem;
2754 {
2755     listwatch_T	*lw, **lwp;
2756 
2757     lwp = &l->lv_watch;
2758     for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2759     {
2760 	if (lw == lwrem)
2761 	{
2762 	    *lwp = lw->lw_next;
2763 	    break;
2764 	}
2765 	lwp = &lw->lw_next;
2766     }
2767 }
2768 
2769 /*
2770  * Just before removing an item from a list: advance watchers to the next
2771  * item.
2772  */
2773     static void
2774 list_fix_watch(l, item)
2775     list_T	*l;
2776     listitem_T	*item;
2777 {
2778     listwatch_T	*lw;
2779 
2780     for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2781 	if (lw->lw_item == item)
2782 	    lw->lw_item = item->li_next;
2783 }
2784 
2785 /*
2786  * Evaluate the expression used in a ":for var in expr" command.
2787  * "arg" points to "var".
2788  * Set "*errp" to TRUE for an error, FALSE otherwise;
2789  * Return a pointer that holds the info.  Null when there is an error.
2790  */
2791     void *
2792 eval_for_line(arg, errp, nextcmdp, skip)
2793     char_u	*arg;
2794     int		*errp;
2795     char_u	**nextcmdp;
2796     int		skip;
2797 {
2798     forinfo_T	*fi;
2799     char_u	*expr;
2800     typval_T	tv;
2801     list_T	*l;
2802 
2803     *errp = TRUE;	/* default: there is an error */
2804 
2805     fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
2806     if (fi == NULL)
2807 	return NULL;
2808 
2809     expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
2810     if (expr == NULL)
2811 	return fi;
2812 
2813     expr = skipwhite(expr);
2814     if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
2815     {
2816 	EMSG(_("E690: Missing \"in\" after :for"));
2817 	return fi;
2818     }
2819 
2820     if (skip)
2821 	++emsg_skip;
2822     if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
2823     {
2824 	*errp = FALSE;
2825 	if (!skip)
2826 	{
2827 	    l = tv.vval.v_list;
2828 	    if (tv.v_type != VAR_LIST || l == NULL)
2829 	    {
2830 		EMSG(_(e_listreq));
2831 		clear_tv(&tv);
2832 	    }
2833 	    else
2834 	    {
2835 		/* No need to increment the refcount, it's already set for the
2836 		 * list being used in "tv". */
2837 		fi->fi_list = l;
2838 		list_add_watch(l, &fi->fi_lw);
2839 		fi->fi_lw.lw_item = l->lv_first;
2840 	    }
2841 	}
2842     }
2843     if (skip)
2844 	--emsg_skip;
2845 
2846     return fi;
2847 }
2848 
2849 /*
2850  * Use the first item in a ":for" list.  Advance to the next.
2851  * Assign the values to the variable (list).  "arg" points to the first one.
2852  * Return TRUE when a valid item was found, FALSE when at end of list or
2853  * something wrong.
2854  */
2855     int
2856 next_for_item(fi_void, arg)
2857     void	*fi_void;
2858     char_u	*arg;
2859 {
2860     forinfo_T    *fi = (forinfo_T *)fi_void;
2861     int		result;
2862     listitem_T	*item;
2863 
2864     item = fi->fi_lw.lw_item;
2865     if (item == NULL)
2866 	result = FALSE;
2867     else
2868     {
2869 	fi->fi_lw.lw_item = item->li_next;
2870 	result = (ex_let_vars(arg, &item->li_tv, TRUE,
2871 			      fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
2872     }
2873     return result;
2874 }
2875 
2876 /*
2877  * Free the structure used to store info used by ":for".
2878  */
2879     void
2880 free_for_info(fi_void)
2881     void *fi_void;
2882 {
2883     forinfo_T    *fi = (forinfo_T *)fi_void;
2884 
2885     if (fi != NULL && fi->fi_list != NULL)
2886     {
2887 	list_rem_watch(fi->fi_list, &fi->fi_lw);
2888 	list_unref(fi->fi_list);
2889     }
2890     vim_free(fi);
2891 }
2892 
2893 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2894 
2895     void
2896 set_context_for_expression(xp, arg, cmdidx)
2897     expand_T	*xp;
2898     char_u	*arg;
2899     cmdidx_T	cmdidx;
2900 {
2901     int		got_eq = FALSE;
2902     int		c;
2903     char_u	*p;
2904 
2905     if (cmdidx == CMD_let)
2906     {
2907 	xp->xp_context = EXPAND_USER_VARS;
2908 	if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
2909 	{
2910 	    /* ":let var1 var2 ...": find last space. */
2911 	    for (p = arg + STRLEN(arg); p >= arg; )
2912 	    {
2913 		xp->xp_pattern = p;
2914 		mb_ptr_back(arg, p);
2915 		if (vim_iswhite(*p))
2916 		    break;
2917 	    }
2918 	    return;
2919 	}
2920     }
2921     else
2922 	xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
2923 							  : EXPAND_EXPRESSION;
2924     while ((xp->xp_pattern = vim_strpbrk(arg,
2925 				  (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
2926     {
2927 	c = *xp->xp_pattern;
2928 	if (c == '&')
2929 	{
2930 	    c = xp->xp_pattern[1];
2931 	    if (c == '&')
2932 	    {
2933 		++xp->xp_pattern;
2934 		xp->xp_context = cmdidx != CMD_let || got_eq
2935 					 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
2936 	    }
2937 	    else if (c != ' ')
2938 	    {
2939 		xp->xp_context = EXPAND_SETTINGS;
2940 		if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
2941 		    xp->xp_pattern += 2;
2942 
2943 	    }
2944 	}
2945 	else if (c == '$')
2946 	{
2947 	    /* environment variable */
2948 	    xp->xp_context = EXPAND_ENV_VARS;
2949 	}
2950 	else if (c == '=')
2951 	{
2952 	    got_eq = TRUE;
2953 	    xp->xp_context = EXPAND_EXPRESSION;
2954 	}
2955 	else if (c == '<'
2956 		&& xp->xp_context == EXPAND_FUNCTIONS
2957 		&& vim_strchr(xp->xp_pattern, '(') == NULL)
2958 	{
2959 	    /* Function name can start with "<SNR>" */
2960 	    break;
2961 	}
2962 	else if (cmdidx != CMD_let || got_eq)
2963 	{
2964 	    if (c == '"')	    /* string */
2965 	    {
2966 		while ((c = *++xp->xp_pattern) != NUL && c != '"')
2967 		    if (c == '\\' && xp->xp_pattern[1] != NUL)
2968 			++xp->xp_pattern;
2969 		xp->xp_context = EXPAND_NOTHING;
2970 	    }
2971 	    else if (c == '\'')	    /* literal string */
2972 	    {
2973 		/* Trick: '' is like stopping and starting a literal string. */
2974 		while ((c = *++xp->xp_pattern) != NUL && c != '\'')
2975 		    /* skip */ ;
2976 		xp->xp_context = EXPAND_NOTHING;
2977 	    }
2978 	    else if (c == '|')
2979 	    {
2980 		if (xp->xp_pattern[1] == '|')
2981 		{
2982 		    ++xp->xp_pattern;
2983 		    xp->xp_context = EXPAND_EXPRESSION;
2984 		}
2985 		else
2986 		    xp->xp_context = EXPAND_COMMANDS;
2987 	    }
2988 	    else
2989 		xp->xp_context = EXPAND_EXPRESSION;
2990 	}
2991 	else
2992 	    /* Doesn't look like something valid, expand as an expression
2993 	     * anyway. */
2994 	    xp->xp_context = EXPAND_EXPRESSION;
2995 	arg = xp->xp_pattern;
2996 	if (*arg != NUL)
2997 	    while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
2998 		/* skip */ ;
2999     }
3000     xp->xp_pattern = arg;
3001 }
3002 
3003 #endif /* FEAT_CMDL_COMPL */
3004 
3005 /*
3006  * ":1,25call func(arg1, arg2)"	function call.
3007  */
3008     void
3009 ex_call(eap)
3010     exarg_T	*eap;
3011 {
3012     char_u	*arg = eap->arg;
3013     char_u	*startarg;
3014     char_u	*name;
3015     char_u	*tofree;
3016     int		len;
3017     typval_T	rettv;
3018     linenr_T	lnum;
3019     int		doesrange;
3020     int		failed = FALSE;
3021     funcdict_T	fudi;
3022 
3023     tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3024     vim_free(fudi.fd_newkey);
3025     if (tofree == NULL)
3026 	return;
3027 
3028     /* Increase refcount on dictionary, it could get deleted when evaluating
3029      * the arguments. */
3030     if (fudi.fd_dict != NULL)
3031 	++fudi.fd_dict->dv_refcount;
3032 
3033     /* If it is the name of a variable of type VAR_FUNC use its contents. */
3034     len = STRLEN(tofree);
3035     name = deref_func_name(tofree, &len);
3036 
3037     /* Skip white space to allow ":call func ()".  Not good, but required for
3038      * backward compatibility. */
3039     startarg = skipwhite(arg);
3040     rettv.v_type = VAR_UNKNOWN;	/* clear_tv() uses this */
3041 
3042     if (*startarg != '(')
3043     {
3044 	EMSG2(_("E107: Missing braces: %s"), eap->arg);
3045 	goto end;
3046     }
3047 
3048     /*
3049      * When skipping, evaluate the function once, to find the end of the
3050      * arguments.
3051      * When the function takes a range, this is discovered after the first
3052      * call, and the loop is broken.
3053      */
3054     if (eap->skip)
3055     {
3056 	++emsg_skip;
3057 	lnum = eap->line2;	/* do it once, also with an invalid range */
3058     }
3059     else
3060 	lnum = eap->line1;
3061     for ( ; lnum <= eap->line2; ++lnum)
3062     {
3063 	if (!eap->skip && eap->addr_count > 0)
3064 	{
3065 	    curwin->w_cursor.lnum = lnum;
3066 	    curwin->w_cursor.col = 0;
3067 	}
3068 	arg = startarg;
3069 	if (get_func_tv(name, STRLEN(name), &rettv, &arg,
3070 		    eap->line1, eap->line2, &doesrange,
3071 					    !eap->skip, fudi.fd_dict) == FAIL)
3072 	{
3073 	    failed = TRUE;
3074 	    break;
3075 	}
3076 	clear_tv(&rettv);
3077 	if (doesrange || eap->skip)
3078 	    break;
3079 	/* Stop when immediately aborting on error, or when an interrupt
3080 	 * occurred or an exception was thrown but not caught.
3081 	 * get_func_tv() returned OK, so that the check for trailing
3082 	 * characters below is executed. */
3083 	if (aborting())
3084 	    break;
3085     }
3086     if (eap->skip)
3087 	--emsg_skip;
3088 
3089     if (!failed)
3090     {
3091 	/* Check for trailing illegal characters and a following command. */
3092 	if (!ends_excmd(*arg))
3093 	{
3094 	    emsg_severe = TRUE;
3095 	    EMSG(_(e_trailing));
3096 	}
3097 	else
3098 	    eap->nextcmd = check_nextcmd(arg);
3099     }
3100 
3101 end:
3102     dict_unref(fudi.fd_dict);
3103     vim_free(tofree);
3104 }
3105 
3106 /*
3107  * ":unlet[!] var1 ... " command.
3108  */
3109     void
3110 ex_unlet(eap)
3111     exarg_T	*eap;
3112 {
3113     ex_unletlock(eap, eap->arg, 0);
3114 }
3115 
3116 /*
3117  * ":lockvar" and ":unlockvar" commands
3118  */
3119     void
3120 ex_lockvar(eap)
3121     exarg_T	*eap;
3122 {
3123     char_u	*arg = eap->arg;
3124     int		deep = 2;
3125 
3126     if (eap->forceit)
3127 	deep = -1;
3128     else if (vim_isdigit(*arg))
3129     {
3130 	deep = getdigits(&arg);
3131 	arg = skipwhite(arg);
3132     }
3133 
3134     ex_unletlock(eap, arg, deep);
3135 }
3136 
3137 /*
3138  * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3139  */
3140     static void
3141 ex_unletlock(eap, argstart, deep)
3142     exarg_T	*eap;
3143     char_u	*argstart;
3144     int		deep;
3145 {
3146     char_u	*arg = argstart;
3147     char_u	*name_end;
3148     int		error = FALSE;
3149     lval_T	lv;
3150 
3151     do
3152     {
3153 	/* Parse the name and find the end. */
3154 	name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3155 							     FNE_CHECK_START);
3156 	if (lv.ll_name == NULL)
3157 	    error = TRUE;	    /* error but continue parsing */
3158 	if (name_end == NULL || (!vim_iswhite(*name_end)
3159 						   && !ends_excmd(*name_end)))
3160 	{
3161 	    if (name_end != NULL)
3162 	    {
3163 		emsg_severe = TRUE;
3164 		EMSG(_(e_trailing));
3165 	    }
3166 	    if (!(eap->skip || error))
3167 		clear_lval(&lv);
3168 	    break;
3169 	}
3170 
3171 	if (!error && !eap->skip)
3172 	{
3173 	    if (eap->cmdidx == CMD_unlet)
3174 	    {
3175 		if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3176 		    error = TRUE;
3177 	    }
3178 	    else
3179 	    {
3180 		if (do_lock_var(&lv, name_end, deep,
3181 					  eap->cmdidx == CMD_lockvar) == FAIL)
3182 		    error = TRUE;
3183 	    }
3184 	}
3185 
3186 	if (!eap->skip)
3187 	    clear_lval(&lv);
3188 
3189 	arg = skipwhite(name_end);
3190     } while (!ends_excmd(*arg));
3191 
3192     eap->nextcmd = check_nextcmd(arg);
3193 }
3194 
3195     static int
3196 do_unlet_var(lp, name_end, forceit)
3197     lval_T	*lp;
3198     char_u	*name_end;
3199     int		forceit;
3200 {
3201     int		ret = OK;
3202     int		cc;
3203 
3204     if (lp->ll_tv == NULL)
3205     {
3206 	cc = *name_end;
3207 	*name_end = NUL;
3208 
3209 	/* Normal name or expanded name. */
3210 	if (check_changedtick(lp->ll_name))
3211 	    ret = FAIL;
3212 	else if (do_unlet(lp->ll_name, forceit) == FAIL)
3213 	    ret = FAIL;
3214 	*name_end = cc;
3215     }
3216     else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3217 	return FAIL;
3218     else if (lp->ll_range)
3219     {
3220 	listitem_T    *li;
3221 
3222 	/* Delete a range of List items. */
3223 	while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3224 	{
3225 	    li = lp->ll_li->li_next;
3226 	    listitem_remove(lp->ll_list, lp->ll_li);
3227 	    lp->ll_li = li;
3228 	    ++lp->ll_n1;
3229 	}
3230     }
3231     else
3232     {
3233 	if (lp->ll_list != NULL)
3234 	    /* unlet a List item. */
3235 	    listitem_remove(lp->ll_list, lp->ll_li);
3236 	else
3237 	    /* unlet a Dictionary item. */
3238 	    dictitem_remove(lp->ll_dict, lp->ll_di);
3239     }
3240 
3241     return ret;
3242 }
3243 
3244 /*
3245  * "unlet" a variable.  Return OK if it existed, FAIL if not.
3246  * When "forceit" is TRUE don't complain if the variable doesn't exist.
3247  */
3248     int
3249 do_unlet(name, forceit)
3250     char_u	*name;
3251     int		forceit;
3252 {
3253     hashtab_T	*ht;
3254     hashitem_T	*hi;
3255     char_u	*varname;
3256 
3257     ht = find_var_ht(name, &varname);
3258     if (ht != NULL && *varname != NUL)
3259     {
3260 	hi = hash_find(ht, varname);
3261 	if (!HASHITEM_EMPTY(hi))
3262 	{
3263 	    if (var_check_ro(HI2DI(hi)->di_flags, name))
3264 		return FAIL;
3265 	    delete_var(ht, hi);
3266 	    return OK;
3267 	}
3268     }
3269     if (forceit)
3270 	return OK;
3271     EMSG2(_("E108: No such variable: \"%s\""), name);
3272     return FAIL;
3273 }
3274 
3275 /*
3276  * Lock or unlock variable indicated by "lp".
3277  * "deep" is the levels to go (-1 for unlimited);
3278  * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3279  */
3280     static int
3281 do_lock_var(lp, name_end, deep, lock)
3282     lval_T	*lp;
3283     char_u	*name_end;
3284     int		deep;
3285     int		lock;
3286 {
3287     int		ret = OK;
3288     int		cc;
3289     dictitem_T	*di;
3290 
3291     if (deep == 0)	/* nothing to do */
3292 	return OK;
3293 
3294     if (lp->ll_tv == NULL)
3295     {
3296 	cc = *name_end;
3297 	*name_end = NUL;
3298 
3299 	/* Normal name or expanded name. */
3300 	if (check_changedtick(lp->ll_name))
3301 	    ret = FAIL;
3302 	else
3303 	{
3304 	    di = find_var(lp->ll_name, NULL);
3305 	    if (di == NULL)
3306 		ret = FAIL;
3307 	    else
3308 	    {
3309 		if (lock)
3310 		    di->di_flags |= DI_FLAGS_LOCK;
3311 		else
3312 		    di->di_flags &= ~DI_FLAGS_LOCK;
3313 		item_lock(&di->di_tv, deep, lock);
3314 	    }
3315 	}
3316 	*name_end = cc;
3317     }
3318     else if (lp->ll_range)
3319     {
3320 	listitem_T    *li = lp->ll_li;
3321 
3322 	/* (un)lock a range of List items. */
3323 	while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3324 	{
3325 	    item_lock(&li->li_tv, deep, lock);
3326 	    li = li->li_next;
3327 	    ++lp->ll_n1;
3328 	}
3329     }
3330     else if (lp->ll_list != NULL)
3331 	/* (un)lock a List item. */
3332 	item_lock(&lp->ll_li->li_tv, deep, lock);
3333     else
3334 	/* un(lock) a Dictionary item. */
3335 	item_lock(&lp->ll_di->di_tv, deep, lock);
3336 
3337     return ret;
3338 }
3339 
3340 /*
3341  * Lock or unlock an item.  "deep" is nr of levels to go.
3342  */
3343     static void
3344 item_lock(tv, deep, lock)
3345     typval_T	*tv;
3346     int		deep;
3347     int		lock;
3348 {
3349     static int	recurse = 0;
3350     list_T	*l;
3351     listitem_T	*li;
3352     dict_T	*d;
3353     hashitem_T	*hi;
3354     int		todo;
3355 
3356     if (recurse >= DICT_MAXNEST)
3357     {
3358 	EMSG(_("E743: variable nested too deep for (un)lock"));
3359 	return;
3360     }
3361     if (deep == 0)
3362 	return;
3363     ++recurse;
3364 
3365     /* lock/unlock the item itself */
3366     if (lock)
3367 	tv->v_lock |= VAR_LOCKED;
3368     else
3369 	tv->v_lock &= ~VAR_LOCKED;
3370 
3371     switch (tv->v_type)
3372     {
3373 	case VAR_LIST:
3374 	    if ((l = tv->vval.v_list) != NULL)
3375 	    {
3376 		if (lock)
3377 		    l->lv_lock |= VAR_LOCKED;
3378 		else
3379 		    l->lv_lock &= ~VAR_LOCKED;
3380 		if (deep < 0 || deep > 1)
3381 		    /* recursive: lock/unlock the items the List contains */
3382 		    for (li = l->lv_first; li != NULL; li = li->li_next)
3383 			item_lock(&li->li_tv, deep - 1, lock);
3384 	    }
3385 	    break;
3386 	case VAR_DICT:
3387 	    if ((d = tv->vval.v_dict) != NULL)
3388 	    {
3389 		if (lock)
3390 		    d->dv_lock |= VAR_LOCKED;
3391 		else
3392 		    d->dv_lock &= ~VAR_LOCKED;
3393 		if (deep < 0 || deep > 1)
3394 		{
3395 		    /* recursive: lock/unlock the items the List contains */
3396 		    todo = d->dv_hashtab.ht_used;
3397 		    for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3398 		    {
3399 			if (!HASHITEM_EMPTY(hi))
3400 			{
3401 			    --todo;
3402 			    item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3403 			}
3404 		    }
3405 		}
3406 	    }
3407     }
3408     --recurse;
3409 }
3410 
3411 /*
3412  * Return TRUE if typeval "tv" is locked: Either tha value is locked itself or
3413  * it refers to a List or Dictionary that is locked.
3414  */
3415     static int
3416 tv_islocked(tv)
3417     typval_T	*tv;
3418 {
3419     return (tv->v_lock & VAR_LOCKED)
3420 	|| (tv->v_type == VAR_LIST
3421 		&& tv->vval.v_list != NULL
3422 		&& (tv->vval.v_list->lv_lock & VAR_LOCKED))
3423 	|| (tv->v_type == VAR_DICT
3424 		&& tv->vval.v_dict != NULL
3425 		&& (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3426 }
3427 
3428 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3429 /*
3430  * Delete all "menutrans_" variables.
3431  */
3432     void
3433 del_menutrans_vars()
3434 {
3435     hashitem_T	*hi;
3436     int		todo;
3437 
3438     hash_lock(&globvarht);
3439     todo = globvarht.ht_used;
3440     for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3441     {
3442 	if (!HASHITEM_EMPTY(hi))
3443 	{
3444 	    --todo;
3445 	    if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3446 		delete_var(&globvarht, hi);
3447 	}
3448     }
3449     hash_unlock(&globvarht);
3450 }
3451 #endif
3452 
3453 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3454 
3455 /*
3456  * Local string buffer for the next two functions to store a variable name
3457  * with its prefix. Allocated in cat_prefix_varname(), freed later in
3458  * get_user_var_name().
3459  */
3460 
3461 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3462 
3463 static char_u	*varnamebuf = NULL;
3464 static int	varnamebuflen = 0;
3465 
3466 /*
3467  * Function to concatenate a prefix and a variable name.
3468  */
3469     static char_u *
3470 cat_prefix_varname(prefix, name)
3471     int		prefix;
3472     char_u	*name;
3473 {
3474     int		len;
3475 
3476     len = (int)STRLEN(name) + 3;
3477     if (len > varnamebuflen)
3478     {
3479 	vim_free(varnamebuf);
3480 	len += 10;			/* some additional space */
3481 	varnamebuf = alloc(len);
3482 	if (varnamebuf == NULL)
3483 	{
3484 	    varnamebuflen = 0;
3485 	    return NULL;
3486 	}
3487 	varnamebuflen = len;
3488     }
3489     *varnamebuf = prefix;
3490     varnamebuf[1] = ':';
3491     STRCPY(varnamebuf + 2, name);
3492     return varnamebuf;
3493 }
3494 
3495 /*
3496  * Function given to ExpandGeneric() to obtain the list of user defined
3497  * (global/buffer/window/built-in) variable names.
3498  */
3499 /*ARGSUSED*/
3500     char_u *
3501 get_user_var_name(xp, idx)
3502     expand_T	*xp;
3503     int		idx;
3504 {
3505     static long_u	gdone;
3506     static long_u	bdone;
3507     static long_u	wdone;
3508     static int		vidx;
3509     static hashitem_T	*hi;
3510     hashtab_T		*ht;
3511 
3512     if (idx == 0)
3513 	gdone = bdone = wdone = vidx = 0;
3514 
3515     /* Global variables */
3516     if (gdone < globvarht.ht_used)
3517     {
3518 	if (gdone++ == 0)
3519 	    hi = globvarht.ht_array;
3520 	else
3521 	    ++hi;
3522 	while (HASHITEM_EMPTY(hi))
3523 	    ++hi;
3524 	if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3525 	    return cat_prefix_varname('g', hi->hi_key);
3526 	return hi->hi_key;
3527     }
3528 
3529     /* b: variables */
3530     ht = &curbuf->b_vars.dv_hashtab;
3531     if (bdone < ht->ht_used)
3532     {
3533 	if (bdone++ == 0)
3534 	    hi = ht->ht_array;
3535 	else
3536 	    ++hi;
3537 	while (HASHITEM_EMPTY(hi))
3538 	    ++hi;
3539 	return cat_prefix_varname('b', hi->hi_key);
3540     }
3541     if (bdone == ht->ht_used)
3542     {
3543 	++bdone;
3544 	return (char_u *)"b:changedtick";
3545     }
3546 
3547     /* w: variables */
3548     ht = &curwin->w_vars.dv_hashtab;
3549     if (wdone < ht->ht_used)
3550     {
3551 	if (wdone++ == 0)
3552 	    hi = ht->ht_array;
3553 	else
3554 	    ++hi;
3555 	while (HASHITEM_EMPTY(hi))
3556 	    ++hi;
3557 	return cat_prefix_varname('w', hi->hi_key);
3558     }
3559 
3560     /* v: variables */
3561     if (vidx < VV_LEN)
3562 	return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3563 
3564     vim_free(varnamebuf);
3565     varnamebuf = NULL;
3566     varnamebuflen = 0;
3567     return NULL;
3568 }
3569 
3570 #endif /* FEAT_CMDL_COMPL */
3571 
3572 /*
3573  * types for expressions.
3574  */
3575 typedef enum
3576 {
3577     TYPE_UNKNOWN = 0
3578     , TYPE_EQUAL	/* == */
3579     , TYPE_NEQUAL	/* != */
3580     , TYPE_GREATER	/* >  */
3581     , TYPE_GEQUAL	/* >= */
3582     , TYPE_SMALLER	/* <  */
3583     , TYPE_SEQUAL	/* <= */
3584     , TYPE_MATCH	/* =~ */
3585     , TYPE_NOMATCH	/* !~ */
3586 } exptype_T;
3587 
3588 /*
3589  * The "evaluate" argument: When FALSE, the argument is only parsed but not
3590  * executed.  The function may return OK, but the rettv will be of type
3591  * VAR_UNKNOWN.  The function still returns FAIL for a syntax error.
3592  */
3593 
3594 /*
3595  * Handle zero level expression.
3596  * This calls eval1() and handles error message and nextcmd.
3597  * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3598  * Note: "rettv.v_lock" is not set.
3599  * Return OK or FAIL.
3600  */
3601     static int
3602 eval0(arg, rettv, nextcmd, evaluate)
3603     char_u	*arg;
3604     typval_T	*rettv;
3605     char_u	**nextcmd;
3606     int		evaluate;
3607 {
3608     int		ret;
3609     char_u	*p;
3610 
3611     p = skipwhite(arg);
3612     ret = eval1(&p, rettv, evaluate);
3613     if (ret == FAIL || !ends_excmd(*p))
3614     {
3615 	if (ret != FAIL)
3616 	    clear_tv(rettv);
3617 	/*
3618 	 * Report the invalid expression unless the expression evaluation has
3619 	 * been cancelled due to an aborting error, an interrupt, or an
3620 	 * exception.
3621 	 */
3622 	if (!aborting())
3623 	    EMSG2(_(e_invexpr2), arg);
3624 	ret = FAIL;
3625     }
3626     if (nextcmd != NULL)
3627 	*nextcmd = check_nextcmd(p);
3628 
3629     return ret;
3630 }
3631 
3632 /*
3633  * Handle top level expression:
3634  *	expr1 ? expr0 : expr0
3635  *
3636  * "arg" must point to the first non-white of the expression.
3637  * "arg" is advanced to the next non-white after the recognized expression.
3638  *
3639  * Note: "rettv.v_lock" is not set.
3640  *
3641  * Return OK or FAIL.
3642  */
3643     static int
3644 eval1(arg, rettv, evaluate)
3645     char_u	**arg;
3646     typval_T	*rettv;
3647     int		evaluate;
3648 {
3649     int		result;
3650     typval_T	var2;
3651 
3652     /*
3653      * Get the first variable.
3654      */
3655     if (eval2(arg, rettv, evaluate) == FAIL)
3656 	return FAIL;
3657 
3658     if ((*arg)[0] == '?')
3659     {
3660 	result = FALSE;
3661 	if (evaluate)
3662 	{
3663 	    int		error = FALSE;
3664 
3665 	    if (get_tv_number_chk(rettv, &error) != 0)
3666 		result = TRUE;
3667 	    clear_tv(rettv);
3668 	    if (error)
3669 		return FAIL;
3670 	}
3671 
3672 	/*
3673 	 * Get the second variable.
3674 	 */
3675 	*arg = skipwhite(*arg + 1);
3676 	if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3677 	    return FAIL;
3678 
3679 	/*
3680 	 * Check for the ":".
3681 	 */
3682 	if ((*arg)[0] != ':')
3683 	{
3684 	    EMSG(_("E109: Missing ':' after '?'"));
3685 	    if (evaluate && result)
3686 		clear_tv(rettv);
3687 	    return FAIL;
3688 	}
3689 
3690 	/*
3691 	 * Get the third variable.
3692 	 */
3693 	*arg = skipwhite(*arg + 1);
3694 	if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3695 	{
3696 	    if (evaluate && result)
3697 		clear_tv(rettv);
3698 	    return FAIL;
3699 	}
3700 	if (evaluate && !result)
3701 	    *rettv = var2;
3702     }
3703 
3704     return OK;
3705 }
3706 
3707 /*
3708  * Handle first level expression:
3709  *	expr2 || expr2 || expr2	    logical OR
3710  *
3711  * "arg" must point to the first non-white of the expression.
3712  * "arg" is advanced to the next non-white after the recognized expression.
3713  *
3714  * Return OK or FAIL.
3715  */
3716     static int
3717 eval2(arg, rettv, evaluate)
3718     char_u	**arg;
3719     typval_T	*rettv;
3720     int		evaluate;
3721 {
3722     typval_T	var2;
3723     long	result;
3724     int		first;
3725     int		error = FALSE;
3726 
3727     /*
3728      * Get the first variable.
3729      */
3730     if (eval3(arg, rettv, evaluate) == FAIL)
3731 	return FAIL;
3732 
3733     /*
3734      * Repeat until there is no following "||".
3735      */
3736     first = TRUE;
3737     result = FALSE;
3738     while ((*arg)[0] == '|' && (*arg)[1] == '|')
3739     {
3740 	if (evaluate && first)
3741 	{
3742 	    if (get_tv_number_chk(rettv, &error) != 0)
3743 		result = TRUE;
3744 	    clear_tv(rettv);
3745 	    if (error)
3746 		return FAIL;
3747 	    first = FALSE;
3748 	}
3749 
3750 	/*
3751 	 * Get the second variable.
3752 	 */
3753 	*arg = skipwhite(*arg + 2);
3754 	if (eval3(arg, &var2, evaluate && !result) == FAIL)
3755 	    return FAIL;
3756 
3757 	/*
3758 	 * Compute the result.
3759 	 */
3760 	if (evaluate && !result)
3761 	{
3762 	    if (get_tv_number_chk(&var2, &error) != 0)
3763 		result = TRUE;
3764 	    clear_tv(&var2);
3765 	    if (error)
3766 		return FAIL;
3767 	}
3768 	if (evaluate)
3769 	{
3770 	    rettv->v_type = VAR_NUMBER;
3771 	    rettv->vval.v_number = result;
3772 	}
3773     }
3774 
3775     return OK;
3776 }
3777 
3778 /*
3779  * Handle second level expression:
3780  *	expr3 && expr3 && expr3	    logical AND
3781  *
3782  * "arg" must point to the first non-white of the expression.
3783  * "arg" is advanced to the next non-white after the recognized expression.
3784  *
3785  * Return OK or FAIL.
3786  */
3787     static int
3788 eval3(arg, rettv, evaluate)
3789     char_u	**arg;
3790     typval_T	*rettv;
3791     int		evaluate;
3792 {
3793     typval_T	var2;
3794     long	result;
3795     int		first;
3796     int		error = FALSE;
3797 
3798     /*
3799      * Get the first variable.
3800      */
3801     if (eval4(arg, rettv, evaluate) == FAIL)
3802 	return FAIL;
3803 
3804     /*
3805      * Repeat until there is no following "&&".
3806      */
3807     first = TRUE;
3808     result = TRUE;
3809     while ((*arg)[0] == '&' && (*arg)[1] == '&')
3810     {
3811 	if (evaluate && first)
3812 	{
3813 	    if (get_tv_number_chk(rettv, &error) == 0)
3814 		result = FALSE;
3815 	    clear_tv(rettv);
3816 	    if (error)
3817 		return FAIL;
3818 	    first = FALSE;
3819 	}
3820 
3821 	/*
3822 	 * Get the second variable.
3823 	 */
3824 	*arg = skipwhite(*arg + 2);
3825 	if (eval4(arg, &var2, evaluate && result) == FAIL)
3826 	    return FAIL;
3827 
3828 	/*
3829 	 * Compute the result.
3830 	 */
3831 	if (evaluate && result)
3832 	{
3833 	    if (get_tv_number_chk(&var2, &error) == 0)
3834 		result = FALSE;
3835 	    clear_tv(&var2);
3836 	    if (error)
3837 		return FAIL;
3838 	}
3839 	if (evaluate)
3840 	{
3841 	    rettv->v_type = VAR_NUMBER;
3842 	    rettv->vval.v_number = result;
3843 	}
3844     }
3845 
3846     return OK;
3847 }
3848 
3849 /*
3850  * Handle third level expression:
3851  *	var1 == var2
3852  *	var1 =~ var2
3853  *	var1 != var2
3854  *	var1 !~ var2
3855  *	var1 > var2
3856  *	var1 >= var2
3857  *	var1 < var2
3858  *	var1 <= var2
3859  *	var1 is var2
3860  *	var1 isnot var2
3861  *
3862  * "arg" must point to the first non-white of the expression.
3863  * "arg" is advanced to the next non-white after the recognized expression.
3864  *
3865  * Return OK or FAIL.
3866  */
3867     static int
3868 eval4(arg, rettv, evaluate)
3869     char_u	**arg;
3870     typval_T	*rettv;
3871     int		evaluate;
3872 {
3873     typval_T	var2;
3874     char_u	*p;
3875     int		i;
3876     exptype_T	type = TYPE_UNKNOWN;
3877     int		type_is = FALSE;    /* TRUE for "is" and "isnot" */
3878     int		len = 2;
3879     long	n1, n2;
3880     char_u	*s1, *s2;
3881     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
3882     regmatch_T	regmatch;
3883     int		ic;
3884     char_u	*save_cpo;
3885 
3886     /*
3887      * Get the first variable.
3888      */
3889     if (eval5(arg, rettv, evaluate) == FAIL)
3890 	return FAIL;
3891 
3892     p = *arg;
3893     switch (p[0])
3894     {
3895 	case '=':   if (p[1] == '=')
3896 			type = TYPE_EQUAL;
3897 		    else if (p[1] == '~')
3898 			type = TYPE_MATCH;
3899 		    break;
3900 	case '!':   if (p[1] == '=')
3901 			type = TYPE_NEQUAL;
3902 		    else if (p[1] == '~')
3903 			type = TYPE_NOMATCH;
3904 		    break;
3905 	case '>':   if (p[1] != '=')
3906 		    {
3907 			type = TYPE_GREATER;
3908 			len = 1;
3909 		    }
3910 		    else
3911 			type = TYPE_GEQUAL;
3912 		    break;
3913 	case '<':   if (p[1] != '=')
3914 		    {
3915 			type = TYPE_SMALLER;
3916 			len = 1;
3917 		    }
3918 		    else
3919 			type = TYPE_SEQUAL;
3920 		    break;
3921 	case 'i':   if (p[1] == 's')
3922 		    {
3923 			if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
3924 			    len = 5;
3925 			if (!vim_isIDc(p[len]))
3926 			{
3927 			    type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
3928 			    type_is = TRUE;
3929 			}
3930 		    }
3931 		    break;
3932     }
3933 
3934     /*
3935      * If there is a comparitive operator, use it.
3936      */
3937     if (type != TYPE_UNKNOWN)
3938     {
3939 	/* extra question mark appended: ignore case */
3940 	if (p[len] == '?')
3941 	{
3942 	    ic = TRUE;
3943 	    ++len;
3944 	}
3945 	/* extra '#' appended: match case */
3946 	else if (p[len] == '#')
3947 	{
3948 	    ic = FALSE;
3949 	    ++len;
3950 	}
3951 	/* nothing appened: use 'ignorecase' */
3952 	else
3953 	    ic = p_ic;
3954 
3955 	/*
3956 	 * Get the second variable.
3957 	 */
3958 	*arg = skipwhite(p + len);
3959 	if (eval5(arg, &var2, evaluate) == FAIL)
3960 	{
3961 	    clear_tv(rettv);
3962 	    return FAIL;
3963 	}
3964 
3965 	if (evaluate)
3966 	{
3967 	    if (type_is && rettv->v_type != var2.v_type)
3968 	    {
3969 		/* For "is" a different type always means FALSE, for "notis"
3970 		 * it means TRUE. */
3971 		n1 = (type == TYPE_NEQUAL);
3972 	    }
3973 	    else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
3974 	    {
3975 		if (type_is)
3976 		{
3977 		    n1 = (rettv->v_type == var2.v_type
3978 				   && rettv->vval.v_list == var2.vval.v_list);
3979 		    if (type == TYPE_NEQUAL)
3980 			n1 = !n1;
3981 		}
3982 		else if (rettv->v_type != var2.v_type
3983 			|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
3984 		{
3985 		    if (rettv->v_type != var2.v_type)
3986 			EMSG(_("E691: Can only compare List with List"));
3987 		    else
3988 			EMSG(_("E692: Invalid operation for Lists"));
3989 		    clear_tv(rettv);
3990 		    clear_tv(&var2);
3991 		    return FAIL;
3992 		}
3993 		else
3994 		{
3995 		    /* Compare two Lists for being equal or unequal. */
3996 		    n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
3997 		    if (type == TYPE_NEQUAL)
3998 			n1 = !n1;
3999 		}
4000 	    }
4001 
4002 	    else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4003 	    {
4004 		if (type_is)
4005 		{
4006 		    n1 = (rettv->v_type == var2.v_type
4007 				   && rettv->vval.v_dict == var2.vval.v_dict);
4008 		    if (type == TYPE_NEQUAL)
4009 			n1 = !n1;
4010 		}
4011 		else if (rettv->v_type != var2.v_type
4012 			|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4013 		{
4014 		    if (rettv->v_type != var2.v_type)
4015 			EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4016 		    else
4017 			EMSG(_("E736: Invalid operation for Dictionary"));
4018 		    clear_tv(rettv);
4019 		    clear_tv(&var2);
4020 		    return FAIL;
4021 		}
4022 		else
4023 		{
4024 		    /* Compare two Dictionaries for being equal or unequal. */
4025 		    n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4026 		    if (type == TYPE_NEQUAL)
4027 			n1 = !n1;
4028 		}
4029 	    }
4030 
4031 	    else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4032 	    {
4033 		if (rettv->v_type != var2.v_type
4034 			|| (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4035 		{
4036 		    if (rettv->v_type != var2.v_type)
4037 			EMSG(_("E693: Can only compare Funcref with Funcref"));
4038 		    else
4039 			EMSG(_("E694: Invalid operation for Funcrefs"));
4040 		    clear_tv(rettv);
4041 		    clear_tv(&var2);
4042 		    return FAIL;
4043 		}
4044 		else
4045 		{
4046 		    /* Compare two Funcrefs for being equal or unequal. */
4047 		    if (rettv->vval.v_string == NULL
4048 						|| var2.vval.v_string == NULL)
4049 			n1 = FALSE;
4050 		    else
4051 			n1 = STRCMP(rettv->vval.v_string,
4052 						     var2.vval.v_string) == 0;
4053 		    if (type == TYPE_NEQUAL)
4054 			n1 = !n1;
4055 		}
4056 	    }
4057 
4058 	    /*
4059 	     * If one of the two variables is a number, compare as a number.
4060 	     * When using "=~" or "!~", always compare as string.
4061 	     */
4062 	    else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4063 		    && type != TYPE_MATCH && type != TYPE_NOMATCH)
4064 	    {
4065 		n1 = get_tv_number(rettv);
4066 		n2 = get_tv_number(&var2);
4067 		switch (type)
4068 		{
4069 		    case TYPE_EQUAL:    n1 = (n1 == n2); break;
4070 		    case TYPE_NEQUAL:   n1 = (n1 != n2); break;
4071 		    case TYPE_GREATER:  n1 = (n1 > n2); break;
4072 		    case TYPE_GEQUAL:   n1 = (n1 >= n2); break;
4073 		    case TYPE_SMALLER:  n1 = (n1 < n2); break;
4074 		    case TYPE_SEQUAL:   n1 = (n1 <= n2); break;
4075 		    case TYPE_UNKNOWN:
4076 		    case TYPE_MATCH:
4077 		    case TYPE_NOMATCH:  break;  /* avoid gcc warning */
4078 		}
4079 	    }
4080 	    else
4081 	    {
4082 		s1 = get_tv_string_buf(rettv, buf1);
4083 		s2 = get_tv_string_buf(&var2, buf2);
4084 		if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4085 		    i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4086 		else
4087 		    i = 0;
4088 		n1 = FALSE;
4089 		switch (type)
4090 		{
4091 		    case TYPE_EQUAL:    n1 = (i == 0); break;
4092 		    case TYPE_NEQUAL:   n1 = (i != 0); break;
4093 		    case TYPE_GREATER:  n1 = (i > 0); break;
4094 		    case TYPE_GEQUAL:   n1 = (i >= 0); break;
4095 		    case TYPE_SMALLER:  n1 = (i < 0); break;
4096 		    case TYPE_SEQUAL:   n1 = (i <= 0); break;
4097 
4098 		    case TYPE_MATCH:
4099 		    case TYPE_NOMATCH:
4100 			    /* avoid 'l' flag in 'cpoptions' */
4101 			    save_cpo = p_cpo;
4102 			    p_cpo = (char_u *)"";
4103 			    regmatch.regprog = vim_regcomp(s2,
4104 							RE_MAGIC + RE_STRING);
4105 			    regmatch.rm_ic = ic;
4106 			    if (regmatch.regprog != NULL)
4107 			    {
4108 				n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4109 				vim_free(regmatch.regprog);
4110 				if (type == TYPE_NOMATCH)
4111 				    n1 = !n1;
4112 			    }
4113 			    p_cpo = save_cpo;
4114 			    break;
4115 
4116 		    case TYPE_UNKNOWN:  break;  /* avoid gcc warning */
4117 		}
4118 	    }
4119 	    clear_tv(rettv);
4120 	    clear_tv(&var2);
4121 	    rettv->v_type = VAR_NUMBER;
4122 	    rettv->vval.v_number = n1;
4123 	}
4124     }
4125 
4126     return OK;
4127 }
4128 
4129 /*
4130  * Handle fourth level expression:
4131  *	+	number addition
4132  *	-	number subtraction
4133  *	.	string concatenation
4134  *
4135  * "arg" must point to the first non-white of the expression.
4136  * "arg" is advanced to the next non-white after the recognized expression.
4137  *
4138  * Return OK or FAIL.
4139  */
4140     static int
4141 eval5(arg, rettv, evaluate)
4142     char_u	**arg;
4143     typval_T	*rettv;
4144     int		evaluate;
4145 {
4146     typval_T	var2;
4147     typval_T	var3;
4148     int		op;
4149     long	n1, n2;
4150     char_u	*s1, *s2;
4151     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4152     char_u	*p;
4153 
4154     /*
4155      * Get the first variable.
4156      */
4157     if (eval6(arg, rettv, evaluate) == FAIL)
4158 	return FAIL;
4159 
4160     /*
4161      * Repeat computing, until no '+', '-' or '.' is following.
4162      */
4163     for (;;)
4164     {
4165 	op = **arg;
4166 	if (op != '+' && op != '-' && op != '.')
4167 	    break;
4168 
4169 	if (op != '+' || rettv->v_type != VAR_LIST)
4170 	{
4171 	    /* For "list + ...", an illegal use of the first operand as
4172 	     * a number cannot be determined before evaluating the 2nd
4173 	     * operand: if this is also a list, all is ok.
4174 	     * For "something . ...", "something - ..." or "non-list + ...",
4175 	     * we know that the first operand needs to be a string or number
4176 	     * without evaluating the 2nd operand.  So check before to avoid
4177 	     * side effects after an error. */
4178 	    if (evaluate && get_tv_string_chk(rettv) == NULL)
4179 	    {
4180 		clear_tv(rettv);
4181 		return FAIL;
4182 	    }
4183 	}
4184 
4185 	/*
4186 	 * Get the second variable.
4187 	 */
4188 	*arg = skipwhite(*arg + 1);
4189 	if (eval6(arg, &var2, evaluate) == FAIL)
4190 	{
4191 	    clear_tv(rettv);
4192 	    return FAIL;
4193 	}
4194 
4195 	if (evaluate)
4196 	{
4197 	    /*
4198 	     * Compute the result.
4199 	     */
4200 	    if (op == '.')
4201 	    {
4202 		s1 = get_tv_string_buf(rettv, buf1);	/* already checked */
4203 		s2 = get_tv_string_buf_chk(&var2, buf2);
4204 		if (s2 == NULL)		/* type error ? */
4205 		{
4206 		    clear_tv(rettv);
4207 		    clear_tv(&var2);
4208 		    return FAIL;
4209 		}
4210 		p = concat_str(s1, s2);
4211 		clear_tv(rettv);
4212 		rettv->v_type = VAR_STRING;
4213 		rettv->vval.v_string = p;
4214 	    }
4215 	    else if (op == '+' && rettv->v_type == VAR_LIST
4216 						   && var2.v_type == VAR_LIST)
4217 	    {
4218 		/* concatenate Lists */
4219 		if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4220 							       &var3) == FAIL)
4221 		{
4222 		    clear_tv(rettv);
4223 		    clear_tv(&var2);
4224 		    return FAIL;
4225 		}
4226 		clear_tv(rettv);
4227 		*rettv = var3;
4228 	    }
4229 	    else
4230 	    {
4231 		int	    error = FALSE;
4232 
4233 		n1 = get_tv_number_chk(rettv, &error);
4234 		if (error)
4235 		{
4236 		    /* This can only happen for "list + non-list".
4237 		     * For "non-list + ..." or "something - ...", we returned
4238 		     * before evaluating the 2nd operand. */
4239 		    clear_tv(rettv);
4240 		    return FAIL;
4241 		}
4242 		n2 = get_tv_number_chk(&var2, &error);
4243 		if (error)
4244 		{
4245 		    clear_tv(rettv);
4246 		    clear_tv(&var2);
4247 		    return FAIL;
4248 		}
4249 		clear_tv(rettv);
4250 		if (op == '+')
4251 		    n1 = n1 + n2;
4252 		else
4253 		    n1 = n1 - n2;
4254 		rettv->v_type = VAR_NUMBER;
4255 		rettv->vval.v_number = n1;
4256 	    }
4257 	    clear_tv(&var2);
4258 	}
4259     }
4260     return OK;
4261 }
4262 
4263 /*
4264  * Handle fifth level expression:
4265  *	*	number multiplication
4266  *	/	number division
4267  *	%	number modulo
4268  *
4269  * "arg" must point to the first non-white of the expression.
4270  * "arg" is advanced to the next non-white after the recognized expression.
4271  *
4272  * Return OK or FAIL.
4273  */
4274     static int
4275 eval6(arg, rettv, evaluate)
4276     char_u	**arg;
4277     typval_T	*rettv;
4278     int		evaluate;
4279 {
4280     typval_T	var2;
4281     int		op;
4282     long	n1, n2;
4283     int		error = FALSE;
4284 
4285     /*
4286      * Get the first variable.
4287      */
4288     if (eval7(arg, rettv, evaluate) == FAIL)
4289 	return FAIL;
4290 
4291     /*
4292      * Repeat computing, until no '*', '/' or '%' is following.
4293      */
4294     for (;;)
4295     {
4296 	op = **arg;
4297 	if (op != '*' && op != '/' && op != '%')
4298 	    break;
4299 
4300 	if (evaluate)
4301 	{
4302 	    n1 = get_tv_number_chk(rettv, &error);
4303 	    clear_tv(rettv);
4304 	    if (error)
4305 		return FAIL;
4306 	}
4307 	else
4308 	    n1 = 0;
4309 
4310 	/*
4311 	 * Get the second variable.
4312 	 */
4313 	*arg = skipwhite(*arg + 1);
4314 	if (eval7(arg, &var2, evaluate) == FAIL)
4315 	    return FAIL;
4316 
4317 	if (evaluate)
4318 	{
4319 	    n2 = get_tv_number_chk(&var2, &error);
4320 	    clear_tv(&var2);
4321 	    if (error)
4322 		return FAIL;
4323 
4324 	    /*
4325 	     * Compute the result.
4326 	     */
4327 	    if (op == '*')
4328 		n1 = n1 * n2;
4329 	    else if (op == '/')
4330 	    {
4331 		if (n2 == 0)	/* give an error message? */
4332 		    n1 = 0x7fffffffL;
4333 		else
4334 		    n1 = n1 / n2;
4335 	    }
4336 	    else
4337 	    {
4338 		if (n2 == 0)	/* give an error message? */
4339 		    n1 = 0;
4340 		else
4341 		    n1 = n1 % n2;
4342 	    }
4343 	    rettv->v_type = VAR_NUMBER;
4344 	    rettv->vval.v_number = n1;
4345 	}
4346     }
4347 
4348     return OK;
4349 }
4350 
4351 /*
4352  * Handle sixth level expression:
4353  *  number		number constant
4354  *  "string"		string contstant
4355  *  'string'		literal string contstant
4356  *  &option-name	option value
4357  *  @r			register contents
4358  *  identifier		variable value
4359  *  function()		function call
4360  *  $VAR		environment variable
4361  *  (expression)	nested expression
4362  *  [expr, expr]	List
4363  *  {key: val, key: val}  Dictionary
4364  *
4365  *  Also handle:
4366  *  ! in front		logical NOT
4367  *  - in front		unary minus
4368  *  + in front		unary plus (ignored)
4369  *  trailing []		subscript in String or List
4370  *  trailing .name	entry in Dictionary
4371  *
4372  * "arg" must point to the first non-white of the expression.
4373  * "arg" is advanced to the next non-white after the recognized expression.
4374  *
4375  * Return OK or FAIL.
4376  */
4377     static int
4378 eval7(arg, rettv, evaluate)
4379     char_u	**arg;
4380     typval_T	*rettv;
4381     int		evaluate;
4382 {
4383     long	n;
4384     int		len;
4385     char_u	*s;
4386     int		val;
4387     char_u	*start_leader, *end_leader;
4388     int		ret = OK;
4389     char_u	*alias;
4390 
4391     /*
4392      * Initialise variable so that clear_tv() can't mistake this for a
4393      * string and free a string that isn't there.
4394      */
4395     rettv->v_type = VAR_UNKNOWN;
4396 
4397     /*
4398      * Skip '!' and '-' characters.  They are handled later.
4399      */
4400     start_leader = *arg;
4401     while (**arg == '!' || **arg == '-' || **arg == '+')
4402 	*arg = skipwhite(*arg + 1);
4403     end_leader = *arg;
4404 
4405     switch (**arg)
4406     {
4407     /*
4408      * Number constant.
4409      */
4410     case '0':
4411     case '1':
4412     case '2':
4413     case '3':
4414     case '4':
4415     case '5':
4416     case '6':
4417     case '7':
4418     case '8':
4419     case '9':
4420 		vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4421 		*arg += len;
4422 		if (evaluate)
4423 		{
4424 		    rettv->v_type = VAR_NUMBER;
4425 		    rettv->vval.v_number = n;
4426 		}
4427 		break;
4428 
4429     /*
4430      * String constant: "string".
4431      */
4432     case '"':	ret = get_string_tv(arg, rettv, evaluate);
4433 		break;
4434 
4435     /*
4436      * Literal string constant: 'str''ing'.
4437      */
4438     case '\'':	ret = get_lit_string_tv(arg, rettv, evaluate);
4439 		break;
4440 
4441     /*
4442      * List: [expr, expr]
4443      */
4444     case '[':	ret = get_list_tv(arg, rettv, evaluate);
4445 		break;
4446 
4447     /*
4448      * Dictionary: {key: val, key: val}
4449      */
4450     case '{':	ret = get_dict_tv(arg, rettv, evaluate);
4451 		break;
4452 
4453     /*
4454      * Option value: &name
4455      */
4456     case '&':	ret = get_option_tv(arg, rettv, evaluate);
4457 		break;
4458 
4459     /*
4460      * Environment variable: $VAR.
4461      */
4462     case '$':	ret = get_env_tv(arg, rettv, evaluate);
4463 		break;
4464 
4465     /*
4466      * Register contents: @r.
4467      */
4468     case '@':	++*arg;
4469 		if (evaluate)
4470 		{
4471 		    rettv->v_type = VAR_STRING;
4472 		    rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4473 		}
4474 		if (**arg != NUL)
4475 		    ++*arg;
4476 		break;
4477 
4478     /*
4479      * nested expression: (expression).
4480      */
4481     case '(':	*arg = skipwhite(*arg + 1);
4482 		ret = eval1(arg, rettv, evaluate);	/* recursive! */
4483 		if (**arg == ')')
4484 		    ++*arg;
4485 		else if (ret == OK)
4486 		{
4487 		    EMSG(_("E110: Missing ')'"));
4488 		    clear_tv(rettv);
4489 		    ret = FAIL;
4490 		}
4491 		break;
4492 
4493     default:	ret = NOTDONE;
4494 		break;
4495     }
4496 
4497     if (ret == NOTDONE)
4498     {
4499 	/*
4500 	 * Must be a variable or function name.
4501 	 * Can also be a curly-braces kind of name: {expr}.
4502 	 */
4503 	s = *arg;
4504 	len = get_name_len(arg, &alias, evaluate, TRUE);
4505 	if (alias != NULL)
4506 	    s = alias;
4507 
4508 	if (len <= 0)
4509 	    ret = FAIL;
4510 	else
4511 	{
4512 	    if (**arg == '(')		/* recursive! */
4513 	    {
4514 		/* If "s" is the name of a variable of type VAR_FUNC
4515 		 * use its contents. */
4516 		s = deref_func_name(s, &len);
4517 
4518 		/* Invoke the function. */
4519 		ret = get_func_tv(s, len, rettv, arg,
4520 			  curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4521 			  &len, evaluate, NULL);
4522 		/* Stop the expression evaluation when immediately
4523 		 * aborting on error, or when an interrupt occurred or
4524 		 * an exception was thrown but not caught. */
4525 		if (aborting())
4526 		{
4527 		    if (ret == OK)
4528 			clear_tv(rettv);
4529 		    ret = FAIL;
4530 		}
4531 	    }
4532 	    else if (evaluate)
4533 		ret = get_var_tv(s, len, rettv, TRUE);
4534 	    else
4535 		ret = OK;
4536 	}
4537 
4538 	if (alias != NULL)
4539 	    vim_free(alias);
4540     }
4541 
4542     *arg = skipwhite(*arg);
4543 
4544     /* Handle following '[', '(' and '.' for expr[expr], expr.name,
4545      * expr(expr). */
4546     if (ret == OK)
4547 	ret = handle_subscript(arg, rettv, evaluate, TRUE);
4548 
4549     /*
4550      * Apply logical NOT and unary '-', from right to left, ignore '+'.
4551      */
4552     if (ret == OK && evaluate && end_leader > start_leader)
4553     {
4554 	int	    error = FALSE;
4555 
4556 	val = get_tv_number_chk(rettv, &error);
4557 	if (error)
4558 	{
4559 	    clear_tv(rettv);
4560 	    ret = FAIL;
4561 	}
4562 	else
4563 	{
4564 	    while (end_leader > start_leader)
4565 	    {
4566 		--end_leader;
4567 		if (*end_leader == '!')
4568 		    val = !val;
4569 		else if (*end_leader == '-')
4570 		    val = -val;
4571 	    }
4572 	    clear_tv(rettv);
4573 	    rettv->v_type = VAR_NUMBER;
4574 	    rettv->vval.v_number = val;
4575 	}
4576     }
4577 
4578     return ret;
4579 }
4580 
4581 /*
4582  * Evaluate an "[expr]" or "[expr:expr]" index.
4583  * "*arg" points to the '['.
4584  * Returns FAIL or OK. "*arg" is advanced to after the ']'.
4585  */
4586     static int
4587 eval_index(arg, rettv, evaluate, verbose)
4588     char_u	**arg;
4589     typval_T	*rettv;
4590     int		evaluate;
4591     int		verbose;	/* give error messages */
4592 {
4593     int		empty1 = FALSE, empty2 = FALSE;
4594     typval_T	var1, var2;
4595     long	n1, n2 = 0;
4596     long	len = -1;
4597     int		range = FALSE;
4598     char_u	*s;
4599     char_u	*key = NULL;
4600 
4601     if (rettv->v_type == VAR_FUNC)
4602     {
4603 	if (verbose)
4604 	    EMSG(_("E695: Cannot index a Funcref"));
4605 	return FAIL;
4606     }
4607 
4608     if (**arg == '.')
4609     {
4610 	/*
4611 	 * dict.name
4612 	 */
4613 	key = *arg + 1;
4614 	for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
4615 	    ;
4616 	if (len == 0)
4617 	    return FAIL;
4618 	*arg = skipwhite(key + len);
4619     }
4620     else
4621     {
4622 	/*
4623 	 * something[idx]
4624 	 *
4625 	 * Get the (first) variable from inside the [].
4626 	 */
4627 	*arg = skipwhite(*arg + 1);
4628 	if (**arg == ':')
4629 	    empty1 = TRUE;
4630 	else if (eval1(arg, &var1, evaluate) == FAIL)	/* recursive! */
4631 	    return FAIL;
4632 	else if (evaluate && get_tv_string_chk(&var1) == NULL)
4633 	{
4634 	    /* not a number or string */
4635 	    clear_tv(&var1);
4636 	    return FAIL;
4637 	}
4638 
4639 	/*
4640 	 * Get the second variable from inside the [:].
4641 	 */
4642 	if (**arg == ':')
4643 	{
4644 	    range = TRUE;
4645 	    *arg = skipwhite(*arg + 1);
4646 	    if (**arg == ']')
4647 		empty2 = TRUE;
4648 	    else if (eval1(arg, &var2, evaluate) == FAIL)	/* recursive! */
4649 	    {
4650 		if (!empty1)
4651 		    clear_tv(&var1);
4652 		return FAIL;
4653 	    }
4654 	    else if (evaluate && get_tv_string_chk(&var2) == NULL)
4655 	    {
4656 		/* not a number or string */
4657 		if (!empty1)
4658 		    clear_tv(&var1);
4659 		clear_tv(&var2);
4660 		return FAIL;
4661 	    }
4662 	}
4663 
4664 	/* Check for the ']'. */
4665 	if (**arg != ']')
4666 	{
4667 	    if (verbose)
4668 		EMSG(_(e_missbrac));
4669 	    clear_tv(&var1);
4670 	    if (range)
4671 		clear_tv(&var2);
4672 	    return FAIL;
4673 	}
4674 	*arg = skipwhite(*arg + 1);	/* skip the ']' */
4675     }
4676 
4677     if (evaluate)
4678     {
4679 	n1 = 0;
4680 	if (!empty1 && rettv->v_type != VAR_DICT)
4681 	{
4682 	    n1 = get_tv_number(&var1);
4683 	    clear_tv(&var1);
4684 	}
4685 	if (range)
4686 	{
4687 	    if (empty2)
4688 		n2 = -1;
4689 	    else
4690 	    {
4691 		n2 = get_tv_number(&var2);
4692 		clear_tv(&var2);
4693 	    }
4694 	}
4695 
4696 	switch (rettv->v_type)
4697 	{
4698 	    case VAR_NUMBER:
4699 	    case VAR_STRING:
4700 		s = get_tv_string(rettv);
4701 		len = (long)STRLEN(s);
4702 		if (range)
4703 		{
4704 		    /* The resulting variable is a substring.  If the indexes
4705 		     * are out of range the result is empty. */
4706 		    if (n1 < 0)
4707 		    {
4708 			n1 = len + n1;
4709 			if (n1 < 0)
4710 			    n1 = 0;
4711 		    }
4712 		    if (n2 < 0)
4713 			n2 = len + n2;
4714 		    else if (n2 >= len)
4715 			n2 = len;
4716 		    if (n1 >= len || n2 < 0 || n1 > n2)
4717 			s = NULL;
4718 		    else
4719 			s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
4720 		}
4721 		else
4722 		{
4723 		    /* The resulting variable is a string of a single
4724 		     * character.  If the index is too big or negative the
4725 		     * result is empty. */
4726 		    if (n1 >= len || n1 < 0)
4727 			s = NULL;
4728 		    else
4729 			s = vim_strnsave(s + n1, 1);
4730 		}
4731 		clear_tv(rettv);
4732 		rettv->v_type = VAR_STRING;
4733 		rettv->vval.v_string = s;
4734 		break;
4735 
4736 	    case VAR_LIST:
4737 		len = list_len(rettv->vval.v_list);
4738 		if (n1 < 0)
4739 		    n1 = len + n1;
4740 		if (!empty1 && (n1 < 0 || n1 >= len))
4741 		{
4742 		    if (verbose)
4743 			EMSGN(_(e_listidx), n1);
4744 		    return FAIL;
4745 		}
4746 		if (range)
4747 		{
4748 		    list_T	*l;
4749 		    listitem_T	*item;
4750 
4751 		    if (n2 < 0)
4752 			n2 = len + n2;
4753 		    if (!empty2 && (n2 < 0 || n2 >= len || n2 + 1 < n1))
4754 		    {
4755 			if (verbose)
4756 			    EMSGN(_(e_listidx), n2);
4757 			return FAIL;
4758 		    }
4759 		    l = list_alloc();
4760 		    if (l == NULL)
4761 			return FAIL;
4762 		    for (item = list_find(rettv->vval.v_list, n1);
4763 							       n1 <= n2; ++n1)
4764 		    {
4765 			if (list_append_tv(l, &item->li_tv) == FAIL)
4766 			{
4767 			    list_free(l);
4768 			    return FAIL;
4769 			}
4770 			item = item->li_next;
4771 		    }
4772 		    clear_tv(rettv);
4773 		    rettv->v_type = VAR_LIST;
4774 		    rettv->vval.v_list = l;
4775 		    ++l->lv_refcount;
4776 		}
4777 		else
4778 		{
4779 		    copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv,
4780 								       &var1);
4781 		    clear_tv(rettv);
4782 		    *rettv = var1;
4783 		}
4784 		break;
4785 
4786 	    case VAR_DICT:
4787 		if (range)
4788 		{
4789 		    if (verbose)
4790 			EMSG(_(e_dictrange));
4791 		    if (len == -1)
4792 			clear_tv(&var1);
4793 		    return FAIL;
4794 		}
4795 		{
4796 		    dictitem_T	*item;
4797 
4798 		    if (len == -1)
4799 		    {
4800 			key = get_tv_string(&var1);
4801 			if (*key == NUL)
4802 			{
4803 			    if (verbose)
4804 				EMSG(_(e_emptykey));
4805 			    clear_tv(&var1);
4806 			    return FAIL;
4807 			}
4808 		    }
4809 
4810 		    item = dict_find(rettv->vval.v_dict, key, (int)len);
4811 
4812 		    if (item == NULL && verbose)
4813 			EMSG2(_(e_dictkey), key);
4814 		    if (len == -1)
4815 			clear_tv(&var1);
4816 		    if (item == NULL)
4817 			return FAIL;
4818 
4819 		    copy_tv(&item->di_tv, &var1);
4820 		    clear_tv(rettv);
4821 		    *rettv = var1;
4822 		}
4823 		break;
4824 	}
4825     }
4826 
4827     return OK;
4828 }
4829 
4830 /*
4831  * Get an option value.
4832  * "arg" points to the '&' or '+' before the option name.
4833  * "arg" is advanced to character after the option name.
4834  * Return OK or FAIL.
4835  */
4836     static int
4837 get_option_tv(arg, rettv, evaluate)
4838     char_u	**arg;
4839     typval_T	*rettv;	/* when NULL, only check if option exists */
4840     int		evaluate;
4841 {
4842     char_u	*option_end;
4843     long	numval;
4844     char_u	*stringval;
4845     int		opt_type;
4846     int		c;
4847     int		working = (**arg == '+');    /* has("+option") */
4848     int		ret = OK;
4849     int		opt_flags;
4850 
4851     /*
4852      * Isolate the option name and find its value.
4853      */
4854     option_end = find_option_end(arg, &opt_flags);
4855     if (option_end == NULL)
4856     {
4857 	if (rettv != NULL)
4858 	    EMSG2(_("E112: Option name missing: %s"), *arg);
4859 	return FAIL;
4860     }
4861 
4862     if (!evaluate)
4863     {
4864 	*arg = option_end;
4865 	return OK;
4866     }
4867 
4868     c = *option_end;
4869     *option_end = NUL;
4870     opt_type = get_option_value(*arg, &numval,
4871 			       rettv == NULL ? NULL : &stringval, opt_flags);
4872 
4873     if (opt_type == -3)			/* invalid name */
4874     {
4875 	if (rettv != NULL)
4876 	    EMSG2(_("E113: Unknown option: %s"), *arg);
4877 	ret = FAIL;
4878     }
4879     else if (rettv != NULL)
4880     {
4881 	if (opt_type == -2)		/* hidden string option */
4882 	{
4883 	    rettv->v_type = VAR_STRING;
4884 	    rettv->vval.v_string = NULL;
4885 	}
4886 	else if (opt_type == -1)	/* hidden number option */
4887 	{
4888 	    rettv->v_type = VAR_NUMBER;
4889 	    rettv->vval.v_number = 0;
4890 	}
4891 	else if (opt_type == 1)		/* number option */
4892 	{
4893 	    rettv->v_type = VAR_NUMBER;
4894 	    rettv->vval.v_number = numval;
4895 	}
4896 	else				/* string option */
4897 	{
4898 	    rettv->v_type = VAR_STRING;
4899 	    rettv->vval.v_string = stringval;
4900 	}
4901     }
4902     else if (working && (opt_type == -2 || opt_type == -1))
4903 	ret = FAIL;
4904 
4905     *option_end = c;		    /* put back for error messages */
4906     *arg = option_end;
4907 
4908     return ret;
4909 }
4910 
4911 /*
4912  * Allocate a variable for a string constant.
4913  * Return OK or FAIL.
4914  */
4915     static int
4916 get_string_tv(arg, rettv, evaluate)
4917     char_u	**arg;
4918     typval_T	*rettv;
4919     int		evaluate;
4920 {
4921     char_u	*p;
4922     char_u	*name;
4923     int		extra = 0;
4924 
4925     /*
4926      * Find the end of the string, skipping backslashed characters.
4927      */
4928     for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
4929     {
4930 	if (*p == '\\' && p[1] != NUL)
4931 	{
4932 	    ++p;
4933 	    /* A "\<x>" form occupies at least 4 characters, and produces up
4934 	     * to 6 characters: reserve space for 2 extra */
4935 	    if (*p == '<')
4936 		extra += 2;
4937 	}
4938     }
4939 
4940     if (*p != '"')
4941     {
4942 	EMSG2(_("E114: Missing quote: %s"), *arg);
4943 	return FAIL;
4944     }
4945 
4946     /* If only parsing, set *arg and return here */
4947     if (!evaluate)
4948     {
4949 	*arg = p + 1;
4950 	return OK;
4951     }
4952 
4953     /*
4954      * Copy the string into allocated memory, handling backslashed
4955      * characters.
4956      */
4957     name = alloc((unsigned)(p - *arg + extra));
4958     if (name == NULL)
4959 	return FAIL;
4960     rettv->v_type = VAR_STRING;
4961     rettv->vval.v_string = name;
4962 
4963     for (p = *arg + 1; *p != NUL && *p != '"'; )
4964     {
4965 	if (*p == '\\')
4966 	{
4967 	    switch (*++p)
4968 	    {
4969 		case 'b': *name++ = BS; ++p; break;
4970 		case 'e': *name++ = ESC; ++p; break;
4971 		case 'f': *name++ = FF; ++p; break;
4972 		case 'n': *name++ = NL; ++p; break;
4973 		case 'r': *name++ = CAR; ++p; break;
4974 		case 't': *name++ = TAB; ++p; break;
4975 
4976 		case 'X': /* hex: "\x1", "\x12" */
4977 		case 'x':
4978 		case 'u': /* Unicode: "\u0023" */
4979 		case 'U':
4980 			  if (vim_isxdigit(p[1]))
4981 			  {
4982 			      int	n, nr;
4983 			      int	c = toupper(*p);
4984 
4985 			      if (c == 'X')
4986 				  n = 2;
4987 			      else
4988 				  n = 4;
4989 			      nr = 0;
4990 			      while (--n >= 0 && vim_isxdigit(p[1]))
4991 			      {
4992 				  ++p;
4993 				  nr = (nr << 4) + hex2nr(*p);
4994 			      }
4995 			      ++p;
4996 #ifdef FEAT_MBYTE
4997 			      /* For "\u" store the number according to
4998 			       * 'encoding'. */
4999 			      if (c != 'X')
5000 				  name += (*mb_char2bytes)(nr, name);
5001 			      else
5002 #endif
5003 				  *name++ = nr;
5004 			  }
5005 			  break;
5006 
5007 			  /* octal: "\1", "\12", "\123" */
5008 		case '0':
5009 		case '1':
5010 		case '2':
5011 		case '3':
5012 		case '4':
5013 		case '5':
5014 		case '6':
5015 		case '7': *name = *p++ - '0';
5016 			  if (*p >= '0' && *p <= '7')
5017 			  {
5018 			      *name = (*name << 3) + *p++ - '0';
5019 			      if (*p >= '0' && *p <= '7')
5020 				  *name = (*name << 3) + *p++ - '0';
5021 			  }
5022 			  ++name;
5023 			  break;
5024 
5025 			    /* Special key, e.g.: "\<C-W>" */
5026 		case '<': extra = trans_special(&p, name, TRUE);
5027 			  if (extra != 0)
5028 			  {
5029 			      name += extra;
5030 			      break;
5031 			  }
5032 			  /* FALLTHROUGH */
5033 
5034 		default:  MB_COPY_CHAR(p, name);
5035 			  break;
5036 	    }
5037 	}
5038 	else
5039 	    MB_COPY_CHAR(p, name);
5040 
5041     }
5042     *name = NUL;
5043     *arg = p + 1;
5044 
5045     return OK;
5046 }
5047 
5048 /*
5049  * Allocate a variable for a 'str''ing' constant.
5050  * Return OK or FAIL.
5051  */
5052     static int
5053 get_lit_string_tv(arg, rettv, evaluate)
5054     char_u	**arg;
5055     typval_T	*rettv;
5056     int		evaluate;
5057 {
5058     char_u	*p;
5059     char_u	*str;
5060     int		reduce = 0;
5061 
5062     /*
5063      * Find the end of the string, skipping ''.
5064      */
5065     for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5066     {
5067 	if (*p == '\'')
5068 	{
5069 	    if (p[1] != '\'')
5070 		break;
5071 	    ++reduce;
5072 	    ++p;
5073 	}
5074     }
5075 
5076     if (*p != '\'')
5077     {
5078 	EMSG2(_("E115: Missing quote: %s"), *arg);
5079 	return FAIL;
5080     }
5081 
5082     /* If only parsing return after setting "*arg" */
5083     if (!evaluate)
5084     {
5085 	*arg = p + 1;
5086 	return OK;
5087     }
5088 
5089     /*
5090      * Copy the string into allocated memory, handling '' to ' reduction.
5091      */
5092     str = alloc((unsigned)((p - *arg) - reduce));
5093     if (str == NULL)
5094 	return FAIL;
5095     rettv->v_type = VAR_STRING;
5096     rettv->vval.v_string = str;
5097 
5098     for (p = *arg + 1; *p != NUL; )
5099     {
5100 	if (*p == '\'')
5101 	{
5102 	    if (p[1] != '\'')
5103 		break;
5104 	    ++p;
5105 	}
5106 	MB_COPY_CHAR(p, str);
5107     }
5108     *str = NUL;
5109     *arg = p + 1;
5110 
5111     return OK;
5112 }
5113 
5114 /*
5115  * Allocate a variable for a List and fill it from "*arg".
5116  * Return OK or FAIL.
5117  */
5118     static int
5119 get_list_tv(arg, rettv, evaluate)
5120     char_u	**arg;
5121     typval_T	*rettv;
5122     int		evaluate;
5123 {
5124     list_T	*l = NULL;
5125     typval_T	tv;
5126     listitem_T	*item;
5127 
5128     if (evaluate)
5129     {
5130 	l = list_alloc();
5131 	if (l == NULL)
5132 	    return FAIL;
5133     }
5134 
5135     *arg = skipwhite(*arg + 1);
5136     while (**arg != ']' && **arg != NUL)
5137     {
5138 	if (eval1(arg, &tv, evaluate) == FAIL)	/* recursive! */
5139 	    goto failret;
5140 	if (evaluate)
5141 	{
5142 	    item = listitem_alloc();
5143 	    if (item != NULL)
5144 	    {
5145 		item->li_tv = tv;
5146 		item->li_tv.v_lock = 0;
5147 		list_append(l, item);
5148 	    }
5149 	    else
5150 		clear_tv(&tv);
5151 	}
5152 
5153 	if (**arg == ']')
5154 	    break;
5155 	if (**arg != ',')
5156 	{
5157 	    EMSG2(_("E696: Missing comma in List: %s"), *arg);
5158 	    goto failret;
5159 	}
5160 	*arg = skipwhite(*arg + 1);
5161     }
5162 
5163     if (**arg != ']')
5164     {
5165 	EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5166 failret:
5167 	if (evaluate)
5168 	    list_free(l);
5169 	return FAIL;
5170     }
5171 
5172     *arg = skipwhite(*arg + 1);
5173     if (evaluate)
5174     {
5175 	rettv->v_type = VAR_LIST;
5176 	rettv->vval.v_list = l;
5177 	++l->lv_refcount;
5178     }
5179 
5180     return OK;
5181 }
5182 
5183 /*
5184  * Allocate an empty header for a list.
5185  * Caller should take care of the reference count.
5186  */
5187     static list_T *
5188 list_alloc()
5189 {
5190     list_T  *l;
5191 
5192     l = (list_T *)alloc_clear(sizeof(list_T));
5193     if (l != NULL)
5194     {
5195 	/* Prepend the list to the list of lists for garbage collection. */
5196 	if (first_list != NULL)
5197 	    first_list->lv_used_prev = l;
5198 	l->lv_used_prev = NULL;
5199 	l->lv_used_next = first_list;
5200 	first_list = l;
5201     }
5202     return l;
5203 }
5204 
5205 /*
5206  * Unreference a list: decrement the reference count and free it when it
5207  * becomes zero.
5208  */
5209     void
5210 list_unref(l)
5211     list_T *l;
5212 {
5213     if (l != NULL && l->lv_refcount != DEL_REFCOUNT && --l->lv_refcount <= 0)
5214 	list_free(l);
5215 }
5216 
5217 /*
5218  * Free a list, including all items it points to.
5219  * Ignores the reference count.
5220  */
5221     static void
5222 list_free(l)
5223     list_T *l;
5224 {
5225     listitem_T *item;
5226 
5227     /* Avoid that recursive reference to the list frees us again. */
5228     l->lv_refcount = DEL_REFCOUNT;
5229 
5230     /* Remove the list from the list of lists for garbage collection. */
5231     if (l->lv_used_prev == NULL)
5232 	first_list = l->lv_used_next;
5233     else
5234 	l->lv_used_prev->lv_used_next = l->lv_used_next;
5235     if (l->lv_used_next != NULL)
5236 	l->lv_used_next->lv_used_prev = l->lv_used_prev;
5237 
5238     for (item = l->lv_first; item != NULL; item = l->lv_first)
5239     {
5240 	/* Remove the item before deleting it. */
5241 	l->lv_first = item->li_next;
5242 	listitem_free(item);
5243     }
5244     vim_free(l);
5245 }
5246 
5247 /*
5248  * Allocate a list item.
5249  */
5250     static listitem_T *
5251 listitem_alloc()
5252 {
5253     return (listitem_T *)alloc(sizeof(listitem_T));
5254 }
5255 
5256 /*
5257  * Free a list item.  Also clears the value.  Does not notify watchers.
5258  */
5259     static void
5260 listitem_free(item)
5261     listitem_T *item;
5262 {
5263     clear_tv(&item->li_tv);
5264     vim_free(item);
5265 }
5266 
5267 /*
5268  * Remove a list item from a List and free it.  Also clears the value.
5269  */
5270     static void
5271 listitem_remove(l, item)
5272     list_T  *l;
5273     listitem_T *item;
5274 {
5275     list_remove(l, item, item);
5276     listitem_free(item);
5277 }
5278 
5279 /*
5280  * Get the number of items in a list.
5281  */
5282     static long
5283 list_len(l)
5284     list_T	*l;
5285 {
5286     if (l == NULL)
5287 	return 0L;
5288     return l->lv_len;
5289 }
5290 
5291 /*
5292  * Return TRUE when two lists have exactly the same values.
5293  */
5294     static int
5295 list_equal(l1, l2, ic)
5296     list_T	*l1;
5297     list_T	*l2;
5298     int		ic;	/* ignore case for strings */
5299 {
5300     listitem_T	*item1, *item2;
5301 
5302     if (list_len(l1) != list_len(l2))
5303 	return FALSE;
5304 
5305     for (item1 = l1->lv_first, item2 = l2->lv_first;
5306 	    item1 != NULL && item2 != NULL;
5307 			       item1 = item1->li_next, item2 = item2->li_next)
5308 	if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5309 	    return FALSE;
5310     return item1 == NULL && item2 == NULL;
5311 }
5312 
5313 /*
5314  * Return TRUE when two dictionaries have exactly the same key/values.
5315  */
5316     static int
5317 dict_equal(d1, d2, ic)
5318     dict_T	*d1;
5319     dict_T	*d2;
5320     int		ic;	/* ignore case for strings */
5321 {
5322     hashitem_T	*hi;
5323     dictitem_T	*item2;
5324     int		todo;
5325 
5326     if (dict_len(d1) != dict_len(d2))
5327 	return FALSE;
5328 
5329     todo = d1->dv_hashtab.ht_used;
5330     for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5331     {
5332 	if (!HASHITEM_EMPTY(hi))
5333 	{
5334 	    item2 = dict_find(d2, hi->hi_key, -1);
5335 	    if (item2 == NULL)
5336 		return FALSE;
5337 	    if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5338 		return FALSE;
5339 	    --todo;
5340 	}
5341     }
5342     return TRUE;
5343 }
5344 
5345 /*
5346  * Return TRUE if "tv1" and "tv2" have the same value.
5347  * Compares the items just like "==" would compare them, but strings and
5348  * numbers are different.
5349  */
5350     static int
5351 tv_equal(tv1, tv2, ic)
5352     typval_T *tv1;
5353     typval_T *tv2;
5354     int	    ic;	    /* ignore case */
5355 {
5356     char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5357     char_u	*s1, *s2;
5358 
5359     if (tv1->v_type != tv2->v_type)
5360 	return FALSE;
5361 
5362     switch (tv1->v_type)
5363     {
5364 	case VAR_LIST:
5365 	    /* recursive! */
5366 	    return list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5367 
5368 	case VAR_DICT:
5369 	    /* recursive! */
5370 	    return dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5371 
5372 	case VAR_FUNC:
5373 	    return (tv1->vval.v_string != NULL
5374 		    && tv2->vval.v_string != NULL
5375 		    && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5376 
5377 	case VAR_NUMBER:
5378 	    return tv1->vval.v_number == tv2->vval.v_number;
5379 
5380 	case VAR_STRING:
5381 	    s1 = get_tv_string_buf(tv1, buf1);
5382 	    s2 = get_tv_string_buf(tv2, buf2);
5383 	    return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5384     }
5385 
5386     EMSG2(_(e_intern2), "tv_equal()");
5387     return TRUE;
5388 }
5389 
5390 /*
5391  * Locate item with index "n" in list "l" and return it.
5392  * A negative index is counted from the end; -1 is the last item.
5393  * Returns NULL when "n" is out of range.
5394  */
5395     static listitem_T *
5396 list_find(l, n)
5397     list_T	*l;
5398     long	n;
5399 {
5400     listitem_T	*item;
5401     long	idx;
5402 
5403     if (l == NULL)
5404 	return NULL;
5405 
5406     /* Negative index is relative to the end. */
5407     if (n < 0)
5408 	n = l->lv_len + n;
5409 
5410     /* Check for index out of range. */
5411     if (n < 0 || n >= l->lv_len)
5412 	return NULL;
5413 
5414     /* When there is a cached index may start search from there. */
5415     if (l->lv_idx_item != NULL)
5416     {
5417 	if (n < l->lv_idx / 2)
5418 	{
5419 	    /* closest to the start of the list */
5420 	    item = l->lv_first;
5421 	    idx = 0;
5422 	}
5423 	else if (n > (l->lv_idx + l->lv_len) / 2)
5424 	{
5425 	    /* closest to the end of the list */
5426 	    item = l->lv_last;
5427 	    idx = l->lv_len - 1;
5428 	}
5429 	else
5430 	{
5431 	    /* closest to the cached index */
5432 	    item = l->lv_idx_item;
5433 	    idx = l->lv_idx;
5434 	}
5435     }
5436     else
5437     {
5438 	if (n < l->lv_len / 2)
5439 	{
5440 	    /* closest to the start of the list */
5441 	    item = l->lv_first;
5442 	    idx = 0;
5443 	}
5444 	else
5445 	{
5446 	    /* closest to the end of the list */
5447 	    item = l->lv_last;
5448 	    idx = l->lv_len - 1;
5449 	}
5450     }
5451 
5452     while (n > idx)
5453     {
5454 	/* search forward */
5455 	item = item->li_next;
5456 	++idx;
5457     }
5458     while (n < idx)
5459     {
5460 	/* search backward */
5461 	item = item->li_prev;
5462 	--idx;
5463     }
5464 
5465     /* cache the used index */
5466     l->lv_idx = idx;
5467     l->lv_idx_item = item;
5468 
5469     return item;
5470 }
5471 
5472 /*
5473  * Locate "item" list "l" and return its index.
5474  * Returns -1 when "item" is not in the list.
5475  */
5476     static long
5477 list_idx_of_item(l, item)
5478     list_T	*l;
5479     listitem_T	*item;
5480 {
5481     long	idx = 0;
5482     listitem_T	*li;
5483 
5484     if (l == NULL)
5485 	return -1;
5486     idx = 0;
5487     for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
5488 	++idx;
5489     if (li == NULL)
5490 	return -1;
5491     return idx;
5492 }
5493 
5494 /*
5495  * Append item "item" to the end of list "l".
5496  */
5497     static void
5498 list_append(l, item)
5499     list_T	*l;
5500     listitem_T	*item;
5501 {
5502     if (l->lv_last == NULL)
5503     {
5504 	/* empty list */
5505 	l->lv_first = item;
5506 	l->lv_last = item;
5507 	item->li_prev = NULL;
5508     }
5509     else
5510     {
5511 	l->lv_last->li_next = item;
5512 	item->li_prev = l->lv_last;
5513 	l->lv_last = item;
5514     }
5515     ++l->lv_len;
5516     item->li_next = NULL;
5517 }
5518 
5519 /*
5520  * Append typval_T "tv" to the end of list "l".
5521  * Return FAIL when out of memory.
5522  */
5523     static int
5524 list_append_tv(l, tv)
5525     list_T	*l;
5526     typval_T	*tv;
5527 {
5528     listitem_T	*li = listitem_alloc();
5529 
5530     if (li == NULL)
5531 	return FAIL;
5532     copy_tv(tv, &li->li_tv);
5533     list_append(l, li);
5534     return OK;
5535 }
5536 
5537 /*
5538  * Add a dictionary to a list.  Used by getqflist().
5539  * Return FAIL when out of memory.
5540  */
5541     int
5542 list_append_dict(list, dict)
5543     list_T	*list;
5544     dict_T	*dict;
5545 {
5546     listitem_T	*li = listitem_alloc();
5547 
5548     if (li == NULL)
5549 	return FAIL;
5550     li->li_tv.v_type = VAR_DICT;
5551     li->li_tv.v_lock = 0;
5552     li->li_tv.vval.v_dict = dict;
5553     list_append(list, li);
5554     ++dict->dv_refcount;
5555     return OK;
5556 }
5557 
5558 /*
5559  * Make a copy of "str" and append it as an item to list "l".
5560  * When "len" >= 0 use "str[len]".
5561  * Returns FAIL when out of memory.
5562  */
5563     static int
5564 list_append_string(l, str, len)
5565     list_T	*l;
5566     char_u	*str;
5567     int		len;
5568 {
5569     listitem_T *li = listitem_alloc();
5570 
5571     if (li == NULL)
5572 	return FAIL;
5573     list_append(l, li);
5574     li->li_tv.v_type = VAR_STRING;
5575     li->li_tv.v_lock = 0;
5576     if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
5577 						 : vim_strsave(str))) == NULL)
5578 	return FAIL;
5579     return OK;
5580 }
5581 
5582 /*
5583  * Append "n" to list "l".
5584  * Returns FAIL when out of memory.
5585  */
5586     static int
5587 list_append_number(l, n)
5588     list_T	*l;
5589     varnumber_T	n;
5590 {
5591     listitem_T	*li;
5592 
5593     li = listitem_alloc();
5594     if (li == NULL)
5595 	return FAIL;
5596     li->li_tv.v_type = VAR_NUMBER;
5597     li->li_tv.v_lock = 0;
5598     li->li_tv.vval.v_number = n;
5599     list_append(l, li);
5600     return OK;
5601 }
5602 
5603 /*
5604  * Insert typval_T "tv" in list "l" before "item".
5605  * If "item" is NULL append at the end.
5606  * Return FAIL when out of memory.
5607  */
5608     static int
5609 list_insert_tv(l, tv, item)
5610     list_T	*l;
5611     typval_T	*tv;
5612     listitem_T	*item;
5613 {
5614     listitem_T	*ni = listitem_alloc();
5615 
5616     if (ni == NULL)
5617 	return FAIL;
5618     copy_tv(tv, &ni->li_tv);
5619     if (item == NULL)
5620 	/* Append new item at end of list. */
5621 	list_append(l, ni);
5622     else
5623     {
5624 	/* Insert new item before existing item. */
5625 	ni->li_prev = item->li_prev;
5626 	ni->li_next = item;
5627 	if (item->li_prev == NULL)
5628 	{
5629 	    l->lv_first = ni;
5630 	    ++l->lv_idx;
5631 	}
5632 	else
5633 	{
5634 	    item->li_prev->li_next = ni;
5635 	    l->lv_idx_item = NULL;
5636 	}
5637 	item->li_prev = ni;
5638 	++l->lv_len;
5639     }
5640     return OK;
5641 }
5642 
5643 /*
5644  * Extend "l1" with "l2".
5645  * If "bef" is NULL append at the end, otherwise insert before this item.
5646  * Returns FAIL when out of memory.
5647  */
5648     static int
5649 list_extend(l1, l2, bef)
5650     list_T	*l1;
5651     list_T	*l2;
5652     listitem_T	*bef;
5653 {
5654     listitem_T	*item;
5655 
5656     for (item = l2->lv_first; item != NULL; item = item->li_next)
5657 	if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
5658 	    return FAIL;
5659     return OK;
5660 }
5661 
5662 /*
5663  * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
5664  * Return FAIL when out of memory.
5665  */
5666     static int
5667 list_concat(l1, l2, tv)
5668     list_T	*l1;
5669     list_T	*l2;
5670     typval_T	*tv;
5671 {
5672     list_T	*l;
5673 
5674     /* make a copy of the first list. */
5675     l = list_copy(l1, FALSE, 0);
5676     if (l == NULL)
5677 	return FAIL;
5678     tv->v_type = VAR_LIST;
5679     tv->vval.v_list = l;
5680 
5681     /* append all items from the second list */
5682     return list_extend(l, l2, NULL);
5683 }
5684 
5685 /*
5686  * Make a copy of list "orig".  Shallow if "deep" is FALSE.
5687  * The refcount of the new list is set to 1.
5688  * See item_copy() for "copyID".
5689  * Returns NULL when out of memory.
5690  */
5691     static list_T *
5692 list_copy(orig, deep, copyID)
5693     list_T	*orig;
5694     int		deep;
5695     int		copyID;
5696 {
5697     list_T	*copy;
5698     listitem_T	*item;
5699     listitem_T	*ni;
5700 
5701     if (orig == NULL)
5702 	return NULL;
5703 
5704     copy = list_alloc();
5705     if (copy != NULL)
5706     {
5707 	if (copyID != 0)
5708 	{
5709 	    /* Do this before adding the items, because one of the items may
5710 	     * refer back to this list. */
5711 	    orig->lv_copyID = copyID;
5712 	    orig->lv_copylist = copy;
5713 	}
5714 	for (item = orig->lv_first; item != NULL && !got_int;
5715 							 item = item->li_next)
5716 	{
5717 	    ni = listitem_alloc();
5718 	    if (ni == NULL)
5719 		break;
5720 	    if (deep)
5721 	    {
5722 		if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
5723 		{
5724 		    vim_free(ni);
5725 		    break;
5726 		}
5727 	    }
5728 	    else
5729 		copy_tv(&item->li_tv, &ni->li_tv);
5730 	    list_append(copy, ni);
5731 	}
5732 	++copy->lv_refcount;
5733 	if (item != NULL)
5734 	{
5735 	    list_unref(copy);
5736 	    copy = NULL;
5737 	}
5738     }
5739 
5740     return copy;
5741 }
5742 
5743 /*
5744  * Remove items "item" to "item2" from list "l".
5745  * Does not free the listitem or the value!
5746  */
5747     static void
5748 list_remove(l, item, item2)
5749     list_T	*l;
5750     listitem_T	*item;
5751     listitem_T	*item2;
5752 {
5753     listitem_T	*ip;
5754 
5755     /* notify watchers */
5756     for (ip = item; ip != NULL; ip = ip->li_next)
5757     {
5758 	--l->lv_len;
5759 	list_fix_watch(l, ip);
5760 	if (ip == item2)
5761 	    break;
5762     }
5763 
5764     if (item2->li_next == NULL)
5765 	l->lv_last = item->li_prev;
5766     else
5767 	item2->li_next->li_prev = item->li_prev;
5768     if (item->li_prev == NULL)
5769 	l->lv_first = item2->li_next;
5770     else
5771 	item->li_prev->li_next = item2->li_next;
5772     l->lv_idx_item = NULL;
5773 }
5774 
5775 /*
5776  * Return an allocated string with the string representation of a list.
5777  * May return NULL.
5778  */
5779     static char_u *
5780 list2string(tv)
5781     typval_T	*tv;
5782 {
5783     garray_T	ga;
5784 
5785     if (tv->vval.v_list == NULL)
5786 	return NULL;
5787     ga_init2(&ga, (int)sizeof(char), 80);
5788     ga_append(&ga, '[');
5789     if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE) == FAIL)
5790     {
5791 	vim_free(ga.ga_data);
5792 	return NULL;
5793     }
5794     ga_append(&ga, ']');
5795     ga_append(&ga, NUL);
5796     return (char_u *)ga.ga_data;
5797 }
5798 
5799 /*
5800  * Join list "l" into a string in "*gap", using separator "sep".
5801  * When "echo" is TRUE use String as echoed, otherwise as inside a List.
5802  * Return FAIL or OK.
5803  */
5804     static int
5805 list_join(gap, l, sep, echo)
5806     garray_T	*gap;
5807     list_T	*l;
5808     char_u	*sep;
5809     int		echo;
5810 {
5811     int		first = TRUE;
5812     char_u	*tofree;
5813     char_u	numbuf[NUMBUFLEN];
5814     listitem_T	*item;
5815     char_u	*s;
5816 
5817     for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
5818     {
5819 	if (first)
5820 	    first = FALSE;
5821 	else
5822 	    ga_concat(gap, sep);
5823 
5824 	if (echo)
5825 	    s = echo_string(&item->li_tv, &tofree, numbuf);
5826 	else
5827 	    s = tv2string(&item->li_tv, &tofree, numbuf);
5828 	if (s != NULL)
5829 	    ga_concat(gap, s);
5830 	vim_free(tofree);
5831 	if (s == NULL)
5832 	    return FAIL;
5833     }
5834     return OK;
5835 }
5836 
5837 /*
5838  * Garbage collection for lists and dictionaries.
5839  *
5840  * We use reference counts to be able to free most items right away when they
5841  * are no longer used.  But for composite items it's possible that it becomes
5842  * unused while the reference count is > 0: When there is a recursive
5843  * reference.  Example:
5844  *	:let l = [1, 2, 3]
5845  *	:let d = {9: l}
5846  *	:let l[1] = d
5847  *
5848  * Since this is quite unusual we handle this with garbage collection: every
5849  * once in a while find out which lists and dicts are not referenced from any
5850  * variable.
5851  *
5852  * Here is a good reference text about garbage collection (refers to Python
5853  * but it applies to all reference-counting mechanisms):
5854  *	http://python.ca/nas/python/gc/
5855  */
5856 
5857 /*
5858  * Do garbage collection for lists and dicts.
5859  * Return TRUE if some memory was freed.
5860  */
5861     int
5862 garbage_collect()
5863 {
5864     dict_T	*dd;
5865     list_T	*ll;
5866     int		copyID = ++current_copyID;
5867     buf_T	*buf;
5868     win_T	*wp;
5869     int		i;
5870     funccall_T	*fc;
5871     int		did_free = FALSE;
5872 
5873     /*
5874      * 1. Go through all accessible variables and mark all lists and dicts
5875      *    with copyID.
5876      */
5877     /* script-local variables */
5878     for (i = 1; i <= ga_scripts.ga_len; ++i)
5879 	set_ref_in_ht(&SCRIPT_VARS(i), copyID);
5880 
5881     /* buffer-local variables */
5882     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
5883 	set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
5884 
5885     /* window-local variables */
5886     FOR_ALL_WINDOWS(wp)
5887 	set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
5888 
5889     /* global variables */
5890     set_ref_in_ht(&globvarht, copyID);
5891 
5892     /* function-local variables */
5893     for (fc = current_funccal; fc != NULL; fc = fc->caller)
5894     {
5895 	set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
5896 	set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
5897     }
5898 
5899     /*
5900      * 2. Go through the list of dicts and free items without the copyID.
5901      */
5902     for (dd = first_dict; dd != NULL; )
5903 	if (dd->dv_copyID != copyID)
5904 	{
5905 	    dict_free(dd);
5906 	    did_free = TRUE;
5907 
5908 	    /* restart, next dict may also have been freed */
5909 	    dd = first_dict;
5910 	}
5911 	else
5912 	    dd = dd->dv_used_next;
5913 
5914     /*
5915      * 3. Go through the list of lists and free items without the copyID.
5916      *    But don't free a list that has a watcher (used in a for loop), these
5917      *    are not referenced anywhere.
5918      */
5919     for (ll = first_list; ll != NULL; )
5920 	if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
5921 	{
5922 	    list_free(ll);
5923 	    did_free = TRUE;
5924 
5925 	    /* restart, next list may also have been freed */
5926 	    ll = first_list;
5927 	}
5928 	else
5929 	    ll = ll->lv_used_next;
5930 
5931     return did_free;
5932 }
5933 
5934 /*
5935  * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
5936  */
5937     static void
5938 set_ref_in_ht(ht, copyID)
5939     hashtab_T	*ht;
5940     int		copyID;
5941 {
5942     int		todo;
5943     hashitem_T	*hi;
5944 
5945     todo = ht->ht_used;
5946     for (hi = ht->ht_array; todo > 0; ++hi)
5947 	if (!HASHITEM_EMPTY(hi))
5948 	{
5949 	    --todo;
5950 	    set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
5951 	}
5952 }
5953 
5954 /*
5955  * Mark all lists and dicts referenced through list "l" with "copyID".
5956  */
5957     static void
5958 set_ref_in_list(l, copyID)
5959     list_T	*l;
5960     int		copyID;
5961 {
5962     listitem_T *li;
5963 
5964     for (li = l->lv_first; li != NULL; li = li->li_next)
5965 	set_ref_in_item(&li->li_tv, copyID);
5966 }
5967 
5968 /*
5969  * Mark all lists and dicts referenced through typval "tv" with "copyID".
5970  */
5971     static void
5972 set_ref_in_item(tv, copyID)
5973     typval_T	*tv;
5974     int		copyID;
5975 {
5976     dict_T	*dd;
5977     list_T	*ll;
5978 
5979     switch (tv->v_type)
5980     {
5981 	case VAR_DICT:
5982 	    dd = tv->vval.v_dict;
5983 	    if (dd->dv_copyID != copyID)
5984 	    {
5985 		/* Didn't see this dict yet. */
5986 		dd->dv_copyID = copyID;
5987 		set_ref_in_ht(&dd->dv_hashtab, copyID);
5988 	    }
5989 	    break;
5990 
5991 	case VAR_LIST:
5992 	    ll = tv->vval.v_list;
5993 	    if (ll->lv_copyID != copyID)
5994 	    {
5995 		/* Didn't see this list yet. */
5996 		ll->lv_copyID = copyID;
5997 		set_ref_in_list(ll, copyID);
5998 	    }
5999 	    break;
6000     }
6001     return;
6002 }
6003 
6004 /*
6005  * Allocate an empty header for a dictionary.
6006  */
6007     dict_T *
6008 dict_alloc()
6009 {
6010     dict_T *d;
6011 
6012     d = (dict_T *)alloc(sizeof(dict_T));
6013     if (d != NULL)
6014     {
6015 	/* Add the list to the hashtable for garbage collection. */
6016 	if (first_dict != NULL)
6017 	    first_dict->dv_used_prev = d;
6018 	d->dv_used_next = first_dict;
6019 	d->dv_used_prev = NULL;
6020 
6021 	hash_init(&d->dv_hashtab);
6022 	d->dv_lock = 0;
6023 	d->dv_refcount = 0;
6024 	d->dv_copyID = 0;
6025     }
6026     return d;
6027 }
6028 
6029 /*
6030  * Unreference a Dictionary: decrement the reference count and free it when it
6031  * becomes zero.
6032  */
6033     static void
6034 dict_unref(d)
6035     dict_T *d;
6036 {
6037     if (d != NULL && d->dv_refcount != DEL_REFCOUNT && --d->dv_refcount <= 0)
6038 	dict_free(d);
6039 }
6040 
6041 /*
6042  * Free a Dictionary, including all items it contains.
6043  * Ignores the reference count.
6044  */
6045     static void
6046 dict_free(d)
6047     dict_T *d;
6048 {
6049     int		todo;
6050     hashitem_T	*hi;
6051     dictitem_T	*di;
6052 
6053     /* Avoid that recursive reference to the dict frees us again. */
6054     d->dv_refcount = DEL_REFCOUNT;
6055 
6056     /* Remove the dict from the list of dicts for garbage collection. */
6057     if (d->dv_used_prev == NULL)
6058 	first_dict = d->dv_used_next;
6059     else
6060 	d->dv_used_prev->dv_used_next = d->dv_used_next;
6061     if (d->dv_used_next != NULL)
6062 	d->dv_used_next->dv_used_prev = d->dv_used_prev;
6063 
6064     /* Lock the hashtab, we don't want it to resize while freeing items. */
6065     hash_lock(&d->dv_hashtab);
6066     todo = d->dv_hashtab.ht_used;
6067     for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6068     {
6069 	if (!HASHITEM_EMPTY(hi))
6070 	{
6071 	    /* Remove the item before deleting it, just in case there is
6072 	     * something recursive causing trouble. */
6073 	    di = HI2DI(hi);
6074 	    hash_remove(&d->dv_hashtab, hi);
6075 	    dictitem_free(di);
6076 	    --todo;
6077 	}
6078     }
6079     hash_clear(&d->dv_hashtab);
6080     vim_free(d);
6081 }
6082 
6083 /*
6084  * Allocate a Dictionary item.
6085  * The "key" is copied to the new item.
6086  * Note that the value of the item "di_tv" still needs to be initialized!
6087  * Returns NULL when out of memory.
6088  */
6089     static dictitem_T *
6090 dictitem_alloc(key)
6091     char_u	*key;
6092 {
6093     dictitem_T *di;
6094 
6095     di = (dictitem_T *)alloc(sizeof(dictitem_T) + STRLEN(key));
6096     if (di != NULL)
6097     {
6098 	STRCPY(di->di_key, key);
6099 	di->di_flags = 0;
6100     }
6101     return di;
6102 }
6103 
6104 /*
6105  * Make a copy of a Dictionary item.
6106  */
6107     static dictitem_T *
6108 dictitem_copy(org)
6109     dictitem_T *org;
6110 {
6111     dictitem_T *di;
6112 
6113     di = (dictitem_T *)alloc(sizeof(dictitem_T) + STRLEN(org->di_key));
6114     if (di != NULL)
6115     {
6116 	STRCPY(di->di_key, org->di_key);
6117 	di->di_flags = 0;
6118 	copy_tv(&org->di_tv, &di->di_tv);
6119     }
6120     return di;
6121 }
6122 
6123 /*
6124  * Remove item "item" from Dictionary "dict" and free it.
6125  */
6126     static void
6127 dictitem_remove(dict, item)
6128     dict_T	*dict;
6129     dictitem_T	*item;
6130 {
6131     hashitem_T	*hi;
6132 
6133     hi = hash_find(&dict->dv_hashtab, item->di_key);
6134     if (HASHITEM_EMPTY(hi))
6135 	EMSG2(_(e_intern2), "dictitem_remove()");
6136     else
6137 	hash_remove(&dict->dv_hashtab, hi);
6138     dictitem_free(item);
6139 }
6140 
6141 /*
6142  * Free a dict item.  Also clears the value.
6143  */
6144     static void
6145 dictitem_free(item)
6146     dictitem_T *item;
6147 {
6148     clear_tv(&item->di_tv);
6149     vim_free(item);
6150 }
6151 
6152 /*
6153  * Make a copy of dict "d".  Shallow if "deep" is FALSE.
6154  * The refcount of the new dict is set to 1.
6155  * See item_copy() for "copyID".
6156  * Returns NULL when out of memory.
6157  */
6158     static dict_T *
6159 dict_copy(orig, deep, copyID)
6160     dict_T	*orig;
6161     int		deep;
6162     int		copyID;
6163 {
6164     dict_T	*copy;
6165     dictitem_T	*di;
6166     int		todo;
6167     hashitem_T	*hi;
6168 
6169     if (orig == NULL)
6170 	return NULL;
6171 
6172     copy = dict_alloc();
6173     if (copy != NULL)
6174     {
6175 	if (copyID != 0)
6176 	{
6177 	    orig->dv_copyID = copyID;
6178 	    orig->dv_copydict = copy;
6179 	}
6180 	todo = orig->dv_hashtab.ht_used;
6181 	for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6182 	{
6183 	    if (!HASHITEM_EMPTY(hi))
6184 	    {
6185 		--todo;
6186 
6187 		di = dictitem_alloc(hi->hi_key);
6188 		if (di == NULL)
6189 		    break;
6190 		if (deep)
6191 		{
6192 		    if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6193 							      copyID) == FAIL)
6194 		    {
6195 			vim_free(di);
6196 			break;
6197 		    }
6198 		}
6199 		else
6200 		    copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6201 		if (dict_add(copy, di) == FAIL)
6202 		{
6203 		    dictitem_free(di);
6204 		    break;
6205 		}
6206 	    }
6207 	}
6208 
6209 	++copy->dv_refcount;
6210 	if (todo > 0)
6211 	{
6212 	    dict_unref(copy);
6213 	    copy = NULL;
6214 	}
6215     }
6216 
6217     return copy;
6218 }
6219 
6220 /*
6221  * Add item "item" to Dictionary "d".
6222  * Returns FAIL when out of memory and when key already existed.
6223  */
6224     static int
6225 dict_add(d, item)
6226     dict_T	*d;
6227     dictitem_T	*item;
6228 {
6229     return hash_add(&d->dv_hashtab, item->di_key);
6230 }
6231 
6232 /*
6233  * Add a number or string entry to dictionary "d".
6234  * When "str" is NULL use number "nr", otherwise use "str".
6235  * Returns FAIL when out of memory and when key already exists.
6236  */
6237     int
6238 dict_add_nr_str(d, key, nr, str)
6239     dict_T	*d;
6240     char	*key;
6241     long	nr;
6242     char_u	*str;
6243 {
6244     dictitem_T	*item;
6245 
6246     item = dictitem_alloc((char_u *)key);
6247     if (item == NULL)
6248 	return FAIL;
6249     item->di_tv.v_lock = 0;
6250     if (str == NULL)
6251     {
6252 	item->di_tv.v_type = VAR_NUMBER;
6253 	item->di_tv.vval.v_number = nr;
6254     }
6255     else
6256     {
6257 	item->di_tv.v_type = VAR_STRING;
6258 	item->di_tv.vval.v_string = vim_strsave(str);
6259     }
6260     if (dict_add(d, item) == FAIL)
6261     {
6262 	dictitem_free(item);
6263 	return FAIL;
6264     }
6265     return OK;
6266 }
6267 
6268 /*
6269  * Get the number of items in a Dictionary.
6270  */
6271     static long
6272 dict_len(d)
6273     dict_T	*d;
6274 {
6275     if (d == NULL)
6276 	return 0L;
6277     return d->dv_hashtab.ht_used;
6278 }
6279 
6280 /*
6281  * Find item "key[len]" in Dictionary "d".
6282  * If "len" is negative use strlen(key).
6283  * Returns NULL when not found.
6284  */
6285     static dictitem_T *
6286 dict_find(d, key, len)
6287     dict_T	*d;
6288     char_u	*key;
6289     int		len;
6290 {
6291 #define AKEYLEN 200
6292     char_u	buf[AKEYLEN];
6293     char_u	*akey;
6294     char_u	*tofree = NULL;
6295     hashitem_T	*hi;
6296 
6297     if (len < 0)
6298 	akey = key;
6299     else if (len >= AKEYLEN)
6300     {
6301 	tofree = akey = vim_strnsave(key, len);
6302 	if (akey == NULL)
6303 	    return NULL;
6304     }
6305     else
6306     {
6307 	/* Avoid a malloc/free by using buf[]. */
6308 	vim_strncpy(buf, key, len);
6309 	akey = buf;
6310     }
6311 
6312     hi = hash_find(&d->dv_hashtab, akey);
6313     vim_free(tofree);
6314     if (HASHITEM_EMPTY(hi))
6315 	return NULL;
6316     return HI2DI(hi);
6317 }
6318 
6319 /*
6320  * Get a string item from a dictionary in allocated memory.
6321  * Returns NULL if the entry doesn't exist or out of memory.
6322  */
6323     char_u *
6324 get_dict_string(d, key)
6325     dict_T	*d;
6326     char_u	*key;
6327 {
6328     dictitem_T	*di;
6329 
6330     di = dict_find(d, key, -1);
6331     if (di == NULL)
6332 	return NULL;
6333     return vim_strsave(get_tv_string(&di->di_tv));
6334 }
6335 
6336 /*
6337  * Get a number item from a dictionary.
6338  * Returns 0 if the entry doesn't exist or out of memory.
6339  */
6340     long
6341 get_dict_number(d, key)
6342     dict_T	*d;
6343     char_u	*key;
6344 {
6345     dictitem_T	*di;
6346 
6347     di = dict_find(d, key, -1);
6348     if (di == NULL)
6349 	return 0;
6350     return get_tv_number(&di->di_tv);
6351 }
6352 
6353 /*
6354  * Return an allocated string with the string representation of a Dictionary.
6355  * May return NULL.
6356  */
6357     static char_u *
6358 dict2string(tv)
6359     typval_T	*tv;
6360 {
6361     garray_T	ga;
6362     int		first = TRUE;
6363     char_u	*tofree;
6364     char_u	numbuf[NUMBUFLEN];
6365     hashitem_T	*hi;
6366     char_u	*s;
6367     dict_T	*d;
6368     int		todo;
6369 
6370     if ((d = tv->vval.v_dict) == NULL)
6371 	return NULL;
6372     ga_init2(&ga, (int)sizeof(char), 80);
6373     ga_append(&ga, '{');
6374 
6375     todo = d->dv_hashtab.ht_used;
6376     for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6377     {
6378 	if (!HASHITEM_EMPTY(hi))
6379 	{
6380 	    --todo;
6381 
6382 	    if (first)
6383 		first = FALSE;
6384 	    else
6385 		ga_concat(&ga, (char_u *)", ");
6386 
6387 	    tofree = string_quote(hi->hi_key, FALSE);
6388 	    if (tofree != NULL)
6389 	    {
6390 		ga_concat(&ga, tofree);
6391 		vim_free(tofree);
6392 	    }
6393 	    ga_concat(&ga, (char_u *)": ");
6394 	    s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf);
6395 	    if (s != NULL)
6396 		ga_concat(&ga, s);
6397 	    vim_free(tofree);
6398 	    if (s == NULL)
6399 		break;
6400 	}
6401     }
6402     if (todo > 0)
6403     {
6404 	vim_free(ga.ga_data);
6405 	return NULL;
6406     }
6407 
6408     ga_append(&ga, '}');
6409     ga_append(&ga, NUL);
6410     return (char_u *)ga.ga_data;
6411 }
6412 
6413 /*
6414  * Allocate a variable for a Dictionary and fill it from "*arg".
6415  * Return OK or FAIL.  Returns NOTDONE for {expr}.
6416  */
6417     static int
6418 get_dict_tv(arg, rettv, evaluate)
6419     char_u	**arg;
6420     typval_T	*rettv;
6421     int		evaluate;
6422 {
6423     dict_T	*d = NULL;
6424     typval_T	tvkey;
6425     typval_T	tv;
6426     char_u	*key;
6427     dictitem_T	*item;
6428     char_u	*start = skipwhite(*arg + 1);
6429     char_u	buf[NUMBUFLEN];
6430 
6431     /*
6432      * First check if it's not a curly-braces thing: {expr}.
6433      * Must do this without evaluating, otherwise a function may be called
6434      * twice.  Unfortunately this means we need to call eval1() twice for the
6435      * first item.
6436      * But {} is an empty Dictionary.
6437      */
6438     if (*start != '}')
6439     {
6440 	if (eval1(&start, &tv, FALSE) == FAIL)	/* recursive! */
6441 	    return FAIL;
6442 	if (*start == '}')
6443 	    return NOTDONE;
6444     }
6445 
6446     if (evaluate)
6447     {
6448 	d = dict_alloc();
6449 	if (d == NULL)
6450 	    return FAIL;
6451     }
6452     tvkey.v_type = VAR_UNKNOWN;
6453     tv.v_type = VAR_UNKNOWN;
6454 
6455     *arg = skipwhite(*arg + 1);
6456     while (**arg != '}' && **arg != NUL)
6457     {
6458 	if (eval1(arg, &tvkey, evaluate) == FAIL)	/* recursive! */
6459 	    goto failret;
6460 	if (**arg != ':')
6461 	{
6462 	    EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
6463 	    clear_tv(&tvkey);
6464 	    goto failret;
6465 	}
6466 	key = get_tv_string_buf_chk(&tvkey, buf);
6467 	if (key == NULL || *key == NUL)
6468 	{
6469 	    /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
6470 	    if (key != NULL)
6471 		EMSG(_(e_emptykey));
6472 	    clear_tv(&tvkey);
6473 	    goto failret;
6474 	}
6475 
6476 	*arg = skipwhite(*arg + 1);
6477 	if (eval1(arg, &tv, evaluate) == FAIL)	/* recursive! */
6478 	{
6479 	    clear_tv(&tvkey);
6480 	    goto failret;
6481 	}
6482 	if (evaluate)
6483 	{
6484 	    item = dict_find(d, key, -1);
6485 	    if (item != NULL)
6486 	    {
6487 		EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
6488 		clear_tv(&tvkey);
6489 		clear_tv(&tv);
6490 		goto failret;
6491 	    }
6492 	    item = dictitem_alloc(key);
6493 	    clear_tv(&tvkey);
6494 	    if (item != NULL)
6495 	    {
6496 		item->di_tv = tv;
6497 		item->di_tv.v_lock = 0;
6498 		if (dict_add(d, item) == FAIL)
6499 		    dictitem_free(item);
6500 	    }
6501 	}
6502 
6503 	if (**arg == '}')
6504 	    break;
6505 	if (**arg != ',')
6506 	{
6507 	    EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
6508 	    goto failret;
6509 	}
6510 	*arg = skipwhite(*arg + 1);
6511     }
6512 
6513     if (**arg != '}')
6514     {
6515 	EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
6516 failret:
6517 	if (evaluate)
6518 	    dict_free(d);
6519 	return FAIL;
6520     }
6521 
6522     *arg = skipwhite(*arg + 1);
6523     if (evaluate)
6524     {
6525 	rettv->v_type = VAR_DICT;
6526 	rettv->vval.v_dict = d;
6527 	++d->dv_refcount;
6528     }
6529 
6530     return OK;
6531 }
6532 
6533 /*
6534  * Return a string with the string representation of a variable.
6535  * If the memory is allocated "tofree" is set to it, otherwise NULL.
6536  * "numbuf" is used for a number.
6537  * Does not put quotes around strings, as ":echo" displays values.
6538  * May return NULL;
6539  */
6540     static char_u *
6541 echo_string(tv, tofree, numbuf)
6542     typval_T	*tv;
6543     char_u	**tofree;
6544     char_u	*numbuf;
6545 {
6546     static int	recurse = 0;
6547     char_u	*r = NULL;
6548 
6549     if (recurse >= DICT_MAXNEST)
6550     {
6551 	EMSG(_("E724: variable nested too deep for displaying"));
6552 	*tofree = NULL;
6553 	return NULL;
6554     }
6555     ++recurse;
6556 
6557     switch (tv->v_type)
6558     {
6559 	case VAR_FUNC:
6560 	    *tofree = NULL;
6561 	    r = tv->vval.v_string;
6562 	    break;
6563 	case VAR_LIST:
6564 	    *tofree = list2string(tv);
6565 	    r = *tofree;
6566 	    break;
6567 	case VAR_DICT:
6568 	    *tofree = dict2string(tv);
6569 	    r = *tofree;
6570 	    break;
6571 	case VAR_STRING:
6572 	case VAR_NUMBER:
6573 	    *tofree = NULL;
6574 	    r = get_tv_string_buf(tv, numbuf);
6575 	    break;
6576 	default:
6577 	    EMSG2(_(e_intern2), "echo_string()");
6578 	    *tofree = NULL;
6579     }
6580 
6581     --recurse;
6582     return r;
6583 }
6584 
6585 /*
6586  * Return a string with the string representation of a variable.
6587  * If the memory is allocated "tofree" is set to it, otherwise NULL.
6588  * "numbuf" is used for a number.
6589  * Puts quotes around strings, so that they can be parsed back by eval().
6590  * May return NULL;
6591  */
6592     static char_u *
6593 tv2string(tv, tofree, numbuf)
6594     typval_T	*tv;
6595     char_u	**tofree;
6596     char_u	*numbuf;
6597 {
6598     switch (tv->v_type)
6599     {
6600 	case VAR_FUNC:
6601 	    *tofree = string_quote(tv->vval.v_string, TRUE);
6602 	    return *tofree;
6603 	case VAR_STRING:
6604 	    *tofree = string_quote(tv->vval.v_string, FALSE);
6605 	    return *tofree;
6606 	case VAR_NUMBER:
6607 	case VAR_LIST:
6608 	case VAR_DICT:
6609 	    break;
6610 	default:
6611 	    EMSG2(_(e_intern2), "tv2string()");
6612     }
6613     return echo_string(tv, tofree, numbuf);
6614 }
6615 
6616 /*
6617  * Return string "str" in ' quotes, doubling ' characters.
6618  * If "str" is NULL an empty string is assumed.
6619  * If "function" is TRUE make it function('string').
6620  */
6621     static char_u *
6622 string_quote(str, function)
6623     char_u	*str;
6624     int		function;
6625 {
6626     unsigned	len;
6627     char_u	*p, *r, *s;
6628 
6629     len = (function ? 13 : 3);
6630     if (str != NULL)
6631     {
6632 	len += STRLEN(str);
6633 	for (p = str; *p != NUL; mb_ptr_adv(p))
6634 	    if (*p == '\'')
6635 		++len;
6636     }
6637     s = r = alloc(len);
6638     if (r != NULL)
6639     {
6640 	if (function)
6641 	{
6642 	    STRCPY(r, "function('");
6643 	    r += 10;
6644 	}
6645 	else
6646 	    *r++ = '\'';
6647 	if (str != NULL)
6648 	    for (p = str; *p != NUL; )
6649 	    {
6650 		if (*p == '\'')
6651 		    *r++ = '\'';
6652 		MB_COPY_CHAR(p, r);
6653 	    }
6654 	*r++ = '\'';
6655 	if (function)
6656 	    *r++ = ')';
6657 	*r++ = NUL;
6658     }
6659     return s;
6660 }
6661 
6662 /*
6663  * Get the value of an environment variable.
6664  * "arg" is pointing to the '$'.  It is advanced to after the name.
6665  * If the environment variable was not set, silently assume it is empty.
6666  * Always return OK.
6667  */
6668     static int
6669 get_env_tv(arg, rettv, evaluate)
6670     char_u	**arg;
6671     typval_T	*rettv;
6672     int		evaluate;
6673 {
6674     char_u	*string = NULL;
6675     int		len;
6676     int		cc;
6677     char_u	*name;
6678     int		mustfree = FALSE;
6679 
6680     ++*arg;
6681     name = *arg;
6682     len = get_env_len(arg);
6683     if (evaluate)
6684     {
6685 	if (len != 0)
6686 	{
6687 	    cc = name[len];
6688 	    name[len] = NUL;
6689 	    /* first try vim_getenv(), fast for normal environment vars */
6690 	    string = vim_getenv(name, &mustfree);
6691 	    if (string != NULL && *string != NUL)
6692 	    {
6693 		if (!mustfree)
6694 		    string = vim_strsave(string);
6695 	    }
6696 	    else
6697 	    {
6698 		if (mustfree)
6699 		    vim_free(string);
6700 
6701 		/* next try expanding things like $VIM and ${HOME} */
6702 		string = expand_env_save(name - 1);
6703 		if (string != NULL && *string == '$')
6704 		{
6705 		    vim_free(string);
6706 		    string = NULL;
6707 		}
6708 	    }
6709 	    name[len] = cc;
6710 	}
6711 	rettv->v_type = VAR_STRING;
6712 	rettv->vval.v_string = string;
6713     }
6714 
6715     return OK;
6716 }
6717 
6718 /*
6719  * Array with names and number of arguments of all internal functions
6720  * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
6721  */
6722 static struct fst
6723 {
6724     char	*f_name;	/* function name */
6725     char	f_min_argc;	/* minimal number of arguments */
6726     char	f_max_argc;	/* maximal number of arguments */
6727     void	(*f_func) __ARGS((typval_T *args, typval_T *rvar));
6728 				/* implemenation of function */
6729 } functions[] =
6730 {
6731     {"add",		2, 2, f_add},
6732     {"append",		2, 2, f_append},
6733     {"argc",		0, 0, f_argc},
6734     {"argidx",		0, 0, f_argidx},
6735     {"argv",		1, 1, f_argv},
6736     {"browse",		4, 4, f_browse},
6737     {"browsedir",	2, 2, f_browsedir},
6738     {"bufexists",	1, 1, f_bufexists},
6739     {"buffer_exists",	1, 1, f_bufexists},	/* obsolete */
6740     {"buffer_name",	1, 1, f_bufname},	/* obsolete */
6741     {"buffer_number",	1, 1, f_bufnr},		/* obsolete */
6742     {"buflisted",	1, 1, f_buflisted},
6743     {"bufloaded",	1, 1, f_bufloaded},
6744     {"bufname",		1, 1, f_bufname},
6745     {"bufnr",		1, 1, f_bufnr},
6746     {"bufwinnr",	1, 1, f_bufwinnr},
6747     {"byte2line",	1, 1, f_byte2line},
6748     {"byteidx",		2, 2, f_byteidx},
6749     {"call",		2, 3, f_call},
6750     {"char2nr",		1, 1, f_char2nr},
6751     {"cindent",		1, 1, f_cindent},
6752     {"col",		1, 1, f_col},
6753 #if defined(FEAT_INS_EXPAND)
6754     {"complete_add",	1, 1, f_complete_add},
6755     {"complete_check",	0, 0, f_complete_check},
6756 #endif
6757     {"confirm",		1, 4, f_confirm},
6758     {"copy",		1, 1, f_copy},
6759     {"count",		2, 4, f_count},
6760     {"cscope_connection",0,3, f_cscope_connection},
6761     {"cursor",		2, 2, f_cursor},
6762     {"deepcopy",	1, 2, f_deepcopy},
6763     {"delete",		1, 1, f_delete},
6764     {"did_filetype",	0, 0, f_did_filetype},
6765     {"diff_filler",	1, 1, f_diff_filler},
6766     {"diff_hlID",	2, 2, f_diff_hlID},
6767     {"empty",		1, 1, f_empty},
6768     {"escape",		2, 2, f_escape},
6769     {"eval",		1, 1, f_eval},
6770     {"eventhandler",	0, 0, f_eventhandler},
6771     {"executable",	1, 1, f_executable},
6772     {"exists",		1, 1, f_exists},
6773     {"expand",		1, 2, f_expand},
6774     {"extend",		2, 3, f_extend},
6775     {"file_readable",	1, 1, f_filereadable},	/* obsolete */
6776     {"filereadable",	1, 1, f_filereadable},
6777     {"filewritable",	1, 1, f_filewritable},
6778     {"filter",		2, 2, f_filter},
6779     {"finddir",		1, 3, f_finddir},
6780     {"findfile",	1, 3, f_findfile},
6781     {"fnamemodify",	2, 2, f_fnamemodify},
6782     {"foldclosed",	1, 1, f_foldclosed},
6783     {"foldclosedend",	1, 1, f_foldclosedend},
6784     {"foldlevel",	1, 1, f_foldlevel},
6785     {"foldtext",	0, 0, f_foldtext},
6786     {"foldtextresult",	1, 1, f_foldtextresult},
6787     {"foreground",	0, 0, f_foreground},
6788     {"function",	1, 1, f_function},
6789     {"garbagecollect",	0, 0, f_garbagecollect},
6790     {"get",		2, 3, f_get},
6791     {"getbufline",	2, 3, f_getbufline},
6792     {"getbufvar",	2, 2, f_getbufvar},
6793     {"getchar",		0, 1, f_getchar},
6794     {"getcharmod",	0, 0, f_getcharmod},
6795     {"getcmdline",	0, 0, f_getcmdline},
6796     {"getcmdpos",	0, 0, f_getcmdpos},
6797     {"getcmdtype",	0, 0, f_getcmdtype},
6798     {"getcwd",		0, 0, f_getcwd},
6799     {"getfontname",	0, 1, f_getfontname},
6800     {"getfperm",	1, 1, f_getfperm},
6801     {"getfsize",	1, 1, f_getfsize},
6802     {"getftime",	1, 1, f_getftime},
6803     {"getftype",	1, 1, f_getftype},
6804     {"getline",		1, 2, f_getline},
6805     {"getqflist",	0, 0, f_getqflist},
6806     {"getreg",		0, 2, f_getreg},
6807     {"getregtype",	0, 1, f_getregtype},
6808     {"getwinposx",	0, 0, f_getwinposx},
6809     {"getwinposy",	0, 0, f_getwinposy},
6810     {"getwinvar",	2, 2, f_getwinvar},
6811     {"glob",		1, 1, f_glob},
6812     {"globpath",	2, 2, f_globpath},
6813     {"has",		1, 1, f_has},
6814     {"has_key",		2, 2, f_has_key},
6815     {"hasmapto",	1, 2, f_hasmapto},
6816     {"highlightID",	1, 1, f_hlID},		/* obsolete */
6817     {"highlight_exists",1, 1, f_hlexists},	/* obsolete */
6818     {"histadd",		2, 2, f_histadd},
6819     {"histdel",		1, 2, f_histdel},
6820     {"histget",		1, 2, f_histget},
6821     {"histnr",		1, 1, f_histnr},
6822     {"hlID",		1, 1, f_hlID},
6823     {"hlexists",	1, 1, f_hlexists},
6824     {"hostname",	0, 0, f_hostname},
6825     {"iconv",		3, 3, f_iconv},
6826     {"indent",		1, 1, f_indent},
6827     {"index",		2, 4, f_index},
6828     {"input",		1, 3, f_input},
6829     {"inputdialog",	1, 3, f_inputdialog},
6830     {"inputlist",	1, 1, f_inputlist},
6831     {"inputrestore",	0, 0, f_inputrestore},
6832     {"inputsave",	0, 0, f_inputsave},
6833     {"inputsecret",	1, 2, f_inputsecret},
6834     {"insert",		2, 3, f_insert},
6835     {"isdirectory",	1, 1, f_isdirectory},
6836     {"islocked",	1, 1, f_islocked},
6837     {"items",		1, 1, f_items},
6838     {"join",		1, 2, f_join},
6839     {"keys",		1, 1, f_keys},
6840     {"last_buffer_nr",	0, 0, f_last_buffer_nr},/* obsolete */
6841     {"len",		1, 1, f_len},
6842     {"libcall",		3, 3, f_libcall},
6843     {"libcallnr",	3, 3, f_libcallnr},
6844     {"line",		1, 1, f_line},
6845     {"line2byte",	1, 1, f_line2byte},
6846     {"lispindent",	1, 1, f_lispindent},
6847     {"localtime",	0, 0, f_localtime},
6848     {"map",		2, 2, f_map},
6849     {"maparg",		1, 2, f_maparg},
6850     {"mapcheck",	1, 2, f_mapcheck},
6851     {"match",		2, 4, f_match},
6852     {"matchend",	2, 4, f_matchend},
6853     {"matchlist",	2, 4, f_matchlist},
6854     {"matchstr",	2, 4, f_matchstr},
6855     {"max",		1, 1, f_max},
6856     {"min",		1, 1, f_min},
6857 #ifdef vim_mkdir
6858     {"mkdir",		1, 3, f_mkdir},
6859 #endif
6860     {"mode",		0, 0, f_mode},
6861     {"nextnonblank",	1, 1, f_nextnonblank},
6862     {"nr2char",		1, 1, f_nr2char},
6863     {"prevnonblank",	1, 1, f_prevnonblank},
6864     {"printf",		2, 19, f_printf},
6865     {"range",		1, 3, f_range},
6866     {"readfile",	1, 3, f_readfile},
6867     {"remote_expr",	2, 3, f_remote_expr},
6868     {"remote_foreground", 1, 1, f_remote_foreground},
6869     {"remote_peek",	1, 2, f_remote_peek},
6870     {"remote_read",	1, 1, f_remote_read},
6871     {"remote_send",	2, 3, f_remote_send},
6872     {"remove",		2, 3, f_remove},
6873     {"rename",		2, 2, f_rename},
6874     {"repeat",		2, 2, f_repeat},
6875     {"resolve",		1, 1, f_resolve},
6876     {"reverse",		1, 1, f_reverse},
6877     {"search",		1, 2, f_search},
6878     {"searchdecl",	1, 3, f_searchdecl},
6879     {"searchpair",	3, 5, f_searchpair},
6880     {"server2client",	2, 2, f_server2client},
6881     {"serverlist",	0, 0, f_serverlist},
6882     {"setbufvar",	3, 3, f_setbufvar},
6883     {"setcmdpos",	1, 1, f_setcmdpos},
6884     {"setline",		2, 2, f_setline},
6885     {"setqflist",	1, 2, f_setqflist},
6886     {"setreg",		2, 3, f_setreg},
6887     {"setwinvar",	3, 3, f_setwinvar},
6888     {"simplify",	1, 1, f_simplify},
6889     {"sort",		1, 2, f_sort},
6890     {"soundfold",	1, 1, f_soundfold},
6891     {"spellbadword",	0, 1, f_spellbadword},
6892     {"spellsuggest",	1, 3, f_spellsuggest},
6893     {"split",		1, 3, f_split},
6894 #ifdef HAVE_STRFTIME
6895     {"strftime",	1, 2, f_strftime},
6896 #endif
6897     {"stridx",		2, 3, f_stridx},
6898     {"string",		1, 1, f_string},
6899     {"strlen",		1, 1, f_strlen},
6900     {"strpart",		2, 3, f_strpart},
6901     {"strridx",		2, 3, f_strridx},
6902     {"strtrans",	1, 1, f_strtrans},
6903     {"submatch",	1, 1, f_submatch},
6904     {"substitute",	4, 4, f_substitute},
6905     {"synID",		3, 3, f_synID},
6906     {"synIDattr",	2, 3, f_synIDattr},
6907     {"synIDtrans",	1, 1, f_synIDtrans},
6908     {"system",		1, 2, f_system},
6909     {"tagfiles",	0, 0, f_tagfiles},
6910     {"taglist",		1, 1, f_taglist},
6911     {"tempname",	0, 0, f_tempname},
6912     {"test",		1, 1, f_test},
6913     {"tolower",		1, 1, f_tolower},
6914     {"toupper",		1, 1, f_toupper},
6915     {"tr",		3, 3, f_tr},
6916     {"type",		1, 1, f_type},
6917     {"values",		1, 1, f_values},
6918     {"virtcol",		1, 1, f_virtcol},
6919     {"visualmode",	0, 1, f_visualmode},
6920     {"winbufnr",	1, 1, f_winbufnr},
6921     {"wincol",		0, 0, f_wincol},
6922     {"winheight",	1, 1, f_winheight},
6923     {"winline",		0, 0, f_winline},
6924     {"winnr",		0, 1, f_winnr},
6925     {"winrestcmd",	0, 0, f_winrestcmd},
6926     {"winwidth",	1, 1, f_winwidth},
6927     {"writefile",	2, 3, f_writefile},
6928 };
6929 
6930 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
6931 
6932 /*
6933  * Function given to ExpandGeneric() to obtain the list of internal
6934  * or user defined function names.
6935  */
6936     char_u *
6937 get_function_name(xp, idx)
6938     expand_T	*xp;
6939     int		idx;
6940 {
6941     static int	intidx = -1;
6942     char_u	*name;
6943 
6944     if (idx == 0)
6945 	intidx = -1;
6946     if (intidx < 0)
6947     {
6948 	name = get_user_func_name(xp, idx);
6949 	if (name != NULL)
6950 	    return name;
6951     }
6952     if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
6953     {
6954 	STRCPY(IObuff, functions[intidx].f_name);
6955 	STRCAT(IObuff, "(");
6956 	if (functions[intidx].f_max_argc == 0)
6957 	    STRCAT(IObuff, ")");
6958 	return IObuff;
6959     }
6960 
6961     return NULL;
6962 }
6963 
6964 /*
6965  * Function given to ExpandGeneric() to obtain the list of internal or
6966  * user defined variable or function names.
6967  */
6968 /*ARGSUSED*/
6969     char_u *
6970 get_expr_name(xp, idx)
6971     expand_T	*xp;
6972     int		idx;
6973 {
6974     static int	intidx = -1;
6975     char_u	*name;
6976 
6977     if (idx == 0)
6978 	intidx = -1;
6979     if (intidx < 0)
6980     {
6981 	name = get_function_name(xp, idx);
6982 	if (name != NULL)
6983 	    return name;
6984     }
6985     return get_user_var_name(xp, ++intidx);
6986 }
6987 
6988 #endif /* FEAT_CMDL_COMPL */
6989 
6990 /*
6991  * Find internal function in table above.
6992  * Return index, or -1 if not found
6993  */
6994     static int
6995 find_internal_func(name)
6996     char_u	*name;		/* name of the function */
6997 {
6998     int		first = 0;
6999     int		last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7000     int		cmp;
7001     int		x;
7002 
7003     /*
7004      * Find the function name in the table. Binary search.
7005      */
7006     while (first <= last)
7007     {
7008 	x = first + ((unsigned)(last - first) >> 1);
7009 	cmp = STRCMP(name, functions[x].f_name);
7010 	if (cmp < 0)
7011 	    last = x - 1;
7012 	else if (cmp > 0)
7013 	    first = x + 1;
7014 	else
7015 	    return x;
7016     }
7017     return -1;
7018 }
7019 
7020 /*
7021  * Check if "name" is a variable of type VAR_FUNC.  If so, return the function
7022  * name it contains, otherwise return "name".
7023  */
7024     static char_u *
7025 deref_func_name(name, lenp)
7026     char_u	*name;
7027     int		*lenp;
7028 {
7029     dictitem_T	*v;
7030     int		cc;
7031 
7032     cc = name[*lenp];
7033     name[*lenp] = NUL;
7034     v = find_var(name, NULL);
7035     name[*lenp] = cc;
7036     if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7037     {
7038 	if (v->di_tv.vval.v_string == NULL)
7039 	{
7040 	    *lenp = 0;
7041 	    return (char_u *)"";	/* just in case */
7042 	}
7043 	*lenp = STRLEN(v->di_tv.vval.v_string);
7044 	return v->di_tv.vval.v_string;
7045     }
7046 
7047     return name;
7048 }
7049 
7050 /*
7051  * Allocate a variable for the result of a function.
7052  * Return OK or FAIL.
7053  */
7054     static int
7055 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7056 							   evaluate, selfdict)
7057     char_u	*name;		/* name of the function */
7058     int		len;		/* length of "name" */
7059     typval_T	*rettv;
7060     char_u	**arg;		/* argument, pointing to the '(' */
7061     linenr_T	firstline;	/* first line of range */
7062     linenr_T	lastline;	/* last line of range */
7063     int		*doesrange;	/* return: function handled range */
7064     int		evaluate;
7065     dict_T	*selfdict;	/* Dictionary for "self" */
7066 {
7067     char_u	*argp;
7068     int		ret = OK;
7069     typval_T	argvars[MAX_FUNC_ARGS];	/* vars for arguments */
7070     int		argcount = 0;		/* number of arguments found */
7071 
7072     /*
7073      * Get the arguments.
7074      */
7075     argp = *arg;
7076     while (argcount < MAX_FUNC_ARGS)
7077     {
7078 	argp = skipwhite(argp + 1);	    /* skip the '(' or ',' */
7079 	if (*argp == ')' || *argp == ',' || *argp == NUL)
7080 	    break;
7081 	if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7082 	{
7083 	    ret = FAIL;
7084 	    break;
7085 	}
7086 	++argcount;
7087 	if (*argp != ',')
7088 	    break;
7089     }
7090     if (*argp == ')')
7091 	++argp;
7092     else
7093 	ret = FAIL;
7094 
7095     if (ret == OK)
7096 	ret = call_func(name, len, rettv, argcount, argvars,
7097 			  firstline, lastline, doesrange, evaluate, selfdict);
7098     else if (!aborting())
7099     {
7100 	if (argcount == MAX_FUNC_ARGS)
7101 	    emsg_funcname("E740: Too many arguments for function %s", name);
7102 	else
7103 	    emsg_funcname("E116: Invalid arguments for function %s", name);
7104     }
7105 
7106     while (--argcount >= 0)
7107 	clear_tv(&argvars[argcount]);
7108 
7109     *arg = skipwhite(argp);
7110     return ret;
7111 }
7112 
7113 
7114 /*
7115  * Call a function with its resolved parameters
7116  * Return OK or FAIL.
7117  */
7118     static int
7119 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7120 						doesrange, evaluate, selfdict)
7121     char_u	*name;		/* name of the function */
7122     int		len;		/* length of "name" */
7123     typval_T	*rettv;		/* return value goes here */
7124     int		argcount;	/* number of "argvars" */
7125     typval_T	*argvars;	/* vars for arguments */
7126     linenr_T	firstline;	/* first line of range */
7127     linenr_T	lastline;	/* last line of range */
7128     int		*doesrange;	/* return: function handled range */
7129     int		evaluate;
7130     dict_T	*selfdict;	/* Dictionary for "self" */
7131 {
7132     int		ret = FAIL;
7133 #define ERROR_UNKNOWN	0
7134 #define ERROR_TOOMANY	1
7135 #define ERROR_TOOFEW	2
7136 #define ERROR_SCRIPT	3
7137 #define ERROR_DICT	4
7138 #define ERROR_NONE	5
7139 #define ERROR_OTHER	6
7140     int		error = ERROR_NONE;
7141     int		i;
7142     int		llen;
7143     ufunc_T	*fp;
7144     int		cc;
7145 #define FLEN_FIXED 40
7146     char_u	fname_buf[FLEN_FIXED + 1];
7147     char_u	*fname;
7148 
7149     /*
7150      * In a script change <SID>name() and s:name() to K_SNR 123_name().
7151      * Change <SNR>123_name() to K_SNR 123_name().
7152      * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7153      */
7154     cc = name[len];
7155     name[len] = NUL;
7156     llen = eval_fname_script(name);
7157     if (llen > 0)
7158     {
7159 	fname_buf[0] = K_SPECIAL;
7160 	fname_buf[1] = KS_EXTRA;
7161 	fname_buf[2] = (int)KE_SNR;
7162 	i = 3;
7163 	if (eval_fname_sid(name))	/* "<SID>" or "s:" */
7164 	{
7165 	    if (current_SID <= 0)
7166 		error = ERROR_SCRIPT;
7167 	    else
7168 	    {
7169 		sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7170 		i = (int)STRLEN(fname_buf);
7171 	    }
7172 	}
7173 	if (i + STRLEN(name + llen) < FLEN_FIXED)
7174 	{
7175 	    STRCPY(fname_buf + i, name + llen);
7176 	    fname = fname_buf;
7177 	}
7178 	else
7179 	{
7180 	    fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
7181 	    if (fname == NULL)
7182 		error = ERROR_OTHER;
7183 	    else
7184 	    {
7185 		mch_memmove(fname, fname_buf, (size_t)i);
7186 		STRCPY(fname + i, name + llen);
7187 	    }
7188 	}
7189     }
7190     else
7191 	fname = name;
7192 
7193     *doesrange = FALSE;
7194 
7195 
7196     /* execute the function if no errors detected and executing */
7197     if (evaluate && error == ERROR_NONE)
7198     {
7199 	rettv->v_type = VAR_NUMBER;	/* default is number rettv */
7200 	error = ERROR_UNKNOWN;
7201 
7202 	if (!builtin_function(fname))
7203 	{
7204 	    /*
7205 	     * User defined function.
7206 	     */
7207 	    fp = find_func(fname);
7208 
7209 #ifdef FEAT_AUTOCMD
7210 	    /* Trigger FuncUndefined event, may load the function. */
7211 	    if (fp == NULL
7212 		    && apply_autocmds(EVENT_FUNCUNDEFINED,
7213 						     fname, fname, TRUE, NULL)
7214 		    && !aborting())
7215 	    {
7216 		/* executed an autocommand, search for the function again */
7217 		fp = find_func(fname);
7218 	    }
7219 #endif
7220 	    /* Try loading a package. */
7221 	    if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
7222 	    {
7223 		/* loaded a package, search for the function again */
7224 		fp = find_func(fname);
7225 	    }
7226 
7227 	    if (fp != NULL)
7228 	    {
7229 		if (fp->uf_flags & FC_RANGE)
7230 		    *doesrange = TRUE;
7231 		if (argcount < fp->uf_args.ga_len)
7232 		    error = ERROR_TOOFEW;
7233 		else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
7234 		    error = ERROR_TOOMANY;
7235 		else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
7236 		    error = ERROR_DICT;
7237 		else
7238 		{
7239 		    /*
7240 		     * Call the user function.
7241 		     * Save and restore search patterns, script variables and
7242 		     * redo buffer.
7243 		     */
7244 		    save_search_patterns();
7245 		    saveRedobuff();
7246 		    ++fp->uf_calls;
7247 		    call_user_func(fp, argcount, argvars, rettv,
7248 					       firstline, lastline,
7249 				  (fp->uf_flags & FC_DICT) ? selfdict : NULL);
7250 		    if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
7251 						      && fp->uf_refcount <= 0)
7252 			/* Function was unreferenced while being used, free it
7253 			 * now. */
7254 			func_free(fp);
7255 		    restoreRedobuff();
7256 		    restore_search_patterns();
7257 		    error = ERROR_NONE;
7258 		}
7259 	    }
7260 	}
7261 	else
7262 	{
7263 	    /*
7264 	     * Find the function name in the table, call its implementation.
7265 	     */
7266 	    i = find_internal_func(fname);
7267 	    if (i >= 0)
7268 	    {
7269 		if (argcount < functions[i].f_min_argc)
7270 		    error = ERROR_TOOFEW;
7271 		else if (argcount > functions[i].f_max_argc)
7272 		    error = ERROR_TOOMANY;
7273 		else
7274 		{
7275 		    argvars[argcount].v_type = VAR_UNKNOWN;
7276 		    functions[i].f_func(argvars, rettv);
7277 		    error = ERROR_NONE;
7278 		}
7279 	    }
7280 	}
7281 	/*
7282 	 * The function call (or "FuncUndefined" autocommand sequence) might
7283 	 * have been aborted by an error, an interrupt, or an explicitly thrown
7284 	 * exception that has not been caught so far.  This situation can be
7285 	 * tested for by calling aborting().  For an error in an internal
7286 	 * function or for the "E132" error in call_user_func(), however, the
7287 	 * throw point at which the "force_abort" flag (temporarily reset by
7288 	 * emsg()) is normally updated has not been reached yet. We need to
7289 	 * update that flag first to make aborting() reliable.
7290 	 */
7291 	update_force_abort();
7292     }
7293     if (error == ERROR_NONE)
7294 	ret = OK;
7295 
7296     /*
7297      * Report an error unless the argument evaluation or function call has been
7298      * cancelled due to an aborting error, an interrupt, or an exception.
7299      */
7300     if (!aborting())
7301     {
7302 	switch (error)
7303 	{
7304 	    case ERROR_UNKNOWN:
7305 		    emsg_funcname("E117: Unknown function: %s", name);
7306 		    break;
7307 	    case ERROR_TOOMANY:
7308 		    emsg_funcname(e_toomanyarg, name);
7309 		    break;
7310 	    case ERROR_TOOFEW:
7311 		    emsg_funcname("E119: Not enough arguments for function: %s",
7312 									name);
7313 		    break;
7314 	    case ERROR_SCRIPT:
7315 		    emsg_funcname("E120: Using <SID> not in a script context: %s",
7316 									name);
7317 		    break;
7318 	    case ERROR_DICT:
7319 		    emsg_funcname("E725: Calling dict function without Dictionary: %s",
7320 									name);
7321 		    break;
7322 	}
7323     }
7324 
7325     name[len] = cc;
7326     if (fname != name && fname != fname_buf)
7327 	vim_free(fname);
7328 
7329     return ret;
7330 }
7331 
7332 /*
7333  * Give an error message with a function name.  Handle <SNR> things.
7334  */
7335     static void
7336 emsg_funcname(msg, name)
7337     char	*msg;
7338     char_u	*name;
7339 {
7340     char_u	*p;
7341 
7342     if (*name == K_SPECIAL)
7343 	p = concat_str((char_u *)"<SNR>", name + 3);
7344     else
7345 	p = name;
7346     EMSG2(_(msg), p);
7347     if (p != name)
7348 	vim_free(p);
7349 }
7350 
7351 /*********************************************
7352  * Implementation of the built-in functions
7353  */
7354 
7355 /*
7356  * "add(list, item)" function
7357  */
7358     static void
7359 f_add(argvars, rettv)
7360     typval_T	*argvars;
7361     typval_T	*rettv;
7362 {
7363     list_T	*l;
7364 
7365     rettv->vval.v_number = 1; /* Default: Failed */
7366     if (argvars[0].v_type == VAR_LIST)
7367     {
7368 	if ((l = argvars[0].vval.v_list) != NULL
7369 		&& !tv_check_lock(l->lv_lock, (char_u *)"add()")
7370 		&& list_append_tv(l, &argvars[1]) == OK)
7371 	    copy_tv(&argvars[0], rettv);
7372     }
7373     else
7374 	EMSG(_(e_listreq));
7375 }
7376 
7377 /*
7378  * "append(lnum, string/list)" function
7379  */
7380     static void
7381 f_append(argvars, rettv)
7382     typval_T	*argvars;
7383     typval_T	*rettv;
7384 {
7385     long	lnum;
7386     char_u	*line;
7387     list_T	*l = NULL;
7388     listitem_T	*li = NULL;
7389     typval_T	*tv;
7390     long	added = 0;
7391 
7392     lnum = get_tv_lnum(argvars);
7393     if (lnum >= 0
7394 	    && lnum <= curbuf->b_ml.ml_line_count
7395 	    && u_save(lnum, lnum + 1) == OK)
7396     {
7397 	if (argvars[1].v_type == VAR_LIST)
7398 	{
7399 	    l = argvars[1].vval.v_list;
7400 	    if (l == NULL)
7401 		return;
7402 	    li = l->lv_first;
7403 	}
7404 	rettv->vval.v_number = 0;	/* Default: Success */
7405 	for (;;)
7406 	{
7407 	    if (l == NULL)
7408 		tv = &argvars[1];	/* append a string */
7409 	    else if (li == NULL)
7410 		break;			/* end of list */
7411 	    else
7412 		tv = &li->li_tv;	/* append item from list */
7413 	    line = get_tv_string_chk(tv);
7414 	    if (line == NULL)		/* type error */
7415 	    {
7416 		rettv->vval.v_number = 1;	/* Failed */
7417 		break;
7418 	    }
7419 	    ml_append(lnum + added, line, (colnr_T)0, FALSE);
7420 	    ++added;
7421 	    if (l == NULL)
7422 		break;
7423 	    li = li->li_next;
7424 	}
7425 
7426 	appended_lines_mark(lnum, added);
7427 	if (curwin->w_cursor.lnum > lnum)
7428 	    curwin->w_cursor.lnum += added;
7429     }
7430     else
7431 	rettv->vval.v_number = 1;	/* Failed */
7432 }
7433 
7434 /*
7435  * "argc()" function
7436  */
7437 /* ARGSUSED */
7438     static void
7439 f_argc(argvars, rettv)
7440     typval_T	*argvars;
7441     typval_T	*rettv;
7442 {
7443     rettv->vval.v_number = ARGCOUNT;
7444 }
7445 
7446 /*
7447  * "argidx()" function
7448  */
7449 /* ARGSUSED */
7450     static void
7451 f_argidx(argvars, rettv)
7452     typval_T	*argvars;
7453     typval_T	*rettv;
7454 {
7455     rettv->vval.v_number = curwin->w_arg_idx;
7456 }
7457 
7458 /*
7459  * "argv(nr)" function
7460  */
7461     static void
7462 f_argv(argvars, rettv)
7463     typval_T	*argvars;
7464     typval_T	*rettv;
7465 {
7466     int		idx;
7467 
7468     idx = get_tv_number_chk(&argvars[0], NULL);
7469     if (idx >= 0 && idx < ARGCOUNT)
7470 	rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
7471     else
7472 	rettv->vval.v_string = NULL;
7473     rettv->v_type = VAR_STRING;
7474 }
7475 
7476 /*
7477  * "browse(save, title, initdir, default)" function
7478  */
7479 /* ARGSUSED */
7480     static void
7481 f_browse(argvars, rettv)
7482     typval_T	*argvars;
7483     typval_T	*rettv;
7484 {
7485 #ifdef FEAT_BROWSE
7486     int		save;
7487     char_u	*title;
7488     char_u	*initdir;
7489     char_u	*defname;
7490     char_u	buf[NUMBUFLEN];
7491     char_u	buf2[NUMBUFLEN];
7492     int		error = FALSE;
7493 
7494     save = get_tv_number_chk(&argvars[0], &error);
7495     title = get_tv_string_chk(&argvars[1]);
7496     initdir = get_tv_string_buf_chk(&argvars[2], buf);
7497     defname = get_tv_string_buf_chk(&argvars[3], buf2);
7498 
7499     if (error || title == NULL || initdir == NULL || defname == NULL)
7500 	rettv->vval.v_string = NULL;
7501     else
7502 	rettv->vval.v_string =
7503 		 do_browse(save ? BROWSE_SAVE : 0,
7504 				 title, defname, NULL, initdir, NULL, curbuf);
7505 #else
7506     rettv->vval.v_string = NULL;
7507 #endif
7508     rettv->v_type = VAR_STRING;
7509 }
7510 
7511 /*
7512  * "browsedir(title, initdir)" function
7513  */
7514 /* ARGSUSED */
7515     static void
7516 f_browsedir(argvars, rettv)
7517     typval_T	*argvars;
7518     typval_T	*rettv;
7519 {
7520 #ifdef FEAT_BROWSE
7521     char_u	*title;
7522     char_u	*initdir;
7523     char_u	buf[NUMBUFLEN];
7524 
7525     title = get_tv_string_chk(&argvars[0]);
7526     initdir = get_tv_string_buf_chk(&argvars[1], buf);
7527 
7528     if (title == NULL || initdir == NULL)
7529 	rettv->vval.v_string = NULL;
7530     else
7531 	rettv->vval.v_string = do_browse(BROWSE_DIR,
7532 				    title, NULL, NULL, initdir, NULL, curbuf);
7533 #else
7534     rettv->vval.v_string = NULL;
7535 #endif
7536     rettv->v_type = VAR_STRING;
7537 }
7538 
7539 static buf_T *find_buffer __ARGS((typval_T *avar));
7540 
7541 /*
7542  * Find a buffer by number or exact name.
7543  */
7544     static buf_T *
7545 find_buffer(avar)
7546     typval_T	*avar;
7547 {
7548     buf_T	*buf = NULL;
7549 
7550     if (avar->v_type == VAR_NUMBER)
7551 	buf = buflist_findnr((int)avar->vval.v_number);
7552     else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
7553     {
7554 	buf = buflist_findname_exp(avar->vval.v_string);
7555 	if (buf == NULL)
7556 	{
7557 	    /* No full path name match, try a match with a URL or a "nofile"
7558 	     * buffer, these don't use the full path. */
7559 	    for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7560 		if (buf->b_fname != NULL
7561 			&& (path_with_url(buf->b_fname)
7562 #ifdef FEAT_QUICKFIX
7563 			    || bt_nofile(buf)
7564 #endif
7565 			   )
7566 			&& STRCMP(buf->b_fname, avar->vval.v_string) == 0)
7567 		    break;
7568 	}
7569     }
7570     return buf;
7571 }
7572 
7573 /*
7574  * "bufexists(expr)" function
7575  */
7576     static void
7577 f_bufexists(argvars, rettv)
7578     typval_T	*argvars;
7579     typval_T	*rettv;
7580 {
7581     rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
7582 }
7583 
7584 /*
7585  * "buflisted(expr)" function
7586  */
7587     static void
7588 f_buflisted(argvars, rettv)
7589     typval_T	*argvars;
7590     typval_T	*rettv;
7591 {
7592     buf_T	*buf;
7593 
7594     buf = find_buffer(&argvars[0]);
7595     rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
7596 }
7597 
7598 /*
7599  * "bufloaded(expr)" function
7600  */
7601     static void
7602 f_bufloaded(argvars, rettv)
7603     typval_T	*argvars;
7604     typval_T	*rettv;
7605 {
7606     buf_T	*buf;
7607 
7608     buf = find_buffer(&argvars[0]);
7609     rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
7610 }
7611 
7612 static buf_T *get_buf_tv __ARGS((typval_T *tv));
7613 
7614 /*
7615  * Get buffer by number or pattern.
7616  */
7617     static buf_T *
7618 get_buf_tv(tv)
7619     typval_T	*tv;
7620 {
7621     char_u	*name = tv->vval.v_string;
7622     int		save_magic;
7623     char_u	*save_cpo;
7624     buf_T	*buf;
7625 
7626     if (tv->v_type == VAR_NUMBER)
7627 	return buflist_findnr((int)tv->vval.v_number);
7628     if (tv->v_type != VAR_STRING)
7629 	return NULL;
7630     if (name == NULL || *name == NUL)
7631 	return curbuf;
7632     if (name[0] == '$' && name[1] == NUL)
7633 	return lastbuf;
7634 
7635     /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
7636     save_magic = p_magic;
7637     p_magic = TRUE;
7638     save_cpo = p_cpo;
7639     p_cpo = (char_u *)"";
7640 
7641     buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
7642 								TRUE, FALSE));
7643 
7644     p_magic = save_magic;
7645     p_cpo = save_cpo;
7646 
7647     /* If not found, try expanding the name, like done for bufexists(). */
7648     if (buf == NULL)
7649 	buf = find_buffer(tv);
7650 
7651     return buf;
7652 }
7653 
7654 /*
7655  * "bufname(expr)" function
7656  */
7657     static void
7658 f_bufname(argvars, rettv)
7659     typval_T	*argvars;
7660     typval_T	*rettv;
7661 {
7662     buf_T	*buf;
7663 
7664     (void)get_tv_number(&argvars[0]);	    /* issue errmsg if type error */
7665     ++emsg_off;
7666     buf = get_buf_tv(&argvars[0]);
7667     rettv->v_type = VAR_STRING;
7668     if (buf != NULL && buf->b_fname != NULL)
7669 	rettv->vval.v_string = vim_strsave(buf->b_fname);
7670     else
7671 	rettv->vval.v_string = NULL;
7672     --emsg_off;
7673 }
7674 
7675 /*
7676  * "bufnr(expr)" function
7677  */
7678     static void
7679 f_bufnr(argvars, rettv)
7680     typval_T	*argvars;
7681     typval_T	*rettv;
7682 {
7683     buf_T	*buf;
7684 
7685     (void)get_tv_number(&argvars[0]);	    /* issue errmsg if type error */
7686     ++emsg_off;
7687     buf = get_buf_tv(&argvars[0]);
7688     if (buf != NULL)
7689 	rettv->vval.v_number = buf->b_fnum;
7690     else
7691 	rettv->vval.v_number = -1;
7692     --emsg_off;
7693 }
7694 
7695 /*
7696  * "bufwinnr(nr)" function
7697  */
7698     static void
7699 f_bufwinnr(argvars, rettv)
7700     typval_T	*argvars;
7701     typval_T	*rettv;
7702 {
7703 #ifdef FEAT_WINDOWS
7704     win_T	*wp;
7705     int		winnr = 0;
7706 #endif
7707     buf_T	*buf;
7708 
7709     (void)get_tv_number(&argvars[0]);	    /* issue errmsg if type error */
7710     ++emsg_off;
7711     buf = get_buf_tv(&argvars[0]);
7712 #ifdef FEAT_WINDOWS
7713     for (wp = firstwin; wp; wp = wp->w_next)
7714     {
7715 	++winnr;
7716 	if (wp->w_buffer == buf)
7717 	    break;
7718     }
7719     rettv->vval.v_number = (wp != NULL ? winnr : -1);
7720 #else
7721     rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
7722 #endif
7723     --emsg_off;
7724 }
7725 
7726 /*
7727  * "byte2line(byte)" function
7728  */
7729 /*ARGSUSED*/
7730     static void
7731 f_byte2line(argvars, rettv)
7732     typval_T	*argvars;
7733     typval_T	*rettv;
7734 {
7735 #ifndef FEAT_BYTEOFF
7736     rettv->vval.v_number = -1;
7737 #else
7738     long	boff = 0;
7739 
7740     boff = get_tv_number(&argvars[0]) - 1;  /* boff gets -1 on type error */
7741     if (boff < 0)
7742 	rettv->vval.v_number = -1;
7743     else
7744 	rettv->vval.v_number = ml_find_line_or_offset(curbuf,
7745 							  (linenr_T)0, &boff);
7746 #endif
7747 }
7748 
7749 /*
7750  * "byteidx()" function
7751  */
7752 /*ARGSUSED*/
7753     static void
7754 f_byteidx(argvars, rettv)
7755     typval_T	*argvars;
7756     typval_T	*rettv;
7757 {
7758 #ifdef FEAT_MBYTE
7759     char_u	*t;
7760 #endif
7761     char_u	*str;
7762     long	idx;
7763 
7764     str = get_tv_string_chk(&argvars[0]);
7765     idx = get_tv_number_chk(&argvars[1], NULL);
7766     rettv->vval.v_number = -1;
7767     if (str == NULL || idx < 0)
7768 	return;
7769 
7770 #ifdef FEAT_MBYTE
7771     t = str;
7772     for ( ; idx > 0; idx--)
7773     {
7774 	if (*t == NUL)		/* EOL reached */
7775 	    return;
7776 	t += (*mb_ptr2len)(t);
7777     }
7778     rettv->vval.v_number = t - str;
7779 #else
7780     if (idx <= STRLEN(str))
7781 	rettv->vval.v_number = idx;
7782 #endif
7783 }
7784 
7785 /*
7786  * "call(func, arglist)" function
7787  */
7788     static void
7789 f_call(argvars, rettv)
7790     typval_T	*argvars;
7791     typval_T	*rettv;
7792 {
7793     char_u	*func;
7794     typval_T	argv[MAX_FUNC_ARGS];
7795     int		argc = 0;
7796     listitem_T	*item;
7797     int		dummy;
7798     dict_T	*selfdict = NULL;
7799 
7800     rettv->vval.v_number = 0;
7801     if (argvars[1].v_type != VAR_LIST)
7802     {
7803 	EMSG(_(e_listreq));
7804 	return;
7805     }
7806     if (argvars[1].vval.v_list == NULL)
7807 	return;
7808 
7809     if (argvars[0].v_type == VAR_FUNC)
7810 	func = argvars[0].vval.v_string;
7811     else
7812 	func = get_tv_string(&argvars[0]);
7813     if (*func == NUL)
7814 	return;		/* type error or empty name */
7815 
7816     if (argvars[2].v_type != VAR_UNKNOWN)
7817     {
7818 	if (argvars[2].v_type != VAR_DICT)
7819 	{
7820 	    EMSG(_(e_dictreq));
7821 	    return;
7822 	}
7823 	selfdict = argvars[2].vval.v_dict;
7824     }
7825 
7826     for (item = argvars[1].vval.v_list->lv_first; item != NULL;
7827 							 item = item->li_next)
7828     {
7829 	if (argc == MAX_FUNC_ARGS)
7830 	{
7831 	    EMSG(_("E699: Too many arguments"));
7832 	    break;
7833 	}
7834 	/* Make a copy of each argument.  This is needed to be able to set
7835 	 * v_lock to VAR_FIXED in the copy without changing the original list.
7836 	 */
7837 	copy_tv(&item->li_tv, &argv[argc++]);
7838     }
7839 
7840     if (item == NULL)
7841 	(void)call_func(func, STRLEN(func), rettv, argc, argv,
7842 				 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
7843 						      &dummy, TRUE, selfdict);
7844 
7845     /* Free the arguments. */
7846     while (argc > 0)
7847 	clear_tv(&argv[--argc]);
7848 }
7849 
7850 /*
7851  * "char2nr(string)" function
7852  */
7853     static void
7854 f_char2nr(argvars, rettv)
7855     typval_T	*argvars;
7856     typval_T	*rettv;
7857 {
7858 #ifdef FEAT_MBYTE
7859     if (has_mbyte)
7860 	rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
7861     else
7862 #endif
7863     rettv->vval.v_number = get_tv_string(&argvars[0])[0];
7864 }
7865 
7866 /*
7867  * "cindent(lnum)" function
7868  */
7869     static void
7870 f_cindent(argvars, rettv)
7871     typval_T	*argvars;
7872     typval_T	*rettv;
7873 {
7874 #ifdef FEAT_CINDENT
7875     pos_T	pos;
7876     linenr_T	lnum;
7877 
7878     pos = curwin->w_cursor;
7879     lnum = get_tv_lnum(argvars);
7880     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
7881     {
7882 	curwin->w_cursor.lnum = lnum;
7883 	rettv->vval.v_number = get_c_indent();
7884 	curwin->w_cursor = pos;
7885     }
7886     else
7887 #endif
7888 	rettv->vval.v_number = -1;
7889 }
7890 
7891 /*
7892  * "col(string)" function
7893  */
7894     static void
7895 f_col(argvars, rettv)
7896     typval_T	*argvars;
7897     typval_T	*rettv;
7898 {
7899     colnr_T	col = 0;
7900     pos_T	*fp;
7901 
7902     fp = var2fpos(&argvars[0], FALSE);
7903     if (fp != NULL)
7904     {
7905 	if (fp->col == MAXCOL)
7906 	{
7907 	    /* '> can be MAXCOL, get the length of the line then */
7908 	    if (fp->lnum <= curbuf->b_ml.ml_line_count)
7909 		col = STRLEN(ml_get(fp->lnum)) + 1;
7910 	    else
7911 		col = MAXCOL;
7912 	}
7913 	else
7914 	{
7915 	    col = fp->col + 1;
7916 #ifdef FEAT_VIRTUALEDIT
7917 	    /* col(".") when the cursor is on the NUL at the end of the line
7918 	     * because of "coladd" can be seen as an extra column. */
7919 	    if (virtual_active() && fp == &curwin->w_cursor)
7920 	    {
7921 		char_u	*p = ml_get_cursor();
7922 
7923 		if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
7924 				 curwin->w_virtcol - curwin->w_cursor.coladd))
7925 		{
7926 # ifdef FEAT_MBYTE
7927 		    int		l;
7928 
7929 		    if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
7930 			col += l;
7931 # else
7932 		    if (*p != NUL && p[1] == NUL)
7933 			++col;
7934 # endif
7935 		}
7936 	    }
7937 #endif
7938 	}
7939     }
7940     rettv->vval.v_number = col;
7941 }
7942 
7943 #if defined(FEAT_INS_EXPAND)
7944 /*
7945  * "complete_add()" function
7946  */
7947 /*ARGSUSED*/
7948     static void
7949 f_complete_add(argvars, rettv)
7950     typval_T	*argvars;
7951     typval_T	*rettv;
7952 {
7953     char_u	*s;
7954 
7955     s = get_tv_string_chk(&argvars[0]);
7956     if (s != NULL)
7957 	rettv->vval.v_number = ins_compl_add(s, -1, NULL, FORWARD, 0);
7958 }
7959 
7960 /*
7961  * "complete_check()" function
7962  */
7963 /*ARGSUSED*/
7964     static void
7965 f_complete_check(argvars, rettv)
7966     typval_T	*argvars;
7967     typval_T	*rettv;
7968 {
7969     int		saved = RedrawingDisabled;
7970 
7971     RedrawingDisabled = 0;
7972     ins_compl_check_keys(0);
7973     rettv->vval.v_number = compl_interrupted;
7974     RedrawingDisabled = saved;
7975 }
7976 #endif
7977 
7978 /*
7979  * "confirm(message, buttons[, default [, type]])" function
7980  */
7981 /*ARGSUSED*/
7982     static void
7983 f_confirm(argvars, rettv)
7984     typval_T	*argvars;
7985     typval_T	*rettv;
7986 {
7987 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
7988     char_u	*message;
7989     char_u	*buttons = NULL;
7990     char_u	buf[NUMBUFLEN];
7991     char_u	buf2[NUMBUFLEN];
7992     int		def = 1;
7993     int		type = VIM_GENERIC;
7994     char_u	*typestr;
7995     int		error = FALSE;
7996 
7997     message = get_tv_string_chk(&argvars[0]);
7998     if (message == NULL)
7999 	error = TRUE;
8000     if (argvars[1].v_type != VAR_UNKNOWN)
8001     {
8002 	buttons = get_tv_string_buf_chk(&argvars[1], buf);
8003 	if (buttons == NULL)
8004 	    error = TRUE;
8005 	if (argvars[2].v_type != VAR_UNKNOWN)
8006 	{
8007 	    def = get_tv_number_chk(&argvars[2], &error);
8008 	    if (argvars[3].v_type != VAR_UNKNOWN)
8009 	    {
8010 		typestr = get_tv_string_buf_chk(&argvars[3], buf2);
8011 		if (typestr == NULL)
8012 		    error = TRUE;
8013 		else
8014 		{
8015 		    switch (TOUPPER_ASC(*typestr))
8016 		    {
8017 			case 'E': type = VIM_ERROR; break;
8018 			case 'Q': type = VIM_QUESTION; break;
8019 			case 'I': type = VIM_INFO; break;
8020 			case 'W': type = VIM_WARNING; break;
8021 			case 'G': type = VIM_GENERIC; break;
8022 		    }
8023 		}
8024 	    }
8025 	}
8026     }
8027 
8028     if (buttons == NULL || *buttons == NUL)
8029 	buttons = (char_u *)_("&Ok");
8030 
8031     if (error)
8032 	rettv->vval.v_number = 0;
8033     else
8034 	rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
8035 								   def, NULL);
8036 #else
8037     rettv->vval.v_number = 0;
8038 #endif
8039 }
8040 
8041 /*
8042  * "copy()" function
8043  */
8044     static void
8045 f_copy(argvars, rettv)
8046     typval_T	*argvars;
8047     typval_T	*rettv;
8048 {
8049     item_copy(&argvars[0], rettv, FALSE, 0);
8050 }
8051 
8052 /*
8053  * "count()" function
8054  */
8055     static void
8056 f_count(argvars, rettv)
8057     typval_T	*argvars;
8058     typval_T	*rettv;
8059 {
8060     long	n = 0;
8061     int		ic = FALSE;
8062 
8063     if (argvars[0].v_type == VAR_LIST)
8064     {
8065 	listitem_T	*li;
8066 	list_T		*l;
8067 	long		idx;
8068 
8069 	if ((l = argvars[0].vval.v_list) != NULL)
8070 	{
8071 	    li = l->lv_first;
8072 	    if (argvars[2].v_type != VAR_UNKNOWN)
8073 	    {
8074 		int error = FALSE;
8075 
8076 		ic = get_tv_number_chk(&argvars[2], &error);
8077 		if (argvars[3].v_type != VAR_UNKNOWN)
8078 		{
8079 		    idx = get_tv_number_chk(&argvars[3], &error);
8080 		    if (!error)
8081 		    {
8082 			li = list_find(l, idx);
8083 			if (li == NULL)
8084 			    EMSGN(_(e_listidx), idx);
8085 		    }
8086 		}
8087 		if (error)
8088 		    li = NULL;
8089 	    }
8090 
8091 	    for ( ; li != NULL; li = li->li_next)
8092 		if (tv_equal(&li->li_tv, &argvars[1], ic))
8093 		    ++n;
8094 	}
8095     }
8096     else if (argvars[0].v_type == VAR_DICT)
8097     {
8098 	int		todo;
8099 	dict_T		*d;
8100 	hashitem_T	*hi;
8101 
8102 	if ((d = argvars[0].vval.v_dict) != NULL)
8103 	{
8104 	    int error = FALSE;
8105 
8106 	    if (argvars[2].v_type != VAR_UNKNOWN)
8107 	    {
8108 		ic = get_tv_number_chk(&argvars[2], &error);
8109 		if (argvars[3].v_type != VAR_UNKNOWN)
8110 		    EMSG(_(e_invarg));
8111 	    }
8112 
8113 	    todo = error ? 0 : d->dv_hashtab.ht_used;
8114 	    for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
8115 	    {
8116 		if (!HASHITEM_EMPTY(hi))
8117 		{
8118 		    --todo;
8119 		    if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
8120 			++n;
8121 		}
8122 	    }
8123 	}
8124     }
8125     else
8126 	EMSG2(_(e_listdictarg), "count()");
8127     rettv->vval.v_number = n;
8128 }
8129 
8130 /*
8131  * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
8132  *
8133  * Checks the existence of a cscope connection.
8134  */
8135 /*ARGSUSED*/
8136     static void
8137 f_cscope_connection(argvars, rettv)
8138     typval_T	*argvars;
8139     typval_T	*rettv;
8140 {
8141 #ifdef FEAT_CSCOPE
8142     int		num = 0;
8143     char_u	*dbpath = NULL;
8144     char_u	*prepend = NULL;
8145     char_u	buf[NUMBUFLEN];
8146 
8147     if (argvars[0].v_type != VAR_UNKNOWN
8148 	    && argvars[1].v_type != VAR_UNKNOWN)
8149     {
8150 	num = (int)get_tv_number(&argvars[0]);
8151 	dbpath = get_tv_string(&argvars[1]);
8152 	if (argvars[2].v_type != VAR_UNKNOWN)
8153 	    prepend = get_tv_string_buf(&argvars[2], buf);
8154     }
8155 
8156     rettv->vval.v_number = cs_connection(num, dbpath, prepend);
8157 #else
8158     rettv->vval.v_number = 0;
8159 #endif
8160 }
8161 
8162 /*
8163  * "cursor(lnum, col)" function
8164  *
8165  * Moves the cursor to the specified line and column
8166  */
8167 /*ARGSUSED*/
8168     static void
8169 f_cursor(argvars, rettv)
8170     typval_T	*argvars;
8171     typval_T	*rettv;
8172 {
8173     long	line, col;
8174 
8175     line = get_tv_lnum(argvars);
8176     col = get_tv_number_chk(&argvars[1], NULL);
8177     if (line < 0 || col < 0)
8178 	return;		/* type error; errmsg already given */
8179     if (line > 0)
8180 	curwin->w_cursor.lnum = line;
8181     if (col > 0)
8182 	curwin->w_cursor.col = col - 1;
8183 #ifdef FEAT_VIRTUALEDIT
8184     curwin->w_cursor.coladd = 0;
8185 #endif
8186 
8187     /* Make sure the cursor is in a valid position. */
8188     check_cursor();
8189 #ifdef FEAT_MBYTE
8190     /* Correct cursor for multi-byte character. */
8191     if (has_mbyte)
8192 	mb_adjust_cursor();
8193 #endif
8194 
8195     curwin->w_set_curswant = TRUE;
8196 }
8197 
8198 /*
8199  * "deepcopy()" function
8200  */
8201     static void
8202 f_deepcopy(argvars, rettv)
8203     typval_T	*argvars;
8204     typval_T	*rettv;
8205 {
8206     int		noref = 0;
8207 
8208     if (argvars[1].v_type != VAR_UNKNOWN)
8209 	noref = get_tv_number_chk(&argvars[1], NULL);
8210     if (noref < 0 || noref > 1)
8211 	EMSG(_(e_invarg));
8212     else
8213 	item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
8214 }
8215 
8216 /*
8217  * "delete()" function
8218  */
8219     static void
8220 f_delete(argvars, rettv)
8221     typval_T	*argvars;
8222     typval_T	*rettv;
8223 {
8224     if (check_restricted() || check_secure())
8225 	rettv->vval.v_number = -1;
8226     else
8227 	rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
8228 }
8229 
8230 /*
8231  * "did_filetype()" function
8232  */
8233 /*ARGSUSED*/
8234     static void
8235 f_did_filetype(argvars, rettv)
8236     typval_T	*argvars;
8237     typval_T	*rettv;
8238 {
8239 #ifdef FEAT_AUTOCMD
8240     rettv->vval.v_number = did_filetype;
8241 #else
8242     rettv->vval.v_number = 0;
8243 #endif
8244 }
8245 
8246 /*
8247  * "diff_filler()" function
8248  */
8249 /*ARGSUSED*/
8250     static void
8251 f_diff_filler(argvars, rettv)
8252     typval_T	*argvars;
8253     typval_T	*rettv;
8254 {
8255 #ifdef FEAT_DIFF
8256     rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
8257 #endif
8258 }
8259 
8260 /*
8261  * "diff_hlID()" function
8262  */
8263 /*ARGSUSED*/
8264     static void
8265 f_diff_hlID(argvars, rettv)
8266     typval_T	*argvars;
8267     typval_T	*rettv;
8268 {
8269 #ifdef FEAT_DIFF
8270     linenr_T		lnum = get_tv_lnum(argvars);
8271     static linenr_T	prev_lnum = 0;
8272     static int		changedtick = 0;
8273     static int		fnum = 0;
8274     static int		change_start = 0;
8275     static int		change_end = 0;
8276     static hlf_T	hlID = 0;
8277     int			filler_lines;
8278     int			col;
8279 
8280     if (lnum < 0)	/* ignore type error in {lnum} arg */
8281 	lnum = 0;
8282     if (lnum != prev_lnum
8283 	    || changedtick != curbuf->b_changedtick
8284 	    || fnum != curbuf->b_fnum)
8285     {
8286 	/* New line, buffer, change: need to get the values. */
8287 	filler_lines = diff_check(curwin, lnum);
8288 	if (filler_lines < 0)
8289 	{
8290 	    if (filler_lines == -1)
8291 	    {
8292 		change_start = MAXCOL;
8293 		change_end = -1;
8294 		if (diff_find_change(curwin, lnum, &change_start, &change_end))
8295 		    hlID = HLF_ADD;	/* added line */
8296 		else
8297 		    hlID = HLF_CHD;	/* changed line */
8298 	    }
8299 	    else
8300 		hlID = HLF_ADD;	/* added line */
8301 	}
8302 	else
8303 	    hlID = (hlf_T)0;
8304 	prev_lnum = lnum;
8305 	changedtick = curbuf->b_changedtick;
8306 	fnum = curbuf->b_fnum;
8307     }
8308 
8309     if (hlID == HLF_CHD || hlID == HLF_TXD)
8310     {
8311 	col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
8312 	if (col >= change_start && col <= change_end)
8313 	    hlID = HLF_TXD;			/* changed text */
8314 	else
8315 	    hlID = HLF_CHD;			/* changed line */
8316     }
8317     rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
8318 #endif
8319 }
8320 
8321 /*
8322  * "empty({expr})" function
8323  */
8324     static void
8325 f_empty(argvars, rettv)
8326     typval_T	*argvars;
8327     typval_T	*rettv;
8328 {
8329     int		n;
8330 
8331     switch (argvars[0].v_type)
8332     {
8333 	case VAR_STRING:
8334 	case VAR_FUNC:
8335 	    n = argvars[0].vval.v_string == NULL
8336 					  || *argvars[0].vval.v_string == NUL;
8337 	    break;
8338 	case VAR_NUMBER:
8339 	    n = argvars[0].vval.v_number == 0;
8340 	    break;
8341 	case VAR_LIST:
8342 	    n = argvars[0].vval.v_list == NULL
8343 				  || argvars[0].vval.v_list->lv_first == NULL;
8344 	    break;
8345 	case VAR_DICT:
8346 	    n = argvars[0].vval.v_dict == NULL
8347 			|| argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
8348 	    break;
8349 	default:
8350 	    EMSG2(_(e_intern2), "f_empty()");
8351 	    n = 0;
8352     }
8353 
8354     rettv->vval.v_number = n;
8355 }
8356 
8357 /*
8358  * "escape({string}, {chars})" function
8359  */
8360     static void
8361 f_escape(argvars, rettv)
8362     typval_T	*argvars;
8363     typval_T	*rettv;
8364 {
8365     char_u	buf[NUMBUFLEN];
8366 
8367     rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
8368 					 get_tv_string_buf(&argvars[1], buf));
8369     rettv->v_type = VAR_STRING;
8370 }
8371 
8372 /*
8373  * "eval()" function
8374  */
8375 /*ARGSUSED*/
8376     static void
8377 f_eval(argvars, rettv)
8378     typval_T	*argvars;
8379     typval_T	*rettv;
8380 {
8381     char_u	*s;
8382 
8383     s = get_tv_string_chk(&argvars[0]);
8384     if (s != NULL)
8385 	s = skipwhite(s);
8386 
8387     if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
8388     {
8389 	rettv->v_type = VAR_NUMBER;
8390 	rettv->vval.v_number = 0;
8391     }
8392     else if (*s != NUL)
8393 	EMSG(_(e_trailing));
8394 }
8395 
8396 /*
8397  * "eventhandler()" function
8398  */
8399 /*ARGSUSED*/
8400     static void
8401 f_eventhandler(argvars, rettv)
8402     typval_T	*argvars;
8403     typval_T	*rettv;
8404 {
8405     rettv->vval.v_number = vgetc_busy;
8406 }
8407 
8408 /*
8409  * "executable()" function
8410  */
8411     static void
8412 f_executable(argvars, rettv)
8413     typval_T	*argvars;
8414     typval_T	*rettv;
8415 {
8416     rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
8417 }
8418 
8419 /*
8420  * "exists()" function
8421  */
8422     static void
8423 f_exists(argvars, rettv)
8424     typval_T	*argvars;
8425     typval_T	*rettv;
8426 {
8427     char_u	*p;
8428     char_u	*name;
8429     int		n = FALSE;
8430     int		len = 0;
8431 
8432     p = get_tv_string(&argvars[0]);
8433     if (*p == '$')			/* environment variable */
8434     {
8435 	/* first try "normal" environment variables (fast) */
8436 	if (mch_getenv(p + 1) != NULL)
8437 	    n = TRUE;
8438 	else
8439 	{
8440 	    /* try expanding things like $VIM and ${HOME} */
8441 	    p = expand_env_save(p);
8442 	    if (p != NULL && *p != '$')
8443 		n = TRUE;
8444 	    vim_free(p);
8445 	}
8446     }
8447     else if (*p == '&' || *p == '+')			/* option */
8448 	n = (get_option_tv(&p, NULL, TRUE) == OK);
8449     else if (*p == '*')			/* internal or user defined function */
8450     {
8451 	n = function_exists(p + 1);
8452     }
8453     else if (*p == ':')
8454     {
8455 	n = cmd_exists(p + 1);
8456     }
8457     else if (*p == '#')
8458     {
8459 #ifdef FEAT_AUTOCMD
8460 	if (p[1] == '#')
8461 	    n = autocmd_supported(p + 2);
8462 	else
8463 	    n = au_exists(p + 1);
8464 #endif
8465     }
8466     else				/* internal variable */
8467     {
8468 	char_u	    *tofree;
8469 	typval_T    tv;
8470 
8471 	/* get_name_len() takes care of expanding curly braces */
8472 	name = p;
8473 	len = get_name_len(&p, &tofree, TRUE, FALSE);
8474 	if (len > 0)
8475 	{
8476 	    if (tofree != NULL)
8477 		name = tofree;
8478 	    n = (get_var_tv(name, len, &tv, FALSE) == OK);
8479 	    if (n)
8480 	    {
8481 		/* handle d.key, l[idx], f(expr) */
8482 		n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
8483 		if (n)
8484 		    clear_tv(&tv);
8485 	    }
8486 	}
8487 
8488 	vim_free(tofree);
8489     }
8490 
8491     rettv->vval.v_number = n;
8492 }
8493 
8494 /*
8495  * "expand()" function
8496  */
8497     static void
8498 f_expand(argvars, rettv)
8499     typval_T	*argvars;
8500     typval_T	*rettv;
8501 {
8502     char_u	*s;
8503     int		len;
8504     char_u	*errormsg;
8505     int		flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
8506     expand_T	xpc;
8507     int		error = FALSE;
8508 
8509     rettv->v_type = VAR_STRING;
8510     s = get_tv_string(&argvars[0]);
8511     if (*s == '%' || *s == '#' || *s == '<')
8512     {
8513 	++emsg_off;
8514 	rettv->vval.v_string = eval_vars(s, &len, NULL, &errormsg, s);
8515 	--emsg_off;
8516     }
8517     else
8518     {
8519 	/* When the optional second argument is non-zero, don't remove matches
8520 	 * for 'suffixes' and 'wildignore' */
8521 	if (argvars[1].v_type != VAR_UNKNOWN
8522 				    && get_tv_number_chk(&argvars[1], &error))
8523 	    flags |= WILD_KEEP_ALL;
8524 	if (!error)
8525 	{
8526 	    ExpandInit(&xpc);
8527 	    xpc.xp_context = EXPAND_FILES;
8528 	    rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
8529 	    ExpandCleanup(&xpc);
8530 	}
8531 	else
8532 	    rettv->vval.v_string = NULL;
8533     }
8534 }
8535 
8536 /*
8537  * "extend(list, list [, idx])" function
8538  * "extend(dict, dict [, action])" function
8539  */
8540     static void
8541 f_extend(argvars, rettv)
8542     typval_T	*argvars;
8543     typval_T	*rettv;
8544 {
8545     rettv->vval.v_number = 0;
8546     if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
8547     {
8548 	list_T		*l1, *l2;
8549 	listitem_T	*item;
8550 	long		before;
8551 	int		error = FALSE;
8552 
8553 	l1 = argvars[0].vval.v_list;
8554 	l2 = argvars[1].vval.v_list;
8555 	if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
8556 		&& l2 != NULL)
8557 	{
8558 	    if (argvars[2].v_type != VAR_UNKNOWN)
8559 	    {
8560 		before = get_tv_number_chk(&argvars[2], &error);
8561 		if (error)
8562 		    return;		/* type error; errmsg already given */
8563 
8564 		if (before == l1->lv_len)
8565 		    item = NULL;
8566 		else
8567 		{
8568 		    item = list_find(l1, before);
8569 		    if (item == NULL)
8570 		    {
8571 			EMSGN(_(e_listidx), before);
8572 			return;
8573 		    }
8574 		}
8575 	    }
8576 	    else
8577 		item = NULL;
8578 	    list_extend(l1, l2, item);
8579 
8580 	    copy_tv(&argvars[0], rettv);
8581 	}
8582     }
8583     else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
8584     {
8585 	dict_T		*d1, *d2;
8586 	dictitem_T	*di1;
8587 	char_u		*action;
8588 	int		i;
8589 	hashitem_T	*hi2;
8590 	int		todo;
8591 
8592 	d1 = argvars[0].vval.v_dict;
8593 	d2 = argvars[1].vval.v_dict;
8594 	if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
8595 		&& d2 != NULL)
8596 	{
8597 	    /* Check the third argument. */
8598 	    if (argvars[2].v_type != VAR_UNKNOWN)
8599 	    {
8600 		static char *(av[]) = {"keep", "force", "error"};
8601 
8602 		action = get_tv_string_chk(&argvars[2]);
8603 		if (action == NULL)
8604 		    return;		/* type error; errmsg already given */
8605 		for (i = 0; i < 3; ++i)
8606 		    if (STRCMP(action, av[i]) == 0)
8607 			break;
8608 		if (i == 3)
8609 		{
8610 		    EMSGN(_(e_invarg2), action);
8611 		    return;
8612 		}
8613 	    }
8614 	    else
8615 		action = (char_u *)"force";
8616 
8617 	    /* Go over all entries in the second dict and add them to the
8618 	     * first dict. */
8619 	    todo = d2->dv_hashtab.ht_used;
8620 	    for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
8621 	    {
8622 		if (!HASHITEM_EMPTY(hi2))
8623 		{
8624 		    --todo;
8625 		    di1 = dict_find(d1, hi2->hi_key, -1);
8626 		    if (di1 == NULL)
8627 		    {
8628 			di1 = dictitem_copy(HI2DI(hi2));
8629 			if (di1 != NULL && dict_add(d1, di1) == FAIL)
8630 			    dictitem_free(di1);
8631 		    }
8632 		    else if (*action == 'e')
8633 		    {
8634 			EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
8635 			break;
8636 		    }
8637 		    else if (*action == 'f')
8638 		    {
8639 			clear_tv(&di1->di_tv);
8640 			copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
8641 		    }
8642 		}
8643 	    }
8644 
8645 	    copy_tv(&argvars[0], rettv);
8646 	}
8647     }
8648     else
8649 	EMSG2(_(e_listdictarg), "extend()");
8650 }
8651 
8652 /*
8653  * "filereadable()" function
8654  */
8655     static void
8656 f_filereadable(argvars, rettv)
8657     typval_T	*argvars;
8658     typval_T	*rettv;
8659 {
8660     FILE	*fd;
8661     char_u	*p;
8662     int		n;
8663 
8664     p = get_tv_string(&argvars[0]);
8665     if (*p && !mch_isdir(p) && (fd = mch_fopen((char *)p, "r")) != NULL)
8666     {
8667 	n = TRUE;
8668 	fclose(fd);
8669     }
8670     else
8671 	n = FALSE;
8672 
8673     rettv->vval.v_number = n;
8674 }
8675 
8676 /*
8677  * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
8678  * rights to write into.
8679  */
8680     static void
8681 f_filewritable(argvars, rettv)
8682     typval_T	*argvars;
8683     typval_T	*rettv;
8684 {
8685     rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
8686 }
8687 
8688 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int dir));
8689 
8690     static void
8691 findfilendir(argvars, rettv, dir)
8692     typval_T	*argvars;
8693     typval_T	*rettv;
8694     int		dir;
8695 {
8696 #ifdef FEAT_SEARCHPATH
8697     char_u	*fname;
8698     char_u	*fresult = NULL;
8699     char_u	*path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
8700     char_u	*p;
8701     char_u	pathbuf[NUMBUFLEN];
8702     int		count = 1;
8703     int		first = TRUE;
8704 
8705     fname = get_tv_string(&argvars[0]);
8706 
8707     if (argvars[1].v_type != VAR_UNKNOWN)
8708     {
8709 	p = get_tv_string_buf_chk(&argvars[1], pathbuf);
8710 	if (p == NULL)
8711 	    count = -1;	    /* error */
8712 	else
8713 	{
8714 	    if (*p != NUL)
8715 		path = p;
8716 
8717 	    if (argvars[2].v_type != VAR_UNKNOWN)
8718 		count = get_tv_number_chk(&argvars[2], NULL); /* -1: error */
8719 	}
8720     }
8721 
8722     if (*fname != NUL && count >= 0)
8723     {
8724 	do
8725 	{
8726 	    vim_free(fresult);
8727 	    fresult = find_file_in_path_option(first ? fname : NULL,
8728 					       first ? (int)STRLEN(fname) : 0,
8729 					       0, first, path, dir, NULL);
8730 	    first = FALSE;
8731 	} while (--count > 0 && fresult != NULL);
8732     }
8733 
8734     rettv->vval.v_string = fresult;
8735 #else
8736     rettv->vval.v_string = NULL;
8737 #endif
8738     rettv->v_type = VAR_STRING;
8739 }
8740 
8741 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
8742 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
8743 
8744 /*
8745  * Implementation of map() and filter().
8746  */
8747     static void
8748 filter_map(argvars, rettv, map)
8749     typval_T	*argvars;
8750     typval_T	*rettv;
8751     int		map;
8752 {
8753     char_u	buf[NUMBUFLEN];
8754     char_u	*expr;
8755     listitem_T	*li, *nli;
8756     list_T	*l = NULL;
8757     dictitem_T	*di;
8758     hashtab_T	*ht;
8759     hashitem_T	*hi;
8760     dict_T	*d = NULL;
8761     typval_T	save_val;
8762     typval_T	save_key;
8763     int		rem;
8764     int		todo;
8765     char_u	*msg = map ? (char_u *)"map()" : (char_u *)"filter()";
8766 
8767 
8768     rettv->vval.v_number = 0;
8769     if (argvars[0].v_type == VAR_LIST)
8770     {
8771 	if ((l = argvars[0].vval.v_list) == NULL
8772 		|| (map && tv_check_lock(l->lv_lock, msg)))
8773 	    return;
8774     }
8775     else if (argvars[0].v_type == VAR_DICT)
8776     {
8777 	if ((d = argvars[0].vval.v_dict) == NULL
8778 		|| (map && tv_check_lock(d->dv_lock, msg)))
8779 	    return;
8780     }
8781     else
8782     {
8783 	EMSG2(_(e_listdictarg), msg);
8784 	return;
8785     }
8786 
8787     expr = get_tv_string_buf_chk(&argvars[1], buf);
8788     /* On type errors, the preceding call has already displayed an error
8789      * message.  Avoid a misleading error message for an empty string that
8790      * was not passed as argument. */
8791     if (expr != NULL)
8792     {
8793 	prepare_vimvar(VV_VAL, &save_val);
8794 	expr = skipwhite(expr);
8795 
8796 	if (argvars[0].v_type == VAR_DICT)
8797 	{
8798 	    prepare_vimvar(VV_KEY, &save_key);
8799 	    vimvars[VV_KEY].vv_type = VAR_STRING;
8800 
8801 	    ht = &d->dv_hashtab;
8802 	    hash_lock(ht);
8803 	    todo = ht->ht_used;
8804 	    for (hi = ht->ht_array; todo > 0; ++hi)
8805 	    {
8806 		if (!HASHITEM_EMPTY(hi))
8807 		{
8808 		    --todo;
8809 		    di = HI2DI(hi);
8810 		    if (tv_check_lock(di->di_tv.v_lock, msg))
8811 			break;
8812 		    vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
8813 		    if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL)
8814 			break;
8815 		    if (!map && rem)
8816 			dictitem_remove(d, di);
8817 		    clear_tv(&vimvars[VV_KEY].vv_tv);
8818 		}
8819 	    }
8820 	    hash_unlock(ht);
8821 
8822 	    restore_vimvar(VV_KEY, &save_key);
8823 	}
8824 	else
8825 	{
8826 	    for (li = l->lv_first; li != NULL; li = nli)
8827 	    {
8828 		if (tv_check_lock(li->li_tv.v_lock, msg))
8829 		    break;
8830 		nli = li->li_next;
8831 		if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL)
8832 		    break;
8833 		if (!map && rem)
8834 		    listitem_remove(l, li);
8835 	    }
8836 	}
8837 
8838 	restore_vimvar(VV_VAL, &save_val);
8839     }
8840 
8841     copy_tv(&argvars[0], rettv);
8842 }
8843 
8844     static int
8845 filter_map_one(tv, expr, map, remp)
8846     typval_T	*tv;
8847     char_u	*expr;
8848     int		map;
8849     int		*remp;
8850 {
8851     typval_T	rettv;
8852     char_u	*s;
8853 
8854     copy_tv(tv, &vimvars[VV_VAL].vv_tv);
8855     s = expr;
8856     if (eval1(&s, &rettv, TRUE) == FAIL)
8857 	return FAIL;
8858     if (*s != NUL)  /* check for trailing chars after expr */
8859     {
8860 	EMSG2(_(e_invexpr2), s);
8861 	return FAIL;
8862     }
8863     if (map)
8864     {
8865 	/* map(): replace the list item value */
8866 	clear_tv(tv);
8867 	rettv.v_lock = 0;
8868 	*tv = rettv;
8869     }
8870     else
8871     {
8872 	int	    error = FALSE;
8873 
8874 	/* filter(): when expr is zero remove the item */
8875 	*remp = (get_tv_number_chk(&rettv, &error) == 0);
8876 	clear_tv(&rettv);
8877 	/* On type error, nothing has been removed; return FAIL to stop the
8878 	 * loop.  The error message was given by get_tv_number_chk(). */
8879 	if (error)
8880 	    return FAIL;
8881     }
8882     clear_tv(&vimvars[VV_VAL].vv_tv);
8883     return OK;
8884 }
8885 
8886 /*
8887  * "filter()" function
8888  */
8889     static void
8890 f_filter(argvars, rettv)
8891     typval_T	*argvars;
8892     typval_T	*rettv;
8893 {
8894     filter_map(argvars, rettv, FALSE);
8895 }
8896 
8897 /*
8898  * "finddir({fname}[, {path}[, {count}]])" function
8899  */
8900     static void
8901 f_finddir(argvars, rettv)
8902     typval_T	*argvars;
8903     typval_T	*rettv;
8904 {
8905     findfilendir(argvars, rettv, TRUE);
8906 }
8907 
8908 /*
8909  * "findfile({fname}[, {path}[, {count}]])" function
8910  */
8911     static void
8912 f_findfile(argvars, rettv)
8913     typval_T	*argvars;
8914     typval_T	*rettv;
8915 {
8916     findfilendir(argvars, rettv, FALSE);
8917 }
8918 
8919 /*
8920  * "fnamemodify({fname}, {mods})" function
8921  */
8922     static void
8923 f_fnamemodify(argvars, rettv)
8924     typval_T	*argvars;
8925     typval_T	*rettv;
8926 {
8927     char_u	*fname;
8928     char_u	*mods;
8929     int		usedlen = 0;
8930     int		len;
8931     char_u	*fbuf = NULL;
8932     char_u	buf[NUMBUFLEN];
8933 
8934     fname = get_tv_string_chk(&argvars[0]);
8935     mods = get_tv_string_buf_chk(&argvars[1], buf);
8936     if (fname == NULL || mods == NULL)
8937 	fname = NULL;
8938     else
8939     {
8940 	len = (int)STRLEN(fname);
8941 	(void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
8942     }
8943 
8944     rettv->v_type = VAR_STRING;
8945     if (fname == NULL)
8946 	rettv->vval.v_string = NULL;
8947     else
8948 	rettv->vval.v_string = vim_strnsave(fname, len);
8949     vim_free(fbuf);
8950 }
8951 
8952 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
8953 
8954 /*
8955  * "foldclosed()" function
8956  */
8957     static void
8958 foldclosed_both(argvars, rettv, end)
8959     typval_T	*argvars;
8960     typval_T	*rettv;
8961     int		end;
8962 {
8963 #ifdef FEAT_FOLDING
8964     linenr_T	lnum;
8965     linenr_T	first, last;
8966 
8967     lnum = get_tv_lnum(argvars);
8968     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8969     {
8970 	if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
8971 	{
8972 	    if (end)
8973 		rettv->vval.v_number = (varnumber_T)last;
8974 	    else
8975 		rettv->vval.v_number = (varnumber_T)first;
8976 	    return;
8977 	}
8978     }
8979 #endif
8980     rettv->vval.v_number = -1;
8981 }
8982 
8983 /*
8984  * "foldclosed()" function
8985  */
8986     static void
8987 f_foldclosed(argvars, rettv)
8988     typval_T	*argvars;
8989     typval_T	*rettv;
8990 {
8991     foldclosed_both(argvars, rettv, FALSE);
8992 }
8993 
8994 /*
8995  * "foldclosedend()" function
8996  */
8997     static void
8998 f_foldclosedend(argvars, rettv)
8999     typval_T	*argvars;
9000     typval_T	*rettv;
9001 {
9002     foldclosed_both(argvars, rettv, TRUE);
9003 }
9004 
9005 /*
9006  * "foldlevel()" function
9007  */
9008     static void
9009 f_foldlevel(argvars, rettv)
9010     typval_T	*argvars;
9011     typval_T	*rettv;
9012 {
9013 #ifdef FEAT_FOLDING
9014     linenr_T	lnum;
9015 
9016     lnum = get_tv_lnum(argvars);
9017     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9018 	rettv->vval.v_number = foldLevel(lnum);
9019     else
9020 #endif
9021 	rettv->vval.v_number = 0;
9022 }
9023 
9024 /*
9025  * "foldtext()" function
9026  */
9027 /*ARGSUSED*/
9028     static void
9029 f_foldtext(argvars, rettv)
9030     typval_T	*argvars;
9031     typval_T	*rettv;
9032 {
9033 #ifdef FEAT_FOLDING
9034     linenr_T	lnum;
9035     char_u	*s;
9036     char_u	*r;
9037     int		len;
9038     char	*txt;
9039 #endif
9040 
9041     rettv->v_type = VAR_STRING;
9042     rettv->vval.v_string = NULL;
9043 #ifdef FEAT_FOLDING
9044     if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
9045 	    && (linenr_T)vimvars[VV_FOLDEND].vv_nr
9046 						 <= curbuf->b_ml.ml_line_count
9047 	    && vimvars[VV_FOLDDASHES].vv_str != NULL)
9048     {
9049 	/* Find first non-empty line in the fold. */
9050 	lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
9051 	while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9052 	{
9053 	    if (!linewhite(lnum))
9054 		break;
9055 	    ++lnum;
9056 	}
9057 
9058 	/* Find interesting text in this line. */
9059 	s = skipwhite(ml_get(lnum));
9060 	/* skip C comment-start */
9061 	if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
9062 	{
9063 	    s = skipwhite(s + 2);
9064 	    if (*skipwhite(s) == NUL
9065 			    && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9066 	    {
9067 		s = skipwhite(ml_get(lnum + 1));
9068 		if (*s == '*')
9069 		    s = skipwhite(s + 1);
9070 	    }
9071 	}
9072 	txt = _("+-%s%3ld lines: ");
9073 	r = alloc((unsigned)(STRLEN(txt)
9074 		    + STRLEN(vimvars[VV_FOLDDASHES].vv_str)    /* for %s */
9075 		    + 20				    /* for %3ld */
9076 		    + STRLEN(s)));			    /* concatenated */
9077 	if (r != NULL)
9078 	{
9079 	    sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
9080 		    (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
9081 				- (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
9082 	    len = (int)STRLEN(r);
9083 	    STRCAT(r, s);
9084 	    /* remove 'foldmarker' and 'commentstring' */
9085 	    foldtext_cleanup(r + len);
9086 	    rettv->vval.v_string = r;
9087 	}
9088     }
9089 #endif
9090 }
9091 
9092 /*
9093  * "foldtextresult(lnum)" function
9094  */
9095 /*ARGSUSED*/
9096     static void
9097 f_foldtextresult(argvars, rettv)
9098     typval_T	*argvars;
9099     typval_T	*rettv;
9100 {
9101 #ifdef FEAT_FOLDING
9102     linenr_T	lnum;
9103     char_u	*text;
9104     char_u	buf[51];
9105     foldinfo_T  foldinfo;
9106     int		fold_count;
9107 #endif
9108 
9109     rettv->v_type = VAR_STRING;
9110     rettv->vval.v_string = NULL;
9111 #ifdef FEAT_FOLDING
9112     lnum = get_tv_lnum(argvars);
9113     /* treat illegal types and illegal string values for {lnum} the same */
9114     if (lnum < 0)
9115 	lnum = 0;
9116     fold_count = foldedCount(curwin, lnum, &foldinfo);
9117     if (fold_count > 0)
9118     {
9119 	text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
9120 							      &foldinfo, buf);
9121 	if (text == buf)
9122 	    text = vim_strsave(text);
9123 	rettv->vval.v_string = text;
9124     }
9125 #endif
9126 }
9127 
9128 /*
9129  * "foreground()" function
9130  */
9131 /*ARGSUSED*/
9132     static void
9133 f_foreground(argvars, rettv)
9134     typval_T	*argvars;
9135     typval_T	*rettv;
9136 {
9137     rettv->vval.v_number = 0;
9138 #ifdef FEAT_GUI
9139     if (gui.in_use)
9140 	gui_mch_set_foreground();
9141 #else
9142 # ifdef WIN32
9143     win32_set_foreground();
9144 # endif
9145 #endif
9146 }
9147 
9148 /*
9149  * "function()" function
9150  */
9151 /*ARGSUSED*/
9152     static void
9153 f_function(argvars, rettv)
9154     typval_T	*argvars;
9155     typval_T	*rettv;
9156 {
9157     char_u	*s;
9158 
9159     rettv->vval.v_number = 0;
9160     s = get_tv_string(&argvars[0]);
9161     if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
9162 	EMSG2(_(e_invarg2), s);
9163     else if (!function_exists(s))
9164 	EMSG2(_("E700: Unknown function: %s"), s);
9165     else
9166     {
9167 	rettv->vval.v_string = vim_strsave(s);
9168 	rettv->v_type = VAR_FUNC;
9169     }
9170 }
9171 
9172 /*
9173  * "garbagecollect()" function
9174  */
9175 /*ARGSUSED*/
9176     static void
9177 f_garbagecollect(argvars, rettv)
9178     typval_T	*argvars;
9179     typval_T	*rettv;
9180 {
9181     garbage_collect();
9182 }
9183 
9184 /*
9185  * "get()" function
9186  */
9187     static void
9188 f_get(argvars, rettv)
9189     typval_T	*argvars;
9190     typval_T	*rettv;
9191 {
9192     listitem_T	*li;
9193     list_T	*l;
9194     dictitem_T	*di;
9195     dict_T	*d;
9196     typval_T	*tv = NULL;
9197 
9198     if (argvars[0].v_type == VAR_LIST)
9199     {
9200 	if ((l = argvars[0].vval.v_list) != NULL)
9201 	{
9202 	    int		error = FALSE;
9203 
9204 	    li = list_find(l, get_tv_number_chk(&argvars[1], &error));
9205 	    if (!error && li != NULL)
9206 		tv = &li->li_tv;
9207 	}
9208     }
9209     else if (argvars[0].v_type == VAR_DICT)
9210     {
9211 	if ((d = argvars[0].vval.v_dict) != NULL)
9212 	{
9213 	    di = dict_find(d, get_tv_string(&argvars[1]), -1);
9214 	    if (di != NULL)
9215 		tv = &di->di_tv;
9216 	}
9217     }
9218     else
9219 	EMSG2(_(e_listdictarg), "get()");
9220 
9221     if (tv == NULL)
9222     {
9223 	if (argvars[2].v_type == VAR_UNKNOWN)
9224 	    rettv->vval.v_number = 0;
9225 	else
9226 	    copy_tv(&argvars[2], rettv);
9227     }
9228     else
9229 	copy_tv(tv, rettv);
9230 }
9231 
9232 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
9233 
9234 /*
9235  * Get line or list of lines from buffer "buf" into "rettv".
9236  * Return a range (from start to end) of lines in rettv from the specified
9237  * buffer.
9238  * If 'retlist' is TRUE, then the lines are returned as a Vim List.
9239  */
9240     static void
9241 get_buffer_lines(buf, start, end, retlist, rettv)
9242     buf_T	*buf;
9243     linenr_T	start;
9244     linenr_T	end;
9245     int		retlist;
9246     typval_T	*rettv;
9247 {
9248     char_u	*p;
9249     list_T	*l = NULL;
9250 
9251     if (retlist)
9252     {
9253 	l = list_alloc();
9254 	if (l == NULL)
9255 	    return;
9256 
9257 	rettv->vval.v_list = l;
9258 	rettv->v_type = VAR_LIST;
9259 	++l->lv_refcount;
9260     }
9261     else
9262 	rettv->vval.v_number = 0;
9263 
9264     if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
9265 	return;
9266 
9267     if (!retlist)
9268     {
9269 	if (start >= 1 && start <= buf->b_ml.ml_line_count)
9270 	    p = ml_get_buf(buf, start, FALSE);
9271 	else
9272 	    p = (char_u *)"";
9273 
9274 	rettv->v_type = VAR_STRING;
9275 	rettv->vval.v_string = vim_strsave(p);
9276     }
9277     else
9278     {
9279 	if (end < start)
9280 	    return;
9281 
9282 	if (start < 1)
9283 	    start = 1;
9284 	if (end > buf->b_ml.ml_line_count)
9285 	    end = buf->b_ml.ml_line_count;
9286 	while (start <= end)
9287 	    if (list_append_string(l, ml_get_buf(buf, start++, FALSE), -1)
9288 								      == FAIL)
9289 		break;
9290     }
9291 }
9292 
9293 /*
9294  * "getbufline()" function
9295  */
9296     static void
9297 f_getbufline(argvars, rettv)
9298     typval_T	*argvars;
9299     typval_T	*rettv;
9300 {
9301     linenr_T	lnum;
9302     linenr_T	end;
9303     buf_T	*buf;
9304 
9305     (void)get_tv_number(&argvars[0]);	    /* issue errmsg if type error */
9306     ++emsg_off;
9307     buf = get_buf_tv(&argvars[0]);
9308     --emsg_off;
9309 
9310     lnum = get_tv_lnum_buf(&argvars[1], buf);
9311     if (argvars[2].v_type == VAR_UNKNOWN)
9312 	end = lnum;
9313     else
9314 	end = get_tv_lnum_buf(&argvars[2], buf);
9315 
9316     get_buffer_lines(buf, lnum, end, TRUE, rettv);
9317 }
9318 
9319 /*
9320  * "getbufvar()" function
9321  */
9322     static void
9323 f_getbufvar(argvars, rettv)
9324     typval_T	*argvars;
9325     typval_T	*rettv;
9326 {
9327     buf_T	*buf;
9328     buf_T	*save_curbuf;
9329     char_u	*varname;
9330     dictitem_T	*v;
9331 
9332     (void)get_tv_number(&argvars[0]);	    /* issue errmsg if type error */
9333     varname = get_tv_string_chk(&argvars[1]);
9334     ++emsg_off;
9335     buf = get_buf_tv(&argvars[0]);
9336 
9337     rettv->v_type = VAR_STRING;
9338     rettv->vval.v_string = NULL;
9339 
9340     if (buf != NULL && varname != NULL)
9341     {
9342 	if (*varname == '&')	/* buffer-local-option */
9343 	{
9344 	    /* set curbuf to be our buf, temporarily */
9345 	    save_curbuf = curbuf;
9346 	    curbuf = buf;
9347 
9348 	    get_option_tv(&varname, rettv, TRUE);
9349 
9350 	    /* restore previous notion of curbuf */
9351 	    curbuf = save_curbuf;
9352 	}
9353 	else
9354 	{
9355 	    if (*varname == NUL)
9356 		/* let getbufvar({nr}, "") return the "b:" dictionary.  The
9357 		 * scope prefix before the NUL byte is required by
9358 		 * find_var_in_ht(). */
9359 		varname = (char_u *)"b:" + 2;
9360 	    /* look up the variable */
9361 	    v = find_var_in_ht(&buf->b_vars.dv_hashtab, varname, FALSE);
9362 	    if (v != NULL)
9363 		copy_tv(&v->di_tv, rettv);
9364 	}
9365     }
9366 
9367     --emsg_off;
9368 }
9369 
9370 /*
9371  * "getchar()" function
9372  */
9373     static void
9374 f_getchar(argvars, rettv)
9375     typval_T	*argvars;
9376     typval_T	*rettv;
9377 {
9378     varnumber_T		n;
9379     int			error = FALSE;
9380 
9381     ++no_mapping;
9382     ++allow_keys;
9383     if (argvars[0].v_type == VAR_UNKNOWN)
9384 	/* getchar(): blocking wait. */
9385 	n = safe_vgetc();
9386     else if (get_tv_number_chk(&argvars[0], &error) == 1)
9387 	/* getchar(1): only check if char avail */
9388 	n = vpeekc();
9389     else if (error || vpeekc() == NUL)
9390 	/* illegal argument or getchar(0) and no char avail: return zero */
9391 	n = 0;
9392     else
9393 	/* getchar(0) and char avail: return char */
9394 	n = safe_vgetc();
9395     --no_mapping;
9396     --allow_keys;
9397 
9398     rettv->vval.v_number = n;
9399     if (IS_SPECIAL(n) || mod_mask != 0)
9400     {
9401 	char_u		temp[10];   /* modifier: 3, mbyte-char: 6, NUL: 1 */
9402 	int		i = 0;
9403 
9404 	/* Turn a special key into three bytes, plus modifier. */
9405 	if (mod_mask != 0)
9406 	{
9407 	    temp[i++] = K_SPECIAL;
9408 	    temp[i++] = KS_MODIFIER;
9409 	    temp[i++] = mod_mask;
9410 	}
9411 	if (IS_SPECIAL(n))
9412 	{
9413 	    temp[i++] = K_SPECIAL;
9414 	    temp[i++] = K_SECOND(n);
9415 	    temp[i++] = K_THIRD(n);
9416 	}
9417 #ifdef FEAT_MBYTE
9418 	else if (has_mbyte)
9419 	    i += (*mb_char2bytes)(n, temp + i);
9420 #endif
9421 	else
9422 	    temp[i++] = n;
9423 	temp[i++] = NUL;
9424 	rettv->v_type = VAR_STRING;
9425 	rettv->vval.v_string = vim_strsave(temp);
9426     }
9427 }
9428 
9429 /*
9430  * "getcharmod()" function
9431  */
9432 /*ARGSUSED*/
9433     static void
9434 f_getcharmod(argvars, rettv)
9435     typval_T	*argvars;
9436     typval_T	*rettv;
9437 {
9438     rettv->vval.v_number = mod_mask;
9439 }
9440 
9441 /*
9442  * "getcmdline()" function
9443  */
9444 /*ARGSUSED*/
9445     static void
9446 f_getcmdline(argvars, rettv)
9447     typval_T	*argvars;
9448     typval_T	*rettv;
9449 {
9450     rettv->v_type = VAR_STRING;
9451     rettv->vval.v_string = get_cmdline_str();
9452 }
9453 
9454 /*
9455  * "getcmdpos()" function
9456  */
9457 /*ARGSUSED*/
9458     static void
9459 f_getcmdpos(argvars, rettv)
9460     typval_T	*argvars;
9461     typval_T	*rettv;
9462 {
9463     rettv->vval.v_number = get_cmdline_pos() + 1;
9464 }
9465 
9466 /*
9467  * "getcmdtype()" function
9468  */
9469 /*ARGSUSED*/
9470     static void
9471 f_getcmdtype(argvars, rettv)
9472     typval_T	*argvars;
9473     typval_T	*rettv;
9474 {
9475     rettv->v_type = VAR_STRING;
9476     rettv->vval.v_string = alloc(2);
9477     if (rettv->vval.v_string != NULL)
9478     {
9479 	rettv->vval.v_string[0] = get_cmdline_type();
9480 	rettv->vval.v_string[1] = NUL;
9481     }
9482 }
9483 
9484 /*
9485  * "getcwd()" function
9486  */
9487 /*ARGSUSED*/
9488     static void
9489 f_getcwd(argvars, rettv)
9490     typval_T	*argvars;
9491     typval_T	*rettv;
9492 {
9493     char_u	cwd[MAXPATHL];
9494 
9495     rettv->v_type = VAR_STRING;
9496     if (mch_dirname(cwd, MAXPATHL) == FAIL)
9497 	rettv->vval.v_string = NULL;
9498     else
9499     {
9500 	rettv->vval.v_string = vim_strsave(cwd);
9501 #ifdef BACKSLASH_IN_FILENAME
9502 	if (rettv->vval.v_string != NULL)
9503 	    slash_adjust(rettv->vval.v_string);
9504 #endif
9505     }
9506 }
9507 
9508 /*
9509  * "getfontname()" function
9510  */
9511 /*ARGSUSED*/
9512     static void
9513 f_getfontname(argvars, rettv)
9514     typval_T	*argvars;
9515     typval_T	*rettv;
9516 {
9517     rettv->v_type = VAR_STRING;
9518     rettv->vval.v_string = NULL;
9519 #ifdef FEAT_GUI
9520     if (gui.in_use)
9521     {
9522 	GuiFont font;
9523 	char_u	*name = NULL;
9524 
9525 	if (argvars[0].v_type == VAR_UNKNOWN)
9526 	{
9527 	    /* Get the "Normal" font.  Either the name saved by
9528 	     * hl_set_font_name() or from the font ID. */
9529 	    font = gui.norm_font;
9530 	    name = hl_get_font_name();
9531 	}
9532 	else
9533 	{
9534 	    name = get_tv_string(&argvars[0]);
9535 	    if (STRCMP(name, "*") == 0)	    /* don't use font dialog */
9536 		return;
9537 	    font = gui_mch_get_font(name, FALSE);
9538 	    if (font == NOFONT)
9539 		return;	    /* Invalid font name, return empty string. */
9540 	}
9541 	rettv->vval.v_string = gui_mch_get_fontname(font, name);
9542 	if (argvars[0].v_type != VAR_UNKNOWN)
9543 	    gui_mch_free_font(font);
9544     }
9545 #endif
9546 }
9547 
9548 /*
9549  * "getfperm({fname})" function
9550  */
9551     static void
9552 f_getfperm(argvars, rettv)
9553     typval_T	*argvars;
9554     typval_T	*rettv;
9555 {
9556     char_u	*fname;
9557     struct stat st;
9558     char_u	*perm = NULL;
9559     char_u	flags[] = "rwx";
9560     int		i;
9561 
9562     fname = get_tv_string(&argvars[0]);
9563 
9564     rettv->v_type = VAR_STRING;
9565     if (mch_stat((char *)fname, &st) >= 0)
9566     {
9567 	perm = vim_strsave((char_u *)"---------");
9568 	if (perm != NULL)
9569 	{
9570 	    for (i = 0; i < 9; i++)
9571 	    {
9572 		if (st.st_mode & (1 << (8 - i)))
9573 		    perm[i] = flags[i % 3];
9574 	    }
9575 	}
9576     }
9577     rettv->vval.v_string = perm;
9578 }
9579 
9580 /*
9581  * "getfsize({fname})" function
9582  */
9583     static void
9584 f_getfsize(argvars, rettv)
9585     typval_T	*argvars;
9586     typval_T	*rettv;
9587 {
9588     char_u	*fname;
9589     struct stat	st;
9590 
9591     fname = get_tv_string(&argvars[0]);
9592 
9593     rettv->v_type = VAR_NUMBER;
9594 
9595     if (mch_stat((char *)fname, &st) >= 0)
9596     {
9597 	if (mch_isdir(fname))
9598 	    rettv->vval.v_number = 0;
9599 	else
9600 	    rettv->vval.v_number = (varnumber_T)st.st_size;
9601     }
9602     else
9603 	  rettv->vval.v_number = -1;
9604 }
9605 
9606 /*
9607  * "getftime({fname})" function
9608  */
9609     static void
9610 f_getftime(argvars, rettv)
9611     typval_T	*argvars;
9612     typval_T	*rettv;
9613 {
9614     char_u	*fname;
9615     struct stat	st;
9616 
9617     fname = get_tv_string(&argvars[0]);
9618 
9619     if (mch_stat((char *)fname, &st) >= 0)
9620 	rettv->vval.v_number = (varnumber_T)st.st_mtime;
9621     else
9622 	rettv->vval.v_number = -1;
9623 }
9624 
9625 /*
9626  * "getftype({fname})" function
9627  */
9628     static void
9629 f_getftype(argvars, rettv)
9630     typval_T	*argvars;
9631     typval_T	*rettv;
9632 {
9633     char_u	*fname;
9634     struct stat st;
9635     char_u	*type = NULL;
9636     char	*t;
9637 
9638     fname = get_tv_string(&argvars[0]);
9639 
9640     rettv->v_type = VAR_STRING;
9641     if (mch_lstat((char *)fname, &st) >= 0)
9642     {
9643 #ifdef S_ISREG
9644 	if (S_ISREG(st.st_mode))
9645 	    t = "file";
9646 	else if (S_ISDIR(st.st_mode))
9647 	    t = "dir";
9648 # ifdef S_ISLNK
9649 	else if (S_ISLNK(st.st_mode))
9650 	    t = "link";
9651 # endif
9652 # ifdef S_ISBLK
9653 	else if (S_ISBLK(st.st_mode))
9654 	    t = "bdev";
9655 # endif
9656 # ifdef S_ISCHR
9657 	else if (S_ISCHR(st.st_mode))
9658 	    t = "cdev";
9659 # endif
9660 # ifdef S_ISFIFO
9661 	else if (S_ISFIFO(st.st_mode))
9662 	    t = "fifo";
9663 # endif
9664 # ifdef S_ISSOCK
9665 	else if (S_ISSOCK(st.st_mode))
9666 	    t = "fifo";
9667 # endif
9668 	else
9669 	    t = "other";
9670 #else
9671 # ifdef S_IFMT
9672 	switch (st.st_mode & S_IFMT)
9673 	{
9674 	    case S_IFREG: t = "file"; break;
9675 	    case S_IFDIR: t = "dir"; break;
9676 #  ifdef S_IFLNK
9677 	    case S_IFLNK: t = "link"; break;
9678 #  endif
9679 #  ifdef S_IFBLK
9680 	    case S_IFBLK: t = "bdev"; break;
9681 #  endif
9682 #  ifdef S_IFCHR
9683 	    case S_IFCHR: t = "cdev"; break;
9684 #  endif
9685 #  ifdef S_IFIFO
9686 	    case S_IFIFO: t = "fifo"; break;
9687 #  endif
9688 #  ifdef S_IFSOCK
9689 	    case S_IFSOCK: t = "socket"; break;
9690 #  endif
9691 	    default: t = "other";
9692 	}
9693 # else
9694 	if (mch_isdir(fname))
9695 	    t = "dir";
9696 	else
9697 	    t = "file";
9698 # endif
9699 #endif
9700 	type = vim_strsave((char_u *)t);
9701     }
9702     rettv->vval.v_string = type;
9703 }
9704 
9705 /*
9706  * "getline(lnum, [end])" function
9707  */
9708     static void
9709 f_getline(argvars, rettv)
9710     typval_T	*argvars;
9711     typval_T	*rettv;
9712 {
9713     linenr_T	lnum;
9714     linenr_T	end;
9715     int		retlist;
9716 
9717     lnum = get_tv_lnum(argvars);
9718     if (argvars[1].v_type == VAR_UNKNOWN)
9719     {
9720 	end = 0;
9721 	retlist = FALSE;
9722     }
9723     else
9724     {
9725 	end = get_tv_lnum(&argvars[1]);
9726 	retlist = TRUE;
9727     }
9728 
9729     get_buffer_lines(curbuf, lnum, end, retlist, rettv);
9730 }
9731 
9732 /*
9733  * "getqflist()" function
9734  */
9735 /*ARGSUSED*/
9736     static void
9737 f_getqflist(argvars, rettv)
9738     typval_T	*argvars;
9739     typval_T	*rettv;
9740 {
9741 #ifdef FEAT_QUICKFIX
9742     list_T	*l;
9743 #endif
9744 
9745     rettv->vval.v_number = FALSE;
9746 #ifdef FEAT_QUICKFIX
9747     l = list_alloc();
9748     if (l != NULL)
9749     {
9750 	rettv->vval.v_list = l;
9751 	rettv->v_type = VAR_LIST;
9752 	++l->lv_refcount;
9753 	(void)get_errorlist(l);
9754     }
9755 #endif
9756 }
9757 
9758 /*
9759  * "getreg()" function
9760  */
9761     static void
9762 f_getreg(argvars, rettv)
9763     typval_T	*argvars;
9764     typval_T	*rettv;
9765 {
9766     char_u	*strregname;
9767     int		regname;
9768     int		arg2 = FALSE;
9769     int		error = FALSE;
9770 
9771     if (argvars[0].v_type != VAR_UNKNOWN)
9772     {
9773 	strregname = get_tv_string_chk(&argvars[0]);
9774 	error = strregname == NULL;
9775 	if (argvars[1].v_type != VAR_UNKNOWN)
9776 	    arg2 = get_tv_number_chk(&argvars[1], &error);
9777     }
9778     else
9779 	strregname = vimvars[VV_REG].vv_str;
9780     regname = (strregname == NULL ? '"' : *strregname);
9781     if (regname == 0)
9782 	regname = '"';
9783 
9784     rettv->v_type = VAR_STRING;
9785     rettv->vval.v_string = error ? NULL :
9786 				    get_reg_contents(regname, TRUE, arg2);
9787 }
9788 
9789 /*
9790  * "getregtype()" function
9791  */
9792     static void
9793 f_getregtype(argvars, rettv)
9794     typval_T	*argvars;
9795     typval_T	*rettv;
9796 {
9797     char_u	*strregname;
9798     int		regname;
9799     char_u	buf[NUMBUFLEN + 2];
9800     long	reglen = 0;
9801 
9802     if (argvars[0].v_type != VAR_UNKNOWN)
9803     {
9804 	strregname = get_tv_string_chk(&argvars[0]);
9805 	if (strregname == NULL)	    /* type error; errmsg already given */
9806 	{
9807 	    rettv->v_type = VAR_STRING;
9808 	    rettv->vval.v_string = NULL;
9809 	    return;
9810 	}
9811     }
9812     else
9813 	/* Default to v:register */
9814 	strregname = vimvars[VV_REG].vv_str;
9815 
9816     regname = (strregname == NULL ? '"' : *strregname);
9817     if (regname == 0)
9818 	regname = '"';
9819 
9820     buf[0] = NUL;
9821     buf[1] = NUL;
9822     switch (get_reg_type(regname, &reglen))
9823     {
9824 	case MLINE: buf[0] = 'V'; break;
9825 	case MCHAR: buf[0] = 'v'; break;
9826 #ifdef FEAT_VISUAL
9827 	case MBLOCK:
9828 		buf[0] = Ctrl_V;
9829 		sprintf((char *)buf + 1, "%ld", reglen + 1);
9830 		break;
9831 #endif
9832     }
9833     rettv->v_type = VAR_STRING;
9834     rettv->vval.v_string = vim_strsave(buf);
9835 }
9836 
9837 /*
9838  * "getwinposx()" function
9839  */
9840 /*ARGSUSED*/
9841     static void
9842 f_getwinposx(argvars, rettv)
9843     typval_T	*argvars;
9844     typval_T	*rettv;
9845 {
9846     rettv->vval.v_number = -1;
9847 #ifdef FEAT_GUI
9848     if (gui.in_use)
9849     {
9850 	int	    x, y;
9851 
9852 	if (gui_mch_get_winpos(&x, &y) == OK)
9853 	    rettv->vval.v_number = x;
9854     }
9855 #endif
9856 }
9857 
9858 /*
9859  * "getwinposy()" function
9860  */
9861 /*ARGSUSED*/
9862     static void
9863 f_getwinposy(argvars, rettv)
9864     typval_T	*argvars;
9865     typval_T	*rettv;
9866 {
9867     rettv->vval.v_number = -1;
9868 #ifdef FEAT_GUI
9869     if (gui.in_use)
9870     {
9871 	int	    x, y;
9872 
9873 	if (gui_mch_get_winpos(&x, &y) == OK)
9874 	    rettv->vval.v_number = y;
9875     }
9876 #endif
9877 }
9878 
9879 static win_T *find_win_by_nr __ARGS((typval_T *vp));
9880 
9881     static win_T *
9882 find_win_by_nr(vp)
9883     typval_T	*vp;
9884 {
9885 #ifdef FEAT_WINDOWS
9886     win_T	*wp;
9887 #endif
9888     int		nr;
9889 
9890     nr = get_tv_number_chk(vp, NULL);
9891 
9892 #ifdef FEAT_WINDOWS
9893     if (nr < 0)
9894 	return NULL;
9895     if (nr == 0)
9896 	return curwin;
9897 
9898     for (wp = firstwin; wp != NULL; wp = wp->w_next)
9899 	if (--nr <= 0)
9900 	    break;
9901     return wp;
9902 #else
9903     if (nr == 0 || nr == 1)
9904 	return curwin;
9905     return NULL;
9906 #endif
9907 }
9908 
9909 /*
9910  * "getwinvar()" function
9911  */
9912     static void
9913 f_getwinvar(argvars, rettv)
9914     typval_T	*argvars;
9915     typval_T	*rettv;
9916 {
9917     win_T	*win, *oldcurwin;
9918     char_u	*varname;
9919     dictitem_T	*v;
9920 
9921     win = find_win_by_nr(&argvars[0]);
9922     varname = get_tv_string_chk(&argvars[1]);
9923     ++emsg_off;
9924 
9925     rettv->v_type = VAR_STRING;
9926     rettv->vval.v_string = NULL;
9927 
9928     if (win != NULL && varname != NULL)
9929     {
9930 	if (*varname == '&')	/* window-local-option */
9931 	{
9932 	    /* Set curwin to be our win, temporarily.  Also set curbuf, so
9933 	     * that we can get buffer-local options. */
9934 	    oldcurwin = curwin;
9935 	    curwin = win;
9936 	    curbuf = win->w_buffer;
9937 
9938 	    get_option_tv(&varname, rettv, 1);
9939 
9940 	    /* restore previous notion of curwin */
9941 	    curwin = oldcurwin;
9942 	    curbuf = curwin->w_buffer;
9943 	}
9944 	else
9945 	{
9946 	    if (*varname == NUL)
9947 		/* let getwinvar({nr}, "") return the "w:" dictionary.  The
9948 		 * scope prefix before the NUL byte is required by
9949 		 * find_var_in_ht(). */
9950 		varname = (char_u *)"w:" + 2;
9951 	    /* look up the variable */
9952 	    v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
9953 	    if (v != NULL)
9954 		copy_tv(&v->di_tv, rettv);
9955 	}
9956     }
9957 
9958     --emsg_off;
9959 }
9960 
9961 /*
9962  * "glob()" function
9963  */
9964     static void
9965 f_glob(argvars, rettv)
9966     typval_T	*argvars;
9967     typval_T	*rettv;
9968 {
9969     expand_T	xpc;
9970 
9971     ExpandInit(&xpc);
9972     xpc.xp_context = EXPAND_FILES;
9973     rettv->v_type = VAR_STRING;
9974     rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
9975 				     NULL, WILD_USE_NL|WILD_SILENT, WILD_ALL);
9976     ExpandCleanup(&xpc);
9977 }
9978 
9979 /*
9980  * "globpath()" function
9981  */
9982     static void
9983 f_globpath(argvars, rettv)
9984     typval_T	*argvars;
9985     typval_T	*rettv;
9986 {
9987     char_u	buf1[NUMBUFLEN];
9988     char_u	*file = get_tv_string_buf_chk(&argvars[1], buf1);
9989 
9990     rettv->v_type = VAR_STRING;
9991     if (file == NULL)
9992 	rettv->vval.v_string = NULL;
9993     else
9994 	rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file);
9995 }
9996 
9997 /*
9998  * "has()" function
9999  */
10000     static void
10001 f_has(argvars, rettv)
10002     typval_T	*argvars;
10003     typval_T	*rettv;
10004 {
10005     int		i;
10006     char_u	*name;
10007     int		n = FALSE;
10008     static char	*(has_list[]) =
10009     {
10010 #ifdef AMIGA
10011 	"amiga",
10012 # ifdef FEAT_ARP
10013 	"arp",
10014 # endif
10015 #endif
10016 #ifdef __BEOS__
10017 	"beos",
10018 #endif
10019 #ifdef MSDOS
10020 # ifdef DJGPP
10021 	"dos32",
10022 # else
10023 	"dos16",
10024 # endif
10025 #endif
10026 #ifdef MACOS
10027 	"mac",
10028 #endif
10029 #if defined(MACOS_X_UNIX)
10030 	"macunix",
10031 #endif
10032 #ifdef OS2
10033 	"os2",
10034 #endif
10035 #ifdef __QNX__
10036 	"qnx",
10037 #endif
10038 #ifdef RISCOS
10039 	"riscos",
10040 #endif
10041 #ifdef UNIX
10042 	"unix",
10043 #endif
10044 #ifdef VMS
10045 	"vms",
10046 #endif
10047 #ifdef WIN16
10048 	"win16",
10049 #endif
10050 #ifdef WIN32
10051 	"win32",
10052 #endif
10053 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
10054 	"win32unix",
10055 #endif
10056 #ifdef WIN64
10057 	"win64",
10058 #endif
10059 #ifdef EBCDIC
10060 	"ebcdic",
10061 #endif
10062 #ifndef CASE_INSENSITIVE_FILENAME
10063 	"fname_case",
10064 #endif
10065 #ifdef FEAT_ARABIC
10066 	"arabic",
10067 #endif
10068 #ifdef FEAT_AUTOCMD
10069 	"autocmd",
10070 #endif
10071 #ifdef FEAT_BEVAL
10072 	"balloon_eval",
10073 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
10074 	"balloon_multiline",
10075 # endif
10076 #endif
10077 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
10078 	"builtin_terms",
10079 # ifdef ALL_BUILTIN_TCAPS
10080 	"all_builtin_terms",
10081 # endif
10082 #endif
10083 #ifdef FEAT_BYTEOFF
10084 	"byte_offset",
10085 #endif
10086 #ifdef FEAT_CINDENT
10087 	"cindent",
10088 #endif
10089 #ifdef FEAT_CLIENTSERVER
10090 	"clientserver",
10091 #endif
10092 #ifdef FEAT_CLIPBOARD
10093 	"clipboard",
10094 #endif
10095 #ifdef FEAT_CMDL_COMPL
10096 	"cmdline_compl",
10097 #endif
10098 #ifdef FEAT_CMDHIST
10099 	"cmdline_hist",
10100 #endif
10101 #ifdef FEAT_COMMENTS
10102 	"comments",
10103 #endif
10104 #ifdef FEAT_CRYPT
10105 	"cryptv",
10106 #endif
10107 #ifdef FEAT_CSCOPE
10108 	"cscope",
10109 #endif
10110 #ifdef CURSOR_SHAPE
10111 	"cursorshape",
10112 #endif
10113 #ifdef DEBUG
10114 	"debug",
10115 #endif
10116 #ifdef FEAT_CON_DIALOG
10117 	"dialog_con",
10118 #endif
10119 #ifdef FEAT_GUI_DIALOG
10120 	"dialog_gui",
10121 #endif
10122 #ifdef FEAT_DIFF
10123 	"diff",
10124 #endif
10125 #ifdef FEAT_DIGRAPHS
10126 	"digraphs",
10127 #endif
10128 #ifdef FEAT_DND
10129 	"dnd",
10130 #endif
10131 #ifdef FEAT_EMACS_TAGS
10132 	"emacs_tags",
10133 #endif
10134 	"eval",	    /* always present, of course! */
10135 #ifdef FEAT_EX_EXTRA
10136 	"ex_extra",
10137 #endif
10138 #ifdef FEAT_SEARCH_EXTRA
10139 	"extra_search",
10140 #endif
10141 #ifdef FEAT_FKMAP
10142 	"farsi",
10143 #endif
10144 #ifdef FEAT_SEARCHPATH
10145 	"file_in_path",
10146 #endif
10147 #if defined(UNIX) && !defined(USE_SYSTEM)
10148 	"filterpipe",
10149 #endif
10150 #ifdef FEAT_FIND_ID
10151 	"find_in_path",
10152 #endif
10153 #ifdef FEAT_FOLDING
10154 	"folding",
10155 #endif
10156 #ifdef FEAT_FOOTER
10157 	"footer",
10158 #endif
10159 #if !defined(USE_SYSTEM) && defined(UNIX)
10160 	"fork",
10161 #endif
10162 #ifdef FEAT_GETTEXT
10163 	"gettext",
10164 #endif
10165 #ifdef FEAT_GUI
10166 	"gui",
10167 #endif
10168 #ifdef FEAT_GUI_ATHENA
10169 # ifdef FEAT_GUI_NEXTAW
10170 	"gui_neXtaw",
10171 # else
10172 	"gui_athena",
10173 # endif
10174 #endif
10175 #ifdef FEAT_GUI_GTK
10176 	"gui_gtk",
10177 # ifdef HAVE_GTK2
10178 	"gui_gtk2",
10179 # endif
10180 #endif
10181 #ifdef FEAT_GUI_MAC
10182 	"gui_mac",
10183 #endif
10184 #ifdef FEAT_GUI_MOTIF
10185 	"gui_motif",
10186 #endif
10187 #ifdef FEAT_GUI_PHOTON
10188 	"gui_photon",
10189 #endif
10190 #ifdef FEAT_GUI_W16
10191 	"gui_win16",
10192 #endif
10193 #ifdef FEAT_GUI_W32
10194 	"gui_win32",
10195 #endif
10196 #ifdef FEAT_HANGULIN
10197 	"hangul_input",
10198 #endif
10199 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
10200 	"iconv",
10201 #endif
10202 #ifdef FEAT_INS_EXPAND
10203 	"insert_expand",
10204 #endif
10205 #ifdef FEAT_JUMPLIST
10206 	"jumplist",
10207 #endif
10208 #ifdef FEAT_KEYMAP
10209 	"keymap",
10210 #endif
10211 #ifdef FEAT_LANGMAP
10212 	"langmap",
10213 #endif
10214 #ifdef FEAT_LIBCALL
10215 	"libcall",
10216 #endif
10217 #ifdef FEAT_LINEBREAK
10218 	"linebreak",
10219 #endif
10220 #ifdef FEAT_LISP
10221 	"lispindent",
10222 #endif
10223 #ifdef FEAT_LISTCMDS
10224 	"listcmds",
10225 #endif
10226 #ifdef FEAT_LOCALMAP
10227 	"localmap",
10228 #endif
10229 #ifdef FEAT_MENU
10230 	"menu",
10231 #endif
10232 #ifdef FEAT_SESSION
10233 	"mksession",
10234 #endif
10235 #ifdef FEAT_MODIFY_FNAME
10236 	"modify_fname",
10237 #endif
10238 #ifdef FEAT_MOUSE
10239 	"mouse",
10240 #endif
10241 #ifdef FEAT_MOUSESHAPE
10242 	"mouseshape",
10243 #endif
10244 #if defined(UNIX) || defined(VMS)
10245 # ifdef FEAT_MOUSE_DEC
10246 	"mouse_dec",
10247 # endif
10248 # ifdef FEAT_MOUSE_GPM
10249 	"mouse_gpm",
10250 # endif
10251 # ifdef FEAT_MOUSE_JSB
10252 	"mouse_jsbterm",
10253 # endif
10254 # ifdef FEAT_MOUSE_NET
10255 	"mouse_netterm",
10256 # endif
10257 # ifdef FEAT_MOUSE_PTERM
10258 	"mouse_pterm",
10259 # endif
10260 # ifdef FEAT_MOUSE_XTERM
10261 	"mouse_xterm",
10262 # endif
10263 #endif
10264 #ifdef FEAT_MBYTE
10265 	"multi_byte",
10266 #endif
10267 #ifdef FEAT_MBYTE_IME
10268 	"multi_byte_ime",
10269 #endif
10270 #ifdef FEAT_MULTI_LANG
10271 	"multi_lang",
10272 #endif
10273 #ifdef FEAT_MZSCHEME
10274 #ifndef DYNAMIC_MZSCHEME
10275 	"mzscheme",
10276 #endif
10277 #endif
10278 #ifdef FEAT_OLE
10279 	"ole",
10280 #endif
10281 #ifdef FEAT_OSFILETYPE
10282 	"osfiletype",
10283 #endif
10284 #ifdef FEAT_PATH_EXTRA
10285 	"path_extra",
10286 #endif
10287 #ifdef FEAT_PERL
10288 #ifndef DYNAMIC_PERL
10289 	"perl",
10290 #endif
10291 #endif
10292 #ifdef FEAT_PYTHON
10293 #ifndef DYNAMIC_PYTHON
10294 	"python",
10295 #endif
10296 #endif
10297 #ifdef FEAT_POSTSCRIPT
10298 	"postscript",
10299 #endif
10300 #ifdef FEAT_PRINTER
10301 	"printer",
10302 #endif
10303 #ifdef FEAT_PROFILE
10304 	"profile",
10305 #endif
10306 #ifdef FEAT_QUICKFIX
10307 	"quickfix",
10308 #endif
10309 #ifdef FEAT_RIGHTLEFT
10310 	"rightleft",
10311 #endif
10312 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
10313 	"ruby",
10314 #endif
10315 #ifdef FEAT_SCROLLBIND
10316 	"scrollbind",
10317 #endif
10318 #ifdef FEAT_CMDL_INFO
10319 	"showcmd",
10320 	"cmdline_info",
10321 #endif
10322 #ifdef FEAT_SIGNS
10323 	"signs",
10324 #endif
10325 #ifdef FEAT_SMARTINDENT
10326 	"smartindent",
10327 #endif
10328 #ifdef FEAT_SNIFF
10329 	"sniff",
10330 #endif
10331 #ifdef FEAT_STL_OPT
10332 	"statusline",
10333 #endif
10334 #ifdef FEAT_SUN_WORKSHOP
10335 	"sun_workshop",
10336 #endif
10337 #ifdef FEAT_NETBEANS_INTG
10338 	"netbeans_intg",
10339 #endif
10340 #ifdef FEAT_SYN_HL
10341 	"spell",
10342 #endif
10343 #ifdef FEAT_SYN_HL
10344 	"syntax",
10345 #endif
10346 #if defined(USE_SYSTEM) || !defined(UNIX)
10347 	"system",
10348 #endif
10349 #ifdef FEAT_TAG_BINS
10350 	"tag_binary",
10351 #endif
10352 #ifdef FEAT_TAG_OLDSTATIC
10353 	"tag_old_static",
10354 #endif
10355 #ifdef FEAT_TAG_ANYWHITE
10356 	"tag_any_white",
10357 #endif
10358 #ifdef FEAT_TCL
10359 # ifndef DYNAMIC_TCL
10360 	"tcl",
10361 # endif
10362 #endif
10363 #ifdef TERMINFO
10364 	"terminfo",
10365 #endif
10366 #ifdef FEAT_TERMRESPONSE
10367 	"termresponse",
10368 #endif
10369 #ifdef FEAT_TEXTOBJ
10370 	"textobjects",
10371 #endif
10372 #ifdef HAVE_TGETENT
10373 	"tgetent",
10374 #endif
10375 #ifdef FEAT_TITLE
10376 	"title",
10377 #endif
10378 #ifdef FEAT_TOOLBAR
10379 	"toolbar",
10380 #endif
10381 #ifdef FEAT_USR_CMDS
10382 	"user-commands",    /* was accidentally included in 5.4 */
10383 	"user_commands",
10384 #endif
10385 #ifdef FEAT_VIMINFO
10386 	"viminfo",
10387 #endif
10388 #ifdef FEAT_VERTSPLIT
10389 	"vertsplit",
10390 #endif
10391 #ifdef FEAT_VIRTUALEDIT
10392 	"virtualedit",
10393 #endif
10394 #ifdef FEAT_VISUAL
10395 	"visual",
10396 #endif
10397 #ifdef FEAT_VISUALEXTRA
10398 	"visualextra",
10399 #endif
10400 #ifdef FEAT_VREPLACE
10401 	"vreplace",
10402 #endif
10403 #ifdef FEAT_WILDIGN
10404 	"wildignore",
10405 #endif
10406 #ifdef FEAT_WILDMENU
10407 	"wildmenu",
10408 #endif
10409 #ifdef FEAT_WINDOWS
10410 	"windows",
10411 #endif
10412 #ifdef FEAT_WAK
10413 	"winaltkeys",
10414 #endif
10415 #ifdef FEAT_WRITEBACKUP
10416 	"writebackup",
10417 #endif
10418 #ifdef FEAT_XIM
10419 	"xim",
10420 #endif
10421 #ifdef FEAT_XFONTSET
10422 	"xfontset",
10423 #endif
10424 #ifdef USE_XSMP
10425 	"xsmp",
10426 #endif
10427 #ifdef USE_XSMP_INTERACT
10428 	"xsmp_interact",
10429 #endif
10430 #ifdef FEAT_XCLIPBOARD
10431 	"xterm_clipboard",
10432 #endif
10433 #ifdef FEAT_XTERM_SAVE
10434 	"xterm_save",
10435 #endif
10436 #if defined(UNIX) && defined(FEAT_X11)
10437 	"X11",
10438 #endif
10439 	NULL
10440     };
10441 
10442     name = get_tv_string(&argvars[0]);
10443     for (i = 0; has_list[i] != NULL; ++i)
10444 	if (STRICMP(name, has_list[i]) == 0)
10445 	{
10446 	    n = TRUE;
10447 	    break;
10448 	}
10449 
10450     if (n == FALSE)
10451     {
10452 	if (STRNICMP(name, "patch", 5) == 0)
10453 	    n = has_patch(atoi((char *)name + 5));
10454 	else if (STRICMP(name, "vim_starting") == 0)
10455 	    n = (starting != 0);
10456 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
10457 	else if (STRICMP(name, "balloon_multiline") == 0)
10458 	    n = multiline_balloon_available();
10459 #endif
10460 #ifdef DYNAMIC_TCL
10461 	else if (STRICMP(name, "tcl") == 0)
10462 	    n = tcl_enabled(FALSE);
10463 #endif
10464 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
10465 	else if (STRICMP(name, "iconv") == 0)
10466 	    n = iconv_enabled(FALSE);
10467 #endif
10468 #ifdef DYNAMIC_MZSCHEME
10469 	else if (STRICMP(name, "mzscheme") == 0)
10470 	    n = mzscheme_enabled(FALSE);
10471 #endif
10472 #ifdef DYNAMIC_RUBY
10473 	else if (STRICMP(name, "ruby") == 0)
10474 	    n = ruby_enabled(FALSE);
10475 #endif
10476 #ifdef DYNAMIC_PYTHON
10477 	else if (STRICMP(name, "python") == 0)
10478 	    n = python_enabled(FALSE);
10479 #endif
10480 #ifdef DYNAMIC_PERL
10481 	else if (STRICMP(name, "perl") == 0)
10482 	    n = perl_enabled(FALSE);
10483 #endif
10484 #ifdef FEAT_GUI
10485 	else if (STRICMP(name, "gui_running") == 0)
10486 	    n = (gui.in_use || gui.starting);
10487 # ifdef FEAT_GUI_W32
10488 	else if (STRICMP(name, "gui_win32s") == 0)
10489 	    n = gui_is_win32s();
10490 # endif
10491 # ifdef FEAT_BROWSE
10492 	else if (STRICMP(name, "browse") == 0)
10493 	    n = gui.in_use;	/* gui_mch_browse() works when GUI is running */
10494 # endif
10495 #endif
10496 #ifdef FEAT_SYN_HL
10497 	else if (STRICMP(name, "syntax_items") == 0)
10498 	    n = syntax_present(curbuf);
10499 #endif
10500 #if defined(WIN3264)
10501 	else if (STRICMP(name, "win95") == 0)
10502 	    n = mch_windows95();
10503 #endif
10504 #ifdef FEAT_NETBEANS_INTG
10505 	else if (STRICMP(name, "netbeans_enabled") == 0)
10506 	    n = usingNetbeans;
10507 #endif
10508     }
10509 
10510     rettv->vval.v_number = n;
10511 }
10512 
10513 /*
10514  * "has_key()" function
10515  */
10516     static void
10517 f_has_key(argvars, rettv)
10518     typval_T	*argvars;
10519     typval_T	*rettv;
10520 {
10521     rettv->vval.v_number = 0;
10522     if (argvars[0].v_type != VAR_DICT)
10523     {
10524 	EMSG(_(e_dictreq));
10525 	return;
10526     }
10527     if (argvars[0].vval.v_dict == NULL)
10528 	return;
10529 
10530     rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
10531 				      get_tv_string(&argvars[1]), -1) != NULL;
10532 }
10533 
10534 /*
10535  * "hasmapto()" function
10536  */
10537     static void
10538 f_hasmapto(argvars, rettv)
10539     typval_T	*argvars;
10540     typval_T	*rettv;
10541 {
10542     char_u	*name;
10543     char_u	*mode;
10544     char_u	buf[NUMBUFLEN];
10545 
10546     name = get_tv_string(&argvars[0]);
10547     if (argvars[1].v_type == VAR_UNKNOWN)
10548 	mode = (char_u *)"nvo";
10549     else
10550 	mode = get_tv_string_buf(&argvars[1], buf);
10551 
10552     if (map_to_exists(name, mode))
10553 	rettv->vval.v_number = TRUE;
10554     else
10555 	rettv->vval.v_number = FALSE;
10556 }
10557 
10558 /*
10559  * "histadd()" function
10560  */
10561 /*ARGSUSED*/
10562     static void
10563 f_histadd(argvars, rettv)
10564     typval_T	*argvars;
10565     typval_T	*rettv;
10566 {
10567 #ifdef FEAT_CMDHIST
10568     int		histype;
10569     char_u	*str;
10570     char_u	buf[NUMBUFLEN];
10571 #endif
10572 
10573     rettv->vval.v_number = FALSE;
10574     if (check_restricted() || check_secure())
10575 	return;
10576 #ifdef FEAT_CMDHIST
10577     str = get_tv_string_chk(&argvars[0]);	/* NULL on type error */
10578     histype = str != NULL ? get_histtype(str) : -1;
10579     if (histype >= 0)
10580     {
10581 	str = get_tv_string_buf(&argvars[1], buf);
10582 	if (*str != NUL)
10583 	{
10584 	    add_to_history(histype, str, FALSE, NUL);
10585 	    rettv->vval.v_number = TRUE;
10586 	    return;
10587 	}
10588     }
10589 #endif
10590 }
10591 
10592 /*
10593  * "histdel()" function
10594  */
10595 /*ARGSUSED*/
10596     static void
10597 f_histdel(argvars, rettv)
10598     typval_T	*argvars;
10599     typval_T	*rettv;
10600 {
10601 #ifdef FEAT_CMDHIST
10602     int		n;
10603     char_u	buf[NUMBUFLEN];
10604     char_u	*str;
10605 
10606     str = get_tv_string_chk(&argvars[0]);	/* NULL on type error */
10607     if (str == NULL)
10608 	n = 0;
10609     else if (argvars[1].v_type == VAR_UNKNOWN)
10610 	/* only one argument: clear entire history */
10611 	n = clr_history(get_histtype(str));
10612     else if (argvars[1].v_type == VAR_NUMBER)
10613 	/* index given: remove that entry */
10614 	n = del_history_idx(get_histtype(str),
10615 					  (int)get_tv_number(&argvars[1]));
10616     else
10617 	/* string given: remove all matching entries */
10618 	n = del_history_entry(get_histtype(str),
10619 				      get_tv_string_buf(&argvars[1], buf));
10620     rettv->vval.v_number = n;
10621 #else
10622     rettv->vval.v_number = 0;
10623 #endif
10624 }
10625 
10626 /*
10627  * "histget()" function
10628  */
10629 /*ARGSUSED*/
10630     static void
10631 f_histget(argvars, rettv)
10632     typval_T	*argvars;
10633     typval_T	*rettv;
10634 {
10635 #ifdef FEAT_CMDHIST
10636     int		type;
10637     int		idx;
10638     char_u	*str;
10639 
10640     str = get_tv_string_chk(&argvars[0]);	/* NULL on type error */
10641     if (str == NULL)
10642 	rettv->vval.v_string = NULL;
10643     else
10644     {
10645 	type = get_histtype(str);
10646 	if (argvars[1].v_type == VAR_UNKNOWN)
10647 	    idx = get_history_idx(type);
10648 	else
10649 	    idx = (int)get_tv_number_chk(&argvars[1], NULL);
10650 						    /* -1 on type error */
10651 	rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
10652     }
10653 #else
10654     rettv->vval.v_string = NULL;
10655 #endif
10656     rettv->v_type = VAR_STRING;
10657 }
10658 
10659 /*
10660  * "histnr()" function
10661  */
10662 /*ARGSUSED*/
10663     static void
10664 f_histnr(argvars, rettv)
10665     typval_T	*argvars;
10666     typval_T	*rettv;
10667 {
10668     int		i;
10669 
10670 #ifdef FEAT_CMDHIST
10671     char_u	*history = get_tv_string_chk(&argvars[0]);
10672 
10673     i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
10674     if (i >= HIST_CMD && i < HIST_COUNT)
10675 	i = get_history_idx(i);
10676     else
10677 #endif
10678 	i = -1;
10679     rettv->vval.v_number = i;
10680 }
10681 
10682 /*
10683  * "highlightID(name)" function
10684  */
10685     static void
10686 f_hlID(argvars, rettv)
10687     typval_T	*argvars;
10688     typval_T	*rettv;
10689 {
10690     rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
10691 }
10692 
10693 /*
10694  * "highlight_exists()" function
10695  */
10696     static void
10697 f_hlexists(argvars, rettv)
10698     typval_T	*argvars;
10699     typval_T	*rettv;
10700 {
10701     rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
10702 }
10703 
10704 /*
10705  * "hostname()" function
10706  */
10707 /*ARGSUSED*/
10708     static void
10709 f_hostname(argvars, rettv)
10710     typval_T	*argvars;
10711     typval_T	*rettv;
10712 {
10713     char_u hostname[256];
10714 
10715     mch_get_host_name(hostname, 256);
10716     rettv->v_type = VAR_STRING;
10717     rettv->vval.v_string = vim_strsave(hostname);
10718 }
10719 
10720 /*
10721  * iconv() function
10722  */
10723 /*ARGSUSED*/
10724     static void
10725 f_iconv(argvars, rettv)
10726     typval_T	*argvars;
10727     typval_T	*rettv;
10728 {
10729 #ifdef FEAT_MBYTE
10730     char_u	buf1[NUMBUFLEN];
10731     char_u	buf2[NUMBUFLEN];
10732     char_u	*from, *to, *str;
10733     vimconv_T	vimconv;
10734 #endif
10735 
10736     rettv->v_type = VAR_STRING;
10737     rettv->vval.v_string = NULL;
10738 
10739 #ifdef FEAT_MBYTE
10740     str = get_tv_string(&argvars[0]);
10741     from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
10742     to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
10743     vimconv.vc_type = CONV_NONE;
10744     convert_setup(&vimconv, from, to);
10745 
10746     /* If the encodings are equal, no conversion needed. */
10747     if (vimconv.vc_type == CONV_NONE)
10748 	rettv->vval.v_string = vim_strsave(str);
10749     else
10750 	rettv->vval.v_string = string_convert(&vimconv, str, NULL);
10751 
10752     convert_setup(&vimconv, NULL, NULL);
10753     vim_free(from);
10754     vim_free(to);
10755 #endif
10756 }
10757 
10758 /*
10759  * "indent()" function
10760  */
10761     static void
10762 f_indent(argvars, rettv)
10763     typval_T	*argvars;
10764     typval_T	*rettv;
10765 {
10766     linenr_T	lnum;
10767 
10768     lnum = get_tv_lnum(argvars);
10769     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10770 	rettv->vval.v_number = get_indent_lnum(lnum);
10771     else
10772 	rettv->vval.v_number = -1;
10773 }
10774 
10775 /*
10776  * "index()" function
10777  */
10778     static void
10779 f_index(argvars, rettv)
10780     typval_T	*argvars;
10781     typval_T	*rettv;
10782 {
10783     list_T	*l;
10784     listitem_T	*item;
10785     long	idx = 0;
10786     int		ic = FALSE;
10787 
10788     rettv->vval.v_number = -1;
10789     if (argvars[0].v_type != VAR_LIST)
10790     {
10791 	EMSG(_(e_listreq));
10792 	return;
10793     }
10794     l = argvars[0].vval.v_list;
10795     if (l != NULL)
10796     {
10797 	item = l->lv_first;
10798 	if (argvars[2].v_type != VAR_UNKNOWN)
10799 	{
10800 	    int		error = FALSE;
10801 
10802 	    /* Start at specified item.  Use the cached index that list_find()
10803 	     * sets, so that a negative number also works. */
10804 	    item = list_find(l, get_tv_number_chk(&argvars[2], &error));
10805 	    idx = l->lv_idx;
10806 	    if (argvars[3].v_type != VAR_UNKNOWN)
10807 		ic = get_tv_number_chk(&argvars[3], &error);
10808 	    if (error)
10809 		item = NULL;
10810 	}
10811 
10812 	for ( ; item != NULL; item = item->li_next, ++idx)
10813 	    if (tv_equal(&item->li_tv, &argvars[1], ic))
10814 	    {
10815 		rettv->vval.v_number = idx;
10816 		break;
10817 	    }
10818     }
10819 }
10820 
10821 static int inputsecret_flag = 0;
10822 
10823 /*
10824  * "input()" function
10825  *     Also handles inputsecret() when inputsecret is set.
10826  */
10827     static void
10828 f_input(argvars, rettv)
10829     typval_T	*argvars;
10830     typval_T	*rettv;
10831 {
10832     char_u	*prompt = get_tv_string_chk(&argvars[0]);
10833     char_u	*p = NULL;
10834     int		c;
10835     char_u	buf[NUMBUFLEN];
10836     int		cmd_silent_save = cmd_silent;
10837     char_u	*defstr = (char_u *)"";
10838     int		xp_type = EXPAND_NOTHING;
10839     char_u	*xp_arg = NULL;
10840 
10841     rettv->v_type = VAR_STRING;
10842 
10843 #ifdef NO_CONSOLE_INPUT
10844     /* While starting up, there is no place to enter text. */
10845     if (no_console_input())
10846     {
10847 	rettv->vval.v_string = NULL;
10848 	return;
10849     }
10850 #endif
10851 
10852     cmd_silent = FALSE;		/* Want to see the prompt. */
10853     if (prompt != NULL)
10854     {
10855 	/* Only the part of the message after the last NL is considered as
10856 	 * prompt for the command line */
10857 	p = vim_strrchr(prompt, '\n');
10858 	if (p == NULL)
10859 	    p = prompt;
10860 	else
10861 	{
10862 	    ++p;
10863 	    c = *p;
10864 	    *p = NUL;
10865 	    msg_start();
10866 	    msg_clr_eos();
10867 	    msg_puts_attr(prompt, echo_attr);
10868 	    msg_didout = FALSE;
10869 	    msg_starthere();
10870 	    *p = c;
10871 	}
10872 	cmdline_row = msg_row;
10873 
10874 	if (argvars[1].v_type != VAR_UNKNOWN)
10875 	{
10876 	    defstr = get_tv_string_buf_chk(&argvars[1], buf);
10877 	    if (defstr != NULL)
10878 		stuffReadbuffSpec(defstr);
10879 
10880 	    if (argvars[2].v_type != VAR_UNKNOWN)
10881 	    {
10882 		char_u	*xp_name;
10883 		int		xp_namelen;
10884 		long	argt;
10885 
10886 		rettv->vval.v_string = NULL;
10887 
10888 		xp_name = get_tv_string_buf_chk(&argvars[2], buf);
10889 		if (xp_name == NULL)
10890 		    return;
10891 
10892 		xp_namelen = STRLEN(xp_name);
10893 
10894 		if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
10895 							     &xp_arg) == FAIL)
10896 		    return;
10897 	    }
10898 	}
10899 
10900 	if (defstr != NULL)
10901 	    rettv->vval.v_string =
10902 		getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
10903 				  xp_type, xp_arg);
10904 
10905 	vim_free(xp_arg);
10906 
10907 	/* since the user typed this, no need to wait for return */
10908 	need_wait_return = FALSE;
10909 	msg_didout = FALSE;
10910     }
10911     cmd_silent = cmd_silent_save;
10912 }
10913 
10914 /*
10915  * "inputdialog()" function
10916  */
10917     static void
10918 f_inputdialog(argvars, rettv)
10919     typval_T	*argvars;
10920     typval_T	*rettv;
10921 {
10922 #if defined(FEAT_GUI_TEXTDIALOG)
10923     /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
10924     if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
10925     {
10926 	char_u	*message;
10927 	char_u	buf[NUMBUFLEN];
10928 	char_u	*defstr = (char_u *)"";
10929 
10930 	message = get_tv_string_chk(&argvars[0]);
10931 	if (argvars[1].v_type != VAR_UNKNOWN
10932 	    && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
10933 	    vim_strncpy(IObuff, defstr, IOSIZE - 1);
10934 	else
10935 	    IObuff[0] = NUL;
10936 	if (message != NULL && defstr != NULL
10937 		&& do_dialog(VIM_QUESTION, NULL, message,
10938 				(char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
10939 	    rettv->vval.v_string = vim_strsave(IObuff);
10940 	else
10941 	{
10942 	    if (message != NULL && defstr != NULL
10943 					&& argvars[1].v_type != VAR_UNKNOWN
10944 					&& argvars[2].v_type != VAR_UNKNOWN)
10945 		rettv->vval.v_string = vim_strsave(
10946 				      get_tv_string_buf(&argvars[2], buf));
10947 	    else
10948 		rettv->vval.v_string = NULL;
10949 	}
10950 	rettv->v_type = VAR_STRING;
10951     }
10952     else
10953 #endif
10954 	f_input(argvars, rettv);
10955 }
10956 
10957 /*
10958  * "inputlist()" function
10959  */
10960     static void
10961 f_inputlist(argvars, rettv)
10962     typval_T	*argvars;
10963     typval_T	*rettv;
10964 {
10965     listitem_T	*li;
10966     int		selected;
10967     int		mouse_used;
10968 
10969     rettv->vval.v_number = 0;
10970 #ifdef NO_CONSOLE_INPUT
10971     /* While starting up, there is no place to enter text. */
10972     if (no_console_input())
10973 	return;
10974 #endif
10975     if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
10976     {
10977 	EMSG2(_(e_listarg), "inputlist()");
10978 	return;
10979     }
10980 
10981     msg_start();
10982     lines_left = Rows;	/* avoid more prompt */
10983     msg_scroll = TRUE;
10984     msg_clr_eos();
10985 
10986     for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
10987     {
10988 	msg_puts(get_tv_string(&li->li_tv));
10989 	msg_putchar('\n');
10990     }
10991 
10992     /* Ask for choice. */
10993     selected = prompt_for_number(&mouse_used);
10994     if (mouse_used)
10995 	selected -= lines_left;
10996 
10997     rettv->vval.v_number = selected;
10998 }
10999 
11000 
11001 static garray_T	    ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
11002 
11003 /*
11004  * "inputrestore()" function
11005  */
11006 /*ARGSUSED*/
11007     static void
11008 f_inputrestore(argvars, rettv)
11009     typval_T	*argvars;
11010     typval_T	*rettv;
11011 {
11012     if (ga_userinput.ga_len > 0)
11013     {
11014 	--ga_userinput.ga_len;
11015 	restore_typeahead((tasave_T *)(ga_userinput.ga_data)
11016 						       + ga_userinput.ga_len);
11017 	rettv->vval.v_number = 0; /* OK */
11018     }
11019     else if (p_verbose > 1)
11020     {
11021 	verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
11022 	rettv->vval.v_number = 1; /* Failed */
11023     }
11024 }
11025 
11026 /*
11027  * "inputsave()" function
11028  */
11029 /*ARGSUSED*/
11030     static void
11031 f_inputsave(argvars, rettv)
11032     typval_T	*argvars;
11033     typval_T	*rettv;
11034 {
11035     /* Add an entry to the stack of typehead storage. */
11036     if (ga_grow(&ga_userinput, 1) == OK)
11037     {
11038 	save_typeahead((tasave_T *)(ga_userinput.ga_data)
11039 						       + ga_userinput.ga_len);
11040 	++ga_userinput.ga_len;
11041 	rettv->vval.v_number = 0; /* OK */
11042     }
11043     else
11044 	rettv->vval.v_number = 1; /* Failed */
11045 }
11046 
11047 /*
11048  * "inputsecret()" function
11049  */
11050     static void
11051 f_inputsecret(argvars, rettv)
11052     typval_T	*argvars;
11053     typval_T	*rettv;
11054 {
11055     ++cmdline_star;
11056     ++inputsecret_flag;
11057     f_input(argvars, rettv);
11058     --cmdline_star;
11059     --inputsecret_flag;
11060 }
11061 
11062 /*
11063  * "insert()" function
11064  */
11065     static void
11066 f_insert(argvars, rettv)
11067     typval_T	*argvars;
11068     typval_T	*rettv;
11069 {
11070     long	before = 0;
11071     listitem_T	*item;
11072     list_T	*l;
11073     int		error = FALSE;
11074 
11075     rettv->vval.v_number = 0;
11076     if (argvars[0].v_type != VAR_LIST)
11077 	EMSG2(_(e_listarg), "insert()");
11078     else if ((l = argvars[0].vval.v_list) != NULL
11079 	    && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
11080     {
11081 	if (argvars[2].v_type != VAR_UNKNOWN)
11082 	    before = get_tv_number_chk(&argvars[2], &error);
11083 	if (error)
11084 	    return;		/* type error; errmsg already given */
11085 
11086 	if (before == l->lv_len)
11087 	    item = NULL;
11088 	else
11089 	{
11090 	    item = list_find(l, before);
11091 	    if (item == NULL)
11092 	    {
11093 		EMSGN(_(e_listidx), before);
11094 		l = NULL;
11095 	    }
11096 	}
11097 	if (l != NULL)
11098 	{
11099 	    list_insert_tv(l, &argvars[1], item);
11100 	    copy_tv(&argvars[0], rettv);
11101 	}
11102     }
11103 }
11104 
11105 /*
11106  * "isdirectory()" function
11107  */
11108     static void
11109 f_isdirectory(argvars, rettv)
11110     typval_T	*argvars;
11111     typval_T	*rettv;
11112 {
11113     rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
11114 }
11115 
11116 /*
11117  * "islocked()" function
11118  */
11119     static void
11120 f_islocked(argvars, rettv)
11121     typval_T	*argvars;
11122     typval_T	*rettv;
11123 {
11124     lval_T	lv;
11125     char_u	*end;
11126     dictitem_T	*di;
11127 
11128     rettv->vval.v_number = -1;
11129     end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
11130 							     FNE_CHECK_START);
11131     if (end != NULL && lv.ll_name != NULL)
11132     {
11133 	if (*end != NUL)
11134 	    EMSG(_(e_trailing));
11135 	else
11136 	{
11137 	    if (lv.ll_tv == NULL)
11138 	    {
11139 		if (check_changedtick(lv.ll_name))
11140 		    rettv->vval.v_number = 1;	    /* always locked */
11141 		else
11142 		{
11143 		    di = find_var(lv.ll_name, NULL);
11144 		    if (di != NULL)
11145 		    {
11146 			/* Consider a variable locked when:
11147 			 * 1. the variable itself is locked
11148 			 * 2. the value of the variable is locked.
11149 			 * 3. the List or Dict value is locked.
11150 			 */
11151 			rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
11152 						  || tv_islocked(&di->di_tv));
11153 		    }
11154 		}
11155 	    }
11156 	    else if (lv.ll_range)
11157 		EMSG(_("E745: Range not allowed"));
11158 	    else if (lv.ll_newkey != NULL)
11159 		EMSG2(_(e_dictkey), lv.ll_newkey);
11160 	    else if (lv.ll_list != NULL)
11161 		/* List item. */
11162 		rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
11163 	    else
11164 		/* Dictionary item. */
11165 		rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
11166 	}
11167     }
11168 
11169     clear_lval(&lv);
11170 }
11171 
11172 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
11173 
11174 /*
11175  * Turn a dict into a list:
11176  * "what" == 0: list of keys
11177  * "what" == 1: list of values
11178  * "what" == 2: list of items
11179  */
11180     static void
11181 dict_list(argvars, rettv, what)
11182     typval_T	*argvars;
11183     typval_T	*rettv;
11184     int		what;
11185 {
11186     list_T	*l;
11187     list_T	*l2;
11188     dictitem_T	*di;
11189     hashitem_T	*hi;
11190     listitem_T	*li;
11191     listitem_T	*li2;
11192     dict_T	*d;
11193     int		todo;
11194 
11195     rettv->vval.v_number = 0;
11196     if (argvars[0].v_type != VAR_DICT)
11197     {
11198 	EMSG(_(e_dictreq));
11199 	return;
11200     }
11201     if ((d = argvars[0].vval.v_dict) == NULL)
11202 	return;
11203 
11204     l = list_alloc();
11205     if (l == NULL)
11206 	return;
11207     rettv->v_type = VAR_LIST;
11208     rettv->vval.v_list = l;
11209     ++l->lv_refcount;
11210 
11211     todo = d->dv_hashtab.ht_used;
11212     for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
11213     {
11214 	if (!HASHITEM_EMPTY(hi))
11215 	{
11216 	    --todo;
11217 	    di = HI2DI(hi);
11218 
11219 	    li = listitem_alloc();
11220 	    if (li == NULL)
11221 		break;
11222 	    list_append(l, li);
11223 
11224 	    if (what == 0)
11225 	    {
11226 		/* keys() */
11227 		li->li_tv.v_type = VAR_STRING;
11228 		li->li_tv.v_lock = 0;
11229 		li->li_tv.vval.v_string = vim_strsave(di->di_key);
11230 	    }
11231 	    else if (what == 1)
11232 	    {
11233 		/* values() */
11234 		copy_tv(&di->di_tv, &li->li_tv);
11235 	    }
11236 	    else
11237 	    {
11238 		/* items() */
11239 		l2 = list_alloc();
11240 		li->li_tv.v_type = VAR_LIST;
11241 		li->li_tv.v_lock = 0;
11242 		li->li_tv.vval.v_list = l2;
11243 		if (l2 == NULL)
11244 		    break;
11245 		++l2->lv_refcount;
11246 
11247 		li2 = listitem_alloc();
11248 		if (li2 == NULL)
11249 		    break;
11250 		list_append(l2, li2);
11251 		li2->li_tv.v_type = VAR_STRING;
11252 		li2->li_tv.v_lock = 0;
11253 		li2->li_tv.vval.v_string = vim_strsave(di->di_key);
11254 
11255 		li2 = listitem_alloc();
11256 		if (li2 == NULL)
11257 		    break;
11258 		list_append(l2, li2);
11259 		copy_tv(&di->di_tv, &li2->li_tv);
11260 	    }
11261 	}
11262     }
11263 }
11264 
11265 /*
11266  * "items(dict)" function
11267  */
11268     static void
11269 f_items(argvars, rettv)
11270     typval_T	*argvars;
11271     typval_T	*rettv;
11272 {
11273     dict_list(argvars, rettv, 2);
11274 }
11275 
11276 /*
11277  * "join()" function
11278  */
11279     static void
11280 f_join(argvars, rettv)
11281     typval_T	*argvars;
11282     typval_T	*rettv;
11283 {
11284     garray_T	ga;
11285     char_u	*sep;
11286 
11287     rettv->vval.v_number = 0;
11288     if (argvars[0].v_type != VAR_LIST)
11289     {
11290 	EMSG(_(e_listreq));
11291 	return;
11292     }
11293     if (argvars[0].vval.v_list == NULL)
11294 	return;
11295     if (argvars[1].v_type == VAR_UNKNOWN)
11296 	sep = (char_u *)" ";
11297     else
11298 	sep = get_tv_string_chk(&argvars[1]);
11299 
11300     rettv->v_type = VAR_STRING;
11301 
11302     if (sep != NULL)
11303     {
11304 	ga_init2(&ga, (int)sizeof(char), 80);
11305 	list_join(&ga, argvars[0].vval.v_list, sep, TRUE);
11306 	ga_append(&ga, NUL);
11307 	rettv->vval.v_string = (char_u *)ga.ga_data;
11308     }
11309     else
11310 	rettv->vval.v_string = NULL;
11311 }
11312 
11313 /*
11314  * "keys()" function
11315  */
11316     static void
11317 f_keys(argvars, rettv)
11318     typval_T	*argvars;
11319     typval_T	*rettv;
11320 {
11321     dict_list(argvars, rettv, 0);
11322 }
11323 
11324 /*
11325  * "last_buffer_nr()" function.
11326  */
11327 /*ARGSUSED*/
11328     static void
11329 f_last_buffer_nr(argvars, rettv)
11330     typval_T	*argvars;
11331     typval_T	*rettv;
11332 {
11333     int		n = 0;
11334     buf_T	*buf;
11335 
11336     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
11337 	if (n < buf->b_fnum)
11338 	    n = buf->b_fnum;
11339 
11340     rettv->vval.v_number = n;
11341 }
11342 
11343 /*
11344  * "len()" function
11345  */
11346     static void
11347 f_len(argvars, rettv)
11348     typval_T	*argvars;
11349     typval_T	*rettv;
11350 {
11351     switch (argvars[0].v_type)
11352     {
11353 	case VAR_STRING:
11354 	case VAR_NUMBER:
11355 	    rettv->vval.v_number = (varnumber_T)STRLEN(
11356 					       get_tv_string(&argvars[0]));
11357 	    break;
11358 	case VAR_LIST:
11359 	    rettv->vval.v_number = list_len(argvars[0].vval.v_list);
11360 	    break;
11361 	case VAR_DICT:
11362 	    rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
11363 	    break;
11364 	default:
11365 	    EMSG(_("E701: Invalid type for len()"));
11366 	    break;
11367     }
11368 }
11369 
11370 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
11371 
11372     static void
11373 libcall_common(argvars, rettv, type)
11374     typval_T	*argvars;
11375     typval_T	*rettv;
11376     int		type;
11377 {
11378 #ifdef FEAT_LIBCALL
11379     char_u		*string_in;
11380     char_u		**string_result;
11381     int			nr_result;
11382 #endif
11383 
11384     rettv->v_type = type;
11385     if (type == VAR_NUMBER)
11386 	rettv->vval.v_number = 0;
11387     else
11388 	rettv->vval.v_string = NULL;
11389 
11390     if (check_restricted() || check_secure())
11391 	return;
11392 
11393 #ifdef FEAT_LIBCALL
11394     /* The first two args must be strings, otherwise its meaningless */
11395     if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
11396     {
11397 	string_in = NULL;
11398 	if (argvars[2].v_type == VAR_STRING)
11399 	    string_in = argvars[2].vval.v_string;
11400 	if (type == VAR_NUMBER)
11401 	    string_result = NULL;
11402 	else
11403 	    string_result = &rettv->vval.v_string;
11404 	if (mch_libcall(argvars[0].vval.v_string,
11405 			     argvars[1].vval.v_string,
11406 			     string_in,
11407 			     argvars[2].vval.v_number,
11408 			     string_result,
11409 			     &nr_result) == OK
11410 		&& type == VAR_NUMBER)
11411 	    rettv->vval.v_number = nr_result;
11412     }
11413 #endif
11414 }
11415 
11416 /*
11417  * "libcall()" function
11418  */
11419     static void
11420 f_libcall(argvars, rettv)
11421     typval_T	*argvars;
11422     typval_T	*rettv;
11423 {
11424     libcall_common(argvars, rettv, VAR_STRING);
11425 }
11426 
11427 /*
11428  * "libcallnr()" function
11429  */
11430     static void
11431 f_libcallnr(argvars, rettv)
11432     typval_T	*argvars;
11433     typval_T	*rettv;
11434 {
11435     libcall_common(argvars, rettv, VAR_NUMBER);
11436 }
11437 
11438 /*
11439  * "line(string)" function
11440  */
11441     static void
11442 f_line(argvars, rettv)
11443     typval_T	*argvars;
11444     typval_T	*rettv;
11445 {
11446     linenr_T	lnum = 0;
11447     pos_T	*fp;
11448 
11449     fp = var2fpos(&argvars[0], TRUE);
11450     if (fp != NULL)
11451 	lnum = fp->lnum;
11452     rettv->vval.v_number = lnum;
11453 }
11454 
11455 /*
11456  * "line2byte(lnum)" function
11457  */
11458 /*ARGSUSED*/
11459     static void
11460 f_line2byte(argvars, rettv)
11461     typval_T	*argvars;
11462     typval_T	*rettv;
11463 {
11464 #ifndef FEAT_BYTEOFF
11465     rettv->vval.v_number = -1;
11466 #else
11467     linenr_T	lnum;
11468 
11469     lnum = get_tv_lnum(argvars);
11470     if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
11471 	rettv->vval.v_number = -1;
11472     else
11473 	rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
11474     if (rettv->vval.v_number >= 0)
11475 	++rettv->vval.v_number;
11476 #endif
11477 }
11478 
11479 /*
11480  * "lispindent(lnum)" function
11481  */
11482     static void
11483 f_lispindent(argvars, rettv)
11484     typval_T	*argvars;
11485     typval_T	*rettv;
11486 {
11487 #ifdef FEAT_LISP
11488     pos_T	pos;
11489     linenr_T	lnum;
11490 
11491     pos = curwin->w_cursor;
11492     lnum = get_tv_lnum(argvars);
11493     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
11494     {
11495 	curwin->w_cursor.lnum = lnum;
11496 	rettv->vval.v_number = get_lisp_indent();
11497 	curwin->w_cursor = pos;
11498     }
11499     else
11500 #endif
11501 	rettv->vval.v_number = -1;
11502 }
11503 
11504 /*
11505  * "localtime()" function
11506  */
11507 /*ARGSUSED*/
11508     static void
11509 f_localtime(argvars, rettv)
11510     typval_T	*argvars;
11511     typval_T	*rettv;
11512 {
11513     rettv->vval.v_number = (varnumber_T)time(NULL);
11514 }
11515 
11516 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
11517 
11518     static void
11519 get_maparg(argvars, rettv, exact)
11520     typval_T	*argvars;
11521     typval_T	*rettv;
11522     int		exact;
11523 {
11524     char_u	*keys;
11525     char_u	*which;
11526     char_u	buf[NUMBUFLEN];
11527     char_u	*keys_buf = NULL;
11528     char_u	*rhs;
11529     int		mode;
11530     garray_T	ga;
11531 
11532     /* return empty string for failure */
11533     rettv->v_type = VAR_STRING;
11534     rettv->vval.v_string = NULL;
11535 
11536     keys = get_tv_string(&argvars[0]);
11537     if (*keys == NUL)
11538 	return;
11539 
11540     if (argvars[1].v_type != VAR_UNKNOWN)
11541 	which = get_tv_string_buf_chk(&argvars[1], buf);
11542     else
11543 	which = (char_u *)"";
11544     if (which == NULL)
11545 	return;
11546 
11547     mode = get_map_mode(&which, 0);
11548 
11549     keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE);
11550     rhs = check_map(keys, mode, exact, FALSE);
11551     vim_free(keys_buf);
11552     if (rhs != NULL)
11553     {
11554 	ga_init(&ga);
11555 	ga.ga_itemsize = 1;
11556 	ga.ga_growsize = 40;
11557 
11558 	while (*rhs != NUL)
11559 	    ga_concat(&ga, str2special(&rhs, FALSE));
11560 
11561 	ga_append(&ga, NUL);
11562 	rettv->vval.v_string = (char_u *)ga.ga_data;
11563     }
11564 }
11565 
11566 /*
11567  * "map()" function
11568  */
11569     static void
11570 f_map(argvars, rettv)
11571     typval_T	*argvars;
11572     typval_T	*rettv;
11573 {
11574     filter_map(argvars, rettv, TRUE);
11575 }
11576 
11577 /*
11578  * "maparg()" function
11579  */
11580     static void
11581 f_maparg(argvars, rettv)
11582     typval_T	*argvars;
11583     typval_T	*rettv;
11584 {
11585     get_maparg(argvars, rettv, TRUE);
11586 }
11587 
11588 /*
11589  * "mapcheck()" function
11590  */
11591     static void
11592 f_mapcheck(argvars, rettv)
11593     typval_T	*argvars;
11594     typval_T	*rettv;
11595 {
11596     get_maparg(argvars, rettv, FALSE);
11597 }
11598 
11599 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
11600 
11601     static void
11602 find_some_match(argvars, rettv, type)
11603     typval_T	*argvars;
11604     typval_T	*rettv;
11605     int		type;
11606 {
11607     char_u	*str = NULL;
11608     char_u	*expr = NULL;
11609     char_u	*pat;
11610     regmatch_T	regmatch;
11611     char_u	patbuf[NUMBUFLEN];
11612     char_u	strbuf[NUMBUFLEN];
11613     char_u	*save_cpo;
11614     long	start = 0;
11615     long	nth = 1;
11616     int		match = 0;
11617     list_T	*l = NULL;
11618     listitem_T	*li = NULL;
11619     long	idx = 0;
11620     char_u	*tofree = NULL;
11621 
11622     /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
11623     save_cpo = p_cpo;
11624     p_cpo = (char_u *)"";
11625 
11626     rettv->vval.v_number = -1;
11627     if (type == 3)
11628     {
11629 	/* return empty list when there are no matches */
11630 	if ((rettv->vval.v_list = list_alloc()) == NULL)
11631 	    goto theend;
11632 	rettv->v_type = VAR_LIST;
11633 	++rettv->vval.v_list->lv_refcount;
11634     }
11635     else if (type == 2)
11636     {
11637 	rettv->v_type = VAR_STRING;
11638 	rettv->vval.v_string = NULL;
11639     }
11640 
11641     if (argvars[0].v_type == VAR_LIST)
11642     {
11643 	if ((l = argvars[0].vval.v_list) == NULL)
11644 	    goto theend;
11645 	li = l->lv_first;
11646     }
11647     else
11648 	expr = str = get_tv_string(&argvars[0]);
11649 
11650     pat = get_tv_string_buf_chk(&argvars[1], patbuf);
11651     if (pat == NULL)
11652 	goto theend;
11653 
11654     if (argvars[2].v_type != VAR_UNKNOWN)
11655     {
11656 	int	    error = FALSE;
11657 
11658 	start = get_tv_number_chk(&argvars[2], &error);
11659 	if (error)
11660 	    goto theend;
11661 	if (l != NULL)
11662 	{
11663 	    li = list_find(l, start);
11664 	    if (li == NULL)
11665 		goto theend;
11666 	    idx = l->lv_idx;	/* use the cached index */
11667 	}
11668 	else
11669 	{
11670 	    if (start < 0)
11671 		start = 0;
11672 	    if (start > (long)STRLEN(str))
11673 		goto theend;
11674 	    str += start;
11675 	}
11676 
11677 	if (argvars[3].v_type != VAR_UNKNOWN)
11678 	    nth = get_tv_number_chk(&argvars[3], &error);
11679 	if (error)
11680 	    goto theend;
11681     }
11682 
11683     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
11684     if (regmatch.regprog != NULL)
11685     {
11686 	regmatch.rm_ic = p_ic;
11687 
11688 	for (;;)
11689 	{
11690 	    if (l != NULL)
11691 	    {
11692 		if (li == NULL)
11693 		{
11694 		    match = FALSE;
11695 		    break;
11696 		}
11697 		vim_free(tofree);
11698 		str = echo_string(&li->li_tv, &tofree, strbuf);
11699 		if (str == NULL)
11700 		    break;
11701 	    }
11702 
11703 	    match = vim_regexec_nl(&regmatch, str, (colnr_T)0);
11704 
11705 	    if (match && --nth <= 0)
11706 		break;
11707 	    if (l == NULL && !match)
11708 		break;
11709 
11710 	    /* Advance to just after the match. */
11711 	    if (l != NULL)
11712 	    {
11713 		li = li->li_next;
11714 		++idx;
11715 	    }
11716 	    else
11717 	    {
11718 #ifdef FEAT_MBYTE
11719 		str = regmatch.startp[0] + (*mb_ptr2len)(regmatch.startp[0]);
11720 #else
11721 		str = regmatch.startp[0] + 1;
11722 #endif
11723 	    }
11724 	}
11725 
11726 	if (match)
11727 	{
11728 	    if (type == 3)
11729 	    {
11730 		int i;
11731 
11732 		/* return list with matched string and submatches */
11733 		for (i = 0; i < NSUBEXP; ++i)
11734 		{
11735 		    if (regmatch.endp[i] == NULL)
11736 			break;
11737 		    if (list_append_string(rettv->vval.v_list,
11738 				regmatch.startp[i],
11739 				(int)(regmatch.endp[i] - regmatch.startp[i]))
11740 			    == FAIL)
11741 			break;
11742 		}
11743 	    }
11744 	    else if (type == 2)
11745 	    {
11746 		/* return matched string */
11747 		if (l != NULL)
11748 		    copy_tv(&li->li_tv, rettv);
11749 		else
11750 		    rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
11751 				(int)(regmatch.endp[0] - regmatch.startp[0]));
11752 	    }
11753 	    else if (l != NULL)
11754 		rettv->vval.v_number = idx;
11755 	    else
11756 	    {
11757 		if (type != 0)
11758 		    rettv->vval.v_number =
11759 				      (varnumber_T)(regmatch.startp[0] - str);
11760 		else
11761 		    rettv->vval.v_number =
11762 					(varnumber_T)(regmatch.endp[0] - str);
11763 		rettv->vval.v_number += str - expr;
11764 	    }
11765 	}
11766 	vim_free(regmatch.regprog);
11767     }
11768 
11769 theend:
11770     vim_free(tofree);
11771     p_cpo = save_cpo;
11772 }
11773 
11774 /*
11775  * "match()" function
11776  */
11777     static void
11778 f_match(argvars, rettv)
11779     typval_T	*argvars;
11780     typval_T	*rettv;
11781 {
11782     find_some_match(argvars, rettv, 1);
11783 }
11784 
11785 /*
11786  * "matchend()" function
11787  */
11788     static void
11789 f_matchend(argvars, rettv)
11790     typval_T	*argvars;
11791     typval_T	*rettv;
11792 {
11793     find_some_match(argvars, rettv, 0);
11794 }
11795 
11796 /*
11797  * "matchlist()" function
11798  */
11799     static void
11800 f_matchlist(argvars, rettv)
11801     typval_T	*argvars;
11802     typval_T	*rettv;
11803 {
11804     find_some_match(argvars, rettv, 3);
11805 }
11806 
11807 /*
11808  * "matchstr()" function
11809  */
11810     static void
11811 f_matchstr(argvars, rettv)
11812     typval_T	*argvars;
11813     typval_T	*rettv;
11814 {
11815     find_some_match(argvars, rettv, 2);
11816 }
11817 
11818 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
11819 
11820     static void
11821 max_min(argvars, rettv, domax)
11822     typval_T	*argvars;
11823     typval_T	*rettv;
11824     int		domax;
11825 {
11826     long	n = 0;
11827     long	i;
11828     int		error = FALSE;
11829 
11830     if (argvars[0].v_type == VAR_LIST)
11831     {
11832 	list_T		*l;
11833 	listitem_T	*li;
11834 
11835 	l = argvars[0].vval.v_list;
11836 	if (l != NULL)
11837 	{
11838 	    li = l->lv_first;
11839 	    if (li != NULL)
11840 	    {
11841 		n = get_tv_number_chk(&li->li_tv, &error);
11842 		for (;;)
11843 		{
11844 		    li = li->li_next;
11845 		    if (li == NULL)
11846 			break;
11847 		    i = get_tv_number_chk(&li->li_tv, &error);
11848 		    if (domax ? i > n : i < n)
11849 			n = i;
11850 		}
11851 	    }
11852 	}
11853     }
11854     else if (argvars[0].v_type == VAR_DICT)
11855     {
11856 	dict_T		*d;
11857 	int		first = TRUE;
11858 	hashitem_T	*hi;
11859 	int		todo;
11860 
11861 	d = argvars[0].vval.v_dict;
11862 	if (d != NULL)
11863 	{
11864 	    todo = d->dv_hashtab.ht_used;
11865 	    for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
11866 	    {
11867 		if (!HASHITEM_EMPTY(hi))
11868 		{
11869 		    --todo;
11870 		    i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
11871 		    if (first)
11872 		    {
11873 			n = i;
11874 			first = FALSE;
11875 		    }
11876 		    else if (domax ? i > n : i < n)
11877 			n = i;
11878 		}
11879 	    }
11880 	}
11881     }
11882     else
11883 	EMSG(_(e_listdictarg));
11884     rettv->vval.v_number = error ? 0 : n;
11885 }
11886 
11887 /*
11888  * "max()" function
11889  */
11890     static void
11891 f_max(argvars, rettv)
11892     typval_T	*argvars;
11893     typval_T	*rettv;
11894 {
11895     max_min(argvars, rettv, TRUE);
11896 }
11897 
11898 /*
11899  * "min()" function
11900  */
11901     static void
11902 f_min(argvars, rettv)
11903     typval_T	*argvars;
11904     typval_T	*rettv;
11905 {
11906     max_min(argvars, rettv, FALSE);
11907 }
11908 
11909 static int mkdir_recurse __ARGS((char_u *dir, int prot));
11910 
11911 /*
11912  * Create the directory in which "dir" is located, and higher levels when
11913  * needed.
11914  */
11915     static int
11916 mkdir_recurse(dir, prot)
11917     char_u	*dir;
11918     int		prot;
11919 {
11920     char_u	*p;
11921     char_u	*updir;
11922     int		r = FAIL;
11923 
11924     /* Get end of directory name in "dir".
11925      * We're done when it's "/" or "c:/". */
11926     p = gettail_sep(dir);
11927     if (p <= get_past_head(dir))
11928 	return OK;
11929 
11930     /* If the directory exists we're done.  Otherwise: create it.*/
11931     updir = vim_strnsave(dir, (int)(p - dir));
11932     if (updir == NULL)
11933 	return FAIL;
11934     if (mch_isdir(updir))
11935 	r = OK;
11936     else if (mkdir_recurse(updir, prot) == OK)
11937 	r = vim_mkdir_emsg(updir, prot);
11938     vim_free(updir);
11939     return r;
11940 }
11941 
11942 #ifdef vim_mkdir
11943 /*
11944  * "mkdir()" function
11945  */
11946     static void
11947 f_mkdir(argvars, rettv)
11948     typval_T	*argvars;
11949     typval_T	*rettv;
11950 {
11951     char_u	*dir;
11952     char_u	buf[NUMBUFLEN];
11953     int		prot = 0755;
11954 
11955     rettv->vval.v_number = FAIL;
11956     if (check_restricted() || check_secure())
11957 	return;
11958 
11959     dir = get_tv_string_buf(&argvars[0], buf);
11960     if (argvars[1].v_type != VAR_UNKNOWN)
11961     {
11962 	if (argvars[2].v_type != VAR_UNKNOWN)
11963 	    prot = get_tv_number_chk(&argvars[2], NULL);
11964 	if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
11965 	    mkdir_recurse(dir, prot);
11966     }
11967     rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
11968 }
11969 #endif
11970 
11971 /*
11972  * "mode()" function
11973  */
11974 /*ARGSUSED*/
11975     static void
11976 f_mode(argvars, rettv)
11977     typval_T	*argvars;
11978     typval_T	*rettv;
11979 {
11980     char_u	buf[2];
11981 
11982 #ifdef FEAT_VISUAL
11983     if (VIsual_active)
11984     {
11985 	if (VIsual_select)
11986 	    buf[0] = VIsual_mode + 's' - 'v';
11987 	else
11988 	    buf[0] = VIsual_mode;
11989     }
11990     else
11991 #endif
11992 	if (State == HITRETURN || State == ASKMORE || State == SETWSIZE)
11993 	buf[0] = 'r';
11994     else if (State & INSERT)
11995     {
11996 	if (State & REPLACE_FLAG)
11997 	    buf[0] = 'R';
11998 	else
11999 	    buf[0] = 'i';
12000     }
12001     else if (State & CMDLINE)
12002 	buf[0] = 'c';
12003     else
12004 	buf[0] = 'n';
12005 
12006     buf[1] = NUL;
12007     rettv->vval.v_string = vim_strsave(buf);
12008     rettv->v_type = VAR_STRING;
12009 }
12010 
12011 /*
12012  * "nextnonblank()" function
12013  */
12014     static void
12015 f_nextnonblank(argvars, rettv)
12016     typval_T	*argvars;
12017     typval_T	*rettv;
12018 {
12019     linenr_T	lnum;
12020 
12021     for (lnum = get_tv_lnum(argvars); ; ++lnum)
12022     {
12023 	if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
12024 	{
12025 	    lnum = 0;
12026 	    break;
12027 	}
12028 	if (*skipwhite(ml_get(lnum)) != NUL)
12029 	    break;
12030     }
12031     rettv->vval.v_number = lnum;
12032 }
12033 
12034 /*
12035  * "nr2char()" function
12036  */
12037     static void
12038 f_nr2char(argvars, rettv)
12039     typval_T	*argvars;
12040     typval_T	*rettv;
12041 {
12042     char_u	buf[NUMBUFLEN];
12043 
12044 #ifdef FEAT_MBYTE
12045     if (has_mbyte)
12046 	buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
12047     else
12048 #endif
12049     {
12050 	buf[0] = (char_u)get_tv_number(&argvars[0]);
12051 	buf[1] = NUL;
12052     }
12053     rettv->v_type = VAR_STRING;
12054     rettv->vval.v_string = vim_strsave(buf);
12055 }
12056 
12057 /*
12058  * "prevnonblank()" function
12059  */
12060     static void
12061 f_prevnonblank(argvars, rettv)
12062     typval_T	*argvars;
12063     typval_T	*rettv;
12064 {
12065     linenr_T	lnum;
12066 
12067     lnum = get_tv_lnum(argvars);
12068     if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
12069 	lnum = 0;
12070     else
12071 	while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
12072 	    --lnum;
12073     rettv->vval.v_number = lnum;
12074 }
12075 
12076 #ifdef HAVE_STDARG_H
12077 /* This dummy va_list is here because:
12078  * - passing a NULL pointer doesn't work when va_list isn't a pointer
12079  * - locally in the function results in a "used before set" warning
12080  * - using va_start() to initialize it gives "function with fixed args" error */
12081 static va_list	ap;
12082 #endif
12083 
12084 /*
12085  * "printf()" function
12086  */
12087     static void
12088 f_printf(argvars, rettv)
12089     typval_T	*argvars;
12090     typval_T	*rettv;
12091 {
12092     rettv->v_type = VAR_STRING;
12093     rettv->vval.v_string = NULL;
12094 #ifdef HAVE_STDARG_H	    /* only very old compilers can't do this */
12095     {
12096 	char_u	buf[NUMBUFLEN];
12097 	int	len;
12098 	char_u	*s;
12099 	int	saved_did_emsg = did_emsg;
12100 	char	*fmt;
12101 
12102 	/* Get the required length, allocate the buffer and do it for real. */
12103 	did_emsg = FALSE;
12104 	fmt = (char *)get_tv_string_buf(&argvars[0], buf);
12105 	len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
12106 	if (!did_emsg)
12107 	{
12108 	    s = alloc(len + 1);
12109 	    if (s != NULL)
12110 	    {
12111 		rettv->vval.v_string = s;
12112 		(void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
12113 	    }
12114 	}
12115 	did_emsg |= saved_did_emsg;
12116     }
12117 #endif
12118 }
12119 
12120 /*
12121  * "range()" function
12122  */
12123     static void
12124 f_range(argvars, rettv)
12125     typval_T	*argvars;
12126     typval_T	*rettv;
12127 {
12128     long	start;
12129     long	end;
12130     long	stride = 1;
12131     long	i;
12132     list_T	*l;
12133     int		error = FALSE;
12134 
12135     start = get_tv_number_chk(&argvars[0], &error);
12136     if (argvars[1].v_type == VAR_UNKNOWN)
12137     {
12138 	end = start - 1;
12139 	start = 0;
12140     }
12141     else
12142     {
12143 	end = get_tv_number_chk(&argvars[1], &error);
12144 	if (argvars[2].v_type != VAR_UNKNOWN)
12145 	    stride = get_tv_number_chk(&argvars[2], &error);
12146     }
12147 
12148     rettv->vval.v_number = 0;
12149     if (error)
12150 	return;		/* type error; errmsg already given */
12151     if (stride == 0)
12152 	EMSG(_("E726: Stride is zero"));
12153     else if (stride > 0 ? end + 1 < start : end - 1 > start)
12154 	EMSG(_("E727: Start past end"));
12155     else
12156     {
12157 	l = list_alloc();
12158 	if (l != NULL)
12159 	{
12160 	    rettv->v_type = VAR_LIST;
12161 	    rettv->vval.v_list = l;
12162 	    ++l->lv_refcount;
12163 
12164 	    for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
12165 		if (list_append_number(l, (varnumber_T)i) == FAIL)
12166 		    break;
12167 	}
12168     }
12169 }
12170 
12171 /*
12172  * "readfile()" function
12173  */
12174     static void
12175 f_readfile(argvars, rettv)
12176     typval_T	*argvars;
12177     typval_T	*rettv;
12178 {
12179     int		binary = FALSE;
12180     char_u	*fname;
12181     FILE	*fd;
12182     list_T	*l;
12183     listitem_T	*li;
12184 #define FREAD_SIZE 200	    /* optimized for text lines */
12185     char_u	buf[FREAD_SIZE];
12186     int		readlen;    /* size of last fread() */
12187     int		buflen;	    /* nr of valid chars in buf[] */
12188     int		filtd;	    /* how much in buf[] was NUL -> '\n' filtered */
12189     int		tolist;	    /* first byte in buf[] still to be put in list */
12190     int		chop;	    /* how many CR to chop off */
12191     char_u	*prev = NULL;	/* previously read bytes, if any */
12192     int		prevlen = 0;    /* length of "prev" if not NULL */
12193     char_u	*s;
12194     int		len;
12195     long	maxline = MAXLNUM;
12196     long	cnt = 0;
12197 
12198     if (argvars[1].v_type != VAR_UNKNOWN)
12199     {
12200 	if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
12201 	    binary = TRUE;
12202 	if (argvars[2].v_type != VAR_UNKNOWN)
12203 	    maxline = get_tv_number(&argvars[2]);
12204     }
12205 
12206     l = list_alloc();
12207     if (l == NULL)
12208 	return;
12209     rettv->v_type = VAR_LIST;
12210     rettv->vval.v_list = l;
12211     l->lv_refcount = 1;
12212 
12213     /* Always open the file in binary mode, library functions have a mind of
12214      * their own about CR-LF conversion. */
12215     fname = get_tv_string(&argvars[0]);
12216     if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
12217     {
12218 	EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
12219 	return;
12220     }
12221 
12222     filtd = 0;
12223     while (cnt < maxline || maxline < 0)
12224     {
12225 	readlen = fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
12226 	buflen = filtd + readlen;
12227 	tolist = 0;
12228 	for ( ; filtd < buflen || readlen <= 0; ++filtd)
12229 	{
12230 	    if (buf[filtd] == '\n' || readlen <= 0)
12231 	    {
12232 		/* Only when in binary mode add an empty list item when the
12233 		 * last line ends in a '\n'. */
12234 		if (!binary && readlen == 0 && filtd == 0)
12235 		    break;
12236 
12237 		/* Found end-of-line or end-of-file: add a text line to the
12238 		 * list. */
12239 		chop = 0;
12240 		if (!binary)
12241 		    while (filtd - chop - 1 >= tolist
12242 					  && buf[filtd - chop - 1] == '\r')
12243 			++chop;
12244 		len = filtd - tolist - chop;
12245 		if (prev == NULL)
12246 		    s = vim_strnsave(buf + tolist, len);
12247 		else
12248 		{
12249 		    s = alloc((unsigned)(prevlen + len + 1));
12250 		    if (s != NULL)
12251 		    {
12252 			mch_memmove(s, prev, prevlen);
12253 			vim_free(prev);
12254 			prev = NULL;
12255 			mch_memmove(s + prevlen, buf + tolist, len);
12256 			s[prevlen + len] = NUL;
12257 		    }
12258 		}
12259 		tolist = filtd + 1;
12260 
12261 		li = listitem_alloc();
12262 		if (li == NULL)
12263 		{
12264 		    vim_free(s);
12265 		    break;
12266 		}
12267 		li->li_tv.v_type = VAR_STRING;
12268 		li->li_tv.v_lock = 0;
12269 		li->li_tv.vval.v_string = s;
12270 		list_append(l, li);
12271 
12272 		if (++cnt >= maxline && maxline >= 0)
12273 		    break;
12274 		if (readlen <= 0)
12275 		    break;
12276 	    }
12277 	    else if (buf[filtd] == NUL)
12278 		buf[filtd] = '\n';
12279 	}
12280 	if (readlen <= 0)
12281 	    break;
12282 
12283 	if (tolist == 0)
12284 	{
12285 	    /* "buf" is full, need to move text to an allocated buffer */
12286 	    if (prev == NULL)
12287 	    {
12288 		prev = vim_strnsave(buf, buflen);
12289 		prevlen = buflen;
12290 	    }
12291 	    else
12292 	    {
12293 		s = alloc((unsigned)(prevlen + buflen));
12294 		if (s != NULL)
12295 		{
12296 		    mch_memmove(s, prev, prevlen);
12297 		    mch_memmove(s + prevlen, buf, buflen);
12298 		    vim_free(prev);
12299 		    prev = s;
12300 		    prevlen += buflen;
12301 		}
12302 	    }
12303 	    filtd = 0;
12304 	}
12305 	else
12306 	{
12307 	    mch_memmove(buf, buf + tolist, buflen - tolist);
12308 	    filtd -= tolist;
12309 	}
12310     }
12311 
12312     /*
12313      * For a negative line count use only the lines at the end of the file,
12314      * free the rest.
12315      */
12316     if (maxline < 0)
12317 	while (cnt > -maxline)
12318 	{
12319 	    listitem_remove(l, l->lv_first);
12320 	    --cnt;
12321 	}
12322 
12323     vim_free(prev);
12324     fclose(fd);
12325 }
12326 
12327 
12328 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
12329 static void make_connection __ARGS((void));
12330 static int check_connection __ARGS((void));
12331 
12332     static void
12333 make_connection()
12334 {
12335     if (X_DISPLAY == NULL
12336 # ifdef FEAT_GUI
12337 	    && !gui.in_use
12338 # endif
12339 	    )
12340     {
12341 	x_force_connect = TRUE;
12342 	setup_term_clip();
12343 	x_force_connect = FALSE;
12344     }
12345 }
12346 
12347     static int
12348 check_connection()
12349 {
12350     make_connection();
12351     if (X_DISPLAY == NULL)
12352     {
12353 	EMSG(_("E240: No connection to Vim server"));
12354 	return FAIL;
12355     }
12356     return OK;
12357 }
12358 #endif
12359 
12360 #ifdef FEAT_CLIENTSERVER
12361 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
12362 
12363     static void
12364 remote_common(argvars, rettv, expr)
12365     typval_T	*argvars;
12366     typval_T	*rettv;
12367     int		expr;
12368 {
12369     char_u	*server_name;
12370     char_u	*keys;
12371     char_u	*r = NULL;
12372     char_u	buf[NUMBUFLEN];
12373 # ifdef WIN32
12374     HWND	w;
12375 # else
12376     Window	w;
12377 # endif
12378 
12379     if (check_restricted() || check_secure())
12380 	return;
12381 
12382 # ifdef FEAT_X11
12383     if (check_connection() == FAIL)
12384 	return;
12385 # endif
12386 
12387     server_name = get_tv_string_chk(&argvars[0]);
12388     if (server_name == NULL)
12389 	return;		/* type error; errmsg already given */
12390     keys = get_tv_string_buf(&argvars[1], buf);
12391 # ifdef WIN32
12392     if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
12393 # else
12394     if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
12395 									  < 0)
12396 # endif
12397     {
12398 	if (r != NULL)
12399 	    EMSG(r);		/* sending worked but evaluation failed */
12400 	else
12401 	    EMSG2(_("E241: Unable to send to %s"), server_name);
12402 	return;
12403     }
12404 
12405     rettv->vval.v_string = r;
12406 
12407     if (argvars[2].v_type != VAR_UNKNOWN)
12408     {
12409 	dictitem_T	v;
12410 	char_u		str[30];
12411 	char_u		*idvar;
12412 
12413 	sprintf((char *)str, "0x%x", (unsigned int)w);
12414 	v.di_tv.v_type = VAR_STRING;
12415 	v.di_tv.vval.v_string = vim_strsave(str);
12416 	idvar = get_tv_string_chk(&argvars[2]);
12417 	if (idvar != NULL)
12418 	    set_var(idvar, &v.di_tv, FALSE);
12419 	vim_free(v.di_tv.vval.v_string);
12420     }
12421 }
12422 #endif
12423 
12424 /*
12425  * "remote_expr()" function
12426  */
12427 /*ARGSUSED*/
12428     static void
12429 f_remote_expr(argvars, rettv)
12430     typval_T	*argvars;
12431     typval_T	*rettv;
12432 {
12433     rettv->v_type = VAR_STRING;
12434     rettv->vval.v_string = NULL;
12435 #ifdef FEAT_CLIENTSERVER
12436     remote_common(argvars, rettv, TRUE);
12437 #endif
12438 }
12439 
12440 /*
12441  * "remote_foreground()" function
12442  */
12443 /*ARGSUSED*/
12444     static void
12445 f_remote_foreground(argvars, rettv)
12446     typval_T	*argvars;
12447     typval_T	*rettv;
12448 {
12449     rettv->vval.v_number = 0;
12450 #ifdef FEAT_CLIENTSERVER
12451 # ifdef WIN32
12452     /* On Win32 it's done in this application. */
12453     {
12454 	char_u	*server_name = get_tv_string_chk(&argvars[0]);
12455 
12456 	if (server_name != NULL)
12457 	    serverForeground(server_name);
12458     }
12459 # else
12460     /* Send a foreground() expression to the server. */
12461     argvars[1].v_type = VAR_STRING;
12462     argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
12463     argvars[2].v_type = VAR_UNKNOWN;
12464     remote_common(argvars, rettv, TRUE);
12465     vim_free(argvars[1].vval.v_string);
12466 # endif
12467 #endif
12468 }
12469 
12470 /*ARGSUSED*/
12471     static void
12472 f_remote_peek(argvars, rettv)
12473     typval_T	*argvars;
12474     typval_T	*rettv;
12475 {
12476 #ifdef FEAT_CLIENTSERVER
12477     dictitem_T	v;
12478     char_u	*s = NULL;
12479 # ifdef WIN32
12480     int		n = 0;
12481 # endif
12482     char_u	*serverid;
12483 
12484     if (check_restricted() || check_secure())
12485     {
12486 	rettv->vval.v_number = -1;
12487 	return;
12488     }
12489     serverid = get_tv_string_chk(&argvars[0]);
12490     if (serverid == NULL)
12491     {
12492 	rettv->vval.v_number = -1;
12493 	return;		/* type error; errmsg already given */
12494     }
12495 # ifdef WIN32
12496     sscanf(serverid, "%x", &n);
12497     if (n == 0)
12498 	rettv->vval.v_number = -1;
12499     else
12500     {
12501 	s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
12502 	rettv->vval.v_number = (s != NULL);
12503     }
12504 # else
12505     rettv->vval.v_number = 0;
12506     if (check_connection() == FAIL)
12507 	return;
12508 
12509     rettv->vval.v_number = serverPeekReply(X_DISPLAY,
12510 						serverStrToWin(serverid), &s);
12511 # endif
12512 
12513     if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
12514     {
12515 	char_u		*retvar;
12516 
12517 	v.di_tv.v_type = VAR_STRING;
12518 	v.di_tv.vval.v_string = vim_strsave(s);
12519 	retvar = get_tv_string_chk(&argvars[1]);
12520 	if (retvar != NULL)
12521 	    set_var(retvar, &v.di_tv, FALSE);
12522 	vim_free(v.di_tv.vval.v_string);
12523     }
12524 #else
12525     rettv->vval.v_number = -1;
12526 #endif
12527 }
12528 
12529 /*ARGSUSED*/
12530     static void
12531 f_remote_read(argvars, rettv)
12532     typval_T	*argvars;
12533     typval_T	*rettv;
12534 {
12535     char_u	*r = NULL;
12536 
12537 #ifdef FEAT_CLIENTSERVER
12538     char_u	*serverid = get_tv_string_chk(&argvars[0]);
12539 
12540     if (serverid != NULL && !check_restricted() && !check_secure())
12541     {
12542 # ifdef WIN32
12543 	/* The server's HWND is encoded in the 'id' parameter */
12544 	int		n = 0;
12545 
12546 	sscanf(serverid, "%x", &n);
12547 	if (n != 0)
12548 	    r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
12549 	if (r == NULL)
12550 # else
12551 	if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
12552 		serverStrToWin(serverid), &r, FALSE) < 0)
12553 # endif
12554 	    EMSG(_("E277: Unable to read a server reply"));
12555     }
12556 #endif
12557     rettv->v_type = VAR_STRING;
12558     rettv->vval.v_string = r;
12559 }
12560 
12561 /*
12562  * "remote_send()" function
12563  */
12564 /*ARGSUSED*/
12565     static void
12566 f_remote_send(argvars, rettv)
12567     typval_T	*argvars;
12568     typval_T	*rettv;
12569 {
12570     rettv->v_type = VAR_STRING;
12571     rettv->vval.v_string = NULL;
12572 #ifdef FEAT_CLIENTSERVER
12573     remote_common(argvars, rettv, FALSE);
12574 #endif
12575 }
12576 
12577 /*
12578  * "remove()" function
12579  */
12580     static void
12581 f_remove(argvars, rettv)
12582     typval_T	*argvars;
12583     typval_T	*rettv;
12584 {
12585     list_T	*l;
12586     listitem_T	*item, *item2;
12587     listitem_T	*li;
12588     long	idx;
12589     long	end;
12590     char_u	*key;
12591     dict_T	*d;
12592     dictitem_T	*di;
12593 
12594     rettv->vval.v_number = 0;
12595     if (argvars[0].v_type == VAR_DICT)
12596     {
12597 	if (argvars[2].v_type != VAR_UNKNOWN)
12598 	    EMSG2(_(e_toomanyarg), "remove()");
12599 	else if ((d = argvars[0].vval.v_dict) != NULL
12600 		&& !tv_check_lock(d->dv_lock, (char_u *)"remove()"))
12601 	{
12602 	    key = get_tv_string_chk(&argvars[1]);
12603 	    if (key != NULL)
12604 	    {
12605 		di = dict_find(d, key, -1);
12606 		if (di == NULL)
12607 		    EMSG2(_(e_dictkey), key);
12608 		else
12609 		{
12610 		    *rettv = di->di_tv;
12611 		    init_tv(&di->di_tv);
12612 		    dictitem_remove(d, di);
12613 		}
12614 	    }
12615 	}
12616     }
12617     else if (argvars[0].v_type != VAR_LIST)
12618 	EMSG2(_(e_listdictarg), "remove()");
12619     else if ((l = argvars[0].vval.v_list) != NULL
12620 	    && !tv_check_lock(l->lv_lock, (char_u *)"remove()"))
12621     {
12622 	int	    error = FALSE;
12623 
12624 	idx = get_tv_number_chk(&argvars[1], &error);
12625 	if (error)
12626 	    ;		/* type error: do nothing, errmsg already given */
12627 	else if ((item = list_find(l, idx)) == NULL)
12628 	    EMSGN(_(e_listidx), idx);
12629 	else
12630 	{
12631 	    if (argvars[2].v_type == VAR_UNKNOWN)
12632 	    {
12633 		/* Remove one item, return its value. */
12634 		list_remove(l, item, item);
12635 		*rettv = item->li_tv;
12636 		vim_free(item);
12637 	    }
12638 	    else
12639 	    {
12640 		/* Remove range of items, return list with values. */
12641 		end = get_tv_number_chk(&argvars[2], &error);
12642 		if (error)
12643 		    ;		/* type error: do nothing */
12644 		else if ((item2 = list_find(l, end)) == NULL)
12645 		    EMSGN(_(e_listidx), end);
12646 		else
12647 		{
12648 		    int	    cnt = 0;
12649 
12650 		    for (li = item; li != NULL; li = li->li_next)
12651 		    {
12652 			++cnt;
12653 			if (li == item2)
12654 			    break;
12655 		    }
12656 		    if (li == NULL)  /* didn't find "item2" after "item" */
12657 			EMSG(_(e_invrange));
12658 		    else
12659 		    {
12660 			list_remove(l, item, item2);
12661 			l = list_alloc();
12662 			if (l != NULL)
12663 			{
12664 			    rettv->v_type = VAR_LIST;
12665 			    rettv->vval.v_list = l;
12666 			    l->lv_first = item;
12667 			    l->lv_last = item2;
12668 			    l->lv_refcount = 1;
12669 			    item->li_prev = NULL;
12670 			    item2->li_next = NULL;
12671 			    l->lv_len = cnt;
12672 			}
12673 		    }
12674 		}
12675 	    }
12676 	}
12677     }
12678 }
12679 
12680 /*
12681  * "rename({from}, {to})" function
12682  */
12683     static void
12684 f_rename(argvars, rettv)
12685     typval_T	*argvars;
12686     typval_T	*rettv;
12687 {
12688     char_u	buf[NUMBUFLEN];
12689 
12690     if (check_restricted() || check_secure())
12691 	rettv->vval.v_number = -1;
12692     else
12693 	rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
12694 				      get_tv_string_buf(&argvars[1], buf));
12695 }
12696 
12697 /*
12698  * "repeat()" function
12699  */
12700 /*ARGSUSED*/
12701     static void
12702 f_repeat(argvars, rettv)
12703     typval_T	*argvars;
12704     typval_T	*rettv;
12705 {
12706     char_u	*p;
12707     int		n;
12708     int		slen;
12709     int		len;
12710     char_u	*r;
12711     int		i;
12712     list_T	*l;
12713 
12714     n = get_tv_number(&argvars[1]);
12715     if (argvars[0].v_type == VAR_LIST)
12716     {
12717 	l = list_alloc();
12718 	if (l != NULL && argvars[0].vval.v_list != NULL)
12719 	{
12720 	    l->lv_refcount = 1;
12721 	    while (n-- > 0)
12722 		if (list_extend(l, argvars[0].vval.v_list, NULL) == FAIL)
12723 		    break;
12724 	}
12725 	rettv->v_type = VAR_LIST;
12726 	rettv->vval.v_list = l;
12727     }
12728     else
12729     {
12730 	p = get_tv_string(&argvars[0]);
12731 	rettv->v_type = VAR_STRING;
12732 	rettv->vval.v_string = NULL;
12733 
12734 	slen = (int)STRLEN(p);
12735 	len = slen * n;
12736 	if (len <= 0)
12737 	    return;
12738 
12739 	r = alloc(len + 1);
12740 	if (r != NULL)
12741 	{
12742 	    for (i = 0; i < n; i++)
12743 		mch_memmove(r + i * slen, p, (size_t)slen);
12744 	    r[len] = NUL;
12745 	}
12746 
12747 	rettv->vval.v_string = r;
12748     }
12749 }
12750 
12751 /*
12752  * "resolve()" function
12753  */
12754     static void
12755 f_resolve(argvars, rettv)
12756     typval_T	*argvars;
12757     typval_T	*rettv;
12758 {
12759     char_u	*p;
12760 
12761     p = get_tv_string(&argvars[0]);
12762 #ifdef FEAT_SHORTCUT
12763     {
12764 	char_u	*v = NULL;
12765 
12766 	v = mch_resolve_shortcut(p);
12767 	if (v != NULL)
12768 	    rettv->vval.v_string = v;
12769 	else
12770 	    rettv->vval.v_string = vim_strsave(p);
12771     }
12772 #else
12773 # ifdef HAVE_READLINK
12774     {
12775 	char_u	buf[MAXPATHL + 1];
12776 	char_u	*cpy;
12777 	int	len;
12778 	char_u	*remain = NULL;
12779 	char_u	*q;
12780 	int	is_relative_to_current = FALSE;
12781 	int	has_trailing_pathsep = FALSE;
12782 	int	limit = 100;
12783 
12784 	p = vim_strsave(p);
12785 
12786 	if (p[0] == '.' && (vim_ispathsep(p[1])
12787 				   || (p[1] == '.' && (vim_ispathsep(p[2])))))
12788 	    is_relative_to_current = TRUE;
12789 
12790 	len = STRLEN(p);
12791 	if (len > 0 && after_pathsep(p, p + len))
12792 	    has_trailing_pathsep = TRUE;
12793 
12794 	q = getnextcomp(p);
12795 	if (*q != NUL)
12796 	{
12797 	    /* Separate the first path component in "p", and keep the
12798 	     * remainder (beginning with the path separator). */
12799 	    remain = vim_strsave(q - 1);
12800 	    q[-1] = NUL;
12801 	}
12802 
12803 	for (;;)
12804 	{
12805 	    for (;;)
12806 	    {
12807 		len = readlink((char *)p, (char *)buf, MAXPATHL);
12808 		if (len <= 0)
12809 		    break;
12810 		buf[len] = NUL;
12811 
12812 		if (limit-- == 0)
12813 		{
12814 		    vim_free(p);
12815 		    vim_free(remain);
12816 		    EMSG(_("E655: Too many symbolic links (cycle?)"));
12817 		    rettv->vval.v_string = NULL;
12818 		    goto fail;
12819 		}
12820 
12821 		/* Ensure that the result will have a trailing path separator
12822 		 * if the argument has one. */
12823 		if (remain == NULL && has_trailing_pathsep)
12824 		    add_pathsep(buf);
12825 
12826 		/* Separate the first path component in the link value and
12827 		 * concatenate the remainders. */
12828 		q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
12829 		if (*q != NUL)
12830 		{
12831 		    if (remain == NULL)
12832 			remain = vim_strsave(q - 1);
12833 		    else
12834 		    {
12835 			cpy = concat_str(q - 1, remain);
12836 			if (cpy != NULL)
12837 			{
12838 			    vim_free(remain);
12839 			    remain = cpy;
12840 			}
12841 		    }
12842 		    q[-1] = NUL;
12843 		}
12844 
12845 		q = gettail(p);
12846 		if (q > p && *q == NUL)
12847 		{
12848 		    /* Ignore trailing path separator. */
12849 		    q[-1] = NUL;
12850 		    q = gettail(p);
12851 		}
12852 		if (q > p && !mch_isFullName(buf))
12853 		{
12854 		    /* symlink is relative to directory of argument */
12855 		    cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
12856 		    if (cpy != NULL)
12857 		    {
12858 			STRCPY(cpy, p);
12859 			STRCPY(gettail(cpy), buf);
12860 			vim_free(p);
12861 			p = cpy;
12862 		    }
12863 		}
12864 		else
12865 		{
12866 		    vim_free(p);
12867 		    p = vim_strsave(buf);
12868 		}
12869 	    }
12870 
12871 	    if (remain == NULL)
12872 		break;
12873 
12874 	    /* Append the first path component of "remain" to "p". */
12875 	    q = getnextcomp(remain + 1);
12876 	    len = q - remain - (*q != NUL);
12877 	    cpy = vim_strnsave(p, STRLEN(p) + len);
12878 	    if (cpy != NULL)
12879 	    {
12880 		STRNCAT(cpy, remain, len);
12881 		vim_free(p);
12882 		p = cpy;
12883 	    }
12884 	    /* Shorten "remain". */
12885 	    if (*q != NUL)
12886 		STRCPY(remain, q - 1);
12887 	    else
12888 	    {
12889 		vim_free(remain);
12890 		remain = NULL;
12891 	    }
12892 	}
12893 
12894 	/* If the result is a relative path name, make it explicitly relative to
12895 	 * the current directory if and only if the argument had this form. */
12896 	if (!vim_ispathsep(*p))
12897 	{
12898 	    if (is_relative_to_current
12899 		    && *p != NUL
12900 		    && !(p[0] == '.'
12901 			&& (p[1] == NUL
12902 			    || vim_ispathsep(p[1])
12903 			    || (p[1] == '.'
12904 				&& (p[2] == NUL
12905 				    || vim_ispathsep(p[2]))))))
12906 	    {
12907 		/* Prepend "./". */
12908 		cpy = concat_str((char_u *)"./", p);
12909 		if (cpy != NULL)
12910 		{
12911 		    vim_free(p);
12912 		    p = cpy;
12913 		}
12914 	    }
12915 	    else if (!is_relative_to_current)
12916 	    {
12917 		/* Strip leading "./". */
12918 		q = p;
12919 		while (q[0] == '.' && vim_ispathsep(q[1]))
12920 		    q += 2;
12921 		if (q > p)
12922 		    mch_memmove(p, p + 2, STRLEN(p + 2) + (size_t)1);
12923 	    }
12924 	}
12925 
12926 	/* Ensure that the result will have no trailing path separator
12927 	 * if the argument had none.  But keep "/" or "//". */
12928 	if (!has_trailing_pathsep)
12929 	{
12930 	    q = p + STRLEN(p);
12931 	    if (after_pathsep(p, q))
12932 		*gettail_sep(p) = NUL;
12933 	}
12934 
12935 	rettv->vval.v_string = p;
12936     }
12937 # else
12938     rettv->vval.v_string = vim_strsave(p);
12939 # endif
12940 #endif
12941 
12942     simplify_filename(rettv->vval.v_string);
12943 
12944 #ifdef HAVE_READLINK
12945 fail:
12946 #endif
12947     rettv->v_type = VAR_STRING;
12948 }
12949 
12950 /*
12951  * "reverse({list})" function
12952  */
12953     static void
12954 f_reverse(argvars, rettv)
12955     typval_T	*argvars;
12956     typval_T	*rettv;
12957 {
12958     list_T	*l;
12959     listitem_T	*li, *ni;
12960 
12961     rettv->vval.v_number = 0;
12962     if (argvars[0].v_type != VAR_LIST)
12963 	EMSG2(_(e_listarg), "reverse()");
12964     else if ((l = argvars[0].vval.v_list) != NULL
12965 	    && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
12966     {
12967 	li = l->lv_last;
12968 	l->lv_first = l->lv_last = NULL;
12969 	l->lv_len = 0;
12970 	while (li != NULL)
12971 	{
12972 	    ni = li->li_prev;
12973 	    list_append(l, li);
12974 	    li = ni;
12975 	}
12976 	rettv->vval.v_list = l;
12977 	rettv->v_type = VAR_LIST;
12978 	++l->lv_refcount;
12979     }
12980 }
12981 
12982 #define SP_NOMOVE	1	/* don't move cursor */
12983 #define SP_REPEAT	2	/* repeat to find outer pair */
12984 #define SP_RETCOUNT	4	/* return matchcount */
12985 #define SP_SETPCMARK	8       /* set previous context mark */
12986 
12987 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
12988 
12989 /*
12990  * Get flags for a search function.
12991  * Possibly sets "p_ws".
12992  * Returns BACKWARD, FORWARD or zero (for an error).
12993  */
12994     static int
12995 get_search_arg(varp, flagsp)
12996     typval_T	*varp;
12997     int		*flagsp;
12998 {
12999     int		dir = FORWARD;
13000     char_u	*flags;
13001     char_u	nbuf[NUMBUFLEN];
13002     int		mask;
13003 
13004     if (varp->v_type != VAR_UNKNOWN)
13005     {
13006 	flags = get_tv_string_buf_chk(varp, nbuf);
13007 	if (flags == NULL)
13008 	    return 0;		/* type error; errmsg already given */
13009 	while (*flags != NUL)
13010 	{
13011 	    switch (*flags)
13012 	    {
13013 		case 'b': dir = BACKWARD; break;
13014 		case 'w': p_ws = TRUE; break;
13015 		case 'W': p_ws = FALSE; break;
13016 		default:  mask = 0;
13017 			  if (flagsp != NULL)
13018 			     switch (*flags)
13019 			     {
13020 				 case 'n': mask = SP_NOMOVE; break;
13021 				 case 'r': mask = SP_REPEAT; break;
13022 				 case 'm': mask = SP_RETCOUNT; break;
13023 				 case 's': mask = SP_SETPCMARK; break;
13024 			     }
13025 			  if (mask == 0)
13026 			  {
13027 			      EMSG2(_(e_invarg2), flags);
13028 			      dir = 0;
13029 			  }
13030 			  else
13031 			      *flagsp |= mask;
13032 	    }
13033 	    if (dir == 0)
13034 		break;
13035 	    ++flags;
13036 	}
13037     }
13038     return dir;
13039 }
13040 
13041 /*
13042  * "search()" function
13043  */
13044     static void
13045 f_search(argvars, rettv)
13046     typval_T	*argvars;
13047     typval_T	*rettv;
13048 {
13049     char_u	*pat;
13050     pos_T	pos;
13051     pos_T	save_cursor;
13052     int		save_p_ws = p_ws;
13053     int		dir;
13054     int		flags = 0;
13055 
13056     rettv->vval.v_number = 0;	/* default: FAIL */
13057 
13058     pat = get_tv_string(&argvars[0]);
13059     dir = get_search_arg(&argvars[1], &flags);	/* may set p_ws */
13060     if (dir == 0)
13061 	goto theend;
13062     /*
13063      * This function accepts only SP_NOMOVE and SP_SETPCMARK flags.
13064      * Check to make sure only those flags are set.
13065      * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
13066      * flags cannot be set. Check for that condition also.
13067      */
13068     if (((flags & ~(SP_NOMOVE | SP_SETPCMARK)) != 0) ||
13069 	((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
13070     {
13071 	EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
13072 	goto theend;
13073     }
13074 
13075     pos = save_cursor = curwin->w_cursor;
13076     if (searchit(curwin, curbuf, &pos, dir, pat, 1L,
13077 					      SEARCH_KEEP, RE_SEARCH) != FAIL)
13078     {
13079 	rettv->vval.v_number = pos.lnum;
13080 	if (flags & SP_SETPCMARK)
13081 	    setpcmark();
13082 	curwin->w_cursor = pos;
13083 	/* "/$" will put the cursor after the end of the line, may need to
13084 	 * correct that here */
13085 	check_cursor();
13086     }
13087 
13088     /* If 'n' flag is used: restore cursor position. */
13089     if (flags & SP_NOMOVE)
13090 	curwin->w_cursor = save_cursor;
13091 theend:
13092     p_ws = save_p_ws;
13093 }
13094 
13095 /*
13096  * "searchdecl()" function
13097  */
13098     static void
13099 f_searchdecl(argvars, rettv)
13100     typval_T	*argvars;
13101     typval_T	*rettv;
13102 {
13103     int		locally = 1;
13104     int		thisblock = 0;
13105     int		error = FALSE;
13106     char_u	*name;
13107 
13108     rettv->vval.v_number = 1;	/* default: FAIL */
13109 
13110     name = get_tv_string_chk(&argvars[0]);
13111     if (argvars[1].v_type != VAR_UNKNOWN)
13112     {
13113 	locally = get_tv_number_chk(&argvars[1], &error) == 0;
13114 	if (!error && argvars[2].v_type != VAR_UNKNOWN)
13115 	    thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
13116     }
13117     if (!error && name != NULL)
13118 	rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
13119 				     locally, thisblock, SEARCH_KEEP) == FAIL;
13120 }
13121 
13122 /*
13123  * "searchpair()" function
13124  */
13125     static void
13126 f_searchpair(argvars, rettv)
13127     typval_T	*argvars;
13128     typval_T	*rettv;
13129 {
13130     char_u	*spat, *mpat, *epat;
13131     char_u	*skip;
13132     int		save_p_ws = p_ws;
13133     int		dir;
13134     int		flags = 0;
13135     char_u	nbuf1[NUMBUFLEN];
13136     char_u	nbuf2[NUMBUFLEN];
13137     char_u	nbuf3[NUMBUFLEN];
13138 
13139     rettv->vval.v_number = 0;	/* default: FAIL */
13140 
13141     /* Get the three pattern arguments: start, middle, end. */
13142     spat = get_tv_string_chk(&argvars[0]);
13143     mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
13144     epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
13145     if (spat == NULL || mpat == NULL || epat == NULL)
13146 	goto theend;	    /* type error */
13147 
13148     /* Handle the optional fourth argument: flags */
13149     dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
13150     if (dir == 0)
13151 	goto theend;
13152     /*
13153      * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
13154      */
13155     if ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK))
13156     {
13157 	EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
13158 	goto theend;
13159     }
13160 
13161     /* Optional fifth argument: skip expresion */
13162     if (argvars[3].v_type == VAR_UNKNOWN
13163 	    || argvars[4].v_type == VAR_UNKNOWN)
13164 	skip = (char_u *)"";
13165     else
13166 	skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
13167     if (skip == NULL)
13168 	goto theend;	    /* type error */
13169 
13170     rettv->vval.v_number = do_searchpair(spat, mpat, epat, dir, skip, flags);
13171 
13172 theend:
13173     p_ws = save_p_ws;
13174 }
13175 
13176 /*
13177  * Search for a start/middle/end thing.
13178  * Used by searchpair(), see its documentation for the details.
13179  * Returns 0 or -1 for no match,
13180  */
13181     long
13182 do_searchpair(spat, mpat, epat, dir, skip, flags)
13183     char_u	*spat;	    /* start pattern */
13184     char_u	*mpat;	    /* middle pattern */
13185     char_u	*epat;	    /* end pattern */
13186     int		dir;	    /* BACKWARD or FORWARD */
13187     char_u	*skip;	    /* skip expression */
13188     int		flags;	    /* SP_RETCOUNT, SP_REPEAT, SP_NOMOVE */
13189 {
13190     char_u	*save_cpo;
13191     char_u	*pat, *pat2 = NULL, *pat3 = NULL;
13192     long	retval = 0;
13193     pos_T	pos;
13194     pos_T	firstpos;
13195     pos_T	foundpos;
13196     pos_T	save_cursor;
13197     pos_T	save_pos;
13198     int		n;
13199     int		r;
13200     int		nest = 1;
13201     int		err;
13202 
13203     /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13204     save_cpo = p_cpo;
13205     p_cpo = (char_u *)"";
13206 
13207     /* Make two search patterns: start/end (pat2, for in nested pairs) and
13208      * start/middle/end (pat3, for the top pair). */
13209     pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
13210     pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
13211     if (pat2 == NULL || pat3 == NULL)
13212 	goto theend;
13213     sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
13214     if (*mpat == NUL)
13215 	STRCPY(pat3, pat2);
13216     else
13217 	sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
13218 							    spat, epat, mpat);
13219 
13220     save_cursor = curwin->w_cursor;
13221     pos = curwin->w_cursor;
13222     firstpos.lnum = 0;
13223     foundpos.lnum = 0;
13224     pat = pat3;
13225     for (;;)
13226     {
13227 	n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
13228 						      SEARCH_KEEP, RE_SEARCH);
13229 	if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
13230 	    /* didn't find it or found the first match again: FAIL */
13231 	    break;
13232 
13233 	if (firstpos.lnum == 0)
13234 	    firstpos = pos;
13235 	if (equalpos(pos, foundpos))
13236 	{
13237 	    /* Found the same position again.  Can happen with a pattern that
13238 	     * has "\zs" at the end and searching backwards.  Advance one
13239 	     * character and try again. */
13240 	    if (dir == BACKWARD)
13241 		decl(&pos);
13242 	    else
13243 		incl(&pos);
13244 	}
13245 	foundpos = pos;
13246 
13247 	/* If the skip pattern matches, ignore this match. */
13248 	if (*skip != NUL)
13249 	{
13250 	    save_pos = curwin->w_cursor;
13251 	    curwin->w_cursor = pos;
13252 	    r = eval_to_bool(skip, &err, NULL, FALSE);
13253 	    curwin->w_cursor = save_pos;
13254 	    if (err)
13255 	    {
13256 		/* Evaluating {skip} caused an error, break here. */
13257 		curwin->w_cursor = save_cursor;
13258 		retval = -1;
13259 		break;
13260 	    }
13261 	    if (r)
13262 		continue;
13263 	}
13264 
13265 	if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
13266 	{
13267 	    /* Found end when searching backwards or start when searching
13268 	     * forward: nested pair. */
13269 	    ++nest;
13270 	    pat = pat2;		/* nested, don't search for middle */
13271 	}
13272 	else
13273 	{
13274 	    /* Found end when searching forward or start when searching
13275 	     * backward: end of (nested) pair; or found middle in outer pair. */
13276 	    if (--nest == 1)
13277 		pat = pat3;	/* outer level, search for middle */
13278 	}
13279 
13280 	if (nest == 0)
13281 	{
13282 	    /* Found the match: return matchcount or line number. */
13283 	    if (flags & SP_RETCOUNT)
13284 		++retval;
13285 	    else
13286 		retval = pos.lnum;
13287 	    if (flags & SP_SETPCMARK)
13288 		setpcmark();
13289 	    curwin->w_cursor = pos;
13290 	    if (!(flags & SP_REPEAT))
13291 		break;
13292 	    nest = 1;	    /* search for next unmatched */
13293 	}
13294     }
13295 
13296     /* If 'n' flag is used or search failed: restore cursor position. */
13297     if ((flags & SP_NOMOVE) || retval == 0)
13298 	curwin->w_cursor = save_cursor;
13299 
13300 theend:
13301     vim_free(pat2);
13302     vim_free(pat3);
13303     p_cpo = save_cpo;
13304 
13305     return retval;
13306 }
13307 
13308 /*ARGSUSED*/
13309     static void
13310 f_server2client(argvars, rettv)
13311     typval_T	*argvars;
13312     typval_T	*rettv;
13313 {
13314 #ifdef FEAT_CLIENTSERVER
13315     char_u	buf[NUMBUFLEN];
13316     char_u	*server = get_tv_string_chk(&argvars[0]);
13317     char_u	*reply = get_tv_string_buf_chk(&argvars[1], buf);
13318 
13319     rettv->vval.v_number = -1;
13320     if (server == NULL || reply == NULL)
13321 	return;
13322     if (check_restricted() || check_secure())
13323 	return;
13324 # ifdef FEAT_X11
13325     if (check_connection() == FAIL)
13326 	return;
13327 # endif
13328 
13329     if (serverSendReply(server, reply) < 0)
13330     {
13331 	EMSG(_("E258: Unable to send to client"));
13332 	return;
13333     }
13334     rettv->vval.v_number = 0;
13335 #else
13336     rettv->vval.v_number = -1;
13337 #endif
13338 }
13339 
13340 /*ARGSUSED*/
13341     static void
13342 f_serverlist(argvars, rettv)
13343     typval_T	*argvars;
13344     typval_T	*rettv;
13345 {
13346     char_u	*r = NULL;
13347 
13348 #ifdef FEAT_CLIENTSERVER
13349 # ifdef WIN32
13350     r = serverGetVimNames();
13351 # else
13352     make_connection();
13353     if (X_DISPLAY != NULL)
13354 	r = serverGetVimNames(X_DISPLAY);
13355 # endif
13356 #endif
13357     rettv->v_type = VAR_STRING;
13358     rettv->vval.v_string = r;
13359 }
13360 
13361 /*
13362  * "setbufvar()" function
13363  */
13364 /*ARGSUSED*/
13365     static void
13366 f_setbufvar(argvars, rettv)
13367     typval_T	*argvars;
13368     typval_T	*rettv;
13369 {
13370     buf_T	*buf;
13371 #ifdef FEAT_AUTOCMD
13372     aco_save_T	aco;
13373 #else
13374     buf_T	*save_curbuf;
13375 #endif
13376     char_u	*varname, *bufvarname;
13377     typval_T	*varp;
13378     char_u	nbuf[NUMBUFLEN];
13379 
13380     rettv->vval.v_number = 0;
13381 
13382     if (check_restricted() || check_secure())
13383 	return;
13384     (void)get_tv_number(&argvars[0]);	    /* issue errmsg if type error */
13385     varname = get_tv_string_chk(&argvars[1]);
13386     buf = get_buf_tv(&argvars[0]);
13387     varp = &argvars[2];
13388 
13389     if (buf != NULL && varname != NULL && varp != NULL)
13390     {
13391 	/* set curbuf to be our buf, temporarily */
13392 #ifdef FEAT_AUTOCMD
13393 	aucmd_prepbuf(&aco, buf);
13394 #else
13395 	save_curbuf = curbuf;
13396 	curbuf = buf;
13397 #endif
13398 
13399 	if (*varname == '&')
13400 	{
13401 	    long	numval;
13402 	    char_u	*strval;
13403 	    int		error = FALSE;
13404 
13405 	    ++varname;
13406 	    numval = get_tv_number_chk(varp, &error);
13407 	    strval = get_tv_string_buf_chk(varp, nbuf);
13408 	    if (!error && strval != NULL)
13409 		set_option_value(varname, numval, strval, OPT_LOCAL);
13410 	}
13411 	else
13412 	{
13413 	    bufvarname = alloc((unsigned)STRLEN(varname) + 3);
13414 	    if (bufvarname != NULL)
13415 	    {
13416 		STRCPY(bufvarname, "b:");
13417 		STRCPY(bufvarname + 2, varname);
13418 		set_var(bufvarname, varp, TRUE);
13419 		vim_free(bufvarname);
13420 	    }
13421 	}
13422 
13423 	/* reset notion of buffer */
13424 #ifdef FEAT_AUTOCMD
13425 	aucmd_restbuf(&aco);
13426 #else
13427 	curbuf = save_curbuf;
13428 #endif
13429     }
13430 }
13431 
13432 /*
13433  * "setcmdpos()" function
13434  */
13435     static void
13436 f_setcmdpos(argvars, rettv)
13437     typval_T	*argvars;
13438     typval_T	*rettv;
13439 {
13440     int		pos = (int)get_tv_number(&argvars[0]) - 1;
13441 
13442     if (pos >= 0)
13443 	rettv->vval.v_number = set_cmdline_pos(pos);
13444 }
13445 
13446 /*
13447  * "setline()" function
13448  */
13449     static void
13450 f_setline(argvars, rettv)
13451     typval_T	*argvars;
13452     typval_T	*rettv;
13453 {
13454     linenr_T	lnum;
13455     char_u	*line = NULL;
13456     list_T	*l = NULL;
13457     listitem_T	*li = NULL;
13458     long	added = 0;
13459     linenr_T	lcount = curbuf->b_ml.ml_line_count;
13460 
13461     lnum = get_tv_lnum(&argvars[0]);
13462     if (argvars[1].v_type == VAR_LIST)
13463     {
13464 	l = argvars[1].vval.v_list;
13465 	li = l->lv_first;
13466     }
13467     else
13468 	line = get_tv_string_chk(&argvars[1]);
13469 
13470     rettv->vval.v_number = 0;		/* OK */
13471     for (;;)
13472     {
13473 	if (l != NULL)
13474 	{
13475 	    /* list argument, get next string */
13476 	    if (li == NULL)
13477 		break;
13478 	    line = get_tv_string_chk(&li->li_tv);
13479 	    li = li->li_next;
13480 	}
13481 
13482 	rettv->vval.v_number = 1;	/* FAIL */
13483 	if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
13484 	    break;
13485 	if (lnum <= curbuf->b_ml.ml_line_count)
13486 	{
13487 	    /* existing line, replace it */
13488 	    if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
13489 	    {
13490 		changed_bytes(lnum, 0);
13491 		check_cursor_col();
13492 		rettv->vval.v_number = 0;	/* OK */
13493 	    }
13494 	}
13495 	else if (added > 0 || u_save(lnum - 1, lnum) == OK)
13496 	{
13497 	    /* lnum is one past the last line, append the line */
13498 	    ++added;
13499 	    if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
13500 		rettv->vval.v_number = 0;	/* OK */
13501 	}
13502 
13503 	if (l == NULL)			/* only one string argument */
13504 	    break;
13505 	++lnum;
13506     }
13507 
13508     if (added > 0)
13509 	appended_lines_mark(lcount, added);
13510 }
13511 
13512 /*
13513  * "setqflist()" function
13514  */
13515 /*ARGSUSED*/
13516     static void
13517 f_setqflist(argvars, rettv)
13518     typval_T	*argvars;
13519     typval_T	*rettv;
13520 {
13521     char_u	*act;
13522     int		action = ' ';
13523 
13524     rettv->vval.v_number = -1;
13525 
13526 #ifdef FEAT_QUICKFIX
13527     if (argvars[0].v_type != VAR_LIST)
13528 	EMSG(_(e_listreq));
13529     else
13530     {
13531 	list_T  *l = argvars[0].vval.v_list;
13532 
13533 	if (argvars[1].v_type == VAR_STRING)
13534 	{
13535 	    act = get_tv_string_chk(&argvars[1]);
13536 	    if (act == NULL)
13537 		return;		/* type error; errmsg already given */
13538 	    if (*act == 'a' || *act == 'r')
13539 		action = *act;
13540 	}
13541 
13542 	if (l != NULL && set_errorlist(l, action) == OK)
13543 	    rettv->vval.v_number = 0;
13544     }
13545 #endif
13546 }
13547 
13548 /*
13549  * "setreg()" function
13550  */
13551     static void
13552 f_setreg(argvars, rettv)
13553     typval_T	*argvars;
13554     typval_T	*rettv;
13555 {
13556     int		regname;
13557     char_u	*strregname;
13558     char_u	*stropt;
13559     char_u	*strval;
13560     int		append;
13561     char_u	yank_type;
13562     long	block_len;
13563 
13564     block_len = -1;
13565     yank_type = MAUTO;
13566     append = FALSE;
13567 
13568     strregname = get_tv_string_chk(argvars);
13569     rettv->vval.v_number = 1;		/* FAIL is default */
13570 
13571     if (strregname == NULL)
13572 	return;		/* type error; errmsg already given */
13573     regname = *strregname;
13574     if (regname == 0 || regname == '@')
13575 	regname = '"';
13576     else if (regname == '=')
13577 	return;
13578 
13579     if (argvars[2].v_type != VAR_UNKNOWN)
13580     {
13581 	stropt = get_tv_string_chk(&argvars[2]);
13582 	if (stropt == NULL)
13583 	    return;		/* type error */
13584 	for (; *stropt != NUL; ++stropt)
13585 	    switch (*stropt)
13586 	    {
13587 		case 'a': case 'A':	/* append */
13588 		    append = TRUE;
13589 		    break;
13590 		case 'v': case 'c':	/* character-wise selection */
13591 		    yank_type = MCHAR;
13592 		    break;
13593 		case 'V': case 'l':	/* line-wise selection */
13594 		    yank_type = MLINE;
13595 		    break;
13596 #ifdef FEAT_VISUAL
13597 		case 'b': case Ctrl_V:	/* block-wise selection */
13598 		    yank_type = MBLOCK;
13599 		    if (VIM_ISDIGIT(stropt[1]))
13600 		    {
13601 			++stropt;
13602 			block_len = getdigits(&stropt) - 1;
13603 			--stropt;
13604 		    }
13605 		    break;
13606 #endif
13607 	    }
13608     }
13609 
13610     strval = get_tv_string_chk(&argvars[1]);
13611     if (strval != NULL)
13612 	write_reg_contents_ex(regname, strval, -1,
13613 						append, yank_type, block_len);
13614     rettv->vval.v_number = 0;
13615 }
13616 
13617 
13618 /*
13619  * "setwinvar(expr)" function
13620  */
13621 /*ARGSUSED*/
13622     static void
13623 f_setwinvar(argvars, rettv)
13624     typval_T	*argvars;
13625     typval_T	*rettv;
13626 {
13627     win_T	*win;
13628 #ifdef FEAT_WINDOWS
13629     win_T	*save_curwin;
13630 #endif
13631     char_u	*varname, *winvarname;
13632     typval_T	*varp;
13633     char_u	nbuf[NUMBUFLEN];
13634 
13635     rettv->vval.v_number = 0;
13636 
13637     if (check_restricted() || check_secure())
13638 	return;
13639     win = find_win_by_nr(&argvars[0]);
13640     varname = get_tv_string_chk(&argvars[1]);
13641     varp = &argvars[2];
13642 
13643     if (win != NULL && varname != NULL && varp != NULL)
13644     {
13645 #ifdef FEAT_WINDOWS
13646 	/* set curwin to be our win, temporarily */
13647 	save_curwin = curwin;
13648 	curwin = win;
13649 	curbuf = curwin->w_buffer;
13650 #endif
13651 
13652 	if (*varname == '&')
13653 	{
13654 	    long	numval;
13655 	    char_u	*strval;
13656 	    int		error = FALSE;
13657 
13658 	    ++varname;
13659 	    numval = get_tv_number_chk(varp, &error);
13660 	    strval = get_tv_string_buf_chk(varp, nbuf);
13661 	    if (!error && strval != NULL)
13662 		set_option_value(varname, numval, strval, OPT_LOCAL);
13663 	}
13664 	else
13665 	{
13666 	    winvarname = alloc((unsigned)STRLEN(varname) + 3);
13667 	    if (winvarname != NULL)
13668 	    {
13669 		STRCPY(winvarname, "w:");
13670 		STRCPY(winvarname + 2, varname);
13671 		set_var(winvarname, varp, TRUE);
13672 		vim_free(winvarname);
13673 	    }
13674 	}
13675 
13676 #ifdef FEAT_WINDOWS
13677 	/* Restore current window, if it's still valid (autocomands can make
13678 	 * it invalid). */
13679 	if (win_valid(save_curwin))
13680 	{
13681 	    curwin = save_curwin;
13682 	    curbuf = curwin->w_buffer;
13683 	}
13684 #endif
13685     }
13686 }
13687 
13688 /*
13689  * "simplify()" function
13690  */
13691     static void
13692 f_simplify(argvars, rettv)
13693     typval_T	*argvars;
13694     typval_T	*rettv;
13695 {
13696     char_u	*p;
13697 
13698     p = get_tv_string(&argvars[0]);
13699     rettv->vval.v_string = vim_strsave(p);
13700     simplify_filename(rettv->vval.v_string);	/* simplify in place */
13701     rettv->v_type = VAR_STRING;
13702 }
13703 
13704 static int
13705 #ifdef __BORLANDC__
13706     _RTLENTRYF
13707 #endif
13708 	item_compare __ARGS((const void *s1, const void *s2));
13709 static int
13710 #ifdef __BORLANDC__
13711     _RTLENTRYF
13712 #endif
13713 	item_compare2 __ARGS((const void *s1, const void *s2));
13714 
13715 static int	item_compare_ic;
13716 static char_u	*item_compare_func;
13717 static int	item_compare_func_err;
13718 #define ITEM_COMPARE_FAIL 999
13719 
13720 /*
13721  * Compare functions for f_sort() below.
13722  */
13723     static int
13724 #ifdef __BORLANDC__
13725 _RTLENTRYF
13726 #endif
13727 item_compare(s1, s2)
13728     const void	*s1;
13729     const void	*s2;
13730 {
13731     char_u	*p1, *p2;
13732     char_u	*tofree1, *tofree2;
13733     int		res;
13734     char_u	numbuf1[NUMBUFLEN];
13735     char_u	numbuf2[NUMBUFLEN];
13736 
13737     p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1);
13738     p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2);
13739     if (item_compare_ic)
13740 	res = STRICMP(p1, p2);
13741     else
13742 	res = STRCMP(p1, p2);
13743     vim_free(tofree1);
13744     vim_free(tofree2);
13745     return res;
13746 }
13747 
13748     static int
13749 #ifdef __BORLANDC__
13750 _RTLENTRYF
13751 #endif
13752 item_compare2(s1, s2)
13753     const void	*s1;
13754     const void	*s2;
13755 {
13756     int		res;
13757     typval_T	rettv;
13758     typval_T	argv[2];
13759     int		dummy;
13760 
13761     /* shortcut after failure in previous call; compare all items equal */
13762     if (item_compare_func_err)
13763 	return 0;
13764 
13765     /* copy the values.  This is needed to be able to set v_lock to VAR_FIXED
13766      * in the copy without changing the original list items. */
13767     copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
13768     copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
13769 
13770     rettv.v_type = VAR_UNKNOWN;		/* clear_tv() uses this */
13771     res = call_func(item_compare_func, STRLEN(item_compare_func),
13772 				 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
13773     clear_tv(&argv[0]);
13774     clear_tv(&argv[1]);
13775 
13776     if (res == FAIL)
13777 	res = ITEM_COMPARE_FAIL;
13778     else
13779 	/* return value has wrong type */
13780 	res = get_tv_number_chk(&rettv, &item_compare_func_err);
13781     if (item_compare_func_err)
13782 	res = ITEM_COMPARE_FAIL;
13783     clear_tv(&rettv);
13784     return res;
13785 }
13786 
13787 /*
13788  * "sort({list})" function
13789  */
13790     static void
13791 f_sort(argvars, rettv)
13792     typval_T	*argvars;
13793     typval_T	*rettv;
13794 {
13795     list_T	*l;
13796     listitem_T	*li;
13797     listitem_T	**ptrs;
13798     long	len;
13799     long	i;
13800 
13801     rettv->vval.v_number = 0;
13802     if (argvars[0].v_type != VAR_LIST)
13803 	EMSG2(_(e_listarg), "sort()");
13804     else
13805     {
13806 	l = argvars[0].vval.v_list;
13807 	if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
13808 	    return;
13809 	rettv->vval.v_list = l;
13810 	rettv->v_type = VAR_LIST;
13811 	++l->lv_refcount;
13812 
13813 	len = list_len(l);
13814 	if (len <= 1)
13815 	    return;	/* short list sorts pretty quickly */
13816 
13817 	item_compare_ic = FALSE;
13818 	item_compare_func = NULL;
13819 	if (argvars[1].v_type != VAR_UNKNOWN)
13820 	{
13821 	    if (argvars[1].v_type == VAR_FUNC)
13822 		item_compare_func = argvars[1].vval.v_string;
13823 	    else
13824 	    {
13825 		int	    error = FALSE;
13826 
13827 		i = get_tv_number_chk(&argvars[1], &error);
13828 		if (error)
13829 		    return;		/* type error; errmsg already given */
13830 		if (i == 1)
13831 		    item_compare_ic = TRUE;
13832 		else
13833 		    item_compare_func = get_tv_string(&argvars[1]);
13834 	    }
13835 	}
13836 
13837 	/* Make an array with each entry pointing to an item in the List. */
13838 	ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
13839 	if (ptrs == NULL)
13840 	    return;
13841 	i = 0;
13842 	for (li = l->lv_first; li != NULL; li = li->li_next)
13843 	    ptrs[i++] = li;
13844 
13845 	item_compare_func_err = FALSE;
13846 	/* test the compare function */
13847 	if (item_compare_func != NULL
13848 		&& item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
13849 							 == ITEM_COMPARE_FAIL)
13850 	    EMSG(_("E702: Sort compare function failed"));
13851 	else
13852 	{
13853 	    /* Sort the array with item pointers. */
13854 	    qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
13855 		    item_compare_func == NULL ? item_compare : item_compare2);
13856 
13857 	    if (!item_compare_func_err)
13858 	    {
13859 		/* Clear the List and append the items in the sorted order. */
13860 		l->lv_first = l->lv_last = NULL;
13861 		l->lv_len = 0;
13862 		for (i = 0; i < len; ++i)
13863 		    list_append(l, ptrs[i]);
13864 	    }
13865 	}
13866 
13867 	vim_free(ptrs);
13868     }
13869 }
13870 
13871 /*
13872  * "soundfold({word})" function
13873  */
13874     static void
13875 f_soundfold(argvars, rettv)
13876     typval_T	*argvars;
13877     typval_T	*rettv;
13878 {
13879     char_u	*s;
13880 
13881     rettv->v_type = VAR_STRING;
13882     s = get_tv_string(&argvars[0]);
13883 #ifdef FEAT_SYN_HL
13884     rettv->vval.v_string = eval_soundfold(s);
13885 #else
13886     rettv->vval.v_string = vim_strsave(s);
13887 #endif
13888 }
13889 
13890 /*
13891  * "spellbadword()" function
13892  */
13893 /* ARGSUSED */
13894     static void
13895 f_spellbadword(argvars, rettv)
13896     typval_T	*argvars;
13897     typval_T	*rettv;
13898 {
13899     char_u	*word = (char_u *)"";
13900 #ifdef FEAT_SYN_HL
13901     int		len = 0;
13902     hlf_T	attr = HLF_COUNT;
13903     list_T	*l;
13904 #endif
13905 
13906     l = list_alloc();
13907     if (l == NULL)
13908 	return;
13909     rettv->v_type = VAR_LIST;
13910     rettv->vval.v_list = l;
13911     ++l->lv_refcount;
13912 
13913 #ifdef FEAT_SYN_HL
13914     if (argvars[0].v_type == VAR_UNKNOWN)
13915     {
13916 	/* Find the start and length of the badly spelled word. */
13917 	len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
13918 	if (len != 0)
13919 	    word = ml_get_cursor();
13920     }
13921     else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
13922     {
13923 	char_u	*str = get_tv_string_chk(&argvars[0]);
13924 	int	capcol = -1;
13925 
13926 	if (str != NULL)
13927 	{
13928 	    /* Check the argument for spelling. */
13929 	    while (*str != NUL)
13930 	    {
13931 		len = spell_check(curwin, str, &attr, &capcol, FALSE);
13932 		if (attr != HLF_COUNT)
13933 		{
13934 		    word = str;
13935 		    break;
13936 		}
13937 		str += len;
13938 	    }
13939 	}
13940     }
13941 #endif
13942 
13943     list_append_string(l, word, len);
13944     list_append_string(l, (char_u *)(
13945 			attr == HLF_SPB ? "bad" :
13946 			attr == HLF_SPR ? "rare" :
13947 			attr == HLF_SPL ? "local" :
13948 			attr == HLF_SPC ? "caps" :
13949 			""), -1);
13950 }
13951 
13952 /*
13953  * "spellsuggest()" function
13954  */
13955     static void
13956 f_spellsuggest(argvars, rettv)
13957     typval_T	*argvars;
13958     typval_T	*rettv;
13959 {
13960     list_T	*l;
13961 #ifdef FEAT_SYN_HL
13962     char_u	*str;
13963     int		typeerr = FALSE;
13964     int		maxcount;
13965     garray_T	ga;
13966     int		i;
13967     listitem_T	*li;
13968     int		need_capital = FALSE;
13969 #endif
13970 
13971     l = list_alloc();
13972     if (l == NULL)
13973 	return;
13974     rettv->v_type = VAR_LIST;
13975     rettv->vval.v_list = l;
13976     ++l->lv_refcount;
13977 
13978 #ifdef FEAT_SYN_HL
13979     if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
13980     {
13981 	str = get_tv_string(&argvars[0]);
13982 	if (argvars[1].v_type != VAR_UNKNOWN)
13983 	{
13984 	    maxcount = get_tv_number_chk(&argvars[1], &typeerr);
13985 	    if (maxcount <= 0)
13986 		return;
13987 	    if (argvars[2].v_type != VAR_UNKNOWN)
13988 	    {
13989 		need_capital = get_tv_number_chk(&argvars[2], &typeerr);
13990 		if (typeerr)
13991 		    return;
13992 	    }
13993 	}
13994 	else
13995 	    maxcount = 25;
13996 
13997 	spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
13998 
13999 	for (i = 0; i < ga.ga_len; ++i)
14000 	{
14001 	    str = ((char_u **)ga.ga_data)[i];
14002 
14003 	    li = listitem_alloc();
14004 	    if (li == NULL)
14005 		vim_free(str);
14006 	    else
14007 	    {
14008 		li->li_tv.v_type = VAR_STRING;
14009 		li->li_tv.v_lock = 0;
14010 		li->li_tv.vval.v_string = str;
14011 		list_append(l, li);
14012 	    }
14013 	}
14014 	ga_clear(&ga);
14015     }
14016 #endif
14017 }
14018 
14019     static void
14020 f_split(argvars, rettv)
14021     typval_T	*argvars;
14022     typval_T	*rettv;
14023 {
14024     char_u	*str;
14025     char_u	*end;
14026     char_u	*pat = NULL;
14027     regmatch_T	regmatch;
14028     char_u	patbuf[NUMBUFLEN];
14029     char_u	*save_cpo;
14030     int		match;
14031     list_T	*l;
14032     colnr_T	col = 0;
14033     int		keepempty = FALSE;
14034     int		typeerr = FALSE;
14035 
14036     /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14037     save_cpo = p_cpo;
14038     p_cpo = (char_u *)"";
14039 
14040     str = get_tv_string(&argvars[0]);
14041     if (argvars[1].v_type != VAR_UNKNOWN)
14042     {
14043 	pat = get_tv_string_buf_chk(&argvars[1], patbuf);
14044 	if (pat == NULL)
14045 	    typeerr = TRUE;
14046 	if (argvars[2].v_type != VAR_UNKNOWN)
14047 	    keepempty = get_tv_number_chk(&argvars[2], &typeerr);
14048     }
14049     if (pat == NULL || *pat == NUL)
14050 	pat = (char_u *)"[\\x01- ]\\+";
14051 
14052     l = list_alloc();
14053     if (l == NULL)
14054 	return;
14055     rettv->v_type = VAR_LIST;
14056     rettv->vval.v_list = l;
14057     ++l->lv_refcount;
14058     if (typeerr)
14059 	return;
14060 
14061     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
14062     if (regmatch.regprog != NULL)
14063     {
14064 	regmatch.rm_ic = FALSE;
14065 	while (*str != NUL || keepempty)
14066 	{
14067 	    if (*str == NUL)
14068 		match = FALSE;	/* empty item at the end */
14069 	    else
14070 		match = vim_regexec_nl(&regmatch, str, col);
14071 	    if (match)
14072 		end = regmatch.startp[0];
14073 	    else
14074 		end = str + STRLEN(str);
14075 	    if (keepempty || end > str || (l->lv_len > 0 && *str != NUL
14076 					  && match && end < regmatch.endp[0]))
14077 	    {
14078 		if (list_append_string(l, str, (int)(end - str)) == FAIL)
14079 		    break;
14080 	    }
14081 	    if (!match)
14082 		break;
14083 	    /* Advance to just after the match. */
14084 	    if (regmatch.endp[0] > str)
14085 		col = 0;
14086 	    else
14087 	    {
14088 		/* Don't get stuck at the same match. */
14089 #ifdef FEAT_MBYTE
14090 		col = (*mb_ptr2len)(regmatch.endp[0]);
14091 #else
14092 		col = 1;
14093 #endif
14094 	    }
14095 	    str = regmatch.endp[0];
14096 	}
14097 
14098 	vim_free(regmatch.regprog);
14099     }
14100 
14101     p_cpo = save_cpo;
14102 }
14103 
14104 #ifdef HAVE_STRFTIME
14105 /*
14106  * "strftime({format}[, {time}])" function
14107  */
14108     static void
14109 f_strftime(argvars, rettv)
14110     typval_T	*argvars;
14111     typval_T	*rettv;
14112 {
14113     char_u	result_buf[256];
14114     struct tm	*curtime;
14115     time_t	seconds;
14116     char_u	*p;
14117 
14118     rettv->v_type = VAR_STRING;
14119 
14120     p = get_tv_string(&argvars[0]);
14121     if (argvars[1].v_type == VAR_UNKNOWN)
14122 	seconds = time(NULL);
14123     else
14124 	seconds = (time_t)get_tv_number(&argvars[1]);
14125     curtime = localtime(&seconds);
14126     /* MSVC returns NULL for an invalid value of seconds. */
14127     if (curtime == NULL)
14128 	rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
14129     else
14130     {
14131 # ifdef FEAT_MBYTE
14132 	vimconv_T   conv;
14133 	char_u	    *enc;
14134 
14135 	conv.vc_type = CONV_NONE;
14136 	enc = enc_locale();
14137 	convert_setup(&conv, p_enc, enc);
14138 	if (conv.vc_type != CONV_NONE)
14139 	    p = string_convert(&conv, p, NULL);
14140 # endif
14141 	if (p != NULL)
14142 	    (void)strftime((char *)result_buf, sizeof(result_buf),
14143 							  (char *)p, curtime);
14144 	else
14145 	    result_buf[0] = NUL;
14146 
14147 # ifdef FEAT_MBYTE
14148 	if (conv.vc_type != CONV_NONE)
14149 	    vim_free(p);
14150 	convert_setup(&conv, enc, p_enc);
14151 	if (conv.vc_type != CONV_NONE)
14152 	    rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
14153 	else
14154 # endif
14155 	    rettv->vval.v_string = vim_strsave(result_buf);
14156 
14157 # ifdef FEAT_MBYTE
14158 	/* Release conversion descriptors */
14159 	convert_setup(&conv, NULL, NULL);
14160 	vim_free(enc);
14161 # endif
14162     }
14163 }
14164 #endif
14165 
14166 /*
14167  * "stridx()" function
14168  */
14169     static void
14170 f_stridx(argvars, rettv)
14171     typval_T	*argvars;
14172     typval_T	*rettv;
14173 {
14174     char_u	buf[NUMBUFLEN];
14175     char_u	*needle;
14176     char_u	*haystack;
14177     char_u	*save_haystack;
14178     char_u	*pos;
14179     int		start_idx;
14180 
14181     needle = get_tv_string_chk(&argvars[1]);
14182     save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
14183     rettv->vval.v_number = -1;
14184     if (needle == NULL || haystack == NULL)
14185 	return;		/* type error; errmsg already given */
14186 
14187     if (argvars[2].v_type != VAR_UNKNOWN)
14188     {
14189 	int	    error = FALSE;
14190 
14191 	start_idx = get_tv_number_chk(&argvars[2], &error);
14192 	if (error || start_idx >= (int)STRLEN(haystack))
14193 	    return;
14194 	if (start_idx >= 0)
14195 	    haystack += start_idx;
14196     }
14197 
14198     pos	= (char_u *)strstr((char *)haystack, (char *)needle);
14199     if (pos != NULL)
14200 	rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
14201 }
14202 
14203 /*
14204  * "string()" function
14205  */
14206     static void
14207 f_string(argvars, rettv)
14208     typval_T	*argvars;
14209     typval_T	*rettv;
14210 {
14211     char_u	*tofree;
14212     char_u	numbuf[NUMBUFLEN];
14213 
14214     rettv->v_type = VAR_STRING;
14215     rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf);
14216     if (tofree == NULL)
14217 	rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
14218 }
14219 
14220 /*
14221  * "strlen()" function
14222  */
14223     static void
14224 f_strlen(argvars, rettv)
14225     typval_T	*argvars;
14226     typval_T	*rettv;
14227 {
14228     rettv->vval.v_number = (varnumber_T)(STRLEN(
14229 					      get_tv_string(&argvars[0])));
14230 }
14231 
14232 /*
14233  * "strpart()" function
14234  */
14235     static void
14236 f_strpart(argvars, rettv)
14237     typval_T	*argvars;
14238     typval_T	*rettv;
14239 {
14240     char_u	*p;
14241     int		n;
14242     int		len;
14243     int		slen;
14244     int		error = FALSE;
14245 
14246     p = get_tv_string(&argvars[0]);
14247     slen = (int)STRLEN(p);
14248 
14249     n = get_tv_number_chk(&argvars[1], &error);
14250     if (error)
14251 	len = 0;
14252     else if (argvars[2].v_type != VAR_UNKNOWN)
14253 	len = get_tv_number(&argvars[2]);
14254     else
14255 	len = slen - n;	    /* default len: all bytes that are available. */
14256 
14257     /*
14258      * Only return the overlap between the specified part and the actual
14259      * string.
14260      */
14261     if (n < 0)
14262     {
14263 	len += n;
14264 	n = 0;
14265     }
14266     else if (n > slen)
14267 	n = slen;
14268     if (len < 0)
14269 	len = 0;
14270     else if (n + len > slen)
14271 	len = slen - n;
14272 
14273     rettv->v_type = VAR_STRING;
14274     rettv->vval.v_string = vim_strnsave(p + n, len);
14275 }
14276 
14277 /*
14278  * "strridx()" function
14279  */
14280     static void
14281 f_strridx(argvars, rettv)
14282     typval_T	*argvars;
14283     typval_T	*rettv;
14284 {
14285     char_u	buf[NUMBUFLEN];
14286     char_u	*needle;
14287     char_u	*haystack;
14288     char_u	*rest;
14289     char_u	*lastmatch = NULL;
14290     int		haystack_len, end_idx;
14291 
14292     needle = get_tv_string_chk(&argvars[1]);
14293     haystack = get_tv_string_buf_chk(&argvars[0], buf);
14294     haystack_len = STRLEN(haystack);
14295 
14296     rettv->vval.v_number = -1;
14297     if (needle == NULL || haystack == NULL)
14298 	return;		/* type error; errmsg already given */
14299     if (argvars[2].v_type != VAR_UNKNOWN)
14300     {
14301 	/* Third argument: upper limit for index */
14302 	end_idx = get_tv_number_chk(&argvars[2], NULL);
14303 	if (end_idx < 0)
14304 	    return;	/* can never find a match */
14305     }
14306     else
14307 	end_idx = haystack_len;
14308 
14309     if (*needle == NUL)
14310     {
14311 	/* Empty string matches past the end. */
14312 	lastmatch = haystack + end_idx;
14313     }
14314     else
14315     {
14316 	for (rest = haystack; *rest != '\0'; ++rest)
14317 	{
14318 	    rest = (char_u *)strstr((char *)rest, (char *)needle);
14319 	    if (rest == NULL || rest > haystack + end_idx)
14320 		break;
14321 	    lastmatch = rest;
14322 	}
14323     }
14324 
14325     if (lastmatch == NULL)
14326 	rettv->vval.v_number = -1;
14327     else
14328 	rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
14329 }
14330 
14331 /*
14332  * "strtrans()" function
14333  */
14334     static void
14335 f_strtrans(argvars, rettv)
14336     typval_T	*argvars;
14337     typval_T	*rettv;
14338 {
14339     rettv->v_type = VAR_STRING;
14340     rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
14341 }
14342 
14343 /*
14344  * "submatch()" function
14345  */
14346     static void
14347 f_submatch(argvars, rettv)
14348     typval_T	*argvars;
14349     typval_T	*rettv;
14350 {
14351     rettv->v_type = VAR_STRING;
14352     rettv->vval.v_string =
14353 		    reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
14354 }
14355 
14356 /*
14357  * "substitute()" function
14358  */
14359     static void
14360 f_substitute(argvars, rettv)
14361     typval_T	*argvars;
14362     typval_T	*rettv;
14363 {
14364     char_u	patbuf[NUMBUFLEN];
14365     char_u	subbuf[NUMBUFLEN];
14366     char_u	flagsbuf[NUMBUFLEN];
14367 
14368     char_u	*str = get_tv_string_chk(&argvars[0]);
14369     char_u	*pat = get_tv_string_buf_chk(&argvars[1], patbuf);
14370     char_u	*sub = get_tv_string_buf_chk(&argvars[2], subbuf);
14371     char_u	*flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
14372 
14373     rettv->v_type = VAR_STRING;
14374     if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
14375 	rettv->vval.v_string = NULL;
14376     else
14377 	rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
14378 }
14379 
14380 /*
14381  * "synID(lnum, col, trans)" function
14382  */
14383 /*ARGSUSED*/
14384     static void
14385 f_synID(argvars, rettv)
14386     typval_T	*argvars;
14387     typval_T	*rettv;
14388 {
14389     int		id = 0;
14390 #ifdef FEAT_SYN_HL
14391     long	lnum;
14392     long	col;
14393     int		trans;
14394     int		transerr = FALSE;
14395 
14396     lnum = get_tv_lnum(argvars);		/* -1 on type error */
14397     col = get_tv_number(&argvars[1]) - 1;	/* -1 on type error */
14398     trans = get_tv_number_chk(&argvars[2], &transerr);
14399 
14400     if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
14401 	    && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
14402 	id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL);
14403 #endif
14404 
14405     rettv->vval.v_number = id;
14406 }
14407 
14408 /*
14409  * "synIDattr(id, what [, mode])" function
14410  */
14411 /*ARGSUSED*/
14412     static void
14413 f_synIDattr(argvars, rettv)
14414     typval_T	*argvars;
14415     typval_T	*rettv;
14416 {
14417     char_u	*p = NULL;
14418 #ifdef FEAT_SYN_HL
14419     int		id;
14420     char_u	*what;
14421     char_u	*mode;
14422     char_u	modebuf[NUMBUFLEN];
14423     int		modec;
14424 
14425     id = get_tv_number(&argvars[0]);
14426     what = get_tv_string(&argvars[1]);
14427     if (argvars[2].v_type != VAR_UNKNOWN)
14428     {
14429 	mode = get_tv_string_buf(&argvars[2], modebuf);
14430 	modec = TOLOWER_ASC(mode[0]);
14431 	if (modec != 't' && modec != 'c'
14432 #ifdef FEAT_GUI
14433 		&& modec != 'g'
14434 #endif
14435 		)
14436 	    modec = 0;	/* replace invalid with current */
14437     }
14438     else
14439     {
14440 #ifdef FEAT_GUI
14441 	if (gui.in_use)
14442 	    modec = 'g';
14443 	else
14444 #endif
14445 	    if (t_colors > 1)
14446 	    modec = 'c';
14447 	else
14448 	    modec = 't';
14449     }
14450 
14451 
14452     switch (TOLOWER_ASC(what[0]))
14453     {
14454 	case 'b':
14455 		if (TOLOWER_ASC(what[1]) == 'g')	/* bg[#] */
14456 		    p = highlight_color(id, what, modec);
14457 		else					/* bold */
14458 		    p = highlight_has_attr(id, HL_BOLD, modec);
14459 		break;
14460 
14461 	case 'f':					/* fg[#] */
14462 		p = highlight_color(id, what, modec);
14463 		break;
14464 
14465 	case 'i':
14466 		if (TOLOWER_ASC(what[1]) == 'n')	/* inverse */
14467 		    p = highlight_has_attr(id, HL_INVERSE, modec);
14468 		else					/* italic */
14469 		    p = highlight_has_attr(id, HL_ITALIC, modec);
14470 		break;
14471 
14472 	case 'n':					/* name */
14473 		p = get_highlight_name(NULL, id - 1);
14474 		break;
14475 
14476 	case 'r':					/* reverse */
14477 		p = highlight_has_attr(id, HL_INVERSE, modec);
14478 		break;
14479 
14480 	case 's':					/* standout */
14481 		p = highlight_has_attr(id, HL_STANDOUT, modec);
14482 		break;
14483 
14484 	case 'u':
14485 		if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
14486 							/* underline */
14487 		    p = highlight_has_attr(id, HL_UNDERLINE, modec);
14488 		else
14489 							/* undercurl */
14490 		    p = highlight_has_attr(id, HL_UNDERCURL, modec);
14491 		break;
14492     }
14493 
14494     if (p != NULL)
14495 	p = vim_strsave(p);
14496 #endif
14497     rettv->v_type = VAR_STRING;
14498     rettv->vval.v_string = p;
14499 }
14500 
14501 /*
14502  * "synIDtrans(id)" function
14503  */
14504 /*ARGSUSED*/
14505     static void
14506 f_synIDtrans(argvars, rettv)
14507     typval_T	*argvars;
14508     typval_T	*rettv;
14509 {
14510     int		id;
14511 
14512 #ifdef FEAT_SYN_HL
14513     id = get_tv_number(&argvars[0]);
14514 
14515     if (id > 0)
14516 	id = syn_get_final_id(id);
14517     else
14518 #endif
14519 	id = 0;
14520 
14521     rettv->vval.v_number = id;
14522 }
14523 
14524 /*
14525  * "system()" function
14526  */
14527     static void
14528 f_system(argvars, rettv)
14529     typval_T	*argvars;
14530     typval_T	*rettv;
14531 {
14532     char_u	*res = NULL;
14533     char_u	*p;
14534     char_u	*infile = NULL;
14535     char_u	buf[NUMBUFLEN];
14536     int		err = FALSE;
14537     FILE	*fd;
14538 
14539     if (argvars[1].v_type != VAR_UNKNOWN)
14540     {
14541 	/*
14542 	 * Write the string to a temp file, to be used for input of the shell
14543 	 * command.
14544 	 */
14545 	if ((infile = vim_tempname('i')) == NULL)
14546 	{
14547 	    EMSG(_(e_notmp));
14548 	    return;
14549 	}
14550 
14551 	fd = mch_fopen((char *)infile, WRITEBIN);
14552 	if (fd == NULL)
14553 	{
14554 	    EMSG2(_(e_notopen), infile);
14555 	    goto done;
14556 	}
14557 	p = get_tv_string_buf_chk(&argvars[1], buf);
14558 	if (p == NULL)
14559 	    goto done;		/* type error; errmsg already given */
14560 	if (fwrite(p, STRLEN(p), 1, fd) != 1)
14561 	    err = TRUE;
14562 	if (fclose(fd) != 0)
14563 	    err = TRUE;
14564 	if (err)
14565 	{
14566 	    EMSG(_("E677: Error writing temp file"));
14567 	    goto done;
14568 	}
14569     }
14570 
14571     res = get_cmd_output(get_tv_string(&argvars[0]), infile, SHELL_SILENT);
14572 
14573 #ifdef USE_CR
14574     /* translate <CR> into <NL> */
14575     if (res != NULL)
14576     {
14577 	char_u	*s;
14578 
14579 	for (s = res; *s; ++s)
14580 	{
14581 	    if (*s == CAR)
14582 		*s = NL;
14583 	}
14584     }
14585 #else
14586 # ifdef USE_CRNL
14587     /* translate <CR><NL> into <NL> */
14588     if (res != NULL)
14589     {
14590 	char_u	*s, *d;
14591 
14592 	d = res;
14593 	for (s = res; *s; ++s)
14594 	{
14595 	    if (s[0] == CAR && s[1] == NL)
14596 		++s;
14597 	    *d++ = *s;
14598 	}
14599 	*d = NUL;
14600     }
14601 # endif
14602 #endif
14603 
14604 done:
14605     if (infile != NULL)
14606     {
14607 	mch_remove(infile);
14608 	vim_free(infile);
14609     }
14610     rettv->v_type = VAR_STRING;
14611     rettv->vval.v_string = res;
14612 }
14613 
14614 /*
14615  * "tagfiles()" function
14616  */
14617 /*ARGSUSED*/
14618     static void
14619 f_tagfiles(argvars, rettv)
14620     typval_T	*argvars;
14621     typval_T	*rettv;
14622 {
14623     char_u	fname[MAXPATHL + 1];
14624     list_T	*l;
14625 
14626     l = list_alloc();
14627     if (l == NULL)
14628     {
14629 	rettv->vval.v_number = 0;
14630 	return;
14631     }
14632     rettv->vval.v_list = l;
14633     rettv->v_type = VAR_LIST;
14634     ++l->lv_refcount;
14635 
14636     get_tagfname(TRUE, NULL);
14637     for (;;)
14638 	if (get_tagfname(FALSE, fname) == FAIL
14639 		|| list_append_string(l, fname, -1) == FAIL)
14640 	    break;
14641 }
14642 
14643 /*
14644  * "taglist()" function
14645  */
14646     static void
14647 f_taglist(argvars, rettv)
14648     typval_T  *argvars;
14649     typval_T  *rettv;
14650 {
14651     char_u  *tag_pattern;
14652     list_T  *l;
14653 
14654     tag_pattern = get_tv_string(&argvars[0]);
14655 
14656     rettv->vval.v_number = FALSE;
14657     if (*tag_pattern == NUL)
14658 	return;
14659 
14660     l = list_alloc();
14661     if (l != NULL)
14662     {
14663 	if (get_tags(l, tag_pattern) != FAIL)
14664 	{
14665 	    rettv->vval.v_list = l;
14666 	    rettv->v_type = VAR_LIST;
14667 	    ++l->lv_refcount;
14668 	}
14669 	else
14670 	    list_free(l);
14671     }
14672 }
14673 
14674 /*
14675  * "tempname()" function
14676  */
14677 /*ARGSUSED*/
14678     static void
14679 f_tempname(argvars, rettv)
14680     typval_T	*argvars;
14681     typval_T	*rettv;
14682 {
14683     static int	x = 'A';
14684 
14685     rettv->v_type = VAR_STRING;
14686     rettv->vval.v_string = vim_tempname(x);
14687 
14688     /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
14689      * names.  Skip 'I' and 'O', they are used for shell redirection. */
14690     do
14691     {
14692 	if (x == 'Z')
14693 	    x = '0';
14694 	else if (x == '9')
14695 	    x = 'A';
14696 	else
14697 	{
14698 #ifdef EBCDIC
14699 	    if (x == 'I')
14700 		x = 'J';
14701 	    else if (x == 'R')
14702 		x = 'S';
14703 	    else
14704 #endif
14705 		++x;
14706 	}
14707     } while (x == 'I' || x == 'O');
14708 }
14709 
14710 /*
14711  * "test(list)" function: Just checking the walls...
14712  */
14713 /*ARGSUSED*/
14714     static void
14715 f_test(argvars, rettv)
14716     typval_T	*argvars;
14717     typval_T	*rettv;
14718 {
14719     /* Used for unit testing.  Change the code below to your liking. */
14720 #if 0
14721     listitem_T	*li;
14722     list_T	*l;
14723     char_u	*bad, *good;
14724 
14725     if (argvars[0].v_type != VAR_LIST)
14726 	return;
14727     l = argvars[0].vval.v_list;
14728     if (l == NULL)
14729 	return;
14730     li = l->lv_first;
14731     if (li == NULL)
14732 	return;
14733     bad = get_tv_string(&li->li_tv);
14734     li = li->li_next;
14735     if (li == NULL)
14736 	return;
14737     good = get_tv_string(&li->li_tv);
14738     rettv->vval.v_number = test_edit_score(bad, good);
14739 #endif
14740 }
14741 
14742 /*
14743  * "tolower(string)" function
14744  */
14745     static void
14746 f_tolower(argvars, rettv)
14747     typval_T	*argvars;
14748     typval_T	*rettv;
14749 {
14750     char_u	*p;
14751 
14752     p = vim_strsave(get_tv_string(&argvars[0]));
14753     rettv->v_type = VAR_STRING;
14754     rettv->vval.v_string = p;
14755 
14756     if (p != NULL)
14757 	while (*p != NUL)
14758 	{
14759 #ifdef FEAT_MBYTE
14760 	    int		l;
14761 
14762 	    if (enc_utf8)
14763 	    {
14764 		int c, lc;
14765 
14766 		c = utf_ptr2char(p);
14767 		lc = utf_tolower(c);
14768 		l = utf_ptr2len(p);
14769 		/* TODO: reallocate string when byte count changes. */
14770 		if (utf_char2len(lc) == l)
14771 		    utf_char2bytes(lc, p);
14772 		p += l;
14773 	    }
14774 	    else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
14775 		p += l;		/* skip multi-byte character */
14776 	    else
14777 #endif
14778 	    {
14779 		*p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
14780 		++p;
14781 	    }
14782 	}
14783 }
14784 
14785 /*
14786  * "toupper(string)" function
14787  */
14788     static void
14789 f_toupper(argvars, rettv)
14790     typval_T	*argvars;
14791     typval_T	*rettv;
14792 {
14793     rettv->v_type = VAR_STRING;
14794     rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
14795 }
14796 
14797 /*
14798  * "tr(string, fromstr, tostr)" function
14799  */
14800     static void
14801 f_tr(argvars, rettv)
14802     typval_T	*argvars;
14803     typval_T	*rettv;
14804 {
14805     char_u	*instr;
14806     char_u	*fromstr;
14807     char_u	*tostr;
14808     char_u	*p;
14809 #ifdef FEAT_MBYTE
14810     int		inlen;
14811     int		fromlen;
14812     int		tolen;
14813     int		idx;
14814     char_u	*cpstr;
14815     int		cplen;
14816     int		first = TRUE;
14817 #endif
14818     char_u	buf[NUMBUFLEN];
14819     char_u	buf2[NUMBUFLEN];
14820     garray_T	ga;
14821 
14822     instr = get_tv_string(&argvars[0]);
14823     fromstr = get_tv_string_buf_chk(&argvars[1], buf);
14824     tostr = get_tv_string_buf_chk(&argvars[2], buf2);
14825 
14826     /* Default return value: empty string. */
14827     rettv->v_type = VAR_STRING;
14828     rettv->vval.v_string = NULL;
14829     if (fromstr == NULL || tostr == NULL)
14830 	    return;		/* type error; errmsg already given */
14831     ga_init2(&ga, (int)sizeof(char), 80);
14832 
14833 #ifdef FEAT_MBYTE
14834     if (!has_mbyte)
14835 #endif
14836 	/* not multi-byte: fromstr and tostr must be the same length */
14837 	if (STRLEN(fromstr) != STRLEN(tostr))
14838 	{
14839 #ifdef FEAT_MBYTE
14840 error:
14841 #endif
14842 	    EMSG2(_(e_invarg2), fromstr);
14843 	    ga_clear(&ga);
14844 	    return;
14845 	}
14846 
14847     /* fromstr and tostr have to contain the same number of chars */
14848     while (*instr != NUL)
14849     {
14850 #ifdef FEAT_MBYTE
14851 	if (has_mbyte)
14852 	{
14853 	    inlen = (*mb_ptr2len)(instr);
14854 	    cpstr = instr;
14855 	    cplen = inlen;
14856 	    idx = 0;
14857 	    for (p = fromstr; *p != NUL; p += fromlen)
14858 	    {
14859 		fromlen = (*mb_ptr2len)(p);
14860 		if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
14861 		{
14862 		    for (p = tostr; *p != NUL; p += tolen)
14863 		    {
14864 			tolen = (*mb_ptr2len)(p);
14865 			if (idx-- == 0)
14866 			{
14867 			    cplen = tolen;
14868 			    cpstr = p;
14869 			    break;
14870 			}
14871 		    }
14872 		    if (*p == NUL)	/* tostr is shorter than fromstr */
14873 			goto error;
14874 		    break;
14875 		}
14876 		++idx;
14877 	    }
14878 
14879 	    if (first && cpstr == instr)
14880 	    {
14881 		/* Check that fromstr and tostr have the same number of
14882 		 * (multi-byte) characters.  Done only once when a character
14883 		 * of instr doesn't appear in fromstr. */
14884 		first = FALSE;
14885 		for (p = tostr; *p != NUL; p += tolen)
14886 		{
14887 		    tolen = (*mb_ptr2len)(p);
14888 		    --idx;
14889 		}
14890 		if (idx != 0)
14891 		    goto error;
14892 	    }
14893 
14894 	    ga_grow(&ga, cplen);
14895 	    mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
14896 	    ga.ga_len += cplen;
14897 
14898 	    instr += inlen;
14899 	}
14900 	else
14901 #endif
14902 	{
14903 	    /* When not using multi-byte chars we can do it faster. */
14904 	    p = vim_strchr(fromstr, *instr);
14905 	    if (p != NULL)
14906 		ga_append(&ga, tostr[p - fromstr]);
14907 	    else
14908 		ga_append(&ga, *instr);
14909 	    ++instr;
14910 	}
14911     }
14912 
14913     rettv->vval.v_string = ga.ga_data;
14914 }
14915 
14916 /*
14917  * "type(expr)" function
14918  */
14919     static void
14920 f_type(argvars, rettv)
14921     typval_T	*argvars;
14922     typval_T	*rettv;
14923 {
14924     int n;
14925 
14926     switch (argvars[0].v_type)
14927     {
14928 	case VAR_NUMBER: n = 0; break;
14929 	case VAR_STRING: n = 1; break;
14930 	case VAR_FUNC:   n = 2; break;
14931 	case VAR_LIST:   n = 3; break;
14932 	case VAR_DICT:   n = 4; break;
14933 	default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
14934     }
14935     rettv->vval.v_number = n;
14936 }
14937 
14938 /*
14939  * "values(dict)" function
14940  */
14941     static void
14942 f_values(argvars, rettv)
14943     typval_T	*argvars;
14944     typval_T	*rettv;
14945 {
14946     dict_list(argvars, rettv, 1);
14947 }
14948 
14949 /*
14950  * "virtcol(string)" function
14951  */
14952     static void
14953 f_virtcol(argvars, rettv)
14954     typval_T	*argvars;
14955     typval_T	*rettv;
14956 {
14957     colnr_T	vcol = 0;
14958     pos_T	*fp;
14959 
14960     fp = var2fpos(&argvars[0], FALSE);
14961     if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count)
14962     {
14963 	getvvcol(curwin, fp, NULL, NULL, &vcol);
14964 	++vcol;
14965     }
14966 
14967     rettv->vval.v_number = vcol;
14968 }
14969 
14970 /*
14971  * "visualmode()" function
14972  */
14973 /*ARGSUSED*/
14974     static void
14975 f_visualmode(argvars, rettv)
14976     typval_T	*argvars;
14977     typval_T	*rettv;
14978 {
14979 #ifdef FEAT_VISUAL
14980     char_u	str[2];
14981 
14982     rettv->v_type = VAR_STRING;
14983     str[0] = curbuf->b_visual_mode_eval;
14984     str[1] = NUL;
14985     rettv->vval.v_string = vim_strsave(str);
14986 
14987     /* A non-zero number or non-empty string argument: reset mode. */
14988     if ((argvars[0].v_type == VAR_NUMBER
14989 		&& argvars[0].vval.v_number != 0)
14990 	    || (argvars[0].v_type == VAR_STRING
14991 		&& *get_tv_string(&argvars[0]) != NUL))
14992 	curbuf->b_visual_mode_eval = NUL;
14993 #else
14994     rettv->vval.v_number = 0; /* return anything, it won't work anyway */
14995 #endif
14996 }
14997 
14998 /*
14999  * "winbufnr(nr)" function
15000  */
15001     static void
15002 f_winbufnr(argvars, rettv)
15003     typval_T	*argvars;
15004     typval_T	*rettv;
15005 {
15006     win_T	*wp;
15007 
15008     wp = find_win_by_nr(&argvars[0]);
15009     if (wp == NULL)
15010 	rettv->vval.v_number = -1;
15011     else
15012 	rettv->vval.v_number = wp->w_buffer->b_fnum;
15013 }
15014 
15015 /*
15016  * "wincol()" function
15017  */
15018 /*ARGSUSED*/
15019     static void
15020 f_wincol(argvars, rettv)
15021     typval_T	*argvars;
15022     typval_T	*rettv;
15023 {
15024     validate_cursor();
15025     rettv->vval.v_number = curwin->w_wcol + 1;
15026 }
15027 
15028 /*
15029  * "winheight(nr)" function
15030  */
15031     static void
15032 f_winheight(argvars, rettv)
15033     typval_T	*argvars;
15034     typval_T	*rettv;
15035 {
15036     win_T	*wp;
15037 
15038     wp = find_win_by_nr(&argvars[0]);
15039     if (wp == NULL)
15040 	rettv->vval.v_number = -1;
15041     else
15042 	rettv->vval.v_number = wp->w_height;
15043 }
15044 
15045 /*
15046  * "winline()" function
15047  */
15048 /*ARGSUSED*/
15049     static void
15050 f_winline(argvars, rettv)
15051     typval_T	*argvars;
15052     typval_T	*rettv;
15053 {
15054     validate_cursor();
15055     rettv->vval.v_number = curwin->w_wrow + 1;
15056 }
15057 
15058 /*
15059  * "winnr()" function
15060  */
15061 /* ARGSUSED */
15062     static void
15063 f_winnr(argvars, rettv)
15064     typval_T	*argvars;
15065     typval_T	*rettv;
15066 {
15067     int		nr = 1;
15068 #ifdef FEAT_WINDOWS
15069     win_T	*wp;
15070     win_T	*twin = curwin;
15071     char_u	*arg;
15072 
15073     if (argvars[0].v_type != VAR_UNKNOWN)
15074     {
15075 	arg = get_tv_string_chk(&argvars[0]);
15076 	if (arg == NULL)
15077 	    nr = 0;		/* type error; errmsg already given */
15078 	else if (STRCMP(arg, "$") == 0)
15079 	    twin = lastwin;
15080 	else if (STRCMP(arg, "#") == 0)
15081 	{
15082 	    twin = prevwin;
15083 	    if (prevwin == NULL)
15084 		nr = 0;
15085 	}
15086 	else
15087 	{
15088 	    EMSG2(_(e_invexpr2), arg);
15089 	    nr = 0;
15090 	}
15091     }
15092 
15093     if (nr > 0)
15094 	for (wp = firstwin; wp != twin; wp = wp->w_next)
15095 	    ++nr;
15096 #endif
15097     rettv->vval.v_number = nr;
15098 }
15099 
15100 /*
15101  * "winrestcmd()" function
15102  */
15103 /* ARGSUSED */
15104     static void
15105 f_winrestcmd(argvars, rettv)
15106     typval_T	*argvars;
15107     typval_T	*rettv;
15108 {
15109 #ifdef FEAT_WINDOWS
15110     win_T	*wp;
15111     int		winnr = 1;
15112     garray_T	ga;
15113     char_u	buf[50];
15114 
15115     ga_init2(&ga, (int)sizeof(char), 70);
15116     for (wp = firstwin; wp != NULL; wp = wp->w_next)
15117     {
15118 	sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
15119 	ga_concat(&ga, buf);
15120 # ifdef FEAT_VERTSPLIT
15121 	sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
15122 	ga_concat(&ga, buf);
15123 # endif
15124 	++winnr;
15125     }
15126     ga_append(&ga, NUL);
15127 
15128     rettv->vval.v_string = ga.ga_data;
15129 #else
15130     rettv->vval.v_string = NULL;
15131 #endif
15132     rettv->v_type = VAR_STRING;
15133 }
15134 
15135 /*
15136  * "winwidth(nr)" function
15137  */
15138     static void
15139 f_winwidth(argvars, rettv)
15140     typval_T	*argvars;
15141     typval_T	*rettv;
15142 {
15143     win_T	*wp;
15144 
15145     wp = find_win_by_nr(&argvars[0]);
15146     if (wp == NULL)
15147 	rettv->vval.v_number = -1;
15148     else
15149 #ifdef FEAT_VERTSPLIT
15150 	rettv->vval.v_number = wp->w_width;
15151 #else
15152 	rettv->vval.v_number = Columns;
15153 #endif
15154 }
15155 
15156 /*
15157  * "writefile()" function
15158  */
15159     static void
15160 f_writefile(argvars, rettv)
15161     typval_T	*argvars;
15162     typval_T	*rettv;
15163 {
15164     int		binary = FALSE;
15165     char_u	*fname;
15166     FILE	*fd;
15167     listitem_T	*li;
15168     char_u	*s;
15169     int		ret = 0;
15170     int		c;
15171 
15172     if (argvars[0].v_type != VAR_LIST)
15173     {
15174 	EMSG2(_(e_listarg), "writefile()");
15175 	return;
15176     }
15177     if (argvars[0].vval.v_list == NULL)
15178 	return;
15179 
15180     if (argvars[2].v_type != VAR_UNKNOWN
15181 			      && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
15182 	binary = TRUE;
15183 
15184     /* Always open the file in binary mode, library functions have a mind of
15185      * their own about CR-LF conversion. */
15186     fname = get_tv_string(&argvars[1]);
15187     if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
15188     {
15189 	EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
15190 	ret = -1;
15191     }
15192     else
15193     {
15194 	for (li = argvars[0].vval.v_list->lv_first; li != NULL;
15195 							     li = li->li_next)
15196 	{
15197 	    for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
15198 	    {
15199 		if (*s == '\n')
15200 		    c = putc(NUL, fd);
15201 		else
15202 		    c = putc(*s, fd);
15203 		if (c == EOF)
15204 		{
15205 		    ret = -1;
15206 		    break;
15207 		}
15208 	    }
15209 	    if (!binary || li->li_next != NULL)
15210 		if (putc('\n', fd) == EOF)
15211 		{
15212 		    ret = -1;
15213 		    break;
15214 		}
15215 	    if (ret < 0)
15216 	    {
15217 		EMSG(_(e_write));
15218 		break;
15219 	    }
15220 	}
15221 	fclose(fd);
15222     }
15223 
15224     rettv->vval.v_number = ret;
15225 }
15226 
15227 /*
15228  * Translate a String variable into a position.
15229  */
15230     static pos_T *
15231 var2fpos(varp, lnum)
15232     typval_T	*varp;
15233     int		lnum;		/* TRUE when $ is last line */
15234 {
15235     char_u	*name;
15236     static pos_T	pos;
15237     pos_T	*pp;
15238 
15239     name = get_tv_string_chk(varp);
15240     if (name == NULL)
15241 	return NULL;
15242     if (name[0] == '.')		/* cursor */
15243 	return &curwin->w_cursor;
15244     if (name[0] == '\'')	/* mark */
15245     {
15246 	pp = getmark(name[1], FALSE);
15247 	if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
15248 	    return NULL;
15249 	return pp;
15250     }
15251     if (name[0] == '$')		/* last column or line */
15252     {
15253 	if (lnum)
15254 	{
15255 	    pos.lnum = curbuf->b_ml.ml_line_count;
15256 	    pos.col = 0;
15257 	}
15258 	else
15259 	{
15260 	    pos.lnum = curwin->w_cursor.lnum;
15261 	    pos.col = (colnr_T)STRLEN(ml_get_curline());
15262 	}
15263 	return &pos;
15264     }
15265     return NULL;
15266 }
15267 
15268 /*
15269  * Get the length of an environment variable name.
15270  * Advance "arg" to the first character after the name.
15271  * Return 0 for error.
15272  */
15273     static int
15274 get_env_len(arg)
15275     char_u	**arg;
15276 {
15277     char_u	*p;
15278     int		len;
15279 
15280     for (p = *arg; vim_isIDc(*p); ++p)
15281 	;
15282     if (p == *arg)	    /* no name found */
15283 	return 0;
15284 
15285     len = (int)(p - *arg);
15286     *arg = p;
15287     return len;
15288 }
15289 
15290 /*
15291  * Get the length of the name of a function or internal variable.
15292  * "arg" is advanced to the first non-white character after the name.
15293  * Return 0 if something is wrong.
15294  */
15295     static int
15296 get_id_len(arg)
15297     char_u	**arg;
15298 {
15299     char_u	*p;
15300     int		len;
15301 
15302     /* Find the end of the name. */
15303     for (p = *arg; eval_isnamec(*p); ++p)
15304 	;
15305     if (p == *arg)	    /* no name found */
15306 	return 0;
15307 
15308     len = (int)(p - *arg);
15309     *arg = skipwhite(p);
15310 
15311     return len;
15312 }
15313 
15314 /*
15315  * Get the length of the name of a variable or function.
15316  * Only the name is recognized, does not handle ".key" or "[idx]".
15317  * "arg" is advanced to the first non-white character after the name.
15318  * Return -1 if curly braces expansion failed.
15319  * Return 0 if something else is wrong.
15320  * If the name contains 'magic' {}'s, expand them and return the
15321  * expanded name in an allocated string via 'alias' - caller must free.
15322  */
15323     static int
15324 get_name_len(arg, alias, evaluate, verbose)
15325     char_u	**arg;
15326     char_u	**alias;
15327     int		evaluate;
15328     int		verbose;
15329 {
15330     int		len;
15331     char_u	*p;
15332     char_u	*expr_start;
15333     char_u	*expr_end;
15334 
15335     *alias = NULL;  /* default to no alias */
15336 
15337     if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
15338 						  && (*arg)[2] == (int)KE_SNR)
15339     {
15340 	/* hard coded <SNR>, already translated */
15341 	*arg += 3;
15342 	return get_id_len(arg) + 3;
15343     }
15344     len = eval_fname_script(*arg);
15345     if (len > 0)
15346     {
15347 	/* literal "<SID>", "s:" or "<SNR>" */
15348 	*arg += len;
15349     }
15350 
15351     /*
15352      * Find the end of the name; check for {} construction.
15353      */
15354     p = find_name_end(*arg, &expr_start, &expr_end,
15355 					       len > 0 ? 0 : FNE_CHECK_START);
15356     if (expr_start != NULL)
15357     {
15358 	char_u	*temp_string;
15359 
15360 	if (!evaluate)
15361 	{
15362 	    len += (int)(p - *arg);
15363 	    *arg = skipwhite(p);
15364 	    return len;
15365 	}
15366 
15367 	/*
15368 	 * Include any <SID> etc in the expanded string:
15369 	 * Thus the -len here.
15370 	 */
15371 	temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
15372 	if (temp_string == NULL)
15373 	    return -1;
15374 	*alias = temp_string;
15375 	*arg = skipwhite(p);
15376 	return (int)STRLEN(temp_string);
15377     }
15378 
15379     len += get_id_len(arg);
15380     if (len == 0 && verbose)
15381 	EMSG2(_(e_invexpr2), *arg);
15382 
15383     return len;
15384 }
15385 
15386 /*
15387  * Find the end of a variable or function name, taking care of magic braces.
15388  * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
15389  * start and end of the first magic braces item.
15390  * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
15391  * Return a pointer to just after the name.  Equal to "arg" if there is no
15392  * valid name.
15393  */
15394     static char_u *
15395 find_name_end(arg, expr_start, expr_end, flags)
15396     char_u	*arg;
15397     char_u	**expr_start;
15398     char_u	**expr_end;
15399     int		flags;
15400 {
15401     int		mb_nest = 0;
15402     int		br_nest = 0;
15403     char_u	*p;
15404 
15405     if (expr_start != NULL)
15406     {
15407 	*expr_start = NULL;
15408 	*expr_end = NULL;
15409     }
15410 
15411     /* Quick check for valid starting character. */
15412     if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
15413 	return arg;
15414 
15415     for (p = arg; *p != NUL
15416 		    && (eval_isnamec(*p)
15417 			|| *p == '{'
15418 			|| ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
15419 			|| mb_nest != 0
15420 			|| br_nest != 0); mb_ptr_adv(p))
15421     {
15422 	if (*p == '\'')
15423 	{
15424 	    /* skip over 'string' to avoid counting [ and ] inside it. */
15425 	    for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
15426 		;
15427 	    if (*p == NUL)
15428 		break;
15429 	}
15430 	else if (*p == '"')
15431 	{
15432 	    /* skip over "str\"ing" to avoid counting [ and ] inside it. */
15433 	    for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
15434 		if (*p == '\\' && p[1] != NUL)
15435 		    ++p;
15436 	    if (*p == NUL)
15437 		break;
15438 	}
15439 
15440 	if (mb_nest == 0)
15441 	{
15442 	    if (*p == '[')
15443 		++br_nest;
15444 	    else if (*p == ']')
15445 		--br_nest;
15446 	}
15447 
15448 	if (br_nest == 0)
15449 	{
15450 	    if (*p == '{')
15451 	    {
15452 		mb_nest++;
15453 		if (expr_start != NULL && *expr_start == NULL)
15454 		    *expr_start = p;
15455 	    }
15456 	    else if (*p == '}')
15457 	    {
15458 		mb_nest--;
15459 		if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
15460 		    *expr_end = p;
15461 	    }
15462 	}
15463     }
15464 
15465     return p;
15466 }
15467 
15468 /*
15469  * Expands out the 'magic' {}'s in a variable/function name.
15470  * Note that this can call itself recursively, to deal with
15471  * constructs like foo{bar}{baz}{bam}
15472  * The four pointer arguments point to "foo{expre}ss{ion}bar"
15473  *			"in_start"      ^
15474  *			"expr_start"	   ^
15475  *			"expr_end"		 ^
15476  *			"in_end"			    ^
15477  *
15478  * Returns a new allocated string, which the caller must free.
15479  * Returns NULL for failure.
15480  */
15481     static char_u *
15482 make_expanded_name(in_start, expr_start, expr_end, in_end)
15483     char_u	*in_start;
15484     char_u	*expr_start;
15485     char_u	*expr_end;
15486     char_u	*in_end;
15487 {
15488     char_u	c1;
15489     char_u	*retval = NULL;
15490     char_u	*temp_result;
15491     char_u	*nextcmd = NULL;
15492 
15493     if (expr_end == NULL || in_end == NULL)
15494 	return NULL;
15495     *expr_start	= NUL;
15496     *expr_end = NUL;
15497     c1 = *in_end;
15498     *in_end = NUL;
15499 
15500     temp_result = eval_to_string(expr_start + 1, &nextcmd);
15501     if (temp_result != NULL && nextcmd == NULL)
15502     {
15503 	retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
15504 						   + (in_end - expr_end) + 1));
15505 	if (retval != NULL)
15506 	{
15507 	    STRCPY(retval, in_start);
15508 	    STRCAT(retval, temp_result);
15509 	    STRCAT(retval, expr_end + 1);
15510 	}
15511     }
15512     vim_free(temp_result);
15513 
15514     *in_end = c1;		/* put char back for error messages */
15515     *expr_start = '{';
15516     *expr_end = '}';
15517 
15518     if (retval != NULL)
15519     {
15520 	temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
15521 	if (expr_start != NULL)
15522 	{
15523 	    /* Further expansion! */
15524 	    temp_result = make_expanded_name(retval, expr_start,
15525 						       expr_end, temp_result);
15526 	    vim_free(retval);
15527 	    retval = temp_result;
15528 	}
15529     }
15530 
15531     return retval;
15532 }
15533 
15534 /*
15535  * Return TRUE if character "c" can be used in a variable or function name.
15536  * Does not include '{' or '}' for magic braces.
15537  */
15538     static int
15539 eval_isnamec(c)
15540     int	    c;
15541 {
15542     return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
15543 }
15544 
15545 /*
15546  * Return TRUE if character "c" can be used as the first character in a
15547  * variable or function name (excluding '{' and '}').
15548  */
15549     static int
15550 eval_isnamec1(c)
15551     int	    c;
15552 {
15553     return (ASCII_ISALPHA(c) || c == '_');
15554 }
15555 
15556 /*
15557  * Set number v: variable to "val".
15558  */
15559     void
15560 set_vim_var_nr(idx, val)
15561     int		idx;
15562     long	val;
15563 {
15564     vimvars[idx].vv_nr = val;
15565 }
15566 
15567 /*
15568  * Get number v: variable value.
15569  */
15570     long
15571 get_vim_var_nr(idx)
15572     int		idx;
15573 {
15574     return vimvars[idx].vv_nr;
15575 }
15576 
15577 #if defined(FEAT_AUTOCMD) || defined(PROTO)
15578 /*
15579  * Get string v: variable value.  Uses a static buffer, can only be used once.
15580  */
15581     char_u *
15582 get_vim_var_str(idx)
15583     int		idx;
15584 {
15585     return get_tv_string(&vimvars[idx].vv_tv);
15586 }
15587 #endif
15588 
15589 /*
15590  * Set v:count, v:count1 and v:prevcount.
15591  */
15592     void
15593 set_vcount(count, count1)
15594     long	count;
15595     long	count1;
15596 {
15597     vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
15598     vimvars[VV_COUNT].vv_nr = count;
15599     vimvars[VV_COUNT1].vv_nr = count1;
15600 }
15601 
15602 /*
15603  * Set string v: variable to a copy of "val".
15604  */
15605     void
15606 set_vim_var_string(idx, val, len)
15607     int		idx;
15608     char_u	*val;
15609     int		len;	    /* length of "val" to use or -1 (whole string) */
15610 {
15611     /* Need to do this (at least) once, since we can't initialize a union.
15612      * Will always be invoked when "v:progname" is set. */
15613     vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
15614 
15615     vim_free(vimvars[idx].vv_str);
15616     if (val == NULL)
15617 	vimvars[idx].vv_str = NULL;
15618     else if (len == -1)
15619 	vimvars[idx].vv_str = vim_strsave(val);
15620     else
15621 	vimvars[idx].vv_str = vim_strnsave(val, len);
15622 }
15623 
15624 /*
15625  * Set v:register if needed.
15626  */
15627     void
15628 set_reg_var(c)
15629     int		c;
15630 {
15631     char_u	regname;
15632 
15633     if (c == 0 || c == ' ')
15634 	regname = '"';
15635     else
15636 	regname = c;
15637     /* Avoid free/alloc when the value is already right. */
15638     if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
15639 	set_vim_var_string(VV_REG, &regname, 1);
15640 }
15641 
15642 /*
15643  * Get or set v:exception.  If "oldval" == NULL, return the current value.
15644  * Otherwise, restore the value to "oldval" and return NULL.
15645  * Must always be called in pairs to save and restore v:exception!  Does not
15646  * take care of memory allocations.
15647  */
15648     char_u *
15649 v_exception(oldval)
15650     char_u	*oldval;
15651 {
15652     if (oldval == NULL)
15653 	return vimvars[VV_EXCEPTION].vv_str;
15654 
15655     vimvars[VV_EXCEPTION].vv_str = oldval;
15656     return NULL;
15657 }
15658 
15659 /*
15660  * Get or set v:throwpoint.  If "oldval" == NULL, return the current value.
15661  * Otherwise, restore the value to "oldval" and return NULL.
15662  * Must always be called in pairs to save and restore v:throwpoint!  Does not
15663  * take care of memory allocations.
15664  */
15665     char_u *
15666 v_throwpoint(oldval)
15667     char_u	*oldval;
15668 {
15669     if (oldval == NULL)
15670 	return vimvars[VV_THROWPOINT].vv_str;
15671 
15672     vimvars[VV_THROWPOINT].vv_str = oldval;
15673     return NULL;
15674 }
15675 
15676 #if defined(FEAT_AUTOCMD) || defined(PROTO)
15677 /*
15678  * Set v:cmdarg.
15679  * If "eap" != NULL, use "eap" to generate the value and return the old value.
15680  * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
15681  * Must always be called in pairs!
15682  */
15683     char_u *
15684 set_cmdarg(eap, oldarg)
15685     exarg_T	*eap;
15686     char_u	*oldarg;
15687 {
15688     char_u	*oldval;
15689     char_u	*newval;
15690     unsigned	len;
15691 
15692     oldval = vimvars[VV_CMDARG].vv_str;
15693     if (eap == NULL)
15694     {
15695 	vim_free(oldval);
15696 	vimvars[VV_CMDARG].vv_str = oldarg;
15697 	return NULL;
15698     }
15699 
15700     if (eap->force_bin == FORCE_BIN)
15701 	len = 6;
15702     else if (eap->force_bin == FORCE_NOBIN)
15703 	len = 8;
15704     else
15705 	len = 0;
15706     if (eap->force_ff != 0)
15707 	len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
15708 # ifdef FEAT_MBYTE
15709     if (eap->force_enc != 0)
15710 	len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
15711     if (eap->bad_char != 0)
15712 	len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
15713 # endif
15714 
15715     newval = alloc(len + 1);
15716     if (newval == NULL)
15717 	return NULL;
15718 
15719     if (eap->force_bin == FORCE_BIN)
15720 	sprintf((char *)newval, " ++bin");
15721     else if (eap->force_bin == FORCE_NOBIN)
15722 	sprintf((char *)newval, " ++nobin");
15723     else
15724 	*newval = NUL;
15725     if (eap->force_ff != 0)
15726 	sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
15727 						eap->cmd + eap->force_ff);
15728 # ifdef FEAT_MBYTE
15729     if (eap->force_enc != 0)
15730 	sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
15731 					       eap->cmd + eap->force_enc);
15732     if (eap->bad_char != 0)
15733 	sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
15734 					       eap->cmd + eap->bad_char);
15735 # endif
15736     vimvars[VV_CMDARG].vv_str = newval;
15737     return oldval;
15738 }
15739 #endif
15740 
15741 /*
15742  * Get the value of internal variable "name".
15743  * Return OK or FAIL.
15744  */
15745     static int
15746 get_var_tv(name, len, rettv, verbose)
15747     char_u	*name;
15748     int		len;		/* length of "name" */
15749     typval_T	*rettv;		/* NULL when only checking existence */
15750     int		verbose;	/* may give error message */
15751 {
15752     int		ret = OK;
15753     typval_T	*tv = NULL;
15754     typval_T	atv;
15755     dictitem_T	*v;
15756     int		cc;
15757 
15758     /* truncate the name, so that we can use strcmp() */
15759     cc = name[len];
15760     name[len] = NUL;
15761 
15762     /*
15763      * Check for "b:changedtick".
15764      */
15765     if (STRCMP(name, "b:changedtick") == 0)
15766     {
15767 	atv.v_type = VAR_NUMBER;
15768 	atv.vval.v_number = curbuf->b_changedtick;
15769 	tv = &atv;
15770     }
15771 
15772     /*
15773      * Check for user-defined variables.
15774      */
15775     else
15776     {
15777 	v = find_var(name, NULL);
15778 	if (v != NULL)
15779 	    tv = &v->di_tv;
15780     }
15781 
15782     if (tv == NULL)
15783     {
15784 	if (rettv != NULL && verbose)
15785 	    EMSG2(_(e_undefvar), name);
15786 	ret = FAIL;
15787     }
15788     else if (rettv != NULL)
15789 	copy_tv(tv, rettv);
15790 
15791     name[len] = cc;
15792 
15793     return ret;
15794 }
15795 
15796 /*
15797  * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
15798  * Also handle function call with Funcref variable: func(expr)
15799  * Can all be combined: dict.func(expr)[idx]['func'](expr)
15800  */
15801     static int
15802 handle_subscript(arg, rettv, evaluate, verbose)
15803     char_u	**arg;
15804     typval_T	*rettv;
15805     int		evaluate;	/* do more than finding the end */
15806     int		verbose;	/* give error messages */
15807 {
15808     int		ret = OK;
15809     dict_T	*selfdict = NULL;
15810     char_u	*s;
15811     int		len;
15812     typval_T	functv;
15813 
15814     while (ret == OK
15815 	    && (**arg == '['
15816 		|| (**arg == '.' && rettv->v_type == VAR_DICT)
15817 		|| (**arg == '(' && rettv->v_type == VAR_FUNC))
15818 	    && !vim_iswhite(*(*arg - 1)))
15819     {
15820 	if (**arg == '(')
15821 	{
15822 	    /* need to copy the funcref so that we can clear rettv */
15823 	    functv = *rettv;
15824 	    rettv->v_type = VAR_UNKNOWN;
15825 
15826 	    /* Invoke the function.  Recursive! */
15827 	    s = functv.vval.v_string;
15828 	    ret = get_func_tv(s, STRLEN(s), rettv, arg,
15829 			curwin->w_cursor.lnum, curwin->w_cursor.lnum,
15830 			&len, evaluate, selfdict);
15831 
15832 	    /* Clear the funcref afterwards, so that deleting it while
15833 	     * evaluating the arguments is possible (see test55). */
15834 	    clear_tv(&functv);
15835 
15836 	    /* Stop the expression evaluation when immediately aborting on
15837 	     * error, or when an interrupt occurred or an exception was thrown
15838 	     * but not caught. */
15839 	    if (aborting())
15840 	    {
15841 		if (ret == OK)
15842 		    clear_tv(rettv);
15843 		ret = FAIL;
15844 	    }
15845 	    dict_unref(selfdict);
15846 	    selfdict = NULL;
15847 	}
15848 	else /* **arg == '[' || **arg == '.' */
15849 	{
15850 	    dict_unref(selfdict);
15851 	    if (rettv->v_type == VAR_DICT)
15852 	    {
15853 		selfdict = rettv->vval.v_dict;
15854 		if (selfdict != NULL)
15855 		    ++selfdict->dv_refcount;
15856 	    }
15857 	    else
15858 		selfdict = NULL;
15859 	    if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
15860 	    {
15861 		clear_tv(rettv);
15862 		ret = FAIL;
15863 	    }
15864 	}
15865     }
15866     dict_unref(selfdict);
15867     return ret;
15868 }
15869 
15870 /*
15871  * Allocate memory for a variable type-value, and make it emtpy (0 or NULL
15872  * value).
15873  */
15874     static typval_T *
15875 alloc_tv()
15876 {
15877     return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
15878 }
15879 
15880 /*
15881  * Allocate memory for a variable type-value, and assign a string to it.
15882  * The string "s" must have been allocated, it is consumed.
15883  * Return NULL for out of memory, the variable otherwise.
15884  */
15885     static typval_T *
15886 alloc_string_tv(s)
15887     char_u	*s;
15888 {
15889     typval_T	*rettv;
15890 
15891     rettv = alloc_tv();
15892     if (rettv != NULL)
15893     {
15894 	rettv->v_type = VAR_STRING;
15895 	rettv->vval.v_string = s;
15896     }
15897     else
15898 	vim_free(s);
15899     return rettv;
15900 }
15901 
15902 /*
15903  * Free the memory for a variable type-value.
15904  */
15905     void
15906 free_tv(varp)
15907     typval_T *varp;
15908 {
15909     if (varp != NULL)
15910     {
15911 	switch (varp->v_type)
15912 	{
15913 	    case VAR_FUNC:
15914 		func_unref(varp->vval.v_string);
15915 		/*FALLTHROUGH*/
15916 	    case VAR_STRING:
15917 		vim_free(varp->vval.v_string);
15918 		break;
15919 	    case VAR_LIST:
15920 		list_unref(varp->vval.v_list);
15921 		break;
15922 	    case VAR_DICT:
15923 		dict_unref(varp->vval.v_dict);
15924 		break;
15925 	    case VAR_NUMBER:
15926 	    case VAR_UNKNOWN:
15927 		break;
15928 	    default:
15929 		EMSG2(_(e_intern2), "free_tv()");
15930 		break;
15931 	}
15932 	vim_free(varp);
15933     }
15934 }
15935 
15936 /*
15937  * Free the memory for a variable value and set the value to NULL or 0.
15938  */
15939     void
15940 clear_tv(varp)
15941     typval_T *varp;
15942 {
15943     if (varp != NULL)
15944     {
15945 	switch (varp->v_type)
15946 	{
15947 	    case VAR_FUNC:
15948 		func_unref(varp->vval.v_string);
15949 		/*FALLTHROUGH*/
15950 	    case VAR_STRING:
15951 		vim_free(varp->vval.v_string);
15952 		varp->vval.v_string = NULL;
15953 		break;
15954 	    case VAR_LIST:
15955 		list_unref(varp->vval.v_list);
15956 		varp->vval.v_list = NULL;
15957 		break;
15958 	    case VAR_DICT:
15959 		dict_unref(varp->vval.v_dict);
15960 		varp->vval.v_dict = NULL;
15961 		break;
15962 	    case VAR_NUMBER:
15963 		varp->vval.v_number = 0;
15964 		break;
15965 	    case VAR_UNKNOWN:
15966 		break;
15967 	    default:
15968 		EMSG2(_(e_intern2), "clear_tv()");
15969 	}
15970 	varp->v_lock = 0;
15971     }
15972 }
15973 
15974 /*
15975  * Set the value of a variable to NULL without freeing items.
15976  */
15977     static void
15978 init_tv(varp)
15979     typval_T *varp;
15980 {
15981     if (varp != NULL)
15982 	vim_memset(varp, 0, sizeof(typval_T));
15983 }
15984 
15985 /*
15986  * Get the number value of a variable.
15987  * If it is a String variable, uses vim_str2nr().
15988  * For incompatible types, return 0.
15989  * get_tv_number_chk() is similar to get_tv_number(), but informs the
15990  * caller of incompatible types: it sets *denote to TRUE if "denote"
15991  * is not NULL or returns -1 otherwise.
15992  */
15993     static long
15994 get_tv_number(varp)
15995     typval_T	*varp;
15996 {
15997     int		error = FALSE;
15998 
15999     return get_tv_number_chk(varp, &error);	/* return 0L on error */
16000 }
16001 
16002     long
16003 get_tv_number_chk(varp, denote)
16004     typval_T	*varp;
16005     int		*denote;
16006 {
16007     long	n = 0L;
16008 
16009     switch (varp->v_type)
16010     {
16011 	case VAR_NUMBER:
16012 	    return (long)(varp->vval.v_number);
16013 	case VAR_FUNC:
16014 	    EMSG(_("E703: Using a Funcref as a number"));
16015 	    break;
16016 	case VAR_STRING:
16017 	    if (varp->vval.v_string != NULL)
16018 		vim_str2nr(varp->vval.v_string, NULL, NULL,
16019 							TRUE, TRUE, &n, NULL);
16020 	    return n;
16021 	case VAR_LIST:
16022 	    EMSG(_("E745: Using a List as a number"));
16023 	    break;
16024 	case VAR_DICT:
16025 	    EMSG(_("E728: Using a Dictionary as a number"));
16026 	    break;
16027 	default:
16028 	    EMSG2(_(e_intern2), "get_tv_number()");
16029 	    break;
16030     }
16031     if (denote == NULL)		/* useful for values that must be unsigned */
16032 	n = -1;
16033     else
16034 	*denote = TRUE;
16035     return n;
16036 }
16037 
16038 /*
16039  * Get the lnum from the first argument.
16040  * Also accepts ".", "$", etc., but that only works for the current buffer.
16041  * Returns -1 on error.
16042  */
16043     static linenr_T
16044 get_tv_lnum(argvars)
16045     typval_T	*argvars;
16046 {
16047     typval_T	rettv;
16048     linenr_T	lnum;
16049 
16050     lnum = get_tv_number_chk(&argvars[0], NULL);
16051     if (lnum == 0)  /* no valid number, try using line() */
16052     {
16053 	rettv.v_type = VAR_NUMBER;
16054 	f_line(argvars, &rettv);
16055 	lnum = rettv.vval.v_number;
16056 	clear_tv(&rettv);
16057     }
16058     return lnum;
16059 }
16060 
16061 /*
16062  * Get the lnum from the first argument.
16063  * Also accepts "$", then "buf" is used.
16064  * Returns 0 on error.
16065  */
16066     static linenr_T
16067 get_tv_lnum_buf(argvars, buf)
16068     typval_T	*argvars;
16069     buf_T	*buf;
16070 {
16071     if (argvars[0].v_type == VAR_STRING
16072 	    && argvars[0].vval.v_string != NULL
16073 	    && argvars[0].vval.v_string[0] == '$'
16074 	    && buf != NULL)
16075 	return buf->b_ml.ml_line_count;
16076     return get_tv_number_chk(&argvars[0], NULL);
16077 }
16078 
16079 /*
16080  * Get the string value of a variable.
16081  * If it is a Number variable, the number is converted into a string.
16082  * get_tv_string() uses a single, static buffer.  YOU CAN ONLY USE IT ONCE!
16083  * get_tv_string_buf() uses a given buffer.
16084  * If the String variable has never been set, return an empty string.
16085  * Never returns NULL;
16086  * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
16087  * NULL on error.
16088  */
16089     static char_u *
16090 get_tv_string(varp)
16091     typval_T	*varp;
16092 {
16093     static char_u   mybuf[NUMBUFLEN];
16094 
16095     return get_tv_string_buf(varp, mybuf);
16096 }
16097 
16098     static char_u *
16099 get_tv_string_buf(varp, buf)
16100     typval_T	*varp;
16101     char_u	*buf;
16102 {
16103     char_u	*res =  get_tv_string_buf_chk(varp, buf);
16104 
16105     return res != NULL ? res : (char_u *)"";
16106 }
16107 
16108     char_u *
16109 get_tv_string_chk(varp)
16110     typval_T	*varp;
16111 {
16112     static char_u   mybuf[NUMBUFLEN];
16113 
16114     return get_tv_string_buf_chk(varp, mybuf);
16115 }
16116 
16117     static char_u *
16118 get_tv_string_buf_chk(varp, buf)
16119     typval_T	*varp;
16120     char_u	*buf;
16121 {
16122     switch (varp->v_type)
16123     {
16124 	case VAR_NUMBER:
16125 	    sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
16126 	    return buf;
16127 	case VAR_FUNC:
16128 	    EMSG(_("E729: using Funcref as a String"));
16129 	    break;
16130 	case VAR_LIST:
16131 	    EMSG(_("E730: using List as a String"));
16132 	    break;
16133 	case VAR_DICT:
16134 	    EMSG(_("E731: using Dictionary as a String"));
16135 	    break;
16136 	case VAR_STRING:
16137 	    if (varp->vval.v_string != NULL)
16138 		return varp->vval.v_string;
16139 	    return (char_u *)"";
16140 	default:
16141 	    EMSG2(_(e_intern2), "get_tv_string_buf()");
16142 	    break;
16143     }
16144     return NULL;
16145 }
16146 
16147 /*
16148  * Find variable "name" in the list of variables.
16149  * Return a pointer to it if found, NULL if not found.
16150  * Careful: "a:0" variables don't have a name.
16151  * When "htp" is not NULL we are writing to the variable, set "htp" to the
16152  * hashtab_T used.
16153  */
16154     static dictitem_T *
16155 find_var(name, htp)
16156     char_u	*name;
16157     hashtab_T	**htp;
16158 {
16159     char_u	*varname;
16160     hashtab_T	*ht;
16161 
16162     ht = find_var_ht(name, &varname);
16163     if (htp != NULL)
16164 	*htp = ht;
16165     if (ht == NULL)
16166 	return NULL;
16167     return find_var_in_ht(ht, varname, htp != NULL);
16168 }
16169 
16170 /*
16171  * Find variable "varname" in hashtab "ht".
16172  * Returns NULL if not found.
16173  */
16174     static dictitem_T *
16175 find_var_in_ht(ht, varname, writing)
16176     hashtab_T	*ht;
16177     char_u	*varname;
16178     int		writing;
16179 {
16180     hashitem_T	*hi;
16181 
16182     if (*varname == NUL)
16183     {
16184 	/* Must be something like "s:", otherwise "ht" would be NULL. */
16185 	switch (varname[-2])
16186 	{
16187 	    case 's': return &SCRIPT_SV(current_SID).sv_var;
16188 	    case 'g': return &globvars_var;
16189 	    case 'v': return &vimvars_var;
16190 	    case 'b': return &curbuf->b_bufvar;
16191 	    case 'w': return &curwin->w_winvar;
16192 	    case 'l': return current_funccal == NULL
16193 					? NULL : &current_funccal->l_vars_var;
16194 	    case 'a': return current_funccal == NULL
16195 				       ? NULL : &current_funccal->l_avars_var;
16196 	}
16197 	return NULL;
16198     }
16199 
16200     hi = hash_find(ht, varname);
16201     if (HASHITEM_EMPTY(hi))
16202     {
16203 	/* For global variables we may try auto-loading the script.  If it
16204 	 * worked find the variable again.  Don't auto-load a script if it was
16205 	 * loaded already, otherwise it would be loaded every time when
16206 	 * checking if a function name is a Funcref variable. */
16207 	if (ht == &globvarht && !writing
16208 			    && script_autoload(varname, FALSE) && !aborting())
16209 	    hi = hash_find(ht, varname);
16210 	if (HASHITEM_EMPTY(hi))
16211 	    return NULL;
16212     }
16213     return HI2DI(hi);
16214 }
16215 
16216 /*
16217  * Find the hashtab used for a variable name.
16218  * Set "varname" to the start of name without ':'.
16219  */
16220     static hashtab_T *
16221 find_var_ht(name, varname)
16222     char_u  *name;
16223     char_u  **varname;
16224 {
16225     hashitem_T	*hi;
16226 
16227     if (name[1] != ':')
16228     {
16229 	/* The name must not start with a colon or #. */
16230 	if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
16231 	    return NULL;
16232 	*varname = name;
16233 
16234 	/* "version" is "v:version" in all scopes */
16235 	hi = hash_find(&compat_hashtab, name);
16236 	if (!HASHITEM_EMPTY(hi))
16237 	    return &compat_hashtab;
16238 
16239 	if (current_funccal == NULL)
16240 	    return &globvarht;			/* global variable */
16241 	return &current_funccal->l_vars.dv_hashtab; /* l: variable */
16242     }
16243     *varname = name + 2;
16244     if (*name == 'g')				/* global variable */
16245 	return &globvarht;
16246     /* There must be no ':' or '#' in the rest of the name, unless g: is used
16247      */
16248     if (vim_strchr(name + 2, ':') != NULL
16249 			       || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
16250 	return NULL;
16251     if (*name == 'b')				/* buffer variable */
16252 	return &curbuf->b_vars.dv_hashtab;
16253     if (*name == 'w')				/* window variable */
16254 	return &curwin->w_vars.dv_hashtab;
16255     if (*name == 'v')				/* v: variable */
16256 	return &vimvarht;
16257     if (*name == 'a' && current_funccal != NULL) /* function argument */
16258 	return &current_funccal->l_avars.dv_hashtab;
16259     if (*name == 'l' && current_funccal != NULL) /* local function variable */
16260 	return &current_funccal->l_vars.dv_hashtab;
16261     if (*name == 's'				/* script variable */
16262 	    && current_SID > 0 && current_SID <= ga_scripts.ga_len)
16263 	return &SCRIPT_VARS(current_SID);
16264     return NULL;
16265 }
16266 
16267 /*
16268  * Get the string value of a (global/local) variable.
16269  * Returns NULL when it doesn't exist.
16270  */
16271     char_u *
16272 get_var_value(name)
16273     char_u	*name;
16274 {
16275     dictitem_T	*v;
16276 
16277     v = find_var(name, NULL);
16278     if (v == NULL)
16279 	return NULL;
16280     return get_tv_string(&v->di_tv);
16281 }
16282 
16283 /*
16284  * Allocate a new hashtab for a sourced script.  It will be used while
16285  * sourcing this script and when executing functions defined in the script.
16286  */
16287     void
16288 new_script_vars(id)
16289     scid_T id;
16290 {
16291     int		i;
16292     hashtab_T	*ht;
16293     scriptvar_T *sv;
16294 
16295     if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
16296     {
16297 	/* Re-allocating ga_data means that an ht_array pointing to
16298 	 * ht_smallarray becomes invalid.  We can recognize this: ht_mask is
16299 	 * at its init value.  Also reset "v_dict", it's always the same. */
16300 	for (i = 1; i <= ga_scripts.ga_len; ++i)
16301 	{
16302 	    ht = &SCRIPT_VARS(i);
16303 	    if (ht->ht_mask == HT_INIT_SIZE - 1)
16304 		ht->ht_array = ht->ht_smallarray;
16305 	    sv = &SCRIPT_SV(i);
16306 	    sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
16307 	}
16308 
16309 	while (ga_scripts.ga_len < id)
16310 	{
16311 	    sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
16312 	    init_var_dict(&sv->sv_dict, &sv->sv_var);
16313 	    ++ga_scripts.ga_len;
16314 	}
16315     }
16316 }
16317 
16318 /*
16319  * Initialize dictionary "dict" as a scope and set variable "dict_var" to
16320  * point to it.
16321  */
16322     void
16323 init_var_dict(dict, dict_var)
16324     dict_T	*dict;
16325     dictitem_T	*dict_var;
16326 {
16327     hash_init(&dict->dv_hashtab);
16328     dict->dv_refcount = 99999;
16329     dict_var->di_tv.vval.v_dict = dict;
16330     dict_var->di_tv.v_type = VAR_DICT;
16331     dict_var->di_tv.v_lock = VAR_FIXED;
16332     dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
16333     dict_var->di_key[0] = NUL;
16334 }
16335 
16336 /*
16337  * Clean up a list of internal variables.
16338  * Frees all allocated variables and the value they contain.
16339  * Clears hashtab "ht", does not free it.
16340  */
16341     void
16342 vars_clear(ht)
16343     hashtab_T *ht;
16344 {
16345     vars_clear_ext(ht, TRUE);
16346 }
16347 
16348 /*
16349  * Like vars_clear(), but only free the value if "free_val" is TRUE.
16350  */
16351     static void
16352 vars_clear_ext(ht, free_val)
16353     hashtab_T	*ht;
16354     int		free_val;
16355 {
16356     int		todo;
16357     hashitem_T	*hi;
16358     dictitem_T	*v;
16359 
16360     hash_lock(ht);
16361     todo = ht->ht_used;
16362     for (hi = ht->ht_array; todo > 0; ++hi)
16363     {
16364 	if (!HASHITEM_EMPTY(hi))
16365 	{
16366 	    --todo;
16367 
16368 	    /* Free the variable.  Don't remove it from the hashtab,
16369 	     * ht_array might change then.  hash_clear() takes care of it
16370 	     * later. */
16371 	    v = HI2DI(hi);
16372 	    if (free_val)
16373 		clear_tv(&v->di_tv);
16374 	    if ((v->di_flags & DI_FLAGS_FIX) == 0)
16375 		vim_free(v);
16376 	}
16377     }
16378     hash_clear(ht);
16379     ht->ht_used = 0;
16380 }
16381 
16382 /*
16383  * Delete a variable from hashtab "ht" at item "hi".
16384  * Clear the variable value and free the dictitem.
16385  */
16386     static void
16387 delete_var(ht, hi)
16388     hashtab_T	*ht;
16389     hashitem_T	*hi;
16390 {
16391     dictitem_T	*di = HI2DI(hi);
16392 
16393     hash_remove(ht, hi);
16394     clear_tv(&di->di_tv);
16395     vim_free(di);
16396 }
16397 
16398 /*
16399  * List the value of one internal variable.
16400  */
16401     static void
16402 list_one_var(v, prefix)
16403     dictitem_T	*v;
16404     char_u	*prefix;
16405 {
16406     char_u	*tofree;
16407     char_u	*s;
16408     char_u	numbuf[NUMBUFLEN];
16409 
16410     s = echo_string(&v->di_tv, &tofree, numbuf);
16411     list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
16412 						s == NULL ? (char_u *)"" : s);
16413     vim_free(tofree);
16414 }
16415 
16416     static void
16417 list_one_var_a(prefix, name, type, string)
16418     char_u	*prefix;
16419     char_u	*name;
16420     int		type;
16421     char_u	*string;
16422 {
16423     msg_attr(prefix, 0);    /* don't use msg(), it overwrites "v:statusmsg" */
16424     if (name != NULL)	/* "a:" vars don't have a name stored */
16425 	msg_puts(name);
16426     msg_putchar(' ');
16427     msg_advance(22);
16428     if (type == VAR_NUMBER)
16429 	msg_putchar('#');
16430     else if (type == VAR_FUNC)
16431 	msg_putchar('*');
16432     else if (type == VAR_LIST)
16433     {
16434 	msg_putchar('[');
16435 	if (*string == '[')
16436 	    ++string;
16437     }
16438     else if (type == VAR_DICT)
16439     {
16440 	msg_putchar('{');
16441 	if (*string == '{')
16442 	    ++string;
16443     }
16444     else
16445 	msg_putchar(' ');
16446 
16447     msg_outtrans(string);
16448 
16449     if (type == VAR_FUNC)
16450 	msg_puts((char_u *)"()");
16451 }
16452 
16453 /*
16454  * Set variable "name" to value in "tv".
16455  * If the variable already exists, the value is updated.
16456  * Otherwise the variable is created.
16457  */
16458     static void
16459 set_var(name, tv, copy)
16460     char_u	*name;
16461     typval_T	*tv;
16462     int		copy;	    /* make copy of value in "tv" */
16463 {
16464     dictitem_T	*v;
16465     char_u	*varname;
16466     hashtab_T	*ht;
16467     char_u	*p;
16468 
16469     if (tv->v_type == VAR_FUNC)
16470     {
16471 	if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
16472 		&& !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
16473 							 ? name[2] : name[0]))
16474 	{
16475 	    EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
16476 	    return;
16477 	}
16478 	if (function_exists(name))
16479 	{
16480 	    EMSG2(_("E705: Variable name conflicts with existing function: %s"),
16481 									name);
16482 	    return;
16483 	}
16484     }
16485 
16486     ht = find_var_ht(name, &varname);
16487     if (ht == NULL || *varname == NUL)
16488     {
16489 	EMSG2(_(e_illvar), name);
16490 	return;
16491     }
16492 
16493     v = find_var_in_ht(ht, varname, TRUE);
16494     if (v != NULL)
16495     {
16496 	/* existing variable, need to clear the value */
16497 	if (var_check_ro(v->di_flags, name)
16498 				      || tv_check_lock(v->di_tv.v_lock, name))
16499 	    return;
16500 	if (v->di_tv.v_type != tv->v_type
16501 		&& !((v->di_tv.v_type == VAR_STRING
16502 			|| v->di_tv.v_type == VAR_NUMBER)
16503 		    && (tv->v_type == VAR_STRING
16504 			|| tv->v_type == VAR_NUMBER)))
16505 	{
16506 	    EMSG2(_("E706: Variable type mismatch for: %s"), name);
16507 	    return;
16508 	}
16509 
16510 	/*
16511 	 * Handle setting internal v: variables separately: we don't change
16512 	 * the type.
16513 	 */
16514 	if (ht == &vimvarht)
16515 	{
16516 	    if (v->di_tv.v_type == VAR_STRING)
16517 	    {
16518 		vim_free(v->di_tv.vval.v_string);
16519 		if (copy || tv->v_type != VAR_STRING)
16520 		    v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
16521 		else
16522 		{
16523 		    /* Take over the string to avoid an extra alloc/free. */
16524 		    v->di_tv.vval.v_string = tv->vval.v_string;
16525 		    tv->vval.v_string = NULL;
16526 		}
16527 	    }
16528 	    else if (v->di_tv.v_type != VAR_NUMBER)
16529 		EMSG2(_(e_intern2), "set_var()");
16530 	    else
16531 		v->di_tv.vval.v_number = get_tv_number(tv);
16532 	    return;
16533 	}
16534 
16535 	clear_tv(&v->di_tv);
16536     }
16537     else		    /* add a new variable */
16538     {
16539 	/* Make sure the variable name is valid. */
16540 	for (p = varname; *p != NUL; ++p)
16541 	    if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
16542 						       && *p != AUTOLOAD_CHAR)
16543 	    {
16544 		EMSG2(_(e_illvar), varname);
16545 		return;
16546 	    }
16547 
16548 	v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
16549 							  + STRLEN(varname)));
16550 	if (v == NULL)
16551 	    return;
16552 	STRCPY(v->di_key, varname);
16553 	if (hash_add(ht, DI2HIKEY(v)) == FAIL)
16554 	{
16555 	    vim_free(v);
16556 	    return;
16557 	}
16558 	v->di_flags = 0;
16559     }
16560 
16561     if (copy || tv->v_type == VAR_NUMBER)
16562 	copy_tv(tv, &v->di_tv);
16563     else
16564     {
16565 	v->di_tv = *tv;
16566 	v->di_tv.v_lock = 0;
16567 	init_tv(tv);
16568     }
16569 }
16570 
16571 /*
16572  * Return TRUE if di_flags "flags" indicate read-only variable "name".
16573  * Also give an error message.
16574  */
16575     static int
16576 var_check_ro(flags, name)
16577     int		flags;
16578     char_u	*name;
16579 {
16580     if (flags & DI_FLAGS_RO)
16581     {
16582 	EMSG2(_(e_readonlyvar), name);
16583 	return TRUE;
16584     }
16585     if ((flags & DI_FLAGS_RO_SBX) && sandbox)
16586     {
16587 	EMSG2(_(e_readonlysbx), name);
16588 	return TRUE;
16589     }
16590     return FALSE;
16591 }
16592 
16593 /*
16594  * Return TRUE if typeval "tv" is set to be locked (immutable).
16595  * Also give an error message, using "name".
16596  */
16597     static int
16598 tv_check_lock(lock, name)
16599     int		lock;
16600     char_u	*name;
16601 {
16602     if (lock & VAR_LOCKED)
16603     {
16604 	EMSG2(_("E741: Value is locked: %s"),
16605 				name == NULL ? (char_u *)_("Unknown") : name);
16606 	return TRUE;
16607     }
16608     if (lock & VAR_FIXED)
16609     {
16610 	EMSG2(_("E742: Cannot change value of %s"),
16611 				name == NULL ? (char_u *)_("Unknown") : name);
16612 	return TRUE;
16613     }
16614     return FALSE;
16615 }
16616 
16617 /*
16618  * Copy the values from typval_T "from" to typval_T "to".
16619  * When needed allocates string or increases reference count.
16620  * Does not make a copy of a list or dict but copies the reference!
16621  */
16622     static void
16623 copy_tv(from, to)
16624     typval_T *from;
16625     typval_T *to;
16626 {
16627     to->v_type = from->v_type;
16628     to->v_lock = 0;
16629     switch (from->v_type)
16630     {
16631 	case VAR_NUMBER:
16632 	    to->vval.v_number = from->vval.v_number;
16633 	    break;
16634 	case VAR_STRING:
16635 	case VAR_FUNC:
16636 	    if (from->vval.v_string == NULL)
16637 		to->vval.v_string = NULL;
16638 	    else
16639 	    {
16640 		to->vval.v_string = vim_strsave(from->vval.v_string);
16641 		if (from->v_type == VAR_FUNC)
16642 		    func_ref(to->vval.v_string);
16643 	    }
16644 	    break;
16645 	case VAR_LIST:
16646 	    if (from->vval.v_list == NULL)
16647 		to->vval.v_list = NULL;
16648 	    else
16649 	    {
16650 		to->vval.v_list = from->vval.v_list;
16651 		++to->vval.v_list->lv_refcount;
16652 	    }
16653 	    break;
16654 	case VAR_DICT:
16655 	    if (from->vval.v_dict == NULL)
16656 		to->vval.v_dict = NULL;
16657 	    else
16658 	    {
16659 		to->vval.v_dict = from->vval.v_dict;
16660 		++to->vval.v_dict->dv_refcount;
16661 	    }
16662 	    break;
16663 	default:
16664 	    EMSG2(_(e_intern2), "copy_tv()");
16665 	    break;
16666     }
16667 }
16668 
16669 /*
16670  * Make a copy of an item.
16671  * Lists and Dictionaries are also copied.  A deep copy if "deep" is set.
16672  * For deepcopy() "copyID" is zero for a full copy or the ID for when a
16673  * reference to an already copied list/dict can be used.
16674  * Returns FAIL or OK.
16675  */
16676     static int
16677 item_copy(from, to, deep, copyID)
16678     typval_T	*from;
16679     typval_T	*to;
16680     int		deep;
16681     int		copyID;
16682 {
16683     static int	recurse = 0;
16684     int		ret = OK;
16685 
16686     if (recurse >= DICT_MAXNEST)
16687     {
16688 	EMSG(_("E698: variable nested too deep for making a copy"));
16689 	return FAIL;
16690     }
16691     ++recurse;
16692 
16693     switch (from->v_type)
16694     {
16695 	case VAR_NUMBER:
16696 	case VAR_STRING:
16697 	case VAR_FUNC:
16698 	    copy_tv(from, to);
16699 	    break;
16700 	case VAR_LIST:
16701 	    to->v_type = VAR_LIST;
16702 	    to->v_lock = 0;
16703 	    if (from->vval.v_list == NULL)
16704 		to->vval.v_list = NULL;
16705 	    else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
16706 	    {
16707 		/* use the copy made earlier */
16708 		to->vval.v_list = from->vval.v_list->lv_copylist;
16709 		++to->vval.v_list->lv_refcount;
16710 	    }
16711 	    else
16712 		to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
16713 	    if (to->vval.v_list == NULL)
16714 		ret = FAIL;
16715 	    break;
16716 	case VAR_DICT:
16717 	    to->v_type = VAR_DICT;
16718 	    to->v_lock = 0;
16719 	    if (from->vval.v_dict == NULL)
16720 		to->vval.v_dict = NULL;
16721 	    else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
16722 	    {
16723 		/* use the copy made earlier */
16724 		to->vval.v_dict = from->vval.v_dict->dv_copydict;
16725 		++to->vval.v_dict->dv_refcount;
16726 	    }
16727 	    else
16728 		to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
16729 	    if (to->vval.v_dict == NULL)
16730 		ret = FAIL;
16731 	    break;
16732 	default:
16733 	    EMSG2(_(e_intern2), "item_copy()");
16734 	    ret = FAIL;
16735     }
16736     --recurse;
16737     return ret;
16738 }
16739 
16740 /*
16741  * ":echo expr1 ..."	print each argument separated with a space, add a
16742  *			newline at the end.
16743  * ":echon expr1 ..."	print each argument plain.
16744  */
16745     void
16746 ex_echo(eap)
16747     exarg_T	*eap;
16748 {
16749     char_u	*arg = eap->arg;
16750     typval_T	rettv;
16751     char_u	*tofree;
16752     char_u	*p;
16753     int		needclr = TRUE;
16754     int		atstart = TRUE;
16755     char_u	numbuf[NUMBUFLEN];
16756 
16757     if (eap->skip)
16758 	++emsg_skip;
16759     while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
16760     {
16761 	p = arg;
16762 	if (eval1(&arg, &rettv, !eap->skip) == FAIL)
16763 	{
16764 	    /*
16765 	     * Report the invalid expression unless the expression evaluation
16766 	     * has been cancelled due to an aborting error, an interrupt, or an
16767 	     * exception.
16768 	     */
16769 	    if (!aborting())
16770 		EMSG2(_(e_invexpr2), p);
16771 	    break;
16772 	}
16773 	if (!eap->skip)
16774 	{
16775 	    if (atstart)
16776 	    {
16777 		atstart = FALSE;
16778 		/* Call msg_start() after eval1(), evaluating the expression
16779 		 * may cause a message to appear. */
16780 		if (eap->cmdidx == CMD_echo)
16781 		    msg_start();
16782 	    }
16783 	    else if (eap->cmdidx == CMD_echo)
16784 		msg_puts_attr((char_u *)" ", echo_attr);
16785 	    p = echo_string(&rettv, &tofree, numbuf);
16786 	    if (p != NULL)
16787 		for ( ; *p != NUL && !got_int; ++p)
16788 		{
16789 		    if (*p == '\n' || *p == '\r' || *p == TAB)
16790 		    {
16791 			if (*p != TAB && needclr)
16792 			{
16793 			    /* remove any text still there from the command */
16794 			    msg_clr_eos();
16795 			    needclr = FALSE;
16796 			}
16797 			msg_putchar_attr(*p, echo_attr);
16798 		    }
16799 		    else
16800 		    {
16801 #ifdef FEAT_MBYTE
16802 			if (has_mbyte)
16803 			{
16804 			    int i = (*mb_ptr2len)(p);
16805 
16806 			    (void)msg_outtrans_len_attr(p, i, echo_attr);
16807 			    p += i - 1;
16808 			}
16809 			else
16810 #endif
16811 			    (void)msg_outtrans_len_attr(p, 1, echo_attr);
16812 		    }
16813 		}
16814 	    vim_free(tofree);
16815 	}
16816 	clear_tv(&rettv);
16817 	arg = skipwhite(arg);
16818     }
16819     eap->nextcmd = check_nextcmd(arg);
16820 
16821     if (eap->skip)
16822 	--emsg_skip;
16823     else
16824     {
16825 	/* remove text that may still be there from the command */
16826 	if (needclr)
16827 	    msg_clr_eos();
16828 	if (eap->cmdidx == CMD_echo)
16829 	    msg_end();
16830     }
16831 }
16832 
16833 /*
16834  * ":echohl {name}".
16835  */
16836     void
16837 ex_echohl(eap)
16838     exarg_T	*eap;
16839 {
16840     int		id;
16841 
16842     id = syn_name2id(eap->arg);
16843     if (id == 0)
16844 	echo_attr = 0;
16845     else
16846 	echo_attr = syn_id2attr(id);
16847 }
16848 
16849 /*
16850  * ":execute expr1 ..."	execute the result of an expression.
16851  * ":echomsg expr1 ..."	Print a message
16852  * ":echoerr expr1 ..."	Print an error
16853  * Each gets spaces around each argument and a newline at the end for
16854  * echo commands
16855  */
16856     void
16857 ex_execute(eap)
16858     exarg_T	*eap;
16859 {
16860     char_u	*arg = eap->arg;
16861     typval_T	rettv;
16862     int		ret = OK;
16863     char_u	*p;
16864     garray_T	ga;
16865     int		len;
16866     int		save_did_emsg;
16867 
16868     ga_init2(&ga, 1, 80);
16869 
16870     if (eap->skip)
16871 	++emsg_skip;
16872     while (*arg != NUL && *arg != '|' && *arg != '\n')
16873     {
16874 	p = arg;
16875 	if (eval1(&arg, &rettv, !eap->skip) == FAIL)
16876 	{
16877 	    /*
16878 	     * Report the invalid expression unless the expression evaluation
16879 	     * has been cancelled due to an aborting error, an interrupt, or an
16880 	     * exception.
16881 	     */
16882 	    if (!aborting())
16883 		EMSG2(_(e_invexpr2), p);
16884 	    ret = FAIL;
16885 	    break;
16886 	}
16887 
16888 	if (!eap->skip)
16889 	{
16890 	    p = get_tv_string(&rettv);
16891 	    len = (int)STRLEN(p);
16892 	    if (ga_grow(&ga, len + 2) == FAIL)
16893 	    {
16894 		clear_tv(&rettv);
16895 		ret = FAIL;
16896 		break;
16897 	    }
16898 	    if (ga.ga_len)
16899 		((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
16900 	    STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
16901 	    ga.ga_len += len;
16902 	}
16903 
16904 	clear_tv(&rettv);
16905 	arg = skipwhite(arg);
16906     }
16907 
16908     if (ret != FAIL && ga.ga_data != NULL)
16909     {
16910 	if (eap->cmdidx == CMD_echomsg)
16911 	{
16912 	    MSG_ATTR(ga.ga_data, echo_attr);
16913 	    out_flush();
16914 	}
16915 	else if (eap->cmdidx == CMD_echoerr)
16916 	{
16917 	    /* We don't want to abort following commands, restore did_emsg. */
16918 	    save_did_emsg = did_emsg;
16919 	    EMSG((char_u *)ga.ga_data);
16920 	    if (!force_abort)
16921 		did_emsg = save_did_emsg;
16922 	}
16923 	else if (eap->cmdidx == CMD_execute)
16924 	    do_cmdline((char_u *)ga.ga_data,
16925 		       eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
16926     }
16927 
16928     ga_clear(&ga);
16929 
16930     if (eap->skip)
16931 	--emsg_skip;
16932 
16933     eap->nextcmd = check_nextcmd(arg);
16934 }
16935 
16936 /*
16937  * Skip over the name of an option: "&option", "&g:option" or "&l:option".
16938  * "arg" points to the "&" or '+' when called, to "option" when returning.
16939  * Returns NULL when no option name found.  Otherwise pointer to the char
16940  * after the option name.
16941  */
16942     static char_u *
16943 find_option_end(arg, opt_flags)
16944     char_u	**arg;
16945     int		*opt_flags;
16946 {
16947     char_u	*p = *arg;
16948 
16949     ++p;
16950     if (*p == 'g' && p[1] == ':')
16951     {
16952 	*opt_flags = OPT_GLOBAL;
16953 	p += 2;
16954     }
16955     else if (*p == 'l' && p[1] == ':')
16956     {
16957 	*opt_flags = OPT_LOCAL;
16958 	p += 2;
16959     }
16960     else
16961 	*opt_flags = 0;
16962 
16963     if (!ASCII_ISALPHA(*p))
16964 	return NULL;
16965     *arg = p;
16966 
16967     if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
16968 	p += 4;	    /* termcap option */
16969     else
16970 	while (ASCII_ISALPHA(*p))
16971 	    ++p;
16972     return p;
16973 }
16974 
16975 /*
16976  * ":function"
16977  */
16978     void
16979 ex_function(eap)
16980     exarg_T	*eap;
16981 {
16982     char_u	*theline;
16983     int		j;
16984     int		c;
16985     int		saved_did_emsg;
16986     char_u	*name = NULL;
16987     char_u	*p;
16988     char_u	*arg;
16989     garray_T	newargs;
16990     garray_T	newlines;
16991     int		varargs = FALSE;
16992     int		mustend = FALSE;
16993     int		flags = 0;
16994     ufunc_T	*fp;
16995     int		indent;
16996     int		nesting;
16997     char_u	*skip_until = NULL;
16998     dictitem_T	*v;
16999     funcdict_T	fudi;
17000     static int	func_nr = 0;	    /* number for nameless function */
17001     int		paren;
17002     hashtab_T	*ht;
17003     int		todo;
17004     hashitem_T	*hi;
17005 
17006     /*
17007      * ":function" without argument: list functions.
17008      */
17009     if (ends_excmd(*eap->arg))
17010     {
17011 	if (!eap->skip)
17012 	{
17013 	    todo = func_hashtab.ht_used;
17014 	    for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
17015 	    {
17016 		if (!HASHITEM_EMPTY(hi))
17017 		{
17018 		    --todo;
17019 		    fp = HI2UF(hi);
17020 		    if (!isdigit(*fp->uf_name))
17021 			list_func_head(fp, FALSE);
17022 		}
17023 	    }
17024 	}
17025 	eap->nextcmd = check_nextcmd(eap->arg);
17026 	return;
17027     }
17028 
17029     /*
17030      * ":function /pat": list functions matching pattern.
17031      */
17032     if (*eap->arg == '/')
17033     {
17034 	p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
17035 	if (!eap->skip)
17036 	{
17037 	    regmatch_T	regmatch;
17038 
17039 	    c = *p;
17040 	    *p = NUL;
17041 	    regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
17042 	    *p = c;
17043 	    if (regmatch.regprog != NULL)
17044 	    {
17045 		regmatch.rm_ic = p_ic;
17046 
17047 		todo = func_hashtab.ht_used;
17048 		for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
17049 		{
17050 		    if (!HASHITEM_EMPTY(hi))
17051 		    {
17052 			--todo;
17053 			fp = HI2UF(hi);
17054 			if (!isdigit(*fp->uf_name)
17055 				    && vim_regexec(&regmatch, fp->uf_name, 0))
17056 			    list_func_head(fp, FALSE);
17057 		    }
17058 		}
17059 	    }
17060 	}
17061 	if (*p == '/')
17062 	    ++p;
17063 	eap->nextcmd = check_nextcmd(p);
17064 	return;
17065     }
17066 
17067     /*
17068      * Get the function name.  There are these situations:
17069      * func	    normal function name
17070      *		    "name" == func, "fudi.fd_dict" == NULL
17071      * dict.func    new dictionary entry
17072      *		    "name" == NULL, "fudi.fd_dict" set,
17073      *		    "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
17074      * dict.func    existing dict entry with a Funcref
17075      *		    "name" == func, "fudi.fd_dict" set,
17076      *		    "fudi.fd_di" set, "fudi.fd_newkey" == NULL
17077      * dict.func    existing dict entry that's not a Funcref
17078      *		    "name" == NULL, "fudi.fd_dict" set,
17079      *		    "fudi.fd_di" set, "fudi.fd_newkey" == NULL
17080      */
17081     p = eap->arg;
17082     name = trans_function_name(&p, eap->skip, 0, &fudi);
17083     paren = (vim_strchr(p, '(') != NULL);
17084     if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
17085     {
17086 	/*
17087 	 * Return on an invalid expression in braces, unless the expression
17088 	 * evaluation has been cancelled due to an aborting error, an
17089 	 * interrupt, or an exception.
17090 	 */
17091 	if (!aborting())
17092 	{
17093 	    if (!eap->skip && fudi.fd_newkey != NULL)
17094 		EMSG2(_(e_dictkey), fudi.fd_newkey);
17095 	    vim_free(fudi.fd_newkey);
17096 	    return;
17097 	}
17098 	else
17099 	    eap->skip = TRUE;
17100     }
17101     /* An error in a function call during evaluation of an expression in magic
17102      * braces should not cause the function not to be defined. */
17103     saved_did_emsg = did_emsg;
17104     did_emsg = FALSE;
17105 
17106     /*
17107      * ":function func" with only function name: list function.
17108      */
17109     if (!paren)
17110     {
17111 	if (!ends_excmd(*skipwhite(p)))
17112 	{
17113 	    EMSG(_(e_trailing));
17114 	    goto ret_free;
17115 	}
17116 	eap->nextcmd = check_nextcmd(p);
17117 	if (eap->nextcmd != NULL)
17118 	    *p = NUL;
17119 	if (!eap->skip && !got_int)
17120 	{
17121 	    fp = find_func(name);
17122 	    if (fp != NULL)
17123 	    {
17124 		list_func_head(fp, TRUE);
17125 		for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
17126 		{
17127 		    msg_putchar('\n');
17128 		    msg_outnum((long)(j + 1));
17129 		    if (j < 9)
17130 			msg_putchar(' ');
17131 		    if (j < 99)
17132 			msg_putchar(' ');
17133 		    msg_prt_line(FUNCLINE(fp, j), FALSE);
17134 		    out_flush();	/* show a line at a time */
17135 		    ui_breakcheck();
17136 		}
17137 		if (!got_int)
17138 		{
17139 		    msg_putchar('\n');
17140 		    msg_puts((char_u *)"   endfunction");
17141 		}
17142 	    }
17143 	    else
17144 		emsg_funcname("E123: Undefined function: %s", name);
17145 	}
17146 	goto ret_free;
17147     }
17148 
17149     /*
17150      * ":function name(arg1, arg2)" Define function.
17151      */
17152     p = skipwhite(p);
17153     if (*p != '(')
17154     {
17155 	if (!eap->skip)
17156 	{
17157 	    EMSG2(_("E124: Missing '(': %s"), eap->arg);
17158 	    goto ret_free;
17159 	}
17160 	/* attempt to continue by skipping some text */
17161 	if (vim_strchr(p, '(') != NULL)
17162 	    p = vim_strchr(p, '(');
17163     }
17164     p = skipwhite(p + 1);
17165 
17166     ga_init2(&newargs, (int)sizeof(char_u *), 3);
17167     ga_init2(&newlines, (int)sizeof(char_u *), 3);
17168 
17169     if (!eap->skip)
17170     {
17171 	/* Check the name of the function. */
17172 	if (name != NULL)
17173 	    arg = name;
17174 	else
17175 	    arg = fudi.fd_newkey;
17176 	if (arg != NULL)
17177 	{
17178 	    if (*arg == K_SPECIAL)
17179 		j = 3;
17180 	    else
17181 		j = 0;
17182 	    while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
17183 						      : eval_isnamec(arg[j])))
17184 		++j;
17185 	    if (arg[j] != NUL)
17186 		emsg_funcname(_(e_invarg2), arg);
17187 	}
17188     }
17189 
17190     /*
17191      * Isolate the arguments: "arg1, arg2, ...)"
17192      */
17193     while (*p != ')')
17194     {
17195 	if (p[0] == '.' && p[1] == '.' && p[2] == '.')
17196 	{
17197 	    varargs = TRUE;
17198 	    p += 3;
17199 	    mustend = TRUE;
17200 	}
17201 	else
17202 	{
17203 	    arg = p;
17204 	    while (ASCII_ISALNUM(*p) || *p == '_')
17205 		++p;
17206 	    if (arg == p || isdigit(*arg)
17207 		    || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
17208 		    || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
17209 	    {
17210 		if (!eap->skip)
17211 		    EMSG2(_("E125: Illegal argument: %s"), arg);
17212 		break;
17213 	    }
17214 	    if (ga_grow(&newargs, 1) == FAIL)
17215 		goto erret;
17216 	    c = *p;
17217 	    *p = NUL;
17218 	    arg = vim_strsave(arg);
17219 	    if (arg == NULL)
17220 		goto erret;
17221 	    ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
17222 	    *p = c;
17223 	    newargs.ga_len++;
17224 	    if (*p == ',')
17225 		++p;
17226 	    else
17227 		mustend = TRUE;
17228 	}
17229 	p = skipwhite(p);
17230 	if (mustend && *p != ')')
17231 	{
17232 	    if (!eap->skip)
17233 		EMSG2(_(e_invarg2), eap->arg);
17234 	    break;
17235 	}
17236     }
17237     ++p;	/* skip the ')' */
17238 
17239     /* find extra arguments "range", "dict" and "abort" */
17240     for (;;)
17241     {
17242 	p = skipwhite(p);
17243 	if (STRNCMP(p, "range", 5) == 0)
17244 	{
17245 	    flags |= FC_RANGE;
17246 	    p += 5;
17247 	}
17248 	else if (STRNCMP(p, "dict", 4) == 0)
17249 	{
17250 	    flags |= FC_DICT;
17251 	    p += 4;
17252 	}
17253 	else if (STRNCMP(p, "abort", 5) == 0)
17254 	{
17255 	    flags |= FC_ABORT;
17256 	    p += 5;
17257 	}
17258 	else
17259 	    break;
17260     }
17261 
17262     if (*p != NUL && *p != '"' && *p != '\n' && !eap->skip && !did_emsg)
17263 	EMSG(_(e_trailing));
17264 
17265     /*
17266      * Read the body of the function, until ":endfunction" is found.
17267      */
17268     if (KeyTyped)
17269     {
17270 	/* Check if the function already exists, don't let the user type the
17271 	 * whole function before telling him it doesn't work!  For a script we
17272 	 * need to skip the body to be able to find what follows. */
17273 	if (!eap->skip && !eap->forceit)
17274 	{
17275 	    if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
17276 		EMSG(_(e_funcdict));
17277 	    else if (name != NULL && find_func(name) != NULL)
17278 		emsg_funcname(e_funcexts, name);
17279 	}
17280 
17281 	if (!eap->skip && did_emsg)
17282 	    goto erret;
17283 
17284 	msg_putchar('\n');	    /* don't overwrite the function name */
17285 	cmdline_row = msg_row;
17286     }
17287 
17288     indent = 2;
17289     nesting = 0;
17290     for (;;)
17291     {
17292 	msg_scroll = TRUE;
17293 	need_wait_return = FALSE;
17294 	if (eap->getline == NULL)
17295 	    theline = getcmdline(':', 0L, indent);
17296 	else
17297 	    theline = eap->getline(':', eap->cookie, indent);
17298 	if (KeyTyped)
17299 	    lines_left = Rows - 1;
17300 	if (theline == NULL)
17301 	{
17302 	    EMSG(_("E126: Missing :endfunction"));
17303 	    goto erret;
17304 	}
17305 
17306 	if (skip_until != NULL)
17307 	{
17308 	    /* between ":append" and "." and between ":python <<EOF" and "EOF"
17309 	     * don't check for ":endfunc". */
17310 	    if (STRCMP(theline, skip_until) == 0)
17311 	    {
17312 		vim_free(skip_until);
17313 		skip_until = NULL;
17314 	    }
17315 	}
17316 	else
17317 	{
17318 	    /* skip ':' and blanks*/
17319 	    for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
17320 		;
17321 
17322 	    /* Check for "endfunction". */
17323 	    if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
17324 	    {
17325 		vim_free(theline);
17326 		break;
17327 	    }
17328 
17329 	    /* Increase indent inside "if", "while", "for" and "try", decrease
17330 	     * at "end". */
17331 	    if (indent > 2 && STRNCMP(p, "end", 3) == 0)
17332 		indent -= 2;
17333 	    else if (STRNCMP(p, "if", 2) == 0
17334 		    || STRNCMP(p, "wh", 2) == 0
17335 		    || STRNCMP(p, "for", 3) == 0
17336 		    || STRNCMP(p, "try", 3) == 0)
17337 		indent += 2;
17338 
17339 	    /* Check for defining a function inside this function. */
17340 	    if (checkforcmd(&p, "function", 2))
17341 	    {
17342 		if (*p == '!')
17343 		    p = skipwhite(p + 1);
17344 		p += eval_fname_script(p);
17345 		if (ASCII_ISALPHA(*p))
17346 		{
17347 		    vim_free(trans_function_name(&p, TRUE, 0, NULL));
17348 		    if (*skipwhite(p) == '(')
17349 		    {
17350 			++nesting;
17351 			indent += 2;
17352 		    }
17353 		}
17354 	    }
17355 
17356 	    /* Check for ":append" or ":insert". */
17357 	    p = skip_range(p, NULL);
17358 	    if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
17359 		    || (p[0] == 'i'
17360 			&& (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
17361 				&& (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
17362 		skip_until = vim_strsave((char_u *)".");
17363 
17364 	    /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
17365 	    arg = skipwhite(skiptowhite(p));
17366 	    if (arg[0] == '<' && arg[1] =='<'
17367 		    && ((p[0] == 'p' && p[1] == 'y'
17368 				    && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
17369 			|| (p[0] == 'p' && p[1] == 'e'
17370 				    && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
17371 			|| (p[0] == 't' && p[1] == 'c'
17372 				    && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
17373 			|| (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
17374 				    && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
17375 			|| (p[0] == 'm' && p[1] == 'z'
17376 				    && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
17377 			))
17378 	    {
17379 		/* ":python <<" continues until a dot, like ":append" */
17380 		p = skipwhite(arg + 2);
17381 		if (*p == NUL)
17382 		    skip_until = vim_strsave((char_u *)".");
17383 		else
17384 		    skip_until = vim_strsave(p);
17385 	    }
17386 	}
17387 
17388 	/* Add the line to the function. */
17389 	if (ga_grow(&newlines, 1) == FAIL)
17390 	{
17391 	    vim_free(theline);
17392 	    goto erret;
17393 	}
17394 
17395 	/* Copy the line to newly allocated memory.  get_one_sourceline()
17396 	 * allocates 250 bytes per line, this saves 80% on average.  The cost
17397 	 * is an extra alloc/free. */
17398 	p = vim_strsave(theline);
17399 	if (p != NULL)
17400 	{
17401 	    vim_free(theline);
17402 	    theline = p;
17403 	}
17404 
17405 	((char_u **)(newlines.ga_data))[newlines.ga_len] = theline;
17406 	newlines.ga_len++;
17407     }
17408 
17409     /* Don't define the function when skipping commands or when an error was
17410      * detected. */
17411     if (eap->skip || did_emsg)
17412 	goto erret;
17413 
17414     /*
17415      * If there are no errors, add the function
17416      */
17417     if (fudi.fd_dict == NULL)
17418     {
17419 	v = find_var(name, &ht);
17420 	if (v != NULL && v->di_tv.v_type == VAR_FUNC)
17421 	{
17422 	    emsg_funcname("E707: Function name conflicts with variable: %s",
17423 									name);
17424 	    goto erret;
17425 	}
17426 
17427 	fp = find_func(name);
17428 	if (fp != NULL)
17429 	{
17430 	    if (!eap->forceit)
17431 	    {
17432 		emsg_funcname(e_funcexts, name);
17433 		goto erret;
17434 	    }
17435 	    if (fp->uf_calls > 0)
17436 	    {
17437 		emsg_funcname("E127: Cannot redefine function %s: It is in use",
17438 									name);
17439 		goto erret;
17440 	    }
17441 	    /* redefine existing function */
17442 	    ga_clear_strings(&(fp->uf_args));
17443 	    ga_clear_strings(&(fp->uf_lines));
17444 	    vim_free(name);
17445 	    name = NULL;
17446 	}
17447     }
17448     else
17449     {
17450 	char	numbuf[20];
17451 
17452 	fp = NULL;
17453 	if (fudi.fd_newkey == NULL && !eap->forceit)
17454 	{
17455 	    EMSG(_(e_funcdict));
17456 	    goto erret;
17457 	}
17458 	if (fudi.fd_di == NULL)
17459 	{
17460 	    /* Can't add a function to a locked dictionary */
17461 	    if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
17462 		goto erret;
17463 	}
17464 	    /* Can't change an existing function if it is locked */
17465 	else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
17466 	    goto erret;
17467 
17468 	/* Give the function a sequential number.  Can only be used with a
17469 	 * Funcref! */
17470 	vim_free(name);
17471 	sprintf(numbuf, "%d", ++func_nr);
17472 	name = vim_strsave((char_u *)numbuf);
17473 	if (name == NULL)
17474 	    goto erret;
17475     }
17476 
17477     if (fp == NULL)
17478     {
17479 	if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
17480 	{
17481 	    int	    slen, plen;
17482 	    char_u  *scriptname;
17483 
17484 	    /* Check that the autoload name matches the script name. */
17485 	    j = FAIL;
17486 	    if (sourcing_name != NULL)
17487 	    {
17488 		scriptname = autoload_name(name);
17489 		if (scriptname != NULL)
17490 		{
17491 		    p = vim_strchr(scriptname, '/');
17492 		    plen = STRLEN(p);
17493 		    slen = STRLEN(sourcing_name);
17494 		    if (slen > plen && fnamecmp(p,
17495 					    sourcing_name + slen - plen) == 0)
17496 			j = OK;
17497 		    vim_free(scriptname);
17498 		}
17499 	    }
17500 	    if (j == FAIL)
17501 	    {
17502 		EMSG2(_("E746: Function name does not match script file name: %s"), name);
17503 		goto erret;
17504 	    }
17505 	}
17506 
17507 	fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
17508 	if (fp == NULL)
17509 	    goto erret;
17510 
17511 	if (fudi.fd_dict != NULL)
17512 	{
17513 	    if (fudi.fd_di == NULL)
17514 	    {
17515 		/* add new dict entry */
17516 		fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
17517 		if (fudi.fd_di == NULL)
17518 		{
17519 		    vim_free(fp);
17520 		    goto erret;
17521 		}
17522 		if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
17523 		{
17524 		    vim_free(fudi.fd_di);
17525 		    goto erret;
17526 		}
17527 	    }
17528 	    else
17529 		/* overwrite existing dict entry */
17530 		clear_tv(&fudi.fd_di->di_tv);
17531 	    fudi.fd_di->di_tv.v_type = VAR_FUNC;
17532 	    fudi.fd_di->di_tv.v_lock = 0;
17533 	    fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
17534 	    fp->uf_refcount = 1;
17535 	}
17536 
17537 	/* insert the new function in the function list */
17538 	STRCPY(fp->uf_name, name);
17539 	hash_add(&func_hashtab, UF2HIKEY(fp));
17540     }
17541     fp->uf_args = newargs;
17542     fp->uf_lines = newlines;
17543 #ifdef FEAT_PROFILE
17544     fp->uf_tml_count = NULL;
17545     fp->uf_tml_total = NULL;
17546     fp->uf_tml_self = NULL;
17547     fp->uf_profiling = FALSE;
17548     if (prof_def_func())
17549 	func_do_profile(fp);
17550 #endif
17551     fp->uf_varargs = varargs;
17552     fp->uf_flags = flags;
17553     fp->uf_calls = 0;
17554     fp->uf_script_ID = current_SID;
17555     goto ret_free;
17556 
17557 erret:
17558     ga_clear_strings(&newargs);
17559     ga_clear_strings(&newlines);
17560 ret_free:
17561     vim_free(skip_until);
17562     vim_free(fudi.fd_newkey);
17563     vim_free(name);
17564     did_emsg |= saved_did_emsg;
17565 }
17566 
17567 /*
17568  * Get a function name, translating "<SID>" and "<SNR>".
17569  * Also handles a Funcref in a List or Dictionary.
17570  * Returns the function name in allocated memory, or NULL for failure.
17571  * flags:
17572  * TFN_INT:   internal function name OK
17573  * TFN_QUIET: be quiet
17574  * Advances "pp" to just after the function name (if no error).
17575  */
17576     static char_u *
17577 trans_function_name(pp, skip, flags, fdp)
17578     char_u	**pp;
17579     int		skip;		/* only find the end, don't evaluate */
17580     int		flags;
17581     funcdict_T	*fdp;		/* return: info about dictionary used */
17582 {
17583     char_u	*name = NULL;
17584     char_u	*start;
17585     char_u	*end;
17586     int		lead;
17587     char_u	sid_buf[20];
17588     int		len;
17589     lval_T	lv;
17590 
17591     if (fdp != NULL)
17592 	vim_memset(fdp, 0, sizeof(funcdict_T));
17593     start = *pp;
17594 
17595     /* Check for hard coded <SNR>: already translated function ID (from a user
17596      * command). */
17597     if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
17598 						   && (*pp)[2] == (int)KE_SNR)
17599     {
17600 	*pp += 3;
17601 	len = get_id_len(pp) + 3;
17602 	return vim_strnsave(start, len);
17603     }
17604 
17605     /* A name starting with "<SID>" or "<SNR>" is local to a script.  But
17606      * don't skip over "s:", get_lval() needs it for "s:dict.func". */
17607     lead = eval_fname_script(start);
17608     if (lead > 2)
17609 	start += lead;
17610 
17611     end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
17612 					      lead > 2 ? 0 : FNE_CHECK_START);
17613     if (end == start)
17614     {
17615 	if (!skip)
17616 	    EMSG(_("E129: Function name required"));
17617 	goto theend;
17618     }
17619     if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
17620     {
17621 	/*
17622 	 * Report an invalid expression in braces, unless the expression
17623 	 * evaluation has been cancelled due to an aborting error, an
17624 	 * interrupt, or an exception.
17625 	 */
17626 	if (!aborting())
17627 	{
17628 	    if (end != NULL)
17629 		EMSG2(_(e_invarg2), start);
17630 	}
17631 	else
17632 	    *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
17633 	goto theend;
17634     }
17635 
17636     if (lv.ll_tv != NULL)
17637     {
17638 	if (fdp != NULL)
17639 	{
17640 	    fdp->fd_dict = lv.ll_dict;
17641 	    fdp->fd_newkey = lv.ll_newkey;
17642 	    lv.ll_newkey = NULL;
17643 	    fdp->fd_di = lv.ll_di;
17644 	}
17645 	if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
17646 	{
17647 	    name = vim_strsave(lv.ll_tv->vval.v_string);
17648 	    *pp = end;
17649 	}
17650 	else
17651 	{
17652 	    if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
17653 			     || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
17654 		EMSG(_(e_funcref));
17655 	    else
17656 		*pp = end;
17657 	    name = NULL;
17658 	}
17659 	goto theend;
17660     }
17661 
17662     if (lv.ll_name == NULL)
17663     {
17664 	/* Error found, but continue after the function name. */
17665 	*pp = end;
17666 	goto theend;
17667     }
17668 
17669     if (lv.ll_exp_name != NULL)
17670     {
17671 	len = STRLEN(lv.ll_exp_name);
17672 	if (lead <= 2 && lv.ll_name == lv.ll_exp_name
17673 					 && STRNCMP(lv.ll_name, "s:", 2) == 0)
17674 	{
17675 	    /* When there was "s:" already or the name expanded to get a
17676 	     * leading "s:" then remove it. */
17677 	    lv.ll_name += 2;
17678 	    len -= 2;
17679 	    lead = 2;
17680 	}
17681     }
17682     else
17683     {
17684 	if (lead == 2)	/* skip over "s:" */
17685 	    lv.ll_name += 2;
17686 	len = (int)(end - lv.ll_name);
17687     }
17688 
17689     /*
17690      * Copy the function name to allocated memory.
17691      * Accept <SID>name() inside a script, translate into <SNR>123_name().
17692      * Accept <SNR>123_name() outside a script.
17693      */
17694     if (skip)
17695 	lead = 0;	/* do nothing */
17696     else if (lead > 0)
17697     {
17698 	lead = 3;
17699 	if (eval_fname_sid(*pp))	/* If it's "<SID>" */
17700 	{
17701 	    if (current_SID <= 0)
17702 	    {
17703 		EMSG(_(e_usingsid));
17704 		goto theend;
17705 	    }
17706 	    sprintf((char *)sid_buf, "%ld_", (long)current_SID);
17707 	    lead += (int)STRLEN(sid_buf);
17708 	}
17709     }
17710     else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
17711     {
17712 	EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
17713 	goto theend;
17714     }
17715     name = alloc((unsigned)(len + lead + 1));
17716     if (name != NULL)
17717     {
17718 	if (lead > 0)
17719 	{
17720 	    name[0] = K_SPECIAL;
17721 	    name[1] = KS_EXTRA;
17722 	    name[2] = (int)KE_SNR;
17723 	    if (lead > 3)	/* If it's "<SID>" */
17724 		STRCPY(name + 3, sid_buf);
17725 	}
17726 	mch_memmove(name + lead, lv.ll_name, (size_t)len);
17727 	name[len + lead] = NUL;
17728     }
17729     *pp = end;
17730 
17731 theend:
17732     clear_lval(&lv);
17733     return name;
17734 }
17735 
17736 /*
17737  * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
17738  * Return 2 if "p" starts with "s:".
17739  * Return 0 otherwise.
17740  */
17741     static int
17742 eval_fname_script(p)
17743     char_u	*p;
17744 {
17745     if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
17746 					  || STRNICMP(p + 1, "SNR>", 4) == 0))
17747 	return 5;
17748     if (p[0] == 's' && p[1] == ':')
17749 	return 2;
17750     return 0;
17751 }
17752 
17753 /*
17754  * Return TRUE if "p" starts with "<SID>" or "s:".
17755  * Only works if eval_fname_script() returned non-zero for "p"!
17756  */
17757     static int
17758 eval_fname_sid(p)
17759     char_u	*p;
17760 {
17761     return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
17762 }
17763 
17764 /*
17765  * List the head of the function: "name(arg1, arg2)".
17766  */
17767     static void
17768 list_func_head(fp, indent)
17769     ufunc_T	*fp;
17770     int		indent;
17771 {
17772     int		j;
17773 
17774     msg_start();
17775     if (indent)
17776 	MSG_PUTS("   ");
17777     MSG_PUTS("function ");
17778     if (fp->uf_name[0] == K_SPECIAL)
17779     {
17780 	MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
17781 	msg_puts(fp->uf_name + 3);
17782     }
17783     else
17784 	msg_puts(fp->uf_name);
17785     msg_putchar('(');
17786     for (j = 0; j < fp->uf_args.ga_len; ++j)
17787     {
17788 	if (j)
17789 	    MSG_PUTS(", ");
17790 	msg_puts(FUNCARG(fp, j));
17791     }
17792     if (fp->uf_varargs)
17793     {
17794 	if (j)
17795 	    MSG_PUTS(", ");
17796 	MSG_PUTS("...");
17797     }
17798     msg_putchar(')');
17799     msg_clr_eos();
17800     if (p_verbose > 0)
17801 	last_set_msg(fp->uf_script_ID);
17802 }
17803 
17804 /*
17805  * Find a function by name, return pointer to it in ufuncs.
17806  * Return NULL for unknown function.
17807  */
17808     static ufunc_T *
17809 find_func(name)
17810     char_u	*name;
17811 {
17812     hashitem_T	*hi;
17813 
17814     hi = hash_find(&func_hashtab, name);
17815     if (!HASHITEM_EMPTY(hi))
17816 	return HI2UF(hi);
17817     return NULL;
17818 }
17819 
17820 #if defined(EXITFREE) || defined(PROTO)
17821     void
17822 free_all_functions()
17823 {
17824     hashitem_T	*hi;
17825 
17826     /* Need to start all over every time, because func_free() may change the
17827      * hash table. */
17828     while (func_hashtab.ht_used > 0)
17829 	for (hi = func_hashtab.ht_array; ; ++hi)
17830 	    if (!HASHITEM_EMPTY(hi))
17831 	    {
17832 		func_free(HI2UF(hi));
17833 		break;
17834 	    }
17835 }
17836 #endif
17837 
17838 /*
17839  * Return TRUE if a function "name" exists.
17840  */
17841     static int
17842 function_exists(name)
17843     char_u *name;
17844 {
17845     char_u  *p = name;
17846     int	    n = FALSE;
17847 
17848     p = trans_function_name(&p, FALSE, TFN_INT|TFN_QUIET, NULL);
17849     if (p != NULL)
17850     {
17851 	if (builtin_function(p))
17852 	    n = (find_internal_func(p) >= 0);
17853 	else
17854 	    n = (find_func(p) != NULL);
17855 	vim_free(p);
17856     }
17857     return n;
17858 }
17859 
17860 /*
17861  * Return TRUE if "name" looks like a builtin function name: starts with a
17862  * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
17863  */
17864     static int
17865 builtin_function(name)
17866     char_u *name;
17867 {
17868     return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
17869 				   && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
17870 }
17871 
17872 #if defined(FEAT_PROFILE) || defined(PROTO)
17873 /*
17874  * Start profiling function "fp".
17875  */
17876     static void
17877 func_do_profile(fp)
17878     ufunc_T	*fp;
17879 {
17880     fp->uf_tm_count = 0;
17881     profile_zero(&fp->uf_tm_self);
17882     profile_zero(&fp->uf_tm_total);
17883     if (fp->uf_tml_count == NULL)
17884 	fp->uf_tml_count = (int *)alloc_clear((unsigned)
17885 					 (sizeof(int) * fp->uf_lines.ga_len));
17886     if (fp->uf_tml_total == NULL)
17887 	fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
17888 				  (sizeof(proftime_T) * fp->uf_lines.ga_len));
17889     if (fp->uf_tml_self == NULL)
17890 	fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
17891 				  (sizeof(proftime_T) * fp->uf_lines.ga_len));
17892     fp->uf_tml_idx = -1;
17893     if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
17894 						   || fp->uf_tml_self == NULL)
17895 	return;	    /* out of memory */
17896 
17897     fp->uf_profiling = TRUE;
17898 }
17899 
17900 /*
17901  * Dump the profiling results for all functions in file "fd".
17902  */
17903     void
17904 func_dump_profile(fd)
17905     FILE    *fd;
17906 {
17907     hashitem_T	*hi;
17908     int		todo;
17909     ufunc_T	*fp;
17910     int		i;
17911     ufunc_T	**sorttab;
17912     int		st_len = 0;
17913 
17914     todo = func_hashtab.ht_used;
17915     sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
17916 
17917     for (hi = func_hashtab.ht_array; todo > 0; ++hi)
17918     {
17919 	if (!HASHITEM_EMPTY(hi))
17920 	{
17921 	    --todo;
17922 	    fp = HI2UF(hi);
17923 	    if (fp->uf_profiling)
17924 	    {
17925 		if (sorttab != NULL)
17926 		    sorttab[st_len++] = fp;
17927 
17928 		if (fp->uf_name[0] == K_SPECIAL)
17929 		    fprintf(fd, "FUNCTION  <SNR>%s()\n", fp->uf_name + 3);
17930 		else
17931 		    fprintf(fd, "FUNCTION  %s()\n", fp->uf_name);
17932 		if (fp->uf_tm_count == 1)
17933 		    fprintf(fd, "Called 1 time\n");
17934 		else
17935 		    fprintf(fd, "Called %d times\n", fp->uf_tm_count);
17936 		fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
17937 		fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
17938 		fprintf(fd, "\n");
17939 		fprintf(fd, "count  total (s)   self (s)\n");
17940 
17941 		for (i = 0; i < fp->uf_lines.ga_len; ++i)
17942 		{
17943 		    prof_func_line(fd, fp->uf_tml_count[i],
17944 			     &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
17945 		    fprintf(fd, "%s\n", FUNCLINE(fp, i));
17946 		}
17947 		fprintf(fd, "\n");
17948 	    }
17949 	}
17950     }
17951 
17952     if (sorttab != NULL && st_len > 0)
17953     {
17954 	qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
17955 							      prof_total_cmp);
17956 	prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
17957 	qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
17958 							      prof_self_cmp);
17959 	prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
17960     }
17961 }
17962 
17963     static void
17964 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
17965     FILE	*fd;
17966     ufunc_T	**sorttab;
17967     int		st_len;
17968     char	*title;
17969     int		prefer_self;	/* when equal print only self time */
17970 {
17971     int		i;
17972     ufunc_T	*fp;
17973 
17974     fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
17975     fprintf(fd, "count  total (s)   self (s)  function\n");
17976     for (i = 0; i < 20 && i < st_len; ++i)
17977     {
17978 	fp = sorttab[i];
17979 	prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
17980 								 prefer_self);
17981 	if (fp->uf_name[0] == K_SPECIAL)
17982 	    fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
17983 	else
17984 	    fprintf(fd, " %s()\n", fp->uf_name);
17985     }
17986     fprintf(fd, "\n");
17987 }
17988 
17989 /*
17990  * Print the count and times for one function or function line.
17991  */
17992     static void
17993 prof_func_line(fd, count, total, self, prefer_self)
17994     FILE	*fd;
17995     int		count;
17996     proftime_T	*total;
17997     proftime_T	*self;
17998     int		prefer_self;	/* when equal print only self time */
17999 {
18000     if (count > 0)
18001     {
18002 	fprintf(fd, "%5d ", count);
18003 	if (prefer_self && profile_equal(total, self))
18004 	    fprintf(fd, "           ");
18005 	else
18006 	    fprintf(fd, "%s ", profile_msg(total));
18007 	if (!prefer_self && profile_equal(total, self))
18008 	    fprintf(fd, "           ");
18009 	else
18010 	    fprintf(fd, "%s ", profile_msg(self));
18011     }
18012     else
18013 	fprintf(fd, "                            ");
18014 }
18015 
18016 /*
18017  * Compare function for total time sorting.
18018  */
18019     static int
18020 #ifdef __BORLANDC__
18021 _RTLENTRYF
18022 #endif
18023 prof_total_cmp(s1, s2)
18024     const void	*s1;
18025     const void	*s2;
18026 {
18027     ufunc_T	*p1, *p2;
18028 
18029     p1 = *(ufunc_T **)s1;
18030     p2 = *(ufunc_T **)s2;
18031     return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
18032 }
18033 
18034 /*
18035  * Compare function for self time sorting.
18036  */
18037     static int
18038 #ifdef __BORLANDC__
18039 _RTLENTRYF
18040 #endif
18041 prof_self_cmp(s1, s2)
18042     const void	*s1;
18043     const void	*s2;
18044 {
18045     ufunc_T	*p1, *p2;
18046 
18047     p1 = *(ufunc_T **)s1;
18048     p2 = *(ufunc_T **)s2;
18049     return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
18050 }
18051 
18052 #endif
18053 
18054 /* The names of packages that once were loaded is remembered. */
18055 static garray_T	    ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
18056 
18057 /*
18058  * If "name" has a package name try autoloading the script for it.
18059  * Return TRUE if a package was loaded.
18060  */
18061     static int
18062 script_autoload(name, reload)
18063     char_u	*name;
18064     int		reload;	    /* load script again when already loaded */
18065 {
18066     char_u	*p;
18067     char_u	*scriptname, *tofree;
18068     int		ret = FALSE;
18069     int		i;
18070 
18071     /* If there is no '#' after name[0] there is no package name. */
18072     p = vim_strchr(name, AUTOLOAD_CHAR);
18073     if (p == NULL || p == name)
18074 	return FALSE;
18075 
18076     tofree = scriptname = autoload_name(name);
18077 
18078     /* Find the name in the list of previously loaded package names.  Skip
18079      * "autoload/", it's always the same. */
18080     for (i = 0; i < ga_loaded.ga_len; ++i)
18081 	if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
18082 	    break;
18083     if (!reload && i < ga_loaded.ga_len)
18084 	ret = FALSE;	    /* was loaded already */
18085     else
18086     {
18087 	/* Remember the name if it wasn't loaded already. */
18088 	if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
18089 	{
18090 	    ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
18091 	    tofree = NULL;
18092 	}
18093 
18094 	/* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
18095 	if (source_runtime(scriptname, FALSE) == OK)
18096 	    ret = TRUE;
18097     }
18098 
18099     vim_free(tofree);
18100     return ret;
18101 }
18102 
18103 /*
18104  * Return the autoload script name for a function or variable name.
18105  * Returns NULL when out of memory.
18106  */
18107     static char_u *
18108 autoload_name(name)
18109     char_u	*name;
18110 {
18111     char_u	*p;
18112     char_u	*scriptname;
18113 
18114     /* Get the script file name: replace '#' with '/', append ".vim". */
18115     scriptname = alloc((unsigned)(STRLEN(name) + 14));
18116     if (scriptname == NULL)
18117 	return FALSE;
18118     STRCPY(scriptname, "autoload/");
18119     STRCAT(scriptname, name);
18120     *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
18121     STRCAT(scriptname, ".vim");
18122     while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
18123 	*p = '/';
18124     return scriptname;
18125 }
18126 
18127 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
18128 
18129 /*
18130  * Function given to ExpandGeneric() to obtain the list of user defined
18131  * function names.
18132  */
18133     char_u *
18134 get_user_func_name(xp, idx)
18135     expand_T	*xp;
18136     int		idx;
18137 {
18138     static long_u	done;
18139     static hashitem_T	*hi;
18140     ufunc_T		*fp;
18141 
18142     if (idx == 0)
18143     {
18144 	done = 0;
18145 	hi = func_hashtab.ht_array;
18146     }
18147     if (done < func_hashtab.ht_used)
18148     {
18149 	if (done++ > 0)
18150 	    ++hi;
18151 	while (HASHITEM_EMPTY(hi))
18152 	    ++hi;
18153 	fp = HI2UF(hi);
18154 
18155 	if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
18156 	    return fp->uf_name;	/* prevents overflow */
18157 
18158 	cat_func_name(IObuff, fp);
18159 	if (xp->xp_context != EXPAND_USER_FUNC)
18160 	{
18161 	    STRCAT(IObuff, "(");
18162 	    if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
18163 		STRCAT(IObuff, ")");
18164 	}
18165 	return IObuff;
18166     }
18167     return NULL;
18168 }
18169 
18170 #endif /* FEAT_CMDL_COMPL */
18171 
18172 /*
18173  * Copy the function name of "fp" to buffer "buf".
18174  * "buf" must be able to hold the function name plus three bytes.
18175  * Takes care of script-local function names.
18176  */
18177     static void
18178 cat_func_name(buf, fp)
18179     char_u	*buf;
18180     ufunc_T	*fp;
18181 {
18182     if (fp->uf_name[0] == K_SPECIAL)
18183     {
18184 	STRCPY(buf, "<SNR>");
18185 	STRCAT(buf, fp->uf_name + 3);
18186     }
18187     else
18188 	STRCPY(buf, fp->uf_name);
18189 }
18190 
18191 /*
18192  * ":delfunction {name}"
18193  */
18194     void
18195 ex_delfunction(eap)
18196     exarg_T	*eap;
18197 {
18198     ufunc_T	*fp = NULL;
18199     char_u	*p;
18200     char_u	*name;
18201     funcdict_T	fudi;
18202 
18203     p = eap->arg;
18204     name = trans_function_name(&p, eap->skip, 0, &fudi);
18205     vim_free(fudi.fd_newkey);
18206     if (name == NULL)
18207     {
18208 	if (fudi.fd_dict != NULL && !eap->skip)
18209 	    EMSG(_(e_funcref));
18210 	return;
18211     }
18212     if (!ends_excmd(*skipwhite(p)))
18213     {
18214 	vim_free(name);
18215 	EMSG(_(e_trailing));
18216 	return;
18217     }
18218     eap->nextcmd = check_nextcmd(p);
18219     if (eap->nextcmd != NULL)
18220 	*p = NUL;
18221 
18222     if (!eap->skip)
18223 	fp = find_func(name);
18224     vim_free(name);
18225 
18226     if (!eap->skip)
18227     {
18228 	if (fp == NULL)
18229 	{
18230 	    EMSG2(_(e_nofunc), eap->arg);
18231 	    return;
18232 	}
18233 	if (fp->uf_calls > 0)
18234 	{
18235 	    EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
18236 	    return;
18237 	}
18238 
18239 	if (fudi.fd_dict != NULL)
18240 	{
18241 	    /* Delete the dict item that refers to the function, it will
18242 	     * invoke func_unref() and possibly delete the function. */
18243 	    dictitem_remove(fudi.fd_dict, fudi.fd_di);
18244 	}
18245 	else
18246 	    func_free(fp);
18247     }
18248 }
18249 
18250 /*
18251  * Free a function and remove it from the list of functions.
18252  */
18253     static void
18254 func_free(fp)
18255     ufunc_T *fp;
18256 {
18257     hashitem_T	*hi;
18258 
18259     /* clear this function */
18260     ga_clear_strings(&(fp->uf_args));
18261     ga_clear_strings(&(fp->uf_lines));
18262 #ifdef FEAT_PROFILE
18263     vim_free(fp->uf_tml_count);
18264     vim_free(fp->uf_tml_total);
18265     vim_free(fp->uf_tml_self);
18266 #endif
18267 
18268     /* remove the function from the function hashtable */
18269     hi = hash_find(&func_hashtab, UF2HIKEY(fp));
18270     if (HASHITEM_EMPTY(hi))
18271 	EMSG2(_(e_intern2), "func_free()");
18272     else
18273 	hash_remove(&func_hashtab, hi);
18274 
18275     vim_free(fp);
18276 }
18277 
18278 /*
18279  * Unreference a Function: decrement the reference count and free it when it
18280  * becomes zero.  Only for numbered functions.
18281  */
18282     static void
18283 func_unref(name)
18284     char_u	*name;
18285 {
18286     ufunc_T *fp;
18287 
18288     if (name != NULL && isdigit(*name))
18289     {
18290 	fp = find_func(name);
18291 	if (fp == NULL)
18292 	    EMSG2(_(e_intern2), "func_unref()");
18293 	else if (--fp->uf_refcount <= 0)
18294 	{
18295 	    /* Only delete it when it's not being used.  Otherwise it's done
18296 	     * when "uf_calls" becomes zero. */
18297 	    if (fp->uf_calls == 0)
18298 		func_free(fp);
18299 	}
18300     }
18301 }
18302 
18303 /*
18304  * Count a reference to a Function.
18305  */
18306     static void
18307 func_ref(name)
18308     char_u	*name;
18309 {
18310     ufunc_T *fp;
18311 
18312     if (name != NULL && isdigit(*name))
18313     {
18314 	fp = find_func(name);
18315 	if (fp == NULL)
18316 	    EMSG2(_(e_intern2), "func_ref()");
18317 	else
18318 	    ++fp->uf_refcount;
18319     }
18320 }
18321 
18322 /*
18323  * Call a user function.
18324  */
18325     static void
18326 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
18327     ufunc_T	*fp;		/* pointer to function */
18328     int		argcount;	/* nr of args */
18329     typval_T	*argvars;	/* arguments */
18330     typval_T	*rettv;		/* return value */
18331     linenr_T	firstline;	/* first line of range */
18332     linenr_T	lastline;	/* last line of range */
18333     dict_T	*selfdict;	/* Dictionary for "self" */
18334 {
18335     char_u	*save_sourcing_name;
18336     linenr_T	save_sourcing_lnum;
18337     scid_T	save_current_SID;
18338     funccall_T	fc;
18339     int		save_did_emsg;
18340     static int	depth = 0;
18341     dictitem_T	*v;
18342     int		fixvar_idx = 0;	/* index in fixvar[] */
18343     int		i;
18344     int		ai;
18345     char_u	numbuf[NUMBUFLEN];
18346     char_u	*name;
18347 #ifdef FEAT_PROFILE
18348     proftime_T	wait_start;
18349 #endif
18350 
18351     /* If depth of calling is getting too high, don't execute the function */
18352     if (depth >= p_mfd)
18353     {
18354 	EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
18355 	rettv->v_type = VAR_NUMBER;
18356 	rettv->vval.v_number = -1;
18357 	return;
18358     }
18359     ++depth;
18360 
18361     line_breakcheck();		/* check for CTRL-C hit */
18362 
18363     fc.caller = current_funccal;
18364     current_funccal = &fc;
18365     fc.func = fp;
18366     fc.rettv = rettv;
18367     rettv->vval.v_number = 0;
18368     fc.linenr = 0;
18369     fc.returned = FALSE;
18370     fc.level = ex_nesting_level;
18371     /* Check if this function has a breakpoint. */
18372     fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
18373     fc.dbg_tick = debug_tick;
18374 
18375     /*
18376      * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
18377      * with names up to VAR_SHORT_LEN long.  This avoids having to alloc/free
18378      * each argument variable and saves a lot of time.
18379      */
18380     /*
18381      * Init l: variables.
18382      */
18383     init_var_dict(&fc.l_vars, &fc.l_vars_var);
18384     if (selfdict != NULL)
18385     {
18386 	/* Set l:self to "selfdict". */
18387 	v = &fc.fixvar[fixvar_idx++].var;
18388 	STRCPY(v->di_key, "self");
18389 	v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
18390 	hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
18391 	v->di_tv.v_type = VAR_DICT;
18392 	v->di_tv.v_lock = 0;
18393 	v->di_tv.vval.v_dict = selfdict;
18394 	++selfdict->dv_refcount;
18395     }
18396 
18397     /*
18398      * Init a: variables.
18399      * Set a:0 to "argcount".
18400      * Set a:000 to a list with room for the "..." arguments.
18401      */
18402     init_var_dict(&fc.l_avars, &fc.l_avars_var);
18403     add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
18404 				(varnumber_T)(argcount - fp->uf_args.ga_len));
18405     v = &fc.fixvar[fixvar_idx++].var;
18406     STRCPY(v->di_key, "000");
18407     v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18408     hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
18409     v->di_tv.v_type = VAR_LIST;
18410     v->di_tv.v_lock = VAR_FIXED;
18411     v->di_tv.vval.v_list = &fc.l_varlist;
18412     vim_memset(&fc.l_varlist, 0, sizeof(list_T));
18413     fc.l_varlist.lv_refcount = 99999;
18414 
18415     /*
18416      * Set a:firstline to "firstline" and a:lastline to "lastline".
18417      * Set a:name to named arguments.
18418      * Set a:N to the "..." arguments.
18419      */
18420     add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
18421 						      (varnumber_T)firstline);
18422     add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
18423 						       (varnumber_T)lastline);
18424     for (i = 0; i < argcount; ++i)
18425     {
18426 	ai = i - fp->uf_args.ga_len;
18427 	if (ai < 0)
18428 	    /* named argument a:name */
18429 	    name = FUNCARG(fp, i);
18430 	else
18431 	{
18432 	    /* "..." argument a:1, a:2, etc. */
18433 	    sprintf((char *)numbuf, "%d", ai + 1);
18434 	    name = numbuf;
18435 	}
18436 	if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
18437 	{
18438 	    v = &fc.fixvar[fixvar_idx++].var;
18439 	    v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18440 	}
18441 	else
18442 	{
18443 	    v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
18444 							     + STRLEN(name)));
18445 	    if (v == NULL)
18446 		break;
18447 	    v->di_flags = DI_FLAGS_RO;
18448 	}
18449 	STRCPY(v->di_key, name);
18450 	hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
18451 
18452 	/* Note: the values are copied directly to avoid alloc/free.
18453 	 * "argvars" must have VAR_FIXED for v_lock. */
18454 	v->di_tv = argvars[i];
18455 	v->di_tv.v_lock = VAR_FIXED;
18456 
18457 	if (ai >= 0 && ai < MAX_FUNC_ARGS)
18458 	{
18459 	    list_append(&fc.l_varlist, &fc.l_listitems[ai]);
18460 	    fc.l_listitems[ai].li_tv = argvars[i];
18461 	    fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
18462 	}
18463     }
18464 
18465     /* Don't redraw while executing the function. */
18466     ++RedrawingDisabled;
18467     save_sourcing_name = sourcing_name;
18468     save_sourcing_lnum = sourcing_lnum;
18469     sourcing_lnum = 1;
18470     sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
18471 		: STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
18472     if (sourcing_name != NULL)
18473     {
18474 	if (save_sourcing_name != NULL
18475 			  && STRNCMP(save_sourcing_name, "function ", 9) == 0)
18476 	    sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
18477 	else
18478 	    STRCPY(sourcing_name, "function ");
18479 	cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
18480 
18481 	if (p_verbose >= 12)
18482 	{
18483 	    ++no_wait_return;
18484 	    verbose_enter_scroll();
18485 
18486 	    smsg((char_u *)_("calling %s"), sourcing_name);
18487 	    if (p_verbose >= 14)
18488 	    {
18489 		char_u	buf[MSG_BUF_LEN];
18490 		char_u	numbuf[NUMBUFLEN];
18491 		char_u	*tofree;
18492 
18493 		msg_puts((char_u *)"(");
18494 		for (i = 0; i < argcount; ++i)
18495 		{
18496 		    if (i > 0)
18497 			msg_puts((char_u *)", ");
18498 		    if (argvars[i].v_type == VAR_NUMBER)
18499 			msg_outnum((long)argvars[i].vval.v_number);
18500 		    else
18501 		    {
18502 			trunc_string(tv2string(&argvars[i], &tofree, numbuf),
18503 							    buf, MSG_BUF_CLEN);
18504 			msg_puts(buf);
18505 			vim_free(tofree);
18506 		    }
18507 		}
18508 		msg_puts((char_u *)")");
18509 	    }
18510 	    msg_puts((char_u *)"\n");   /* don't overwrite this either */
18511 
18512 	    verbose_leave_scroll();
18513 	    --no_wait_return;
18514 	}
18515     }
18516 #ifdef FEAT_PROFILE
18517     if (do_profiling)
18518     {
18519 	if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
18520 	    func_do_profile(fp);
18521 	if (fp->uf_profiling
18522 		       || (fc.caller != NULL && &fc.caller->func->uf_profiling))
18523 	{
18524 	    ++fp->uf_tm_count;
18525 	    profile_start(&fp->uf_tm_start);
18526 	    profile_zero(&fp->uf_tm_children);
18527 	}
18528 	script_prof_save(&wait_start);
18529     }
18530 #endif
18531 
18532     save_current_SID = current_SID;
18533     current_SID = fp->uf_script_ID;
18534     save_did_emsg = did_emsg;
18535     did_emsg = FALSE;
18536 
18537     /* call do_cmdline() to execute the lines */
18538     do_cmdline(NULL, get_func_line, (void *)&fc,
18539 				     DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
18540 
18541     --RedrawingDisabled;
18542 
18543     /* when the function was aborted because of an error, return -1 */
18544     if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
18545     {
18546 	clear_tv(rettv);
18547 	rettv->v_type = VAR_NUMBER;
18548 	rettv->vval.v_number = -1;
18549     }
18550 
18551 #ifdef FEAT_PROFILE
18552     if (fp->uf_profiling || (fc.caller != NULL && &fc.caller->func->uf_profiling))
18553     {
18554 	profile_end(&fp->uf_tm_start);
18555 	profile_sub_wait(&wait_start, &fp->uf_tm_start);
18556 	profile_add(&fp->uf_tm_total, &fp->uf_tm_start);
18557 	profile_add(&fp->uf_tm_self, &fp->uf_tm_start);
18558 	profile_sub(&fp->uf_tm_self, &fp->uf_tm_children);
18559 	if (fc.caller != NULL && &fc.caller->func->uf_profiling)
18560 	{
18561 	    profile_add(&fc.caller->func->uf_tm_children, &fp->uf_tm_start);
18562 	    profile_add(&fc.caller->func->uf_tml_children, &fp->uf_tm_start);
18563 	}
18564     }
18565 #endif
18566 
18567     /* when being verbose, mention the return value */
18568     if (p_verbose >= 12)
18569     {
18570 	++no_wait_return;
18571 	verbose_enter_scroll();
18572 
18573 	if (aborting())
18574 	    smsg((char_u *)_("%s aborted"), sourcing_name);
18575 	else if (fc.rettv->v_type == VAR_NUMBER)
18576 	    smsg((char_u *)_("%s returning #%ld"), sourcing_name,
18577 					       (long)fc.rettv->vval.v_number);
18578 	else
18579 	{
18580 	    char_u	buf[MSG_BUF_LEN];
18581 	    char_u	numbuf[NUMBUFLEN];
18582 	    char_u	*tofree;
18583 
18584 	    /* The value may be very long.  Skip the middle part, so that we
18585 	     * have some idea how it starts and ends. smsg() would always
18586 	     * truncate it at the end. */
18587 	    trunc_string(tv2string(fc.rettv, &tofree, numbuf),
18588 							   buf, MSG_BUF_CLEN);
18589 	    smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
18590 	    vim_free(tofree);
18591 	}
18592 	msg_puts((char_u *)"\n");   /* don't overwrite this either */
18593 
18594 	verbose_leave_scroll();
18595 	--no_wait_return;
18596     }
18597 
18598     vim_free(sourcing_name);
18599     sourcing_name = save_sourcing_name;
18600     sourcing_lnum = save_sourcing_lnum;
18601     current_SID = save_current_SID;
18602 #ifdef FEAT_PROFILE
18603     if (do_profiling)
18604 	script_prof_restore(&wait_start);
18605 #endif
18606 
18607     if (p_verbose >= 12 && sourcing_name != NULL)
18608     {
18609 	++no_wait_return;
18610 	verbose_enter_scroll();
18611 
18612 	smsg((char_u *)_("continuing in %s"), sourcing_name);
18613 	msg_puts((char_u *)"\n");   /* don't overwrite this either */
18614 
18615 	verbose_leave_scroll();
18616 	--no_wait_return;
18617     }
18618 
18619     did_emsg |= save_did_emsg;
18620     current_funccal = fc.caller;
18621 
18622     /* The a: variables typevals were not alloced, only free the allocated
18623      * variables. */
18624     vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
18625 
18626     vars_clear(&fc.l_vars.dv_hashtab);		/* free all l: variables */
18627     --depth;
18628 }
18629 
18630 /*
18631  * Add a number variable "name" to dict "dp" with value "nr".
18632  */
18633     static void
18634 add_nr_var(dp, v, name, nr)
18635     dict_T	*dp;
18636     dictitem_T	*v;
18637     char	*name;
18638     varnumber_T nr;
18639 {
18640     STRCPY(v->di_key, name);
18641     v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18642     hash_add(&dp->dv_hashtab, DI2HIKEY(v));
18643     v->di_tv.v_type = VAR_NUMBER;
18644     v->di_tv.v_lock = VAR_FIXED;
18645     v->di_tv.vval.v_number = nr;
18646 }
18647 
18648 /*
18649  * ":return [expr]"
18650  */
18651     void
18652 ex_return(eap)
18653     exarg_T	*eap;
18654 {
18655     char_u	*arg = eap->arg;
18656     typval_T	rettv;
18657     int		returning = FALSE;
18658 
18659     if (current_funccal == NULL)
18660     {
18661 	EMSG(_("E133: :return not inside a function"));
18662 	return;
18663     }
18664 
18665     if (eap->skip)
18666 	++emsg_skip;
18667 
18668     eap->nextcmd = NULL;
18669     if ((*arg != NUL && *arg != '|' && *arg != '\n')
18670 	    && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
18671     {
18672 	if (!eap->skip)
18673 	    returning = do_return(eap, FALSE, TRUE, &rettv);
18674 	else
18675 	    clear_tv(&rettv);
18676     }
18677     /* It's safer to return also on error. */
18678     else if (!eap->skip)
18679     {
18680 	/*
18681 	 * Return unless the expression evaluation has been cancelled due to an
18682 	 * aborting error, an interrupt, or an exception.
18683 	 */
18684 	if (!aborting())
18685 	    returning = do_return(eap, FALSE, TRUE, NULL);
18686     }
18687 
18688     /* When skipping or the return gets pending, advance to the next command
18689      * in this line (!returning).  Otherwise, ignore the rest of the line.
18690      * Following lines will be ignored by get_func_line(). */
18691     if (returning)
18692 	eap->nextcmd = NULL;
18693     else if (eap->nextcmd == NULL)	    /* no argument */
18694 	eap->nextcmd = check_nextcmd(arg);
18695 
18696     if (eap->skip)
18697 	--emsg_skip;
18698 }
18699 
18700 /*
18701  * Return from a function.  Possibly makes the return pending.  Also called
18702  * for a pending return at the ":endtry" or after returning from an extra
18703  * do_cmdline().  "reanimate" is used in the latter case.  "is_cmd" is set
18704  * when called due to a ":return" command.  "rettv" may point to a typval_T
18705  * with the return rettv.  Returns TRUE when the return can be carried out,
18706  * FALSE when the return gets pending.
18707  */
18708     int
18709 do_return(eap, reanimate, is_cmd, rettv)
18710     exarg_T	*eap;
18711     int		reanimate;
18712     int		is_cmd;
18713     void	*rettv;
18714 {
18715     int		idx;
18716     struct condstack *cstack = eap->cstack;
18717 
18718     if (reanimate)
18719 	/* Undo the return. */
18720 	current_funccal->returned = FALSE;
18721 
18722     /*
18723      * Cleanup (and inactivate) conditionals, but stop when a try conditional
18724      * not in its finally clause (which then is to be executed next) is found.
18725      * In this case, make the ":return" pending for execution at the ":endtry".
18726      * Otherwise, return normally.
18727      */
18728     idx = cleanup_conditionals(eap->cstack, 0, TRUE);
18729     if (idx >= 0)
18730     {
18731 	cstack->cs_pending[idx] = CSTP_RETURN;
18732 
18733 	if (!is_cmd && !reanimate)
18734 	    /* A pending return again gets pending.  "rettv" points to an
18735 	     * allocated variable with the rettv of the original ":return"'s
18736 	     * argument if present or is NULL else. */
18737 	    cstack->cs_rettv[idx] = rettv;
18738 	else
18739 	{
18740 	    /* When undoing a return in order to make it pending, get the stored
18741 	     * return rettv. */
18742 	    if (reanimate)
18743 		rettv = current_funccal->rettv;
18744 
18745 	    if (rettv != NULL)
18746 	    {
18747 		/* Store the value of the pending return. */
18748 		if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
18749 		    *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
18750 		else
18751 		    EMSG(_(e_outofmem));
18752 	    }
18753 	    else
18754 		cstack->cs_rettv[idx] = NULL;
18755 
18756 	    if (reanimate)
18757 	    {
18758 		/* The pending return value could be overwritten by a ":return"
18759 		 * without argument in a finally clause; reset the default
18760 		 * return value. */
18761 		current_funccal->rettv->v_type = VAR_NUMBER;
18762 		current_funccal->rettv->vval.v_number = 0;
18763 	    }
18764 	}
18765 	report_make_pending(CSTP_RETURN, rettv);
18766     }
18767     else
18768     {
18769 	current_funccal->returned = TRUE;
18770 
18771 	/* If the return is carried out now, store the return value.  For
18772 	 * a return immediately after reanimation, the value is already
18773 	 * there. */
18774 	if (!reanimate && rettv != NULL)
18775 	{
18776 	    clear_tv(current_funccal->rettv);
18777 	    *current_funccal->rettv = *(typval_T *)rettv;
18778 	    if (!is_cmd)
18779 		vim_free(rettv);
18780 	}
18781     }
18782 
18783     return idx < 0;
18784 }
18785 
18786 /*
18787  * Free the variable with a pending return value.
18788  */
18789     void
18790 discard_pending_return(rettv)
18791     void	*rettv;
18792 {
18793     free_tv((typval_T *)rettv);
18794 }
18795 
18796 /*
18797  * Generate a return command for producing the value of "rettv".  The result
18798  * is an allocated string.  Used by report_pending() for verbose messages.
18799  */
18800     char_u *
18801 get_return_cmd(rettv)
18802     void	*rettv;
18803 {
18804     char_u	*s = NULL;
18805     char_u	*tofree = NULL;
18806     char_u	numbuf[NUMBUFLEN];
18807 
18808     if (rettv != NULL)
18809 	s = echo_string((typval_T *)rettv, &tofree, numbuf);
18810     if (s == NULL)
18811 	s = (char_u *)"";
18812 
18813     STRCPY(IObuff, ":return ");
18814     STRNCPY(IObuff + 8, s, IOSIZE - 8);
18815     if (STRLEN(s) + 8 >= IOSIZE)
18816 	STRCPY(IObuff + IOSIZE - 4, "...");
18817     vim_free(tofree);
18818     return vim_strsave(IObuff);
18819 }
18820 
18821 /*
18822  * Get next function line.
18823  * Called by do_cmdline() to get the next line.
18824  * Returns allocated string, or NULL for end of function.
18825  */
18826 /* ARGSUSED */
18827     char_u *
18828 get_func_line(c, cookie, indent)
18829     int	    c;		    /* not used */
18830     void    *cookie;
18831     int	    indent;	    /* not used */
18832 {
18833     funccall_T	*fcp = (funccall_T *)cookie;
18834     ufunc_T	*fp = fcp->func;
18835     char_u	*retval;
18836     garray_T	*gap;  /* growarray with function lines */
18837 
18838     /* If breakpoints have been added/deleted need to check for it. */
18839     if (fcp->dbg_tick != debug_tick)
18840     {
18841 	fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
18842 							       sourcing_lnum);
18843 	fcp->dbg_tick = debug_tick;
18844     }
18845 #ifdef FEAT_PROFILE
18846     if (do_profiling)
18847 	func_line_end(cookie);
18848 #endif
18849 
18850     gap = &fp->uf_lines;
18851     if ((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
18852 	retval = NULL;
18853     else if (fcp->returned || fcp->linenr >= gap->ga_len)
18854 	retval = NULL;
18855     else
18856     {
18857 	retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
18858 	sourcing_lnum = fcp->linenr;
18859 #ifdef FEAT_PROFILE
18860 	if (do_profiling)
18861 	    func_line_start(cookie);
18862 #endif
18863     }
18864 
18865     /* Did we encounter a breakpoint? */
18866     if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
18867     {
18868 	dbg_breakpoint(fp->uf_name, sourcing_lnum);
18869 	/* Find next breakpoint. */
18870 	fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
18871 							       sourcing_lnum);
18872 	fcp->dbg_tick = debug_tick;
18873     }
18874 
18875     return retval;
18876 }
18877 
18878 #if defined(FEAT_PROFILE) || defined(PROTO)
18879 /*
18880  * Called when starting to read a function line.
18881  * "sourcing_lnum" must be correct!
18882  * When skipping lines it may not actually be executed, but we won't find out
18883  * until later and we need to store the time now.
18884  */
18885     void
18886 func_line_start(cookie)
18887     void    *cookie;
18888 {
18889     funccall_T	*fcp = (funccall_T *)cookie;
18890     ufunc_T	*fp = fcp->func;
18891 
18892     if (fp->uf_profiling && sourcing_lnum >= 1
18893 				      && sourcing_lnum <= fp->uf_lines.ga_len)
18894     {
18895 	fp->uf_tml_idx = sourcing_lnum - 1;
18896 	fp->uf_tml_execed = FALSE;
18897 	profile_start(&fp->uf_tml_start);
18898 	profile_zero(&fp->uf_tml_children);
18899 	profile_get_wait(&fp->uf_tml_wait);
18900     }
18901 }
18902 
18903 /*
18904  * Called when actually executing a function line.
18905  */
18906     void
18907 func_line_exec(cookie)
18908     void    *cookie;
18909 {
18910     funccall_T	*fcp = (funccall_T *)cookie;
18911     ufunc_T	*fp = fcp->func;
18912 
18913     if (fp->uf_profiling && fp->uf_tml_idx >= 0)
18914 	fp->uf_tml_execed = TRUE;
18915 }
18916 
18917 /*
18918  * Called when done with a function line.
18919  */
18920     void
18921 func_line_end(cookie)
18922     void    *cookie;
18923 {
18924     funccall_T	*fcp = (funccall_T *)cookie;
18925     ufunc_T	*fp = fcp->func;
18926 
18927     if (fp->uf_profiling && fp->uf_tml_idx >= 0)
18928     {
18929 	if (fp->uf_tml_execed)
18930 	{
18931 	    ++fp->uf_tml_count[fp->uf_tml_idx];
18932 	    profile_end(&fp->uf_tml_start);
18933 	    profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
18934 	    profile_add(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start);
18935 	    profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
18936 	    profile_sub(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_children);
18937 	}
18938 	fp->uf_tml_idx = -1;
18939     }
18940 }
18941 #endif
18942 
18943 /*
18944  * Return TRUE if the currently active function should be ended, because a
18945  * return was encountered or an error occured.  Used inside a ":while".
18946  */
18947     int
18948 func_has_ended(cookie)
18949     void    *cookie;
18950 {
18951     funccall_T  *fcp = (funccall_T *)cookie;
18952 
18953     /* Ignore the "abort" flag if the abortion behavior has been changed due to
18954      * an error inside a try conditional. */
18955     return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
18956 	    || fcp->returned);
18957 }
18958 
18959 /*
18960  * return TRUE if cookie indicates a function which "abort"s on errors.
18961  */
18962     int
18963 func_has_abort(cookie)
18964     void    *cookie;
18965 {
18966     return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
18967 }
18968 
18969 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
18970 typedef enum
18971 {
18972     VAR_FLAVOUR_DEFAULT,
18973     VAR_FLAVOUR_SESSION,
18974     VAR_FLAVOUR_VIMINFO
18975 } var_flavour_T;
18976 
18977 static var_flavour_T var_flavour __ARGS((char_u *varname));
18978 
18979     static var_flavour_T
18980 var_flavour(varname)
18981     char_u *varname;
18982 {
18983     char_u *p = varname;
18984 
18985     if (ASCII_ISUPPER(*p))
18986     {
18987 	while (*(++p))
18988 	    if (ASCII_ISLOWER(*p))
18989 		return VAR_FLAVOUR_SESSION;
18990 	return VAR_FLAVOUR_VIMINFO;
18991     }
18992     else
18993 	return VAR_FLAVOUR_DEFAULT;
18994 }
18995 #endif
18996 
18997 #if defined(FEAT_VIMINFO) || defined(PROTO)
18998 /*
18999  * Restore global vars that start with a capital from the viminfo file
19000  */
19001     int
19002 read_viminfo_varlist(virp, writing)
19003     vir_T	*virp;
19004     int		writing;
19005 {
19006     char_u	*tab;
19007     int		is_string = FALSE;
19008     typval_T	tv;
19009 
19010     if (!writing && (find_viminfo_parameter('!') != NULL))
19011     {
19012 	tab = vim_strchr(virp->vir_line + 1, '\t');
19013 	if (tab != NULL)
19014 	{
19015 	    *tab++ = '\0';	/* isolate the variable name */
19016 	    if (*tab == 'S')	/* string var */
19017 		is_string = TRUE;
19018 
19019 	    tab = vim_strchr(tab, '\t');
19020 	    if (tab != NULL)
19021 	    {
19022 		if (is_string)
19023 		{
19024 		    tv.v_type = VAR_STRING;
19025 		    tv.vval.v_string = viminfo_readstring(virp,
19026 				       (int)(tab - virp->vir_line + 1), TRUE);
19027 		}
19028 		else
19029 		{
19030 		    tv.v_type = VAR_NUMBER;
19031 		    tv.vval.v_number = atol((char *)tab + 1);
19032 		}
19033 		set_var(virp->vir_line + 1, &tv, FALSE);
19034 		if (is_string)
19035 		    vim_free(tv.vval.v_string);
19036 	    }
19037 	}
19038     }
19039 
19040     return viminfo_readline(virp);
19041 }
19042 
19043 /*
19044  * Write global vars that start with a capital to the viminfo file
19045  */
19046     void
19047 write_viminfo_varlist(fp)
19048     FILE    *fp;
19049 {
19050     hashitem_T	*hi;
19051     dictitem_T	*this_var;
19052     int		todo;
19053     char	*s;
19054     char_u	*p;
19055     char_u	*tofree;
19056     char_u	numbuf[NUMBUFLEN];
19057 
19058     if (find_viminfo_parameter('!') == NULL)
19059 	return;
19060 
19061     fprintf(fp, _("\n# global variables:\n"));
19062 
19063     todo = globvarht.ht_used;
19064     for (hi = globvarht.ht_array; todo > 0; ++hi)
19065     {
19066 	if (!HASHITEM_EMPTY(hi))
19067 	{
19068 	    --todo;
19069 	    this_var = HI2DI(hi);
19070 	    if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
19071 	    {
19072 		switch (this_var->di_tv.v_type)
19073 		{
19074 		    case VAR_STRING: s = "STR"; break;
19075 		    case VAR_NUMBER: s = "NUM"; break;
19076 		    default: continue;
19077 		}
19078 		fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
19079 		p = echo_string(&this_var->di_tv, &tofree, numbuf);
19080 		if (p != NULL)
19081 		    viminfo_writestring(fp, p);
19082 		vim_free(tofree);
19083 	    }
19084 	}
19085     }
19086 }
19087 #endif
19088 
19089 #if defined(FEAT_SESSION) || defined(PROTO)
19090     int
19091 store_session_globals(fd)
19092     FILE	*fd;
19093 {
19094     hashitem_T	*hi;
19095     dictitem_T	*this_var;
19096     int		todo;
19097     char_u	*p, *t;
19098 
19099     todo = globvarht.ht_used;
19100     for (hi = globvarht.ht_array; todo > 0; ++hi)
19101     {
19102 	if (!HASHITEM_EMPTY(hi))
19103 	{
19104 	    --todo;
19105 	    this_var = HI2DI(hi);
19106 	    if ((this_var->di_tv.v_type == VAR_NUMBER
19107 			|| this_var->di_tv.v_type == VAR_STRING)
19108 		    && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
19109 	    {
19110 		/* Escape special characters with a backslash.  Turn a LF and
19111 		 * CR into \n and \r. */
19112 		p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
19113 							(char_u *)"\\\"\n\r");
19114 		if (p == NULL)	    /* out of memory */
19115 		    break;
19116 		for (t = p; *t != NUL; ++t)
19117 		    if (*t == '\n')
19118 			*t = 'n';
19119 		    else if (*t == '\r')
19120 			*t = 'r';
19121 		if ((fprintf(fd, "let %s = %c%s%c",
19122 				this_var->di_key,
19123 				(this_var->di_tv.v_type == VAR_STRING) ? '"'
19124 									: ' ',
19125 				p,
19126 				(this_var->di_tv.v_type == VAR_STRING) ? '"'
19127 								   : ' ') < 0)
19128 			|| put_eol(fd) == FAIL)
19129 		{
19130 		    vim_free(p);
19131 		    return FAIL;
19132 		}
19133 		vim_free(p);
19134 	    }
19135 	}
19136     }
19137     return OK;
19138 }
19139 #endif
19140 
19141 /*
19142  * Display script name where an item was last set.
19143  * Should only be invoked when 'verbose' is non-zero.
19144  */
19145     void
19146 last_set_msg(scriptID)
19147     scid_T scriptID;
19148 {
19149     char_u *p;
19150 
19151     if (scriptID != 0)
19152     {
19153 	p = home_replace_save(NULL, get_scriptname(scriptID));
19154 	if (p != NULL)
19155 	{
19156 	    verbose_enter();
19157 	    MSG_PUTS(_("\n\tLast set from "));
19158 	    MSG_PUTS(p);
19159 	    vim_free(p);
19160 	    verbose_leave();
19161 	}
19162     }
19163 }
19164 
19165 #endif /* FEAT_EVAL */
19166 
19167 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
19168 
19169 
19170 #ifdef WIN3264
19171 /*
19172  * Functions for ":8" filename modifier: get 8.3 version of a filename.
19173  */
19174 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
19175 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
19176 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
19177 
19178 /*
19179  * Get the short pathname of a file.
19180  * Returns 1 on success. *fnamelen is 0 for nonexistant path.
19181  */
19182     static int
19183 get_short_pathname(fnamep, bufp, fnamelen)
19184     char_u	**fnamep;
19185     char_u	**bufp;
19186     int		*fnamelen;
19187 {
19188     int		l,len;
19189     char_u	*newbuf;
19190 
19191     len = *fnamelen;
19192 
19193     l = GetShortPathName(*fnamep, *fnamep, len);
19194     if (l > len - 1)
19195     {
19196 	/* If that doesn't work (not enough space), then save the string
19197 	 * and try again with a new buffer big enough
19198 	 */
19199 	newbuf = vim_strnsave(*fnamep, l);
19200 	if (newbuf == NULL)
19201 	    return 0;
19202 
19203 	vim_free(*bufp);
19204 	*fnamep = *bufp = newbuf;
19205 
19206 	l = GetShortPathName(*fnamep,*fnamep,l+1);
19207 
19208 	/* Really should always succeed, as the buffer is big enough */
19209     }
19210 
19211     *fnamelen = l;
19212     return 1;
19213 }
19214 
19215 /*
19216  * Create a short path name.  Returns the length of the buffer it needs.
19217  * Doesn't copy over the end of the buffer passed in.
19218  */
19219     static int
19220 shortpath_for_invalid_fname(fname, bufp, fnamelen)
19221     char_u	**fname;
19222     char_u	**bufp;
19223     int		*fnamelen;
19224 {
19225     char_u	*s, *p, *pbuf2, *pbuf3;
19226     char_u	ch;
19227     int		len, len2, plen, slen;
19228 
19229     /* Make a copy */
19230     len2 = *fnamelen;
19231     pbuf2 = vim_strnsave(*fname, len2);
19232     pbuf3 = NULL;
19233 
19234     s = pbuf2 + len2 - 1; /* Find the end */
19235     slen = 1;
19236     plen = len2;
19237 
19238     if (after_pathsep(pbuf2, s + 1))
19239     {
19240 	--s;
19241 	++slen;
19242 	--plen;
19243     }
19244 
19245     do
19246     {
19247 	/* Go back one path-seperator */
19248 	while (s > pbuf2 && !after_pathsep(pbuf2, s + 1))
19249 	{
19250 	    --s;
19251 	    ++slen;
19252 	    --plen;
19253 	}
19254 	if (s <= pbuf2)
19255 	    break;
19256 
19257 	/* Remeber the character that is about to be blatted */
19258 	ch = *s;
19259 	*s = 0; /* get_short_pathname requires a null-terminated string */
19260 
19261 	/* Try it in situ */
19262 	p = pbuf2;
19263 	if (!get_short_pathname(&p, &pbuf3, &plen))
19264 	{
19265 	    vim_free(pbuf2);
19266 	    return -1;
19267 	}
19268 	*s = ch;    /* Preserve the string */
19269     } while (plen == 0);
19270 
19271     if (plen > 0)
19272     {
19273 	/* Remeber the length of the new string.  */
19274 	*fnamelen = len = plen + slen;
19275 	vim_free(*bufp);
19276 	if (len > len2)
19277 	{
19278 	    /* If there's not enough space in the currently allocated string,
19279 	     * then copy it to a buffer big enough.
19280 	     */
19281 	    *fname= *bufp = vim_strnsave(p, len);
19282 	    if (*fname == NULL)
19283 		return -1;
19284 	}
19285 	else
19286 	{
19287 	    /* Transfer pbuf2 to being the main buffer  (it's big enough) */
19288 	    *fname = *bufp = pbuf2;
19289 	    if (p != pbuf2)
19290 		strncpy(*fname, p, plen);
19291 	    pbuf2 = NULL;
19292 	}
19293 	/* Concat the next bit */
19294 	strncpy(*fname + plen, s, slen);
19295 	(*fname)[len] = '\0';
19296     }
19297     vim_free(pbuf3);
19298     vim_free(pbuf2);
19299     return 0;
19300 }
19301 
19302 /*
19303  * Get a pathname for a partial path.
19304  */
19305     static int
19306 shortpath_for_partial(fnamep, bufp, fnamelen)
19307     char_u	**fnamep;
19308     char_u	**bufp;
19309     int		*fnamelen;
19310 {
19311     int		sepcount, len, tflen;
19312     char_u	*p;
19313     char_u	*pbuf, *tfname;
19314     int		hasTilde;
19315 
19316     /* Count up the path seperators from the RHS.. so we know which part
19317      * of the path to return.
19318      */
19319     sepcount = 0;
19320     for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
19321 	if (vim_ispathsep(*p))
19322 	    ++sepcount;
19323 
19324     /* Need full path first (use expand_env() to remove a "~/") */
19325     hasTilde = (**fnamep == '~');
19326     if (hasTilde)
19327 	pbuf = tfname = expand_env_save(*fnamep);
19328     else
19329 	pbuf = tfname = FullName_save(*fnamep, FALSE);
19330 
19331     len = tflen = STRLEN(tfname);
19332 
19333     if (!get_short_pathname(&tfname, &pbuf, &len))
19334 	return -1;
19335 
19336     if (len == 0)
19337     {
19338 	/* Don't have a valid filename, so shorten the rest of the
19339 	 * path if we can. This CAN give us invalid 8.3 filenames, but
19340 	 * there's not a lot of point in guessing what it might be.
19341 	 */
19342 	len = tflen;
19343 	if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == -1)
19344 	    return -1;
19345     }
19346 
19347     /* Count the paths backward to find the beginning of the desired string. */
19348     for (p = tfname + len - 1; p >= tfname; --p)
19349     {
19350 #ifdef FEAT_MBYTE
19351 	if (has_mbyte)
19352 	    p -= mb_head_off(tfname, p);
19353 #endif
19354 	if (vim_ispathsep(*p))
19355 	{
19356 	    if (sepcount == 0 || (hasTilde && sepcount == 1))
19357 		break;
19358 	    else
19359 		sepcount --;
19360 	}
19361     }
19362     if (hasTilde)
19363     {
19364 	--p;
19365 	if (p >= tfname)
19366 	    *p = '~';
19367 	else
19368 	    return -1;
19369     }
19370     else
19371 	++p;
19372 
19373     /* Copy in the string - p indexes into tfname - allocated at pbuf */
19374     vim_free(*bufp);
19375     *fnamelen = (int)STRLEN(p);
19376     *bufp = pbuf;
19377     *fnamep = p;
19378 
19379     return 0;
19380 }
19381 #endif /* WIN3264 */
19382 
19383 /*
19384  * Adjust a filename, according to a string of modifiers.
19385  * *fnamep must be NUL terminated when called.  When returning, the length is
19386  * determined by *fnamelen.
19387  * Returns valid flags.
19388  * When there is an error, *fnamep is set to NULL.
19389  */
19390     int
19391 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
19392     char_u	*src;		/* string with modifiers */
19393     int		*usedlen;	/* characters after src that are used */
19394     char_u	**fnamep;	/* file name so far */
19395     char_u	**bufp;		/* buffer for allocated file name or NULL */
19396     int		*fnamelen;	/* length of fnamep */
19397 {
19398     int		valid = 0;
19399     char_u	*tail;
19400     char_u	*s, *p, *pbuf;
19401     char_u	dirname[MAXPATHL];
19402     int		c;
19403     int		has_fullname = 0;
19404 #ifdef WIN3264
19405     int		has_shortname = 0;
19406 #endif
19407 
19408 repeat:
19409     /* ":p" - full path/file_name */
19410     if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
19411     {
19412 	has_fullname = 1;
19413 
19414 	valid |= VALID_PATH;
19415 	*usedlen += 2;
19416 
19417 	/* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
19418 	if ((*fnamep)[0] == '~'
19419 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
19420 		&& ((*fnamep)[1] == '/'
19421 # ifdef BACKSLASH_IN_FILENAME
19422 		    || (*fnamep)[1] == '\\'
19423 # endif
19424 		    || (*fnamep)[1] == NUL)
19425 
19426 #endif
19427 	   )
19428 	{
19429 	    *fnamep = expand_env_save(*fnamep);
19430 	    vim_free(*bufp);	/* free any allocated file name */
19431 	    *bufp = *fnamep;
19432 	    if (*fnamep == NULL)
19433 		return -1;
19434 	}
19435 
19436 	/* When "/." or "/.." is used: force expansion to get rid of it. */
19437 	for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
19438 	{
19439 	    if (vim_ispathsep(*p)
19440 		    && p[1] == '.'
19441 		    && (p[2] == NUL
19442 			|| vim_ispathsep(p[2])
19443 			|| (p[2] == '.'
19444 			    && (p[3] == NUL || vim_ispathsep(p[3])))))
19445 		break;
19446 	}
19447 
19448 	/* FullName_save() is slow, don't use it when not needed. */
19449 	if (*p != NUL || !vim_isAbsName(*fnamep))
19450 	{
19451 	    *fnamep = FullName_save(*fnamep, *p != NUL);
19452 	    vim_free(*bufp);	/* free any allocated file name */
19453 	    *bufp = *fnamep;
19454 	    if (*fnamep == NULL)
19455 		return -1;
19456 	}
19457 
19458 	/* Append a path separator to a directory. */
19459 	if (mch_isdir(*fnamep))
19460 	{
19461 	    /* Make room for one or two extra characters. */
19462 	    *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
19463 	    vim_free(*bufp);	/* free any allocated file name */
19464 	    *bufp = *fnamep;
19465 	    if (*fnamep == NULL)
19466 		return -1;
19467 	    add_pathsep(*fnamep);
19468 	}
19469     }
19470 
19471     /* ":." - path relative to the current directory */
19472     /* ":~" - path relative to the home directory */
19473     /* ":8" - shortname path - postponed till after */
19474     while (src[*usedlen] == ':'
19475 		  && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
19476     {
19477 	*usedlen += 2;
19478 	if (c == '8')
19479 	{
19480 #ifdef WIN3264
19481 	    has_shortname = 1; /* Postpone this. */
19482 #endif
19483 	    continue;
19484 	}
19485 	pbuf = NULL;
19486 	/* Need full path first (use expand_env() to remove a "~/") */
19487 	if (!has_fullname)
19488 	{
19489 	    if (c == '.' && **fnamep == '~')
19490 		p = pbuf = expand_env_save(*fnamep);
19491 	    else
19492 		p = pbuf = FullName_save(*fnamep, FALSE);
19493 	}
19494 	else
19495 	    p = *fnamep;
19496 
19497 	has_fullname = 0;
19498 
19499 	if (p != NULL)
19500 	{
19501 	    if (c == '.')
19502 	    {
19503 		mch_dirname(dirname, MAXPATHL);
19504 		s = shorten_fname(p, dirname);
19505 		if (s != NULL)
19506 		{
19507 		    *fnamep = s;
19508 		    if (pbuf != NULL)
19509 		    {
19510 			vim_free(*bufp);   /* free any allocated file name */
19511 			*bufp = pbuf;
19512 			pbuf = NULL;
19513 		    }
19514 		}
19515 	    }
19516 	    else
19517 	    {
19518 		home_replace(NULL, p, dirname, MAXPATHL, TRUE);
19519 		/* Only replace it when it starts with '~' */
19520 		if (*dirname == '~')
19521 		{
19522 		    s = vim_strsave(dirname);
19523 		    if (s != NULL)
19524 		    {
19525 			*fnamep = s;
19526 			vim_free(*bufp);
19527 			*bufp = s;
19528 		    }
19529 		}
19530 	    }
19531 	    vim_free(pbuf);
19532 	}
19533     }
19534 
19535     tail = gettail(*fnamep);
19536     *fnamelen = (int)STRLEN(*fnamep);
19537 
19538     /* ":h" - head, remove "/file_name", can be repeated  */
19539     /* Don't remove the first "/" or "c:\" */
19540     while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
19541     {
19542 	valid |= VALID_HEAD;
19543 	*usedlen += 2;
19544 	s = get_past_head(*fnamep);
19545 	while (tail > s && after_pathsep(s, tail))
19546 	    --tail;
19547 	*fnamelen = (int)(tail - *fnamep);
19548 #ifdef VMS
19549 	if (*fnamelen > 0)
19550 	    *fnamelen += 1; /* the path separator is part of the path */
19551 #endif
19552 	while (tail > s && !after_pathsep(s, tail))
19553 	    mb_ptr_back(*fnamep, tail);
19554     }
19555 
19556     /* ":8" - shortname  */
19557     if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
19558     {
19559 	*usedlen += 2;
19560 #ifdef WIN3264
19561 	has_shortname = 1;
19562 #endif
19563     }
19564 
19565 #ifdef WIN3264
19566     /* Check shortname after we have done 'heads' and before we do 'tails'
19567      */
19568     if (has_shortname)
19569     {
19570 	pbuf = NULL;
19571 	/* Copy the string if it is shortened by :h */
19572 	if (*fnamelen < (int)STRLEN(*fnamep))
19573 	{
19574 	    p = vim_strnsave(*fnamep, *fnamelen);
19575 	    if (p == 0)
19576 		return -1;
19577 	    vim_free(*bufp);
19578 	    *bufp = *fnamep = p;
19579 	}
19580 
19581 	/* Split into two implementations - makes it easier.  First is where
19582 	 * there isn't a full name already, second is where there is.
19583 	 */
19584 	if (!has_fullname && !vim_isAbsName(*fnamep))
19585 	{
19586 	    if (shortpath_for_partial(fnamep, bufp, fnamelen) == -1)
19587 		return -1;
19588 	}
19589 	else
19590 	{
19591 	    int		l;
19592 
19593 	    /* Simple case, already have the full-name
19594 	     * Nearly always shorter, so try first time. */
19595 	    l = *fnamelen;
19596 	    if (!get_short_pathname(fnamep, bufp, &l))
19597 		return -1;
19598 
19599 	    if (l == 0)
19600 	    {
19601 		/* Couldn't find the filename.. search the paths.
19602 		 */
19603 		l = *fnamelen;
19604 		if (shortpath_for_invalid_fname(fnamep, bufp, &l ) == -1)
19605 		    return -1;
19606 	    }
19607 	    *fnamelen = l;
19608 	}
19609     }
19610 #endif /* WIN3264 */
19611 
19612     /* ":t" - tail, just the basename */
19613     if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
19614     {
19615 	*usedlen += 2;
19616 	*fnamelen -= (int)(tail - *fnamep);
19617 	*fnamep = tail;
19618     }
19619 
19620     /* ":e" - extension, can be repeated */
19621     /* ":r" - root, without extension, can be repeated */
19622     while (src[*usedlen] == ':'
19623 	    && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
19624     {
19625 	/* find a '.' in the tail:
19626 	 * - for second :e: before the current fname
19627 	 * - otherwise: The last '.'
19628 	 */
19629 	if (src[*usedlen + 1] == 'e' && *fnamep > tail)
19630 	    s = *fnamep - 2;
19631 	else
19632 	    s = *fnamep + *fnamelen - 1;
19633 	for ( ; s > tail; --s)
19634 	    if (s[0] == '.')
19635 		break;
19636 	if (src[*usedlen + 1] == 'e')		/* :e */
19637 	{
19638 	    if (s > tail)
19639 	    {
19640 		*fnamelen += (int)(*fnamep - (s + 1));
19641 		*fnamep = s + 1;
19642 #ifdef VMS
19643 		/* cut version from the extension */
19644 		s = *fnamep + *fnamelen - 1;
19645 		for ( ; s > *fnamep; --s)
19646 		    if (s[0] == ';')
19647 			break;
19648 		if (s > *fnamep)
19649 		    *fnamelen = s - *fnamep;
19650 #endif
19651 	    }
19652 	    else if (*fnamep <= tail)
19653 		*fnamelen = 0;
19654 	}
19655 	else				/* :r */
19656 	{
19657 	    if (s > tail)	/* remove one extension */
19658 		*fnamelen = (int)(s - *fnamep);
19659 	}
19660 	*usedlen += 2;
19661     }
19662 
19663     /* ":s?pat?foo?" - substitute */
19664     /* ":gs?pat?foo?" - global substitute */
19665     if (src[*usedlen] == ':'
19666 	    && (src[*usedlen + 1] == 's'
19667 		|| (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
19668     {
19669 	char_u	    *str;
19670 	char_u	    *pat;
19671 	char_u	    *sub;
19672 	int	    sep;
19673 	char_u	    *flags;
19674 	int	    didit = FALSE;
19675 
19676 	flags = (char_u *)"";
19677 	s = src + *usedlen + 2;
19678 	if (src[*usedlen + 1] == 'g')
19679 	{
19680 	    flags = (char_u *)"g";
19681 	    ++s;
19682 	}
19683 
19684 	sep = *s++;
19685 	if (sep)
19686 	{
19687 	    /* find end of pattern */
19688 	    p = vim_strchr(s, sep);
19689 	    if (p != NULL)
19690 	    {
19691 		pat = vim_strnsave(s, (int)(p - s));
19692 		if (pat != NULL)
19693 		{
19694 		    s = p + 1;
19695 		    /* find end of substitution */
19696 		    p = vim_strchr(s, sep);
19697 		    if (p != NULL)
19698 		    {
19699 			sub = vim_strnsave(s, (int)(p - s));
19700 			str = vim_strnsave(*fnamep, *fnamelen);
19701 			if (sub != NULL && str != NULL)
19702 			{
19703 			    *usedlen = (int)(p + 1 - src);
19704 			    s = do_string_sub(str, pat, sub, flags);
19705 			    if (s != NULL)
19706 			    {
19707 				*fnamep = s;
19708 				*fnamelen = (int)STRLEN(s);
19709 				vim_free(*bufp);
19710 				*bufp = s;
19711 				didit = TRUE;
19712 			    }
19713 			}
19714 			vim_free(sub);
19715 			vim_free(str);
19716 		    }
19717 		    vim_free(pat);
19718 		}
19719 	    }
19720 	    /* after using ":s", repeat all the modifiers */
19721 	    if (didit)
19722 		goto repeat;
19723 	}
19724     }
19725 
19726     return valid;
19727 }
19728 
19729 /*
19730  * Perform a substitution on "str" with pattern "pat" and substitute "sub".
19731  * "flags" can be "g" to do a global substitute.
19732  * Returns an allocated string, NULL for error.
19733  */
19734     char_u *
19735 do_string_sub(str, pat, sub, flags)
19736     char_u	*str;
19737     char_u	*pat;
19738     char_u	*sub;
19739     char_u	*flags;
19740 {
19741     int		sublen;
19742     regmatch_T	regmatch;
19743     int		i;
19744     int		do_all;
19745     char_u	*tail;
19746     garray_T	ga;
19747     char_u	*ret;
19748     char_u	*save_cpo;
19749 
19750     /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
19751     save_cpo = p_cpo;
19752     p_cpo = (char_u *)"";
19753 
19754     ga_init2(&ga, 1, 200);
19755 
19756     do_all = (flags[0] == 'g');
19757 
19758     regmatch.rm_ic = p_ic;
19759     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
19760     if (regmatch.regprog != NULL)
19761     {
19762 	tail = str;
19763 	while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
19764 	{
19765 	    /*
19766 	     * Get some space for a temporary buffer to do the substitution
19767 	     * into.  It will contain:
19768 	     * - The text up to where the match is.
19769 	     * - The substituted text.
19770 	     * - The text after the match.
19771 	     */
19772 	    sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
19773 	    if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
19774 			    (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
19775 	    {
19776 		ga_clear(&ga);
19777 		break;
19778 	    }
19779 
19780 	    /* copy the text up to where the match is */
19781 	    i = (int)(regmatch.startp[0] - tail);
19782 	    mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
19783 	    /* add the substituted text */
19784 	    (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
19785 					  + ga.ga_len + i, TRUE, TRUE, FALSE);
19786 	    ga.ga_len += i + sublen - 1;
19787 	    /* avoid getting stuck on a match with an empty string */
19788 	    if (tail == regmatch.endp[0])
19789 	    {
19790 		if (*tail == NUL)
19791 		    break;
19792 		*((char_u *)ga.ga_data + ga.ga_len) = *tail++;
19793 		++ga.ga_len;
19794 	    }
19795 	    else
19796 	    {
19797 		tail = regmatch.endp[0];
19798 		if (*tail == NUL)
19799 		    break;
19800 	    }
19801 	    if (!do_all)
19802 		break;
19803 	}
19804 
19805 	if (ga.ga_data != NULL)
19806 	    STRCPY((char *)ga.ga_data + ga.ga_len, tail);
19807 
19808 	vim_free(regmatch.regprog);
19809     }
19810 
19811     ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
19812     ga_clear(&ga);
19813     p_cpo = save_cpo;
19814 
19815     return ret;
19816 }
19817 
19818 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */
19819